unslop-design 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -300,6 +300,21 @@ edit just added, with the fix number. It says nothing when the edit is
300
300
  clean, never changes code itself, and turns off with `UNSLOP_HOOK=off` or
301
301
  `hook: off` in `.unslop/context.md`.
302
302
 
303
+ **While other agents write.** The same hook works wherever an agent's hooks
304
+ can hand a note back to the model. One command sets it up in the project:
305
+
306
+ ```bash
307
+ npx unslop-design hooks gemini --write # .gemini/settings.json, AfterTool
308
+ npx unslop-design hooks copilot --write # .github/hooks/unslop-design.json, postToolUse (preview)
309
+ npx unslop-design hooks codex # prints the ~/.codex/config.toml block, PostToolUse
310
+ ```
311
+
312
+ Each runs `npx -y unslop-design hook` after a write or edit, reads the
313
+ agent's event (Gemini's `write_file`/`replace`, Codex's `apply_patch`,
314
+ Copilot's tool arguments) and answers in the format they share. Cursor's and
315
+ Windsurf's post-edit hooks can't send anything back to the agent yet, so
316
+ there is no hook for them; the scanner and the CI work there as anywhere.
317
+
303
318
  **On every pull request (GitHub Actions).** Each hit becomes an annotation
304
319
  on its line, and one comment on the PR keeps the score and the change
305
320
  against the base branch, updated on every push:
@@ -321,7 +336,7 @@ jobs:
321
336
  runs-on: ubuntu-latest
322
337
  steps:
323
338
  - uses: actions/checkout@v5
324
- - uses: marcosnovo/unslop-design@v1.12.0
339
+ - uses: marcosnovo/unslop-design@v1.13.0
325
340
  with:
326
341
  paths: src
327
342
  min: 80 # optional; also: allow, scale, type-scale, comment: false
package/bin/unslop.mjs CHANGED
@@ -2,6 +2,7 @@
2
2
  // npx unslop-design <command>: one entry point for the installer and the scripts.
3
3
  // No dependencies. scan and score need Python 3; audit needs Playwright.
4
4
  import { spawnSync } from "node:child_process";
5
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
6
  import { dirname, join } from "node:path";
6
7
  import { fileURLToPath } from "node:url";
7
8
 
@@ -20,6 +21,8 @@ const HELP = `unslop-design: make your app or site stop looking AI-generated
20
21
  the rendered page at 390/768/1280 px (needs Playwright)
21
22
  npx unslop-design rules
22
23
  every rule id with its fix number
24
+ npx unslop-design hooks <gemini|codex|copilot|claude> [--write]
25
+ the post-edit hook for that agent: prints its config, --write adds it to this project
23
26
 
24
27
  Then, in your agent: "unslop this screen". Docs: https://github.com/marcosnovo/unslop-design`;
25
28
 
@@ -38,6 +41,72 @@ function python(script, args) {
38
41
  process.exit(2);
39
42
  }
40
43
 
44
+ // The same hook for every agent: `npx -y unslop-design hook` reads the agent's event on stdin.
45
+ const HOOK = "npx -y unslop-design hook";
46
+ const HOOKS = {
47
+ gemini: {
48
+ file: ".gemini/settings.json",
49
+ note: "Gemini CLI: AfterTool on write_file and replace. Project hooks ask for approval the first time.",
50
+ merge: (cfg) => {
51
+ cfg.hooks ??= {};
52
+ cfg.hooks.AfterTool = withOurHook(cfg.hooks.AfterTool,
53
+ { matcher: "write_file|replace", hooks: [{ name: "unslop-design", type: "command", command: HOOK, timeout: 30000 }] });
54
+ return cfg;
55
+ },
56
+ },
57
+ copilot: {
58
+ file: ".github/hooks/unslop-design.json",
59
+ note: "GitHub Copilot (VS Code agent, Copilot CLI, cloud agent): postToolUse. Agent hooks are in preview; commit the file for cloud sessions.",
60
+ merge: () => ({ version: 1, hooks: { postToolUse: [{ type: "command", command: HOOK, timeoutSec: 30 }] } }),
61
+ },
62
+ claude: {
63
+ file: ".claude/settings.json",
64
+ note: "Claude Code: the plugin already ships this hook (/plugin install unslop-design@unslop). Use this only without the plugin.",
65
+ merge: (cfg) => {
66
+ cfg.hooks ??= {};
67
+ cfg.hooks.PostToolUse = withOurHook(cfg.hooks.PostToolUse,
68
+ { matcher: "Write|Edit|MultiEdit", hooks: [{ type: "command", command: HOOK, timeout: 30 }] });
69
+ return cfg;
70
+ },
71
+ },
72
+ codex: {
73
+ file: null,
74
+ note: "Codex CLI: PostToolUse on apply_patch. Add this to ~/.codex/config.toml (hooks may need enabling in your version, and some versions don't fire it for apply_patch).",
75
+ text: `[[hooks.PostToolUse]]\nmatcher = "apply_patch"\n\n[[hooks.PostToolUse.hooks]]\ntype = "command"\ncommand = "${HOOK}"\n`,
76
+ },
77
+ };
78
+
79
+ // Replace only our own handler in a list of hook groups: other commands in the same group stay.
80
+ function withOurHook(groups, group) {
81
+ const ours = (h) => typeof h?.command === "string" && h.command.includes("unslop-design");
82
+ const kept = (groups || []).map(g => ({ ...g, hooks: (g.hooks || []).filter(h => !ours(h)) })).filter(g => g.hooks.length);
83
+ return [...kept, group];
84
+ }
85
+
86
+ function hooks([agent, ...flags]) {
87
+ const h = HOOKS[agent];
88
+ if (!h) {
89
+ console.error(`usage: npx unslop-design hooks <${Object.keys(HOOKS).join("|")}> [--write]\n` +
90
+ "Cursor and Windsurf hooks can't send a note back to the agent yet, so there is no hook for them.");
91
+ process.exit(2);
92
+ }
93
+ console.log(h.note + "\n");
94
+ if (!h.file) { console.log(h.text); return; }
95
+ let cfg = {};
96
+ if (existsSync(h.file)) {
97
+ try { cfg = JSON.parse(readFileSync(h.file, "utf8")); }
98
+ catch { console.error(`${h.file} isn't valid JSON: fix it or add the hook by hand.`); process.exit(2); }
99
+ }
100
+ const next = JSON.stringify(h.merge(cfg), null, 2) + "\n";
101
+ if (flags.includes("--write")) {
102
+ mkdirSync(dirname(h.file), { recursive: true });
103
+ writeFileSync(h.file, next);
104
+ console.log(`Wrote ${h.file}. The hook runs after each UI edit and is silent when it's clean.`);
105
+ } else {
106
+ console.log(`${h.file}:\n${next}\nRun again with --write to save it.`);
107
+ }
108
+ }
109
+
41
110
  switch (cmd) {
42
111
  case "install": {
43
112
  const code = run("bash", [join(ROOT, "install.sh"), ...rest]);
@@ -50,6 +119,11 @@ switch (cmd) {
50
119
  case "scan": python("slop-scan.py", rest); break;
51
120
  case "score": python("unslop-score.py", rest); break;
52
121
  case "rules": python("slop-scan.py", ["--list-rules"]); break;
122
+ case "hook": {
123
+ const r = spawnSync(process.execPath, [join(ROOT, "hooks", "unslop-hook.mjs")], { stdio: "inherit" });
124
+ process.exit(r.status ?? 0);
125
+ }
126
+ case "hooks": hooks(rest); break;
53
127
  case "audit": process.exit(run(process.execPath, [join(ROOT, "scripts", "web-audit.mjs"), ...rest]) ?? 1);
54
128
  case undefined: case "help": case "-h": case "--help": console.log(HELP); break;
55
129
  default:
@@ -1,17 +1,27 @@
1
1
  #!/usr/bin/env node
2
- // PostToolUse hook: scan the UI file the agent just wrote or edited with
2
+ // Post-edit hook: scan the UI files the agent just wrote or edited with
3
3
  // scripts/slop-scan.py and hand the new hits back to the agent as context.
4
- // Silent when clean, when the file isn't UI, when Python is missing, or when
5
- // turned off (UNSLOP_HOOK=off, or a line "hook: off" in .unslop/context.md).
4
+ //
5
+ // One script for every agent whose hooks can talk back to the model:
6
+ // Claude Code PostToolUse Write, Edit, MultiEdit: tool_input.file_path
7
+ // Gemini CLI AfterTool write_file, replace: tool_input.file_path
8
+ // Codex CLI PostToolUse apply_patch: the paths inside the patch text
9
+ // Copilot / VS Code agents PostToolUse: a file path in tool_input or toolArgs
10
+ // All of them read {"hookSpecificOutput": {"additionalContext": "…"}} on stdout.
11
+ //
12
+ // Silent when clean, when no UI file was touched, when Python is missing, or
13
+ // when turned off (UNSLOP_HOOK=off, or a line "hook: off" in .unslop/context.md).
6
14
  // It never edits anything: the agent decides, the user approves.
7
15
  import { spawnSync } from "node:child_process";
8
16
  import { existsSync, readFileSync } from "node:fs";
9
- import { dirname, join, relative, extname } from "node:path";
17
+ import { dirname, join, relative, resolve, extname } from "node:path";
10
18
  import { fileURLToPath } from "node:url";
11
19
 
12
20
  const UI = new Set([".css", ".scss", ".sass", ".less", ".html", ".htm", ".jsx", ".tsx", ".vue", ".svelte", ".astro", ".mdx", ".swift", ".kt"]);
13
21
  const SCAN = join(dirname(fileURLToPath(import.meta.url)), "..", "scripts", "slop-scan.py");
14
22
  const MAX = 8;
23
+ const PATH_KEYS = ["file_path", "filePath", "path", "absolute_path", "absolutePath", "target_file", "filename"];
24
+ const WRITE_TOOLS = /^(Write|write_file|create_file|createFile|create)$/;
15
25
 
16
26
  function quit() { process.exit(0); }
17
27
 
@@ -21,12 +31,38 @@ let ev;
21
31
  try { ev = JSON.parse(input); } catch { quit(); }
22
32
  if (/^(off|0|false|no)$/i.test(process.env.UNSLOP_HOOK || "")) quit();
23
33
 
24
- const tool = ev.tool_input || {};
25
- const file = tool.file_path;
26
- if (!file || !UI.has(extname(file).toLowerCase()) || !existsSync(file)) quit();
34
+ const cwd = ev.cwd || process.cwd();
35
+ let tool = ev.tool_input ?? ev.toolArgs ?? ev.tool_args ?? {};
36
+ if (typeof tool === "string") { try { tool = JSON.parse(tool); } catch { tool = { input: tool }; } }
37
+ const toolName = ev.tool_name || ev.toolName || "";
38
+
39
+ // The files this edit touched -> the text it brought in (null: the whole file is new).
40
+ const files = new Map();
41
+ const fresh = [tool.new_string, tool.newString, ...(Array.isArray(tool.edits) ? tool.edits : [])
42
+ .map(e => e && (e.new_string ?? e.newString))].filter(s => typeof s === "string" && s);
43
+ const whole = WRITE_TOOLS.test(toolName) || !fresh.length;
44
+ for (const key of PATH_KEYS) {
45
+ if (typeof tool[key] === "string" && tool[key]) files.set(resolve(cwd, tool[key]), whole ? null : fresh.join("\n"));
46
+ }
47
+ // Codex apply_patch: "*** Update File: src/Card.tsx" then "+added line" rows.
48
+ const strings = [];
49
+ (function walk(v) {
50
+ if (typeof v === "string") strings.push(v);
51
+ else if (Array.isArray(v)) v.forEach(walk);
52
+ else if (v && typeof v === "object") Object.values(v).forEach(walk);
53
+ })(tool);
54
+ for (const s of strings) {
55
+ for (const block of s.split(/^(?=\*\*\* (?:Add|Update|Delete) File: )/m)) {
56
+ const m = block.match(/^\*\*\* (Add|Update) File: (.+)$/m);
57
+ if (!m) continue;
58
+ const added = block.split("\n").filter(l => l.startsWith("+") && !l.startsWith("+++")).map(l => l.slice(1));
59
+ files.set(resolve(cwd, m[2].trim()), m[1] === "Add" ? null : added.join("\n"));
60
+ }
61
+ }
62
+ const targets = [...files].filter(([f]) => UI.has(extname(f).toLowerCase()) && existsSync(f));
63
+ if (!targets.length) quit();
27
64
 
28
65
  // Project context (written by "init"): slop-scan reads its scales and allowed rules itself.
29
- const cwd = ev.cwd || process.cwd();
30
66
  const opts = [];
31
67
  const ctxPath = join(cwd, ".unslop", "context.md");
32
68
  if (existsSync(ctxPath)) {
@@ -35,8 +71,8 @@ if (existsSync(ctxPath)) {
35
71
  }
36
72
 
37
73
  let out = null;
38
- for (const py of ["python3", "python"]) {
39
- const r = spawnSync(py, [SCAN, file, "--json", ...opts], { encoding: "utf8", timeout: 15000 });
74
+ for (const py of process.platform === "win32" ? ["py", "python", "python3"] : ["python3", "python"]) {
75
+ const r = spawnSync(py, [SCAN, ...targets.map(([f]) => f), "--json", ...opts], { encoding: "utf8", timeout: 15000 });
40
76
  if (r.error) continue; // not installed under this name
41
77
  if (r.status !== 0) quit(); // a bad --allow in context.md, etc.: stay out of the way
42
78
  out = r.stdout;
@@ -46,29 +82,34 @@ if (!out) quit();
46
82
 
47
83
  let hits;
48
84
  try { hits = JSON.parse(out).hits; } catch { quit(); }
49
- // After an Edit, only what the edit brought in: hits on the lines its new text now spans
50
- // (a partial-line edit counts its whole line).
51
- const fresh = [tool.new_string, ...(tool.edits || []).map(e => e.new_string)].filter(Boolean);
52
- if (fresh.length && ev.tool_name !== "Write") {
53
- const text = readFileSync(file, "utf8");
54
- const touched = new Set();
55
- for (const ns of fresh) {
56
- for (let at = text.indexOf(ns); at !== -1; at = text.indexOf(ns, at + Math.max(1, ns.length))) {
57
- const first = text.slice(0, at).split("\n").length;
58
- const last = first + ns.split("\n").length - 1;
59
- for (let n = first; n <= last; n++) touched.add(n);
85
+
86
+ // After an edit, only the lines its new text now sits on (a partial-line edit counts its whole line).
87
+ const touched = new Map();
88
+ for (const [f, text] of targets) {
89
+ if (text === null) continue;
90
+ const body = readFileSync(f, "utf8");
91
+ const lines = new Set();
92
+ // Every non-empty piece counts, even "3": a short value is a common UI edit. A short piece may
93
+ // also match other lines; reporting a few extra beats missing what the edit added.
94
+ for (const piece of text.split("\n").map(l => l.trim()).filter(Boolean)) {
95
+ for (let at = body.indexOf(piece); at !== -1; at = body.indexOf(piece, at + piece.length)) {
96
+ lines.add(body.slice(0, at).split("\n").length);
60
97
  }
61
98
  }
62
- hits = hits.filter(h => touched.has(h.line));
99
+ touched.set(f, lines);
63
100
  }
101
+ hits = hits.filter(h => {
102
+ const lines = touched.get(resolve(h.file));
103
+ return !lines || lines.has(h.line);
104
+ });
64
105
  if (!hits.length) quit();
65
- hits.sort((a, b) => a.line - b.line);
106
+ hits.sort((a, b) => (a.file === b.file ? a.line - b.line : a.file < b.file ? -1 : 1));
66
107
 
67
- const rel = relative(cwd, file) || file;
68
- const shown = hits.slice(0, MAX).map(h => `- line ${h.line}: ${h.ref} ${h.rule} — ${h.description}`);
69
- const more = hits.length > MAX ? `\n- … ${hits.length - MAX} more (python3 scripts/slop-scan.py ${rel})` : "";
70
- const note = `unslop-design found ${hits.length} slop pattern${hits.length === 1 ? "" : "s"} in what you just wrote to ${rel}:\n` +
108
+ const shown = hits.slice(0, MAX).map(h => `- ${relative(cwd, resolve(h.file)) || h.file}:${h.line}: ${h.ref} ${h.rule} — ${h.description}`);
109
+ const more = hits.length > MAX ? `\n- … ${hits.length - MAX} more (run scripts/slop-scan.py on the same files)` : "";
110
+ const note = `unslop-design found ${hits.length} slop pattern${hits.length === 1 ? "" : "s"} in what you just wrote:\n` +
71
111
  shown.join("\n") + more +
72
112
  "\nFix them by changing the value or the token (checklist.md has each fix), not by hiding them. " +
73
113
  "If one is a written project decision, it belongs in .unslop/context.md under allow:, not in an unslop-ignore.";
74
- process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: note } }));
114
+ const event = ev.hook_event_name || ev.hookEventName || "PostToolUse";
115
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: note } }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "unslop-design",
3
- "version": "1.12.0",
3
+ "version": "1.13.0",
4
4
  "description": "Make your app or site stop looking AI-generated: install the agent skill, scan UI code for slop and score it 0-100.",
5
5
  "license": "MIT",
6
6
  "author": "Marcos Novo (https://github.com/marcosnovo)",