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,1505 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One-Command Refactor Safety Lock engine for vibecode-anything.
|
|
3
|
+
*
|
|
4
|
+
* Snapshots a working application's executable behavior into `.vibecode/contract.json`,
|
|
5
|
+
* `.vibecode/SPEC.md`, external vault holdouts, and `.vibecode/lock.json` before
|
|
6
|
+
* refactoring, dependency upgrades, or stack migrations — providing cryptographic
|
|
7
|
+
* contract-tamper detection and workspace source-drift tracking with zero runtime deps.
|
|
8
|
+
*/
|
|
9
|
+
import crypto from "node:crypto";
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { VibecodeError, errorMessage } from "../core/errors.js";
|
|
13
|
+
import { splitCommand } from "../core/exec.js";
|
|
14
|
+
import { VALID_DOMAINS, VALID_SLICE_STATUSES, makeDefaultContract } from "../core/schema.js";
|
|
15
|
+
import { ANSI, FORBIDDEN_OBJECT_KEYS, STRICT_CONTROL_CHARS_RE, hasCrossPlatformPathEscape, isInsideVaultDirectory, isPathWithinDir, isRecordSafe, isSecretRelativePath, redactSensitiveText, styleAnsi } from "../core/security.js";
|
|
16
|
+
import { deriveDefaultSlices } from "../core/slices.js";
|
|
17
|
+
import { writeSpecFile } from "../core/spec-writer.js";
|
|
18
|
+
import { CONTRACT_FILE, SPEC_FILE, readContract, readHoldouts, resolveWorkspace, writeContract, writeLastReport } from "../core/store.js";
|
|
19
|
+
import { detectDomain, ingest } from "../ingestors/index.js";
|
|
20
|
+
import { isSensitiveHeader } from "../ingestors/trace.js";
|
|
21
|
+
import { verifyContract } from "../oracles/index.js";
|
|
22
|
+
export const LOCK_FILE = path.join(".vibecode", "lock.json");
|
|
23
|
+
const MAX_FINGERPRINT_FILES = 25;
|
|
24
|
+
const MAX_FINGERPRINT_FILE_BYTES = 1024 * 1024;
|
|
25
|
+
const MAX_LOCK_FILE_BYTES = 1024 * 1024;
|
|
26
|
+
const MAX_LOCK_FINGERPRINTED_ENTRIES = 100;
|
|
27
|
+
const MAX_LOCK_NAME_LENGTH = 256;
|
|
28
|
+
const MAX_LOCK_COMMAND_LENGTH = 4096;
|
|
29
|
+
const MAX_LOCK_PATH_LENGTH = 512;
|
|
30
|
+
const MAX_LOCK_DATE_LENGTH = 64;
|
|
31
|
+
const MAX_CANONICAL_CONTRACT_BYTES = 16 * 1024 * 1024;
|
|
32
|
+
const MAX_CANONICAL_JSON_DEPTH = 64;
|
|
33
|
+
const MAX_SLICE_NOTES_LENGTH = 4096;
|
|
34
|
+
const MAX_EXPORT_WALK_DEPTH = 6;
|
|
35
|
+
const SHA256_HEX_RE = /^[0-9a-f]{64}$/i;
|
|
36
|
+
const DANGEROUS_KEYS = FORBIDDEN_OBJECT_KEYS;
|
|
37
|
+
const CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/;
|
|
38
|
+
const CONTROL_CHAR_NON_WS_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/;
|
|
39
|
+
const CONTROL_CHAR_GLOBAL_RE = /[\x00-\x1f\x7f]+/g;
|
|
40
|
+
const WINDOWS_DRIVE_ANY_RE = /^[A-Za-z]:/;
|
|
41
|
+
const SHELL_UNSAFE_BIN_PATH_RE = /[\x00-\x1f\x7f$`;&|<>()'"\\!%^*?~#{}[\]]/;
|
|
42
|
+
const SAFE_BIN_NAME_RE = /^(?:@[A-Za-z0-9._-]+\/)?[A-Za-z0-9._-]+$/;
|
|
43
|
+
const MUTABLE_SLICE_FIELDS = new Set(["status", "lastVerifiedAt", "lastScore", "notes"]);
|
|
44
|
+
const ALLOWED_SLICE_FIELDS = new Set([
|
|
45
|
+
"id",
|
|
46
|
+
"title",
|
|
47
|
+
"description",
|
|
48
|
+
"invariantIds",
|
|
49
|
+
"dependsOn",
|
|
50
|
+
"status",
|
|
51
|
+
"lastVerifiedAt",
|
|
52
|
+
"lastScore",
|
|
53
|
+
"notes"
|
|
54
|
+
]);
|
|
55
|
+
const STANDARD_MANIFEST_FILES = ["package.json", "tsconfig.json", "pyproject.toml", "Cargo.toml", "go.mod", "Makefile"];
|
|
56
|
+
const COMMON_ENTRY_FILES = [
|
|
57
|
+
"src/index.ts", "src/index.mts", "src/index.js", "src/index.mjs", "src/index.cjs",
|
|
58
|
+
"src/main.ts", "src/main.js", "src/cli.ts", "src/cli.js",
|
|
59
|
+
"index.ts", "index.js", "index.mjs", "index.cjs",
|
|
60
|
+
"main.py", "app.py", "src/main.rs", "src/lib.rs", "main.go"
|
|
61
|
+
];
|
|
62
|
+
const IGNORED_PATH_SEGMENTS = new Set([".git", "node_modules", ".vibecode", ".vibecode-vault"]);
|
|
63
|
+
const INTERPRETER_TOKENS = new Set([
|
|
64
|
+
"node", "node.exe", "python", "python3", "py", "tsx", "ts-node", "npx", "npm", "pnpm", "yarn",
|
|
65
|
+
"deno", "bun", "ruby", "perl", "bash", "sh", "zsh", "pwsh", "powershell", "cmd", "cmd.exe", "php", "java", "go", "cargo"
|
|
66
|
+
]);
|
|
67
|
+
const API_SPEC_LOCK_DOMAINS = new Set([
|
|
68
|
+
"api",
|
|
69
|
+
"postman",
|
|
70
|
+
"curl",
|
|
71
|
+
"graphql",
|
|
72
|
+
"http-file",
|
|
73
|
+
"insomnia",
|
|
74
|
+
"bruno",
|
|
75
|
+
"asyncapi",
|
|
76
|
+
"proto",
|
|
77
|
+
"openrpc"
|
|
78
|
+
]);
|
|
79
|
+
const VALID_BASELINE_GATES = new Set(["pass", "pass_with_warnings", "fail", "incomplete", "unverified"]);
|
|
80
|
+
const SENSITIVE_META_KEY_RE = /^(?:authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token|api[-_]?key|apikey|secret|client[-_]?secret|password|passwd|token|jwt|access[-_]?token|refresh[-_]?token|id[-_]?token|auth[-_]?token|auth|sig|signature|private[-_]?key|session[-_]?id)$/i;
|
|
81
|
+
const isRecord = isRecordSafe;
|
|
82
|
+
function compareAscii(a, b) {
|
|
83
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
84
|
+
}
|
|
85
|
+
function toPosixRelative(rootReal, targetReal) {
|
|
86
|
+
return path.relative(rootReal, targetReal).replace(/\\/g, "/");
|
|
87
|
+
}
|
|
88
|
+
function resolveCanonicalDir(dirPath) {
|
|
89
|
+
const resolved = path.resolve(dirPath);
|
|
90
|
+
try {
|
|
91
|
+
return fs.realpathSync(resolved);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return resolved;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function inspectPathNoFollow(filePath) {
|
|
98
|
+
try {
|
|
99
|
+
const lstat = fs.lstatSync(filePath);
|
|
100
|
+
return {
|
|
101
|
+
exists: true,
|
|
102
|
+
isSymlink: lstat.isSymbolicLink(),
|
|
103
|
+
isFile: lstat.isFile(),
|
|
104
|
+
isDirectory: lstat.isDirectory(),
|
|
105
|
+
size: lstat.size
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return { exists: false, isSymlink: false, isFile: false, isDirectory: false, size: 0 };
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function inspectVibecodeDirSafety(rootDir, rootReal) {
|
|
113
|
+
const vibecodeDir = path.join(rootDir, ".vibecode");
|
|
114
|
+
const info = inspectPathNoFollow(vibecodeDir);
|
|
115
|
+
if (!info.exists)
|
|
116
|
+
return null;
|
|
117
|
+
if (info.isSymlink)
|
|
118
|
+
return "Refusing to operate on symlinked .vibecode directory.";
|
|
119
|
+
if (!info.isDirectory)
|
|
120
|
+
return "Invalid .vibecode path: expected a directory.";
|
|
121
|
+
try {
|
|
122
|
+
if (!isPathWithinDir(fs.realpathSync(vibecodeDir), rootReal)) {
|
|
123
|
+
return "Refusing to operate on .vibecode directory resolving outside workspace root.";
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return "Failed to resolve .vibecode directory.";
|
|
128
|
+
}
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
function isSecretOrExcludedRelativePath(posixRel) {
|
|
132
|
+
if (!posixRel || posixRel === "." || posixRel.startsWith("/") || posixRel.startsWith(".."))
|
|
133
|
+
return true;
|
|
134
|
+
if (posixRel.split("/").some((s) => !s || s === "." || s === ".."))
|
|
135
|
+
return true;
|
|
136
|
+
return isSecretRelativePath(posixRel, { allowEnvExample: false, ignoredSegments: IGNORED_PATH_SEGMENTS });
|
|
137
|
+
}
|
|
138
|
+
const style = styleAnsi;
|
|
139
|
+
export function resolveLockPath(cwd = process.cwd()) {
|
|
140
|
+
return path.join(path.resolve(cwd), LOCK_FILE);
|
|
141
|
+
}
|
|
142
|
+
export function computeFileSha256(filePath) {
|
|
143
|
+
if (typeof filePath !== "string" || !filePath || filePath.includes("\0")) {
|
|
144
|
+
throw new VibecodeError("CONFIG_INVALID", "Invalid file path for SHA-256 computation.");
|
|
145
|
+
}
|
|
146
|
+
const resolved = path.resolve(filePath);
|
|
147
|
+
let stat;
|
|
148
|
+
try {
|
|
149
|
+
stat = fs.statSync(resolved);
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
throw new VibecodeError("NOT_FOUND", `File not found for SHA-256 computation: ${filePath}`);
|
|
153
|
+
}
|
|
154
|
+
if (!stat.isFile()) {
|
|
155
|
+
throw new VibecodeError("CONFIG_INVALID", `Expected regular file for SHA-256 computation: ${filePath}`);
|
|
156
|
+
}
|
|
157
|
+
const buf = fs.readFileSync(resolved);
|
|
158
|
+
return crypto.createHash("sha256").update(buf).digest("hex");
|
|
159
|
+
}
|
|
160
|
+
function stableJsonStringify(value, depth = 0, seen = new WeakSet()) {
|
|
161
|
+
if (depth > MAX_CANONICAL_JSON_DEPTH) {
|
|
162
|
+
throw new Error("Canonical JSON depth limit exceeded.");
|
|
163
|
+
}
|
|
164
|
+
if (value === null || typeof value !== "object")
|
|
165
|
+
return JSON.stringify(value);
|
|
166
|
+
if (seen.has(value)) {
|
|
167
|
+
throw new Error("Circular reference in canonical JSON.");
|
|
168
|
+
}
|
|
169
|
+
seen.add(value);
|
|
170
|
+
try {
|
|
171
|
+
if (Array.isArray(value)) {
|
|
172
|
+
return `[${value.map((item) => (item === undefined ? "null" : stableJsonStringify(item, depth + 1, seen))).join(",")}]`;
|
|
173
|
+
}
|
|
174
|
+
const rec = value;
|
|
175
|
+
const keys = Object.keys(rec).sort(compareAscii);
|
|
176
|
+
const parts = [];
|
|
177
|
+
for (const key of keys) {
|
|
178
|
+
if (!Object.prototype.hasOwnProperty.call(rec, key))
|
|
179
|
+
continue;
|
|
180
|
+
const val = rec[key];
|
|
181
|
+
if (val === undefined)
|
|
182
|
+
continue;
|
|
183
|
+
parts.push(`${JSON.stringify(key)}:${stableJsonStringify(val, depth + 1, seen)}`);
|
|
184
|
+
}
|
|
185
|
+
return `{${parts.join(",")}}`;
|
|
186
|
+
}
|
|
187
|
+
finally {
|
|
188
|
+
seen.delete(value);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
function isValidSliceNotes(notes) {
|
|
192
|
+
if (notes === undefined)
|
|
193
|
+
return true;
|
|
194
|
+
if (typeof notes !== "string" || notes.length > MAX_SLICE_NOTES_LENGTH)
|
|
195
|
+
return false;
|
|
196
|
+
if (CONTROL_CHAR_NON_WS_RE.test(notes))
|
|
197
|
+
return false;
|
|
198
|
+
return redactSensitiveText(notes) === notes;
|
|
199
|
+
}
|
|
200
|
+
function isValidSliceVerifiedAt(value) {
|
|
201
|
+
if (value === undefined)
|
|
202
|
+
return true;
|
|
203
|
+
return (typeof value === "string" &&
|
|
204
|
+
value.trim().length > 0 &&
|
|
205
|
+
value.length <= MAX_LOCK_DATE_LENGTH &&
|
|
206
|
+
!CONTROL_CHAR_RE.test(value) &&
|
|
207
|
+
Number.isFinite(Date.parse(value)));
|
|
208
|
+
}
|
|
209
|
+
function inspectCanonicalContract(contractPath) {
|
|
210
|
+
if (typeof contractPath !== "string" || !contractPath || contractPath.includes("\0"))
|
|
211
|
+
return null;
|
|
212
|
+
let parsed;
|
|
213
|
+
try {
|
|
214
|
+
const resolved = path.resolve(contractPath);
|
|
215
|
+
const stat = fs.statSync(resolved);
|
|
216
|
+
if (!stat.isFile() || stat.size > MAX_CANONICAL_CONTRACT_BYTES)
|
|
217
|
+
return null;
|
|
218
|
+
parsed = JSON.parse(fs.readFileSync(resolved, "utf8"));
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
if (!isRecord(parsed))
|
|
224
|
+
return null;
|
|
225
|
+
const canonical = Object.create(null);
|
|
226
|
+
let hasValidSlices = false;
|
|
227
|
+
let hasDangerousTopKey = false;
|
|
228
|
+
for (const key of Object.keys(parsed)) {
|
|
229
|
+
if (!Object.prototype.hasOwnProperty.call(parsed, key))
|
|
230
|
+
continue;
|
|
231
|
+
if (DANGEROUS_KEYS.has(key)) {
|
|
232
|
+
hasDangerousTopKey = true;
|
|
233
|
+
}
|
|
234
|
+
if (key === "slices" && Array.isArray(parsed.slices)) {
|
|
235
|
+
let slicesValid = parsed.slices.length > 0;
|
|
236
|
+
canonical.slices = parsed.slices.map((entry) => {
|
|
237
|
+
if (!isRecord(entry)) {
|
|
238
|
+
slicesValid = false;
|
|
239
|
+
return entry;
|
|
240
|
+
}
|
|
241
|
+
const id = getOwn(entry, "id");
|
|
242
|
+
const title = getOwn(entry, "title");
|
|
243
|
+
const invariantIds = getOwn(entry, "invariantIds");
|
|
244
|
+
const status = getOwn(entry, "status");
|
|
245
|
+
const lastVerifiedAt = getOwn(entry, "lastVerifiedAt");
|
|
246
|
+
const lastScore = getOwn(entry, "lastScore");
|
|
247
|
+
const notes = getOwn(entry, "notes");
|
|
248
|
+
if (typeof id !== "string" ||
|
|
249
|
+
!id.trim() ||
|
|
250
|
+
typeof title !== "string" ||
|
|
251
|
+
!title.trim() ||
|
|
252
|
+
!Array.isArray(invariantIds) ||
|
|
253
|
+
(status !== undefined && (typeof status !== "string" || !VALID_SLICE_STATUSES.has(status))) ||
|
|
254
|
+
!isValidSliceVerifiedAt(lastVerifiedAt) ||
|
|
255
|
+
(lastScore !== undefined &&
|
|
256
|
+
(typeof lastScore !== "number" || !Number.isFinite(lastScore) || lastScore < 0 || lastScore > 1)) ||
|
|
257
|
+
!isValidSliceNotes(notes)) {
|
|
258
|
+
slicesValid = false;
|
|
259
|
+
}
|
|
260
|
+
const cleaned = Object.create(null);
|
|
261
|
+
for (const sk of Object.keys(entry)) {
|
|
262
|
+
if (!Object.prototype.hasOwnProperty.call(entry, sk))
|
|
263
|
+
continue;
|
|
264
|
+
if (DANGEROUS_KEYS.has(sk) || !ALLOWED_SLICE_FIELDS.has(sk)) {
|
|
265
|
+
slicesValid = false;
|
|
266
|
+
}
|
|
267
|
+
if (!MUTABLE_SLICE_FIELDS.has(sk)) {
|
|
268
|
+
cleaned[sk] = entry[sk];
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return cleaned;
|
|
272
|
+
});
|
|
273
|
+
hasValidSlices = slicesValid;
|
|
274
|
+
}
|
|
275
|
+
else {
|
|
276
|
+
canonical[key] = parsed[key];
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
let serialized;
|
|
280
|
+
try {
|
|
281
|
+
serialized = stableJsonStringify(canonical);
|
|
282
|
+
}
|
|
283
|
+
catch {
|
|
284
|
+
return null;
|
|
285
|
+
}
|
|
286
|
+
return {
|
|
287
|
+
sha256: crypto.createHash("sha256").update(serialized, "utf8").digest("hex"),
|
|
288
|
+
hasValidSlices: hasValidSlices && !hasDangerousTopKey
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Computes a deterministic SHA-256 hash of `.vibecode/contract.json` after stripping
|
|
293
|
+
* ONLY mutable slice progress fields (`status`, `lastVerifiedAt`, `lastScore`, `notes`)
|
|
294
|
+
* from `slices[]`, preserving all contract invariants, thresholds, target metadata, and
|
|
295
|
+
* immutable slice definitions verbatim.
|
|
296
|
+
*/
|
|
297
|
+
export function computeCanonicalContractSha256(contractPath) {
|
|
298
|
+
return inspectCanonicalContract(contractPath)?.sha256 ?? null;
|
|
299
|
+
}
|
|
300
|
+
export function redactLockValue(value) {
|
|
301
|
+
return redactSensitiveText(value);
|
|
302
|
+
}
|
|
303
|
+
function readPackageJsonSafe(rootDir, rootReal) {
|
|
304
|
+
const safePkg = resolveSafeWorkspaceFile(rootDir, rootReal, "package.json", MAX_FINGERPRINT_FILE_BYTES);
|
|
305
|
+
if (!safePkg)
|
|
306
|
+
return null;
|
|
307
|
+
try {
|
|
308
|
+
const raw = JSON.parse(fs.readFileSync(safePkg.realPath, "utf8"));
|
|
309
|
+
return isRecord(raw) ? raw : null;
|
|
310
|
+
}
|
|
311
|
+
catch {
|
|
312
|
+
return null;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
function extractExportTargetPaths(value, out, depth = 0) {
|
|
316
|
+
if (depth > MAX_EXPORT_WALK_DEPTH || value === null || value === undefined)
|
|
317
|
+
return;
|
|
318
|
+
if (typeof value === "string") {
|
|
319
|
+
const trimmed = value.trim();
|
|
320
|
+
if (trimmed && !trimmed.includes("*"))
|
|
321
|
+
out.push(trimmed);
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (Array.isArray(value)) {
|
|
325
|
+
for (const item of value)
|
|
326
|
+
extractExportTargetPaths(item, out, depth + 1);
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
if (isRecord(value)) {
|
|
330
|
+
const prioritizedKeys = ["import", "default", "node", "require", "module"];
|
|
331
|
+
const visited = new Set();
|
|
332
|
+
for (const key of prioritizedKeys) {
|
|
333
|
+
if (Object.prototype.hasOwnProperty.call(value, key)) {
|
|
334
|
+
visited.add(key);
|
|
335
|
+
extractExportTargetPaths(value[key], out, depth + 1);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
339
|
+
if (visited.has(key) || key === "types" || DANGEROUS_KEYS.has(key))
|
|
340
|
+
continue;
|
|
341
|
+
extractExportTargetPaths(entry, out, depth + 1);
|
|
342
|
+
}
|
|
343
|
+
if (Object.prototype.hasOwnProperty.call(value, "types")) {
|
|
344
|
+
extractExportTargetPaths(value.types, out, depth + 1);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
function collectPackageEntryCandidates(pkg) {
|
|
349
|
+
const bins = [];
|
|
350
|
+
const entries = [];
|
|
351
|
+
if (!pkg)
|
|
352
|
+
return { bins, entries };
|
|
353
|
+
if (Object.prototype.hasOwnProperty.call(pkg, "bin")) {
|
|
354
|
+
if (typeof pkg.bin === "string" && pkg.bin.trim()) {
|
|
355
|
+
bins.push(pkg.bin.trim());
|
|
356
|
+
}
|
|
357
|
+
else if (isRecord(pkg.bin)) {
|
|
358
|
+
for (const [binKey, val] of Object.entries(pkg.bin)) {
|
|
359
|
+
if (DANGEROUS_KEYS.has(binKey) || !SAFE_BIN_NAME_RE.test(binKey))
|
|
360
|
+
continue;
|
|
361
|
+
if (typeof val === "string" && val.trim())
|
|
362
|
+
bins.push(val.trim());
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
for (const field of ["main", "module"]) {
|
|
367
|
+
if (!Object.prototype.hasOwnProperty.call(pkg, field))
|
|
368
|
+
continue;
|
|
369
|
+
const v = pkg[field];
|
|
370
|
+
if (typeof v === "string" && v.trim())
|
|
371
|
+
entries.push(v.trim());
|
|
372
|
+
}
|
|
373
|
+
if (Object.prototype.hasOwnProperty.call(pkg, "exports") && pkg.exports !== undefined) {
|
|
374
|
+
extractExportTargetPaths(pkg.exports, entries);
|
|
375
|
+
}
|
|
376
|
+
return { bins, entries };
|
|
377
|
+
}
|
|
378
|
+
function resolveSafeWorkspaceFile(rootDir, rootReal, candidatePath, maxBytes) {
|
|
379
|
+
if (typeof candidatePath !== "string" || hasCrossPlatformPathEscape(candidatePath))
|
|
380
|
+
return null;
|
|
381
|
+
const trimmed = candidatePath.trim();
|
|
382
|
+
if (!trimmed)
|
|
383
|
+
return null;
|
|
384
|
+
// Normalize Windows separators for relative paths so `src\\index.ts` and `..\\..\\` behave consistently across OSes.
|
|
385
|
+
const isWinAbs = /^[A-Za-z]:[\\/]/.test(trimmed);
|
|
386
|
+
const normalizedInput = !isWinAbs && !path.isAbsolute(trimmed) ? trimmed.replace(/\\/g, "/") : trimmed;
|
|
387
|
+
const absCandidate = path.resolve(rootDir, normalizedInput);
|
|
388
|
+
let lstat;
|
|
389
|
+
let realPath;
|
|
390
|
+
let stat;
|
|
391
|
+
try {
|
|
392
|
+
lstat = fs.lstatSync(absCandidate);
|
|
393
|
+
realPath = fs.realpathSync(absCandidate);
|
|
394
|
+
if (!isPathWithinDir(realPath, rootReal) || isInsideVaultDirectory(absCandidate) || isInsideVaultDirectory(realPath)) {
|
|
395
|
+
return null;
|
|
396
|
+
}
|
|
397
|
+
stat = lstat.isSymbolicLink() ? fs.statSync(realPath) : lstat;
|
|
398
|
+
}
|
|
399
|
+
catch {
|
|
400
|
+
return null;
|
|
401
|
+
}
|
|
402
|
+
if (!stat.isFile() || (typeof maxBytes === "number" && stat.size > maxBytes))
|
|
403
|
+
return null;
|
|
404
|
+
const posixRel = toPosixRelative(rootReal, realPath);
|
|
405
|
+
if (isSecretOrExcludedRelativePath(posixRel))
|
|
406
|
+
return null;
|
|
407
|
+
return { posixRel, realPath };
|
|
408
|
+
}
|
|
409
|
+
export function computeWorkspaceFingerprint(cwd, extraFiles = []) {
|
|
410
|
+
const rootDir = path.resolve(cwd);
|
|
411
|
+
const rootReal = resolveCanonicalDir(rootDir);
|
|
412
|
+
const selected = new Map();
|
|
413
|
+
const tryAdd = (candidate) => {
|
|
414
|
+
if (selected.size >= MAX_FINGERPRINT_FILES)
|
|
415
|
+
return;
|
|
416
|
+
const resolved = resolveSafeWorkspaceFile(rootDir, rootReal, candidate, MAX_FINGERPRINT_FILE_BYTES);
|
|
417
|
+
if (!resolved)
|
|
418
|
+
return;
|
|
419
|
+
if (!selected.has(resolved.posixRel)) {
|
|
420
|
+
selected.set(resolved.posixRel, resolved.realPath);
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
for (const manifestFile of STANDARD_MANIFEST_FILES) {
|
|
424
|
+
tryAdd(manifestFile);
|
|
425
|
+
}
|
|
426
|
+
for (const extra of extraFiles) {
|
|
427
|
+
if (typeof extra === "string")
|
|
428
|
+
tryAdd(extra);
|
|
429
|
+
}
|
|
430
|
+
const pkg = readPackageJsonSafe(rootDir, rootReal);
|
|
431
|
+
const { bins, entries } = collectPackageEntryCandidates(pkg);
|
|
432
|
+
for (const binFile of bins)
|
|
433
|
+
tryAdd(binFile);
|
|
434
|
+
for (const entryFile of entries)
|
|
435
|
+
tryAdd(entryFile);
|
|
436
|
+
for (const commonFile of COMMON_ENTRY_FILES)
|
|
437
|
+
tryAdd(commonFile);
|
|
438
|
+
const sortedFiles = [...selected.keys()].sort(compareAscii);
|
|
439
|
+
const hash = crypto.createHash("sha256");
|
|
440
|
+
const hashedFiles = [];
|
|
441
|
+
for (const rel of sortedFiles) {
|
|
442
|
+
const absPath = selected.get(rel);
|
|
443
|
+
if (!absPath)
|
|
444
|
+
continue;
|
|
445
|
+
let buf;
|
|
446
|
+
try {
|
|
447
|
+
const stat = fs.statSync(absPath);
|
|
448
|
+
if (!stat.isFile() || stat.size > MAX_FINGERPRINT_FILE_BYTES)
|
|
449
|
+
continue;
|
|
450
|
+
buf = fs.readFileSync(absPath);
|
|
451
|
+
}
|
|
452
|
+
catch {
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
hashedFiles.push(rel);
|
|
456
|
+
hash.update(`${rel}\0${buf.length}\0`, "utf8");
|
|
457
|
+
hash.update(buf);
|
|
458
|
+
hash.update("\n", "utf8");
|
|
459
|
+
}
|
|
460
|
+
return {
|
|
461
|
+
sha256: hash.digest("hex"),
|
|
462
|
+
files: hashedFiles
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
function detectDomainWithCwd(rootDir, source, options) {
|
|
466
|
+
const trimmed = source.trim();
|
|
467
|
+
if (/^https?:\/\//i.test(trimmed)) {
|
|
468
|
+
if (Array.isArray(options.endpoints) && options.endpoints.length > 0) {
|
|
469
|
+
return "api";
|
|
470
|
+
}
|
|
471
|
+
return "web";
|
|
472
|
+
}
|
|
473
|
+
const absCandidate = path.resolve(rootDir, trimmed);
|
|
474
|
+
if (fs.existsSync(absCandidate)) {
|
|
475
|
+
return detectDomain(absCandidate);
|
|
476
|
+
}
|
|
477
|
+
return detectDomain(trimmed);
|
|
478
|
+
}
|
|
479
|
+
function inferDefaultTarget(domain, source, rootDir, baseUrl) {
|
|
480
|
+
const normalized = String(domain).trim().toLowerCase();
|
|
481
|
+
const trimmedSource = source.trim();
|
|
482
|
+
const trimmedBaseUrl = typeof baseUrl === "string" && baseUrl.trim() ? baseUrl.trim() : undefined;
|
|
483
|
+
if (normalized === "cli" || normalized === "script") {
|
|
484
|
+
return trimmedSource || undefined;
|
|
485
|
+
}
|
|
486
|
+
if (normalized === "repo") {
|
|
487
|
+
return trimmedSource ? path.resolve(rootDir, trimmedSource) : rootDir;
|
|
488
|
+
}
|
|
489
|
+
if (normalized === "web" || normalized === "url") {
|
|
490
|
+
if (/^https?:\/\//i.test(trimmedSource))
|
|
491
|
+
return trimmedSource;
|
|
492
|
+
return trimmedBaseUrl;
|
|
493
|
+
}
|
|
494
|
+
if (API_SPEC_LOCK_DOMAINS.has(normalized)) {
|
|
495
|
+
if (/^https?:\/\//i.test(trimmedSource))
|
|
496
|
+
return trimmedSource;
|
|
497
|
+
return trimmedBaseUrl;
|
|
498
|
+
}
|
|
499
|
+
return undefined;
|
|
500
|
+
}
|
|
501
|
+
function formatNodeCommandForBin(posixRel) {
|
|
502
|
+
if (!posixRel || SHELL_UNSAFE_BIN_PATH_RE.test(posixRel))
|
|
503
|
+
return null;
|
|
504
|
+
return /\s/.test(posixRel) ? `node "${posixRel}"` : `node ${posixRel}`;
|
|
505
|
+
}
|
|
506
|
+
function sanitizeProjectName(raw) {
|
|
507
|
+
const cleaned = redactLockValue(raw.replace(CONTROL_CHAR_GLOBAL_RE, " ").trim()).slice(0, MAX_LOCK_NAME_LENGTH);
|
|
508
|
+
return cleaned || "workspace";
|
|
509
|
+
}
|
|
510
|
+
function resolveProjectName(rootDir, options, pkg) {
|
|
511
|
+
if (typeof options.name === "string" && options.name.trim())
|
|
512
|
+
return sanitizeProjectName(options.name);
|
|
513
|
+
if (typeof options.discoverHint?.name === "string" && options.discoverHint.name.trim()) {
|
|
514
|
+
return sanitizeProjectName(options.discoverHint.name);
|
|
515
|
+
}
|
|
516
|
+
if (pkg && Object.prototype.hasOwnProperty.call(pkg, "name") && typeof pkg.name === "string" && pkg.name.trim()) {
|
|
517
|
+
return sanitizeProjectName(pkg.name);
|
|
518
|
+
}
|
|
519
|
+
return sanitizeProjectName(path.basename(rootDir) || "workspace");
|
|
520
|
+
}
|
|
521
|
+
export function autoInferLockTarget(cwd, options = {}) {
|
|
522
|
+
const rootDir = path.resolve(cwd);
|
|
523
|
+
const rootReal = resolveCanonicalDir(rootDir);
|
|
524
|
+
const pkg = readPackageJsonSafe(rootDir, rootReal);
|
|
525
|
+
const name = resolveProjectName(rootDir, options, pkg);
|
|
526
|
+
const explicitDomain = typeof options.domain === "string" && options.domain.trim()
|
|
527
|
+
? options.domain.trim()
|
|
528
|
+
: undefined;
|
|
529
|
+
if (typeof options.source === "string" && options.source.includes("\0")) {
|
|
530
|
+
throw new VibecodeError("CONFIG_INVALID", "Lock source must not contain NUL bytes.");
|
|
531
|
+
}
|
|
532
|
+
if (typeof options.target === "string" && options.target.includes("\0")) {
|
|
533
|
+
throw new VibecodeError("CONFIG_INVALID", "Lock target must not contain NUL bytes.");
|
|
534
|
+
}
|
|
535
|
+
const explicitTarget = typeof options.target === "string" && options.target.trim() ? options.target.trim() : undefined;
|
|
536
|
+
// 0. Explicit source provided by caller
|
|
537
|
+
if (typeof options.source === "string" && options.source.trim()) {
|
|
538
|
+
const source = options.source.trim();
|
|
539
|
+
const domain = explicitDomain ?? detectDomainWithCwd(rootDir, source, options);
|
|
540
|
+
const target = explicitTarget ?? inferDefaultTarget(domain, source, rootDir, options.baseUrl);
|
|
541
|
+
return {
|
|
542
|
+
domain,
|
|
543
|
+
source,
|
|
544
|
+
...(target ? { target } : {}),
|
|
545
|
+
name
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
// 1. Discover hint provided by caller (e.g. from discoverProject())
|
|
549
|
+
const hint = options.discoverHint;
|
|
550
|
+
if (hint) {
|
|
551
|
+
if (typeof hint.source === "string" && hint.source.trim() && !CONTROL_CHAR_RE.test(hint.source)) {
|
|
552
|
+
const source = hint.source.trim();
|
|
553
|
+
const domain = explicitDomain ?? hint.domain ?? detectDomainWithCwd(rootDir, source, options);
|
|
554
|
+
const hintTarget = typeof hint.target === "string" && hint.target.trim() && !CONTROL_CHAR_RE.test(hint.target)
|
|
555
|
+
? hint.target.trim()
|
|
556
|
+
: undefined;
|
|
557
|
+
const target = explicitTarget ?? hintTarget ?? inferDefaultTarget(domain, source, rootDir, options.baseUrl);
|
|
558
|
+
return {
|
|
559
|
+
domain,
|
|
560
|
+
source,
|
|
561
|
+
...(target ? { target } : {}),
|
|
562
|
+
name
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
if (typeof hint.target === "string" &&
|
|
566
|
+
!CONTROL_CHAR_RE.test(hint.target) &&
|
|
567
|
+
/^https?:\/\//i.test(hint.target.trim())) {
|
|
568
|
+
const urlTarget = hint.target.trim();
|
|
569
|
+
const domain = explicitDomain ??
|
|
570
|
+
hint.domain ??
|
|
571
|
+
(Array.isArray(options.endpoints) && options.endpoints.length > 0 ? "api" : "web");
|
|
572
|
+
return {
|
|
573
|
+
domain,
|
|
574
|
+
source: urlTarget,
|
|
575
|
+
target: explicitTarget ?? urlTarget,
|
|
576
|
+
name
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
// 2. Inspect package.json bin / main / exports and common repo entrypoints
|
|
581
|
+
const { bins, entries } = collectPackageEntryCandidates(pkg);
|
|
582
|
+
if (!explicitDomain || explicitDomain === "cli" || explicitDomain === "script") {
|
|
583
|
+
for (const binCandidate of bins) {
|
|
584
|
+
const resolved = resolveSafeWorkspaceFile(rootDir, rootReal, binCandidate);
|
|
585
|
+
if (resolved) {
|
|
586
|
+
const command = formatNodeCommandForBin(resolved.posixRel);
|
|
587
|
+
if (!command)
|
|
588
|
+
continue;
|
|
589
|
+
return {
|
|
590
|
+
domain: explicitDomain ?? "cli",
|
|
591
|
+
source: command,
|
|
592
|
+
target: explicitTarget ?? command,
|
|
593
|
+
name
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
if (!explicitDomain || explicitDomain === "repo") {
|
|
599
|
+
const repoCandidates = [
|
|
600
|
+
...entries,
|
|
601
|
+
"src/index.ts",
|
|
602
|
+
"src/index.mts",
|
|
603
|
+
"src/index.js",
|
|
604
|
+
"src/index.mjs",
|
|
605
|
+
"src/index.cjs",
|
|
606
|
+
"index.ts",
|
|
607
|
+
"index.js",
|
|
608
|
+
"index.mjs",
|
|
609
|
+
"index.cjs"
|
|
610
|
+
];
|
|
611
|
+
for (const entryCandidate of repoCandidates) {
|
|
612
|
+
const resolved = resolveSafeWorkspaceFile(rootDir, rootReal, entryCandidate);
|
|
613
|
+
if (resolved) {
|
|
614
|
+
return {
|
|
615
|
+
domain: "repo",
|
|
616
|
+
source: rootDir,
|
|
617
|
+
target: explicitTarget ?? rootDir,
|
|
618
|
+
name
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
// 3. Explicit HTTP(S) target URL
|
|
624
|
+
if (explicitTarget && /^https?:\/\//i.test(explicitTarget)) {
|
|
625
|
+
const domain = explicitDomain ??
|
|
626
|
+
(Array.isArray(options.endpoints) && options.endpoints.length > 0 ? "api" : "web");
|
|
627
|
+
return {
|
|
628
|
+
domain,
|
|
629
|
+
source: explicitTarget,
|
|
630
|
+
target: explicitTarget,
|
|
631
|
+
name
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
throw new VibecodeError("TARGET_MISSING", "Could not auto-infer an executable lock target in this workspace. Pass --source \"<command|url|dir|spec>\" or --target \"http://...\" to lock behavior.", {
|
|
635
|
+
fallbackHint: 'Examples: vibecode-anything lock --source "node dist/cli.js" | vibecode-anything lock --source . --domain repo | vibecode-anything lock --target http://localhost:3000'
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
function sanitizeInvariantForLock(inv) {
|
|
639
|
+
const next = { ...inv };
|
|
640
|
+
if (typeof next.description === "string") {
|
|
641
|
+
next.description = redactLockValue(next.description);
|
|
642
|
+
}
|
|
643
|
+
if (isRecord(next.input)) {
|
|
644
|
+
const cleanInput = { ...next.input };
|
|
645
|
+
if (typeof cleanInput.url === "string") {
|
|
646
|
+
cleanInput.url = redactLockValue(cleanInput.url);
|
|
647
|
+
}
|
|
648
|
+
if (typeof cleanInput.path === "string") {
|
|
649
|
+
cleanInput.path = redactLockValue(cleanInput.path);
|
|
650
|
+
}
|
|
651
|
+
if (isRecord(cleanInput.headers)) {
|
|
652
|
+
const cleanHeaders = {};
|
|
653
|
+
for (const [hk, hv] of Object.entries(cleanInput.headers)) {
|
|
654
|
+
if (DANGEROUS_KEYS.has(hk) || isSensitiveHeader(hk) || SENSITIVE_META_KEY_RE.test(hk))
|
|
655
|
+
continue;
|
|
656
|
+
cleanHeaders[hk] = typeof hv === "string" ? redactLockValue(hv) : hv;
|
|
657
|
+
}
|
|
658
|
+
cleanInput.headers = cleanHeaders;
|
|
659
|
+
}
|
|
660
|
+
if (isRecord(cleanInput.query)) {
|
|
661
|
+
const cleanQuery = {};
|
|
662
|
+
for (const [qk, qv] of Object.entries(cleanInput.query)) {
|
|
663
|
+
if (DANGEROUS_KEYS.has(qk) || SENSITIVE_META_KEY_RE.test(qk))
|
|
664
|
+
continue;
|
|
665
|
+
cleanQuery[qk] = typeof qv === "string" ? redactLockValue(qv) : qv;
|
|
666
|
+
}
|
|
667
|
+
if (Object.keys(cleanQuery).length > 0) {
|
|
668
|
+
cleanInput.query = cleanQuery;
|
|
669
|
+
}
|
|
670
|
+
else {
|
|
671
|
+
delete cleanInput.query;
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
next.input = cleanInput;
|
|
675
|
+
}
|
|
676
|
+
return next;
|
|
677
|
+
}
|
|
678
|
+
function sanitizeSliceForLock(slice) {
|
|
679
|
+
const cleanNotes = typeof slice.notes === "string"
|
|
680
|
+
? redactLockValue(slice.notes).slice(0, MAX_SLICE_NOTES_LENGTH)
|
|
681
|
+
: undefined;
|
|
682
|
+
return {
|
|
683
|
+
id: slice.id,
|
|
684
|
+
title: redactLockValue(slice.title),
|
|
685
|
+
invariantIds: Array.isArray(slice.invariantIds) ? [...slice.invariantIds] : [],
|
|
686
|
+
status: slice.status,
|
|
687
|
+
...(typeof slice.description === "string" ? { description: redactLockValue(slice.description) } : {}),
|
|
688
|
+
...(Array.isArray(slice.dependsOn) ? { dependsOn: [...slice.dependsOn] } : {}),
|
|
689
|
+
...(typeof slice.lastVerifiedAt === "string" ? { lastVerifiedAt: slice.lastVerifiedAt } : {}),
|
|
690
|
+
...(typeof slice.lastScore === "number" ? { lastScore: slice.lastScore } : {}),
|
|
691
|
+
...(cleanNotes !== undefined ? { notes: cleanNotes } : {})
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
function sanitizeSourceMetaValue(value, depth) {
|
|
695
|
+
if (depth > 5)
|
|
696
|
+
return "[REDACTED]";
|
|
697
|
+
if (typeof value === "string")
|
|
698
|
+
return redactLockValue(value);
|
|
699
|
+
if (Array.isArray(value))
|
|
700
|
+
return value.map((item) => sanitizeSourceMetaValue(item, depth + 1));
|
|
701
|
+
if (isRecord(value))
|
|
702
|
+
return sanitizeSourceMeta(value, depth + 1);
|
|
703
|
+
return value;
|
|
704
|
+
}
|
|
705
|
+
function sanitizeSourceMeta(meta, depth = 0) {
|
|
706
|
+
if (!isRecord(meta) || depth > 5)
|
|
707
|
+
return {};
|
|
708
|
+
const out = {};
|
|
709
|
+
for (const [key, value] of Object.entries(meta)) {
|
|
710
|
+
if (DANGEROUS_KEYS.has(key) || value === undefined)
|
|
711
|
+
continue;
|
|
712
|
+
if (SENSITIVE_META_KEY_RE.test(key)) {
|
|
713
|
+
out[key] = "[REDACTED]";
|
|
714
|
+
continue;
|
|
715
|
+
}
|
|
716
|
+
out[key] = sanitizeSourceMetaValue(value, depth);
|
|
717
|
+
}
|
|
718
|
+
return out;
|
|
719
|
+
}
|
|
720
|
+
function collectCommandFileCandidates(command) {
|
|
721
|
+
if (!command || /^https?:\/\//i.test(command.trim()))
|
|
722
|
+
return [];
|
|
723
|
+
const out = [];
|
|
724
|
+
for (const token of splitCommand(command)) {
|
|
725
|
+
if (!token || token.startsWith("-"))
|
|
726
|
+
continue;
|
|
727
|
+
if (/^https?:\/\//i.test(token))
|
|
728
|
+
continue;
|
|
729
|
+
if (INTERPRETER_TOKENS.has(path.basename(token).toLowerCase()))
|
|
730
|
+
continue;
|
|
731
|
+
out.push(token);
|
|
732
|
+
}
|
|
733
|
+
return out;
|
|
734
|
+
}
|
|
735
|
+
function hasSensitiveHeaders(headers) {
|
|
736
|
+
if (!isRecord(headers))
|
|
737
|
+
return false;
|
|
738
|
+
return Object.keys(headers).some((key) => isSensitiveHeader(key));
|
|
739
|
+
}
|
|
740
|
+
function hasDangerousShellMetachars(value) {
|
|
741
|
+
if (CONTROL_CHAR_RE.test(value))
|
|
742
|
+
return true;
|
|
743
|
+
if (/[`$;|<>'\\!()]/.test(value))
|
|
744
|
+
return true;
|
|
745
|
+
if (/%[A-Za-z_][A-Za-z0-9_]*%/.test(value))
|
|
746
|
+
return true;
|
|
747
|
+
if (value.includes("&")) {
|
|
748
|
+
// Allow `&` strictly inside an HTTP(S) URL query string (`?k=v&k2=v2`) with no adjacent whitespace.
|
|
749
|
+
const isHttpUrl = /^https?:\/\/[^\s]+$/i.test(value);
|
|
750
|
+
const qIdx = value.indexOf("?");
|
|
751
|
+
const firstAmp = value.indexOf("&");
|
|
752
|
+
if (!isHttpUrl || qIdx < 0 || firstAmp < qIdx || value.includes("&&"))
|
|
753
|
+
return true;
|
|
754
|
+
const queryPart = value.slice(qIdx + 1);
|
|
755
|
+
if (!/^[A-Za-z0-9_.~:+/@[\]=%&-]+$/.test(queryPart))
|
|
756
|
+
return true;
|
|
757
|
+
for (const pair of queryPart.split("&")) {
|
|
758
|
+
if (!pair.includes("="))
|
|
759
|
+
return true;
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
if (value.includes('"')) {
|
|
763
|
+
const quoteCount = (value.match(/"/g) ?? []).length;
|
|
764
|
+
if (quoteCount % 2 !== 0)
|
|
765
|
+
return true;
|
|
766
|
+
// Allow quotes only for clean space-wrapping path tokens (e.g. `node "bin/my cli.mjs"`).
|
|
767
|
+
if (!/^[A-Za-z0-9_./:@ +-]+(?:"[A-Za-z0-9_./:@ +-]+"[A-Za-z0-9_./:@ +-]*)+$/.test(value)) {
|
|
768
|
+
return true;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
return false;
|
|
772
|
+
}
|
|
773
|
+
function buildVerifyCommand(domain, rootDir, verifyTarget, strict) {
|
|
774
|
+
let displayTarget = "<target>";
|
|
775
|
+
let sanitizedUnsafeTarget = false;
|
|
776
|
+
if (verifyTarget) {
|
|
777
|
+
if (domain === "repo" && path.resolve(rootDir, verifyTarget) === rootDir) {
|
|
778
|
+
displayTarget = ".";
|
|
779
|
+
}
|
|
780
|
+
else {
|
|
781
|
+
const redacted = redactLockValue(verifyTarget);
|
|
782
|
+
if (hasDangerousShellMetachars(redacted) || hasDangerousShellMetachars(verifyTarget)) {
|
|
783
|
+
displayTarget = "<target>";
|
|
784
|
+
sanitizedUnsafeTarget = true;
|
|
785
|
+
}
|
|
786
|
+
else {
|
|
787
|
+
displayTarget = redacted;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
const escaped = displayTarget.replace(CONTROL_CHAR_GLOBAL_RE, " ").replace(/[\\"$`!]/g, "\\$&");
|
|
792
|
+
const strictSuffix = strict ? " --strict" : "";
|
|
793
|
+
return {
|
|
794
|
+
command: redactLockValue(`vibecode-anything verify --target "${escaped}"${strictSuffix}`),
|
|
795
|
+
sanitizedUnsafeTarget
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
function writeLockManifestAtomic(lockPath, manifest, rootDir, rootReal) {
|
|
799
|
+
const dirIssue = inspectVibecodeDirSafety(rootDir, rootReal);
|
|
800
|
+
if (dirIssue) {
|
|
801
|
+
throw new VibecodeError("CONFIG_INVALID", dirIssue);
|
|
802
|
+
}
|
|
803
|
+
const existingLock = inspectPathNoFollow(lockPath);
|
|
804
|
+
if (existingLock.isSymlink) {
|
|
805
|
+
throw new VibecodeError("CONFIG_INVALID", `Refusing to write symlinked ${LOCK_FILE}.`);
|
|
806
|
+
}
|
|
807
|
+
fs.mkdirSync(path.dirname(lockPath), { recursive: true });
|
|
808
|
+
const postMkdirIssue = inspectVibecodeDirSafety(rootDir, rootReal);
|
|
809
|
+
if (postMkdirIssue) {
|
|
810
|
+
throw new VibecodeError("CONFIG_INVALID", postMkdirIssue);
|
|
811
|
+
}
|
|
812
|
+
const uniqueSuffix = `${process.pid}.${crypto.randomBytes(6).toString("hex")}`;
|
|
813
|
+
const tmpPath = `${lockPath}.${uniqueSuffix}.tmp`;
|
|
814
|
+
try {
|
|
815
|
+
fs.writeFileSync(tmpPath, JSON.stringify(manifest, null, 2) + "\n", {
|
|
816
|
+
encoding: "utf8",
|
|
817
|
+
flag: "wx"
|
|
818
|
+
});
|
|
819
|
+
let renamed = false;
|
|
820
|
+
let lastErr;
|
|
821
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
822
|
+
try {
|
|
823
|
+
fs.renameSync(tmpPath, lockPath);
|
|
824
|
+
renamed = true;
|
|
825
|
+
break;
|
|
826
|
+
}
|
|
827
|
+
catch (err) {
|
|
828
|
+
lastErr = err;
|
|
829
|
+
const code = err?.code;
|
|
830
|
+
if (process.platform === "win32" && (code === "EPERM" || code === "EBUSY" || code === "EACCES")) {
|
|
831
|
+
continue;
|
|
832
|
+
}
|
|
833
|
+
throw err;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
if (!renamed)
|
|
837
|
+
throw lastErr;
|
|
838
|
+
}
|
|
839
|
+
catch (err) {
|
|
840
|
+
fs.rmSync(tmpPath, { force: true });
|
|
841
|
+
throw err;
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
const activeWorkspaceLocks = new Map();
|
|
845
|
+
async function withWorkspaceLock(rootReal, fn) {
|
|
846
|
+
const key = process.platform === "win32" ? rootReal.toLowerCase() : rootReal;
|
|
847
|
+
const previous = activeWorkspaceLocks.get(key) ?? Promise.resolve();
|
|
848
|
+
let release;
|
|
849
|
+
const current = new Promise((resolve) => {
|
|
850
|
+
release = resolve;
|
|
851
|
+
});
|
|
852
|
+
const chained = previous.then(() => current);
|
|
853
|
+
activeWorkspaceLocks.set(key, chained);
|
|
854
|
+
await previous;
|
|
855
|
+
try {
|
|
856
|
+
return await fn();
|
|
857
|
+
}
|
|
858
|
+
finally {
|
|
859
|
+
release();
|
|
860
|
+
if (activeWorkspaceLocks.get(key) === chained) {
|
|
861
|
+
activeWorkspaceLocks.delete(key);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
export async function lockProject(options = {}, deps = {}) {
|
|
866
|
+
const rootDir = path.resolve(options.cwd ?? process.cwd());
|
|
867
|
+
const rootReal = resolveCanonicalDir(rootDir);
|
|
868
|
+
return withWorkspaceLock(rootReal, () => lockProjectUnlocked(rootDir, rootReal, options, deps));
|
|
869
|
+
}
|
|
870
|
+
async function lockProjectUnlocked(rootDir, rootReal, options, deps) {
|
|
871
|
+
const workspace = resolveWorkspace(rootDir);
|
|
872
|
+
const lockPath = resolveLockPath(rootDir);
|
|
873
|
+
const dirIssue = inspectVibecodeDirSafety(rootDir, rootReal);
|
|
874
|
+
if (dirIssue) {
|
|
875
|
+
throw new VibecodeError("CONFIG_INVALID", dirIssue);
|
|
876
|
+
}
|
|
877
|
+
const lockInfo = inspectPathNoFollow(lockPath);
|
|
878
|
+
const contractInfo = inspectPathNoFollow(workspace.contractPath);
|
|
879
|
+
if (lockInfo.isSymlink) {
|
|
880
|
+
throw new VibecodeError("CONFIG_INVALID", `Refusing to operate on symlinked ${LOCK_FILE}.`);
|
|
881
|
+
}
|
|
882
|
+
if (lockInfo.exists && !lockInfo.isFile) {
|
|
883
|
+
throw new VibecodeError("CONFIG_INVALID", `Refusing to overwrite non-file ${LOCK_FILE}.`);
|
|
884
|
+
}
|
|
885
|
+
if (contractInfo.isSymlink) {
|
|
886
|
+
throw new VibecodeError("CONFIG_INVALID", `Refusing to operate on symlinked ${CONTRACT_FILE}.`);
|
|
887
|
+
}
|
|
888
|
+
if (contractInfo.exists && !contractInfo.isFile) {
|
|
889
|
+
throw new VibecodeError("CONFIG_INVALID", `Refusing to overwrite non-file ${CONTRACT_FILE}.`);
|
|
890
|
+
}
|
|
891
|
+
if (!options.force && (lockInfo.exists || contractInfo.exists)) {
|
|
892
|
+
const existing = lockInfo.exists ? LOCK_FILE : CONTRACT_FILE;
|
|
893
|
+
throw new VibecodeError("CONFIG_INVALID", `Refactor lock or contract already exists at ${existing}. Use --force to overwrite.`);
|
|
894
|
+
}
|
|
895
|
+
const inferred = autoInferLockTarget(rootDir, options);
|
|
896
|
+
const verifyTarget = (typeof options.target === "string" && options.target.trim() ? options.target.trim() : undefined) ??
|
|
897
|
+
inferred.target;
|
|
898
|
+
const offlineSpecOnly = !verifyTarget &&
|
|
899
|
+
!/^https?:\/\//i.test(inferred.source.trim()) &&
|
|
900
|
+
API_SPEC_LOCK_DOMAINS.has(inferred.domain);
|
|
901
|
+
const warnings = [];
|
|
902
|
+
const ingestOptions = {
|
|
903
|
+
domain: inferred.domain,
|
|
904
|
+
source: inferred.source,
|
|
905
|
+
name: inferred.name,
|
|
906
|
+
cwd: rootDir,
|
|
907
|
+
...(offlineSpecOnly ? { offline: true } : {}),
|
|
908
|
+
...(options.probes !== undefined ? { probes: options.probes } : {}),
|
|
909
|
+
...(options.routes !== undefined ? { routes: options.routes } : {}),
|
|
910
|
+
...(options.endpoints !== undefined ? { endpoints: options.endpoints } : {}),
|
|
911
|
+
...(options.baseUrl !== undefined ? { baseUrl: options.baseUrl } : {}),
|
|
912
|
+
...(options.headers !== undefined ? { headers: options.headers } : {}),
|
|
913
|
+
...(options.storageState !== undefined ? { storageState: options.storageState } : {}),
|
|
914
|
+
...(options.fsDiff === true ? { fsDiff: true } : {}),
|
|
915
|
+
...(options.crawlDepth !== undefined ? { crawlDepth: options.crawlDepth } : {}),
|
|
916
|
+
...(options.holdoutRoutes && options.holdoutRoutes.length > 0 ? { holdoutRoutes: options.holdoutRoutes } : {}),
|
|
917
|
+
...(options.env !== undefined ? { env: options.env } : {}),
|
|
918
|
+
...(options.noSpec === true ? { noSpec: true } : {})
|
|
919
|
+
};
|
|
920
|
+
const adaptedFetchRoute = deps.ingestDeps?.fetchRoute ??
|
|
921
|
+
(deps.fetchRoute
|
|
922
|
+
? (url, _viewport, timeoutMs, headers) => deps.fetchRoute(url, timeoutMs, headers)
|
|
923
|
+
: undefined);
|
|
924
|
+
const ingestDeps = {
|
|
925
|
+
...(deps.ingestDeps ?? {}),
|
|
926
|
+
...(deps.sharp !== undefined ? { sharp: deps.sharp } : {}),
|
|
927
|
+
...(deps.playwright !== undefined ? { playwright: deps.playwright } : {}),
|
|
928
|
+
...(deps.ffmpegAdapter !== undefined ? { ffmpegAdapter: deps.ffmpegAdapter } : {}),
|
|
929
|
+
...(adaptedFetchRoute ? { fetchRoute: adaptedFetchRoute } : {}),
|
|
930
|
+
...((deps.fetchJson ?? deps.fetchWithTimeout) ? { fetchJson: deps.fetchJson ?? deps.fetchWithTimeout } : {}),
|
|
931
|
+
...(deps.tmpDir !== undefined ? { tmpDir: deps.tmpDir } : {}),
|
|
932
|
+
...(deps.timeoutMs !== undefined ? { timeoutMs: deps.timeoutMs } : {})
|
|
933
|
+
};
|
|
934
|
+
const ingested = await ingest(ingestOptions, ingestDeps);
|
|
935
|
+
for (const w of ingested.warnings || []) {
|
|
936
|
+
warnings.push(redactLockValue(w.message));
|
|
937
|
+
}
|
|
938
|
+
const redactedSource = redactLockValue(inferred.source);
|
|
939
|
+
const contract = makeDefaultContract({
|
|
940
|
+
name: inferred.name,
|
|
941
|
+
domain: ingested.domain,
|
|
942
|
+
source: redactedSource
|
|
943
|
+
});
|
|
944
|
+
const invDomains = (ingested.invariants || [])
|
|
945
|
+
.map((inv) => inv.domain)
|
|
946
|
+
.filter((dom) => VALID_DOMAINS.has(dom));
|
|
947
|
+
contract.target.domains = [
|
|
948
|
+
...new Set([ingested.domain, ...invDomains].filter((dom) => VALID_DOMAINS.has(dom)))
|
|
949
|
+
];
|
|
950
|
+
contract.target.sources = (ingested.sources || []).map((src) => ({
|
|
951
|
+
...src,
|
|
952
|
+
ref: redactLockValue(src.ref),
|
|
953
|
+
meta: sanitizeSourceMeta(src.meta)
|
|
954
|
+
}));
|
|
955
|
+
contract.artifacts = ingested.artifacts;
|
|
956
|
+
contract.invariants = (ingested.invariants || []).map(sanitizeInvariantForLock);
|
|
957
|
+
if (options.slices === true) {
|
|
958
|
+
const derived = deriveDefaultSlices(contract);
|
|
959
|
+
if (derived.length > 0)
|
|
960
|
+
contract.slices = derived;
|
|
961
|
+
}
|
|
962
|
+
else if (Array.isArray(options.slices) && options.slices.length > 0) {
|
|
963
|
+
contract.slices = options.slices.map(sanitizeSliceForLock);
|
|
964
|
+
}
|
|
965
|
+
const contractPath = writeContract(contract, rootDir, {
|
|
966
|
+
force: Boolean(options.force),
|
|
967
|
+
replaceHoldouts: true
|
|
968
|
+
});
|
|
969
|
+
const persistedContract = readContract(rootDir);
|
|
970
|
+
const holdouts = readHoldouts(rootDir);
|
|
971
|
+
const visibleInvariants = persistedContract.invariants.length;
|
|
972
|
+
const holdoutInvariants = holdouts.length;
|
|
973
|
+
const specPath = options.noSpec
|
|
974
|
+
? undefined
|
|
975
|
+
: writeSpecFile(rootDir, { contract: persistedContract, holdoutCount: holdoutInvariants });
|
|
976
|
+
const extraFingerprintFiles = [];
|
|
977
|
+
if (Array.isArray(options.discoverHint?.entryFiles)) {
|
|
978
|
+
extraFingerprintFiles.push(...options.discoverHint.entryFiles);
|
|
979
|
+
}
|
|
980
|
+
extraFingerprintFiles.push(...collectCommandFileCandidates(inferred.source));
|
|
981
|
+
extraFingerprintFiles.push(...collectCommandFileCandidates(inferred.target));
|
|
982
|
+
for (const inv of persistedContract.invariants) {
|
|
983
|
+
if (inv.type === "repo_exports") {
|
|
984
|
+
if (typeof inv.input?.modulePath === "string" && inv.input.modulePath.trim()) {
|
|
985
|
+
extraFingerprintFiles.push(inv.input.modulePath.trim());
|
|
986
|
+
}
|
|
987
|
+
if (Array.isArray(inv.expected?.filesPresent)) {
|
|
988
|
+
for (const rel of inv.expected.filesPresent) {
|
|
989
|
+
if (typeof rel === "string" && rel.trim())
|
|
990
|
+
extraFingerprintFiles.push(rel.trim());
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
const fingerprint = computeWorkspaceFingerprint(rootDir, extraFingerprintFiles);
|
|
996
|
+
let baselineVerified = false;
|
|
997
|
+
let baselineGate = "unverified";
|
|
998
|
+
let baselineHardParity = null;
|
|
999
|
+
let baselineSoftParity = null;
|
|
1000
|
+
let baselineReport;
|
|
1001
|
+
let ok = true;
|
|
1002
|
+
if (options.noVerify === true) {
|
|
1003
|
+
warnings.push("Baseline self-verification was skipped (--no-verify). Run verify to confirm baseline parity.");
|
|
1004
|
+
}
|
|
1005
|
+
else if (!verifyTarget) {
|
|
1006
|
+
warnings.push("No runnable target available for offline spec lock; baseline self-verification was skipped. Run verify with --target once your implementation is running.");
|
|
1007
|
+
}
|
|
1008
|
+
else {
|
|
1009
|
+
const ctx = {
|
|
1010
|
+
target: verifyTarget,
|
|
1011
|
+
cwd: rootDir,
|
|
1012
|
+
contract: persistedContract,
|
|
1013
|
+
artifactsDir: workspace.artifactsDir,
|
|
1014
|
+
cacheDir: workspace.cacheDir,
|
|
1015
|
+
strict: options.strict === true,
|
|
1016
|
+
...(options.headers ? { headers: options.headers } : {}),
|
|
1017
|
+
...(options.storageState ? { storageState: options.storageState } : {}),
|
|
1018
|
+
runtimeCache: {}
|
|
1019
|
+
};
|
|
1020
|
+
baselineReport = await verifyContract(persistedContract, ctx, deps);
|
|
1021
|
+
writeLastReport(baselineReport, rootDir);
|
|
1022
|
+
baselineGate = baselineReport.gate.status;
|
|
1023
|
+
baselineHardParity = baselineReport.hard.parity;
|
|
1024
|
+
baselineSoftParity = baselineReport.soft.parity;
|
|
1025
|
+
if (baselineReport.gate.passed) {
|
|
1026
|
+
baselineVerified = true;
|
|
1027
|
+
if (baselineGate === "pass_with_warnings") {
|
|
1028
|
+
warnings.push("Baseline self-verification passed with soft invariant warnings.");
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
else {
|
|
1032
|
+
ok = false;
|
|
1033
|
+
baselineVerified = false;
|
|
1034
|
+
const reasonSummary = baselineReport.gate.reasons.length > 0
|
|
1035
|
+
? baselineReport.gate.reasons.map((r) => redactLockValue(r)).join("; ")
|
|
1036
|
+
: `gate=${baselineGate}`;
|
|
1037
|
+
warnings.push(`Baseline self-verification failed (${reasonSummary}). ${LOCK_FILE} was NOT written so the lock never records a broken baseline.`);
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
const contractSha256 = computeFileSha256(contractPath);
|
|
1041
|
+
const canonicalInfo = inspectCanonicalContract(contractPath);
|
|
1042
|
+
const canonicalContractSha256 = canonicalInfo?.hasValidSlices ? canonicalInfo.sha256 : undefined;
|
|
1043
|
+
const redactedTarget = verifyTarget !== undefined
|
|
1044
|
+
? ingested.domain === "repo" && path.resolve(rootDir, verifyTarget) === rootDir
|
|
1045
|
+
? "."
|
|
1046
|
+
: redactLockValue(verifyTarget)
|
|
1047
|
+
: undefined;
|
|
1048
|
+
const verifyBuilt = buildVerifyCommand(ingested.domain, rootDir, verifyTarget, options.strict === true);
|
|
1049
|
+
const verifyCommand = verifyBuilt.command;
|
|
1050
|
+
if (verifyBuilt.sanitizedUnsafeTarget) {
|
|
1051
|
+
warnings.push("Target contains shell metacharacters; omitted from verifyCommand placeholder for safety.");
|
|
1052
|
+
}
|
|
1053
|
+
const manifest = {
|
|
1054
|
+
schemaVersion: "1.0.0",
|
|
1055
|
+
lockedAt: new Date().toISOString(),
|
|
1056
|
+
name: sanitizeProjectName(inferred.name),
|
|
1057
|
+
domain: ingested.domain,
|
|
1058
|
+
source: redactedSource,
|
|
1059
|
+
...(redactedTarget !== undefined ? { target: redactedTarget } : {}),
|
|
1060
|
+
contractSha256,
|
|
1061
|
+
...(canonicalContractSha256 ? { canonicalContractSha256 } : {}),
|
|
1062
|
+
visibleInvariants,
|
|
1063
|
+
holdoutInvariants,
|
|
1064
|
+
baselineVerified,
|
|
1065
|
+
baselineGate,
|
|
1066
|
+
baselineHardParity,
|
|
1067
|
+
baselineSoftParity,
|
|
1068
|
+
sourceFingerprint: fingerprint.sha256,
|
|
1069
|
+
fingerprintedFiles: fingerprint.files,
|
|
1070
|
+
verifyCommand
|
|
1071
|
+
};
|
|
1072
|
+
if (ok) {
|
|
1073
|
+
writeLockManifestAtomic(lockPath, manifest, rootDir, rootReal);
|
|
1074
|
+
}
|
|
1075
|
+
else if (inspectPathNoFollow(lockPath).isFile) {
|
|
1076
|
+
fs.rmSync(lockPath, { force: true });
|
|
1077
|
+
}
|
|
1078
|
+
const nextSteps = ok
|
|
1079
|
+
? [
|
|
1080
|
+
`Perform your refactor, upgrade, or migration edits without modifying ${CONTRACT_FILE}.`,
|
|
1081
|
+
`Prove zero regressions with: ${verifyCommand}`,
|
|
1082
|
+
"Check contract tamper & source drift status with: vibecode-anything lock --check"
|
|
1083
|
+
]
|
|
1084
|
+
: [
|
|
1085
|
+
"Inspect failing baseline invariants in .vibecode/last-report.json and resolve nondeterminism or target errors.",
|
|
1086
|
+
"Re-run lock with --force once the baseline target passes cleanly."
|
|
1087
|
+
];
|
|
1088
|
+
if (ok && hasSensitiveHeaders(options.headers)) {
|
|
1089
|
+
nextSteps.push('Sensitive headers were redacted from the lock; supply them at runtime via --header "<Name>: <value>" during verify.');
|
|
1090
|
+
}
|
|
1091
|
+
return {
|
|
1092
|
+
ok,
|
|
1093
|
+
manifest,
|
|
1094
|
+
contractPath,
|
|
1095
|
+
lockPath,
|
|
1096
|
+
...(specPath ? { specPath } : {}),
|
|
1097
|
+
...(baselineReport ? { baselineReport } : {}),
|
|
1098
|
+
warnings,
|
|
1099
|
+
nextSteps
|
|
1100
|
+
};
|
|
1101
|
+
}
|
|
1102
|
+
function getOwn(obj, key) {
|
|
1103
|
+
return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
|
|
1104
|
+
}
|
|
1105
|
+
function isValidFingerprintedEntry(entry) {
|
|
1106
|
+
if (typeof entry !== "string" || entry.length === 0 || entry.length > MAX_LOCK_PATH_LENGTH) {
|
|
1107
|
+
return false;
|
|
1108
|
+
}
|
|
1109
|
+
if (hasCrossPlatformPathEscape(entry) ||
|
|
1110
|
+
path.isAbsolute(entry) ||
|
|
1111
|
+
entry.startsWith("/") ||
|
|
1112
|
+
WINDOWS_DRIVE_ANY_RE.test(entry)) {
|
|
1113
|
+
return false;
|
|
1114
|
+
}
|
|
1115
|
+
const normalized = entry.replace(/\\/g, "/");
|
|
1116
|
+
return !normalized.split("/").includes("..") && !isSecretOrExcludedRelativePath(normalized);
|
|
1117
|
+
}
|
|
1118
|
+
function validateLockManifest(raw) {
|
|
1119
|
+
const issues = [];
|
|
1120
|
+
if (!isRecord(raw)) {
|
|
1121
|
+
return { issues: [`Invalid ${LOCK_FILE}: root value must be a JSON object.`] };
|
|
1122
|
+
}
|
|
1123
|
+
const schemaVersion = getOwn(raw, "schemaVersion");
|
|
1124
|
+
const lockedAt = getOwn(raw, "lockedAt");
|
|
1125
|
+
const name = getOwn(raw, "name");
|
|
1126
|
+
const domain = getOwn(raw, "domain");
|
|
1127
|
+
const source = getOwn(raw, "source");
|
|
1128
|
+
const target = getOwn(raw, "target");
|
|
1129
|
+
const contractSha256 = getOwn(raw, "contractSha256");
|
|
1130
|
+
const canonicalContractSha256 = getOwn(raw, "canonicalContractSha256");
|
|
1131
|
+
const visibleInvariants = getOwn(raw, "visibleInvariants");
|
|
1132
|
+
const holdoutInvariants = getOwn(raw, "holdoutInvariants");
|
|
1133
|
+
const baselineVerified = getOwn(raw, "baselineVerified");
|
|
1134
|
+
const baselineGate = getOwn(raw, "baselineGate");
|
|
1135
|
+
const baselineHardParity = getOwn(raw, "baselineHardParity");
|
|
1136
|
+
const baselineSoftParity = getOwn(raw, "baselineSoftParity");
|
|
1137
|
+
const sourceFingerprint = getOwn(raw, "sourceFingerprint");
|
|
1138
|
+
const fingerprintedFiles = getOwn(raw, "fingerprintedFiles");
|
|
1139
|
+
const verifyCommand = getOwn(raw, "verifyCommand");
|
|
1140
|
+
if (schemaVersion !== "1.0.0") {
|
|
1141
|
+
issues.push(`Unsupported or missing schemaVersion in ${LOCK_FILE}: expected "1.0.0".`);
|
|
1142
|
+
}
|
|
1143
|
+
if (typeof lockedAt !== "string" ||
|
|
1144
|
+
!lockedAt.trim() ||
|
|
1145
|
+
lockedAt.length > MAX_LOCK_DATE_LENGTH ||
|
|
1146
|
+
CONTROL_CHAR_RE.test(lockedAt) ||
|
|
1147
|
+
!Number.isFinite(Date.parse(lockedAt))) {
|
|
1148
|
+
issues.push(`Missing or invalid lockedAt in ${LOCK_FILE}.`);
|
|
1149
|
+
}
|
|
1150
|
+
if (typeof name !== "string" ||
|
|
1151
|
+
!name.trim() ||
|
|
1152
|
+
name.length > MAX_LOCK_NAME_LENGTH ||
|
|
1153
|
+
CONTROL_CHAR_RE.test(name)) {
|
|
1154
|
+
issues.push(`Missing or invalid name in ${LOCK_FILE}.`);
|
|
1155
|
+
}
|
|
1156
|
+
if (typeof domain !== "string" || !VALID_DOMAINS.has(domain)) {
|
|
1157
|
+
issues.push(`Invalid domain in ${LOCK_FILE}: ${String(domain)}.`);
|
|
1158
|
+
}
|
|
1159
|
+
if (typeof source !== "string" || source.length > MAX_LOCK_COMMAND_LENGTH || source.includes("\0")) {
|
|
1160
|
+
issues.push(`Missing or invalid source in ${LOCK_FILE}.`);
|
|
1161
|
+
}
|
|
1162
|
+
if (target !== undefined &&
|
|
1163
|
+
(typeof target !== "string" || target.length > MAX_LOCK_COMMAND_LENGTH || STRICT_CONTROL_CHARS_RE.test(target))) {
|
|
1164
|
+
issues.push(`Invalid target in ${LOCK_FILE}: must be a safe string when present.`);
|
|
1165
|
+
}
|
|
1166
|
+
if (typeof contractSha256 !== "string" || !SHA256_HEX_RE.test(contractSha256)) {
|
|
1167
|
+
issues.push(`Missing or invalid contractSha256 in ${LOCK_FILE}.`);
|
|
1168
|
+
}
|
|
1169
|
+
if (canonicalContractSha256 !== undefined &&
|
|
1170
|
+
(typeof canonicalContractSha256 !== "string" || !SHA256_HEX_RE.test(canonicalContractSha256))) {
|
|
1171
|
+
issues.push(`Invalid canonicalContractSha256 in ${LOCK_FILE}.`);
|
|
1172
|
+
}
|
|
1173
|
+
if (typeof visibleInvariants !== "number" ||
|
|
1174
|
+
!Number.isSafeInteger(visibleInvariants) ||
|
|
1175
|
+
visibleInvariants < 0) {
|
|
1176
|
+
issues.push(`Invalid visibleInvariants in ${LOCK_FILE}.`);
|
|
1177
|
+
}
|
|
1178
|
+
if (typeof holdoutInvariants !== "number" ||
|
|
1179
|
+
!Number.isSafeInteger(holdoutInvariants) ||
|
|
1180
|
+
holdoutInvariants < 0) {
|
|
1181
|
+
issues.push(`Invalid holdoutInvariants in ${LOCK_FILE}.`);
|
|
1182
|
+
}
|
|
1183
|
+
if (typeof baselineVerified !== "boolean") {
|
|
1184
|
+
issues.push(`Invalid baselineVerified in ${LOCK_FILE}.`);
|
|
1185
|
+
}
|
|
1186
|
+
if (typeof baselineGate !== "string" ||
|
|
1187
|
+
!VALID_BASELINE_GATES.has(baselineGate)) {
|
|
1188
|
+
issues.push(`Invalid baselineGate in ${LOCK_FILE}: ${String(baselineGate)}.`);
|
|
1189
|
+
}
|
|
1190
|
+
else if (typeof baselineVerified === "boolean") {
|
|
1191
|
+
const gatePassed = baselineGate === "pass" || baselineGate === "pass_with_warnings";
|
|
1192
|
+
if (baselineVerified !== gatePassed) {
|
|
1193
|
+
issues.push(`Inconsistent baselineVerified (${String(baselineVerified)}) and baselineGate (${baselineGate}) in ${LOCK_FILE}.`);
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
if (baselineHardParity !== null &&
|
|
1197
|
+
(typeof baselineHardParity !== "number" ||
|
|
1198
|
+
!Number.isFinite(baselineHardParity) ||
|
|
1199
|
+
baselineHardParity < 0 ||
|
|
1200
|
+
baselineHardParity > 1)) {
|
|
1201
|
+
issues.push(`Invalid baselineHardParity in ${LOCK_FILE}.`);
|
|
1202
|
+
}
|
|
1203
|
+
if (baselineSoftParity !== null &&
|
|
1204
|
+
(typeof baselineSoftParity !== "number" ||
|
|
1205
|
+
!Number.isFinite(baselineSoftParity) ||
|
|
1206
|
+
baselineSoftParity < 0 ||
|
|
1207
|
+
baselineSoftParity > 1)) {
|
|
1208
|
+
issues.push(`Invalid baselineSoftParity in ${LOCK_FILE}.`);
|
|
1209
|
+
}
|
|
1210
|
+
if (typeof sourceFingerprint !== "string" || !SHA256_HEX_RE.test(sourceFingerprint)) {
|
|
1211
|
+
issues.push(`Missing or invalid sourceFingerprint in ${LOCK_FILE}.`);
|
|
1212
|
+
}
|
|
1213
|
+
if (!Array.isArray(fingerprintedFiles) ||
|
|
1214
|
+
fingerprintedFiles.length > MAX_LOCK_FINGERPRINTED_ENTRIES ||
|
|
1215
|
+
!fingerprintedFiles.every(isValidFingerprintedEntry)) {
|
|
1216
|
+
issues.push(`Invalid fingerprintedFiles in ${LOCK_FILE}: must be an array of safe relative paths.`);
|
|
1217
|
+
}
|
|
1218
|
+
if (typeof verifyCommand !== "string" ||
|
|
1219
|
+
verifyCommand.length > MAX_LOCK_COMMAND_LENGTH ||
|
|
1220
|
+
CONTROL_CHAR_RE.test(verifyCommand)) {
|
|
1221
|
+
issues.push(`Missing or invalid verifyCommand in ${LOCK_FILE}.`);
|
|
1222
|
+
}
|
|
1223
|
+
if (issues.length > 0) {
|
|
1224
|
+
return { issues };
|
|
1225
|
+
}
|
|
1226
|
+
// Reconstruct a clean plain LockManifest object (strips any `__proto__` or unknown attacker keys).
|
|
1227
|
+
const cleanManifest = {
|
|
1228
|
+
schemaVersion: "1.0.0",
|
|
1229
|
+
lockedAt: lockedAt,
|
|
1230
|
+
name: name,
|
|
1231
|
+
domain: domain,
|
|
1232
|
+
source: source,
|
|
1233
|
+
...(target !== undefined ? { target: target } : {}),
|
|
1234
|
+
contractSha256: contractSha256,
|
|
1235
|
+
...(canonicalContractSha256 !== undefined ? { canonicalContractSha256: canonicalContractSha256 } : {}),
|
|
1236
|
+
visibleInvariants: visibleInvariants,
|
|
1237
|
+
holdoutInvariants: holdoutInvariants,
|
|
1238
|
+
baselineVerified: baselineVerified,
|
|
1239
|
+
baselineGate: baselineGate,
|
|
1240
|
+
baselineHardParity: baselineHardParity,
|
|
1241
|
+
baselineSoftParity: baselineSoftParity,
|
|
1242
|
+
sourceFingerprint: sourceFingerprint,
|
|
1243
|
+
fingerprintedFiles: fingerprintedFiles.map((p) => p.replace(/\\/g, "/")),
|
|
1244
|
+
verifyCommand: verifyCommand
|
|
1245
|
+
};
|
|
1246
|
+
return {
|
|
1247
|
+
manifest: cleanManifest,
|
|
1248
|
+
issues: []
|
|
1249
|
+
};
|
|
1250
|
+
}
|
|
1251
|
+
function parseLockManifestFile(lockPath, rootDir, rootReal) {
|
|
1252
|
+
const dirIssue = inspectVibecodeDirSafety(rootDir, rootReal);
|
|
1253
|
+
if (dirIssue) {
|
|
1254
|
+
return { exists: true, issues: [dirIssue] };
|
|
1255
|
+
}
|
|
1256
|
+
const info = inspectPathNoFollow(lockPath);
|
|
1257
|
+
if (!info.exists) {
|
|
1258
|
+
return { exists: false, issues: [] };
|
|
1259
|
+
}
|
|
1260
|
+
if (info.isSymlink) {
|
|
1261
|
+
return {
|
|
1262
|
+
exists: true,
|
|
1263
|
+
issues: [`Refusing to read symlinked ${LOCK_FILE}.`]
|
|
1264
|
+
};
|
|
1265
|
+
}
|
|
1266
|
+
if (!info.isFile) {
|
|
1267
|
+
return {
|
|
1268
|
+
exists: true,
|
|
1269
|
+
issues: [`Invalid ${LOCK_FILE}: expected a regular file.`]
|
|
1270
|
+
};
|
|
1271
|
+
}
|
|
1272
|
+
if (info.size > MAX_LOCK_FILE_BYTES) {
|
|
1273
|
+
return {
|
|
1274
|
+
exists: true,
|
|
1275
|
+
issues: [`Invalid ${LOCK_FILE}: file exceeds maximum allowed size (${MAX_LOCK_FILE_BYTES} bytes).`]
|
|
1276
|
+
};
|
|
1277
|
+
}
|
|
1278
|
+
try {
|
|
1279
|
+
const realLockPath = fs.realpathSync(lockPath);
|
|
1280
|
+
if (!isPathWithinDir(realLockPath, rootReal)) {
|
|
1281
|
+
return {
|
|
1282
|
+
exists: true,
|
|
1283
|
+
issues: [`Refusing to read ${LOCK_FILE} resolving outside workspace root.`]
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
catch (err) {
|
|
1288
|
+
return {
|
|
1289
|
+
exists: true,
|
|
1290
|
+
issues: [`Failed to resolve ${LOCK_FILE}: ${errorMessage(err)}`]
|
|
1291
|
+
};
|
|
1292
|
+
}
|
|
1293
|
+
let raw;
|
|
1294
|
+
try {
|
|
1295
|
+
raw = JSON.parse(fs.readFileSync(lockPath, "utf8"));
|
|
1296
|
+
}
|
|
1297
|
+
catch (err) {
|
|
1298
|
+
return {
|
|
1299
|
+
exists: true,
|
|
1300
|
+
issues: [`Failed to parse ${LOCK_FILE}: ${errorMessage(err)}`]
|
|
1301
|
+
};
|
|
1302
|
+
}
|
|
1303
|
+
const validated = validateLockManifest(raw);
|
|
1304
|
+
return {
|
|
1305
|
+
exists: true,
|
|
1306
|
+
...(validated.manifest ? { manifest: validated.manifest } : {}),
|
|
1307
|
+
issues: validated.issues
|
|
1308
|
+
};
|
|
1309
|
+
}
|
|
1310
|
+
export function readLockManifest(cwd = process.cwd()) {
|
|
1311
|
+
const rootDir = path.resolve(cwd);
|
|
1312
|
+
const rootReal = resolveCanonicalDir(rootDir);
|
|
1313
|
+
const parsed = parseLockManifestFile(resolveLockPath(rootDir), rootDir, rootReal);
|
|
1314
|
+
return parsed.manifest ?? null;
|
|
1315
|
+
}
|
|
1316
|
+
export function checkLockStatus(cwd = process.cwd()) {
|
|
1317
|
+
const rootDir = path.resolve(cwd);
|
|
1318
|
+
const rootReal = resolveCanonicalDir(rootDir);
|
|
1319
|
+
const lockPath = resolveLockPath(rootDir);
|
|
1320
|
+
const workspace = resolveWorkspace(rootDir);
|
|
1321
|
+
const parsed = parseLockManifestFile(lockPath, rootDir, rootReal);
|
|
1322
|
+
if (!parsed.exists) {
|
|
1323
|
+
return {
|
|
1324
|
+
exists: false,
|
|
1325
|
+
valid: false,
|
|
1326
|
+
contractTampered: false,
|
|
1327
|
+
sourceChanged: false,
|
|
1328
|
+
issues: [`No refactor safety lock found at ${LOCK_FILE}. Run 'vibecode-anything lock' first.`]
|
|
1329
|
+
};
|
|
1330
|
+
}
|
|
1331
|
+
if (!parsed.manifest || parsed.issues.length > 0) {
|
|
1332
|
+
return {
|
|
1333
|
+
exists: true,
|
|
1334
|
+
valid: false,
|
|
1335
|
+
contractTampered: false,
|
|
1336
|
+
sourceChanged: false,
|
|
1337
|
+
issues: parsed.issues
|
|
1338
|
+
};
|
|
1339
|
+
}
|
|
1340
|
+
const manifest = parsed.manifest;
|
|
1341
|
+
const issues = [];
|
|
1342
|
+
let contractTampered = false;
|
|
1343
|
+
let currentContractSha256;
|
|
1344
|
+
if (manifest.baselineGate === "fail") {
|
|
1345
|
+
issues.push(`${LOCK_FILE} records a failed baseline gate.`);
|
|
1346
|
+
}
|
|
1347
|
+
const contractInfo = inspectPathNoFollow(workspace.contractPath);
|
|
1348
|
+
if (!contractInfo.exists) {
|
|
1349
|
+
contractTampered = true;
|
|
1350
|
+
issues.push(`Locked contract ${CONTRACT_FILE} is missing — contract was deleted or moved after locking.`);
|
|
1351
|
+
}
|
|
1352
|
+
else if (contractInfo.isSymlink) {
|
|
1353
|
+
contractTampered = true;
|
|
1354
|
+
issues.push(`Refusing to verify symlinked ${CONTRACT_FILE} — contract integrity compromised.`);
|
|
1355
|
+
}
|
|
1356
|
+
else if (!contractInfo.isFile) {
|
|
1357
|
+
contractTampered = true;
|
|
1358
|
+
issues.push(`Invalid ${CONTRACT_FILE}: expected a regular file.`);
|
|
1359
|
+
}
|
|
1360
|
+
else {
|
|
1361
|
+
try {
|
|
1362
|
+
const contractReal = fs.realpathSync(workspace.contractPath);
|
|
1363
|
+
if (!isPathWithinDir(contractReal, rootReal)) {
|
|
1364
|
+
contractTampered = true;
|
|
1365
|
+
issues.push(`Refusing to verify ${CONTRACT_FILE} resolving outside workspace root.`);
|
|
1366
|
+
}
|
|
1367
|
+
else {
|
|
1368
|
+
currentContractSha256 = computeFileSha256(contractReal);
|
|
1369
|
+
const rawMatches = currentContractSha256.toLowerCase() === manifest.contractSha256.toLowerCase();
|
|
1370
|
+
if (manifest.canonicalContractSha256) {
|
|
1371
|
+
const canonical = inspectCanonicalContract(contractReal);
|
|
1372
|
+
const canonicalMatches = Boolean(canonical?.hasValidSlices) &&
|
|
1373
|
+
canonical.sha256.toLowerCase() === manifest.canonicalContractSha256.toLowerCase();
|
|
1374
|
+
if (!canonicalMatches) {
|
|
1375
|
+
contractTampered = true;
|
|
1376
|
+
issues.push(rawMatches
|
|
1377
|
+
? `Contract tamper detected: ${LOCK_FILE} canonicalContractSha256 does not match ${CONTRACT_FILE} canonical slice integrity.`
|
|
1378
|
+
: `Contract tamper detected: ${CONTRACT_FILE} SHA-256 (${currentContractSha256.slice(0, 12)}) does not match locked SHA-256 (${manifest.contractSha256.slice(0, 12)}).`);
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
else if (!rawMatches) {
|
|
1382
|
+
contractTampered = true;
|
|
1383
|
+
issues.push(`Contract tamper detected: ${CONTRACT_FILE} SHA-256 (${currentContractSha256.slice(0, 12)}) does not match locked SHA-256 (${manifest.contractSha256.slice(0, 12)}).`);
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
catch (err) {
|
|
1388
|
+
contractTampered = true;
|
|
1389
|
+
issues.push(`Failed to hash ${CONTRACT_FILE}: ${errorMessage(err)}`);
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
const currentFingerprint = computeWorkspaceFingerprint(rootDir, manifest.fingerprintedFiles);
|
|
1393
|
+
const sourceChanged = currentFingerprint.sha256.toLowerCase() !== manifest.sourceFingerprint.toLowerCase();
|
|
1394
|
+
const valid = !contractTampered && issues.length === 0;
|
|
1395
|
+
return {
|
|
1396
|
+
exists: true,
|
|
1397
|
+
valid,
|
|
1398
|
+
contractTampered,
|
|
1399
|
+
sourceChanged,
|
|
1400
|
+
...(currentContractSha256 ? { currentContractSha256 } : {}),
|
|
1401
|
+
lockedContractSha256: manifest.contractSha256,
|
|
1402
|
+
currentSourceFingerprint: currentFingerprint.sha256,
|
|
1403
|
+
lockedSourceFingerprint: manifest.sourceFingerprint,
|
|
1404
|
+
manifest,
|
|
1405
|
+
issues
|
|
1406
|
+
};
|
|
1407
|
+
}
|
|
1408
|
+
function formatParityPercent(value) {
|
|
1409
|
+
if (value === null || !Number.isFinite(value))
|
|
1410
|
+
return "n/a";
|
|
1411
|
+
return `${(Math.max(0, Math.min(1, value)) * 100).toFixed(1)}%`;
|
|
1412
|
+
}
|
|
1413
|
+
export function formatPrettyLock(result, options = {}) {
|
|
1414
|
+
const useColor = options.color === true;
|
|
1415
|
+
const m = result.manifest;
|
|
1416
|
+
const lines = [];
|
|
1417
|
+
const badge = !result.ok
|
|
1418
|
+
? { label: "[LOCK FAILED]", color: `${ANSI.bold}${ANSI.red}` }
|
|
1419
|
+
: !m.baselineVerified
|
|
1420
|
+
? { label: "[LOCKED (UNVERIFIED)]", color: `${ANSI.bold}${ANSI.yellow}` }
|
|
1421
|
+
: m.baselineGate === "pass_with_warnings"
|
|
1422
|
+
? { label: "[LOCKED WITH WARNINGS]", color: `${ANSI.bold}${ANSI.yellow}` }
|
|
1423
|
+
: { label: "[LOCKED]", color: `${ANSI.bold}${ANSI.green}` };
|
|
1424
|
+
lines.push(`${style("vibecode-anything lock", `${ANSI.bold}${ANSI.cyan}`, useColor)} ${style(badge.label, badge.color, useColor)} ${style(redactLockValue(m.name), ANSI.bold, useColor)}`);
|
|
1425
|
+
const sourceSafe = redactLockValue(m.source);
|
|
1426
|
+
const targetPart = m.target ? ` | Target: ${redactLockValue(m.target)}` : "";
|
|
1427
|
+
lines.push(`Domain: ${m.domain} | Source: ${sourceSafe}${targetPart}`);
|
|
1428
|
+
lines.push(`Invariants: ${m.visibleInvariants} visible, ${m.holdoutInvariants} holdouts (external vault)`);
|
|
1429
|
+
const baselineDetails = m.baselineHardParity !== null
|
|
1430
|
+
? ` (hard ${formatParityPercent(m.baselineHardParity)}, soft ${formatParityPercent(m.baselineSoftParity)})`
|
|
1431
|
+
: "";
|
|
1432
|
+
const baselineColor = !result.ok
|
|
1433
|
+
? ANSI.red
|
|
1434
|
+
: m.baselineVerified
|
|
1435
|
+
? m.baselineGate === "pass_with_warnings"
|
|
1436
|
+
? ANSI.yellow
|
|
1437
|
+
: ANSI.green
|
|
1438
|
+
: ANSI.yellow;
|
|
1439
|
+
lines.push(`Baseline: ${style(m.baselineGate, baselineColor, useColor)}${baselineDetails}`);
|
|
1440
|
+
lines.push(`Contract SHA-256: ${style(m.contractSha256.slice(0, 16) + "...", ANSI.dim, useColor)}`);
|
|
1441
|
+
lines.push(`Source Fingerprint: ${style(m.sourceFingerprint.slice(0, 16) + "...", ANSI.dim, useColor)} (${m.fingerprintedFiles.length} ${m.fingerprintedFiles.length === 1 ? "file" : "files"})`);
|
|
1442
|
+
const fileParts = [CONTRACT_FILE];
|
|
1443
|
+
if (result.specPath)
|
|
1444
|
+
fileParts.push(SPEC_FILE);
|
|
1445
|
+
if (result.ok)
|
|
1446
|
+
fileParts.push(LOCK_FILE);
|
|
1447
|
+
lines.push(`Files: ${fileParts.join(", ")}`);
|
|
1448
|
+
lines.push(`Verify: ${style(redactLockValue(m.verifyCommand), ANSI.cyan, useColor)}`);
|
|
1449
|
+
if (result.warnings.length > 0) {
|
|
1450
|
+
lines.push("");
|
|
1451
|
+
lines.push(style(`Warnings (${result.warnings.length}):`, `${ANSI.bold}${ANSI.yellow}`, useColor));
|
|
1452
|
+
for (const warning of result.warnings) {
|
|
1453
|
+
lines.push(` - ${redactLockValue(warning)}`);
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
if (result.nextSteps.length > 0) {
|
|
1457
|
+
lines.push("");
|
|
1458
|
+
lines.push(style("Next steps:", ANSI.bold, useColor));
|
|
1459
|
+
result.nextSteps.forEach((step, idx) => {
|
|
1460
|
+
lines.push(` ${idx + 1}. ${redactLockValue(step)}`);
|
|
1461
|
+
});
|
|
1462
|
+
}
|
|
1463
|
+
return lines.join("\n");
|
|
1464
|
+
}
|
|
1465
|
+
export function formatPrettyLockCheck(result, options = {}) {
|
|
1466
|
+
const useColor = options.color === true;
|
|
1467
|
+
const lines = [];
|
|
1468
|
+
const badge = !result.exists
|
|
1469
|
+
? { label: "[NO LOCK]", color: `${ANSI.bold}${ANSI.yellow}` }
|
|
1470
|
+
: result.contractTampered
|
|
1471
|
+
? { label: "[TAMPERED]", color: `${ANSI.bold}${ANSI.red}` }
|
|
1472
|
+
: !result.valid
|
|
1473
|
+
? { label: "[INVALID]", color: `${ANSI.bold}${ANSI.red}` }
|
|
1474
|
+
: result.sourceChanged
|
|
1475
|
+
? { label: "[LOCK VALID - SOURCE CHANGED]", color: `${ANSI.bold}${ANSI.cyan}` }
|
|
1476
|
+
: { label: "[LOCK VALID - CLEAN]", color: `${ANSI.bold}${ANSI.green}` };
|
|
1477
|
+
lines.push(`${style("vibecode-anything lock --check", `${ANSI.bold}${ANSI.cyan}`, useColor)} ${style(badge.label, badge.color, useColor)}`);
|
|
1478
|
+
if (result.manifest) {
|
|
1479
|
+
const m = result.manifest;
|
|
1480
|
+
lines.push(`Project: ${style(redactLockValue(m.name), ANSI.bold, useColor)} (${m.domain}) | Locked: ${m.lockedAt}`);
|
|
1481
|
+
const integrityText = result.contractTampered
|
|
1482
|
+
? style("TAMPERED", `${ANSI.bold}${ANSI.red}`, useColor)
|
|
1483
|
+
: style("INTACT", ANSI.green, useColor);
|
|
1484
|
+
const shaInfo = result.lockedContractSha256 && result.currentContractSha256
|
|
1485
|
+
? ` (locked=${result.lockedContractSha256.slice(0, 12)}, current=${result.currentContractSha256.slice(0, 12)})`
|
|
1486
|
+
: result.lockedContractSha256
|
|
1487
|
+
? ` (locked=${result.lockedContractSha256.slice(0, 12)}, current=missing)`
|
|
1488
|
+
: "";
|
|
1489
|
+
lines.push(`Contract Integrity: ${integrityText}${shaInfo}`);
|
|
1490
|
+
const driftText = result.sourceChanged
|
|
1491
|
+
? style("CHANGED (refactor edits detected — run verify)", ANSI.yellow, useColor)
|
|
1492
|
+
: style("UNCHANGED", ANSI.green, useColor);
|
|
1493
|
+
lines.push(`Source Drift: ${driftText}`);
|
|
1494
|
+
lines.push(`Invariants: ${m.visibleInvariants} visible, ${m.holdoutInvariants} holdouts | Baseline: ${m.baselineGate}`);
|
|
1495
|
+
lines.push(`Verify: ${style(redactLockValue(m.verifyCommand), ANSI.cyan, useColor)}`);
|
|
1496
|
+
}
|
|
1497
|
+
if (result.issues.length > 0) {
|
|
1498
|
+
lines.push("");
|
|
1499
|
+
lines.push(style(`Issues (${result.issues.length}):`, `${ANSI.bold}${ANSI.red}`, useColor));
|
|
1500
|
+
for (const issue of result.issues) {
|
|
1501
|
+
lines.push(` - ${redactLockValue(issue)}`);
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
return lines.join("\n");
|
|
1505
|
+
}
|