@sloppy-ai/cli 1.1.0 → 1.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/dist/index.js CHANGED
@@ -1,5 +1,9 @@
1
- import { auditCode, AUTO_FIX_RULE_TYPES, CANONICAL_RULES, RULE_METADATA, createRepairPlan, DESIGN_MD_TEMPLATE, detectProjectStack, evaluateCraftRubric, extractDesignDna, getComponentById, getNextMaterial, getPatternById, getSynthesizedArchetype, loadSloppyConfig, resolveDesignContract, LOOKS, MOTION_ECOSYSTEMS, PATTERNS_CATALOG, SLOPPY_COMPONENTS, SLOPPY_LIBRARIES, SYNTHESIZED_ARCHETYPES, transformSlopToCraft } from '@sloppy-ai/core';
2
- import { runServer } from '@sloppy-ai/mcp';
1
+ import { auditCode, AUTO_FIX_RULE_TYPES, CANONICAL_RULES, RULE_METADATA, createRepairPlan, DESIGN_MD_TEMPLATE, MOTION_SPEC_TEMPLATE, materialDesignMd, fingerprintLook, assessConvergence, dealLooks, detectProjectStack, evaluateCraftRubric, isSiteKind, policyFor, extractDesignDna, getComponentById, getLook, getNextMaterial, getPatternById, getSynthesizedArchetype, loadSloppyConfig, resolveDesignContract, toMaterial, resolveMaterial, LOOKS, MOTION_ECOSYSTEMS, PATTERNS_CATALOG, SLOPPY_COMPONENTS, SLOPPY_LIBRARIES, SYNTHESIZED_ARCHETYPES, transformSlopToCraft } from '@sloppy-ai/core';
2
+ import { runGate, installGate } from './gate.js';
3
+ import { BRIEF_FILE, describeBrief, runBrief } from './brief.js';
4
+ import { summarizeEvaluation } from './evaluate.js';
5
+ import { createFreshReviewPrompt } from './review.js';
6
+ import { summarize } from './gate-core.js';
3
7
  import { execFileSync, spawn } from 'child_process';
4
8
  import { createHash } from 'crypto';
5
9
  import * as fs from 'fs';
@@ -201,14 +205,30 @@ function checkFiles(paths, options) {
201
205
  let cacheDirty = false;
202
206
  const optSignature = JSON.stringify({ maxScore: options.maxScore, failOn: options.failOn, minGrade: options.minGrade, type: options.type, codeOnly: options.codeOnly, strict: options.strict, version });
203
207
  const files = paths.map(file => {
204
- const code = fs.readFileSync(file, 'utf8');
205
208
  const relative = path.relative(process.cwd(), file) || file;
206
209
  const ctx = resolveContext(file);
207
210
  let contentHash = '';
211
+ let stat = null;
212
+ if (cacheEnabled) {
213
+ const cached = scanCache[`check:${relative}`];
214
+ stat = fs.statSync(file);
215
+ if (cached &&
216
+ cached.mtimeMs === stat.mtimeMs &&
217
+ cached.size === stat.size &&
218
+ cached.optSig === optSignature &&
219
+ cached.ctxSig === ctx.signature &&
220
+ cached.entry &&
221
+ typeof cached.entry === 'object') {
222
+ return cached.entry;
223
+ }
224
+ }
225
+ const code = fs.readFileSync(file, 'utf8');
208
226
  if (cacheEnabled) {
209
227
  contentHash = createHash('sha256').update(optSignature).update(ctx.signature).update(code).digest('hex');
210
228
  const cached = scanCache[`check:${relative}`];
211
229
  if (cached && cached.hash === contentHash && cached.entry && typeof cached.entry === 'object') {
230
+ nextCache[`check:${relative}`] = { ...cached, mtimeMs: stat?.mtimeMs, size: stat?.size, optSig: optSignature, ctxSig: ctx.signature };
231
+ cacheDirty = true;
212
232
  return cached.entry;
213
233
  }
214
234
  }
@@ -220,7 +240,9 @@ function checkFiles(paths, options) {
220
240
  config: ctx.config ?? undefined,
221
241
  designContract: ctx.designContract
222
242
  });
223
- const rubric = evaluateCraftRubric(code, { filepath: relative, componentType: options.type, strict: options.strict, audit });
243
+ const grade = options.skipRubric
244
+ ? 'B'
245
+ : evaluateCraftRubric(code, { filepath: relative, componentType: options.type, strict: options.strict, audit }).grade;
224
246
  const violations = audit.violations.map(v => ({
225
247
  id: v.id,
226
248
  type: v.type,
@@ -234,9 +256,9 @@ function checkFiles(paths, options) {
234
256
  objective: v.objective,
235
257
  evidence: v.evidence
236
258
  }));
237
- const entry = { path: relative, score: audit.slopScore, grade: rubric.grade, isSlopFree: audit.isSlopFree, words: audit.stats.estimatedWordCount, suppressed: audit.stats.suppressedCount ?? 0, violations };
259
+ const entry = { path: relative, score: audit.slopScore, grade, isSlopFree: audit.isSlopFree, words: audit.stats.estimatedWordCount, suppressed: audit.stats.suppressedCount ?? 0, violations };
238
260
  if (cacheEnabled) {
239
- nextCache[`check:${relative}`] = { hash: contentHash, entry };
261
+ nextCache[`check:${relative}`] = { hash: contentHash, mtimeMs: stat?.mtimeMs, size: stat?.size, optSig: optSignature, ctxSig: ctx.signature, entry };
240
262
  cacheDirty = true;
241
263
  }
242
264
  return entry;
@@ -294,7 +316,7 @@ async function handleAgentCommand(command, args) {
294
316
  return true;
295
317
  }
296
318
  if (command === '--help' || (command === 'help' && args.includes('--help'))) {
297
- console.log('Usage: sloppy <command> [options]\nCommands: setup, check, audit, plan, fix, rubric, verify, install-mcp, rules, version, looks, archetypes, list, mcp');
319
+ console.log('Usage: sloppy <command> [options]\nCommands: setup, check, audit, plan, fix, rubric, verify, review, eval, install-mcp, rules, version, looks, archetypes, list, mcp');
298
320
  return true;
299
321
  }
300
322
  if (command === 'rules') {
@@ -326,7 +348,7 @@ async function handleAgentCommand(command, args) {
326
348
  setup: 'Usage: sloppy setup [--write|-w] [--global|-g] [--json]',
327
349
  check: 'Usage: sloppy check [paths...|url] [--changed|--staged] [--cache] [--compact] [--strict] [--json] [--max-score <n>] [--fail-on <none|low|medium|high|critical>] [--min-grade <A+|A|B|C|D|F>] [--type <illustration|feature-card|hero|application|bento>] [--render|--multi-width] [--a11y] [--static] [--quiet]',
328
350
  fix: 'Usage: sloppy fix <file> [--diff|--check|--write] [--look <look>] [--json]\n sloppy fix --stdin [--json]',
329
- verify: 'Usage: sloppy verify [target] [--json] [--multi-width] [--a11y] (verification timeout: 15000ms)',
351
+ verify: 'Usage: sloppy verify [target] [--json] [--multi-width] [--a11y] [--tells] [--motion [spec.json]] [--repeat N] [--baseline <path>] (flags combine in one browser; timeout: 15000ms)',
330
352
  'install-mcp': 'Usage: sloppy install-mcp --client <cursor|vscode|claude|codex> [--dir <path>] [--write] [--json]'
331
353
  };
332
354
  console.log(help[command]);
@@ -533,7 +555,7 @@ async function handleAgentCommand(command, args) {
533
555
  fail('Usage: sloppy install-mcp --client <cursor|vscode|claude|codex> [--dir <path>] [--write]');
534
556
  return true;
535
557
  }
536
- const snippet = '[mcp_servers.sloppy]\ncommand = "npx"\nargs = ["-y", "sloppy", "mcp"]';
558
+ const snippet = '[mcp_servers.sloppy]\ncommand = "npx"\nargs = ["-y", "@sloppy-ai/cli", "mcp"]';
537
559
  if (client === 'codex') {
538
560
  if (!args.includes('--write')) {
539
561
  if (json)
@@ -566,7 +588,7 @@ async function handleAgentCommand(command, args) {
566
588
  }
567
589
  const key = client === 'vscode' ? 'servers' : 'mcpServers';
568
590
  config[key] ||= {};
569
- config[key].sloppy = { command: 'npx', args: ['-y', 'sloppy', 'mcp'] };
591
+ config[key].sloppy = { command: 'npx', args: ['-y', '@sloppy-ai/cli', 'mcp'] };
570
592
  writeFileSafe(dest, `${JSON.stringify(config, null, 2)}\n`, true);
571
593
  if (json)
572
594
  emitJson({ client, written: true, path: dest });
@@ -599,7 +621,7 @@ async function handleAgentCommand(command, args) {
599
621
  catch { }
600
622
  }
601
623
  config[client.key] = config[client.key] || {};
602
- config[client.key].sloppy = { command: 'npx', args: ['-y', 'sloppy', 'mcp'] };
624
+ config[client.key].sloppy = { command: 'npx', args: ['-y', '@sloppy-ai/cli', 'mcp'] };
603
625
  writeFileSafe(client.file, `${JSON.stringify(config, null, 2)}\n`, true);
604
626
  mcpResults.push({ client: client.id, path: client.file, status: 'configured' });
605
627
  }
@@ -612,7 +634,7 @@ async function handleAgentCommand(command, args) {
612
634
  }
613
635
  }
614
636
  const codexFile = path.join(homeDir, '.codex/config.toml');
615
- const codexSnippet = '[mcp_servers.sloppy]\ncommand = "npx"\nargs = ["-y", "sloppy", "mcp"]';
637
+ const codexSnippet = '[mcp_servers.sloppy]\ncommand = "npx"\nargs = ["-y", "@sloppy-ai/cli", "mcp"]';
616
638
  if (shouldWrite) {
617
639
  try {
618
640
  let content = readOptionalFile(codexFile) || '';
@@ -627,38 +649,51 @@ async function handleAgentCommand(command, args) {
627
649
  else {
628
650
  mcpResults.push({ client: 'codex', path: codexFile, status: 'dry-run (pass --write to save)' });
629
651
  }
630
- const sourceSkillDir = path.resolve(ROOT_DIR, 'skills/sloppy');
631
- const skillTargets = [
632
- { name: 'Universal Agents', dir: path.join(homeDir, '.agents/skills/sloppy') },
633
- { name: 'Antigravity', dir: path.join(homeDir, '.gemini/config/skills/sloppy') },
634
- { name: 'Claude Code', dir: path.join(homeDir, '.claude/skills/sloppy') }
652
+ const skillList = [
653
+ 'sloppy',
654
+ 'sloppy-ui',
655
+ 'sloppy-code',
656
+ 'sloppy-copywriting',
657
+ 'sloppy-human',
658
+ 'sloppy-layoutmobile'
635
659
  ];
636
- if (fs.existsSync(sourceSkillDir)) {
637
- for (const target of skillTargets) {
638
- if (shouldWrite) {
639
- try {
640
- fs.mkdirSync(path.dirname(target.dir), { recursive: true });
660
+ const sourceBaseDir = fs.existsSync(path.resolve(__dirname, '../skills'))
661
+ ? path.resolve(__dirname, '../skills')
662
+ : path.resolve(ROOT_DIR, 'skills');
663
+ for (const skillName of skillList) {
664
+ const sourceSkillDir = path.resolve(sourceBaseDir, skillName);
665
+ if (fs.existsSync(sourceSkillDir)) {
666
+ const skillTargets = [
667
+ { name: `Universal Agents (${skillName})`, dir: path.join(homeDir, '.agents/skills', skillName) },
668
+ { name: `Antigravity (${skillName})`, dir: path.join(homeDir, '.gemini/config/skills', skillName) },
669
+ { name: `Claude Code (${skillName})`, dir: path.join(homeDir, '.claude/skills', skillName) }
670
+ ];
671
+ for (const target of skillTargets) {
672
+ if (shouldWrite) {
641
673
  try {
642
- fs.symlinkSync(sourceSkillDir, target.dir, 'dir');
643
- skillResults.push({ target: target.name, path: target.dir, status: 'symlinked' });
644
- }
645
- catch (err) {
646
- if (err?.code === 'EEXIST') {
647
- skillResults.push({ target: target.name, path: target.dir, status: 'already-installed' });
674
+ fs.mkdirSync(path.dirname(target.dir), { recursive: true });
675
+ try {
676
+ fs.symlinkSync(sourceSkillDir, target.dir, 'dir');
677
+ skillResults.push({ target: target.name, path: target.dir, status: 'symlinked' });
648
678
  }
649
- else {
650
- fs.cpSync(sourceSkillDir, target.dir, { recursive: true });
651
- skillResults.push({ target: target.name, path: target.dir, status: 'copied' });
679
+ catch (err) {
680
+ if (err?.code === 'EEXIST') {
681
+ skillResults.push({ target: target.name, path: target.dir, status: 'already-installed' });
682
+ }
683
+ else {
684
+ fs.cpSync(sourceSkillDir, target.dir, { recursive: true });
685
+ skillResults.push({ target: target.name, path: target.dir, status: 'copied' });
686
+ }
652
687
  }
653
688
  }
689
+ catch (err) {
690
+ skillResults.push({ target: target.name, path: target.dir, status: `error: ${err.message}` });
691
+ }
654
692
  }
655
- catch (err) {
656
- skillResults.push({ target: target.name, path: target.dir, status: `error: ${err.message}` });
693
+ else {
694
+ skillResults.push({ target: target.name, path: target.dir, status: 'dry-run (pass --write to save)' });
657
695
  }
658
696
  }
659
- else {
660
- skillResults.push({ target: target.name, path: target.dir, status: 'dry-run (pass --write to save)' });
661
- }
662
697
  }
663
698
  }
664
699
  const pluginDoorResults = [];
@@ -1092,13 +1127,85 @@ export async function runCli(args) {
1092
1127
  const target = args[1] && !args[1].startsWith('-') ? args[1] : 'http://127.0.0.1:1355';
1093
1128
  const isMultiWidth = args.includes('--multi-width') || args.includes('--render') || args.includes('-m');
1094
1129
  const staticOnly = args.includes('--static');
1130
+ const a11yRequested = args.includes('--a11y');
1131
+ const tellsRequested = args.includes('--tells');
1132
+ const motionIdx = args.indexOf('--motion');
1133
+ const besidesRender = motionIdx !== -1 || a11yRequested || tellsRequested || isMultiWidth;
1134
+ const sections = {};
1135
+ let worstExit = 0;
1136
+ let sharedBrowser;
1137
+ const noteExit = (result) => {
1138
+ worstExit = Math.max(worstExit, result.unavailable ? 2 : result.ok ? 0 : 1);
1139
+ };
1140
+ // One launch serves every requested pass; modules fall back to their own launch when absent.
1141
+ const ensureBrowser = async () => {
1142
+ if (!sharedBrowser) {
1143
+ const { tryLaunch } = await import('@sloppy-ai/verify/browser').catch(async () => import(path.resolve(ROOT_DIR, 'packages/verify/browser.mjs')));
1144
+ sharedBrowser = (await tryLaunch()).browser || undefined;
1145
+ }
1146
+ return sharedBrowser;
1147
+ };
1095
1148
  try {
1096
- if (args.includes('--a11y')) {
1149
+ if (motionIdx !== -1) {
1150
+ const explicitSpec = args[motionIdx + 1] && !args[motionIdx + 1].startsWith('-') ? args[motionIdx + 1] : null;
1151
+ const specPath = explicitSpec || 'sloppy.motion.json';
1152
+ const repeatIdx = args.indexOf('--repeat');
1153
+ const repeat = repeatIdx !== -1 ? Math.min(10, Math.max(1, Number(args[repeatIdx + 1]) || 1)) : 1;
1154
+ const baselineIdx = args.indexOf('--baseline');
1155
+ const baselinePath = baselineIdx !== -1 && args[baselineIdx + 1] && !args[baselineIdx + 1].startsWith('-') ? args[baselineIdx + 1] : null;
1156
+ let spec = null;
1157
+ try {
1158
+ spec = JSON.parse(fs.readFileSync(path.resolve(specPath), 'utf8'));
1159
+ }
1160
+ catch (error) {
1161
+ console.error(`[ERROR] Could not read motion spec ${specPath}: ${error.message}`);
1162
+ console.error(explicitSpec ? '' : 'Create sloppy.motion.json in the project root or pass --motion <path>.');
1163
+ worstExit = 2;
1164
+ }
1165
+ if (spec) {
1166
+ const module = await import('@sloppy-ai/verify/motion-interactions').catch(async () => import(path.resolve(ROOT_DIR, 'packages/verify/motion-interactions.mjs')));
1167
+ const runs = [];
1168
+ for (let index = 0; index < repeat; index += 1) {
1169
+ const run = await module.runMotionInteractionAudit(target, { spec, timeoutMs: 15000, browser: await ensureBrowser() });
1170
+ runs.push(run);
1171
+ if (run.unavailable)
1172
+ break;
1173
+ }
1174
+ let res = runs[0];
1175
+ if (runs.length > 1) {
1176
+ const stability = module.stabilizeMotionRuns(runs);
1177
+ const findings = [...stability.stable, ...stability.unstable];
1178
+ res = { ...res, ok: findings.length === 0, runs: stability.runs, stable: stability.stable, unstable: stability.unstable, findings };
1179
+ }
1180
+ if (baselinePath && !res.unavailable) {
1181
+ const stable = res.stable || res.findings;
1182
+ fs.writeFileSync(path.resolve(baselinePath), `${JSON.stringify({ target, runs: res.runs || 1, stable }, null, 2)}\n`);
1183
+ }
1184
+ sections.motion = res;
1185
+ noteExit(res);
1186
+ if (!json) {
1187
+ console.log(`\n======================================================`);
1188
+ console.log(`SLOPPY MOTION INTERACTION VERIFICATION`);
1189
+ console.log(`======================================================\n`);
1190
+ console.log(`Target: ${res.target} (${res.mode})`);
1191
+ console.log(`Summary: ${res.summary}`);
1192
+ for (const finding of res.findings)
1193
+ console.log(` [${finding.severity.toUpperCase()}] ${finding.rule}: ${finding.message}`);
1194
+ if (res.runs > 1)
1195
+ console.log(`Repeat: ${res.runs} runs, ${res.stable.length} stable, ${res.unstable.length} machine-dependent`);
1196
+ if (baselinePath && !res.unavailable)
1197
+ console.log(`Baseline: ${baselinePath}`);
1198
+ if (res.unavailable)
1199
+ console.error(`Motion verification unavailable: ${res.unavailable}`);
1200
+ }
1201
+ }
1202
+ }
1203
+ if (a11yRequested) {
1097
1204
  const module = await import('@sloppy-ai/verify/accessibility').catch(async () => import(path.resolve(ROOT_DIR, 'packages/verify/accessibility.mjs')));
1098
- const res = await module.runAccessibilityAudit(target, { timeoutMs: 15000 });
1099
- if (json)
1100
- emitJson(res);
1101
- else {
1205
+ const res = await module.runAccessibilityAudit(target, { timeoutMs: 15000, browser: await ensureBrowser() });
1206
+ sections.a11y = res;
1207
+ noteExit(res);
1208
+ if (!json) {
1102
1209
  console.log(`\n======================================================`);
1103
1210
  console.log(`SLOPPY RENDERED ACCESSIBILITY VERIFICATION`);
1104
1211
  console.log(`======================================================\n`);
@@ -1109,19 +1216,35 @@ export async function runCli(args) {
1109
1216
  if (res.unavailable)
1110
1217
  console.error(`Accessibility unavailable: ${res.unavailable}`);
1111
1218
  }
1219
+ }
1220
+ if (tellsRequested) {
1221
+ const module = await import('@sloppy-ai/verify/tells').catch(async () => import(path.resolve(ROOT_DIR, 'packages/verify/tells.mjs')));
1222
+ const configuredAccents = loadSloppyConfig(process.cwd())?.brand?.allowColors || [];
1223
+ const res = await module.runTellAudit(target, { timeoutMs: 15000, browser: await ensureBrowser(), allowAccents: configuredAccents });
1224
+ sections.tells = res;
1112
1225
  if (res.unavailable)
1113
- process.exitCode = 2;
1114
- else if (!res.ok)
1115
- process.exitCode = 1;
1116
- break;
1226
+ worstExit = Math.max(worstExit, 2);
1227
+ if (!json) {
1228
+ console.log(`\n======================================================`);
1229
+ console.log(`SLOPPY RENDERED TELLS (ADVISORY)`);
1230
+ console.log(`======================================================\n`);
1231
+ console.log(`Target: ${res.target} (${res.mode})`);
1232
+ console.log(`Summary: ${res.summary}`);
1233
+ for (const finding of res.findings)
1234
+ console.log(` [${finding.severity.toUpperCase()}] ${finding.rule}: ${finding.message}`);
1235
+ for (const screenshot of res.screenshots || [])
1236
+ console.log(`Screenshot: ${screenshot}`);
1237
+ if (res.unavailable)
1238
+ console.error(`Rendered tells unavailable: ${res.unavailable}`);
1239
+ }
1117
1240
  }
1118
1241
  if (isMultiWidth) {
1119
1242
  const moduleName = '@sloppy-ai/verify/multi-width';
1120
1243
  const module = await import(moduleName).catch(async () => import(path.resolve(ROOT_DIR, 'packages/verify/multi-width.mjs')));
1121
- const res = await module.runMultiWidthVerification(target, { staticOnly });
1122
- if (json)
1123
- emitJson(res);
1124
- else {
1244
+ const res = await module.runMultiWidthVerification(target, { staticOnly, browser: staticOnly ? undefined : await ensureBrowser() });
1245
+ sections.multiWidth = res;
1246
+ worstExit = Math.max(worstExit, res.allPassed ? 0 : 1);
1247
+ if (!json) {
1125
1248
  console.log(`\n======================================================`);
1126
1249
  console.log(`SLOPPY MULTI-WIDTH VIEWPORT VERIFICATION (${res.totalViewportsTested} WIDTHS)`);
1127
1250
  console.log(`======================================================\n`);
@@ -1131,28 +1254,34 @@ export async function runCli(args) {
1131
1254
  for (const f of res.findings)
1132
1255
  console.log(` [${f.severity.toUpperCase()}] ${f.viewportName} (${f.width}px): ${f.message}`);
1133
1256
  }
1134
- if (!res.allPassed)
1135
- process.exitCode = 1;
1136
- break;
1137
1257
  }
1138
- const { verifyTarget } = await import('@sloppy-ai/verify').catch(async () => import(path.resolve(ROOT_DIR, 'packages/verify/verification.mjs')));
1139
- const result = await verifyTarget(target, { timeoutMs: 15000 });
1140
- if (json)
1141
- emitJson(result);
1142
- else {
1143
- console.log(`\n======================================================`);
1144
- console.log(`SLOPPY BROWSER & GEOMETRIC VERIFICATION HARNESS`);
1145
- console.log(`======================================================\n`);
1146
- console.log(`Verification ${result.ok ? 'passed' : 'failed'}: ${result.target} (${result.mode})`);
1147
- for (const violation of result.violations)
1148
- console.log(`[${violation.rule}] ${violation.message}${violation.evidence ? `: ${violation.evidence}` : ''}`);
1258
+ if (!besidesRender) {
1259
+ const { verifyTarget } = await import('@sloppy-ai/verify').catch(async () => import(path.resolve(ROOT_DIR, 'packages/verify/verification.mjs')));
1260
+ const result = await verifyTarget(target, { timeoutMs: 15000 });
1261
+ if (json)
1262
+ emitJson(result);
1263
+ else {
1264
+ console.log(`\n======================================================`);
1265
+ console.log(`SLOPPY BROWSER & GEOMETRIC VERIFICATION HARNESS`);
1266
+ console.log(`======================================================\n`);
1267
+ console.log(`Verification ${result.ok ? 'passed' : 'failed'}: ${result.target} (${result.mode})`);
1268
+ for (const violation of result.violations)
1269
+ console.log(`[${violation.rule}] ${violation.message}${violation.evidence ? `: ${violation.evidence}` : ''}`);
1270
+ if (result.unavailable)
1271
+ console.error(`Verification unavailable: ${result.unavailable}`);
1272
+ }
1149
1273
  if (result.unavailable)
1150
- console.error(`Verification unavailable: ${result.unavailable}`);
1274
+ process.exitCode = 2;
1275
+ else if (!result.ok)
1276
+ process.exitCode = 1;
1277
+ }
1278
+ if (json) {
1279
+ const passes = Object.values(sections);
1280
+ if (passes.length === 1)
1281
+ emitJson(passes[0]);
1282
+ else if (passes.length > 1)
1283
+ emitJson({ ok: worstExit === 0, target, ...sections });
1151
1284
  }
1152
- if (result.unavailable)
1153
- process.exitCode = 2;
1154
- else if (!result.ok)
1155
- process.exitCode = 1;
1156
1285
  }
1157
1286
  catch (error) {
1158
1287
  const unavailable = `Verification unavailable: ${error.message}`;
@@ -1162,6 +1291,12 @@ export async function runCli(args) {
1162
1291
  console.error(unavailable);
1163
1292
  process.exitCode = 2;
1164
1293
  }
1294
+ finally {
1295
+ if (sharedBrowser)
1296
+ await sharedBrowser.close().catch(() => { });
1297
+ }
1298
+ if (worstExit)
1299
+ process.exitCode = Math.max(Number(process.exitCode) || 0, worstExit);
1165
1300
  break;
1166
1301
  }
1167
1302
  case 'create': {
@@ -1378,6 +1513,7 @@ export async function runCli(args) {
1378
1513
  const safeDesignMd = `# Design System Specification (DESIGN.md)\n\n- **Theme Mode**: ${dna.theme === 'light' ? 'Light Mode' : 'Dark Mode'}\n- **Border Radius**: ${dna.borderRadius}\n- **Ground**: \`${dna.colors.ground}\`\n- **Accent**: \`${dna.colors.accent}\`\n- **Primary Sans**: \`${dna.fontSans}\`\n- **Monospace**: \`${dna.fontMono}\`\n`;
1379
1514
  writeFileSafe(path.resolve(process.cwd(), 'sloppy.config.json'), safeConfigJson, true);
1380
1515
  writeFileSafe(path.resolve(process.cwd(), 'DESIGN.md'), safeDesignMd, true);
1516
+ writeFileSafe(path.resolve(process.cwd(), 'sloppy.motion.json'), MOTION_SPEC_TEMPLATE, true);
1381
1517
  console.log(`[SUCCESS] Extracted design DNA from ${dna.sourceUrl}:`);
1382
1518
  console.log(` - Theme: ${dna.theme}`);
1383
1519
  console.log(` - Font Sans: ${dna.fontSans}`);
@@ -1387,6 +1523,7 @@ export async function runCli(args) {
1387
1523
  console.log(`\nCreated files:`);
1388
1524
  console.log(` * ./sloppy.config.json (Brand tokens & 3-tier rules)`);
1389
1525
  console.log(` * ./DESIGN.md (Comprehensive design system specification)`);
1526
+ console.log(` * ./sloppy.motion.json (Starter interaction spec; edit its selectors)`);
1390
1527
  break;
1391
1528
  }
1392
1529
  console.log(`\n======================================================`);
@@ -1398,6 +1535,8 @@ export async function runCli(args) {
1398
1535
  console.log(` - ${item}`);
1399
1536
  }
1400
1537
  const force = args.includes('--force');
1538
+ const lookIdx = args.indexOf('--look');
1539
+ const requestedLook = lookIdx !== -1 && args[lookIdx + 1] && !args[lookIdx + 1].startsWith('-') ? args[lookIdx + 1] : null;
1401
1540
  const configPath = path.resolve(process.cwd(), 'sloppy.config.json');
1402
1541
  if (writeFileSafe(configPath, JSON.stringify(stack.suggestedConfig, null, 2) + '\n', force) !== 'exists') {
1403
1542
  console.log(`\n[SUCCESS] Generated ./sloppy.config.json tailored to detected stack.`);
@@ -1406,11 +1545,21 @@ export async function runCli(args) {
1406
1545
  console.log(`\n[INFO] ./sloppy.config.json already exists. Pass --force to regenerate.`);
1407
1546
  }
1408
1547
  const designPath = path.resolve(process.cwd(), 'DESIGN.md');
1409
- if (writeFileSafe(designPath, DESIGN_MD_TEMPLATE, force) !== 'exists') {
1410
- console.log(`[SUCCESS] Generated ./DESIGN.md design contract (token lock: palette, type, radius, blur cap, signature).`);
1548
+ const designContent = requestedLook ? materialDesignMd(getLook(requestedLook)) : DESIGN_MD_TEMPLATE;
1549
+ if (writeFileSafe(designPath, designContent, force) !== 'exists') {
1550
+ console.log(requestedLook
1551
+ ? `[SUCCESS] Generated ./DESIGN.md from the "${getLook(requestedLook).name}" material (palette, type scale, radius, density, motif, motion contract).`
1552
+ : '[SUCCESS] Generated ./DESIGN.md design contract (token lock: palette, type, radius, blur cap, signature, motion scale).');
1553
+ }
1554
+ else {
1555
+ console.log('[INFO] ./DESIGN.md already exists. Pass --force to regenerate the token-lock template.');
1556
+ }
1557
+ const motionPath = path.resolve(process.cwd(), 'sloppy.motion.json');
1558
+ if (writeFileSafe(motionPath, MOTION_SPEC_TEMPLATE, force) !== 'exists') {
1559
+ console.log(`[SUCCESS] Generated ./sloppy.motion.json starter (edit the placeholder selectors before running --motion).`);
1411
1560
  }
1412
1561
  else {
1413
- console.log(`[INFO] ./DESIGN.md already exists. Pass --force to regenerate the token-lock template.`);
1562
+ console.log(`[INFO] ./sloppy.motion.json already exists. Pass --force to regenerate the starter spec.`);
1414
1563
  }
1415
1564
  const destDir = path.resolve(process.cwd(), 'src/kit');
1416
1565
  fs.mkdirSync(destDir, { recursive: true });
@@ -1453,12 +1602,54 @@ export async function runCli(args) {
1453
1602
  break;
1454
1603
  }
1455
1604
  case 'looks': {
1605
+ if (args.includes('--deal')) {
1606
+ const countIdx = args.indexOf('--count');
1607
+ const requested = countIdx !== -1 ? Number(args[countIdx + 1]) : 3;
1608
+ const explicitTheme = args.includes('--dark') ? 'dark' : args.includes('--light') ? 'light' : undefined;
1609
+ // Without an explicit theme, the saved brief kind sets the bias (tech and gaming lean dark).
1610
+ let kindTheme;
1611
+ try {
1612
+ const saved = JSON.parse(fs.readFileSync(path.resolve(process.cwd(), BRIEF_FILE), 'utf8'));
1613
+ if (typeof saved.kind === 'string' && isSiteKind(saved.kind))
1614
+ kindTheme = policyFor(saved.kind).themeBias;
1615
+ }
1616
+ catch {
1617
+ // No brief saved: the deal is unbiased.
1618
+ }
1619
+ const dealt = dealLooks({
1620
+ count: Number.isFinite(requested) ? requested : 3,
1621
+ theme: explicitTheme ?? (kindTheme === 'either' ? undefined : kindTheme),
1622
+ cwd: process.cwd(),
1623
+ allowLoudAccent: args.includes('--allow-loud-accent'),
1624
+ record: !args.includes('--no-record')
1625
+ });
1626
+ if (json) {
1627
+ emitJson(dealt);
1628
+ break;
1629
+ }
1630
+ console.log(`\nSLOPPY LOOK DEAL (${dealt.length} looks, recent looks excluded)\n`);
1631
+ for (const look of dealt) {
1632
+ const material = resolveMaterial(look);
1633
+ const convergence = assessConvergence(fingerprintLook(look));
1634
+ console.log(`* ${look.name.toUpperCase()} [${look.theme.toUpperCase()}] accent ${look.accent} ground ${look.background}`);
1635
+ console.log(` ${look.description}`);
1636
+ console.log(` motif: ${material.layoutMotif}`);
1637
+ console.log(` type: display ${material.typeScale.display}px / body ${material.typeScale.body}px radius ${material.radius}px density ${material.density}`);
1638
+ if (convergence)
1639
+ console.log(` [CONVERGENCE] ${convergence.cluster}: ${convergence.reason}`);
1640
+ }
1641
+ console.log(`\nHistory: ${args.includes('--no-record') ? 'not recorded' : '.sloppy/dealt-looks.json'}`);
1642
+ break;
1643
+ }
1456
1644
  const isNext = args.includes('--next');
1457
1645
  if (isNext) {
1458
1646
  const theme = args.includes('--dark') ? 'dark' : args.includes('--light') ? 'light' : undefined;
1459
- const material = getNextMaterial({ theme });
1647
+ const materialLook = getNextMaterial({ theme });
1648
+ const material = resolveMaterial(materialLook);
1649
+ const fingerprint = fingerprintLook(materialLook);
1650
+ const convergence = assessConvergence(fingerprint);
1460
1651
  if (json) {
1461
- emitJson(material);
1652
+ emitJson({ ...toMaterial(materialLook), fingerprint, convergence });
1462
1653
  break;
1463
1654
  }
1464
1655
  console.log(`\n======================================================`);
@@ -1466,11 +1657,18 @@ export async function runCli(args) {
1466
1657
  console.log(`======================================================\n`);
1467
1658
  console.log(`Selected Material: ${material.name.toUpperCase()} [${material.theme.toUpperCase()}]`);
1468
1659
  console.log(`Description: ${material.description}`);
1469
- console.log(`Surfaces: ground: ${material.background} | s1: ${material.surface1} | s2: ${material.surface2} | s3: ${material.surface3}`);
1660
+ console.log(`Surfaces: ground: ${material.ground} | s1: ${material.surfaces[0]} | s2: ${material.surfaces[1]} | s3: ${material.surfaces[2]}`);
1470
1661
  console.log(`Accent: ${material.accent}`);
1471
1662
  console.log(`Border: ${material.border}`);
1472
1663
  if (material.fontSans)
1473
1664
  console.log(`Typography: ${material.fontSans}`);
1665
+ console.log(`Type scale: display ${material.typeScale.display}px | heading ${material.typeScale.heading}px | body ${material.typeScale.body}px | label ${material.typeScale.label}px`);
1666
+ console.log(`Radius / density: ${material.radius}px / ${material.density}`);
1667
+ console.log(`Layout motif: ${material.layoutMotif}`);
1668
+ console.log(`Component identity: ${material.componentIdentity}`);
1669
+ console.log(`Motion contract: ${material.motion.fast}/${material.motion.base}/${material.motion.slow}ms, ${material.motion.easeEnter}`);
1670
+ if (convergence)
1671
+ console.log(`\n[CONVERGENCE WARNING] ${convergence.cluster}: ${convergence.reason}. Declare a brand token or deal again.`);
1474
1672
  console.log(`\n[HISTORY UPDATED] Dealt "${material.name}". Anti-repetition tracker updated.`);
1475
1673
  break;
1476
1674
  }
@@ -1496,6 +1694,134 @@ export async function runCli(args) {
1496
1694
  }
1497
1695
  break;
1498
1696
  }
1697
+ case 'brief': {
1698
+ const text = args.filter((arg, index) => arg !== 'brief' && !arg.startsWith('--') && !(index > 0 && args[index - 1] === '--file')).join(' ').trim();
1699
+ const fileIdx = args.indexOf('--file');
1700
+ const briefText = fileIdx !== -1 && args[fileIdx + 1] ? fs.readFileSync(path.resolve(process.cwd(), args[fileIdx + 1]), 'utf8') : text;
1701
+ if (!briefText) {
1702
+ fail('Usage: sloppy brief "<project brief>" [--write] [--json] or sloppy brief --file <path> [--write]', 2);
1703
+ break;
1704
+ }
1705
+ const record = runBrief(briefText, { write: args.includes('--write') });
1706
+ if (json) {
1707
+ emitJson(record);
1708
+ break;
1709
+ }
1710
+ console.log(`\nSLOPPY BRIEF`);
1711
+ for (const line of describeBrief(record))
1712
+ console.log(line);
1713
+ console.log(args.includes('--write') ? `\nSaved to ${BRIEF_FILE}. The finish gate will use this kind.` : `\nRun with --write to save the kind for the finish gate.`);
1714
+ break;
1715
+ }
1716
+ case 'review': {
1717
+ const target = args[1] && !args[1].startsWith('-') ? args[1] : '';
1718
+ if (!/^https?:\/\//i.test(target)) {
1719
+ fail('Usage: sloppy review <http(s) URL> [--out <directory>] [--json]', 2);
1720
+ break;
1721
+ }
1722
+ const outIdx = args.indexOf('--out');
1723
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
1724
+ const outputDir = path.resolve(process.cwd(), outIdx !== -1 && args[outIdx + 1] ? args[outIdx + 1] : `.sloppy/reviews/${stamp}`);
1725
+ if (fs.existsSync(outputDir)) {
1726
+ fail(`Review output already exists: ${outputDir}`, 2);
1727
+ break;
1728
+ }
1729
+ const module = await import('@sloppy-ai/verify/tells').catch(async () => import(path.resolve(ROOT_DIR, 'packages/verify/tells.mjs')));
1730
+ const result = await module.runTellAudit(target, {
1731
+ timeoutMs: 15000,
1732
+ screenshotDir: outputDir,
1733
+ allowAccents: loadSloppyConfig(process.cwd())?.brand?.allowColors || []
1734
+ });
1735
+ if (result.unavailable) {
1736
+ fail(`Fresh review not created: ${result.unavailable}`, 2);
1737
+ break;
1738
+ }
1739
+ let briefText = null;
1740
+ try {
1741
+ briefText = JSON.parse(fs.readFileSync(path.resolve(process.cwd(), BRIEF_FILE), 'utf8')).brief || null;
1742
+ }
1743
+ catch { }
1744
+ const prompt = createFreshReviewPrompt({
1745
+ target,
1746
+ brief: briefText,
1747
+ designContract: readOptionalFile(path.resolve(process.cwd(), 'DESIGN.md')),
1748
+ screenshots: result.screenshots.map((file) => path.relative(process.cwd(), file)),
1749
+ findings: result.findings
1750
+ });
1751
+ fs.writeFileSync(path.join(outputDir, 'review.md'), prompt, { encoding: 'utf8', flag: 'wx' });
1752
+ const output = { target, outputDir, screenshots: result.screenshots, findings: result.findings, promptPath: path.join(outputDir, 'review.md') };
1753
+ if (json)
1754
+ emitJson(output);
1755
+ else
1756
+ console.log(`Saved a fresh-context review pack to ${outputDir}. Read review.md with the screenshots in a new reviewer context.`);
1757
+ break;
1758
+ }
1759
+ case 'eval': {
1760
+ const inputPath = args[1] && !args[1].startsWith('-') ? path.resolve(process.cwd(), args[1]) : '';
1761
+ if (!inputPath) {
1762
+ fail('Usage: sloppy eval <results.json> [--json]', 2);
1763
+ break;
1764
+ }
1765
+ try {
1766
+ const summary = summarizeEvaluation(JSON.parse(fs.readFileSync(inputPath, 'utf8')));
1767
+ if (json)
1768
+ emitJson(summary);
1769
+ else
1770
+ console.log(JSON.stringify(summary, null, 2));
1771
+ }
1772
+ catch (error) {
1773
+ fail(`Evaluation failed: ${error.message}`, 2);
1774
+ }
1775
+ break;
1776
+ }
1777
+ case 'gate': {
1778
+ if (args.includes('--install')) {
1779
+ for (const line of installGate(process.cwd()))
1780
+ console.log(line);
1781
+ console.log(`Run \`sloppy gate\` to check the working tree now. Add waivers to .sloppy/waivers.json only with a real reason.`);
1782
+ break;
1783
+ }
1784
+ const hookMode = args.includes('--hook');
1785
+ const targets = args.filter(arg => !arg.startsWith('--') && arg !== 'gate');
1786
+ try {
1787
+ const result = runGate(args, {
1788
+ changed: () => collectGitChangedFiles('changed', targets),
1789
+ audit: (file) => checkFiles([file], { maxScore: 100, failOn: 'none', cache: false, skipRubric: true }).files.flatMap(f => f.violations.map(v => ({
1790
+ id: v.type,
1791
+ severity: v.severity,
1792
+ file: f.path,
1793
+ line: v.line,
1794
+ message: v.message,
1795
+ recommendation: v.recommendation
1796
+ })))
1797
+ });
1798
+ if (hookMode) {
1799
+ process.exitCode = 0;
1800
+ break;
1801
+ }
1802
+ if (json) {
1803
+ emitJson(result);
1804
+ process.exitCode = result.exit;
1805
+ break;
1806
+ }
1807
+ console.log(`\nSLOPPY FINISH GATE: ${result.label} (round ${result.round} of ${result.maxRounds}, ${result.waivedCount} waived)`);
1808
+ for (const line of summarize(result.blocking, 50).split('\n').filter(Boolean))
1809
+ console.log(line);
1810
+ if (result.label === 'OPEN')
1811
+ console.log('Round limit reached. The gate has stopped blocking this turn; review the list above with the user.');
1812
+ process.exitCode = result.exit;
1813
+ }
1814
+ catch (error) {
1815
+ if (hookMode) {
1816
+ // A broken gate must not trap the agent in a loop; report and let the turn end.
1817
+ console.error(`sloppy gate failed open: ${error.message}`);
1818
+ process.exitCode = 0;
1819
+ break;
1820
+ }
1821
+ fail(`sloppy gate: ${error.message}`, 2);
1822
+ }
1823
+ break;
1824
+ }
1499
1825
  case 'hook': {
1500
1826
  const sub = args[1];
1501
1827
  if (sub === 'install') {
@@ -1526,6 +1852,7 @@ export async function runCli(args) {
1526
1852
  break;
1527
1853
  }
1528
1854
  case 'mcp': {
1855
+ const { runServer } = await import('@sloppy-ai/mcp');
1529
1856
  await runServer();
1530
1857
  break;
1531
1858
  }
@@ -1539,13 +1866,17 @@ Combining MIT Component Ecosystems (stageshow, shadcn, motion-primitives, magicu
1539
1866
  Usage:
1540
1867
  sloppy setup [--write|-w] All-in-one setup: configure MCP clients and link Agent Skills
1541
1868
  sloppy check <paths...|url> Gate files on slop score, severity, and craft grade (--code, --compact, --render)
1869
+ sloppy brief "<brief>" Classify a project brief into a site kind (--write saves it for the gate)
1870
+ sloppy gate [paths...] Finish gate over changed files: audit, guards, assets, waivers (--hook, --install, --reset, --json)
1542
1871
  sloppy audit <file|dir> Audit code or directory for AI slop anti-patterns (--strict, --floor-only, --code)
1543
1872
  sloppy gain Display measured craft value scoreboard & token efficiency
1544
1873
  sloppy rubric <file> Evaluate code against 10-point Craft Rubric (Grade A+ to F)
1545
1874
  sloppy plan <file> Generate structured repair plan with confidence & risk scores
1546
1875
  sloppy fix <file> [--diff|--check|--write] Review or apply a proposed repair
1547
1876
  sloppy fix --stdin [--json] Transform source from stdin
1548
- sloppy verify [target] Run browser or static verification (--multi-width, --static)
1877
+ sloppy review <url> Capture screenshots and print a fresh-context review packet (--json)
1878
+ sloppy eval <file.json> Summarize blinded pairs and per-rule detector cases (--json)
1879
+ sloppy verify [target] Run browser or static verification (flags combine: --multi-width, --a11y, --tells, --motion <spec>, --repeat N, --baseline <path>)
1549
1880
  sloppy rules List canonical rule IDs with tier, severity, and auto-fix/detect-only mode
1550
1881
  sloppy install-mcp --client <client> Configure an MCP client
1551
1882
  sloppy version [--json] Show CLI and core versions
@@ -1554,8 +1885,8 @@ Usage:
1554
1885
  sloppy list [library] List all components or filter by library
1555
1886
  sloppy libs Show the 7 integrated UI libraries and their design roles
1556
1887
  sloppy add <componentId> Install a component directly into your project
1557
- sloppy init Scaffold the anti-slop React kit into ./src/kit/
1558
- sloppy looks View available design looks and token scales
1888
+ sloppy init [--from <url>|--look <name>] Scaffold the React kit, DESIGN.md (optionally from a material), and sloppy.motion.json
1889
+ sloppy looks View available design looks and token scales (--deal [--count N] deals distinct looks)
1559
1890
  sloppy dev Launch visual playground on http://127.0.0.1:1355
1560
1891
  sloppy mcp Start the stdio Model Context Protocol server
1561
1892
  sloppy help Show this help screen