@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,617 @@
1
+ 'use strict';
2
+
3
+ // Foundry / Hardhat-inspired zero-dependency terminal UI for GuardeFi CLI.
4
+ // Preserves 100% pure JSON on non-TTY pipes and `--json` while rendering
5
+ // scannable, color-aware human output on interactive terminals or `--pretty`.
6
+
7
+ const path = require('node:path');
8
+
9
+ const ASCII_LOGO_LINES = Object.freeze([
10
+ ' :::===== ::: === :::==== :::==== :::==== :::===== :::===== :::',
11
+ ' ::: ::: === ::: === ::: === ::: === ::: ::: :::',
12
+ ' === ===== === === ======== ======= === === ====== ====== ===',
13
+ ' === === === === === === === === === === === === ===',
14
+ ' ======= ====== === === === === ======= ======== === ===',
15
+ ]);
16
+
17
+ function isPrettyMode(opt = {}, env = process.env, stdout = process.stdout) {
18
+ const fmt = Array.isArray(opt.format) ? opt.format.at(-1) : opt.format;
19
+ if (opt.json || fmt === 'sarif') return false;
20
+ if (opt.pretty || env.GUARDEFI_PRETTY === '1') return true;
21
+ if (env.GUARDEFI_PRETTY === '0') return false;
22
+ return Boolean(stdout && stdout.isTTY);
23
+ }
24
+
25
+ function useColor(opt = {}, env = process.env, stream = process.stdout) {
26
+ if (opt['no-color'] || env.NO_COLOR !== undefined || env.TERM === 'dumb') return false;
27
+ if (env.FORCE_COLOR !== undefined && env.FORCE_COLOR !== '0') return true;
28
+ return Boolean((stream && stream.isTTY) || opt.pretty || env.GUARDEFI_PRETTY === '1');
29
+ }
30
+
31
+ function createStyler(enabled) {
32
+ const wrap = (open, close = '\x1b[0m') => (text) => (enabled ? `${open}${text}${close}` : String(text));
33
+ return {
34
+ enabled,
35
+ bold: wrap('\x1b[1m'),
36
+ dim: wrap('\x1b[2m'),
37
+ italic: wrap('\x1b[3m'),
38
+ green: wrap('\x1b[32m'),
39
+ brightGreen: wrap('\x1b[1;32m'),
40
+ red: wrap('\x1b[31m'),
41
+ brightRed: wrap('\x1b[1;31m'),
42
+ yellow: wrap('\x1b[33m'),
43
+ brightYellow: wrap('\x1b[1;33m'),
44
+ cyan: wrap('\x1b[36m'),
45
+ brightCyan: wrap('\x1b[1;36m'),
46
+ blue: wrap('\x1b[34m'),
47
+ gray: wrap('\x1b[90m'),
48
+ badgeShip: (t = 'SHIP') => (enabled ? `\x1b[1;30;42m ${t} \x1b[0m` : `[${t}]`),
49
+ badgeReview: (t = 'REVIEW') => (enabled ? `\x1b[1;30;43m ${t} \x1b[0m` : `[${t}]`),
50
+ badgeNoShip: (t = 'NO_SHIP') => (enabled ? `\x1b[1;37;41m ${t} \x1b[0m` : `[${t}]`),
51
+ badgePass: (t = 'PASS') => (enabled ? `\x1b[32m[${t}]\x1b[0m` : `[${t}]`),
52
+ badgeBounded: (t = 'BOUNDED') => (enabled ? `\x1b[36m[${t}]\x1b[0m` : `[${t}]`),
53
+ badgeWarn: (t = 'REVIEW') => (enabled ? `\x1b[33m[${t}]\x1b[0m` : `[${t}]`),
54
+ badgeFail: (t = 'FAIL') => (enabled ? `\x1b[1;31m[${t}]\x1b[0m` : `[${t}]`),
55
+ };
56
+ }
57
+
58
+ function verdictBadge(s, verdict) {
59
+ if (verdict === 'SHIP' || verdict === 'VALID' || verdict === 'PASS') return s.badgeShip(verdict);
60
+ if (verdict === 'NO_SHIP' || verdict === 'INVALID' || verdict === 'FAIL') return s.badgeNoShip(verdict);
61
+ return s.badgeReview(verdict || 'REVIEW');
62
+ }
63
+
64
+ function renderBanner({ opt = {}, env = process.env, stream = process.stdout, tagline = null } = {}) {
65
+ if (opt.quiet) return '';
66
+ const colorOn = useColor(opt, env, stream);
67
+ const s = createStyler(colorOn);
68
+ const styledLogo = ASCII_LOGO_LINES.map((line) => {
69
+ if (!colorOn) return line;
70
+ return line
71
+ .replace(/:+/g, (m) => `\x1b[1;36m${m}\x1b[0m`)
72
+ .replace(/=+/g, (m) => `\x1b[36m${m}\x1b[0m`);
73
+ });
74
+ if (tagline) {
75
+ styledLogo.push(` ${s.gray(tagline)}`);
76
+ }
77
+ return styledLogo.join('\n');
78
+ }
79
+
80
+ function formatMs(ms) {
81
+ if (typeof ms !== 'number' || !Number.isFinite(ms)) return '';
82
+ return ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${Math.round(ms)}ms`;
83
+ }
84
+
85
+ function shortHash(h, keep = 10) {
86
+ if (typeof h !== 'string') return '';
87
+ if (h.startsWith('0x') && h.length > keep * 2 + 4) return `${h.slice(0, keep + 2)}…${h.slice(-6)}`;
88
+ if (h.length > keep * 2 + 2) return `${h.slice(0, keep)}…${h.slice(-6)}`;
89
+ return h;
90
+ }
91
+
92
+ function relPath(p, cwd = process.cwd()) {
93
+ if (!p || typeof p !== 'string') return '';
94
+ const rel = path.relative(cwd, p);
95
+ if (!rel) return '.';
96
+ return rel.startsWith('..') ? p : `./${rel}`;
97
+ }
98
+
99
+ function createSpinner(message, { opt = {}, env = process.env, stream = process.stderr } = {}) {
100
+ const active = Boolean(stream && stream.isTTY && !opt.json && !opt.quiet && env.TERM !== 'dumb');
101
+ const s = createStyler(useColor(opt, env, stream));
102
+ const started = Date.now();
103
+ if (!active) {
104
+ return {
105
+ update() {},
106
+ succeed() {},
107
+ warn() {},
108
+ fail() {},
109
+ stop() {},
110
+ };
111
+ }
112
+ const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
113
+ let idx = 0;
114
+ let text = message;
115
+ const draw = () => {
116
+ stream.write(`\r\x1b[K${s.cyan(frames[idx % frames.length])} ${text}`);
117
+ idx += 1;
118
+ };
119
+ draw();
120
+ const timer = setInterval(draw, 80);
121
+ if (typeof timer.unref === 'function') timer.unref();
122
+ const clear = () => {
123
+ clearInterval(timer);
124
+ stream.write('\r\x1b[K');
125
+ };
126
+ return {
127
+ update(nextText) { text = nextText; },
128
+ succeed(doneText) {
129
+ clear();
130
+ stream.write(`${s.green('✓')} ${doneText || text} ${s.gray(`(${formatMs(Date.now() - started)})`)}\n`);
131
+ },
132
+ warn(doneText) {
133
+ clear();
134
+ stream.write(`${s.yellow('!')} ${doneText || text} ${s.gray(`(${formatMs(Date.now() - started)})`)}\n`);
135
+ },
136
+ fail(doneText) {
137
+ clear();
138
+ stream.write(`${s.red('✗')} ${doneText || text} ${s.gray(`(${formatMs(Date.now() - started)})`)}\n`);
139
+ },
140
+ stop() { clear(); },
141
+ };
142
+ }
143
+
144
+ // Levenshtein edit distance for "did you mean ...?" hints
145
+ function editDistance(a, b) {
146
+ const s = String(a).toLowerCase();
147
+ const t = String(b).toLowerCase();
148
+ const m = s.length;
149
+ const n = t.length;
150
+ const dp = Array.from({ length: m + 1 }, (_, i) => i);
151
+ for (let j = 1; j <= n; j++) {
152
+ let prev = dp[0];
153
+ dp[0] = j;
154
+ for (let i = 1; i <= m; i++) {
155
+ const tmp = dp[i];
156
+ dp[i] = s[i - 1] === t[j - 1] ? prev : 1 + Math.min(prev, dp[i], dp[i - 1]);
157
+ prev = tmp;
158
+ }
159
+ }
160
+ return dp[m];
161
+ }
162
+
163
+ function suggestClosest(input, candidates, maxDist = 3) {
164
+ if (!input || !Array.isArray(candidates) || !candidates.length) return null;
165
+ let best = null;
166
+ let bestScore = Infinity;
167
+ for (const c of candidates) {
168
+ if (String(c).startsWith(String(input)) && c !== input) return c;
169
+ const d = editDistance(input, c);
170
+ if (d < bestScore) {
171
+ bestScore = d;
172
+ best = c;
173
+ }
174
+ }
175
+ const limit = Math.min(maxDist, Math.max(1, Math.floor(String(input).length / 2) + 1));
176
+ return bestScore <= limit ? best : null;
177
+ }
178
+
179
+ function formatHumanError(message, { cmd = null, hint = null, opt = {}, env = process.env, stream = process.stderr } = {}) {
180
+ const s = createStyler(useColor(opt, env, stream));
181
+ const lines = [`${s.brightRed('error:')} ${message}`];
182
+ if (hint) lines.push(` ${s.cyan('hint:')} ${hint}`);
183
+ const helpCmd = cmd ? `guardefi ${cmd} --help` : 'guardefi --help';
184
+ lines.push(` ${s.gray('help:')} ${helpCmd}`);
185
+ return lines.join('\n');
186
+ }
187
+
188
+ function renderDoctor(report, s) {
189
+ const lines = [];
190
+ const statusBadge = report.ok ? s.badgeShip('READY') : s.badgeNoShip('BLOCKERS');
191
+ lines.push(`${s.bold('GuardeFi Doctor')} ${statusBadge} ${s.gray(relPath(report.project))}`);
192
+ lines.push('');
193
+
194
+ if (report.toolchain) {
195
+ lines.push(s.bold('Toolchain'));
196
+ for (const [tool, ver] of Object.entries(report.toolchain)) {
197
+ const mark = ver ? s.green('✓') : (['forge', 'cast', 'halmos'].includes(tool) ? s.red('✗') : s.yellow('○'));
198
+ lines.push(` ${mark} ${tool.padEnd(8)} ${ver ? s.gray(ver) : s.yellow('not installed')}`);
199
+ }
200
+ lines.push('');
201
+ }
202
+
203
+ if (report.applied?.length) {
204
+ lines.push(`${s.green('✓')} Auto-created: ${report.applied.map((f) => s.cyan(f)).join(', ')}`);
205
+ lines.push('');
206
+ }
207
+
208
+ if (report.blockers?.length) {
209
+ lines.push(`${s.brightRed(`Blockers (${report.blockers.length})`)}`);
210
+ for (const b of report.blockers) {
211
+ lines.push(` ${s.red('✗')} ${s.bold(b.id)}: ${b.message}`);
212
+ if (b.fix) {
213
+ for (const fl of String(b.fix).split('\n')) {
214
+ lines.push(` ${s.cyan('fix:')} ${fl}`);
215
+ }
216
+ }
217
+ }
218
+ lines.push('');
219
+ } else {
220
+ lines.push(`${s.green('✓')} Zero blockers (${report.checked?.length || 0} checks passed)`);
221
+ lines.push('');
222
+ }
223
+
224
+ if (report.warnings?.length) {
225
+ lines.push(`${s.yellow(`Warnings (${report.warnings.length})`)}`);
226
+ for (const w of report.warnings) {
227
+ lines.push(` ${s.yellow('!')} ${s.bold(w.id)}: ${w.message}`);
228
+ if (w.fix) lines.push(` ${s.gray('tip:')} ${w.fix}`);
229
+ }
230
+ lines.push('');
231
+ }
232
+
233
+ if (report.next?.length) {
234
+ lines.push(s.bold('Next'));
235
+ for (const n of report.next) lines.push(` ${s.cyan('$')} ${n}`);
236
+ }
237
+ return lines.join('\n');
238
+ }
239
+
240
+ function renderDiscover(report, s) {
241
+ const lines = [`${s.bold('GuardeFi Project Discovery')}`];
242
+ if (!report.projects?.length) {
243
+ lines.push(` ${s.yellow('!')} No Solidity, Foundry, or Hardhat projects found.`);
244
+ lines.push(` ${s.cyan('$')} guardefi new my-vault`);
245
+ return lines.join('\n');
246
+ }
247
+ for (const p of report.projects) {
248
+ lines.push('');
249
+ lines.push(` ${s.green('●')} ${s.bold(p.path)} ${s.gray(`[${(p.frameworks || []).join(', ')}]`)}`);
250
+ lines.push(` sources: ${p.sources?.length || 0} tests: ${p.tests?.length || 0} specs: ${p.specifications?.length || 0}`);
251
+ for (const src of (p.sources || []).slice(0, 8)) lines.push(` ${s.cyan(src)}`);
252
+ if ((p.sources || []).length > 8) lines.push(` ${s.gray(`… +${p.sources.length - 8} more`)}`);
253
+ for (const sp of p.specifications || []) lines.push(` ${s.green('spec:')} ${sp}`);
254
+ }
255
+ lines.push('', s.bold('Next'), ` ${s.cyan('$')} guardefi check`);
256
+ return lines.join('\n');
257
+ }
258
+
259
+ function renderInit(report, s) {
260
+ if (report.schema === 'guardefi.new-project.v1') {
261
+ const dirRel = relPath(report.directory);
262
+ const lines = [
263
+ `${s.green('✓')} ${s.bold(`Created GuardeFi starter project (${report.template || 'vault'})`)} in ${s.cyan(dirRel)}`,
264
+ '',
265
+ s.bold('Scaffolded files'),
266
+ ...report.files.map((f) => ` ${s.green('+')} ${f}`),
267
+ '',
268
+ s.bold('Try it right now (takes ~5 seconds)'),
269
+ ];
270
+ if (dirRel !== '.') lines.push(` ${s.cyan('$')} cd ${dirRel}`);
271
+ if (report.tryCommands?.length) {
272
+ for (const [cmd, note] of report.tryCommands) {
273
+ lines.push(` ${s.cyan('$')} ${cmd.padEnd(48)} ${s.gray(`# ${note}`)}`);
274
+ }
275
+ } else {
276
+ lines.push(
277
+ ` ${s.cyan('$')} guardefi check VaultV2 VaultV1 ${s.gray('# proves safe upgrade -> PASS')}`,
278
+ ` ${s.cyan('$')} guardefi check VaultV2Backdoor VaultV1 ${s.gray('# catches cap & freeze bugs -> NO_SHIP')}`,
279
+ );
280
+ }
281
+ return lines.join('\n');
282
+ }
283
+ const lines = [
284
+ `${s.green('✓')} ${s.bold('Initialized GuardeFi project')} (${s.cyan(report.file || 'guardefi.project.json')})`,
285
+ '',
286
+ s.bold('Next'),
287
+ ` ${s.cyan('$')} guardefi doctor`,
288
+ ` ${s.cyan('$')} guardefi check`,
289
+ ];
290
+ return lines.join('\n');
291
+ }
292
+
293
+ function renderCheck(report, s) {
294
+ const lines = [];
295
+ const pairLabel = report.baseline ? `${report.baseline} -> ${report.candidate}` : report.candidate;
296
+ lines.push(
297
+ `${s.bold('GuardeFi Check')} ${verdictBadge(s, report.verdict)} ${s.bold(pairLabel)} ${s.gray(formatMs(report.elapsedMs))}`,
298
+ );
299
+ if (report.links?.length) {
300
+ lines.push(
301
+ ` ${s.gray('Linked contracts:')} ${report.links.map((l) => `${s.cyan(l.field)}=${s.bold(l.contract)}${l.closed ? s.green(' ✓') : s.yellow(' (open)')}`).join(', ')}`,
302
+ );
303
+ }
304
+ if (report.islFiles?.length) {
305
+ lines.push(` ${s.gray('ISL policies:')} ${report.islFiles.map((f) => s.cyan(relPath(f))).join(', ')}`);
306
+ }
307
+ lines.push('');
308
+
309
+ if (report.suites?.length) {
310
+ for (const suite of report.suites) {
311
+ lines.push(`${s.bold(suite.title)}`);
312
+ for (const item of suite.items) {
313
+ const tag = item.status === 'pass'
314
+ ? (item.epistemic === 'BOUNDED' ? s.badgeBounded('BOUNDED') : s.badgePass('PASS'))
315
+ : item.status === 'fail'
316
+ ? s.badgeFail('FAIL')
317
+ : s.badgeWarn('REVIEW');
318
+ lines.push(` ${tag} ${s.bold(item.label)}${item.detail ? ` — ${item.detail}` : ''}`);
319
+ if (item.decodedCall) {
320
+ lines.push(` ${s.brightYellow('exploit call:')} ${s.bold(item.decodedCall)}`);
321
+ } else if (item.witness) {
322
+ lines.push(` ${s.yellow('counterexample:')} ${item.witness}`);
323
+ }
324
+ }
325
+ lines.push('');
326
+ }
327
+ }
328
+
329
+ if (report.reproFile) {
330
+ lines.push(
331
+ `${s.green('✓')} Wrote runnable Foundry PoC test: ${s.cyan(relPath(path.join(report.project, report.reproFile)))}`,
332
+ '',
333
+ );
334
+ }
335
+
336
+ lines.push(s.bold('Summary'));
337
+ lines.push(
338
+ ` Passed: ${s.green(String(report.summary.passed))} Bounded: ${s.cyan(String(report.summary.bounded))} Review: ${s.yellow(String(report.summary.review))} Failed: ${report.summary.failed ? s.brightRed(String(report.summary.failed)) : '0'}`,
339
+ );
340
+ if (report.next?.length) {
341
+ lines.push('', s.bold('Next'));
342
+ for (const cmd of report.next) lines.push(` ${s.cyan('$')} ${cmd}`);
343
+ }
344
+ return lines.join('\n');
345
+ }
346
+
347
+ function renderDiff(report, s) {
348
+ const d = report.diff || {};
349
+ const lines = [
350
+ `${s.bold('GuardeFi Behavioral Diff')} ${verdictBadge(s, report.decision)} ${s.bold(`${d.baseline} -> ${d.candidate}`)}`,
351
+ '',
352
+ ];
353
+ const deltas = d.classifiedDeltas || d.deltas || [];
354
+ if (!deltas.length) {
355
+ lines.push(` ${s.green('✓')} No surface, storage, or privilege deltas detected.`);
356
+ } else {
357
+ lines.push(`${s.bold(`Detected Changes (${deltas.length})`)}`);
358
+ for (const item of deltas) {
359
+ const sev = String(item.severity || 'info').toUpperCase();
360
+ const sevStyled = sev === 'CRITICAL' || sev === 'HIGH'
361
+ ? s.brightRed(sev.padEnd(8))
362
+ : sev === 'MEDIUM'
363
+ ? s.yellow(sev.padEnd(8))
364
+ : s.gray(sev.padEnd(8));
365
+ lines.push(` ${sevStyled} ${s.gray(`[${item.epistemicClass}]`)} ${item.change}`);
366
+ }
367
+ }
368
+ lines.push('', s.gray(report.scope || 'Behavioral comparison only. Run `guardefi verify` or `guardefi ship` for release authorization.'));
369
+ return lines.join('\n');
370
+ }
371
+
372
+ function renderRelease(report, s) {
373
+ const pair = report.baseline
374
+ ? `${report.baseline.name} (${shortHash(report.baseline.bytecodeHash, 6)}) -> ${report.candidate.name} (${shortHash(report.candidate.bytecodeHash, 6)})`
375
+ : `${report.candidate.name} (${shortHash(report.candidate.bytecodeHash, 6)})`;
376
+ const lines = [
377
+ `${s.bold('GuardeFi Release Verification')} ${verdictBadge(s, report.verdict)} ${s.gray(formatMs(report.elapsedMs))}`,
378
+ ` ${s.gray('Subject:')} ${s.bold(pair)}`,
379
+ ` ${s.gray('Gates:')} policy=${s.bold(report.policyVerdict)} · engine=${s.bold(report.engineGate?.decision || report.verdict)} · openObligations=${report.openObligations ?? 0}`,
380
+ '',
381
+ ];
382
+
383
+ const guarantees = report.decision?.guarantees || [];
384
+ if (guarantees.length) {
385
+ lines.push(s.bold('Policy Guarantees'));
386
+ for (const g of guarantees) {
387
+ const badge = g.status === 'pass' ? s.badgePass('PASS') : g.status === 'fail' ? s.badgeFail('FAIL') : s.badgeWarn('OPEN');
388
+ const kind = g.mandatory ? '' : s.gray(' (advisory)');
389
+ lines.push(` ${badge} ${s.bold(g.id)}${kind}${g.reason ? ` — ${g.reason}` : ''}`);
390
+ }
391
+ lines.push('');
392
+ }
393
+
394
+ if (report.reasons?.length) {
395
+ lines.push(s.bold('Findings & Notes'));
396
+ for (const r of report.reasons.slice(0, 10)) lines.push(` ${s.yellow('•')} ${r}`);
397
+ if (report.reasons.length > 10) lines.push(` ${s.gray(`… +${report.reasons.length - 10} more (pass --json for full packet)`)}`);
398
+ lines.push('');
399
+ }
400
+
401
+ if (report.receipt?.file) {
402
+ lines.push(
403
+ `${s.green('✓')} Receipt written to ${s.cyan(relPath(report.receipt.file))} ${s.gray(`(digest ${shortHash(report.receipt.digest, 8)}, ${report.receipt.signed ? 'signed' : 'unsigned'})`)}`,
404
+ );
405
+ }
406
+ return lines.join('\n');
407
+ }
408
+
409
+ function renderShip(report, s) {
410
+ const lines = [
411
+ `${s.bold('GuardeFi Ship Packet')} ${verdictBadge(s, report.verdict)}`,
412
+ ` ${s.gray('Packet directory:')} ${s.cyan(relPath(report.out))}`,
413
+ '',
414
+ s.bold('Pipeline Steps'),
415
+ ];
416
+ for (const st of report.steps || []) {
417
+ const ok = st.exitCode === 0 || st.status === 'SAFE_PREFLIGHT_OK';
418
+ const warn = st.exitCode === 3 || st.status === 'SAFE_PREFLIGHT_REVIEW';
419
+ const mark = ok ? s.green('✓') : warn ? s.yellow('!') : s.red('✗');
420
+ const extra = st.error ? ` — ${s.red(st.error)}` : st.status ? ` (${st.status})` : '';
421
+ lines.push(` ${mark} ${st.name}${extra}`);
422
+ }
423
+ lines.push('', s.bold('Generated Artifacts'));
424
+ for (const f of report.files || []) {
425
+ const highlight = f === 'SHIP-PACKET.md' || f === 'SafeTransactionBuilder.json' ? s.cyan(f) : f;
426
+ lines.push(` • ${highlight}`);
427
+ }
428
+ lines.push('', ` Read ${s.cyan(relPath(path.join(report.out, 'SHIP-PACKET.md')))} before signing.`);
429
+ return lines.join('\n');
430
+ }
431
+
432
+ function renderCertificate(report, s) {
433
+ const badge = report.status === 'VALID' ? s.badgeShip('VALID') : report.status === 'INVALID' ? s.badgeNoShip('INVALID') : s.badgeReview(report.status);
434
+ const lines = [
435
+ `${s.bold('GuardeFi Certificate Check')} ${badge} verdict=${verdictBadge(s, report.verdict)}`,
436
+ ` ${s.gray('Digest:')} ${report.digest || 'n/a'}`,
437
+ ` ${s.gray('Authorized:')} ${report.executionAuthorized ? s.green('yes') : s.yellow('no')}`,
438
+ ];
439
+ if (report.checked?.length) lines.push(` ${s.gray('Verified:')} ${report.checked.join(', ')}`);
440
+ const problems = report.problems || report.errors || [];
441
+ if (problems.length) {
442
+ lines.push('', s.brightRed('Problems'));
443
+ for (const e of problems) lines.push(` ${s.red('✗')} ${e}`);
444
+ }
445
+ return lines.join('\n');
446
+ }
447
+
448
+ function renderKeygen(report, s) {
449
+ return [
450
+ `${s.green('✓')} ${s.bold('Generated Ed25519 signing keypair')}`,
451
+ ` ${s.gray('Key ID:')} ${s.bold(report.keyId)}`,
452
+ ` ${s.gray('Private key:')} ${s.cyan(relPath(report.privateKey))} ${s.gray('(mode 0600 — keep secret)')}`,
453
+ ` ${s.gray('Public key:')} ${report.publicKey}`,
454
+ ].join('\n');
455
+ }
456
+
457
+ function renderSpecScaffold(report, s) {
458
+ const [writtenSpec, writtenHarness] = report.written || [];
459
+ const lines = [
460
+ `${s.green('✓')} ${s.bold('Scaffolded draft specification & Halmos harness')} ${s.badgeReview('DRAFT')}`,
461
+ ` ${s.gray('Spec:')} ${s.cyan(relPath(report.specFile || report.spec || writtenSpec || ''))}`,
462
+ ` ${s.gray('Harness:')} ${s.cyan(relPath(report.harnessFile || report.harness || writtenHarness || ''))}`,
463
+ '',
464
+ ` ${s.yellow('Note:')} Draft specs carry \`authorized: false\` until you review TODOs and remove draft markers.`,
465
+ ];
466
+ if (report.next?.length) {
467
+ lines.push('', s.bold('Next'));
468
+ for (const cmd of report.next) lines.push(` ${s.cyan('$')} ${cmd}`);
469
+ }
470
+ return lines.join('\n');
471
+ }
472
+
473
+ function slotBar(s, usedBytes) {
474
+ const width = 16;
475
+ const filled = Math.min(width, Math.max(usedBytes > 0 ? 1 : 0, Math.round((usedBytes / 32) * width)));
476
+ const bar = '█'.repeat(filled) + '░'.repeat(width - filled);
477
+ return `${usedBytes === 32 ? s.cyan(bar) : s.green(bar)} ${String(usedBytes).padStart(2)}/32B`;
478
+ }
479
+
480
+ function renderStorage(report, s) {
481
+ if (report.mode === 'inspect') {
482
+ const lay = report.layout;
483
+ const lines = [
484
+ `${s.bold('GuardeFi Storage Inspector')} ${s.bold(report.contract)} ${s.gray(`(${lay.totalSlots} slot(s), ${lay.totalVariables} variable(s), ${lay.packedSlots} packed)`)}`,
485
+ '',
486
+ ];
487
+ if (!lay.slots.length) {
488
+ lines.push(` ${s.gray('No plain storage slots declared.')}`);
489
+ } else {
490
+ for (const sl of lay.slots) {
491
+ const desc = sl.variables.map((v) => `${s.bold(v.label)}: ${s.cyan(v.typeLabel)}${v.offset ? s.gray(` (+${v.offset}B)`) : ''}`).join(' | ');
492
+ lines.push(` slot ${String(sl.slot).padStart(3)} [${slotBar(s, sl.usedBytes)}] ${desc}`);
493
+ }
494
+ }
495
+ if (report.erc7201?.length) {
496
+ lines.push('', s.bold('ERC-7201 Namespaces'));
497
+ for (const ns of report.erc7201) {
498
+ lines.push(` • ${s.cyan(ns.id)} (${ns.struct}) @ ${shortHash(ns.baseSlot, 8)}`);
499
+ }
500
+ }
501
+ return lines.join('\n');
502
+ }
503
+
504
+ const lines = [
505
+ `${s.bold('GuardeFi Storage Upgrade Diff')} ${verdictBadge(s, report.verdict)} ${s.bold(`${report.baseline} -> ${report.candidate}`)}`,
506
+ ` ${s.gray('Slots:')} ${report.baselineLayout.totalSlots} -> ${report.candidateLayout.totalSlots} · ${s.gray('Collisions:')} ${report.collisions.length ? s.brightRed(String(report.collisions.length)) : s.green('0')}`,
507
+ '',
508
+ ];
509
+ for (const d of report.deltas) {
510
+ const tag = d.status === 'COLLISION'
511
+ ? s.badgeFail('COLLISION')
512
+ : d.status === 'APPENDED' || d.status === 'PACKED_APPEND'
513
+ ? s.badgeBounded(d.status === 'PACKED_APPEND' ? 'PACKED+' : 'APPENDED')
514
+ : d.status === 'RENAMED'
515
+ ? s.badgeWarn('RENAMED')
516
+ : s.badgePass('KEEP');
517
+ lines.push(` ${tag} slot ${String(d.slot).padStart(2)}${d.offset ? `+${d.offset}B` : ' '} ${d.detail}`);
518
+ }
519
+ return lines.join('\n');
520
+ }
521
+
522
+ function renderAudit(report, s) {
523
+ const statusBadge = report.status === 'HIGH_RISK_SIGNALS'
524
+ ? s.badgeNoShip('HIGH RISK')
525
+ : report.status === 'SIGNALS_FOUND'
526
+ ? s.badgeReview('SIGNALS')
527
+ : s.badgeShip('CLEAN');
528
+ const lines = [
529
+ `${s.bold('GuardeFi Repo Security X-Ray')} ${statusBadge} ${s.gray(relPath(report.project))}`,
530
+ ` ${s.gray('Deployable contracts:')} ${report.contracts.length} · ${s.gray('Upgrade pairs:')} ${report.upgradePairs.length} · ${s.gray('Findings:')} ${report.findings.length}`,
531
+ '',
532
+ s.bold('Contract Surface & Storage'),
533
+ ];
534
+
535
+ for (const c of report.contracts) {
536
+ const guarded = c.mutators.filter((m) => m.guarded).length;
537
+ const caps = c.capabilities.length ? s.cyan(`[${c.capabilities.join(', ')}]`) : s.gray('[local]');
538
+ lines.push(
539
+ ` • ${s.bold(c.name.padEnd(22))} ${String(c.runtimeBytes).padStart(5)} B (${String(c.eip170Pct).padStart(4)}%) slots=${String(c.storage.totalSlots).padEnd(2)} mutators=${guarded}/${c.mutators.length} guarded ${caps}`,
540
+ );
541
+ }
542
+
543
+ if (report.upgradePairs.length) {
544
+ lines.push('', s.bold('Detected Upgrade Pairs'));
545
+ for (const p of report.upgradePairs) {
546
+ const badge = p.compatible ? s.badgePass('COMPATIBLE') : s.badgeFail('COLLISION');
547
+ const fixtureNote = p.adversarialFixture ? s.gray(' (adversarial fixture)') : '';
548
+ lines.push(` ${badge} ${s.bold(`${p.baseline} -> ${p.candidate}`)}${fixtureNote} — ${p.summary}`);
549
+ }
550
+ }
551
+
552
+ if (report.findings.length) {
553
+ lines.push('', s.bold('Findings & Signals'));
554
+ for (const f of report.findings) {
555
+ const sev = f.severity === 'high' ? s.badgeFail('HIGH') : f.severity === 'medium' ? s.badgeWarn('MED') : s.badgeBounded(f.severity.toUpperCase());
556
+ lines.push(` ${sev} ${s.bold(f.contract)}: ${f.message}`);
557
+ }
558
+ }
559
+
560
+ if (report.markdownFile) {
561
+ lines.push('', `${s.green('✓')} Wrote Markdown audit report: ${s.cyan(relPath(report.markdownFile))}`);
562
+ }
563
+ if (report.next?.length) {
564
+ lines.push('', s.bold('Next'));
565
+ for (const cmd of report.next) lines.push(` ${s.cyan('$')} ${cmd}`);
566
+ }
567
+ return lines.join('\n');
568
+ }
569
+
570
+ function renderCi(report, s) {
571
+ const label = report.kind === 'hook' ? 'Git pre-push guard hook' : 'GitHub Actions workflow';
572
+ return [
573
+ `${s.green('✓')} ${s.bold(`Installed GuardeFi ${label}`)}`,
574
+ ` ${s.gray('File:')} ${s.cyan(relPath(report.written))}`,
575
+ ].join('\n');
576
+ }
577
+
578
+ function renderHuman(cmd, report, { opt = {}, env = process.env, stream = process.stdout } = {}) {
579
+ const s = createStyler(useColor(opt, env, stream));
580
+ let body;
581
+ switch (cmd) {
582
+ case 'doctor': body = renderDoctor(report, s); break;
583
+ case 'discover': body = renderDiscover(report, s); break;
584
+ case 'init':
585
+ case 'new': body = renderInit(report, s); break;
586
+ case 'check': body = renderCheck(report, s); break;
587
+ case 'storage': body = renderStorage(report, s); break;
588
+ case 'audit': body = renderAudit(report, s); break;
589
+ case 'ci': body = renderCi(report, s); break;
590
+ case 'diff': body = renderDiff(report, s); break;
591
+ case 'release':
592
+ case 'verify': body = renderRelease(report, s); break;
593
+ case 'ship': body = renderShip(report, s); break;
594
+ case 'certificate': body = renderCertificate(report, s); break;
595
+ case 'keygen': body = renderKeygen(report, s); break;
596
+ case 'spec': body = renderSpecScaffold(report, s); break;
597
+ default: return JSON.stringify(report, null, 2);
598
+ }
599
+ const banner = renderBanner({ opt, env, stream });
600
+ return banner ? `${banner}\n\n${body}` : body;
601
+ }
602
+
603
+ module.exports = {
604
+ ASCII_LOGO_LINES,
605
+ isPrettyMode,
606
+ useColor,
607
+ createStyler,
608
+ createSpinner,
609
+ editDistance,
610
+ suggestClosest,
611
+ formatHumanError,
612
+ renderBanner,
613
+ renderHuman,
614
+ shortHash,
615
+ relPath,
616
+ formatMs,
617
+ };
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const { parseArgs } = require('node:util');
5
+ const { isPrettyMode, renderHuman } = require('./cli-ui');
6
+
7
+ const USAGE = `Usage: guardefi <command> [options]
8
+
9
+ check [projectDir] [Candidate] [Baseline] Verify upgrade properties and ISL invariants
10
+ storage [projectDir] <Contract> [CandidateContract] Inspect or compare storage layouts
11
+ --version Print the CLI version
12
+
13
+ check options: --isl FILE (repeatable), --link field=Contract (repeatable), --fast, --artifacts-only
14
+ Output options: --json, --pretty, --no-color, --quiet
15
+ Exit codes: 0 success, 1 check failed, 2 usage or runtime error, 3 review required`;
16
+
17
+ const OUTPUT_OPTIONS = {
18
+ json: { type: 'boolean' },
19
+ pretty: { type: 'boolean' },
20
+ 'no-color': { type: 'boolean' },
21
+ quiet: { type: 'boolean', short: 'q' },
22
+ };
23
+ const CHECK_OPTIONS = {
24
+ isl: { type: 'string', multiple: true },
25
+ link: { type: 'string', multiple: true },
26
+ fast: { type: 'boolean' },
27
+ 'artifacts-only': { type: 'boolean' },
28
+ };
29
+
30
+ async function main([command, ...args]) {
31
+ if (!command || ['help', '--help', '-h'].includes(command)) {
32
+ console.log(USAGE);
33
+ return 0;
34
+ }
35
+ if (args.length === 0 && ['version', '--version', '-V'].includes(command)) {
36
+ console.log(require('../package.json').version);
37
+ return 0;
38
+ }
39
+ if (command !== 'check' && command !== 'storage') throw new Error(`Unknown command: ${command}. Run guardefi --help.`);
40
+
41
+ const { values, positionals: pos } = parseArgs({
42
+ args,
43
+ allowPositionals: true,
44
+ options: {
45
+ ...OUTPUT_OPTIONS,
46
+ ...(command === 'check' ? CHECK_OPTIONS : {}),
47
+ help: { type: 'boolean', short: 'h' },
48
+ },
49
+ });
50
+ if (values.help) {
51
+ console.log(USAGE);
52
+ return 0;
53
+ }
54
+
55
+ const opt = Object.fromEntries(Object.entries(values).map(([name, value]) => [name, Array.isArray(value) ? value : [value]]));
56
+ const { report, exitCode } = command === 'check'
57
+ ? await require('./cli-check').runCheck({ pos, opt }, { publicRelease: true })
58
+ : await require('./cli-storage').runStorage({ pos, opt });
59
+ console.log(isPrettyMode(opt) ? renderHuman(command, report, { opt }) : JSON.stringify(report, null, 2));
60
+ return exitCode;
61
+ }
62
+
63
+ main(process.argv.slice(2)).then((code) => { process.exitCode = code; }).catch((error) => {
64
+ console.error(error.message);
65
+ process.exitCode = 2;
66
+ });