@guardefi/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +18 -0
  3. package/README.md +31 -2
  4. package/assurance/cli-check.js +446 -0
  5. package/assurance/cli-project-paths.js +56 -0
  6. package/assurance/cli-storage.js +289 -0
  7. package/assurance/cli-ui.js +617 -0
  8. package/assurance/guardefi-public.js +66 -0
  9. package/assurance/release-policy.js +212 -0
  10. package/core/behavioral-diff.js +555 -0
  11. package/core/canonical-json.js +9 -0
  12. package/core/engine/abi.js +99 -0
  13. package/core/engine/assumptions.json +86 -0
  14. package/core/engine/bytecode.js +119 -0
  15. package/core/engine/callee-binding.js +140 -0
  16. package/core/engine/deployment.js +175 -0
  17. package/core/engine/external-effects.js +40 -0
  18. package/core/engine/harness.js +503 -0
  19. package/core/engine/index.js +638 -0
  20. package/core/engine/integrity.js +124 -0
  21. package/core/engine/model.js +369 -0
  22. package/core/engine/policy.js +59 -0
  23. package/core/engine/proof-certificate.js +69 -0
  24. package/core/engine/provenance.js +354 -0
  25. package/core/engine/screen.js +117 -0
  26. package/core/engine/upgrade-authority.js +327 -0
  27. package/core/generic.js +334 -0
  28. package/core/hardhat.js +114 -0
  29. package/core/isl/behavior-profile.js +169 -0
  30. package/core/isl/behavior-solidity.js +267 -0
  31. package/core/isl/behavior-storage.js +151 -0
  32. package/core/isl/behavior-verify.js +223 -0
  33. package/core/isl/getter-profile.js +149 -0
  34. package/core/isl/vendor/NOTICE.md +38 -0
  35. package/core/isl/vendor/isl-parser.cjs +5872 -0
  36. package/core/isl-compiler.js +19 -0
  37. package/core/isl-firewall.js +1396 -0
  38. package/core/keccak.js +89 -0
  39. package/core/prove.js +376 -0
  40. package/core/release-receipt.js +793 -0
  41. package/core/rpc.js +74 -0
  42. package/core/tools.js +129 -0
  43. package/core/verdict-policy.js +195 -0
  44. package/docs/public-cli.md +32 -0
  45. package/package.json +29 -4
@@ -0,0 +1,446 @@
1
+ 'use strict';
2
+
3
+ // `guardefi check`: everyday developer command (like `forge test` / `cargo check`).
4
+ // Auto-discovers contracts, ISL specs, and `guardefi.project.json` check bindings when omitted,
5
+ // auto-builds Foundry projects when `out/` is missing or stale, decodes Halmos hex counterexamples
6
+ // into concrete Solidity calls, and optionally emits runnable `test/guardefi/Repro_*.t.sol` files (`--repro`).
7
+
8
+ const fs = require('node:fs');
9
+ const path = require('node:path');
10
+ const { run, isName } = require('../core/tools');
11
+ const { runBehavioralUpgradeDiff } = require('../core/behavioral-diff');
12
+ const { verifyIntentFirewall } = require('../core/isl-firewall');
13
+ const { verifyUpgrade } = require('../core/engine');
14
+ const { isHardhat, hardhatWorkspace } = require('../core/hardhat');
15
+ const { stricter, exitCode } = require('./release-policy');
16
+ const { normalizeProjectPos } = require('./cli-project-paths');
17
+ const { createSpinner, suggestClosest } = require('./cli-ui');
18
+
19
+ const ALLOWED_FLAGS = new Set([
20
+ 'isl',
21
+ 'link',
22
+ 'fast',
23
+ 'repro',
24
+ 'artifacts-only',
25
+ 'json',
26
+ 'pretty',
27
+ 'no-color',
28
+ 'quiet',
29
+ ]);
30
+
31
+ function walkFiles(dir, ext, out = [], depth = 0) {
32
+ if (!fs.existsSync(dir) || depth > 12) return out;
33
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
34
+ if (entry.name.startsWith('.') || ['node_modules', 'lib', 'out', 'cache', 'artifacts'].includes(entry.name)) continue;
35
+ const full = path.join(dir, entry.name);
36
+ if (entry.isDirectory()) walkFiles(full, ext, out, depth + 1);
37
+ else if (entry.isFile() && entry.name.endsWith(ext)) out.push(full);
38
+ }
39
+ return out;
40
+ }
41
+
42
+ function discoverContractsInSources(root) {
43
+ const srcDirs = ['src', 'contracts'].map((d) => path.join(root, d)).filter((d) => fs.existsSync(d));
44
+ const contracts = [];
45
+ for (const dir of srcDirs) {
46
+ for (const file of walkFiles(dir, '.sol')) {
47
+ const stripped = fs.readFileSync(file, 'utf8')
48
+ .replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '');
49
+ for (const m of stripped.matchAll(/\bcontract\s+([A-Za-z_][A-Za-z0-9_]*)\b/g)) {
50
+ contracts.push({ name: m[1], file: path.relative(root, file) });
51
+ }
52
+ }
53
+ }
54
+ return contracts;
55
+ }
56
+
57
+ function loadProjectCheckDefaults(root) {
58
+ const cfgPath = path.join(root, 'guardefi.project.json');
59
+ if (!fs.existsSync(cfgPath)) return null;
60
+ try {
61
+ const parsed = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
62
+ if (Array.isArray(parsed?.checks) && parsed.checks.length > 0 && typeof parsed.checks[0] === 'object') {
63
+ return parsed.checks[0];
64
+ }
65
+ } catch {
66
+ return null;
67
+ }
68
+ return null;
69
+ }
70
+
71
+ function inferContractTargets(root) {
72
+ const cfgCheck = loadProjectCheckDefaults(root);
73
+ if (cfgCheck?.candidate) {
74
+ return { candidate: cfgCheck.candidate, baseline: cfgCheck.baseline || null };
75
+ }
76
+ const contracts = discoverContractsInSources(root);
77
+ const names = [...new Set(contracts.map((c) => c.name))];
78
+ if (names.length === 0) {
79
+ throw new Error('No Solidity contracts found in src/ or contracts/. Run this command from your Solidity project or provide its path.');
80
+ }
81
+ if (names.length === 1) {
82
+ return { candidate: names[0], baseline: null };
83
+ }
84
+ for (const name of names) {
85
+ const v1Match = /^(.+?)(?:V1|Base)$/.exec(name);
86
+ if (!v1Match) continue;
87
+ const stem = v1Match[1];
88
+ const exactV2 = names.find((n) => n === `${stem}V2` || n === `${stem}V2Honest`);
89
+ if (exactV2) return { candidate: exactV2, baseline: name };
90
+ const anyV2 = names.filter((n) => n.startsWith(`${stem}V2`) && !/Backdoor|Bug|Bad|Malicious|Broken|Collision/i.test(n));
91
+ if (anyV2.length === 1) return { candidate: anyV2[0], baseline: name };
92
+ }
93
+ throw new Error(
94
+ `Multiple contracts found (${names.slice(0, 8).join(', ')}${names.length > 8 ? ', …' : ''}). Specify which to check: guardefi check <Candidate> [Baseline]`,
95
+ );
96
+ }
97
+
98
+ function discoverIslFiles(root, explicitIsl = [], cfgIsl = []) {
99
+ const chosen = explicitIsl.length > 0 ? explicitIsl : cfgIsl;
100
+ if (chosen.length > 0) {
101
+ return chosen.map((f) => {
102
+ const resolved = path.isAbsolute(f) ? f : path.resolve(root, f);
103
+ const fallbackCwd = path.resolve(f);
104
+ const actual = fs.existsSync(resolved) ? resolved : fs.existsSync(fallbackCwd) ? fallbackCwd : null;
105
+ if (!actual) throw new Error(`ISL file not found: ${f}`);
106
+ return actual;
107
+ });
108
+ }
109
+ const found = [];
110
+ for (const folder of ['policies', 'spec']) {
111
+ const dir = path.join(root, folder);
112
+ if (fs.existsSync(dir)) walkFiles(dir, '.isl', found);
113
+ }
114
+ return found;
115
+ }
116
+
117
+ function needsFoundryBuild(root, requiredNames) {
118
+ const outDir = path.join(root, 'out');
119
+ if (!fs.existsSync(outDir)) return true;
120
+ let newestSrcMtime = 0;
121
+ for (const d of ['src', 'contracts']) {
122
+ for (const f of walkFiles(path.join(root, d), '.sol')) {
123
+ newestSrcMtime = Math.max(newestSrcMtime, fs.statSync(f).mtimeMs);
124
+ }
125
+ }
126
+ for (const name of requiredNames.filter(Boolean)) {
127
+ const artPath = findArtifactPath(outDir, name);
128
+ if (!artPath) return true;
129
+ const stat = fs.statSync(artPath);
130
+ if (stat.mtimeMs < newestSrcMtime) return true;
131
+ const parsed = JSON.parse(fs.readFileSync(artPath, 'utf8'));
132
+ if (!parsed.storageLayout?.storage) return true;
133
+ }
134
+ return false;
135
+ }
136
+
137
+ function findArtifactPath(outDir, name) {
138
+ if (!fs.existsSync(outDir)) return null;
139
+ for (const folder of fs.readdirSync(outDir).sort()) {
140
+ if (folder === 'build-info') continue;
141
+ const full = path.join(outDir, folder);
142
+ if (!fs.statSync(full).isDirectory()) continue;
143
+ const candidate = path.join(full, `${name}.json`);
144
+ if (fs.existsSync(candidate)) return candidate;
145
+ }
146
+ return null;
147
+ }
148
+
149
+ function loadBuiltArtifact(root, name) {
150
+ const p = findArtifactPath(path.join(root, 'out'), name);
151
+ if (!p) throw new Error(`Compiled artifact not found for contract "${name}". Check the contract name or run \`forge build\`.`);
152
+ return JSON.parse(fs.readFileSync(p, 'utf8'));
153
+ }
154
+
155
+ function ensureBuilt(buildRoot, requiredNames, opt = {}, labelDir = buildRoot) {
156
+ if (fs.existsSync(path.join(buildRoot, 'foundry.toml')) && needsFoundryBuild(buildRoot, requiredNames)) {
157
+ return (async () => {
158
+ const buildSpin = createSpinner(`Compiling Solidity contracts in ${path.basename(labelDir)}…`, { opt });
159
+ const built = await run('forge', ['build', '--root', buildRoot, '--ast', '--extra-output', 'storageLayout']);
160
+ if (built.code !== 0) {
161
+ buildSpin.fail('Solidity build failed');
162
+ throw new Error(`forge build failed:\n${(built.stderr || built.stdout).trim()}`);
163
+ }
164
+ buildSpin.succeed('Compiled Solidity artifacts');
165
+ })();
166
+ }
167
+ return Promise.resolve();
168
+ }
169
+
170
+ function parseLinks(rawLinks = [], root) {
171
+ return rawLinks.map((spec) => {
172
+ const eq = String(spec).indexOf('=');
173
+ if (eq <= 0 || eq === spec.length - 1) {
174
+ throw new Error(`Invalid --link "${spec}"; expected <field>=<Contract>.`);
175
+ }
176
+ const field = spec.slice(0, eq).trim();
177
+ const contract = spec.slice(eq + 1).trim();
178
+ if (!isName(contract)) throw new Error(`Invalid contract name "${contract}" in --link "${spec}".`);
179
+ return { field, contract, artifact: loadBuiltArtifact(root, contract) };
180
+ });
181
+ }
182
+
183
+ async function runCheck({ pos: rawPos = [], opt = {} }, { publicRelease = false } = {}) {
184
+ const allowedFlags = [...ALLOWED_FLAGS].filter((f) => !publicRelease || f !== 'repro');
185
+ const validFlags = allowedFlags.map((f) => `--${f}`);
186
+ for (const k of Object.keys(opt)) {
187
+ if (!allowedFlags.includes(k)) {
188
+ const hint = suggestClosest(`--${k}`, validFlags);
189
+ throw new Error(`Unsupported option --${k} on \`guardefi check\`${hint ? ` (did you mean ${hint}?)` : ''}.`);
190
+ }
191
+ }
192
+
193
+ const started = Date.now();
194
+ const normalized = normalizeProjectPos('check', rawPos, process.cwd());
195
+ let projectArg = '.';
196
+ let candidate = null;
197
+ let baseline = null;
198
+
199
+ if (normalized.length === 0) {
200
+ projectArg = '.';
201
+ } else if (normalized.length === 1) {
202
+ projectArg = normalized[0];
203
+ } else if (normalized.length === 2) {
204
+ [projectArg, candidate] = normalized;
205
+ } else if (normalized.length === 3) {
206
+ [projectArg, candidate, baseline] = normalized;
207
+ } else {
208
+ throw new Error('Usage: guardefi check [projectDir] [Candidate] [Baseline] [--isl FILE]... [--link field=Contract]... [--fast]' + (publicRelease ? '' : ' [--repro]'));
209
+ }
210
+
211
+ const diagnosticTools = publicRelease ? null : require('./cli-counterexample');
212
+
213
+ const projectRoot = path.resolve(projectArg);
214
+ if (!fs.existsSync(projectRoot) || !fs.statSync(projectRoot).isDirectory()) {
215
+ throw new Error(`Project directory not found: ${projectArg}`);
216
+ }
217
+
218
+ const cfgCheck = loadProjectCheckDefaults(projectRoot);
219
+ if (!candidate) {
220
+ const inferred = inferContractTargets(projectRoot);
221
+ candidate = inferred.candidate;
222
+ baseline = inferred.baseline;
223
+ }
224
+ if (!isName(candidate) || (baseline && !isName(baseline))) {
225
+ throw new Error('Contract names must be valid Solidity identifiers.');
226
+ }
227
+
228
+ const fast = Boolean(opt.fast || opt['artifacts-only']);
229
+ const cfgIsl = Array.isArray(cfgCheck?.isl) ? cfgCheck.isl : [];
230
+ const islFiles = discoverIslFiles(projectRoot, opt.isl || [], cfgIsl);
231
+
232
+ const cfgLinks = cfgCheck?.links && typeof cfgCheck.links === 'object'
233
+ ? Object.entries(cfgCheck.links).map(([f, c]) => `${f}=${c}`)
234
+ : [];
235
+ const rawLinks = opt.link?.length ? opt.link : cfgLinks;
236
+ const linkedNames = rawLinks.map((s) => String(s).split('=')[1]?.trim()).filter(Boolean);
237
+
238
+ const hhWorkspace = isHardhat(projectRoot) && !fs.existsSync(path.join(projectRoot, 'foundry.toml'))
239
+ ? hardhatWorkspace(projectRoot, [candidate, ...(baseline ? [baseline] : []), ...linkedNames])
240
+ : null;
241
+
242
+ try {
243
+ const buildRoot = hhWorkspace?.root || projectRoot;
244
+ await ensureBuilt(buildRoot, [candidate, baseline, ...linkedNames], opt, projectRoot);
245
+
246
+ const candidateArtifact = loadBuiltArtifact(buildRoot, candidate);
247
+ const baseArtifact = baseline ? loadBuiltArtifact(buildRoot, baseline) : null;
248
+ const links = parseLinks(rawLinks, buildRoot);
249
+
250
+ const suites = [];
251
+ let verdict = 'SHIP';
252
+
253
+ // 1. Behavioral Upgrade Diff (when a baseline is provided)
254
+ let diffResult = null;
255
+ if (baseline) {
256
+ const diffSpin = createSpinner(
257
+ `Comparing upgrade surface (${baseline} -> ${candidate})${fast ? ' [fast]' : ''}…`,
258
+ { opt },
259
+ );
260
+ diffResult = await runBehavioralUpgradeDiff({
261
+ dir: buildRoot,
262
+ baseline,
263
+ candidate,
264
+ artifactsOnly: Boolean(fast || islFiles.length > 0),
265
+ });
266
+ diffSpin.succeed(`Checked storage layout & upgrade surface (${baseline} -> ${candidate})`);
267
+
268
+ const deltas = diffResult.diff?.deltas || [];
269
+ const layoutViolations = deltas.filter((d) => d.impact === 'violation');
270
+ const highSurface = deltas.filter((d) => d.impact !== 'violation' && d.impact !== 'compatible');
271
+ const diffItems = [];
272
+ if (diffResult.diff.storageCompatible === true) {
273
+ diffItems.push({ status: 'pass', epistemic: 'PROVEN', label: 'storage-layout', detail: `Compatible with ${baseline}` });
274
+ } else if (layoutViolations.length > 0) {
275
+ for (const v of layoutViolations) {
276
+ diffItems.push({ status: 'fail', epistemic: 'PROVEN', label: 'storage-layout', detail: v.change });
277
+ }
278
+ verdict = stricter(verdict, 'NO_SHIP');
279
+ }
280
+ for (const delta of deltas.filter((d) => d.locus !== 'storageLayout')) {
281
+ if (delta.impact === 'violation') {
282
+ diffItems.push({ status: 'fail', epistemic: delta.epistemicClass, label: delta.category, detail: delta.change });
283
+ verdict = stricter(verdict, 'NO_SHIP');
284
+ } else if (delta.impact === 'compatible') {
285
+ diffItems.push({ status: 'pass', epistemic: delta.epistemicClass, label: delta.category, detail: delta.change });
286
+ } else if (fast) {
287
+ diffItems.push({ status: 'review', epistemic: delta.epistemicClass, label: delta.category, detail: delta.change });
288
+ verdict = stricter(verdict, 'REVIEW');
289
+ } else if (!islFiles.length && highSurface.length) {
290
+ diffItems.push({ status: 'pass', epistemic: delta.epistemicClass, label: delta.category, detail: `${delta.change} (checked symbolically below)` });
291
+ } else {
292
+ diffItems.push({ status: 'pass', epistemic: delta.epistemicClass, label: delta.category, detail: delta.change });
293
+ }
294
+ }
295
+ if (diffItems.length) suites.push({ title: 'Upgrade Surface & Layout', items: diffItems });
296
+ if (fast) verdict = stricter(verdict, 'REVIEW');
297
+ }
298
+
299
+ // 2. Symbolic ISL Intent Firewall (when ISL specs are present and not --fast)
300
+ let intentResult = null;
301
+ if (!fast && islFiles.length > 0 && verdict !== 'NO_SHIP') {
302
+ const islSpin = createSpinner(
303
+ `Proving ${islFiles.length} ISL specification(s)${links.length ? ` across ${links.length + 1} linked contracts` : ''}…`,
304
+ { opt },
305
+ );
306
+ const islSpecs = islFiles.map((f) => ({ name: path.basename(f), source: fs.readFileSync(f, 'utf8') }));
307
+ intentResult = await verifyIntentFirewall({
308
+ dir: buildRoot,
309
+ candidate,
310
+ baseline,
311
+ candidateArtifact,
312
+ baseArtifact,
313
+ islSpecs,
314
+ links,
315
+ });
316
+ if (intentResult.decision === 'NO_SHIP') islSpin.fail('Counterexample found in ISL verification');
317
+ else if (intentResult.decision === 'REVIEW') islSpin.warn('ISL verification completed (bounded / review)');
318
+ else islSpin.succeed('All ISL claims proven');
319
+
320
+ verdict = stricter(verdict, intentResult.decision);
321
+ suites.push({
322
+ title: 'Symbolic Intent & Exit-Liveness Proofs',
323
+ items: intentResult.claims.map((c) => {
324
+ const decoded = diagnosticTools && c.counterexample
325
+ ? diagnosticTools.decodeCounterexample(c.counterexample, { claimId: c.id, candidateArtifact, baseArtifact })
326
+ : null;
327
+ return {
328
+ status: c.outcome === 'satisfied' ? 'pass' : c.outcome === 'violated' ? 'fail' : 'review',
329
+ epistemic: c.epistemicClass,
330
+ label: c.id,
331
+ detail: c.detail,
332
+ ...(diagnosticTools ? { witness: c.counterexample || null, decodedCall: decoded?.formattedCall || null, decoded } : {}),
333
+ };
334
+ }),
335
+ });
336
+ } else if (!fast && islFiles.length === 0 && baseline && verdict !== 'NO_SHIP') {
337
+ // 3. Differential Symbolic Upgrade Engine (when no ISL file is present)
338
+ const engSpin = createSpinner(`Running differential symbolic engine (${baseline} -> ${candidate})…`, { opt });
339
+ const engineReport = await verifyUpgrade({ dir: buildRoot, artifact: candidateArtifact, baseArtifact });
340
+ const engDecision = engineReport.verdict === 'UNVERIFIED' ? 'REVIEW' : engineReport.verdict;
341
+ if (engDecision === 'NO_SHIP') engSpin.fail('Violation found by symbolic upgrade engine');
342
+ else if (engDecision === 'REVIEW') engSpin.warn('Differential properties checked (deployment obligations open)');
343
+ else engSpin.succeed('Differential upgrade verification passed');
344
+
345
+ verdict = stricter(verdict, engDecision);
346
+ suites.push({
347
+ title: 'Differential Upgrade Properties',
348
+ items: (engineReport.properties || []).map((p) => {
349
+ const matchingFinding = (engineReport.findings || []).find((f) => f.category === p.name || f.rule === p.name);
350
+ return {
351
+ status: ['proven', 'accepted'].includes(p.status)
352
+ ? 'pass'
353
+ : p.status === 'bounded'
354
+ ? 'pass'
355
+ : p.status === 'violated'
356
+ ? 'fail'
357
+ : 'review',
358
+ epistemic: p.status === 'bounded' ? 'BOUNDED' : p.status === 'proven' ? 'PROVEN' : 'UNKNOWN',
359
+ label: p.name,
360
+ detail: matchingFinding ? matchingFinding.detail : `status: ${p.status}`,
361
+ ...(diagnosticTools ? { witness: matchingFinding?.witness && Object.keys(matchingFinding.witness).length
362
+ ? JSON.stringify(matchingFinding.witness)
363
+ : null } : {}),
364
+ };
365
+ }),
366
+ });
367
+ } else if (fast && !baseline) {
368
+ verdict = 'REVIEW';
369
+ suites.push({
370
+ title: 'Static Artifact Check',
371
+ items: [{ status: 'review', epistemic: 'PROVEN', label: candidate, detail: 'Compiled cleanly; pass a baseline or drop --fast to run symbolic proofs.' }],
372
+ });
373
+ }
374
+
375
+ const allItems = suites.flatMap((st) => st.items);
376
+ const failedItems = allItems.filter((i) => i.status === 'fail');
377
+
378
+ let reproFile = null;
379
+ if (diagnosticTools && opt.repro && failedItems.length > 0) {
380
+ reproFile = diagnosticTools.writeFoundryRepro({
381
+ root: projectRoot,
382
+ candidate,
383
+ baseline,
384
+ candidateArtifact,
385
+ baseArtifact,
386
+ failedItems,
387
+ });
388
+ }
389
+
390
+ // Strip internal `decoded` helper object from external JSON items while keeping `decodedCall`
391
+ for (const item of allItems) {
392
+ if ('decoded' in item) delete item.decoded;
393
+ }
394
+
395
+ const summary = {
396
+ passed: allItems.filter((i) => i.status === 'pass' && i.epistemic !== 'BOUNDED').length,
397
+ bounded: allItems.filter((i) => i.status === 'pass' && i.epistemic === 'BOUNDED').length,
398
+ review: allItems.filter((i) => i.status === 'review').length,
399
+ failed: failedItems.length,
400
+ };
401
+
402
+ const next = [];
403
+ if (reproFile) {
404
+ next.push(`forge test --match-path ${reproFile} -vvvv`);
405
+ } else if (verdict === 'NO_SHIP' && failedItems.some((f) => f.witness)) {
406
+ next.push(`guardefi check ${candidate}${baseline ? ` ${baseline}` : ''} --repro`);
407
+ } else if (fast) {
408
+ next.push(`guardefi check ${candidate}${baseline ? ` ${baseline}` : ''}`);
409
+ } else if (!publicRelease && verdict === 'SHIP') {
410
+ next.push(`guardefi ship ${candidate}${baseline ? ` ${baseline}` : ''} --out ./guardefi-ship`);
411
+ } else if (!publicRelease && verdict === 'REVIEW' && !islFiles.length) {
412
+ next.push(`guardefi spec scaffold ${candidate}`);
413
+ }
414
+
415
+ const report = {
416
+ schema: 'guardefi.check.v1',
417
+ project: projectRoot,
418
+ candidate,
419
+ baseline: baseline || null,
420
+ mode: fast ? 'fast' : 'symbolic',
421
+ verdict,
422
+ islFiles,
423
+ links: intentResult?.links || links.map((l) => ({ field: l.field, contract: l.contract, closed: null })),
424
+ ...(diagnosticTools ? { reproFile } : {}),
425
+ summary,
426
+ suites,
427
+ next,
428
+ elapsedMs: Date.now() - started,
429
+ };
430
+
431
+ return { report, exitCode: exitCode(verdict) };
432
+ } finally {
433
+ hhWorkspace?.cleanup();
434
+ }
435
+ }
436
+
437
+ module.exports = {
438
+ runCheck,
439
+ inferContractTargets,
440
+ discoverIslFiles,
441
+ discoverContractsInSources,
442
+ findArtifactPath,
443
+ loadBuiltArtifact,
444
+ ensureBuilt,
445
+ walkFiles,
446
+ };
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { isName } = require('../core/tools');
6
+
7
+ function isProjectRoot(dir) {
8
+ try {
9
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return false;
10
+ const names = fs.readdirSync(dir);
11
+ return (
12
+ names.includes('foundry.toml') ||
13
+ names.includes('guardefi.project.json') ||
14
+ names.includes('src') ||
15
+ names.includes('contracts') ||
16
+ names.some((n) => /^hardhat\.config\.[cm]?[jt]s$/.test(n))
17
+ );
18
+ } catch {
19
+ return false;
20
+ }
21
+ }
22
+
23
+ function looksLikeBareContractName(token, cwd) {
24
+ if (typeof token !== 'string' || !isName(token)) return false;
25
+ if (token === '.' || token === '..' || token.includes('/') || token.includes('\\')) return false;
26
+ return !fs.existsSync(path.resolve(cwd, token));
27
+ }
28
+
29
+ /**
30
+ * Allows developers already inside a Foundry/Hardhat directory to omit `.`:
31
+ * `guardefi verify VaultV2 VaultV1` -> `['.', 'VaultV2', 'VaultV1']`
32
+ * `guardefi diff VaultV1 VaultV2` -> `['.', 'VaultV1', 'VaultV2']`
33
+ * `guardefi storage VaultV1 VaultV2` -> `['.', 'VaultV1', 'VaultV2']`
34
+ * `guardefi ship VaultV2 VaultV1` -> `['.', 'VaultV2', 'VaultV1']`
35
+ * `guardefi watch VaultV2 VaultV1` -> `['.', 'VaultV2', 'VaultV1']`
36
+ * `guardefi spec scaffold VaultV2` -> `['scaffold', '.', 'VaultV2']`
37
+ */
38
+ function normalizeProjectPos(cmd, pos, cwd = process.cwd()) {
39
+ if (!Array.isArray(pos) || !isProjectRoot(cwd)) return pos;
40
+ if (['verify', 'release', 'ship', 'check', 'watch', 'storage'].includes(cmd)) {
41
+ if ((pos.length === 1 || pos.length === 2) && looksLikeBareContractName(pos[0], cwd)) {
42
+ return ['.', ...pos];
43
+ }
44
+ }
45
+ if (cmd === 'diff') {
46
+ if (pos.length === 2 && looksLikeBareContractName(pos[0], cwd) && isName(pos[1])) {
47
+ return ['.', ...pos];
48
+ }
49
+ }
50
+ if (cmd === 'spec' && pos[0] === 'scaffold' && pos.length === 2 && looksLikeBareContractName(pos[1], cwd)) {
51
+ return ['scaffold', '.', pos[1]];
52
+ }
53
+ return pos;
54
+ }
55
+
56
+ module.exports = { isProjectRoot, normalizeProjectPos };