Plugin · 42 files
unslop
Three Claude Code skills for reviewing AI-generated writing, code and website design, with scanners and manual checks.
Use AI to draft something and it often comes out sounding like AI: the same words, the same rhythm, the same stock look everyone else gets. unslop is three tools that flag those repeated patterns, one for writing, one for code, one for web design. Each works in two ways. While you draft, it helps you set your own direction before anything is generated. When you review, a scanner checks configured patterns and a manual review covers meaning, structure and layout. Claude can start each tool during related work, or you can run it by name, and you can mark a pattern you chose on purpose with unslop-ignore so the scanner skips it.
The tools leave style choices to you. They flag the patterns, and you choose changes that fit your own voice, conventions and brand.
What you get
- a-unslop-text for reader-facing prose: docs, posts, commit bodies, emails.
- a-unslop-code for source that reads tutorial-shaped or machine-written.
- a-unslop-ui for web UI stuck on a stock default look.
Each linked page carries the full case for its skill: what it catches, what it deliberately refuses to do, and the trap it watches for that the obvious fix walks into.
Version 1.5.0 updates all three against 2026 research. The writing tool can compare a rewrite with the original and list any number, URL, negation or modal verb that went missing or appeared (--compare), the code tool flags diffs that weaken tests, and the design tool knows the newer stock looks, not just the old purple gradients.
Every scanner reports file, line, and fix, plus a severity-weighted score, and exits non-zero on high-severity findings so a CI job can stop when it fails. All three tell catalogs and scanner designs are adapted from the vibecoded-design-tells research (MIT), a large-scale study of what people actually name when they call something AI-written, AI-coded, or AI-designed.
What's in the bundle
.claude-plugin/plugin.json1.1 KB
{
"name": "unslop",
"displayName": "Unslop: Writing, Code and Web Design Cleanup",
"description": "Review and revise writing, code and websites that read as generic AI output. Three scanners for prose, source code and web design, guidance for what a scanner can't see, and a method for building a voice profile from your own writing.",
"version": "1.5.0",
"author": {
"name": "Ivan Misic",
"url": "https://ivanmisic.net"
},
"homepage": "https://ivanmisic.net/toolshed/plugins/unslop",
"repository": "https://github.com/imisic/claude-marketplace",
"license": "MIT",
"keywords": [
"writing",
"editing",
"writing-style",
"ai-writing",
"code-quality",
"code-review",
"web-design",
"ui",
"design"
],
"documentationUrl": "https://github.com/imisic/claude-marketplace/tree/main/plugins/unslop#readme",
"privacyPolicyUrl": "https://github.com/imisic/claude-marketplace/tree/main/plugins/unslop#privacy",
"supportUrl": "https://github.com/imisic/claude-marketplace/issues",
"termsOfServiceUrl": "https://github.com/imisic/claude-marketplace/blob/main/LICENSE"
}
CHANGELOG.md2.8 KB
# unslop changelog
## 1.5.0
All three tools are updated against 2026 research on what people now call AI-written, AI-coded and AI-designed.
- `a-unslop-text` separates evidence-backed patterns from style preferences, so it flags fewer harmless words. It also catches newer patterns: staged reveals ("The result:"), tacked-on significance ("highlighting the importance of"), leftover citation markup from chat tools, and "not just X, it's Y" in its variants. A new `--compare ORIGINAL REWRITE` mode lists the numbers, URLs, negations and modal verbs that a rewrite dropped or added.
- `a-unslop-code` checks diffs for weakened tests (`--diff` or `--diff-base REF`): removed assertions, newly skipped tests, `assert True`. It is much quieter on hand-written code: doc comments, ordinary names and `??` defaults no longer count.
- `a-unslop-ui` knows the newer defaults: the cream, serif and terracotta look, near-black with one acid accent, and template details such as all-caps eyebrows and arrow buttons. Commented-out CSS no longer counts.
- Every scanner ships clean and dirty test fixtures. Project scans skip `fixtures` folders; pass a fixture path directly to scan it.
## 1.4.3
The skills now call their scanners through `${CLAUDE_SKILL_DIR}`, so they run from your project directory instead of depending on the current working directory. The README opens with installation and requirements, uses full command names (`/unslop:a-unslop-text`), and explains the tools in plainer words.
## 1.4.2
Clearer name, description and keywords for the plugin directory. The README now opens by saying plainly what the plugin does and for whom, and its privacy section separates what the plugin does from how Claude itself handles your conversation. Skill descriptions reworded for accuracy; no behaviour changes.
## 1.4.1
`a-unslop-code` and `a-unslop-ui` now ship regression tests (`tests/`, run with `python3 -m unittest`) covering the false positives that were fixed and the true positives each fix had to keep. `a-unslop-ui` documents which directories its scanner skips and how to scan one of them anyway. `a-unslop-text` says when not to load it: tiny labels, routine code comments and one-line edits.
## 1.4.0
The text scanner and its reference catalog now carry the latest rules, exceptions, and structural review guidance.
## 1.3.1
The README now says which commands you get after installing.
## 1.3.0
The skills in this plugin now carry an `agents/openai.yaml` sidecar, so they show up in Codex's skill picker with a proper name and one-line description instead of a raw folder name. All three stay implicitly invocable, so Codex reaches for them while you write, the same as Claude Code does.
## Earlier
Versions before this predate this file. See the git history at https://github.com/imisic/claude-marketplace.
README.md5.9 KB
# unslop unslop helps writers, developers and web designers revise output that reads as generic AI work. It checks prose, source code and web design for the specific patterns that make something look machine-made, then guides changes that fit your voice, your project's conventions or your brand. Each of the three skills has a scanner you can run, which prints the file, line and a suggested fix for every match, and a review pass for what a scanner can't see, such as rhythm and layout. Mark a deliberate choice with `unslop-ignore` and the scanner leaves it alone. Once it is listed, you can also add it from Anthropic's plugin directory: **Customize > Plugins** in claude.ai, or `/plugin` in Claude Code. ## Install ``` /plugin marketplace add imisic/claude-marketplace /plugin install unslop@imisic ``` Then the commands are `/unslop:a-unslop-text`, `/unslop:a-unslop-code` and `/unslop:a-unslop-ui`. You install the plugin, you run the skills. Needs Python 3 for the scanners. Output is findings in the terminal (file, line, fix), or JSON with `--json`. The longer write-up lives on the storefront: [ivanmisic.net/toolshed/plugins/unslop](https://ivanmisic.net/toolshed/plugins/unslop). The tools flag repeated patterns in AI-generated writing, code and design. You choose changes that fit your own voice and project. The scanners check configured patterns; a manual review covers meaning, structure and layout. ## The three skills | Skill | Surface | Scanner | |---|---|---| | `a-unslop-text` | Prose: docs, READMEs, posts, commit bodies, emails | `unslop_text_scan.py` | | `a-unslop-code` | Source code, any language | `unslop_code_scan.py` | | `a-unslop-ui` | Web UI: HTML/CSS/JS/JSX/Vue/Svelte/Astro | `devibe_scan.py` | Each scanner reports findings with file, line, and fix, plus a severity-weighted score, and exits non-zero on high-severity findings so a CI job can stop when it fails. ## a-unslop-text Catches the em dash, banned corporate/AI diction (`delve`, `leverage`, `utilize`, `robust`, `paradigm`...), the "it's not just X, it's Y" cadence, sycophantic openers, bookending, and leftover assistant boilerplate. Flags the over-corrected 2026 register too (forced staccato fragments, fake typos) so you don't trade one tell for another. Also ships `references/voice-profile.md`: a method for building a voice profile from your own writing from before you used AI: the phrasing habits you repeat, the tone you use for each destination, and the vocabulary level you actually write at. A draft with every pattern removed is clean, but it still needs to sound like you. Build mode loads the profile when the byline is yours. A matching scanner rule flags literary vocabulary (`whilst`, `endeavour`, `notwithstanding`) that reads as out of place when the author's real register is plainer, which is common for non-native writers. Inside Claude Code the skill runs its scanner for you. To run one by hand from a clone of this repo, start in `plugins/unslop/`: ```bash python3 skills/a-unslop-text/scripts/unslop_text_scan.py <path> python3 skills/a-unslop-text/scripts/unslop_text_scan.py <path> --severity high ``` ## a-unslop-code Sorts every tell into bugs (swallowed errors, a made-up API, a left-in stub), substance (tutorial-shaped boilerplate, over-engineering, code that ignores the repo), and cosmetic (emoji in source, narrating comments, generic `process_data` names, pasted chat text). Says plainly that the loudest tells are structural and need a compiler or a human, not a regex. ```bash python3 skills/a-unslop-code/scripts/unslop_code_scan.py <path> python3 skills/a-unslop-code/scripts/unslop_code_scan.py <path> --severity high ``` ## a-unslop-ui Flags both the 2024 default (shadcn/Tailwind stock theme, AI-purple, gradient text, unprompted neon glow, emoji-as-icons, the centered-hero-plus-three-cards skeleton) and the 2026 "tasteful default" (cream background, serif display face, sage-green accent) that anti-slop advice itself created. Prescribes no palette or font; asks that whatever you use be a choice you can justify. ```bash python3 skills/a-unslop-ui/scripts/devibe_scan.py <path> python3 skills/a-unslop-ui/scripts/devibe_scan.py <path> --severity high ``` ## Use Claude can start each skill during related work (writing prose, generating or reviewing code, building or styling UI), or you can run it by name. Run the matching scanner as a final check; read the linked `references/tells.md` (and `references/choosing-a-look.md` / `references/writing-with-intent.md` / `references/voice-profile.md` / `references/fitting-the-codebase.md`) for the tells a scanner cannot see. ## Examples - `Review docs/launch-post.md with a-unslop-text and rewrite anything that reads machine-written.` - `Run a-unslop-code over src/ and fix the bug-class findings before anything cosmetic.` - `Check templates/landing.html with a-unslop-ui for stock AI-default design and propose a deliberate alternative.` ## Privacy Everything runs on your machine. The skills read the files you point them at, the scanners are standard-library Python that print findings to your terminal, and the plugin itself collects nothing, stores nothing outside your project and sends nothing anywhere. There is no telemetry. Your conversation with Claude is processed by Anthropic under its usual terms; that is separate from the plugin. Retention: the plugin's author never receives any of it, and the only thing kept is what the plugin writes in your own project, which you can delete at any time. ## Support Questions, bugs or a security concern: open an issue at https://github.com/imisic/claude-marketplace/issues, or email hello@ivanmisic.net. ## Credits All three tell catalogs and scanner designs are adapted (MIT) from the vibecoded-design-tells research by JCarterJohnson (https://github.com/JCarterJohnson/vibecoded-design-tells), a large-scale analysis of what people actually name as AI-writing, AI-code, and AI-website giveaways. Each `SKILL.md` and scanner header credits it directly.
skills/a-unslop-code/SKILL.md7.8 KB
---
name: a-unslop-code
description: "Finds what makes source code read as AI-written and points you at the parts that actually ship bugs. Sorts every tell into three buckets and fixes them in that order: bugs (swallowed errors, a made-up API, a left-in \"rest of the code\" stub), substance (tutorial-shaped boilerplate, over-engineering, code that ignores the surrounding repo), and cosmetic (emoji in source, a comment narrating the obvious, a generic process_data name, chat text pasted into a file). Ships a scanner for the surface tells and says plainly that the loudest ones are structural and need a compiler or a human. Use when writing, generating, reviewing, refactoring, or auditing code, and when the user says it \"looks AI-written,\" \"reads like a tutorial,\" \"is too generic,\" or \"de-slop this.\" Trigger even if \"AI tell\" is never said."
---
# a-unslop-code
Part of the unslop family (see `a-unslop-text`, `a-unslop-ui`). Same shape: one global source, an auto-trigger, a Build mode and an Audit mode, a scanner that counts HIGH findings in its exit code, and an `unslop-ignore` line escape. This one is about code.
**What it is not.** It does not write good code and it has no house style. It removes the surface cues that read as machine-generated, and it points at the deeper tells that ship bugs, the ones no scanner catches. Whether the code is correct and right for the problem is still your call.
## Sort every tell before you fix it
One question sets the order of work: is the code wrong, wrong for the job, or does it just look machine-made?
- **Bug.** A swallowed exception hides a failure you needed. A made-up API will not run. A `// rest of your code` stub means the file is unfinished. Fix these because the code is broken, the same as any bug, whether or not anyone suspected AI.
- **Substance.** Not a local bug, wrong for the job: tutorial-shaped boilerplate, an abstraction with one caller, a 2000-line change that should have been 50 because it ignored the repo. A compiler passes these; a reader comparing the diff to the neighbouring code does not.
- **Cosmetic.** The chat voice leaking into the file: emoji, a comment that restates the next line, a `process_data` doing eleven things, pasted "Good catch!" text. Worth removing, but nothing breaks if one survives.
The ranking behind this is blunt: the structural tells (tutorial shape, made-up APIs) lead by a wide margin, and the cosmetic ones people argue about sit far down. So the surface scan is the cheap part, not the job. A clean scan is not clean code.
## How it fits your setup
If your project already has house rules for substance (smallest code that solves the problem, no abstraction for single-use code, surgical changes, comment the why not the what, no commented-out code, no v2/v3 files, remove orphaned imports), this skill does not restate them. It is the audit layer that catches a violation of them, plus the scanner for the cosmetic tells. If no-emoji and no-em-dash are already house rules for you, the scanner flags emoji in source on top of that.
## Build mode
Most "looks AI-written" output is an under-specified prompt, not a style problem. The average of public code is the tutorial. Before generating, set three things:
- **The surrounding code.** Give the model the file it will sit beside, the nearest sibling that does something similar, and how the repo handles errors, logging, and naming. This one input does more than the rest combined. The single most repeated fix in the data was "make it follow the existing code instead of guessing the average."
- **The real requirement.** What the code has to do, including the failure modes and the real integration, not the demo. A vague ask gets the sample-app shape: one page, dummy data, no backend.
- **Calls that exist.** Generated code invents plausible APIs. Plan to run it and check every import and method against real docs.
`references/fitting-the-codebase.md` is the method.
## Audit mode
Order matters, because the scanner is blind to the worst tell.
1. **Run what only code lets you run.** Code can be executed, and that is the strongest tool you have. Build it, type-check it, lint it, resolve every import and call against real docs. This is how the made-up API surfaces, and no regex sees it. Python: `py_compile`, `ruff` or `pyflakes`, `mypy`, plus a real import. JS/TS: `tsc --noEmit`, `eslint`, `node --check`. Go: `go build ./...` and `go vet`. Rust: `cargo check` and `cargo clippy`. If it will not build, or a call resolves to nothing, fix that first.
2. **Run the scanner** for the surface tells.
```bash
python3 "${CLAUDE_SKILL_DIR}/scripts/unslop_code_scan.py" <path> # report + slop score
python3 "${CLAUDE_SKILL_DIR}/scripts/unslop_code_scan.py" <path> --severity high # strongest only
python3 "${CLAUDE_SKILL_DIR}/scripts/unslop_code_scan.py" <path> --json # structured findings
git diff | python3 "${CLAUDE_SKILL_DIR}/scripts/unslop_code_scan.py" --diff # test integrity
python3 "${CLAUDE_SKILL_DIR}/scripts/unslop_code_scan.py" --diff-base REF # git diff REF
```
It covers Python, JS/TS, Java, Go, Rust, Ruby, PHP, C/C++, C#, and more. Each finding carries a class (bug, substance, or cosmetic) and a fix. Cosmetic findings are advisory; only bug-class HIGHs should gate review. The compatible exit code still counts all HIGH findings, so a gate must filter JSON findings by class and severity. Review the advisory findings in context.
`python3 -m unittest discover -s tests` covers the precision rules. Run it after touching a pattern; several exist only to keep a specific false positive dead. Test names are exempt from the verbose-identifier rule, because a test name is a sentence on purpose.
3. **Read the diff** for tutorial shape, over-engineering, trusted-path defensive probing, duplicated helpers, and whether the code matches the repo. For agent-written diffs, use `--diff` (stdin) or `--diff-base REF` to flag removed assertions, added skips, and constant-true checks in test files. Then check what the scanner cannot: fallbacks that hide invalid absence, tests asserting only their own mocks, production branches special-casing test inputs, hardcoded expected outputs, and evaluator monkeypatches. `references/tells.md` covers the limits and sources.
**Escape hatch.** A line with `unslop-ignore` is skipped, for a real decision (a broad catch at a boundary, an emoji in a CLI banner).
## The over-correction trap
Told to "write clean code" or "make this not look AI," a model over-produces: a null check for a case that cannot happen, a type on every local, a comment on every block, a factory for a thing with one caller. That is performed seniority, and it reads as AI for the same reason boilerplate does. The cure is the same anchor as the rest: match the level the surrounding code operates at. Add nothing the neighbouring code would not have.
## Fixing well
Renaming `process_data` to `processDataFunction` is a different tell, not a fix. Name it for what it does, the way the repo names things. Code has little aesthetic room: the question is almost always "is it correct, and does it match this project," not "which look do I want."
## Reporting
Lead with the verdict and the single highest-impact change. Findings by priority with file:line and the fix, bug-class first. Close with the slop score and a reminder that the structural tells still need a compiler or a human.
## Credits
The tell catalog and its ranking come from the vibecoded-design-tells research by JCarterJohnson (https://github.com/JCarterJohnson/vibecoded-design-tells, MIT), which mined Reddit for what developers name as AI-code giveaways. This skill rewrites that material into the unslop family: one skill per surface, a shared bug/substance/cosmetic split as its spine, and a shared Build/Audit shape with the text and ui skills. `scripts/unslop_code_scan.py` is an adapted fork of that project's scanner (MIT); the credit is in its header.
skills/a-unslop-code/agents/openai.yaml103 B
interface: display_name: "Unslop Code" short_description: "Catch AI tells and real bugs in source"
skills/a-unslop-code/references/fitting-the-codebase.md3.0 KB
# Making code fit the repo Code reads as AI because the model reaches for the most common pattern in its training set instead of the one your project uses. Any fixed style applied by default is just a different average. So this is how to make code fit the project, which is the property that stops it reading as machine-made. Code has little aesthetic room. The question is almost never which look you want; it is whether the code is correct and matches what the project already does. Fit is the standard, not taste. ## Feed it the repo The input that does the most work is the repo itself. Before generating, give the model the file it will sit beside, the nearest sibling that already does something similar, and the conventions (how errors are handled, how things log, how modules are structured, the naming). A change that follows the patterns is small and invisible. One that ignores them is the 2000-line change that should have been 50. On a brand-new project with no precedent, make one deliberate decision and write it down (a short conventions note the model can read), rather than letting each file invent its own. The tell is not any one pattern; it is the absence of a chosen one. ## State the requirement, not the demo Name the real inputs, the real failure modes, the real integration before generating. Tutorial-shaped code is the loudest tell because the model falls back to the sample-app shape when the ask is vague. If you cannot state the requirement, you will get the demo. ## Run what only code lets you run The tells that bite are the ones no scanner sees, and code has one advantage prose and design do not: you can execute it. Two checks catch most: - Does it call anything that does not exist? Build it, type-check it, resolve every import and method against real docs, not the model's confidence. `tsc --noEmit` and `eslint`, `mypy` and a real import, `go build ./...` and `go vet`, `cargo check` and `cargo clippy`. - Does it match how this repo does things? Read the diff against the neighbouring code. A new logging style or a new structure mid-file is the mismatch tell. If you cannot explain a line the model wrote, do not ship it. ## Do not over-correct "Write clean code" or "do not look AI" backfires into over-production: checks for cases that cannot happen, a type on every local, a comment on every block, a layer for one caller. That is performed seniority, and it reads as AI for the same reason boilerplate does. Match the level the surrounding code operates at. Add nothing the neighbouring code would not have. ## Escape hatch A pattern chosen on purpose is not a tell. A project may want a broad catch at a boundary, an emoji in a CLI banner, a `process_data` step in a throwaway script. The skill flags unchosen defaults, not banned constructs. Mark a real decision `unslop-ignore`. ## One line Feed the model the surrounding code and tell it to match it, then run the result and check every call is real. The scanner removes the surface tells; this removes the ones that ship bugs.
skills/a-unslop-code/references/tells.md11.9 KB
# AI-code tells: the catalog
The scanner (`scripts/unslop_code_scan.py`) finds surface patterns and test-integrity risks. These are review candidates, not proof of authorship or measured scanner precision. The original catalog comes from the Reddit research credited in `SKILL.md`; later checks have separate sources below. Dates on provenance tags identify the source edition or review month.
Sort by class first. Bug findings point to possible broken behavior; substance findings need the requirement and repo context; cosmetic findings are advisory. Only bug-class HIGHs should gate review. The CLI preserves its existing exit code, the count of all HIGH findings, so gates must filter JSON findings by class and severity. A clean scan still needs execution and human review.
## Human review (no scanner rule)
- **Fallback masking.** Substance. `or {}`, `?? []`, `?? {}`, and `getattr(..., None)` can turn a broken contract into plausible empty data. A regex cannot distinguish that from a valid default, including idiomatic PHP view defaults. Check whether absence is a valid state; if not, fail loudly. (source: code-humanizer, 2026-10)
- **Tutorial-shaped boilerplate.** Substance. Sample data, dummy integrations, or a demo-shaped implementation where the requirement needs the real service. Build against the real requirement; the scanner's dummy-data markers are only a weak proxy. (source: vibecoded-design-tells, 2026-10)
- **Made-up APIs and libraries.** Bug. A plausible import or call does not establish that the dependency or API exists. Build, type-check, run, and check the actual documentation. (source: vibecoded-design-tells, 2026-10)
- **Over-engineering.** Substance. Layers and abstractions without a requirement. Compare the change to a direct implementation and the surrounding code before deleting them. (source: vibecoded-design-tells, 2026-10)
- **Ignoring the surrounding repo.** Substance. A new logging style, error pattern, or structure that duplicates or conflicts with local conventions. Read the nearest sibling and match it. (source: vibecoded-design-tells, 2026-10)
- **Mixed skill level.** Substance. Advanced patterns beside basic mistakes warrant a closer read. Require an explanation and evidence that the code works. (source: vibecoded-design-tells, 2026-10)
- **Too clean, no human mess.** A weak, contested complaint, not a reason to add quirks. A clean surface does not end a correctness review. (source: vibecoded-design-tells, 2026-10)
- **Defensive probing on trusted internal paths.** Substance. Review `isinstance`/`hasattr` ladders, repeated null checks after validation, and try/except around internal invariants. If the contract already guarantees the value, remove checks that hide a broken invariant. Validation at trust boundaries remains exempt. (source: Cursor deslop, 2026-10)
- **Duplicating an existing helper.** Substance. A broad complaint about reinventing the wheel is not enough, but concrete duplication of an existing helper is a review finding. Search the repo and reuse the helper when its contract fits. (source: Cursor deslop; code-humanizer, 2026-10)
- **Tests asserting only their own mocks.** Bug review. Trace assertions to the real system under test. A test that supplies a mock value and only checks that same value may never exercise the implementation; mock count alone proves nothing. This needs human review. (source: slopguard, 2026-10)
- **Hardcoded success and evaluator interference.** Bug review. Look for production branches special-casing test inputs, hardcoded expected outputs used instead of computing results, and evaluator monkeypatches. Ordinary expected values in tests are valid. These require human review beyond the diff patterns below. (source: EvilGenie, 2026-05; METR reward hacking, 2025-06)
## Surface rules
Each entry names the scanner rule, its severity, and its class. `unslop-ignore` skips its line.
- **Swallowed errors** (`swallowed-errors`, MEDIUM bug). Python bare, `Exception`, and `BaseException` handlers (including singleton tuples and `builtins` qualification) are checked with indentation-based lookahead. Only empty, `pass`, `...`, or print/log-only bodies are flagged. Re-raises, raises, returns, and real handling are left for review. Inline empty or comment-open catches in JS/TS, Java, and C#, Ruby `rescue => name` headers, and Go's single-line empty or comment-open error blocks retain their surface checks. Rust `.unwrap()`/`let _ =` and multi-line empty catches or Go blocks need a human. (source: vibecoded-design-tells; Ruff BLE001, 2026-10)
- **Placeholder stubs** (`placeholder-comment`, HIGH bug). `// rest of your code`, `# your logic here`, `// implementation goes here`, or `# TODO: implement` can mark unfinished code. Write the implementation or explain an intentional example with `unslop-ignore`. (source: vibecoded-design-tells, 2026-10)
- **Emoji in source** (`emoji-in-code`, MEDIUM cosmetic). Emoji in comments, strings, or logs. Remove them unless deliberately chosen, such as a CLI checkmark marked `unslop-ignore`. Emoji logs are counted here rather than also as boilerplate markers. (house preference)
- **Narrating comments** (`narrating-comment`, MEDIUM cosmetic). Full-line `//`, `#`, and `--` comments that restate the immediately following line nearly verbatim (`# increment i` above `i += 1`), or explicitly narrate steps (`Step 1`, `Now we`, `First, we`, `Next, we`, `Finally, we`). Docblock lines are exempt. Single-verb section labels above a block are allowed. (source: vibecoded-design-tells, 2026-10)
- **Generic placeholder names** (`generic-naming`, MEDIUM cosmetic). `process_data`, `handle_data`, `do_stuff`, and related placeholders. Name the function for its actual job; check whether it does too much. (source: vibecoded-design-tells, 2026-10)
- **Pasted chat artifacts** (`chat-artifact`, HIGH cosmetic). Code fences, `Here's the updated code`, `As an AI`, or `Good catch!`. Assistant residue includes first-person change reports such as `I have updated` or `I've added`, `as requested`, `here is the updated code`, `let me know`, `hope this helps`, and reader instructions such as `replace the token before running` or `don't forget to`. An invariant such as `# Note: writes must remain atomic` is allowed. (source: vibecoded-design-tells, 2026-10)
- **Whole-sentence identifiers** (`verbose-naming`, LOW cosmetic). Definitions with at least six word segments, such as `getUserDataFromApiResponseHandler`. `WebSite` and `JsonLd` each count as one compound segment. Calls and HTML IDs are excluded. Trim only when the precise job survives; test names and uppercase constants are exempt. (source: vibecoded-design-tells, 2026-10)
- **Dummy-data markers** (`boilerplate-marker`, LOW cosmetic). Placeholder API keys, `lorem ipsum`, sample identities, `example.com`, and `Here we go` logs. `example.com` in comments, HTML form placeholders, or visible HTML text is exempt. Inspect their purpose before replacing them. Plain `Successfully...` and `Done!` logging is not flagged. (source: vibecoded-design-tells, 2026-10)
- **Checker suppression** (`checker-suppression`, MEDIUM bug, advisory). `# type: ignore`, `# noqa`, `@ts-ignore`, `@ts-expect-error`, `eslint-disable`, `as any`, `as unknown as`, and `: any` annotations without a same-line reason. Directives must be in real comments; casts and annotations must be outside strings, comments, and visible markup text. Fix the underlying error or add a reason. Codes and target types alone are not reasons; `# noqa: E501 reason` and `// @ts-expect-error: upstream types wrong` are exempt. Casts need a comment explaining the reason. (source: Cursor deslop, 2026-10)
- **Change narration** (`change-narration`, MEDIUM cosmetic). Comments beginning `Updated/Changed/Modified/Fixed/Refactored to/from/so/the`, or `Now uses`, `Previously this/was`, `was changed to`, `Old:`, `New:`. Strings and continuing requirements such as `Previously computed values must remain available` are exempt. Remove edit history or explain the continuing reason for the code. (source: code-humanizer, 2026-10)
- **Repo debris** (`repo-debris`, MEDIUM cosmetic). Files named `IMPLEMENTATION_SUMMARY.md`, `*_SUMMARY.md`, `COMPLETED.md`, `CHANGES_MADE.md`, or `FIX_NOTES.md` at any scanned depth. Check filenames only, not Markdown contents; retain files with a continuing documentation purpose. A first-line `unslop-ignore` exempts the filename finding. Existing skipped directories stay skipped; `tests/` stays in normal scan scope, but `fixtures` directories are excluded from project traversal; a direct path still scans them. (house preference)
## Test-integrity diff rules
Run `git diff | python3 "${CLAUDE_SKILL_DIR}/scripts/unslop_code_scan.py" --diff` or `python3 "${CLAUDE_SKILL_DIR}/scripts/unslop_code_scan.py" --diff-base REF`. The latter runs `git diff REF` in the supplied path (or the current repo). These modes run only the test-integrity rules, not the normal surface scan. They preserve the JSON fields and count only test files with hunk lines in `files_scanned`.
Test paths match `test_*`, `*_test.*`, `*.test.*`, `*.spec.*`, or files under `tests/` and `__tests__/`. Findings use the old line number for deletions and the new line number for additions. Only executable assertions, skip calls, and decorators count. Quoted data, comments, context lines, production files, and lines carrying `unslop-ignore` are ignored. Treat flags as requests to inspect the requirement and any replacement checks, not proof of cheating.
- **Removed assertions** (`test-assertion-removed`, HIGH bug). Removed `assert`, assertion calls, or `expect(...)` lines. Confirm a replacement check or a requirement change; moving an assertion can still flag. (source: EvilGenie, 2026-05; METR reward hacking, 2025-06)
- **Added skips** (`test-skip-added`, HIGH bug). Added pytest skip/skipif/xfail calls or decorators, unittest skip decorators, it/test/describe `.skip`, `xit`/`xdescribe`, `@Disabled`, Go `t.Skip`/`t.Skipf`/`t.SkipNow`, or PHPUnit `markTestSkipped`/`markTestIncomplete`. Require a reason tied to the requirement before weakening coverage. (source: EvilGenie, 2026-05; METR reward hacking, 2025-06)
- **Added tautologies** (`test-tautology-added`, HIGH bug). Added `assert True` or `expect(true).toBe(true)`, including whitespace and parentheses variants and an expectation continued on the next added line. Check an observable result from the implementation instead. (source: EvilGenie, 2026-05; METR reward hacking, 2025-06)
## Do not chase without context
- **Bare debug or success logging.** The research did not establish ordinary `print`/`console.log` or `Successfully...` messages as reliable code defects. Deliberate logging is allowed; separately matched placeholders or emoji still receive their own findings. (source: vibecoded-design-tells, 2026-10)
- **Validation at trust boundaries.** Validate untrusted input and external responses. Review defensive probing only where an internal contract already guarantees the value. (source: Cursor deslop, 2026-10)
## Sources
- [vibecoded-design-tells](https://github.com/JCarterJohnson/vibecoded-design-tells/tree/main/unslop-ai-code), original MIT catalog and scanner credit. Its discussion classifications do not establish scanner precision.
- [EvilGenie, arXiv 2511.21654](https://arxiv.org/abs/2511.21654), revised May 2026, test editing and hardcoded test cases.
- [METR reward hacking](https://metr.org/blog/2025-06-05-recent-reward-hacking/), June 2025, scoring and evaluator interference.
- [Cursor deslop](https://github.com/cursor/plugins/blob/main/cursor-team-kit/skills/deslop/SKILL.md), trusted-path defensive checks and checker bypasses. <!-- ship-allow: public upstream source URL -->
- [code-humanizer](https://github.com/LeonardNJU/code-humanizer/blob/main/SKILL.md), practitioner guidance for fallbacks, existing helpers, and change narration.
- [slopguard](https://github.com/WT-MM/slopguard), mock-echo and mock-only review candidates.
- [Ruff BLE001](https://docs.astral.sh/ruff/rules/blind-except/), handling and re-raise distinctions for broad Python exceptions.
skills/a-unslop-code/scripts/unslop_code_scan.py30.0 KB
#!/usr/bin/env python3
"""
Scan source code for surface tells and test diffs for weakened checks.
Adapted (MIT) from github.com/JCarterJohnson/vibecoded-design-tells, whose Reddit study catalogs developer complaints. Those classifications do not measure scanner precision. Severity sets review priority; class separates bug, substance, and cosmetic findings. Cosmetic findings are advisory. Only bug-class HIGHs should gate review, but the compatible CLI exit code counts all HIGH findings. Structural problems still need execution and human review; see references/tells.md.
Usage:
python3 unslop_code_scan.py <path>
python3 unslop_code_scan.py <path> --severity high
python3 unslop_code_scan.py <path> --json
python3 unslop_code_scan.py <path> --max 8
git diff | python3 unslop_code_scan.py --diff
python3 unslop_code_scan.py --diff-base REF
A line containing unslop-ignore is skipped. Exit code is the number of HIGH findings (0 = none); invalid input exits 2.
"""
import os, re, sys, json, argparse, ast, textwrap, subprocess
EXTS = {".py", ".js", ".jsx", ".ts", ".tsx", ".java", ".go", ".rs", ".rb", ".php",
".c", ".h", ".cpp", ".cc", ".hpp", ".cs", ".kt", ".kts", ".swift", ".scala",
".m", ".mm", ".sh", ".bash", ".lua", ".dart", ".vue", ".svelte", ".sql", ".r"}
SKIP_DIRS = {"node_modules", ".git", "dist", "build", ".next", "out", "vendor", "target",
"coverage", ".venv", "venv", "__pycache__", ".idea", ".gradle", "bin", "obj",
"fixtures"} # test fixtures quote tells on purpose; scan one by path to include it
W = {"high": 3, "medium": 2, "low": 1}
# Comment openers across common languages. The SQL/Lua `--` must be followed by a space,
# or every shell long-flag (`--create`, `--comments`) reads as a comment about creating.
CMT = r"(?://|\#|/\*|\*|--(?=\s)|<!--)"
EMOJI = ("\U0001F300-\U0001FAFF\U00002600-\U000027BF\U0001F000-\U0001F0FF"
"\U00002B00-\U00002BFF\U0001F900-\U0001F9FF\U00002764")
DEBRIS = r"(?:IMPLEMENTATION_SUMMARY|.+_SUMMARY|COMPLETED|CHANGES_MADE|FIX_NOTES)\.md"
# Each rule: id, label, severity, class, share (provenance), fix, patterns.
RULES = [
# ---------- HIGH: paste-in artifacts and unfinished code ----------
{"id": "chat-artifact", "label": "Leftover chat / assistant / markdown artifact in the code", "sev": "high", "class": "cosmetic",
"share": "vibecoded-design-tells; assistant-voice matching narrowed locally",
"fix": "Delete the assistant's voice: code fences, 'Here's the updated code', 'As an AI', 'Good catch!', or assistant instructions after 'Note:'.",
"pats": [r"^\s*```", r"\b(?:here's|here is) the (updated|complete|full|fixed|revised|new) (code|version|implementation|file)\b",
r"\bas an? (ai|a\.i\.) (language )?model\b", r"\bas a large language model\b",
r"\b(good|great) catch!", r"\b(?:you['’]re|you are) absolutely right\b",
r"\bi(?:['’]ve| have)?\s+(?:updated|added|changed|fixed|refactored|implemented)\b", r"\bas requested\b",
r"^\s*" + CMT + r"\s*(?:note|remember|important|keep in mind|tip)\b\s*:?\s*(?:you(?:['’]ll| will) need to (?:configure this|add the path|install)\b|to replace the token\b|make sure you run this\b)",
r"\breplace the token before running\b", r"\b(?:don['’]t|do not) forget to\b",
r"\b(certainly|sure)! here('?s| is)\b", r"\bi(?:['’]ll| will) (add|update|fix|implement) .{0,40}\bnow\b",
r"\b(?:i )?hope this helps\b", r"\blet me know\b"]},
{"id": "placeholder-comment", "label": "Placeholder / ellipsis comment left in (\"// rest of your code\")", "sev": "high", "class": "bug",
"share": "vibecoded-design-tells; unfinished-code marker",
"fix": "Write the actual code. These '... rest of the code' stubs mean the file is unfinished, not just untidy.",
"pats": [r"" + CMT + r"\s*\.{2,}\s*(rest|the rest|your|remaining|existing|previous|other)\b",
r"" + CMT + r"\s*(rest|remainder) of (your |the |my )?(code|implementation|logic|function|file|owl)\b",
r"" + CMT + r"\s*(your|the) (code|logic|implementation|stuff) (goes )?here\b",
r"" + CMT + r"\s*(add|insert|implement|put) (your )?(code|logic|implementation) here\b",
r"" + CMT + r"\s*(implementation|code|logic) (goes |go )?here\b",
r"" + CMT + r"\s*existing code (here|unchanged|stays|remains)\b",
r"" + CMT + r"\s*\.\.\. ?\((?:rest|your|the|existing)[^)]*\)",
r"" + CMT + r"\s*TODO:?\s*(implement|add|fill in|finish)\b"]},
# ---------- MEDIUM: the surface tells ----------
{"id": "emoji-in-code", "label": "Emoji in code, comments, strings, logs, or commit text", "sev": "medium", "class": "cosmetic",
"share": "house preference; also cataloged by vibecoded-design-tells",
"fix": "Remove emoji from source. They survive from the model's chat output and read as vibe-coded.",
"pats": [r"[" + EMOJI + r"]"]},
{"id": "swallowed-errors", "label": "Catch-all / swallowed errors (bare except, empty catch, empty Go err block)", "sev": "medium", "class": "bug",
"share": "vibecoded-design-tells; Python handler-body check",
"fix": "Catch specific exceptions and handle them. Empty or log-only handlers hide failures; propagate or handle the error.",
"pats": [r"^\s*except(?:\s+(?:(?:builtins\.)?(?:Exception|BaseException)|\(\s*(?:builtins\.)?(?:Exception|BaseException)\s*,?\s*\))(?:\s+as\s+\w+)?)?\s*:",
r"\bcatch\s*\([^)]*\)\s*\{\s*\}", r"\bcatch\s*\{\s*\}",
r"\brescue\s*=>\s*\w+\s*$", r"\bcatch\s*\([^)]*\)\s*\{\s*//",
r"\bif\s+err\s*!=\s*nil\s*\{\s*\}", r"\bif\s+err\s*!=\s*nil\s*\{\s*//"]},
{"id": "narrating-comment", "label": "Narrating comment that restates the obvious / step-by-step '# Step 1'", "sev": "medium", "class": "cosmetic",
"share": "vibecoded-design-tells; adjacent-line restatement or explicit steps",
"fix": "Cut comments that say what the next line plainly does. Comment why, not what.",
"pats": [r"^\s*(?://|\#|--(?=\s))\s*(?P<comment>\S.*?)\s*$"]},
{"id": "generic-naming", "label": "Generic placeholder function name (process_data, handleData, doStuff)", "sev": "medium", "class": "cosmetic",
"share": "vibecoded-design-tells; placeholder-name subset",
"fix": "Name it for what it actually does in this domain. process_data() that does 11 things is the AI tell.",
"pats": [r"\b(def|function|func|fn|fun|sub)\s+(process_?[Dd]ata|handle_?[Dd]ata|do_?[Ss]tuff|do_?[Ss]omething|my_?[Ff]unction|process_?[Ii]tem|process_?[Ii]nput|main_?[Ff]unction)\b",
r"\b(process_?[Dd]ata|handle_?[Dd]ata|do_?[Ss]tuff|do_?[Ss]omething)\s*\("]},
# ---------- LOW: weak / inflated signals ----------
{"id": "verbose-naming", "label": "Over-verbose, robotically self-documenting identifier", "sev": "low", "class": "cosmetic",
"share": "vibecoded-design-tells; weak, contextual signal", "cs": True,
"fix": "A name that is a whole sentence (getUserDataFromApiResponseHandler) reads as machine-generated. Trim it.",
"pats": [r"^\s*(?:(?:public|protected|private|static|abstract|final|export|default|async|override|open|suspend)\s+)*(?:def|function|func|fn|fun|sub|class)\s+&?(?P<name>[A-Za-z_]\w*)\b",
r"^\s*func\s+\([^)]*\)\s+(?P<name>[A-Za-z_]\w*)\b",
r"^\s*(?:(?:export|public|protected|private|static|readonly)\s+)*(?:(?:const|let|var)\s+)?(?P<name>\$?[A-Za-z_]\w*)\s*(?::[^=;]+)?=(?!=|>)",
r"^\s*(?:(?:public|protected|private|static|async)\s+)*(?P<name>[A-Za-z_]\w*)\s*\([^;{}]*\)\s*(?::[\w<>\[\]|? ]+)?\s*\{",
r"^\s*(?:(?:public|protected|private|static|final|readonly)\s+)*(?!(?:return|throw|new|yield|await|raise)\b)[A-Za-z_]\w*(?:<[^>]+>|\[\]|\?)?\s+(?P<name>\$?[A-Za-z_]\w*)\s*(?:\(|=|;)"],
# A test name is a sentence on purpose: test_returns_none_on_malformed_yaml is the
# convention, not a tell. Left unsuppressed this rule was 30 of 37 findings on a
# clean repo, and its own share note already calls the signal inflated.
"suppress": r"\bdef\s+test|\btest_|\b(it|describe|context|specify)\s*\(|\bfunc\s+Test|@Test\b"},
{"id": "boilerplate-marker", "label": "Boilerplate / dummy-data marker (placeholder keys, sample data)", "sev": "low", "class": "cosmetic",
"share": "vibecoded-design-tells; weak proxy for tutorial-shaped code",
"fix": "Replace generated dummy data and placeholders with the real thing. Tutorial-shaped sample data is the loudest tell, but only a human can judge the shape.",
"pats": [r"\blorem ipsum\b", r"\b(your|my)[-_]?api[-_]?key\b", r"\bYOUR_API_KEY\b", r"\bexample\.com\b",
r"\b(John|Jane) (Doe|Smith)\b", r"['\"]sk-(xxx|your|placeholder|123)",
r"(console\.log|print|println|fmt\.Print\w*|System\.out\.print\w*)\s*\(\s*['\"]Here we go"]},
{"id": "checker-suppression", "label": "Checker suppression without a reason", "sev": "medium", "class": "bug",
"share": "cursor deslop; advisory bypass check",
"fix": "fix the underlying error or add a reason",
"pats": [r"#\s*type:\s*ignore\b(?:\s*\[[^\]]*\])?", r"#\s*noqa\b(?::\s*[A-Z]\d+(?:\s*,\s*[A-Z]\d+)*)?",
r"@ts-(?:ignore|expect-error)\b", r"eslint-disable(?:-next-line|-line)?\b(?:\s+[\w@/.-]+(?:\s*,\s*[\w@/.-]+)*)?",
r"\bas\s+unknown\s+as\b", r"\bas\s+any\b", r":\s*any\b"]},
{"id": "change-narration", "label": "Comment narrates an edit instead of explaining the code", "sev": "medium", "class": "cosmetic",
"share": "code-humanizer; change-narration comments",
"fix": "Remove the edit history or explain the continuing reason for the code.",
"pats": [r"(?:#|//|/\*|\*)\s*(?:(?:Updated|Changed|Modified|Fixed|Refactored)\s+(?:to|from|so|the)\b|Now\s+uses\b|Previously\s+(?:this|was)\b|(?:This\s+)?was\s+changed\s+to\b|Old:|New:)"]},
{"id": "repo-debris", "label": "Possible leftover implementation summary", "sev": "medium", "class": "cosmetic",
"share": "house preference; review whether the file has a continuing purpose",
"fix": "Remove transient implementation notes or keep them only for a continuing documentation purpose.",
"filename": True, "pats": [r"^" + DEBRIS + r"$"]},
{"id": "test-assertion-removed", "label": "Assertion removed from a test", "sev": "high", "class": "bug",
"share": "EvilGenie arXiv:2511.21654; METR reward hacking (2025)",
"fix": "Restore the check or verify that a changed requirement justifies its removal.",
"diff": "-", "pats": [r"(?<![\w.$])assert(?=\s|\()|\b(?:\w+\.)?assert\w*\s*\(|\bexpect\s*\("]},
{"id": "test-skip-added", "label": "Skip or expected-failure marker added to a test", "sev": "high", "class": "bug",
"share": "EvilGenie arXiv:2511.21654; METR reward hacking (2025)",
"fix": "Run the test and fix the failure, or document why the requirement permits skipping it.",
"diff": "+", "pats": [r"@pytest\s*\.\s*mark\s*\.\s*(?:skip|skipif|xfail)\b|\bpytest\s*\.\s*mark\s*\.\s*(?:skip|skipif|xfail)\s*\(|\bpytest\s*\.\s*(?:skip|xfail)\s*\(|@(?:unittest\s*\.\s*)?(?:skip|skipIf|skipUnless|expectedFailure)\b|\.\s*skip\s*\(|\b(?:it|test|describe)\s*\.\s*skip\b|\b(?:xit|xdescribe)\s*\(|@Disabled\b|\bt\s*\.\s*Skip(?:f|Now)?\s*\(|(?:->|::)\s*markTest(?:Skipped|Incomplete)\s*\("]},
{"id": "test-tautology-added", "label": "Always-true assertion added to a test", "sev": "high", "class": "bug",
"share": "EvilGenie arXiv:2511.21654; METR reward hacking (2025)", "cs": True,
"fix": "Assert an observable result from the implementation instead of a constant truth.",
"diff": "+", "pats": [r"\bassert\s*(?:\(\s*)*True(?:\s*\))*\s*(?:$|[,;])", r"\bexpect\s*\(\s*(?:\(\s*)*true(?:\s*\))*\s*\)\s*\.\s*toBe\s*\(\s*(?:\(\s*)*true(?:\s*\))*\s*\)"]},
]
def compile_rules(min_sev):
order = ["high", "medium", "low"]
floor = order.index(min_sev) if min_sev else len(order) - 1
out = []
for r in RULES:
if order.index(r["sev"]) > floor:
continue
r = dict(r)
flags = 0 if r.get("cs") else re.IGNORECASE
r["rx"] = [re.compile(p, flags) for p in r["pats"]]
# Per-rule opt-out, same mechanism the ui scanner uses.
r["suppress_rx"] = re.compile(r["suppress"], re.IGNORECASE) if r.get("suppress") else None
out.append(r)
return out
def iter_files(path):
if os.path.isfile(path):
yield path; return
for root, dirs, files in os.walk(path):
dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
for f in files:
if f.endswith(".min.js") or f.endswith(".min.css") or f.endswith(".map"):
continue
if os.path.splitext(f)[1].lower() in EXTS or re.fullmatch(DEBRIS, f, re.IGNORECASE):
yield os.path.join(root, f)
def finding(rule, fp, number, line, match):
return {"rule": rule["id"], "label": rule["label"], "sev": rule["sev"],
"class": rule["class"], "share": rule["share"], "fix": rule["fix"],
"file": fp, "line": number, "match": match.strip()[:50], "snippet": line.strip()[:160]}
def python_swallow(lines, index):
header = re.match(r"^([ \t]*)except[^:]*:(.*)", lines[index])
body = [header[2].lstrip() + "\n"]
if not header[2].split("#", 1)[0].strip():
indent = len(header[1].expandtabs())
body = []
for line in lines[index + 1:]:
if line.strip() and not line.lstrip().startswith("#"):
if len(line.expandtabs()) - len(line.expandtabs().lstrip()) <= indent:
break
body.append(line)
try:
statements = ast.parse(textwrap.dedent("".join(body))).body
except SyntaxError:
return False
for node in statements:
if isinstance(node, ast.Pass):
continue
if isinstance(node, ast.Expr):
if isinstance(node.value, ast.Constant) and node.value.value is Ellipsis:
continue
if isinstance(node.value, ast.Call):
func = node.value.func
if isinstance(func, ast.Name) and func.id == "print":
continue
if isinstance(func, ast.Name) and func.id == "error_log":
continue
if isinstance(func, ast.Attribute) and func.attr in {"debug", "info", "warning", "warn", "error", "exception", "critical", "log"}:
if ast.unparse(func.value) in {"logger", "logging", "log", "console", "self.logger", "this.logger", "Log"}:
continue
return False
return True
def suppression_reason(comments, match):
tail = comments[match.end():].split("*/", 1)[0]
return bool(re.search(r"[a-zA-Z]", tail))
def source_views(lines, fp):
"""Keep offsets while separating code, comments, and quoted data."""
quote = block = ""
hash_comment = os.path.splitext(fp)[1].lower() not in {".js", ".jsx", ".ts", ".tsx", ".css", ".java", ".go", ".c", ".cpp", ".cs"}
for line in lines:
code, comments = list(line), [" "] * len(line)
i = 0
while i < len(line):
start = i
if block:
end = line.find(block, i)
i = len(line) if end < 0 else end + len(block)
if end >= 0:
block = ""
comments[start:i] = line[start:i]
code[start:i] = " " * (i - start)
elif quote:
if line.startswith(quote, i):
i += len(quote)
quote = ""
elif line[i] == "\\":
i = min(i + 2, len(line))
else:
i += 1
code[start:i] = "~" * (i - start)
elif line.startswith(("//", "-- "), i) or (hash_comment and line[i] == "#"):
comments[i:] = line[i:]
code[i:] = " " * (len(line) - i)
break
elif line.startswith(("/*", "<!--"), i):
block = "*/" if line.startswith("/*", i) else "-->"
elif line[i] in "\"'`":
quote = line[i] * (3 if line.startswith(line[i] * 3, i) else 1)
i += len(quote)
code[start:i] = "~" * (i - start)
else:
i += 1
# Visible markup text is data too, including prose in PHP templates and JSX.
for text in re.finditer(r"<(?!/?(?:script|style)\b)/?[a-z][^>]*>([^<]*)", line, re.IGNORECASE):
before = line[:text.start()].rstrip()
if re.search(r"[\w)\]]$", before) and not re.search(r"\breturn$", before):
continue # a generic argument list, not an opening markup tag
code[text.start(1):text.end(1)] = "~" * len(text[1])
yield "".join(code), "".join(comments)
def identifier_words(name):
name = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1 \2", name)
name = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", name)
return re.findall(r"[a-z]+|\d+", name.lower())
def sentence_identifier(name):
if name.lstrip("$").isupper():
return False
# These conventional compounds each name one concept despite internal capitals.
name = name.replace("WebSite", "Website").replace("JsonLd", "Jsonld")
words = [word for word in identifier_words(name) if word.isalpha()]
return len(words) >= 6
def narrates_next_line(comment, lines, index):
if re.match(r"(?:step\s*\d+\b|now we\b|(?:first|next|finally),?\s+we\b)", comment, re.IGNORECASE):
return True
if index + 1 >= len(lines):
return False
code = lines[index + 1].strip()
if not code or code.startswith(("#", "//", "/*", "*")) or re.match(r"--\s", code):
return False
words = [word for word in identifier_words(comment) if word not in {"a", "an", "the"}]
# Operators have no word tokens, so match increment/decrement explicitly.
for verb, operator in (("increment", "+"), ("decrement", "-")):
op = re.escape(operator)
update = re.fullmatch(rf"(?:(\$?[A-Za-z_]\w*)\s*(?:{op}{op}|{op}=\s*1)|{op}{op}\s*(\$?[A-Za-z_]\w*))\s*;?", code)
if update and words == [verb] + identifier_words(update[1] or update[2]):
return True
return len(words) >= 2 and words == identifier_words(code)
def documented_example(line, match):
if re.match(r"\s*(?://|#|/\*|\*|--\s|<!--)", line):
return True
for attr in re.finditer(r"(?<![\w:-])placeholder\s*=\s*(['\"])(.*?)\1", line, re.IGNORECASE):
if attr.start(2) <= match.start() and match.end() <= attr.end(2):
return True
for text in re.finditer(r"<(?!/?(?:script|style)\b)/?[a-z][^>]*>([^<]*)", line, re.IGNORECASE):
if text.start(1) <= match.start() and match.end() <= text.end(1):
return True
return False
def scan(path, min_sev):
rules = compile_rules(min_sev)
findings = []
for fp in iter_files(path):
try:
with open(fp, "r", encoding="utf-8", errors="ignore") as fh:
lines = fh.readlines()
except OSError:
continue # unreadable file: skip, not fatal
for r in rules:
if r.get("filename") and r["rx"][0].fullmatch(os.path.basename(fp)):
if not lines or "unslop-ignore" not in lines[0].lower():
findings.append(finding(r, fp, 1, os.path.basename(fp), os.path.basename(fp)))
if fp.lower().endswith(".md"):
continue # debris check is filename-only
if len(lines) == 1 and len(lines[0]) > 5000: # likely minified
continue
in_docblock = False
views = list(source_views(lines, fp))
for i, line in enumerate(lines, 1):
code, comments = views[i - 1]
docblock_line = in_docblock or bool(re.match(r"\s*/\*\*", line))
if docblock_line:
in_docblock = "*/" not in line
if "unslop-ignore" in line.lower():
continue
for r in rules:
if r.get("diff") or r.get("filename"):
continue
if r["suppress_rx"] and r["suppress_rx"].search(line):
continue
for rx in r["rx"]:
target = line
if r["id"] == "verbose-naming":
target = code
elif r["id"] == "change-narration":
target = comments
elif r["id"] == "checker-suppression":
target = code if rx.pattern.startswith((r"\bas", r":\s*any")) else comments
m = rx.search(target)
if m:
if r["id"] == "verbose-naming" and (docblock_line or not sentence_identifier(m["name"])):
continue
if r["id"] == "narrating-comment" and (docblock_line or not narrates_next_line(m["comment"], lines, i - 1)):
break
if r["id"] == "boilerplate-marker" and m.group(0).lower() == "example.com":
m = next((example for example in rx.finditer(line)
if not (docblock_line or documented_example(line, example))), None)
if m is None:
continue
if r["id"] == "swallowed-errors" and line.lstrip().startswith("except"):
if not fp.lower().endswith(".py") or not python_swallow(lines, i - 1):
break
if r["id"] == "checker-suppression" and suppression_reason(comments, m):
continue
match = m["name"] if r["id"] == "verbose-naming" else m.group(0)
findings.append(finding(r, fp, i, line, match))
break
return findings
def is_test_file(path):
return bool(re.search(r"(?:^|/)(?:tests|__tests__)/|(?:^|/)test_[^/]+$|(?:^|/)[^/]*_test\.[^/]+$|\.(?:test|spec)\.[^/]+$", path))
def iter_diff_lines(diff, context_sides=False):
old_path = new_path = ""
old_line = new_line = old_left = new_left = 0
for raw in diff.splitlines():
if raw.startswith("diff --git "):
old_path = new_path = ""
old_left = new_left = 0
elif not (old_left or new_left) and raw.startswith(("--- ", "+++ ")):
path = raw[4:].split("\t", 1)[0]
if path.startswith('"'):
path = ast.literal_eval(path)
path = re.sub(r"^[ab]/", "", path)
if raw.startswith("--- "):
old_path = path
else:
new_path = path
elif raw.startswith("@@ "):
hunk = re.match(r"@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", raw)
if hunk:
old_line, new_line = int(hunk[1]), int(hunk[3])
old_left, new_left = int(hunk[2] or 1), int(hunk[4] or 1)
elif (old_left or new_left) and raw[:1] in {"-", "+", " "}:
kind = raw[0]
path, number = (old_path, old_line) if kind == "-" else (new_path, new_line)
if kind == " " and context_sides:
yield old_path, old_line, "old-context", raw[1:]
yield new_path, new_line, "new-context", raw[1:]
else:
yield path, number, kind, raw[1:]
if kind != "+":
old_line += 1; old_left -= 1
if kind != "-":
new_line += 1; new_left -= 1
def scan_diff(diff, min_sev):
rules = [r for r in compile_rules(min_sev) if r.get("diff")]
findings = []
# Reconstruct each hunk side so strings and block comments retain lexical state.
groups, latest = [], {}
for fp, number, kind, line in iter_diff_lines(diff, context_sides=True):
side = "-" if kind in {"-", "old-context"} else "+"
key = fp, side
rows = latest.get(key)
if rows is None or rows[-1][0] + 1 != number:
rows = []
latest[key] = rows
groups.append((fp, side, rows))
rows.append((number, kind, line))
for fp, side, rows in groups:
if not is_test_file(fp):
continue
views = list(source_views([line for _, _, line in rows], fp))
for index, (number, kind, line) in enumerate(rows):
if kind != side or "unslop-ignore" in line.lower():
continue
code = views[index][0].strip()
if not code:
continue
for r in rules:
if r["diff"] != kind:
continue
candidate = code
if r["id"] == "test-tautology-added" and index + 1 < len(rows) and "unslop-ignore" not in rows[index + 1][2].lower():
following = views[index + 1][0].strip()
if rows[index + 1][1] == "+" and following.startswith("."):
candidate += " " + following
for rx in r["rx"]:
m = rx.search(candidate)
if m:
findings.append(finding(r, fp, number, line, m.group(0)))
break
return findings
def verdict(by_sev, weighted):
# Severity mix decides, not the weighted total. The total let a pile of low findings
# read as STRONG with zero high ones, which is how the scanner lost its credibility.
high, med = by_sev.get("high", 0), by_sev.get("medium", 0)
if high >= 3 or (high >= 1 and med >= 5):
return "STRONG AI-written-code tells"
if high >= 1 or med >= 3:
return "Some AI tells present"
if weighted > 0:
return "Mostly clean, minor tells"
return "Clean, no surface tells detected"
def main():
ap = argparse.ArgumentParser(description="Scan source code for AI-written-code tells.")
ap.add_argument("path", nargs="?")
ap.add_argument("--diff", action="store_true", help="check test integrity in a git diff read from stdin")
ap.add_argument("--diff-base", metavar="REF", help="check test integrity in git diff REF (path selects the repo)")
ap.add_argument("--severity", choices=["high", "medium", "low"], default="low",
help="minimum severity to report (default: low = everything)")
ap.add_argument("--json", action="store_true", help="machine-readable output")
ap.add_argument("--max", type=int, default=10, help="max examples shown per rule (text mode)")
args = ap.parse_args()
if not args.path and not (args.diff or args.diff_base):
ap.error("path is required unless --diff or --diff-base is used")
if args.path and not os.path.exists(args.path):
print(f"path not found: {args.path}", file=sys.stderr); sys.exit(2)
if args.diff or args.diff_base:
if args.diff_base:
cwd = args.path or "."
if os.path.isfile(cwd):
cwd = os.path.dirname(os.path.abspath(cwd))
try:
diff = subprocess.run(["git", "diff", "--no-ext-diff", "--no-color", args.diff_base, "--"], cwd=cwd,
check=True, capture_output=True, text=True).stdout
except (OSError, subprocess.CalledProcessError) as exc:
print(f"git diff failed: {exc}", file=sys.stderr); sys.exit(2)
else:
diff = sys.stdin.read()
findings = scan_diff(diff, args.severity)
files_scanned = len({fp for fp, _, _, _ in iter_diff_lines(diff) if is_test_file(fp)})
args.path = args.path or "."
else:
findings = scan(args.path, args.severity)
files_scanned = sum(1 for _ in iter_files(args.path))
by_sev, by_class, by_rule = {}, {}, {}
for f in findings:
by_sev[f["sev"]] = by_sev.get(f["sev"], 0) + 1
by_class[f["class"]] = by_class.get(f["class"], 0) + 1
by_rule.setdefault(f["rule"], []).append(f)
weighted = sum(W[s] * n for s, n in by_sev.items())
if args.json:
print(json.dumps({"path": args.path, "files_scanned": files_scanned, "counts": by_sev,
"class_counts": by_class, "slop_score": weighted,
"verdict": verdict(by_sev, weighted), "findings": findings}, indent=2))
sys.exit(by_sev.get("high", 0))
sev_order = {"high": 0, "medium": 1, "low": 2}
rule_ids = sorted(by_rule, key=lambda rid: (sev_order[by_rule[rid][0]["sev"]], -len(by_rule[rid])))
print(f"\n unslop-code scan: {args.path}")
print(f" files scanned: {files_scanned} findings: {len(findings)} slop score: {weighted}")
print(f" verdict: {verdict(by_sev, weighted)}")
print(f" high: {by_sev.get('high',0)} medium: {by_sev.get('medium',0)} low: {by_sev.get('low',0)}")
print(f" bug-class: {by_class.get('bug',0)} (review behavior) "
f"substance: {by_class.get('substance',0)} (review contract) "
f"cosmetic: {by_class.get('cosmetic',0)} (advisory)\n")
if not findings:
print(" No surface tells flagged. The loudest tells are structural and a regex cannot see\n"
" them: boilerplate / tutorial-shaped code, hallucinated APIs, over-engineering, and\n"
" code that ignores the surrounding repo. Hallucinated APIs are a bug, not a style\n"
" issue: build it, type-check it, run it, resolve every import. Then read the diff for\n"
" the rest by hand against references/tells.md.\n")
return
for rid in rule_ids:
items = by_rule[rid]
f0 = items[0]
print(f" [{f0['sev'].upper()} · {f0['class']}] {f0['label']} ({len(items)} hit{'s' if len(items)!=1 else ''}) [{f0['share']}]")
print(f" fix: {f0['fix']}")
for it in items[:args.max]:
print(f" {it['file']}:{it['line']} ({it['match']}) {it['snippet']}")
if len(items) > args.max:
print(f" ... +{len(items) - args.max} more")
print()
top = [by_rule[rid][0]['label'] for rid in rule_ids[:3]]
print(" Top things to change: " + "; ".join(top))
print(" Review bug-class findings first; verify the behavior before changing it.")
print(" The big tells (boilerplate, hallucinated APIs, over-engineering) the regex cannot see:")
print(" build / type-check / run for the hallucinated calls, read the diff for the rest. See references/tells.md.\n")
sys.exit(by_sev.get("high", 0))
if __name__ == "__main__":
main()
skills/a-unslop-code/tests/fixtures/clean/Invoice.php269 B
<?php
$items = $lineItems ?? [];
final class Invoice
{
public function __construct(private int $net, private int $tax) {}
public function total(): int
{
// Note: both amounts use the same currency.
return $this->net + $this->tax;
}
}
+32 more · Show all 42
skills/a-unslop-code/tests/fixtures/clean/atomic_store.py401 B
import logging
from pathlib import Path
def write_snapshot(destination: Path, payload: bytes):
# Note: writes must remain atomic.
staged = destination.with_suffix(".pending")
try:
staged.write_bytes(payload)
staged.replace(destination)
except Exception:
logging.exception("Snapshot write failed")
raise
logging.info("Successfully saved snapshot")
skills/a-unslop-code/tests/fixtures/clean/cart.ts365 B
type Line = { quantity: number; price: number };
export function subtotal(lines: Line[]): number {
// Important: prices are stored in cents.
return lines.reduce((total, line) => total + line.quantity * line.price, 0);
}
export function auditReceipt(receiptId: string): void {
console.log("Successfully stored receipt", receiptId);
console.log("Done!");
}
skills/a-unslop-code/tests/fixtures/dirty/handler.py361 B
# Note: I've updated the implementation.
# ... rest of your code
# increment i
i += 1
print("done ✅")
def process_data(value):
try:
return value.read()
except Exception:
print("failed")
def getUserDataFromApiResponseHandler():
pass
endpoint = "YOUR_API_KEY"
value = legacy_call() # type: ignore
# Updated to use the new response.
skills/a-unslop-code/tests/fixtures/dirty/notes/IMPLEMENTATION_SUMMARY.md32 B
Temporary implementation notes.
skills/a-unslop-code/tests/fixtures/dirty/surface.ts89 B
// @ts-ignore const amount = response as any; // Previously this used the old transport.
skills/a-unslop-code/tests/test_unslop_code_scan.py36.8 KB
"""Regression tests for surface findings, test-integrity diffs, and CLI compatibility."""
import importlib.util
import contextlib
import io
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
SCRIPT = Path(__file__).parents[1] / "scripts" / "unslop_code_scan.py"
SPEC = importlib.util.spec_from_file_location("unslop_code_scan", SCRIPT)
SCANNER = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(SCANNER)
FIXTURES = Path(__file__).parent / "fixtures"
class ScannerTests(unittest.TestCase):
def scan(self, text, name="sample.py"):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
path = Path(tmp) / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
return SCANNER.scan(str(path), "low")
def rules(self, text, name="sample.py"):
return sorted({f["rule"] for f in self.scan(text, name)})
# ---- verbose-naming: a test name is a sentence on purpose ----
def test_descriptive_pytest_names_are_allowed(self):
self.assertEqual([], self.rules(
"def test_returns_none_on_malformed_yaml(tmp_path):\n pass\n"
"def test_one_file_is_one_task_regardless_of_body_checkboxes(tmp_path):\n pass\n"))
def test_go_and_jest_test_names_are_allowed(self):
self.assertEqual([], self.rules(
"func TestReturnsNoneOnMalformedYamlInput(t *testing.T) {}\n", "a.go"))
self.assertEqual([], self.rules(
"it('renders the user profile card when data has loaded', () => {})\n", "a.js"))
def test_genuinely_sentence_shaped_identifier_is_still_caught(self):
for name in ("getUserDataFromApiResponseHandler", "getActiveUserApiJsonPayload",
"get_active_user_api_json_payload"):
with self.subTest(name=name):
self.assertEqual(["verbose-naming"], self.rules(f"def {name}():\n pass\n"))
def test_five_segment_identifiers_are_allowed(self):
for name in ("getUserFromApiResponse", "getUserForApiResponse", "getUserWithApiResponse",
"getUserAndApiResponse", "getUserApiResponseHandler", "getUserApiResponseFunction"):
with self.subTest(name=name):
self.assertNotIn("verbose-naming", self.rules(f"function {name}() {{}}", "a.js"))
for name in ("getUserApiJsonPayload", "getUserFromApi", "buildItemListJsonLd",
"getCollectionPageJsonLd", "editItemIsComingSoon", "exchangeCodeForUserInfo",
"getWebSiteWithSearchJsonLd", "get_user_from_api_response"):
with self.subTest(name=name):
self.assertNotIn("verbose-naming", self.rules(f"public function {name}() {{}}", "a.php"))
def test_verbose_names_only_fire_on_definitions(self):
name = "getUserDataFromApiResponseHandler"
for text, suffix in ((f"async def {name}():\n pass", "py"),
(f"public static function {name}(): array {{}}", "php"),
(f"const {name} = () => {{}};", "ts"),
(f" {name}() {{}}", "js"),
(f"public static Result {name}() {{}}", "java"),
(f"func (s *Service) {name}() {{}}", "go"),
(f"${name} = null;", "php")):
with self.subTest(text=text):
self.assertEqual(["verbose-naming"], self.rules(text, "a." + suffix))
for text in (f"{name}();", f"result = {name}()", f"return {name}();",
f"await {name}();", f"new {name}();", f"$this->{name}();",
f"Service::{name}();", f'<input id="{name}">',
f'const id = "{name}";', f"// {name}",
"const ZERO_RESULT_QUERY_MAX_PER_DAY = 200;"):
with self.subTest(text=text):
self.assertNotIn("verbose-naming", self.rules(text, "a.php"))
# ---- CMT: `--` opens a SQL comment, not a shell flag ----
def test_shell_long_flags_are_not_comments(self):
self.assertEqual([], self.rules(
'rsync --archive --delete --comments "nightly" src/ dst/\n', "a.sh"))
def test_real_sql_comment_still_matches(self):
self.assertEqual(["narrating-comment"], self.rules(
"-- Step 1: create the table\nCREATE TABLE t (id int);\n", "a.sql"))
# ---- narrating-comment: adjacency and explicit steps ----
def test_long_comment_carrying_a_reason_is_allowed(self):
self.assertEqual([], self.rules(
"# Retry once before failing the job: the upstream API drops the first request\n"
"# after a cold start, and its own docs recommend a single retry.\n", "a.sh"))
def test_short_restating_comment_is_still_caught(self):
for text in ("# increment i\ni += 1\n", "// increment i\n$i++;\n",
"# increment the counter\ncounter += 1\n", "# decrement i\n--i;\n",
"// Return the result\nreturn result;\n", "// Save invoice\nsaveInvoice();\n"):
with self.subTest(text=text):
self.assertEqual(["narrating-comment"], self.rules(text))
def test_explicit_step_narration_is_caught(self):
for prefix in ("#", "//"):
for text in ("Step 1", "Now we connect", "First, we connect", "Next, we connect",
"Finally, we close", "Step 2: " + "a long explanation " * 6):
with self.subTest(prefix=prefix, text=text):
self.assertIn("narrating-comment", self.rules(f"{prefix} {text}\n"))
def test_docblock_lines_are_exempt_from_narration(self):
for suffix in ("php", "js"):
for text in ("/**\n * Create a new note\n * Get the application secret key\n */\n",
" * Step 1\n * Now we connect\n * First, we connect\n",
"/**\n// Step 1\n# Now we connect\n*/\n",
"/** Step 1 */\n"):
with self.subTest(suffix=suffix, text=text):
self.assertNotIn("narrating-comment", self.rules(text, "a." + suffix))
self.assertIn("narrating-comment", self.rules("/** ignored */\n# Step 1\n"))
def test_section_labels_and_nonadjacent_or_different_code_are_allowed(self):
for text in ("// Initialize database connection\n$db = new PDO($dsn);\n",
"// Create a new note\nif ($ready) {\n saveNote();\n}\n",
"# Initialize database connection\n{\nconnect()\n}\n",
"# First, validate input\nvalidate(request)\n",
"# increment i\n\ni += 1\n", "# increment i\nsave()\ni += 1\n",
"# increment i\nj += 1\n", "# increment i\ni += 10\n",
"# increment i\n# i += 1\n", "# increment i\n",
"const label = '// Step 1';"):
with self.subTest(text=text):
self.assertNotIn("narrating-comment", self.rules(text))
# ---- the loud tells must keep firing ----
def test_placeholder_stub_is_high_and_bug_class(self):
findings = self.scan("def f():\n # ... rest of your code\n pass\n")
self.assertEqual(["placeholder-comment"], [f["rule"] for f in findings])
self.assertEqual("high", findings[0]["sev"])
self.assertEqual("bug", findings[0]["class"])
def test_chat_artifact_is_caught(self):
self.assertIn("chat-artifact", self.rules(
"# Here's the updated code for your handler\nx = 1\n"))
def test_assistant_instructions_after_preambles_are_caught(self):
for text in ("# Note: I've updated this", "# Note: you'll need to configure this",
"# Remember to replace the token", "# Important: make sure you run this",
"// Tip: you'll need to add the path", "# Keep in mind: I'll fix this now"):
with self.subTest(text=text):
self.assertIn("chat-artifact", self.rules(text))
def test_invariant_preambles_are_allowed(self):
for text in ("# Note: writes must remain atomic", "# Remember: retries are bounded",
"// Important: order is stable", "# Tip: cache entries expire after a minute",
"# Keep in mind: offsets are in bytes", "# Important: you must hold the lock",
"# Note: you can read committed snapshots", "# Tip: to run faster, batch writes"):
with self.subTest(text=text):
self.assertNotIn("chat-artifact", self.rules(text))
def test_bare_except_is_bug_class(self):
findings = self.scan("try:\n f()\nexcept:\n pass\n")
self.assertEqual(["swallowed-errors"], [f["rule"] for f in findings])
self.assertEqual("bug", findings[0]["class"])
def test_empty_and_log_only_python_handlers_are_caught(self):
for header in ("except:", "except Exception:", "except BaseException as exc:"):
for body in ("", " pass\n", " ...\n", " # failure ignored\n",
' print("failed")\n', ' logger.exception("failed")\n',
' logger.error(\n "failed"\n )\n'):
with self.subTest(header=header, body=body):
self.assertIn("swallowed-errors", self.rules("try:\n save()\n" + header + "\n" + body))
def test_handled_python_errors_are_allowed(self):
for header in ("except:", "except Exception:", "except BaseException as exc:"):
for body in (' logger.exception("failed")\n raise\n',
' print("failed")\n return None\n',
' logger.error("failed")\n raise WriteError()\n',
" recover()\n", " if retry:\n raise\n"):
with self.subTest(header=header, body=body):
self.assertNotIn("swallowed-errors", self.rules("try:\n save()\n" + header + "\n" + body))
def test_python_handler_stops_at_dedent_and_supports_inline_suites(self):
self.assertIn("swallowed-errors", self.rules("try:\n save()\nexcept Exception:\n pass\nraise OtherError()\n"))
self.assertIn("swallowed-errors", self.rules("except Exception: print('failed')\n"))
self.assertNotIn("swallowed-errors", self.rules("except Exception: print('failed'); raise\n"))
self.assertNotIn("swallowed-errors", self.rules("except ValueError:\n pass\n"))
self.assertNotIn("swallowed-errors", self.rules("except Exception: return None\n"))
def test_javascript_empty_catches_are_still_caught(self):
for suffix in ("js", "ts"):
with self.subTest(suffix=suffix):
self.assertIn("swallowed-errors", self.rules("try { save(); } catch (err) {}", "a." + suffix))
self.assertNotIn("swallowed-errors", self.rules("try { save(); } catch (err) { throw err; }", "a." + suffix))
def test_success_logging_is_allowed_and_emoji_is_counted_once(self):
for call in ("print", "console.log", "println", "fmt.Println", "System.out.println"):
for message in ("Successfully saved", "Done!"):
with self.subTest(call=call, message=message):
self.assertEqual([], self.rules(f'{call}("{message}")'))
findings = self.scan(f'{call}("\U00002705 done")')
self.assertEqual(["emoji-in-code"], [f["rule"] for f in findings])
def test_dummy_markers_and_remaining_log_marker_still_fire(self):
for text in ('key = "YOUR_API_KEY"', 'print("Here we go")'):
self.assertIn("boilerplate-marker", self.rules(text))
self.assertNotIn("boilerplate-marker", self.rules('key = read_secret()'))
def test_example_domain_in_documentation_and_form_hints_is_allowed(self):
for text in ('placeholder="you@example.com">',
'placeholder="https://example.com" value="<?= e($url) ?>">',
"placeholder='https://example.com'>",
'<p class="help">Absolute URL (https://example.com/page).</p>',
'<li>Absolute (<code class="url">https://example.com</code>)</li>',
" * in subdirectories (e.g., 'example.com/myapp/').",
" * sc-domain:example.com keeps a colon.",
"/**\nAn example.com installation.\n*/",
"// See https://example.com for the URL format."):
with self.subTest(text=text):
self.assertNotIn("boilerplate-marker", self.rules(text, "a.php"))
def test_runtime_example_domains_and_other_placeholders_still_fire(self):
for text in ('endpoint = "https://example.com"',
'const endpoint = "you@example.com";',
'<a href="https://example.com">Service</a>',
'<script>const endpoint = "https://example.com";</script>',
'<input placeholder="example.com"><script>const endpoint = "https://example.com";</script>',
'<input placeholder="YOUR_API_KEY">', '// YOUR_API_KEY',
'<p>lorem ipsum</p>', '<p>John Doe</p>'):
with self.subTest(text=text):
self.assertIn("boilerplate-marker", self.rules(text, "a.php"))
def test_fallbacks_are_left_to_human_review(self):
self.assertNotIn("fallback-masking", {rule["id"] for rule in SCANNER.RULES})
for text in ("config = payload or {}", "rows = payload ?? []", "options = payload ?? {}",
'value = getattr(item, "name", None)', "$eng = $engagement ?? [];"):
with self.subTest(text=text):
self.assertEqual([], self.rules(text))
def test_required_values_and_explicit_getattr_defaults_are_allowed(self):
for text in ("config = payload", "rows = payload ?? loadRows()", 'value = getattr(item, "name", "anonymous")'):
self.assertEqual([], self.rules(text))
def test_checker_suppressions_without_reasons_are_caught(self):
for text in ("x = f() # type: ignore", "x = f() # type: ignore[arg-type]",
"x = f() # noqa", "x = f() # noqa: E501, F401", "// @ts-ignore",
"// @ts-expect-error", "// eslint-disable", "// eslint-disable-next-line no-console",
"const result = value as any;", "const result = value as unknown as Result;"):
with self.subTest(text=text):
findings = [f for f in self.scan(text) if f["rule"] == "checker-suppression"]
self.assertEqual(1, len(findings))
self.assertEqual(("medium", "bug"), (findings[0]["sev"], findings[0]["class"]))
def test_checker_suppressions_with_reasons_are_allowed(self):
for text in ("x = f() # type: ignore[arg-type] upstream annotation is wrong",
"x = f() # noqa: E501 reason", "// @ts-expect-error: upstream types wrong",
"// @ts-ignore: tracked upstream issue", "// eslint-disable no-console -- CLI output",
"const result = value as any; // vendor has no types",
"const result = value as unknown as Result; /* upstream type mismatch */"):
with self.subTest(text=text):
self.assertNotIn("checker-suppression", self.rules(text))
def test_change_narration_is_caught(self):
for text in ("# Updated to match responses", "// Changed from the previous helper",
"# Modified so errors propagate", "# Fixed the retry loop", "// Refactored to share setup",
"# Previously this was inline", "// Old: transport", "# New: transport"):
with self.subTest(text=text):
self.assertIn("change-narration", self.rules(text))
def test_continuing_rationale_is_allowed(self):
self.assertNotIn("change-narration", self.rules("# Retries stop here because the request may have committed."))
self.assertNotIn("change-narration", self.rules('status = "Updated to current version"'))
def test_debris_filenames_are_checked_at_any_depth(self):
for name in ("IMPLEMENTATION_SUMMARY.md", "docs/API_SUMMARY.md", "docs/deep/COMPLETED.md",
"CHANGES_MADE.md", "notes/FIX_NOTES.md"):
with self.subTest(name=name):
findings = self.scan("", name)
self.assertEqual(["repo-debris"], [f["rule"] for f in findings])
self.assertEqual(("medium", "cosmetic"), (findings[0]["sev"], findings[0]["class"]))
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
nested = Path(tmp) / "docs"
nested.mkdir()
(nested / "COMPLETED.md").write_text("# Here's the updated code", encoding="utf-8")
(nested / "guide.md").write_text("# Here's the updated code", encoding="utf-8")
self.assertEqual(["repo-debris"], [f["rule"] for f in SCANNER.scan(tmp, "low")])
def test_regular_documentation_and_filename_escape_are_allowed(self):
for name in ("docs/README.md", "notes/SUMMARY.md", "docs/COMPLETED.py"):
self.assertNotIn("repo-debris", self.rules("", name))
self.assertEqual([], self.rules("<!-- unslop-ignore: retained as a release record -->", "COMPLETED.md"))
def diff(self, removed, added, name="tests/test_invoice.py"):
old = "\n".join("-" + line for line in removed)
new = "\n".join("+" + line for line in added)
return (f"diff --git a/{name} b/{name}\n--- a/{name}\n+++ b/{name}\n"
f"@@ -12,{len(removed)} +20,{len(added)} @@\n" + old + ("\n" if old else "") + new + "\n")
def test_diff_literals_and_comments_are_data(self):
for text in ('message = "Please use .skip() to omit optional data"',
'message = "assert failed for malformed input"',
'const text = "expect(true).toBe(true)";',
'text = "@pytest.mark.skipif(True)"',
'# assert True; test.skip("case", run)',
'/* t.Skipf("pending"); assert True */',
'message = """\nassert True\nt.SkipNow()\n"""'):
for direction in ("+", "-"):
with self.subTest(text=text, direction=direction):
diff = self.diff(text.splitlines() if direction == "-" else [],
text.splitlines() if direction == "+" else [])
self.assertEqual([], SCANNER.scan_diff(diff, "low"))
for text, direction, rule in (("assert result", "-", "test-assertion-removed"),
("test.skip('case', run)", "+", "test-skip-added"),
("assert True", "+", "test-tautology-added")):
findings = SCANNER.scan_diff(self.diff([text] if direction == "-" else [],
[text] if direction == "+" else []), "low")
self.assertEqual([rule], [f["rule"] for f in findings])
def test_regression_module_as_added_diff_has_no_integrity_findings(self):
lines = Path(__file__).read_text().splitlines()
self.assertEqual([], SCANNER.scan_diff(self.diff([], lines), "low"))
def test_diff_context_preserves_quote_and_comment_state(self):
for opening, closing in (('message = """', '"""'), ('/*', '*/')):
diff = ('--- a/tests/test_invoice.py\n+++ b/tests/test_invoice.py\n'
'@@ -10,3 +10,3 @@\n ' + opening + '\n'
'-assert failed for malformed input\n'
'+t.Skipf("pending"); assert True\n ' + closing + '\n')
with self.subTest(opening=opening):
self.assertEqual([], SCANNER.scan_diff(diff, "low"))
diff = ('--- a/tests/test_invoice.py\n+++ b/tests/test_invoice.py\n'
'@@ -10,4 +10,4 @@\n message = """\n text\n """\n'
'-assert result\n+assert (True)\n')
self.assertEqual(["test-assertion-removed", "test-tautology-added"],
[f["rule"] for f in SCANNER.scan_diff(diff, "low")])
def test_standard_skip_variants(self):
for text in ('@pytest.mark.skipif(True, reason="temporary")',
'@pytest.mark.xfail(reason="pending")', 'pytest.skip("pending")',
'pytest.xfail("pending")', '@unittest.skip("pending")',
'@unittest.skipIf(True, "pending")', '@unittest.skipUnless(False, "pending")',
'@skipIf(True, "pending")', '@unittest.expectedFailure',
'test.skip("case", run)', 'describe.skip("case", run)', 'xdescribe("case", run)',
'xit("case", run)', 'it . skip ("case", run)',
't.Skipf("pending")', 't.SkipNow()',
'$this->markTestSkipped("pending");', '$this->markTestIncomplete("pending");'):
with self.subTest(text=text):
self.assertEqual(["test-skip-added"], [f["rule"] for f in SCANNER.scan_diff(self.diff([], [text]), "low")])
for text in ('skip_reason = "pending"', 'xfail = False', 't.Skipper()',
'transaction.error()', '@unittest.skipper', 'pytest.mark.skipping',
'marker = pytest.mark.skip', 'const key = obj.assert;', '$assert = value;'):
with self.subTest(text=text):
self.assertEqual([], SCANNER.scan_diff(self.diff([], [text]), "low"))
def test_tautology_spacing_parentheses_and_continuation(self):
for lines in (("assert (True)",), ("assert (( True ))",),
("assert(True)",), ("expect ( ( true ) ).toBe ( ( true ) )",),
("expect (true).toBe(true)",), ("expect((true)).toBe((true))",),
("expect(true)", " .toBe(true)")):
with self.subTest(lines=lines):
findings = SCANNER.scan_diff(self.diff([], lines), "low")
self.assertEqual(["test-tautology-added"], [f["rule"] for f in findings])
self.assertEqual(20, findings[0]["line"])
for lines in (("assert (result)",), ("assert (True) == result",),
("expect(false)", " .toBe(true)"), ("expect(true)", " .toBe(result)")):
with self.subTest(lines=lines):
self.assertEqual([], SCANNER.scan_diff(self.diff([], lines), "low"))
def test_diff_base_and_stdin_ignore_quoted_data(self):
diff = self.diff(['message = "assert failed for malformed input"'],
['message = "Please use .skip() to omit optional data"'])
code, report = self.cli(["--diff", "--json"], diff)
self.assertEqual((0, []), (code, report["findings"]))
with patch.object(SCANNER.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, stdout=diff)):
code, report = self.cli(["--diff-base", "main", "--json"])
self.assertEqual((0, []), (code, report["findings"]))
def test_chat_change_reports_and_reader_instructions(self):
for text in ("# Note: I have updated this code", "# I've added retry handling",
"// I changed the parser", "# As requested, here is the updated file",
"# Here is the updated code", "# Let me know", "# Hope this helps",
"# Remember: replace the token before running", "# Don't forget to add the path",
"# Do not forget to configure the token", "# I will fix this now"):
with self.subTest(text=text):
self.assertIn("chat-artifact", self.rules(text))
for text in ("# Important: make sure you hold the lock during writes",
"# Note: make sure you preserve insertion order", "# Previously computed values remain valid",
"# Important: you'll need to hold the lock during writes",
"# Remember to update the index under the lock"):
with self.subTest(text=text):
self.assertNotIn("chat-artifact", self.rules(text))
def test_type_suppression_requires_syntax(self):
for text, name in (('const text = "Customers may cancel as any authorized user"', 'a.ts'),
('<p>Works as any standard adapter.</p>', 'a.tsx'),
('// folded the same as any other', 'a.ts'),
('const text = "folded the same as any other"', 'a.ts'),
('const directive = "// @ts-ignore"', 'a.ts'),
('text = "# type: ignore"', 'a.py'),
('/* as any */', 'a.ts')):
with self.subTest(text=text):
self.assertNotIn("checker-suppression", self.rules(text, name))
for text, name in (('const value: any = source;', 'a.ts'),
('const value = source as any;', 'a.ts'),
('const value = identity<Result>(source) as any;', 'a.ts'),
('const value = identity <string>(source) as any;', 'a.ts'),
('value = read() # type: ignore [arg-type]', 'a.py'),
('/* @ts-expect-error */', 'a.ts'), ('/* @ts-ignore */', 'a.ts')):
with self.subTest(text=text):
self.assertIn("checker-suppression", self.rules(text, name))
for text, name in (('// @ts-expect-error: lib types wrong, see #12', 'a.ts'),
('/* @ts-ignore: vendor types wrong */', 'a.ts'),
('value = read() # type: ignore [arg-type] vendor types wrong', 'a.py'),
('const value: any = source; // untyped library', 'a.ts')):
with self.subTest(text=text):
self.assertNotIn("checker-suppression", self.rules(text, name))
def test_suppression_reason_stays_inside_its_comment(self):
self.assertIn("checker-suppression", self.rules('/* @ts-ignore */ const value = source;', 'a.ts'))
self.assertNotIn("checker-suppression", self.rules('/* @ts-ignore: vendor types wrong */ const value = source;', 'a.ts'))
def test_broad_exception_variants_use_narrow_logging_receivers(self):
for header in ('except (Exception,):', 'except builtins.Exception:',
'except ( builtins.BaseException, ) as exc:'):
for call in ('logger.error', 'logging.exception', 'log.warning', 'console.log',
'self.logger.error', 'this.logger.error', 'error_log', 'Log.error'):
with self.subTest(header=header, call=call):
self.assertIn("swallowed-errors", self.rules(f'try:\n save()\n{header}\n {call}("failed")\n'))
for body in (' transaction.error()\n', ' service.exception()\n', ' logger.error("failed")\n raise\n'):
with self.subTest(header=header, body=body):
self.assertNotIn("swallowed-errors", self.rules(f'try:\n save()\n{header}\n' + body))
self.assertNotIn("swallowed-errors", self.rules('except (ValueError,):\n pass\n'))
def test_change_history_only_in_real_comments(self):
for text, name in (('# Updated to use a shared parser', 'a.py'),
('// Now uses a shared parser', 'a.ts'),
('# Previously this was inline', 'a.py'),
('# This was changed to share the parser', 'a.py'),
('/* Updated to share setup */', 'a.css')):
with self.subTest(text=text):
self.assertIn("change-narration", self.rules(text, name))
for text, name in (('const label = "// New: subscription";', 'a.ts'),
('a { content: "// New: pending"; }', 'a.css'),
('# Previously computed values must remain available for rollback.', 'a.py'),
('text = """\n# Updated to share setup\n"""', 'a.py'),
('// Updated values must remain available', 'a.ts')):
with self.subTest(text=text):
self.assertNotIn("change-narration", self.rules(text, name))
def test_fixture_scope_documentation_matches_traversal(self):
catalog = (SCRIPT.parents[1] / 'references' / 'tells.md').read_text()
self.assertIn('`fixtures` directories are excluded from project traversal', catalog)
self.assertIn('a direct path still scans them', catalog)
self.assertNotIn('fixtures stay in normal scan scope', catalog)
def test_removed_assertions_fire_only_in_test_paths(self):
for name in ("test_invoice.py", "invoice_test.go", "invoice.test.ts", "invoice.spec.js",
"pkg/tests/invoice.py", "pkg/__tests__/invoice.js"):
with self.subTest(name=name):
findings = SCANNER.scan_diff(self.diff([" assert result == 42"], [], name), "low")
self.assertEqual(["test-assertion-removed"], [f["rule"] for f in findings])
self.assertEqual((name, 12, "high", "bug"), (findings[0]["file"], findings[0]["line"], findings[0]["sev"], findings[0]["class"]))
for line in ("expect(result).toBe(42)", "self.assertEqual(result, 42)"):
self.assertEqual(1, len(SCANNER.scan_diff(self.diff([line], []), "low")))
for name in ("src/invoice.py", "src/contest.py", "docs/testing.md"):
self.assertEqual([], SCANNER.scan_diff(self.diff(["assert value"], [], name), "low"))
def test_added_skip_markers_are_high_bug_findings(self):
for text in ("@pytest.mark.skip", "@pytest.mark.xfail", "describe.skip('case', run)",
"it.skip('case', run)", "xit('case', run)", "@Disabled", 't.Skip("pending")'):
with self.subTest(text=text):
findings = SCANNER.scan_diff(self.diff([], [text]), "low")
self.assertEqual(["test-skip-added"], [f["rule"] for f in findings])
self.assertEqual(("high", "bug", 20), (findings[0]["sev"], findings[0]["class"], findings[0]["line"]))
self.assertEqual([], SCANNER.scan_diff(self.diff([], [text], "src/invoice.py"), "low"))
def test_new_tautologies_are_high_bug_findings(self):
for text in ("assert True", " assert True, 'always passes'", "expect(true).toBe(true);"):
with self.subTest(text=text):
findings = SCANNER.scan_diff(self.diff([], [text]), "low")
self.assertEqual(["test-tautology-added"], [f["rule"] for f in findings])
self.assertEqual(("high", "bug"), (findings[0]["sev"], findings[0]["class"]))
for text in ("assert True == result", "assert TrueValue", "assert result", "expect(result).toBe(true)"):
self.assertEqual([], SCANNER.scan_diff(self.diff([], [text]), "low"))
def test_diff_direction_context_comments_and_escape(self):
self.assertEqual([], SCANNER.scan_diff(self.diff(["@pytest.mark.skip"], ["assert value"]), "low"))
for text in ("# assert value", "// expect(value)", "assert value # unslop-ignore"):
self.assertEqual([], SCANNER.scan_diff(self.diff([text], []), "low"))
for text in ("assert True # unslop-ignore", "@pytest.mark.skip # unslop-ignore"):
self.assertEqual([], SCANNER.scan_diff(self.diff([], [text]), "low"))
context = self.diff([], ["assert result"]) + " assert True\n"
self.assertEqual([], SCANNER.scan_diff(context, "low"))
def test_diff_multiple_hunks_deleted_files_and_quoted_paths(self):
diff = ('--- "a/tests/test invoice.py"\n+++ /dev/null\n@@ -5,1 +0,0 @@\n-assert value\n'
'\\ No newline at end of file\n'
'--- a/invoice.test.ts\n+++ b/invoice.test.ts\n@@ -2,0 +3,1 @@\n+it.skip("case", run)\n'
'@@ -8,0 +10,1 @@\n+expect(true).toBe(true)\n')
findings = SCANNER.scan_diff(diff, "high")
self.assertEqual([("tests/test invoice.py", 5), ("invoice.test.ts", 3), ("invoice.test.ts", 10)],
[(f["file"], f["line"]) for f in findings])
def test_clean_fixtures_have_zero_findings(self):
self.assertEqual(3, len(list((FIXTURES / "clean").iterdir())))
self.assertEqual([], SCANNER.scan(str(FIXTURES / "clean"), "low"))
def test_every_rule_fires_on_a_dirty_fixture(self):
findings = SCANNER.scan(str(FIXTURES / "dirty"), "low")
for path in (FIXTURES / "dirty").rglob("*.diff"):
findings.extend(SCANNER.scan_diff(path.read_text(encoding="utf-8"), "low"))
self.assertEqual({r["id"] for r in SCANNER.RULES}, {f["rule"] for f in findings})
def test_project_scan_skips_fixtures_but_direct_path_scans_them(self):
files = set(SCANNER.iter_files(str(SCRIPT.parents[1])))
self.assertIn(str(Path(__file__)), files)
self.assertNotIn(str(FIXTURES / "dirty" / "handler.py"), files)
self.assertIn(str(FIXTURES / "dirty" / "handler.py"), set(SCANNER.iter_files(str(FIXTURES / "dirty"))))
def cli(self, args, stdin=""):
output = io.StringIO()
with patch.object(sys, "argv", [str(SCRIPT)] + args), patch.object(sys, "stdin", io.StringIO(stdin)), contextlib.redirect_stdout(output):
with self.assertRaises(SystemExit) as result:
SCANNER.main()
return result.exception.code, json.loads(output.getvalue())
def test_diff_stdin_cli_keeps_json_shape_and_high_count_exit(self):
diff = (FIXTURES / "dirty" / "integrity.diff").read_text(encoding="utf-8")
code, report = self.cli(["--diff", "--json"], diff)
self.assertEqual(3, code)
self.assertEqual({"path", "files_scanned", "counts", "class_counts", "slop_score", "verdict", "findings"}, set(report))
self.assertEqual(1, report["files_scanned"])
self.assertEqual({"high": 3}, report["counts"])
def test_diff_base_runs_git_diff_without_a_shell(self):
diff = self.diff(["assert value"], [])
with patch.object(SCANNER.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, stdout=diff)) as run:
code, report = self.cli(["--diff-base", "main", "--json"])
self.assertEqual(1, code)
self.assertEqual("test-assertion-removed", report["findings"][0]["rule"])
self.assertEqual(["git", "diff", "--no-ext-diff", "--no-color", "main", "--"], run.call_args.args[0])
self.assertTrue(run.call_args.kwargs["check"])
def test_diff_base_also_accepts_diff_flag_and_repo_path(self):
with patch.object(SCANNER.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, stdout="")) as run:
code, report = self.cli([str(SCRIPT.parents[1]), "--diff", "--diff-base", "main", "--json"])
self.assertEqual(0, code)
self.assertEqual([], report["findings"])
self.assertEqual(str(SCRIPT.parents[1]), run.call_args.kwargs["cwd"])
def test_new_surface_rules_keep_the_line_escape(self):
for text in ("const result = value as any;", "# Updated to reuse the response",
"function getUserDataFromApiResponseHandler() {}", "# Step 1"):
with self.subTest(text=text):
self.assertTrue(self.rules(text))
self.assertEqual([], self.rules(text + " // unslop-ignore"))
def test_failed_diff_base_exits_two(self):
with patch.object(SCANNER.subprocess, "run", side_effect=subprocess.CalledProcessError(128, ["git", "diff"])), contextlib.redirect_stderr(io.StringIO()):
with patch.object(sys, "argv", [str(SCRIPT), "--diff-base", "missing"]), self.assertRaises(SystemExit) as result:
SCANNER.main()
self.assertEqual(2, result.exception.code)
def test_normal_cli_counts_only_high_findings(self):
code, report = self.cli([str(FIXTURES / "dirty" / "handler.py"), "--json"])
self.assertEqual(2, code)
self.assertEqual(report["counts"]["high"], code)
self.assertGreater(report["counts"]["medium"], 0)
code, report = self.cli([str(FIXTURES / "dirty" / "surface.ts"), "--json"])
self.assertEqual(0, code)
self.assertTrue(report["findings"])
def test_severity_filter_preserves_high_findings(self):
code, report = self.cli([str(FIXTURES / "dirty" / "handler.py"), "--severity", "high", "--json"])
self.assertEqual(2, code)
self.assertEqual({"high"}, {f["sev"] for f in report["findings"]})
def test_generic_naming_is_caught(self):
self.assertEqual(["generic-naming"], self.rules("def process_data(x):\n return x\n"))
def test_emoji_in_source_is_caught(self):
self.assertEqual(["emoji-in-code"], self.rules('print("done ✅")\n'))
# ---- escape hatch ----
def test_unslop_ignore_line_is_skipped(self):
self.assertEqual([], self.rules("def process_data(x): # unslop-ignore\n return x\n"))
# ---- verdict: low-severity noise must not read as STRONG ----
def test_many_low_findings_never_reach_strong(self):
self.assertEqual("Mostly clean, minor tells", SCANNER.verdict({"low": 40}, 40))
def test_three_highs_reach_strong(self):
self.assertEqual("STRONG AI-written-code tells", SCANNER.verdict({"high": 3}, 9))
def test_clean_is_clean(self):
self.assertEqual("Clean, no surface tells detected", SCANNER.verdict({}, 0))
if __name__ == "__main__":
unittest.main()
skills/a-unslop-text/SKILL.md9.9 KB
---
name: a-unslop-text
description: "Remove generic, padded or machine-written phrasing while keeping the author's voice. Use when writing, editing, reviewing or auditing substantive reader-facing prose: docs, READMEs, blog posts, emails, commit bodies and site copy. Also trigger for \"sounds like AI\", \"de-slop this\", \"make it sound like me\" or \"is this slop\". Apply during prose work even when AI is not mentioned. Includes a style scanner and a method for building a voice profile from real writing. Checks style, not authorship. Skip tiny labels, routine code comments and one-line mechanical edits."
---
# a-unslop-text
This skill checks writing for the patterns that make it read as machine-written and helps you revise it. The scanner is `python3 "${CLAUDE_SKILL_DIR}/scripts/unslop_text_scan.py" <path>`; the manual review covers what a scanner cannot see.
**This skill does not write well for you, and it does not impose a single house voice.** It does two narrow things. It removes the specific cues that make text read as machine-written, and where the text reads as AI because nobody chose a voice, it forces a deliberate, register-appropriate one. The argument and what you actually want to say are still yours. A guardrail is not a writer.
Most of the work is the first thing, and most of the first thing is mechanical. The configured dash rule calls for a comma or a period where it fits. Figurative `delve into` can become `look at`. The sycophantic opener gets cut. The `as an AI` boilerplate gets deleted. Those are not style calls; there is no voice to invent. Lead with the plain fix. Reserve the deliberate-voice work for the stylistic choices.
## How this fits alongside a house style guide
This is the depth layer, not the floor. If you already have an always-on style floor (a house style doc, a project CLAUDE.md rule: no em dash, no bookending, contractions, match length to the question), that floor still applies whether or not this skill loaded. This skill owns the full banned-vocabulary catalog and the scanner, so a single list stays canonical instead of drifting across every project that keeps its own copy.
If you also have a write-time hook that blocks the em dash on public-facing content, that hook and this skill's scanner share the same rule and neither re-derives it: the hook stops it at write time, the scanner catches it at audit time everywhere else.
Per-project overlays sit on top of this layer, not under it: a project's own terminology, provenance rules, and register choice, or a first-person brand voice a project already keeps. Those overlays describe the project; this skill describes the prose.
## The trap to avoid
The failure mode of every anti-AI-writing effort is swapping one default register for another. The smooth corporate voice (the em dash, `delve`, a bulleted list for everything, a tidy "in conclusion") was the 2024 default. The 2026 over-correction is its mirror: staccato three-word fragments, forced lowercase, a `here's the thing` cold open, a swear bolted on, fake typos to beat a detector. Wikipedia dates dash overuse to 2022 through September 2026 and reports newer models tuned to avoid dashes, with plain words and short 8-20 word sentences. Dash-free short plain prose is no longer evidence of a human. Review uniform short sentences and punctuation impoverishment instead, with reader context in mind. The dash ban is a house preference, not an authorship signal. (source: Wikipedia:Signs of AI writing, 2026-10) The fix for a dash is a comma in a sentence you would actually write, not an ellipsis and not a contortion around the gap. See `references/writing-with-intent.md`.
## Not an AI detector
Detectors return a probability and are wrong often enough to ruin a real writer's day. This skill does not guess who wrote something. It finds configured style violations and advisory patterns, removes them, and then asks for a human read on rhythm, substance, and voice. It adds a deterministic scanner you can run in CI and an explicit warning against the over-corrected register.
## Build mode
Most "sounds like AI" outcomes are a specification problem, not a wording one. A prompt that sets no tone or audience gets the model's most generic voice. So before drafting anything for a reader, choose the register (how formal the writing is) (A casual / B conversational-professional / C expository / D formal), then a speaker inside it, then state the claim in a sentence. `references/writing-with-intent.md` is the method. Then write, avoiding the tells in `references/tells.md`.
The ban list alone gets you to clean, not to you. So before drafting under a real person's byline, check whether they have a voice profile: a short file describing the phrasing habits in their own writing from before they used AI, the tone they use for each destination, and the vocabulary level they write at. Ask if you don't know. If they do, the speaker step is already answered: load the profile and hold it. If they don't, do not silently produce generic text under their name. Offer the choice: build one now with them (about an hour following `references/voice-profile.md`, and it moves a draft further toward its author than everything else in this skill combined), or proceed and say plainly the result will read as clean, not as them. Keep any resulting profile private; the method is shareable, the output is personal data.
If you already have a default register for chat and most docs (say, terse: verdict first, short sentences, fragments for punch, no preamble), that is a chosen register, not the model's default, so hold it. Do not pad it back toward generic model prose, and do not over-correct it into performative fragments.
## Audit mode
When reviewing or cleaning existing prose, or on "does this sound like AI / de-slop this / make it sound like me," run the scanner first, then fix in priority order.
```bash
python3 "${CLAUDE_SKILL_DIR}/scripts/unslop_text_scan.py" <path> # report + slop score
python3 "${CLAUDE_SKILL_DIR}/scripts/unslop_text_scan.py" <path> --severity high # only the hard bans (gated tier)
python3 "${CLAUDE_SKILL_DIR}/scripts/unslop_text_scan.py" <path> --json # for CI
```
It scans `.md .markdown .mdx .txt .rst .html`, skips any `fixtures` directory beneath a `test` or `tests` directory during traversal (explicit file paths still scan), reports each finding with file, line, matched text, and fix, plus a configured-style score and density per 1,000 authored words. Exit code is `1` when any high-severity violation exists, `0` when none exists, and `2` for invalid input.
HTML tags and attributes, script/style bodies, and comments are excluded from authored prose. Markdown emphasis, heading prefixes, and list markers are removed for phrase matching. Paragraph whitespace is normalized for phrase matching, with findings mapped to source lines. HTML block tags separate paragraphs; inline tags preserve surrounding text.
Be honest about what the scanner is: a lexical style filter. It catches the em dash, the high-signal diction, the antithesis cadence, the formatting tics. It cannot judge authorship, factual value, originality, uniform rhythm, or whether a paragraph earns its space. A clean scan means the configured lexical layer is clean, not that the writing reads as a person. After every scan, run the structural and concision pass in `references/tells.md`.
For the concision pass, test every paragraph and sentence: keep it only if it adds a claim, evidence, a decision, an exception, necessary context, or a reader action. Cut it when removing it changes nothing. Do not shorten away a requirement, a factual caveat, or a source.
After a rewrite, compare it with the original: numbers, names, dates, URLs, citations, negations (`not`, `never`, `no`), and modals (`must`, `should`, `may`) must survive unchanged, and nothing may be invented. See the meaning check in `references/tells.md`. `python3 "${CLAUDE_SKILL_DIR}/scripts/unslop_text_scan.py" --compare ORIGINAL REWRITE` checks token inventories for numbers, URLs, negations, and modals (advisory, exit 0); verify meaning and attribution by hand, then rescan the rewrite.
**Escape hatch.** A line containing `unslop-ignore` or `voice-allow` is skipped, for a tell used on purpose (a verbatim citation, a section name, a deliberate register). `voice-allow` accepts comments such as `<!-- voice-allow: reason -->`. Use it sparingly; if you reach for it more than once or twice per pass, the rule probably needs adjusting.
**Fixing well.** Do not fix `delve into` by swapping in `dive into`, which is another tell. Use the plain verb you would actually say. A fix that introduces the over-corrected register (choppy fragments, fake typos) is not a fix.
## What it does not flag
Grounded in what readers actually cite, not a keyword pass. Lone `however`, `thus`, a single register-appropriate `crucial`, a real thematic-break `---`: these are usually the writer's own prose, not a tell. The scanner leaves them alone (the DO NOT CHASE section of `references/tells.md`). Over-flagging trains people to ignore the tool, so the scanner stays narrow.
## Reporting an audit
Lead with the verdict and the single highest-impact change. Then findings by priority with file:line and the fix. Close with the configured-style score and the top three changes, reported as a style measurement and not as a claim about who wrote the text. Plain and specific. The goal is prose that reads like one person who meant it, which is the one thing the scanner cannot do for them.
## Credits
The over-correction framing, the register model, and the scanner design are adapted from the vibecoded-design-tells research by JCarterJohnson (https://github.com/JCarterJohnson/vibecoded-design-tells, MIT). The banned-vocabulary list and its tiers here are this skill's own merge of several style guides into one canonical source; the shape and the over-correction idea come from that project. `scripts/unslop_text_scan.py` is an adapted fork of its text scanner (MIT); the credit is in its header.
skills/a-unslop-text/agents/openai.yaml103 B
interface: display_name: "Unslop Text" short_description: "Review writing for generic AI phrasing"
skills/a-unslop-text/references/tells.md17.2 KB
# The prose tells: the catalog
This is the human-readable view of the vocabulary and patterns in `scripts/unslop_text_scan.py`. The documentation and the implementation must agree. Treat any mismatch as a defect; neither silently overrides the other.
The catalog combines style preferences and sourced review cues. HIGH gates the exit code. MEDIUM and LOW are advisories. These are configured style rules and review prompts, not an authorship test. Thresholds are heuristics, not measured detection accuracy.
Provenance tags distinguish observational sources from owner preferences. [Wikipedia:Signs of AI writing](https://en.wikipedia.org/w/index.php?oldid=1380310647&title=Wikipedia:Signs_of_AI_writing) is the dated reference for Wikipedia tags below. The vocabulary changes over time; [Human-LLM Coevolution: Evidence from Academic Writing](https://aclanthology.org/2025.findings-acl.657/) documents that drift in academic writing. Neither validates this scanner across genres.
## HIGH: gated violations
### The em dash and en dash (house preference)
Unicode `U+2014` and `U+2013`, including the HTML entities `—` / `–`, are banned even inside quotes. The fix is a comma, a period, parentheses, or a colon when it fits the sentence. Avoid contortions around the gap. If a project also uses a write-time dash hook, the scanner catches the same rule at audit time. This is a house preference, not a detection signal.
### High-signal vocabulary (house preference)
These configured phrases gate on a single use. The earlier-era words are separated below because their generic severity changed.
| Configured word or phrase | Prefer |
|-|-|
| `dive into`, `let's dive`, `dive deeper`, `let's unpack this`, `unpack the issue` | look at, examine, go through |
| `synergy` / `synergies` | describe the specific interaction |
| `holistic` | whole, end-to-end |
| `cutting-edge` | new, the specific capability |
| `game-changer` | what actually changes |
| `unleash` | the specific result |
| `best-in-class` | what makes it good |
### Earlier-era vocabulary: contextual advisory (source: Wikipedia:Signs of AI writing, 2026-10)
The `era-vocab` rule reports figurative `delve`, `paradigm`, `realm`, `tapestry`, `beacon`, `testament`, `myriad`, and `plethora` as MEDIUM advisories. Wikipedia supplies the era context; this retained list and its severity are owner policy, not a claim that every term belongs to one measured cohort. (house preference)
Recognized literal and technical contexts pass. Textile cues immediately before `tapestry`, such as `woven`, `handwoven`, `silk`, `wool`, and `medieval`, or a tapestry hanging on or covering a wall, support a literal reading. `A woven tapestry of Saint George covers the wall` passes. Figurative `rich tapestry`, `tapestry of ideas`, and `we have woven a tapestry celebrating our community` still fire. Named programming, computing, software, scientific, functional, object-oriented, dataflow, logic, imperative, and declarative paradigms pass, as do recognized physical radio/navigation beacons, Kerberos/DNS/authentication realms, and the Old or New Testament. Bare `paradigm shift` remains advisory; a named technical paradigm passes. These narrow context checks can miss unfamiliar literal uses; review those and use the escape hatch when justified. (house preference)
### Vocabulary by era (source: Wikipedia:Signs of AI writing, 2026-10)
These are reading cues, not additional single-word scanner bans. Context and the destination matter more than the date label.
| Era described by Wikipedia | Examples |
|-|-|
| 2023 to mid-2024 | `delve`, `tapestry`, `testament`, `intricate`, `pivotal`, `underscore`, `vibrant`, `meticulous` |
| Mid-2024 to mid-2025 | `align with`, `enhance`, `fostering`, `highlighting`, `showcasing`, `underscore` |
| Mid-2025 to mid-2026 | `emphasizing`, `enhance`, `highlighting`, `showcasing` |
| Mid-2026 onward | `challenge`, `clearer`, `dependable`, `echoed`, `foster`, `leverage`, `matters`, `multifaceted`, `practical`, `prioritize`, `quietly`, `steady`, `universally` |
The last row comes from a review blog cited by Wikipedia, so treat it as moderate evidence. `current-era-cluster` reports MEDIUM only when at least three distinct listed words occur within 300 authored words. Repeating one term does not qualify. This rule matches the listed forms, not every inflection. The plain-word vocabulary rule can also flag local clusters containing `foster` or `leverage`; `multifaceted` alone no longer gets a LOW finding. (source: Wikipedia:Signs of AI writing, 2026-10)
### Plain-word vocabulary clusters (house preference)
One use passes and two or more within 300 authored words are MEDIUM. Distant uses do not form a cluster.
| Word | Prefer |
|-|-|
| `leverage` | use, apply, build on |
| `utilize` / `utilise` | use |
| `robust` | reliable, handles edge cases, or describe the behaviour |
| `comprehensive` | covers the named scope |
| `seamless` | works without an extra step |
| `streamline` | cut steps, simplify |
| `foster` | build, support, grow |
| `empower` | let, give, enable |
| `unlock` | name the result |
| `elevate` | improve, raise |
### Contextual consultant compounds (house preference)
Gate phrases such as `competitive landscape`, `regulatory landscape`, `market landscape`, `navigate the complexities`, `product ecosystem`, `partner ecosystem`, `strategic alignment`, and `customer alignment`. Literal landscape orientation, browser navigation, and biological ecosystems pass. `cross-product synergies` is caught by the vocabulary rule.
### Stacked connective openers (house preference)
`Moreover`, `Furthermore`, `Additionally`, `Consequently`, `Notably` at a line start or after a period. Start with the new point. The scanner flags a single configured opener; it does not require several.
### The antithesis cadence (source: Wikipedia:Signs of AI writing, 2026-10)
The scanner gates promotional `it's not just X, it's Y`, `not just X, but Y`, and related `only`/`merely` forms. `It's not just a tool, it's a movement` still fires, including curly apostrophes, expanded `it is`, multiword noun phrases, and `but a movement` endings. Plain `not X, but Y` is a human review cue, not a general regex ban.
A factual correction of cause should pass: `failed not because the file is missing but because access was denied`. The scanner leaves `not because X but because Y` alone, rather than guessing whether the causes are factual. This heuristic can miss a rhetorical causal contrast; judge that in the human pass. Do not delete a real correction to satisfy cadence advice. (house preference)
### The assistant voice leaking in (house preference)
`as an AI language model`, a refusal (`I cannot assist`), a `knowledge cutoff` line, `I don't have personal opinions`. Remove assistant boilerplate from reader-facing copy. Quoted discussion and examples are skipped.
### Sycophancy and the apology reflex (house preference)
`Great question`, `Certainly!`, `You're absolutely right`, `I'd be happy to`, `happy to help`, `good catch`, `I apologize for the confusion`. Open with the point. When wrong, acknowledge it briefly and fix it.
### Filler and preamble patterns (house preference)
`it's important to note`, `it's worth mentioning`, `in today's [anything]`, `let me break this down`, `Imagine a world where`, `Picture this`, `that being said`, `With that in mind`, `At the end of the day`, `needless to say`. State the thing.
### Bookending and trailing offers (house preference)
`I hope this helps`, `Let me know if you need more`, `Would you like me to`, `is there anything else`, `feel free to reach out`, `hope this email finds you well`, `happy to answer`. In chat replies and docs, cut empty assistant bookends and stop at the last useful point. In an actual email to a colleague, a real invitation such as `Let me know if you need more` or a polite closer is fine. Judge whether it invites a useful reply in that relationship. The scanner still flags these phrases; retain a justified email use with `voice-allow` or `unslop-ignore` and a reason.
### Leaked citation or renderer markup (source: Wikipedia:Signs of AI writing, 2026-10)
`contentReference`, `oaicite`, `oai_citation`, `turn0search` followed by digits, `attributableIndex`, `grok_card`, `<grok-card>`, `grok_render_citation_card_json`, `[cite: N]` with one or more comma-separated numeric values, `[span_N](start_span)` with a numeric N, and `ppl-ai-file-upload` are HIGH. Delete the markup and restore the real citation. Never invent a source. Structured JSON citation keys are checked before prose quote stripping, so `({"attribution":{"attributableIndex":"1009-1"}})` is caught. Code, blockquote, and ignore escapes still apply; ordinary quoted prose examples pass.
## MEDIUM: use sparingly (advisory)
- **Worn social-post templates**: `the guide I wish existed`, `I kept seeing X, so I built Y`, `I saw a gap, so I made this`. MEDIUM advisory; review especially closely in short outreach copy. Lead with what the thing is. A dropped-pronoun opener (`Made a free guide for...`) passes. (house preference)
- **Cross-sentence antithesis**: `The value was not typing speed. It was the forcing function.` / `The speed was not the interesting part. The interesting part was...`. The scanner catches the split cadence; preserve an informative correction on human review. (source: Wikipedia:Signs of AI writing, 2026-10)
- **Frequency-sensitive words**: `crucial`, `vital`, `essential`, `essentially`, `fundamentally`, `various`, `versatile`, `significant`, `genuinely`, `nuance`, `meticulous`, `showcase`, `straightforward`, `precisely`, `dramatically`, `incredibly`, `particularly`, `ultimately`. Two or more within 300 authored words are advisory; one or distant uses pass. (house preference)
- **Softeners**: `simply run X`, `just click Y`. Drop a word that implies the instruction is trivial. (house preference)
- **Bolded lead-in labels**: `**Word:**` before prose is advisory. A list gets the separate `bolded-label-list` advisory only for three or more consecutive Markdown list items with bolded labels, including `- **Owner:** text` and `- **Owner**: text`. One or two pass. Blank lines and indented wrapped continuations preserve the run; an unlabelled item, heading, or paragraph outside the list breaks it. Useful definition lists and work-email labels can stay on review. (source: Wikipedia:Signs of AI writing, 2026-10)
- **Staged reveals**: sentence-initial `The result:`, `The catch?`, `The kicker:`, `The payoff:`, `The twist:`, `The answer:`, `The truth?`. The tell is manufactured revelation, not the colon or question mark itself. (source: workbravely.substack.com/p/sentences-that-sound-like-other-sentences, 2026-07)
- **Significance tails**: `, highlighting the`, `, underscoring its`, `, reflecting their`, `, symbolizing a`, `, showcasing the`, `, emphasizing the`. The scanner accepts any listed participle followed by `the`, `its`, `their`, or `a`. Check that the tail adds a supported inference rather than borrowed importance. (source: Wikipedia:Signs of AI writing, 2026-10)
- **Listicle scaffolding**: `5 ways to`, `7 signs`, `3 reasons`. Ambiguous `things`, `steps`, and `rules` need a heading or listicle continuation such as `to`, `for`, or `you`; plain counts pass. (house preference)
- **Decorative emoji** as a bullet, icon, or heading. Banned unless the user used emoji first in the conversation. Inline conversational emoji can stay. (house preference)
- **Signposted closers**: `In conclusion`, `In summary`, `to summarize`. End on a useful point. (house preference)
- **Hedging when you have a view**: `you might want to consider`, `it may be worth`, `perhaps you`, `on one hand ... on the other`, `it depends`. Keep real uncertainty and trade-offs; state your recommendation. (house preference)
- **Marketing hype**: `revolutionary`, `transformative`, `supercharge`, `to the next level`, `say goodbye to`, `look no further`. Say what the thing does. (house preference)
- **Literary/native flourish (check against the byline)**: `whilst`, `amongst`, `endeavour`, `ascertain`, `elucidate`, `quintessential`, `notwithstanding`, `henceforth`, `hitherto`, `whereby`, `thereby`, `wherein`, `albeit`, `one might`. These are byline choices, not generic AI tells. The scanner raises a MEDIUM advisory; keep vocabulary that fits the author. Build a private voice profile using `references/voice-profile.md`. (house preference)
## LOW: weak or contextual (advisory)
- **Inflated generic diction**: `facilitate`, `paramount`, `pivotal`, `intricacies`. Prefer the plain word. (house preference)
- **Work-announcement preambles**: `Let me take a look`, `I'll start by`, `Here's a breakdown of`. The reader needs the result. (house preference)
- **Fake-relatability openers**: `Honestly,`, `Look, I get it`, `Let's be real`. (house preference)
- **Copula avoidance**: `serves as a`, `stands as an`, `serves as the`. Use `is` or `are` when the phrase only renames the subject. A real function or role can justify it; this is a weak advisory. (source: Wikipedia:Signs of AI writing, 2026-10)
## DO NOT CHASE (deliberately not flagged)
- Ordinary `however`, `thus`, and `hence` connectives. (house preference)
- `when it comes to`, a single `crucial`, or a single `comprehensive` in generic prose. (house preference)
- Technical `unpack a tuple` and the literal vocabulary exceptions described above. (house preference)
- A horizontal rule (`---`) as a real thematic break. (house preference)
## STRUCTURAL (human pass)
- **Uniform rhythm and punctuation impoverishment.** Similar sentence lengths and shapes can sound mechanical, including uniform short sentences. Wikipedia now dates dash overuse to 2022 through September 2026 and describes newer models avoiding dashes while leaning on plain words and 8-20 word sentences. Dash-free plain prose is no evidence of a human. Read for rhythm that fits the argument; the dash ban remains a configured house preference. (source: Wikipedia:Signs of AI writing, 2026-10)
- **Rhythmic triads.** Three items or matching sentences just to tie up a paragraph. A natural list of three is fine. (source: Wikipedia:Signs of AI writing, 2026-10)
- **Sycophancy as tone.** Reflexive agreement without a position. Disagree when you disagree. (house preference)
- **Saying nothing at length.** Fluent prose with no claim. Cut a paragraph if nothing is lost. (house preference)
- **Low substance per word.** Keep claims, evidence, decisions, exceptions, necessary context, requirements, source caveats, and reader actions. Cut repetition and process narration. (house preference)
- **Same paragraph openings.** Repeated openings such as `This` can expose a template. (house preference)
- **The `. That's [adjective].` tic.** Repeated evaluations after facts add little. Let the fact speak or explain its consequence. (house preference)
- **`Think of it as / like` as an analogy launcher.** Make a useful analogy directly. (house preference)
- **Setup before the point.** Lead with the strongest claim when the reader needs it first. (house preference)
- **False ranges.** `from X to Y` implies breadth without endpoints on a coherent scale or whole, such as `from teenagers to managing directors`. Genuine geographical, chronological, and organizational ranges pass. Human-only: no regex. (source: workbravely.substack.com/p/sentences-that-sound-like-other-sentences, 2026-07)
- **Mini-report scaffolding in short pieces.** A short answer split into title-case headings, tiny sections, and unnecessary tables can add ceremony without value. Keep structure that helps this destination and reader. Human-only: no regex. (source: Wikipedia:Signs of AI writing, 2026-10)
- **Overdone voice mimicry.** Repeating the author's signature phrases in every paragraph is an impression. Hold the phrasing habits and register in their private voice profile; `references/voice-profile.md` explains how to build one. (house preference)
### A chosen terse register
Short sentences, earned fragments, and blunt verdicts are a chosen register, not a detection signal. Do not pad them to force variation. Over-correction is prose straining to look human: fragments on every beat, forced lowercase, a swear bolted on, conspicuous punctuation avoidance. Hold a real voice and give thoughts enough connective tissue for the destination.
## Post-rewrite meaning check (house preference)
Compare original and rewrite before delivery. Verify that numbers, names, dates, URLs, citations, negations (`not`, `never`, `no`), and modals (`must`, `should`, `may`) survived unchanged. Check that their relationships and scope still mean the same thing and nothing was invented. Restore lost facts or qualifications, then rescan for style and structure.
`python3 "${CLAUDE_SKILL_DIR}/scripts/unslop_text_scan.py" --compare ORIGINAL REWRITE` lists differing token counts for signed numbers (including exponents), full URLs with balanced parentheses, negations (including `cannot` and `can't`), and modals (including `can`). Curly and ASCII apostrophes compare equally. Surrounding Markdown link punctuation is excluded from URL tokens. It is advisory and exits 0 for a valid comparison, even when differences exist; unreadable files are invalid input and exit 2. It uses full file text and does not apply scan escapes. Its inventories cannot detect moved negations, swapped subjects, invented claims using the same tokens, or changed names and citations. Human comparison is required; identical inventories do not prove meaning survived. Comparison is text-only; the existing scan JSON schema is unchanged.
skills/a-unslop-text/references/voice-profile.md6.8 KB
# Build a voice profile from your own writing
**This is a method, not a template.** You do not fill this file in. Following the steps below produces a *separate* file, your voice profile, which you keep in your own private config and point the skill at. This method file is generic and shareable; the profile it produces is personal data, so keep it private and never ship it in a public bundle.
The ban catalog has a ceiling. Remove every tell from a draft and you get text that is clean and correct but still generic, with nothing of the author in it. What makes text read as a specific person was never the absence of `delve`; it is a set of habits the author does not know they have. This file is the method for extracting those habits from your real writing and turning them into a profile the Build mode can load. An hour with your own sent emails buys more authenticity than any banned-word list.
## Step 1: gather real samples
Collect 10 to 15 pieces you actually wrote, before AI assistants were involved, across more than one register: work emails you sent, feedback you gave on someone's work, a doc or spec you wrote alone, chat messages, a post if you have one. Unedited and unpolished beats curated. The typos stay in for now; they carry information for step 6.
Two things matter about the sample set. It must be yours alone (in shared documents, other contributors' sections sneak in; drop anything you did not write yourself). And it should span situations, because the interesting part is what changes between them and what does not.
## Step 2: extract moves, not phrases
A move is a repeatable decision about how you handle a situation in prose. Phrases are what the move leaves behind. Profile the moves; list the phrases only as evidence.
Questions that surface moves, with the kind of answer you are looking for:
- **How do you open?** Position first ("Agree, with one change...") or context first ("Some background before I answer...")? Whichever it is, it is probably consistent, and it is probably the strongest single marker you have.
- **How do you disagree?** Flat contradiction, a softened "not sure this holds because...", a question that carries the objection ("would this survive two concurrent users?")?
- **Do your suggestions travel with their reasons?** Some writers attach a "because" to every proposal; others state the proposal bare and defend it only if challenged.
- **Where does your opinion live?** In the main clause, in a parenthetical aside, in a dry closing fragment?
- **How do you handle uncertainty?** Hedge words, explicit confidence levels, silence until sure?
- **What do you do with numbers?** Some writers reach for a figure wherever one exists; others reach for an adjective.
- **How do you close?** A named owner and a next step, a one-word sign-off, nothing at all?
Write each move as one line with one or two short real examples from your samples. Eight to twelve moves is a full fingerprint; more than that and you are cataloging noise.
## Step 3: map your registers
You are not one voice; you are one identity at different intensities. Map your real destinations (email, chat, docs, posts, specs) onto the A/B/C/D register model in `writing-with-intent.md`, and note what changes between them: where the softeners drop away, where fragments appear, where the wit is allowed out. The profile should say which moves are always on and which belong to one register only.
## Step 4: set a language ceiling (the vocabulary level you actually write at)
This is the step most people skip and the one that catches the most ghostwriting. The model's natural register is polished, native, faintly literary English. If that is not how you write, every draft published under your name is dressed in someone else's vocabulary, and readers who know you notice even when they cannot say what is off.
State the ceiling explicitly. For a non-native author the effective instruction is: **write in clean C1 English**. Grammar and spelling always correct, but everyday professional vocabulary, main clause first, at most one subordinate clause, no rare idioms a language learner would not use, plain intensity words. Correct is not the same as fancy. For a native author with a plain register, the same idea applies with a different label: cap the vocabulary at how you talk in a meeting, not how you would write an essay.
The scanner's `c2-flourish` rule backs this ceiling from the ban side, but the ceiling belongs in the profile because it is a positive instruction, not a list of exceptions.
## Step 5: signature phrases, capped
List the phrases that recur in your samples. Then cap them: at most one or two per generated piece, and only where they would fall naturally. This anti-parroting rule is load-bearing. A draft that hits four of your signature phrases is an impression of you, which reads worse than a plain draft; the moves carry the voice, the phrases are incidental. (Same logic as the over-correction trap in `tells.md`: an overdone costume is its own tell.)
## Step 6: list what not to copy
Now use the typos. Recurring misspellings, dropped articles, run-on chains, inconsistent capitalization: these are typing artifacts and second-language slips, not voice. The profile should name them explicitly as things never to reproduce, because a model shown your raw samples will otherwise imitate them, and deliberate fake errors are a known over-correction tell. The recognizable signal survives cleanup; the slips do not need to.
## Step 7: set precedence
One line at the end of the profile: the ban catalog (`tells.md` and the scanner) always wins. The profile chooses among what the bans allow; it never licenses a banned form. If one of your real habits collides with a hard ban (plenty of real people close emails with a phrase that is now an assistant tell), the ban wins for generated text, because the reader cannot tell your habit from the machine's.
## The template
```markdown
# <name>'s voice profile
Private. Derived <date> from <n> samples (<kinds>). Never ships in a public bundle.
## Who is speaking
<two or three sentences: role, stance, what they connect when they argue>
## The moves
<8-12 one-liners, each with a short example>
## Register dial (the tone you use for each destination)
<destination -> register letter + which moves intensify or drop>
## Language ceiling (your vocabulary level)
<e.g. "Write in clean C1 English: ..." with the concrete rules>
## Signature phrases (evidence, not injection)
<the list, then: max 1-2 per piece, never mechanically placed>
## What not to copy
<typing artifacts, normalized away>
## Precedence
tells.md and the scanner always win.
```
## Using it
Wire the profile into the Build mode flow: pin the register per piece as usual, and when the byline is the profile's owner, the speaker step is already answered. Load the profile and hold it. Then audit as always; the scanner catches the bans, and your own read catches whether the person on the page is you.
skills/a-unslop-text/references/writing-with-intent.md5.0 KB
# Writing in a chosen voice This file does not hand you a voice to copy. Any fixed style, repeated, becomes the next default and the next tell. The smooth corporate voice was the 2024 default; the clipped, lowercase, swear-to-seem-real voice is the 2026 over-correction, and it can read as a machine trying not to look like a machine. So this is a way to decide what the writing is, not a thing to imitate. The goal is one outcome: prose where every choice has a reason specific to this piece. That is the one property a default can never have. ## Pin a register, then a speaker A register sets what "plain" means and what counts as a tell. Decide which one the piece is in before anything else: - **A, casual.** Texts, DMs, personal posts. Contractions, fragments, slang, dropped subjects. - **B, conversational-professional** (work email, Slack, updates, changelogs, most chat replies): plain, direct, contractions, light warmth, no throat-clearing. - **C, expository** (essays, READMEs, blog posts, deep-dive docs): a clear argument, varied rhythm, a point of view, paragraphs over bullets. Where most unslopping happens. - **D, formal** (specs, briefs, ADRs, research docs): structured, sourced, impersonal. Formality here is correct, not a tell. The register is the guard against over-correcting. A fragment is native in A and a tell in D. A contraction is right in A through C and wrong in D. A `lol` is voice in A and costume in C. A research doc or ADR is mostly C and D; a first-person blog is mostly C with a named speaker; chat replies are B. Same banned list, different register on top. Then a speaker inside the register. For a project that already has a voice, anchor to it. If you must choose, pick a named direction (plain-technical, blunt operator, dry and concrete) over "professional and engaging," which means nothing. ## The claim Before the body, state the one thing the piece asserts, in a sentence. AI prose reads as empty because it is fluent with nothing to say. If you cannot write the claim, there is nothing to write yet. Every paragraph earns its place against that claim; if one could be cut with nothing lost, cut it. Say it with less: cut the paragraph that restates the claim instead of extending it. ## Structure follows the argument The order is set by what the reader needs first, not a template. That is how you avoid the intro / three-even-body-paragraphs / "in conclusion" skeleton: the shape appears when structure is chosen by default. Most pieces do not need a summary at the end. Reserve bullets for list-like content; argument lives in paragraphs. ## Rhythm and diction Vary sentence length on purpose. Use the plain word: `use` not `utilize`, `look at` not `delve into`. Cut the antithesis cadence and the throat-clearing opener. The point goes in the first sentence, not after a warm-up. ## The over-correction trap (the thing to actually watch) Told to "sound less like AI," a model swings the other way: staccato three-word fragments on every beat, forced lowercase, a `here's the thing` cold open, a swear dropped in to seem casual, every natural dash replaced by an ellipsis or a contorted sentence. Wikipedia dates dash overuse to 2022 through September 2026 and reports newer models tuned to avoid dashes, with plain words and short 8-20 word sentences. Dash-free short plain prose is no longer evidence of a human. Review uniform short sentences and punctuation impoverishment, including prose reduced to periods and commas whatever the thought needs. This is a contextual pattern, not an authorship test. The dash ban remains a configured house preference; a project may enforce it with a write-time hook. (source: Wikipedia:Signs of AI writing, 2026-10) The fix is a real register held consistently, not the absence of voice dressed up as casual. ## A terse register is a choice, not a tell If your default for chat and most docs is terse (short sentences, fragments for punch, the verdict first, no preamble), that can be a deliberate register, so the rhythm-variation note does not have to flag it. Do not "fix" a chosen terse register by padding it back toward generic model prose, and do not over-correct it into performative fragments either. Hold the register; vary length within it when a thought needs room. ## The escape hatch A register or word chosen on purpose is not a tell. A formal ADR is formal. A verbatim citation reproduces external wording. A section name has to match a source. When a flagged form is a real decision, keep it and mark the line `unslop-ignore` (or `voice-allow`, a variant some docs already use), so the audit stays honest. ## Clarity wins If a rule here produces a sentence that reads worse than the alternative, the rule loses. Rewrite the sentence and, if the rule keeps fighting clarity, change the rule (`tells.md` plus the scanner). The rules exist to make writing better, not to constrain it when they fight clarity. ## The one-line version Pin the register, state the claim in a sentence, then write the way that speaker talks and read it back. The skill removes the tells; this is how you replace them with something chosen.
skills/a-unslop-text/scripts/unslop_text_scan.py38.4 KB
#!/usr/bin/env python3
"""
unslop_text_scan.py - scan prose for configured style violations and advisory patterns.
This implementation and references/tells.md are two views of the same policy. A mismatch
is a defect, not a reason for one to silently override the other. Plain Python, standard
library only.
Forked (MIT) from github.com/JCarterJohnson/vibecoded-design-tells (unslop-text). The
scanning machinery (quote/code-span skipping, density weighting, severity floor, JSON
mode, exit-code gating) is upstream's; the RULES are this skill's own merge.
What it can and cannot see. Mechanical style rules live here: the dash rule, high-signal
phrases, plain-word vocabulary, and formatting tics. A regex cannot judge authorship,
originality, factual value, rhythm, or whether a paragraph earns its space. Those need
the structural pass in references/tells.md.
How it reads a file. It lints YOUR running prose. A quoted line (starts with > or sits
inside "double quotes") and a literal example (inside `backticks` or a fenced block) is
skipped, because flagging a cliche you are quoting in order to discuss it would be wrong.
The one exception is the em dash, flagged everywhere, because the rule is simply not to
ship one.
Escape hatch. A line containing unslop-ignore OR voice-allow is skipped, for a tell
used on purpose (a verbatim citation, a section name, a deliberate register). The
voice-allow token matches the <!-- voice-allow: reason --> comment style some docs
already use, so those need no rewrite.
Usage:
python3 unslop_text_scan.py <path> # scan a file or dir
python3 unslop_text_scan.py <path> --severity high # only the hard bans (gated tier)
python3 unslop_text_scan.py <path> --json # machine-readable (for CI)
python3 unslop_text_scan.py <path> --max 8 # cap examples shown per rule
python3 unslop_text_scan.py --compare ORIGINAL REWRITE # advisory meaning check
Exit code is 1 when any HIGH-severity finding exists, 0 when none exists, and 2 for invalid
input. A boolean failure avoids shell exit-code wraparound on files with many findings.
"""
import os, re, sys, json, argparse
from bisect import bisect_right
from html.parser import HTMLParser
EXTS = {".md", ".markdown", ".mdx", ".txt", ".text", ".rst", ".html", ".htm"}
SKIP_DIRS = {"node_modules", ".git", "dist", "build", ".next", "out", "vendor",
"coverage", "__pycache__", ".venv", "venv"}
W = {"high": 3, "medium": 2, "low": 1}
EMOJI = ("\U0001F300-\U0001FAFF\U00002600-\U000027BF\U0001F000-\U0001F0FF"
"\U00002190-\U000021FF\U00002B00-\U00002BFF\U0000FE00-\U0000FE0F\U00002764")
# Each rule has an id, label, default severity, note, fix, and patterns. Optional
# min_hits, window_words, distinct, and consecutive fields adjust local grouping
# without copying patterns. HIGH gates the exit code. MEDIUM and LOW are advisory.
# The dash rule is raw=True because it also covers quoted text.
RULES = [
# ---------- HIGH: gated violations ----------
{"id": "em-dash", "label": "Em dash or en dash (hard ban, anywhere)", "sev": "high",
"note": "configured house preference", "raw": True,
"fix": "Cut it. Use a comma, a period, or parentheses. Use a colon when the sentence calls for one.",
"pats": [r"\u2014", r"\u2013", r"—", r"–"]},
{"id": "high-signal-vocab", "label": "High-signal generic or consultant diction", "sev": "high",
"note": "configured high-signal pattern",
"fix": "Use the plain word or state the concrete behavior. See the high-signal table in tells.md.",
"pats": [r"\b(dives? in(to)?|let'?s dive|diving in|dive deep(er)?( into)?)\b",
r"\bsynerg(y|ies|istic)\b",
r"\bholistic(ally)?\b", r"\bcutting[- ]?edge\b", r"\bgame[- ]?chang(er|ers|ing)\b",
r"\bunleash(es|ing|ed)?\b", r"\bbest[- ]?in[- ]?class\b",
r"\b(?:let'?s\s+unpack(?:\s+(?:this|that|the (?:topic|issue|idea|question|concept|complexity|details?)))?|unpack\s+(?:this|that|the (?:topic|issue|idea|question|concept|complexity|details?)))\b"]},
{"id": "era-vocab", "label": "Earlier-era vocabulary (contextual advisory)", "sev": "medium",
"note": "earlier-era advisory; literal senses pass",
"fix": "Use the plain word for figurative filler. Keep a literal or technical term when it names the thing.",
"pats": [r"\bdelv(e|es|ing|ed)\b", r"\bparadigm(s|atic)?\b", r"\brealm\b",
r"\btapestr(y|ies)\b", r"\bbeacon\b", r"\btestament\b", r"\bmyriad\b", r"\bplethora\b"]},
{"id": "house-vocab", "label": "Plain-word house vocabulary", "sev": "medium",
"min_hits": 2, "window_words": 300,
"note": "one use passes; two or more within 300 words are advisory",
"fix": "Prefer the plain word or describe the behavior. One register-appropriate use is not an authorship signal.",
"pats": [r"\bleverag(e|es|ing|ed)\b", r"\butili[sz](e|es|ing|ed|ation|ate)\b",
r"\brobust\b", r"\bcomprehensive\b", r"\bseamless(ly)?\b",
r"\bstreamlin(e|es|ing|ed)\b", r"\bfoster(s|ing|ed)?\b",
r"\bempower(s|ing|ed|ment)?\b", r"\bunlock(?:s|ed|ing)?\s+(?:(?:your|our|their|the|its|new|full|true|hidden|untapped)\s+){0,3}(?:potential|possibilit(?:y|ies)|opportunit(?:y|ies)|growth|success|creativity|productivity|value)\b",
r"\belevat(e|es|ing|ed)\b"]},
{"id": "consultant-compound", "label": "Contextual consultant-speak compound", "sev": "high",
"note": "phrase-level rule; the same words used literally pass",
"fix": "Name the competitors, the decision, the products, or the relationship instead of the consultant phrase. 'the competitive landscape' is 'who we compete with'.",
"pats": [r"\b(competitive|regulatory|market|vendor|technology|business) landscape\b",
r"\bnavigate the (complexity|complexities|landscape)\b",
r"\b(product|partner|partnership|technology|developer) ecosystem\b",
r"\b(strategic|customer|organi[sz]ational) alignment\b"]},
{"id": "transition-openers", "label": "Stacked connective as a sentence opener (Moreover, Furthermore, Additionally, Consequently, Notably)", "sev": "high",
"note": "hard ban",
"fix": "Just start the new sentence. These mean 'extending a thought without a new idea'.",
"pats": [r"(^|\.\s+|\n)\s*(moreover|furthermore|additionally|consequently|notably)\b"]},
{"id": "antithesis", "label": "\"not just X, it's Y\" / \"not just X, but Y\" antithesis cadence", "sev": "high",
"note": "manufactured-profundity cadence",
"fix": "State the point plainly. If Y is the point, say Y; drop the negation in front.",
"pats": [r"\b(?:(?:it'?s|it is|that'?s|that is|this is|they'?re|they are)\s+not|isn'?t|not)\s+(?:just|only|merely|simply)\s+[^.?!,;]{1,100},?\s+(?:but\b|(?:it'?s|it is|they'?re|they are)\b)"]},
{"id": "assistant-boilerplate", "label": "Leftover assistant boilerplate", "sev": "high",
"note": "the assistant talking; delete",
"fix": "Delete assistant disclaimers, refusals, and knowledge-cutoff lines.",
"pats": [r"\bas an?\s+(ai|a\.i\.)\s+(language\s+)?model\b", r"\bas a large language model\b",
r"\bi (cannot|can'?t|am unable to)\s+(assist|help|fulfil|fulfill|comply|provide)\b",
r"\bknowledge cut[- ]?off\b", r"\bas of my last (knowledge )?(update|training)\b",
r"\bi (do not|don'?t) have (personal|the ability|access|feelings|opinions)\b"]},
{"id": "sycophancy-apology", "label": "Sycophantic opener / apology reflex (\"Great question!\", \"You're absolutely right\", \"I apologize for the confusion\")", "sev": "high",
"note": "flattery / apology paragraph",
"fix": "Drop it; open with the point. When wrong, acknowledge in one line and fix. No apology paragraph.",
"pats": [r"\b(great|good|excellent|that'?s a (great|good))\s+question\b",
r"(^|[\"'`(]\s*)(certainly|absolutely|sure thing|of course)\s*[!,]",
r"\bi'?d be (happy|glad|delighted) to\b", r"\bhappy to help\b",
r"\byou'?re absolutely right\b", r"\bwhat a (great|fascinating|wonderful)\b",
r"\bi apologi[sz]e for (the|any) (confusion|misunderstanding|mistake)\b",
r"\b(good|great) catch\b"]},
{"id": "banned-pattern", "label": "Filler / preamble pattern (\"it's important to note\", \"in today's ...\", \"let me break this down\")", "sev": "high",
"note": "filler",
"fix": "Cut the preamble and state the thing. If it's worth noting, just note it.",
"pats": [r"\bit'?s (important|worth) (to note|noting|mentioning|pointing out)\b",
r"\b(it'?s |it is )?important to (note|remember|understand|recognize)\b",
r"\bin today'?s\b", r"\blet me break (this|it) down\b",
r"\bimagine a world where\b", r"\bpicture this\b",
r"\bat the end of the day\b", r"\bthat being said\b", r"\bneedless to say\b",
r"\bwith that in mind\b"]},
{"id": "bookend-offer", "label": "Bookending / trailing offer (\"I hope this helps\", \"Let me know if ...\", \"Would you like me to\")", "sev": "high",
"note": "bookend; stop at the last real sentence",
"fix": "Delete the sign-off and the meta-offer. If the answer is done, stop.",
"pats": [r"\bi hope this helps\b", r"\bhope (this|it|you'?re) .{0,20}(helps|finds? you well)\b",
r"\blet me know if you'?d?\s*(like|need|want|have)\b",
r"\bwould you like me to\b", r"\bis there anything else\b",
r"\bfeel free to (ask|reach|let me)\b",
r"\bhappy to answer\b"]},
{"id": "citation-markup", "label": "Leaked chatbot citation or renderer markup", "sev": "high",
"note": "tool-output residue; quoted examples still pass",
"fix": "Delete the markup and restore the real citation. Do not invent a source.",
"pats": [r"\b(contentReference|oaicite|oai_citation|turn0search\d+|attributableIndex|grok[-_]card|grok_render_citation_card_json|ppl-ai-file-upload)\b",
r"\[cite:\s*\d+(?:\s*,\s*\d+)*\s*\]", r"\[span_\d+\]\(start_span\)"]},
# ---------- MEDIUM: use sparingly / formatting tic (advisory) ----------
{"id": "frequency-words", "label": "Frequency-sensitive word cluster", "sev": "medium",
"min_hits": 2, "window_words": 300,
"note": "one passes; two or more within 300 words are advisory",
"fix": "Review the local cluster. crucial/vital/essential->important or describe the stakes; essentially/fundamentally->cut; various->name them.",
"pats": [r"\bcrucial(ly)?\b", r"\bvital(ly)?\b", r"\bessential(ly)?\b", r"\bfundamental(ly)?\b",
r"\bvarious\b", r"\bversatile\b", r"\bsignificant(ly)?\b", r"\bgenuinely\b",
r"\bnuanc(e|es|ed)\b", r"\bmeticulous(ly)?\b", r"\bshowcas(e|es|ing|ed)\b",
r"\bstraightforward\b", r"\bprecisely\b", r"\bdramatically\b", r"\bincredibly\b",
r"\bparticularly\b", r"\bultimately\b"]},
{"id": "current-era-cluster", "label": "Mid-2026 vocabulary cluster", "sev": "medium",
"min_hits": 3, "window_words": 300, "distinct": True,
"note": "three distinct terms in 300 words; moderate evidence from a review blog cited by Wikipedia",
"fix": "Read the passage for generic phrasing. Keep ordinary words that do real work.",
"pats": [r"\b(challenge|clearer|dependable|echoed|foster|leverage|matters|multifaceted|practical|prioritize|quietly|steady|universally)\b"]},
{"id": "staged-reveal", "label": "Staged reveal", "sev": "medium",
"note": "routine claim presented as a revelation",
"fix": "State the result or answer directly; keep a real question when the reader needs it.",
"pats": [r"(^|[.?!]\s+)\s*the (result|catch|kicker|payoff|twist|answer|truth)[?:]"]},
{"id": "significance-tail", "label": "Unsupported significance tail", "sev": "medium",
"note": "check whether the source supports the attached inference",
"fix": "Delete the tail unless it adds a supported relationship or fact.",
"pats": [r",\s+(highlighting|underscoring|reflecting|symbolizing|showcasing|emphasizing)\s+(the|its|their|a)\b"]},
{"id": "bolded-label-list", "label": "Consecutive bolded-label bullets", "sev": "low",
"consecutive": 3,
"note": "three or more consecutive Markdown items with bolded labels",
"fix": "Check whether the labels help scanning. Remove them when they split prose into artificial mini-sections.",
"pats": [r"^\s*(?:[-*+]\s+|\d+\.\s+)\*\*[^*\n]{2,40}(?::\*\*\s|\*\*\s*:\s)"]},
{"id": "softener", "label": "Softener (\"simply\" / \"just\" before a verb) that undercuts the instruction", "sev": "medium",
"note": "softener",
"fix": "Drop it. 'Simply run X' is 'Run X'. The word adds nothing and implies it is trivial.",
"pats": [r"\bsimply\s+(run|use|add|do|call|set|click|open|type|install|copy|edit|change)\b",
r"\bjust\s+(run|use|add|do|call|set|click|open|type|install|copy)\b"]},
{"id": "bolded-lead-in", "label": "Bolded lead-in label (**Word:** then a sentence)", "sev": "medium",
"note": "chat-formatting tic", "skip_list": True,
"fix": "Write a normal sentence without the boldface label. Reserve bold for true terms of art or warnings. (One or two bolded-label bullets pass; runs of three get a separate advisory.)",
"pats": [r"(^|\s)\*\*[^*\n]{2,40}:\*\*\s", r"(^|\s)\*\*[^*\n]{2,40}\*\*\s*:"]},
{"id": "listicle-scaffold", "label": "Listicle scaffolding (\"5 ways to ...\", \"7 signs ...\")", "sev": "medium",
"note": "list-as-default-shape",
"fix": "Write prose. Reserve bullets for genuinely list-like content.",
# High-signal nouns (ways/tips/signs/...) match anywhere. Ambiguous count-nouns
# (things/steps/rules) also appear in plain prose ("15 rules files", "3 steps in the
# pipeline"), so they only flag in a heading or before a listicle continuation word.
# This kills the "N rules"/"N things" false positive without missing real listicles.
"pats": [r"\b\d+\s+(ways|tips|signs|reasons|tricks|secrets|lessons|mistakes)\b",
r"(^|\n)\s{0,3}#{1,4}\s+\d+\s+(ways|tips|signs|reasons|things|steps|tricks|secrets|lessons|mistakes|rules)\b",
r"\b\d+\s+(things|steps|rules)\s+(to|for|that|you|your|why|i|we|every)\b"]},
{"id": "emoji-decoration", "label": "Emoji as a bullet, icon, or in a heading", "sev": "medium",
"note": "decorative emoji (banned unless the user used them first)",
"fix": "Use plain headers and real list markers. An emoji in a sentence where a person would use one is fine; emoji as structure is not.",
"pats": [r"^\s{0,3}#{1,6}\s*[" + EMOJI + r"]", r"^\s{0,3}[" + EMOJI + r"]\s+\S",
r"[" + EMOJI + r"]\s*\*\*", r"\*\*\s*[" + EMOJI + r"]"]},
{"id": "in-conclusion", "label": "\"In conclusion\" / \"in summary\" / \"to summarize\" closer", "sev": "medium",
"note": "signposted recap",
"fix": "End on a real last point. If the reader needs a summary, the piece is too long.",
"pats": [r"\bin (conclusion|summary)\b", r"\bto (summari[sz]e|conclude|wrap (this |it )?up)\b", r"\bin closing\b"]},
{"id": "hedge", "label": "Hedging when you have a view (\"you might want to consider\", \"it may be worth\", \"perhaps\", \"on one hand ... on the other\")", "sev": "medium",
"note": "hedge; take a position",
"fix": "State the take. List a real trade-off if it matters, but say what you would do.",
"pats": [r"\byou might want to consider\b", r"\byou could potentially\b",
r"\bit may be worth\b", r"\bperhaps you\b",
r"\bon (the )?one hand\b[^.\n]{0,120}\bon the other\b", r"\bit (really )?depends\b"]},
{"id": "social-template", "label": "Worn social-post template (\"the guide I wish existed\", \"I kept seeing X, so I built Y\")", "sev": "medium",
"note": "Reddit/HN launch-post cliche; review especially closely in short outreach copy",
"fix": "Say what the thing is and what it covers. The origin story ('I saw a gap, so I made this') is the most-reused launch template on the internet; cut it.",
"pats": [r"\bi wish existed\b", r"\bwish i('d| had) (had|found)\b",
r"\bi kept (seeing|getting|hearing)\b[^.?!\n]{0,80}\bso i\b",
r"\bi (saw|noticed|found) (a |the )?(gap|problem|need)\b[^.?!\n]{0,80}\bso i (built|made|created|wrote)\b"]},
{"id": "split-antithesis", "label": "Cross-sentence antithesis (\"The value was not X. It was Y.\" / \"not the X part. The X was ...\")", "sev": "medium",
"note": "the not-X-but-Y cadence split over two sentences; the one-sentence form is the high-tier 'antithesis' check",
"fix": "Say Y directly and drop the negated setup sentence.",
"pats": [r"\b(was|is|were|are)(n'?t| not)\s+[^.?!\n]{2,50}\.\s+(it|that|this)\s+(was|is|'s)\b",
r"\bnot the ([a-z][a-z ]{2,30}?)\.\s+the \1\b"]},
{"id": "hype-marketing", "label": "Marketing hype (revolutionary, transformative, supercharge, to the next level)", "sev": "medium",
"note": "landing-page voice",
"fix": "Say what the thing literally does, with a specific. Strip the promotional adjective.",
"pats": [r"\brevolution(ary|i[sz]e)\b", r"\btransform(ative)\b", r"\btransform your (life|business|workflow)\b",
r"\bto the next level\b", r"\bsupercharge\b", r"\bsay goodbye to\b", r"\blook no further\b"]},
{"id": "c2-flourish", "label": "Literary/native flourish (whilst, endeavour, notwithstanding: check it against the byline)", "sev": "medium",
"note": "byline mismatch; see references/voice-profile.md",
"fix": "Use the everyday word: whilst->while, amongst->among, endeavour->try, ascertain->find out, notwithstanding->even so. If the named author's real register is plainer than this vocabulary (a non-native writer, a terse operator), the polish itself is the tell.",
"pats": [r"\bwhilst\b", r"\bamongst\b", r"\bendeavou?r(s|ed|ing)?\b", r"\bascertain(s|ed|ing)?\b",
r"\belucidat(e|es|ed|ing)\b", r"\bquintessential(ly)?\b", r"\bnotwithstanding\b",
r"\bhenceforth\b", r"\bhitherto\b", r"\bwhereby\b", r"\bthereby\b", r"\bwherein\b",
r"\balbeit\b", r"\bone might\b"]},
# ---------- LOW: weak / contextual (advisory) ----------
{"id": "copula-avoidance", "label": "Copula avoidance", "sev": "low",
"note": "weak contextual advisory; a real function may justify the phrase",
"fix": "Use is or are when the phrase only renames the subject.",
"pats": [r"\b(serves|stands) as (a|an|the)\b"]},
{"id": "generic-diction", "label": "Inflated generic diction (facilitate, paramount, pivotal, intricacies)", "sev": "low",
"note": "prefer the plain word",
"fix": "facilitate->help/let, paramount->matters most, pivotal->describe the moment.",
"pats": [r"\bfacilitat(e|es|ing|ed)\b", r"\bparamount\b", r"\bpivotal\b",
r"\bintricac(y|ies)\b"]},
{"id": "preamble", "label": "Work-announcement preamble (\"Let me ...\", \"I'll start by ...\", \"Here's what I ...\")", "sev": "low",
"note": "narrating intent; just do it",
"fix": "Do the thing. The reader sees the result. No 'Let me take a look', no 'Here's a breakdown of'.",
"pats": [r"(^|\n)\s*let me (take a look|start|check|see|explain|walk you)\b",
r"(^|\n)\s*i'?ll (start by|begin by|go ahead)\b",
r"(^|\n)\s*here'?s (a breakdown|what i (found|changed|did))\b"]},
{"id": "honestly-opener", "label": "Fake-relatability opener (\"Honestly, ...\", \"Look, I get it\")", "sev": "low",
"note": "throat-clearing",
"fix": "Cut it and start with the point.",
"pats": [r"(^|\n)\s*honestly,\s", r"\blook,\s+i (get it|know)\b", r"\blet'?s be (honest|real)\b"]},
]
def compile_rules(min_sev):
order = ["high", "medium", "low"]
floor = order.index(min_sev) if min_sev else len(order) - 1
out = []
for r in RULES:
if order.index(r["sev"]) > floor:
continue
r = dict(r)
r["min_hits"] = r.get("min_hits", 1)
r["rx"] = [re.compile(p, re.IGNORECASE) for p in r["pats"]]
out.append(r)
return out
def iter_files(path):
if os.path.isfile(path):
yield path; return
for root, dirs, files in os.walk(path):
parts = os.path.normpath(os.path.abspath(root)).split(os.sep)
under_test = any(part in {"test", "tests"} for part in parts)
if any(part == "fixtures" and any(p in {"test", "tests"} for p in parts[:i])
for i, part in enumerate(parts)):
dirs[:] = []
continue
dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not (under_test and d == "fixtures")]
for f in files:
if os.path.splitext(f)[1].lower() in EXTS:
yield os.path.join(root, f)
def strip_noise(line, in_code, in_quote):
"""Blank what the author is quoting or showing as a literal example, so the prose
rules lint the author's own sentences. Inline-code spans (backticks) and double-quoted
spans are removed, and the open/closed state carries across lines. State resets at every
blank line, so an unbalanced quote can never swallow more than one paragraph."""
out = []
for ch in line:
if in_code:
if ch == "`":
in_code = False
out.append(" ")
elif ch == "`":
in_code = True
out.append(" ")
elif ch in "\"“”":
in_quote = not in_quote
out.append(" ")
else:
out.append(" " if in_quote else ch)
return "".join(out), in_code, in_quote
def literal_vocab(target, match):
"""Narrow literal/technical exceptions, not a semantic classifier."""
word = match.group(0).lower()
before = target[max(0, match.start() - 70):match.start()].lower()
after = target[match.end():match.end() + 70].lower()
if word.startswith("tapestr"):
if re.search(r"\brich\s+$", before) or re.match(r"\s+(?:of\s+(?:ideas|stories|cultures|experiences|life)|celebrating)\b", after):
return False
return bool(re.search(r"\b(?:woven|hand(?:woven)?|silk|wool|medieval|bought|restored)(?:\s+a)?\s+$", before)
or re.match(r"\s+(?:hangs?|hung|on the wall|from (?:iran|persia))\b", after)
or re.match(r"\s+of\b[^.?!]{0,45}\b(?:covers|hangs on) the wall\b", after))
if word.startswith("paradigm"):
return bool(re.search(r"\b(programming|computing|software|scientific|functional|object[- ]oriented|dataflow|logic|imperative|declarative)\s+$", before))
if word == "beacon":
return bool(re.search(r"\b(radio|bluetooth|emergency|distress|navigation|homing|lighthouse|gps)\s+$", before)
or re.match(r"\s+(flashes|flashed|transmits|transmitted)\b", after))
if word == "realm":
return bool(re.search(r"\b(kerberos|dns|authentication)\s+$", before))
if word == "testament":
return bool(re.search(r"\b(old|new)\s+$", before))
return False
def eligible_findings(findings, rules):
groups = {}
for finding in findings:
groups.setdefault((finding["file"], finding["rule"]), []).append(finding)
policy = {r["id"]: r for r in rules}
keep = set()
for (_, rid), items in groups.items():
rule = policy[rid]
if rule.get("consecutive"):
start = 0
for end in range(1, len(items) + 1):
if end < len(items) and items[end]["_item"] == items[end - 1]["_item"] + 1:
continue
if end - start >= rule["consecutive"]:
keep.update(id(f) for f in items[start:end])
start = end
elif rule["min_hits"] > 1:
end = 0
for start, first in enumerate(items):
while end < len(items) and items[end]["_word"] - first["_word"] < rule["window_words"]:
end += 1
window = items[start:end]
count = len({f["match"].lower() for f in window}) if rule.get("distinct") else len(window)
if count >= rule["min_hits"]:
keep.update(id(f) for f in window)
else:
keep.update(id(f) for f in items)
return [{k: v for k, v in f.items() if not k.startswith("_")} for f in findings if id(f) in keep]
class ProseHTML(HTMLParser):
"""Mask tags and script/style bodies without moving source characters."""
def __init__(self, text):
super().__init__(convert_charrefs=False)
self.source = text
self.output = list(text)
self.citations = list(text)
self.starts = [0] + [m.end() for m in re.finditer("\n", text)]
self.hidden = None
self.feed(text)
self.close()
def mask(self, length, boundary=False, keep_citation=False):
row, column = self.getpos()
start = self.starts[row - 1] + column
for i in range(start, start + length):
if self.output[i] != "\n":
self.output[i] = " "
if not keep_citation:
self.citations[i] = self.output[i]
if boundary and length:
self.output[start] = "\n"
def handle_starttag(self, tag, attrs):
self.mask(len(self.get_starttag_text()), tag in {"p", "div", "br", "li", "h1", "h2", "h3"}, tag == "grok-card")
if tag in {"script", "style"}:
self.hidden = tag
def handle_endtag(self, tag):
row, column = self.getpos()
start = self.starts[row - 1] + column
end = self.source.find(">", start)
self.mask(end - start + 1, tag in {"p", "div", "li"}, tag == "grok-card")
if tag == self.hidden:
self.hidden = None
def handle_startendtag(self, tag, attrs):
self.handle_starttag(tag, attrs)
if tag == self.hidden:
self.hidden = None
def handle_data(self, data):
if self.hidden:
self.mask(len(data))
def handle_comment(self, data):
self.mask(len(data) + 7)
def strip_code(line, in_code):
out = []
for ch in line:
if ch == "`":
in_code = not in_code
out.append(" ")
else:
out.append(" " if in_code else ch)
return "".join(out), in_code
def citation_prose(line, in_code, in_quote):
"""Keep JSON citation keys, but retain ordinary quote and code escapes."""
code_free, _ = strip_code(line, in_code)
protected = list(line)
decoder = json.JSONDecoder()
for match in re.finditer(r"\{", code_free):
_, _, quoted = strip_noise(line[:match.start()], in_code, in_quote)
if quoted:
continue
try:
_, length = decoder.raw_decode(code_free[match.start():])
except ValueError:
continue
for i in range(match.start(), match.start() + length):
if protected[i] == '"':
protected[i] = " "
return strip_noise("".join(protected), in_code, in_quote)[0]
def scan(path, min_sev):
rules = compile_rules(min_sev)
line_rules = {"bolded-label-list", "bolded-lead-in", "emoji-decoration", "preamble",
"honestly-opener", "transition-openers", "listicle-scaffold"}
findings = []
total_words = 0
for fp in iter_files(path):
try:
with open(fp, "r", encoding="utf-8", errors="ignore") as fh:
source = fh.read()
except OSError:
continue
raw_lines = source.splitlines()
starts = [0] + [m.end() for m in re.finditer("\n", source)]
html = ProseHTML(source)
markup = "".join(html.output)
citation_markup = "".join(html.citations)
# splitlines() would treat inserted HTML boundaries as extra source lines.
lines = [markup[start:starts[i + 1] if i + 1 < len(starts) else len(markup)]
for i, start in enumerate(starts)]
fm_end = 0
if raw_lines and raw_lines[0].strip() == "---":
for j in range(1, len(raw_lines)):
if raw_lines[j].strip() == "---":
fm_end = j + 1
break
in_fence = in_code = in_quote = False
paragraph = []
item = 0
list_indent = None
def emit(rule, target, mapping, is_list=False, item_number=0):
if rule.get("skip_list") and is_list:
return
matches = {}
for rx in rule["rx"]:
for m in rx.finditer(target):
if rule["id"] == "era-vocab" and literal_vocab(target, m):
continue
matches[(m.start(), m.end(), m.group(0))] = m
for _, m in sorted(matches.items()):
position = m.start() + len(m.group(0)) - len(m.group(0).lstrip(" .?!\n\t"))
line = mapping[min(position, len(mapping) - 1)]
findings.append({"rule": rule["id"], "label": rule["label"], "sev": rule["sev"],
"note": rule["note"], "fix": rule["fix"], "file": fp, "line": line,
"match": m.group(0).strip()[:60], "snippet": raw_lines[line - 1].strip()[:160],
"_word": total_words + len(re.findall(r"\b[\w'-]+\b", target[:m.start()])),
"_item": item_number})
def flush():
nonlocal total_words
if not paragraph:
return
text = "".join(part[0] for part in paragraph)
text = re.sub(r"(?<!\w)(\*\*|__|\*|_)(?=\S)(.+?)(?<=\S)\1(?!\w)",
lambda m: " " * len(m[1]) + m[2] + " " * len(m[1]), text)
mapping = [line for part, line, _ in paragraph for _ in part]
normalized, normalized_map = [], []
for m in re.finditer(r"\s+|\S+", text):
chunk = " " if m.group().isspace() else m.group().replace("’", "'")
normalized.extend(chunk)
normalized_map.extend([mapping[m.start()]] if m.group().isspace() else mapping[m.start():m.end()])
text = "".join(normalized)
for rule in rules:
if not rule.get("raw") and rule["id"] not in line_rules | {"citation-markup"}:
emit(rule, text, normalized_map, paragraph[0][2])
total_words += len(re.findall(r"\b[\w'-]+\b", text))
paragraph.clear()
for i, (raw, visible) in enumerate(zip(raw_lines, lines), 1):
if i <= fm_end:
continue
stripped = raw.strip()
if not stripped:
flush()
in_code = in_quote = False
continue
if stripped.startswith(("```", "~~~")):
flush()
item += 1
in_fence = not in_fence
in_code = in_quote = False
continue
if in_fence:
continue
bullet = re.match(r"^(\s*)(?:[-*+]\s+|\d+\.\s+)", raw)
if bullet:
flush()
item += 1
list_indent = len(bullet.group(0))
elif stripped and (list_indent is None or len(raw) - len(raw.lstrip()) < list_indent):
item += 1
list_indent = None
if "unslop-ignore" in raw.lower() or "voice-allow" in raw.lower():
flush()
_, in_code, in_quote = strip_noise(visible, in_code, in_quote)
continue
is_quote = stripped.startswith(">")
for rule in rules:
if rule.get("raw"):
emit(rule, raw, [i] * len(raw))
elif rule["id"] == "citation-markup" and not is_quote:
start = starts[i - 1]
citation_line = citation_markup[start:starts[i] if i < len(starts) else len(source)]
emit(rule, citation_prose(citation_line, in_code, in_quote), [i] * len(citation_line))
prose, in_code, in_quote = strip_noise(visible, in_code, in_quote)
if is_quote:
flush()
continue
for rule in rules:
if rule["id"] in line_rules:
normalized_line = re.sub(r"[ \t]+", " ", prose).replace("’", "'")
emit(rule, normalized_line, [i] * len(normalized_line), bool(bullet), item)
if bullet:
prose = " " * bullet.end() + prose[bullet.end():]
prose = re.sub(r"^(\s{0,3})#{1,6}\s+", lambda m: " " * len(m[0]), prose)
# A source newline is a soft wrap; inserted HTML newlines are boundaries.
if prose.endswith("\n"):
prose = prose[:-1]
parts = prose.split("\n")
for index, part in enumerate(parts):
if part.strip():
paragraph.append((part + " ", i, bool(bullet)))
if index < len(parts) - 1:
flush()
flush()
return eligible_findings(findings, rules), total_words
def density(weighted, words):
return weighted / max(words, 1) * 1000.0
def verdict(by_sev, weighted, words):
hi, med = by_sev.get("high", 0), by_sev.get("medium", 0)
if weighted == 0:
return "Clean under the configured rules"
dens = density(weighted, words)
if hi == 0 and med == 0:
return "Mostly clean, minor style advisories"
if hi >= 3 or weighted >= 15 or (words >= 300 and dens >= 10):
return "High concentration of configured style violations"
if hi >= 1:
return "Configured style violations present"
if weighted >= 6 and not (words >= 600 and dens < 2.0):
return "Several advisory style patterns present"
return "Mostly clean, minor style advisories"
def compare_text(original, rewrite):
"""Advisory token inventories. A human still checks meaning and attribution."""
from collections import Counter
patterns = {
"numbers": r"(?<![\w.])[+-]?(?:\d+(?:[.,]\d+)*|\.\d+)(?:[eE][+-]?\d+)?%?",
"URLs": r"https?://[^\s<>\"\[\]]+",
"negations": r"\b(?:cannot|not|never|no|\w+n['’]t)\b",
"modals": r"\b(?:can(?!['’]t\b)|must|should|may)\b",
}
texts = []
for path in (original, rewrite):
with open(path, encoding="utf-8") as fh:
texts.append(fh.read())
def clean_url(token):
token = token.rstrip(".,;:!?")
while token.endswith(")") and token.count(")") > token.count("("):
token = token[:-1].rstrip(".,;:!?")
return token
differences = []
for label, pattern in patterns.items():
inventories = [Counter(token.lower().replace("’", "'") if label in ("negations", "modals") else
clean_url(token) if label == "URLs" else token
for token in re.findall(pattern, text, re.IGNORECASE)) for text in texts]
for side, left, right in (("original", 0, 1), ("rewrite", 1, 0)):
for token, count in sorted((inventories[left] - inventories[right]).items()):
differences.append(f"{label} only in {side}: {token} ({count})")
return differences
def main():
ap = argparse.ArgumentParser(description="Scan prose against the configured writing-style rules.")
ap.add_argument("path", nargs="?")
ap.add_argument("--compare", nargs=2, metavar=("ORIGINAL", "REWRITE"),
help="advisory numbers/URLs/negations/modals comparison (exit 0)")
ap.add_argument("--severity", choices=["high", "medium", "low"], default="low",
help="minimum severity to report (default: low = everything)")
ap.add_argument("--json", action="store_true", help="machine-readable output")
ap.add_argument("--max", type=int, default=10, help="max examples shown per rule (text mode)")
args = ap.parse_args()
if args.compare:
if args.path or args.json:
ap.error("--compare takes two files and cannot be combined with path or --json")
try:
differences = compare_text(*args.compare)
except (OSError, UnicodeError) as exc:
ap.error(str(exc))
print("Meaning-check advisory: token inventories only; verify facts and meaning by hand.")
print("\n".join(differences) if differences else "No token inventory differences found.")
return
if not args.path:
ap.error("path is required unless --compare is used")
if not os.path.exists(args.path):
print(f"path not found: {args.path}", file=sys.stderr); sys.exit(2)
findings, total_words = scan(args.path, args.severity)
by_sev, by_rule = {}, {}
for f in findings:
by_sev[f["sev"]] = by_sev.get(f["sev"], 0) + 1
by_rule.setdefault(f["rule"], []).append(f)
weighted = sum(W[s] * n for s, n in by_sev.items())
files_scanned = sum(1 for _ in iter_files(args.path))
dens = round(density(weighted, total_words), 1)
if args.json:
print(json.dumps({"path": args.path, "files_scanned": files_scanned,
"words": total_words, "counts": by_sev,
"configured_style_score": weighted,
"density_per_1k_words": dens,
"verdict": verdict(by_sev, weighted, total_words),
"findings": findings}, indent=2))
sys.exit(1 if by_sev.get("high", 0) else 0)
sev_order = {"high": 0, "medium": 1, "low": 2}
rule_ids = sorted(by_rule, key=lambda rid: (sev_order[by_rule[rid][0]["sev"]], -len(by_rule[rid])))
print(f"\n unslop-text scan: {args.path}")
print(f" files scanned: {files_scanned} words: {total_words} findings: {len(findings)}")
print(f" configured style score: {weighted} density: {dens}/1k authored words")
print(f" verdict: {verdict(by_sev, weighted, total_words)}")
print(f" high: {by_sev.get('high',0)} medium: {by_sev.get('medium',0)} low: {by_sev.get('low',0)}")
print(" (high is the gated tier; medium/low are advisory)\n")
if not findings:
print(" Nothing flagged. The scanner cannot judge authorship, rhythm, originality,\n"
" factual value, or whether each paragraph earns its space. Run the structural\n"
" and concision pass in references/tells.md.\n")
return
for rid in rule_ids:
items = by_rule[rid]
f0 = items[0]
print(f" [{f0['sev'].upper()}] {f0['label']} ({len(items)} hit{'s' if len(items)!=1 else ''}) [{f0['note']}]")
print(f" fix: {f0['fix']}")
for it in items[:args.max]:
print(f" {it['file']}:{it['line']} ({it['match']}) {it['snippet']}")
if len(items) > args.max:
print(f" ... +{len(items) - args.max} more")
print()
top = [by_rule[rid][0]['label'] for rid in rule_ids[:3]]
print(" Top things to change: " + "; ".join(top))
print(" Rhythm, substance, factual value, and authorship need a human pass. See references/tells.md.\n")
sys.exit(1 if by_sev.get("high", 0) else 0)
if __name__ == "__main__":
main()
skills/a-unslop-text/tests/fixtures/clean/email.txt460 B
Hi Casey, Agree we should move the review to Thursday. The supplier needs another day to check the drawings, and we should have their comments before we send the order. Can you send the revised invitation to the same group? Keep the room booking for 10:30. I will bring the printed drawings and the cost sheet from last week. The extra delivery charge is EUR 45. It is already included in the total on page 2, so please do not add it again. Thanks, Morgan
skills/a-unslop-text/tests/fixtures/clean/museum.md628 B
# Textile room: loan notes The display includes a woven tapestry from Iran and a medieval silk tapestry. The larger tapestry hangs on the north wall, away from direct sunlight. Visitors can see the repaired section near the bottom edge without touching the cloth. A copy of the Old Testament is in the adjoining case. The catalogue records the printer and the year on the title page. Staff should check those details against the loan form before preparing a replacement label. The lender has asked us to keep the room below 22 degrees. If the monitor records a higher reading, close the blinds and call the collections team.
skills/a-unslop-text/tests/fixtures/clean/report.md3.0 KB
# Archive move: storage and access The crucial decision is whether readers can request boxes during the move. We propose keeping the reading room open on Tuesdays and Thursdays, with requests due by noon on the previous working day. That gives staff time to fetch material before the packing crew starts. Readers who need several boxes should send the catalogue references together, so staff can check the storage location in one visit. Each box will keep its current reference number. The move does not change the catalogue or the order of files inside a box. Staff will attach a second label to the lid because the original label may be hidden when boxes are stacked on the trolley. The new label must show the reference in full. Shortened references caused confusion during the last shelf check, when two collections used the same final digits. The packing crew will work on one aisle at a time. A member of the archive team will check the list before each trolley leaves the room and sign it when the boxes reach the new shelves. The signed lists will stay at the desk until the catalogue locations have been updated. If a box cannot be found, staff should mark it as awaiting a location check and keep the request open. They should not tell the reader that the material has been lost before checking both rooms. Some maps are stored flat and will need a separate trip. We have asked the transport team to bring trays that fit the cabinet drawers. Staff can measure the trays against an empty drawer before the first map is packed. The largest sheets must stay flat during loading and unloading. If the trays do not fit, the maps will remain in the current room until the team agrees on another method. The rest of the move can continue. The desk will keep a paper copy of each day's request list in case the network is unavailable. This copy should contain references and collection titles, with reader contact details held in the booking system. Before closing, staff will record completed requests in the system and put the working copy in the locked waste bin. Requests carried over to the next day should be copied onto the next list before the old one is destroyed. The vital check after the move is that a reader can request a box and receive the right material. On the first morning, someone who did not pack the boxes will choose ten catalogue records and follow the normal request process. Record the shelf position and the time needed for each request. Any wrong location should be corrected in the catalogue before the reading room opens. A missing label should be replaced from the signed transport list, with a second person checking the reference. We will review the request process after two weeks. The review needs the number of requests received, the number completed on the requested day, and the reason for each delay. It does not need a new survey or a separate reporting tool. Staff can keep a short note beside the existing desk log and bring it to the Friday meeting. The team will use those notes to decide whether the temporary request deadline can be removed.
skills/a-unslop-text/tests/fixtures/clean/technical.md675 B
# Worker restart procedure The worker failed not because the file is missing but because access was denied. Check the service account before restarting it. The log should include the account name and the path that failed. Functional programming is the programming paradigm used in this module. Unpack the tuple returned by the parser, then pass the second value to the worker. The authentication realm must match the value in the service configuration. - **Owner:** Platform team - **Deadline:** Friday at 14:00 The radio beacon transmits every ten seconds. Use landscape orientation for the maintenance diagram. The diagram labels the sensor and the antenna separately.
skills/a-unslop-text/tests/fixtures/dirty/catalog.md1.3 KB
The schedule — approved – is final. We need to delve into a rich tapestry of ideas. This holistic approach creates synergy. The robust proposal is comprehensive. The competitive landscape is changing. Moreover, the plan is ready. It's not just a tool, it's a movement. As an AI language model, I cannot assist with that. Great question! I'd be happy to explain. It's important to note that the plan works. I hope this helps. Let me know if you need more. The reference is contentReference[oaicite:1] and [cite: 2]. The crucial decision is ultimately clear. The dependable plan is practical and steady. The result: we moved a button. The change is small, highlighting the importance of the work. - **Owner:** Casey - **Scope:** Search - **Date:** Friday Simply run the tool. **Summary:** The update is ready. Here are 5 ways to start. # 🚀 Release notes In conclusion, we are ready. You might want to consider the alternative. I saw a gap in the tools, so I built this. The value was not typing speed. It was the forcing function. This revolutionary change will supercharge the workflow. Whilst we wait, ascertain the cause. The building serves as a landmark. The plan will facilitate the move. Let me take a look at that. Honestly, we can do this.
skills/a-unslop-text/tests/test_unslop_text_scan.py26.4 KB
import importlib.util
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
SCRIPT = Path(__file__).parents[1] / "scripts" / "unslop_text_scan.py"
SPEC = importlib.util.spec_from_file_location("unslop_text_scan", SCRIPT)
SCANNER = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(SCANNER)
FIXTURES = Path(__file__).parent / "fixtures"
class ScannerTests(unittest.TestCase):
def scan_text(self, text):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
path = Path(tmp) / "sample.md"
path.write_text(text, encoding="utf-8")
return SCANNER.scan(str(path), "low")
def test_literal_landscape_navigation_and_ecosystem_pass(self):
findings, _ = self.scan_text(
"Use landscape orientation for the image. "
"The app navigates to the next page. "
"A pond ecosystem has insects."
)
self.assertEqual([], findings)
def test_consultant_compound_is_high(self):
findings, _ = self.scan_text("The competitive landscape keeps changing.")
self.assertEqual(["consultant-compound"], [item["rule"] for item in findings])
self.assertEqual("high", findings[0]["sev"])
def test_rhetorical_unpack_fails_but_tuple_operation_passes(self):
rhetorical, _ = self.scan_text("Let's unpack this before deciding.")
technical, _ = self.scan_text("The function returns three values; unpack the tuple first.")
self.assertEqual(["high-signal-vocab"], [item["rule"] for item in rhetorical])
self.assertEqual([], technical)
def test_house_words_need_a_cluster_and_count_same_line(self):
one, _ = self.scan_text("The plan is robust.")
two, _ = self.scan_text("The robust plan is comprehensive.")
self.assertEqual([], one)
self.assertEqual(2, len(two))
self.assertEqual({"medium"}, {item["sev"] for item in two})
def test_frequency_rule_requires_two_hits(self):
one, _ = self.scan_text("This is crucial.")
two, _ = self.scan_text("This is crucial and ultimately useful.")
self.assertFalse(any(item["rule"] == "frequency-words" for item in one))
self.assertEqual(2, len([item for item in two if item["rule"] == "frequency-words"]))
def test_frontmatter_quotes_code_and_allow_comments_are_ignored(self):
findings, words = self.scan_text(
"---\ntitle: Delve into this\n---\n"
"> Delve into this quoted sentence.\n"
"`delve into this literal`\n"
"Delve into this allowed example. <!-- unslop-ignore -->\n"
"One visible sentence.\n"
)
self.assertEqual([], findings)
self.assertEqual(3, words)
def test_dash_house_rule_still_applies_inside_quotes(self):
findings, _ = self.scan_text('A quoted "range \u2014 still blocked" appears here.')
self.assertEqual(["em-dash"], [item["rule"] for item in findings])
def test_worn_origin_template_is_flagged(self):
findings, _ = self.scan_text("I saw a gap in the available tools, so I built this one.")
self.assertEqual(["social-template"], [item["rule"] for item in findings])
self.assertEqual("medium", findings[0]["sev"])
def test_dropped_pronoun_opener_passes(self):
findings, _ = self.scan_text(
"Made a free guide for people setting up their first server."
)
self.assertEqual([], findings)
def test_many_high_findings_return_boolean_failure(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
path = Path(tmp) / "many.md"
path.write_text("\u2014" * 300, encoding="utf-8")
result = subprocess.run(
[sys.executable, str(SCRIPT), str(path), "--json"],
capture_output=True,
text=True,
check=False,
)
self.assertEqual(1, result.returncode)
def rule_hits(self, text, rule, severity="low"):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
path = Path(tmp) / "sample.md"
path.write_text(text, encoding="utf-8")
findings, _ = SCANNER.scan(str(path), severity)
return [item for item in findings if item["rule"] == rule]
def test_literal_earlier_vocabulary_passes(self):
examples = (
"A woven tapestry from Iran covers the wall.",
"A hand-woven tapestry is on display.",
"A silk tapestry is in the case.",
"A medieval tapestry hangs in the hall.",
"The tapestry hangs on the wall.",
"They restored a tapestry yesterday.",
"The programming paradigm uses functions.",
"This scientific paradigm explains the observation.",
"The radio beacon transmits at noon.",
"A beacon flashes beside the harbour.",
"The Kerberos realm is EXAMPLE.ORG.",
"The New Testament is in the case.",
)
for text in examples:
with self.subTest(text=text):
self.assertEqual([], self.rule_hits(text, "era-vocab"))
def test_figurative_earlier_vocabulary_is_advisory(self):
for word in ("delve", "tapestry", "realm", "beacon", "testament", "myriad", "plethora", "paradigm"):
with self.subTest(word=word):
hits = self.rule_hits("We describe a " + word + " of ideas.", "era-vocab")
self.assertEqual(1, len(hits))
self.assertEqual("medium", hits[0]["sev"])
self.assertTrue(self.rule_hits("A rich tapestry of ideas.", "era-vocab"))
self.assertTrue(self.rule_hits("A woven tapestry of ideas.", "era-vocab"))
self.assertTrue(self.rule_hits("A paradigm shift is coming.", "era-vocab"))
self.assertEqual([], self.rule_hits("A rich tapestry of ideas.", "era-vocab", severity="high"))
def test_real_cause_corrections_pass_and_promotional_antithesis_fires(self):
correction = "The job failed not because the file is missing but because access was denied."
self.assertEqual([], self.scan_text(correction)[0])
self.assertEqual([], self.rule_hits("It is not red, but blue.", "antithesis"))
for text in ("It's not just a tool, it's a movement.", "This is not merely a tool, but a movement."):
with self.subTest(text=text):
self.assertTrue(self.rule_hits(text, "antithesis"))
def test_bolded_bullet_labels_need_three_consecutive_items(self):
for marker in ("-", "*", "+", "1."):
for label in ("**Owner:** Casey", "**Owner**: Casey"):
with self.subTest(marker=marker, label=label):
bullet = marker + " " + label + "\n"
self.assertEqual([], self.rule_hits(bullet, "bolded-label-list"))
self.assertEqual([], self.rule_hits(bullet * 2, "bolded-label-list"))
hits = self.rule_hits(bullet * 3, "bolded-label-list")
self.assertEqual([1, 2, 3], [f["line"] for f in hits])
self.assertEqual({"low"}, {f["sev"] for f in hits})
self.assertEqual(3, len(self.rule_hits(bullet * 2 + "\n" + bullet, "bolded-label-list")))
self.assertEqual([], self.rule_hits(bullet * 2 + "Plain text.\n" + bullet, "bolded-label-list"))
self.assertTrue(self.rule_hits("**Owner:** Casey", "bolded-lead-in"))
self.assertEqual([], self.rule_hits("- **Owner:** Casey", "bolded-lead-in"))
def test_current_vocabulary_needs_three_distinct_local_words(self):
hits = self.rule_hits("A dependable and practical plan stays steady.", "current-era-cluster")
self.assertEqual(3, len(hits))
self.assertEqual({"medium"}, {f["sev"] for f in hits})
self.assertEqual([], self.rule_hits("Practical practical practical.", "current-era-cluster"))
self.assertEqual([], self.rule_hits("A dependable practical plan.", "current-era-cluster"))
self.assertEqual([], self.rule_hits("Practical steady " + "word " * 300 + "dependable", "current-era-cluster"))
self.assertEqual([], self.scan_text("The problem is multifaceted.")[0])
words = "challenge clearer dependable echoed foster leverage matters multifaceted practical prioritize quietly steady universally"
hits = self.rule_hits(words, "current-era-cluster")
self.assertEqual(13, len(hits))
def test_current_vocabulary_does_not_combine_separate_windows(self):
text = "practical " + "word " * 200 + "steady " + "word " * 200 + "dependable"
self.assertEqual([], self.rule_hits(text, "current-era-cluster"))
hits = self.rule_hits("practical steady dependable " + "word " * 300 + "clearer", "current-era-cluster")
self.assertEqual({"practical", "steady", "dependable"}, {f["match"] for f in hits})
def test_frequency_and_house_clusters_are_local_across_lines(self):
for rule, first, second in (("frequency-words", "crucial", "vital"), ("house-vocab", "robust", "comprehensive")):
with self.subTest(rule=rule):
self.assertEqual(2, len(self.rule_hits(first + "\n" + "word " * 298 + second, rule)))
self.assertEqual([], self.rule_hits(first + "\n" + "word " * 299 + second, rule))
hits = self.rule_hits(first + " " + first + " " + "word " * 300 + second, rule)
self.assertEqual([first, first], [f["match"] for f in hits])
def test_local_clusters_do_not_cross_files(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
Path(tmp, "a.md").write_text("crucial robust practical steady", encoding="utf-8")
Path(tmp, "b.md").write_text("vital comprehensive dependable", encoding="utf-8")
findings, _ = SCANNER.scan(tmp, "low")
self.assertEqual([], findings)
def test_staged_reveals_are_sentence_initial(self):
for word in ("result", "catch", "kicker", "payoff", "twist", "answer", "truth"):
for punctuation in (":", "?"):
with self.subTest(word=word, punctuation=punctuation):
self.assertTrue(self.rule_hits("The " + word + punctuation + " It works.", "staged-reveal"))
self.assertTrue(self.rule_hits("We checked. The " + word + punctuation + " It works.", "staged-reveal"))
self.assertEqual([], self.rule_hits("We recorded the " + word + punctuation + " it works.", "staged-reveal"))
self.assertEqual([], self.scan_text("The port: 8080. The result was accepted.")[0])
def test_significance_tails_need_comma_participle_and_determiner(self):
for verb in ("highlighting", "underscoring", "reflecting", "symbolizing", "showcasing", "emphasizing"):
for determiner in ("the", "its", "their", "a"):
with self.subTest(verb=verb, determiner=determiner):
self.assertTrue(self.rule_hits("It changed, " + verb + " " + determiner + " role.", "significance-tail"))
self.assertEqual([], self.rule_hits("We are " + verb + " " + determiner + " role.", "significance-tail"))
self.assertEqual([], self.rule_hits("It changed, " + verb + " evidence.", "significance-tail"))
def test_copula_avoidance_is_low_and_needs_an_article(self):
for verb in ("serves", "stands"):
for article in ("a", "an", "the"):
with self.subTest(verb=verb, article=article):
hits = self.rule_hits("It " + verb + " as " + article + " example.", "copula-avoidance")
self.assertEqual(1, len(hits))
self.assertEqual("low", hits[0]["sev"])
self.assertEqual([], self.rule_hits("It " + verb + " as evidence.", "copula-avoidance"))
self.assertEqual([], self.rule_hits("It stands beside the gate.", "copula-avoidance"))
def test_renderer_citation_residue_is_high(self):
tokens = ("contentReference", "oaicite", "oai_citation", "turn0search12", "attributableIndex", "grok_card", "grok_render_citation_card_json", "[cite: 7]", "[span_12](start_span)", "ppl-ai-file-upload")
for token in tokens:
with self.subTest(token=token):
hits = self.rule_hits("The source is " + token + ".", "citation-markup")
self.assertEqual(1, len(hits))
self.assertEqual("high", hits[0]["sev"])
self.assertEqual([], self.rule_hits("`" + token + "` is a literal example.", "citation-markup"))
for text in ("The source is [7](https://example.org/paper).", "The content reference is in the note.", "turn0search has no numeric suffix.", "The citation is [cite: author]."):
with self.subTest(text=text):
self.assertEqual([], self.rule_hits(text, "citation-markup"))
def test_new_rules_keep_noise_and_escape_handling(self):
text = "The result: practical steady dependable, highlighting the source contentReference."
for wrapped in ("> " + text, '`' + text + '`', '"' + text + '"', "```\n" + text + "\n```", text + " <!-- unslop-ignore -->", text + " <!-- voice-allow: quoted example -->"):
with self.subTest(wrapped=wrapped):
self.assertEqual([], self.scan_text(wrapped)[0])
bullet = "- **Owner:** Casey\n"
self.assertEqual([], self.rule_hits(bullet + bullet.rstrip() + " <!-- unslop-ignore -->\n" + bullet, "bolded-label-list"))
def test_clean_fixtures_have_zero_findings(self):
files = list((FIXTURES / "clean").iterdir())
self.assertGreaterEqual(len(files), 2)
self.assertLessEqual(len(files), 4)
for path in files:
with self.subTest(path=path.name):
findings, _ = SCANNER.scan(str(path), "low")
self.assertEqual([], findings)
def test_every_rule_fires_on_a_dirty_fixture(self):
seen = set()
for path in (FIXTURES / "dirty").iterdir():
findings, _ = SCANNER.scan(str(path), "low")
seen.update(f["rule"] for f in findings)
self.assertEqual({r["id"] for r in SCANNER.RULES}, seen)
def test_fixture_traversal_excludes_test_fixtures(self):
files = set(SCANNER.iter_files(str(SCRIPT.parents[1])))
self.assertNotIn(str(FIXTURES / "dirty" / "catalog.md"), files)
def test_scan_cli_keeps_json_shape_severity_and_exit_codes(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
path = Path(tmp) / "sample.md"
path.write_text("Delve into this.", encoding="utf-8")
for text, code in (("Delve into this.", 0), ("This holistic approach brings synergy.", 1)):
path.write_text(text, encoding="utf-8")
result = subprocess.run([sys.executable, str(SCRIPT), str(path), "--json"], capture_output=True, text=True)
self.assertEqual(code, result.returncode)
data = json.loads(result.stdout)
self.assertEqual({"path", "files_scanned", "words", "counts", "configured_style_score", "density_per_1k_words", "verdict", "findings"}, set(data))
self.assertEqual({"rule", "label", "sev", "note", "fix", "file", "line", "match", "snippet"}, set(data["findings"][0]))
high_only = subprocess.run([sys.executable, str(SCRIPT), str(path), "--severity", "high", "--json"], capture_output=True, text=True)
self.assertEqual(1, high_only.returncode)
self.assertTrue(all(f["sev"] == "high" for f in json.loads(high_only.stdout)["findings"]))
missing = subprocess.run([sys.executable, str(SCRIPT), str(path) + ".missing"], capture_output=True, text=True)
self.assertEqual(2, missing.returncode)
missing_path = subprocess.run([sys.executable, str(SCRIPT)], capture_output=True, text=True)
self.assertEqual(2, missing_path.returncode)
def test_structured_citations_survive_json_quotes_but_examples_pass(self):
residues = ('({"attribution":{"attributableIndex":"1009-1"}})', '<grok-card data-id="e8ff4f">', '[cite: 19, 20, 21]', '{"type":"grok_card","citation_id":"abc"}')
for text in residues:
with self.subTest(text=text):
hits = self.rule_hits(text, "citation-markup")
self.assertEqual(1, len(hits))
self.assertEqual("high", hits[0]["sev"])
for example in ('`' + text + '`', '> ' + text, text + ' <!-- unslop-ignore -->'):
self.assertEqual([], self.rule_hits(example, "citation-markup"))
for text in ('"attributableIndex" is a quoted field name.', '"The field is attributableIndex."', '[cite: Alice, Bob]', '<p title="attributableIndex">Source</p>'):
self.assertEqual([], self.rule_hits(text, "citation-markup"))
def test_project_traversal_prunes_nested_fixtures_but_scans_direct_files(self):
with tempfile.TemporaryDirectory(dir=SCRIPT.parent.parent) as tmp:
root = Path(tmp)
readme = root / "README.md"
readme.write_text("A plain guide.", encoding="utf-8")
dirty = []
for parent in ("tests", "test"):
for middle in ("", "unit/helpers"):
path = root / parent / middle / "fixtures" / "dirty.md"
path.parent.mkdir(parents=True)
path.write_text("Delve into this.", encoding="utf-8")
dirty.append(path)
ordinary = root / "fixtures" / "guide.md"
ordinary.parent.mkdir()
ordinary.write_text("A plain guide.", encoding="utf-8")
live = root / "test" / "notes.md"
live.write_text("Delve into this.", encoding="utf-8")
self.assertEqual({str(readme), str(ordinary), str(live)}, set(SCANNER.iter_files(tmp)))
self.assertEqual(1, len(SCANNER.scan(tmp, "low")[0]))
for path in dirty:
self.assertEqual(1, len(SCANNER.scan(str(path), "low")[0]))
self.assertEqual([], list(SCANNER.iter_files(str(path.parent))))
live.unlink()
self.assertEqual([], SCANNER.scan(tmp, "low")[0])
def test_literal_textiles_and_dataflow_pass_but_figurative_weaving_fires(self):
for text in ("A woven tapestry of Saint George covers the wall.", "A rich collector owns a silk tapestry.", "Together, we restored a silk tapestry.", "The museum displays a woven\ntapestry from France.", "Python supports the object oriented paradigm.", "The dataflow paradigm represents computation as a directed graph."):
self.assertEqual([], self.rule_hits(text, "era-vocab"))
for text in ("Together, we have woven a rich tapestry celebrating our community.", "We have woven a tapestry celebrating our community.", "A woven tapestry of ideas.", "A paradigm of excellence."):
hits = self.rule_hits(text, "era-vocab")
self.assertEqual(1, len(hits))
self.assertEqual("medium", hits[0]["sev"])
def test_promotional_antithesis_variants_gate_and_cause_corrections_pass(self):
for subject, repeat in (("It's", "it's"), ("It’s", "it’s"), ("It is", "it is")):
for noun in ("a tool", "another software tool", "a server deployment tool"):
for ending in (repeat + " a movement", "but a movement"):
text = subject + " not just " + noun + ", " + ending + "."
hits = self.rule_hits(text, "antithesis")
self.assertEqual(1, len(hits), text)
self.assertEqual("high", hits[0]["sev"])
self.assertTrue(self.rule_hits("Not just another software tool, but a movement.", "antithesis"))
for text in ("The job failed not because the file is missing but because access was denied.", "It is not red, but blue.", "It is not just another tool.", "It is just a tool, but a useful one."):
self.assertEqual([], self.rule_hits(text, "antithesis"))
def test_markup_and_soft_wraps_keep_phrase_matching_and_source_lines(self):
cases = (("\n<p>The result: You move faster.</p>", "staged-reveal", 2),
("The team grew,\nhighlighting the power of collaboration.", "significance-tail", 1),
("Our product serves as a guide to excellence.", "copula-avoidance", 1),
("<p>The team grew,\nhighlighting the power of collaboration.</p>", "significance-tail", 1),
("<p>The <em>result:</em> You move faster.</p>", "staged-reveal", 1),
("**The result:** You move faster.", "staged-reveal", 1),
("- The catch? There is none.", "staged-reveal", 1),
("The team grew, highlighting **the** power of collaboration.", "significance-tail", 1),
("The team grew, _highlighting_ the power of collaboration.", "significance-tail", 1),
("Plain text.\nThe result: You move faster.", "staged-reveal", 2))
for text, rule, line in cases:
hits = self.rule_hits(text, rule)
self.assertEqual([line], [f["line"] for f in hits], text)
for text, rule in (("<p>We recorded the result: accepted.</p>", "staged-reveal"),
("The team grew,\n\nhighlighting the power of collaboration.", "significance-tail"),
("Our product serves as evidence.", "copula-avoidance"),
('<p title="The result:">A plain paragraph.</p>', "staged-reveal")):
self.assertEqual([], self.rule_hits(text, rule))
def test_bolded_label_items_allow_blank_lines_and_wrapped_continuations(self):
item = "- **Owner:** Casey\n manages the queue.\n\n"
hits = self.rule_hits(item * 3, "bolded-label-list")
self.assertEqual([1, 4, 7], [f["line"] for f in hits])
for separator in ("A new paragraph.\n", "- An unlabelled item.\n", "## A new section\n"):
self.assertEqual([], self.rule_hits(item * 2 + separator + item, "bolded-label-list"))
self.assertEqual([], self.rule_hits(item * 2, "bolded-label-list"))
def test_compare_preserves_signed_numbers_exponents_negation_and_url_suffixes(self):
pairs = (("The balance is -5.", "The balance is 5.", "numbers only in original: -5"),
("The value is 1e3.", "The value is 1e4.", "numbers only in original: 1e3"),
("You cannot proceed.", "You can proceed.", "negations only in original: cannot"),
("You can't proceed.", "You can proceed.", "negations only in original: can't"),
("https://example.org/Function_(mathematics)", "https://example.org/Function_(physics)", "URLs only in original: https://example.org/Function_(mathematics)"))
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
original, rewrite = Path(tmp) / "a.md", Path(tmp) / "b.md"
for before, after, expected in pairs:
original.write_text(before, encoding="utf-8")
rewrite.write_text(after, encoding="utf-8")
differences = SCANNER.compare_text(str(original), str(rewrite))
self.assertTrue(any(expected in d for d in differences), differences)
self.assertEqual([], SCANNER.compare_text(str(original), str(original)))
for before, after in (("You can’t proceed.", "You can't proceed."),
("https://example.org/Function_(mathematics)", "[source](https://example.org/Function_(mathematics))."),
("https://example.org/Function_(mathematics)", "(https://example.org/Function_(mathematics)).")):
original.write_text(before, encoding="utf-8")
rewrite.write_text(after, encoding="utf-8")
self.assertEqual([], SCANNER.compare_text(str(original), str(rewrite)))
def test_html_script_style_bodies_are_not_prose_but_visible_text_is(self):
for hidden in ('<script>const challenge = 1; const steady = 2; const practical = 3;</script>',
'<style>.challenge { --steady: practical; }</style>',
'<SCRIPT type="text/javascript">\nconst challenge = "steady practical";\n</SCRIPT>',
'<script>const residue = "<grok-card>";</script>'):
self.assertEqual([], self.scan_text(hidden + '<p>A plain guide.</p>')[0])
findings, words = self.scan_text(hidden + '<p>challenge steady practical</p>')
self.assertEqual(3, len([f for f in findings if f["rule"] == "current-era-cluster"]))
self.assertEqual(3, words)
def test_compare_lists_lost_and_added_tokens_but_exits_zero(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
original = Path(tmp) / "original.md"
rewrite = Path(tmp) / "rewrite.md"
original.write_text("It must not cost 12.5 at https://example.org/a", encoding="utf-8")
rewrite.write_text("It may cost 20 at https://example.org/b", encoding="utf-8")
result = subprocess.run([sys.executable, str(SCRIPT), "--compare", str(original), str(rewrite)], capture_output=True, text=True)
self.assertEqual(0, result.returncode)
for difference in ("numbers only in original: 12.5", "numbers only in rewrite: 20", "URLs only in original: https://example.org/a", "URLs only in rewrite: https://example.org/b", "negations only in original: not", "modals only in original: must", "modals only in rewrite: may"):
self.assertIn(difference, result.stdout)
def test_compare_unchanged_inventories_do_not_report_differences(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
original = Path(tmp) / "original.md"
rewrite = Path(tmp) / "rewrite.md"
original.write_text("No user should pay 12 at https://example.org/a", encoding="utf-8")
rewrite.write_text("At [the source](https://example.org/a), no user should pay 12", encoding="utf-8")
# Capitalization of sentence-initial negations must not create a difference.
self.assertEqual([], SCANNER.compare_text(str(original), str(rewrite)))
result = subprocess.run([sys.executable, str(SCRIPT), "--compare", str(original), str(original)], capture_output=True, text=True)
self.assertEqual(0, result.returncode)
self.assertIn("No token inventory differences found.", result.stdout)
missing = subprocess.run([sys.executable, str(SCRIPT), "--compare", str(original), str(rewrite) + ".missing"], capture_output=True, text=True)
self.assertEqual(2, missing.returncode)
if __name__ == "__main__":
unittest.main()
skills/a-unslop-ui/SKILL.md7.2 KB
---
name: a-unslop-ui
description: "Remove stock AI-generated design patterns without imposing a look. Use when building, styling, reviewing, refactoring or auditing websites, landing pages, web app UIs, dashboards or web components; for \"looks AI-generated\", \"de-slop this\", \"make it look custom\", slop or vibe-coded UI; and for Tailwind or shadcn appearance work. Apply during web UI work even when AI is not mentioned. Checks stock themes, AI-purple, gradient hero/body text, unprompted neon glow, emoji icons, hero-plus-three-cards layouts and cream/serif/green defaults. Includes a scanner plus visual checks for layout, spacing and overflow. Preserve deliberate brand choices."
---
# a-unslop-ui
Part of the unslop family (see `a-unslop-text`, `a-unslop-code`). Same shape: an auto-trigger, Build and Audit modes, a scanner that gates on a high-severity exit code, an `unslop-ignore` escape. This one is about web UI. It works on any web codebase, whatever sites or apps you run it against, and the method and scanner do not assume a particular stack.
**What it is not.** It does not give you a good design and it has no preferred look. It removes the cues that read as AI-made, and where the model would reach for a default it forces a choice the project actually made. Taste, brand, and layout judgment stay yours.
## The trap: do not swap one default for another
Every anti-slop effort fails the same way, by replacing one default look with another. The 2024 default was the purple-to-blue gradient on a dark hero. The 2026 default is a warm cream background, a serif display face (Instrument Serif, Fraunces), and a sage, forest-green, or terracotta accent. Swapping the first for the second is not unslopping. People clock it just as fast, and it reads as AI for the same reason: nobody chose it, the model did.
So this skill prescribes no palette, no font, no layout. It detects the defaults, old and new, and asks that any replacement be a choice the project made on purpose. The one rule is "make a deliberate choice and be able to say why," which is the one thing a default never is. If the brand really is purple, neon, or a cream serif look, that is not slop; mark it `unslop-ignore` and move on. A tell is an unspecified default, not a banned colour.
## How it differs from the built-in frontend-design skill
Anthropic's [frontend-design skill](https://raw.githubusercontent.com/anthropics/skills/main/skills/frontend-design/SKILL.md), checked 2026-10-16, already warns against cream/serif/clay, dark acid-accent palettes, hairline broadsheets, the SaaS card kit, and repeated template chrome. It permits one type family and says the brief wins. This skill adds a deterministic scanner and CI gate for mechanical signatures across both old and new defaults, plus a catalog for human review. Use them together; neither a finding nor a clean scan establishes authorship.
## Build mode
Most "looks AI" output is an under-specified prompt. An unspecified prompt gets the median of the training data, and everyone's median is the same. Before generating, set four things:
- **A reference.** One real site, brand, or screenshot whose design language to follow. This one input does more than the rest combined. If there is none, pick a named direction (editorial, brutalist, dense-utilitarian, warm-consumer, technical-mono), not "modern and clean," which means nothing.
- **A colour.** A real brand colour or a chosen one, stated. Not the framework default, not the cream/sage default.
- **A typeface.** A specific face or pairing chosen for this project, with a reason. The autopilot picks are Inter and Geist on the sans side, Instrument Serif, Fraunces, Playfair on the "tasteful" side; both are defaults, so reach for them only as a real choice.
- **A layout intent.** What the page is for and what the reader should do first. Structure follows the goal, which is how you avoid the hero-plus-three-cards skeleton.
With no brief, do not produce one median result. Produce a deliberate one and say what you chose, or offer two or three distinct directions. The value is breaking the monoculture. `references/choosing-a-look.md` is the method; the tells to avoid are in `references/tells.md`.
## Audit mode
On "does this look AI" or "de-slop this," run the scanner, then fix in priority order.
```bash
python3 "${CLAUDE_SKILL_DIR}/scripts/devibe_scan.py" <path> # report + vibe score
python3 "${CLAUDE_SKILL_DIR}/scripts/devibe_scan.py" <path> --severity high # strongest only
python3 "${CLAUDE_SKILL_DIR}/scripts/devibe_scan.py" <path> --json # for CI
```
It scans `.html .htm .css .scss .sass .less .js .jsx .ts .tsx .vue .svelte .astro .mdx` and files named `components.json`, reports each finding with file, line, and fix, and gives a vibe score. Exit code is the high count, so CI can gate on it. It catches mechanical tells: colours, fonts, gradients, palette/type clusters, and repeated template chrome. It cannot see layout coherence, spacing, or text overflowing its container, and those are also why a page reads as AI, so after the scan check them by eye against the catalog.
**Shipped UI only.** It skips `docs/`, `_archive/`, `archive/`, `mockups/`, `examples/`, `_demo/`, `demo/`, `demos/`, `fixtures/` and `storybook-static/` alongside the usual `node_modules`/`dist`/`vendor`. A design comp or a palette swatch page quotes a tell rather than committing one, and scanning them buried the real findings. If a site genuinely serves its UI from one of those directories, scan that path directly.
`python3 -m unittest discover -s tests` covers the precision rules. Run it after touching a pattern; several cases preserve fixes for specific false positives.
**Escape hatch.** A line with `unslop-ignore` is skipped, for a real brand decision.
**Fixing well.** Do not fix `bg-purple-600` by swapping in `bg-emerald-700`, which is a different default. Apply the project's real colour, or ask what it should be. A fix that introduces a new unspecified default is not a fix.
## What it does not flag
Mesh/blob/aurora backgrounds, bento grids, and glassmorphism stay outside the scanner. Review them as advisories when repeated reflexively or unrelated to content. The original Reddit study cannot prove their absence as tells; current catalogs list them (see `references/tells.md`). Dark mode itself is fine; only the unprompted glow is a tell. shadcn and Tailwind are fine; their untouched defaults are the tell. Over-flagging trains people to ignore the tool, so the scanner stays narrow.
## Reporting
Lead with the verdict and the single highest-impact change. Findings by priority with file:line and the fix. Close with the vibe score and the top three changes. The goal is a site that looks like a person made a decision, the one thing the scanner cannot do for you.
## Credits
The original tell catalog comes from the vibecoded-design-tells research by JCarterJohnson (https://github.com/JCarterJohnson/vibecoded-design-tells, MIT), a Reddit study of what people flag as AI-built websites. Current additions have dated sources in `references/tells.md`; severity reflects judged risk and pattern precision. This skill rewrites that material into the unslop family and a shared Build/Audit shape with the text and code skills. `scripts/devibe_scan.py` is an adapted fork of that project's scanner (MIT); the credit is in its header.
skills/a-unslop-ui/agents/openai.yaml110 B
interface: display_name: "Unslop UI" short_description: "Review websites for repeated AI design patterns"
skills/a-unslop-ui/references/choosing-a-look.md2.9 KB
# Choosing a look on purpose This file gives you a way to decide, not a thing to copy. Any specific recommendation, repeated, becomes the next default and the next tell. The first version of this skill recommended cream backgrounds, forest green, and Fraunces, which is exactly the look people now read as AI-tasteful on sight. So: a method. The goal is one outcome: a design where every major choice has a reason specific to this project. That is the one property a default cannot have. ## Start from a reference The input that does the most work is a real reference. Ask for one site, brand, or screenshot whose feel they want, and anchor colour, type, and density to it. If they cannot name one, that is the conversation to have before writing CSS, because without it you are choosing the median for them. With no reference, pick a named direction and commit: dense and utilitarian (a trading terminal), editorial and text-forward (a magazine), warm and consumer (a friendly app), stark and technical (developer tooling), expressive and brand-loud. Naming it forces specificity and steers off the centre. ## Colour Decide a primary from the project, not the framework. A real brand colour is best. If you are choosing, sample from something concrete (a product photo, a logo, a place) so the palette has a source. Build a neutral ramp you picked, not stock slate or stock cream. The test is not "is this nice," it is "can I say why this project uses it." Avoid both current defaults: framework indigo/violet, and tasteful cream/sage. Either is fine as a stated decision, neither as a fallback. ## Type Choose one family or two for a reason. The reason can be tone (a geometric sans for precision, a humanist serif for warmth), but it has to be a reason. One family can carry the hierarchy through weight, size, and spacing. If you use two, make them clearly distinct. Steer off the autopilot picks on both sides: Inter and Geist (the "no choice" default), Instrument Serif, Fraunces, Playfair (the "tasteful choice" default). Not banned, overexposed. Use them only as a real decision, ideally not for the headline that sets the tone. ## Layout Structure follows the goal, not a template. Decide what the page is for and what the reader does first, and let that set the sections. That is how you avoid the centred hero plus three identical cards: the skeleton appears when structure is chosen by default. Show the real product (a true screenshot, real numbers) over abstract icon cards. Vary section shape and density down the page. ## Motion, radius, detail Decide these consciously and sparingly. Motion should communicate something and honour `prefers-reduced-motion`. Radius is a small intentional scale, not one value on everything. Glow, gradients, and effects are decisions to justify, not defaults to accept. ## One line Get a real reference and match it. Everything else here is what to do when you cannot. The skill removes the tells; this is how you replace them with something chosen.
skills/a-unslop-ui/references/tells.md12.7 KB
# AI-website tells: the catalog
The scanner (`scripts/devibe_scan.py`) enforces mechanical signatures; human review decides whether they fit the brief. A tell is a reason to inspect a choice, not proof of AI authorship. Severity reflects judged risk and pattern precision, not complaint frequency. HIGH findings gate CI; MEDIUM and LOW are advisory. Sources below were checked or carried forward in 2026-10, not necessarily published then.
Source names: [Reddit study](https://github.com/JCarterJohnson/vibecoded-design-tells), [Anthropic frontend-design](https://raw.githubusercontent.com/anthropics/skills/main/skills/frontend-design/SKILL.md), [shadcn Card](https://raw.githubusercontent.com/shadcn-ui/ui/main/apps/v4/registry/new-york-v4/ui/card.tsx), [Impeccable](https://impeccable.style/slop/), [signs-of-ai-design](https://github.com/febbhav/signs-of-ai-design), [stop-design-slop](https://github.com/Juuzoe/stop-design-slop), and [NN/g sparkles](https://www.nngroup.com/articles/ai-sparkles-icon-problem/). Source guidance supports review candidates; the scanner thresholds are house choices, not validated authorship tests.
## High
### The tasteful default (`claude-default-look`)
Warm cream, a serif display face, and a sage/forest or terracotta/clay accent can become another interchangeable default. Anthropic now warns against the cream/serif/clay cluster itself. (source: Anthropic frontend-design, 2026-10)
- Scanner: any two of three signal groups in one file produce one HIGH finding. A single group produces no finding. Cream backgrounds include `#faf8f5`, `#f5f1e8`, `#f4f1ea` and related listed swatches in the scanner, or `bg-stone-50/100`, `bg-amber-50/100`, `bg-orange-50/100`. Hex cream counts on `background`, `background-color`, or `--background` declarations. Serif names are Instrument Serif, Fraunces, Playfair Display, Cormorant, Spectral, and DM Serif. The accent group includes green/emerald 700-900 colour utilities, sage/forest swatches `#9caf88`, `#87a878`, `#2d4a3e`, `#264e36`, and clay swatches `#d97757`, `#c96442`, `#cc785c`. Green and clay together still count as one group; hex matching uses listed swatches, not a continuous colour range.
- The accent must appear on a button, link or heading, a class/selector naming primary, accent, brand, CTA, button, link or heading roles, or a `--primary`, `--accent` or `--brand` theme variable (including suffixed names). Green pills combining `bg-green-100` with `text-green-700` (or emerald equivalents), and `span` elements with `rounded-full text-xs`, do not supply an accent signal. Status and warning lines do not contribute. Block, HTML and code line comments are masked across lines without treating quoted comment delimiters as comments; `unslop-ignore` lines do not contribute to any rule. Signals never combine across files. These are source co-occurrences, not computed styles or proof that a serif is used for display.
- Fix: anchor the choices to a real brand or reference. Keep a deliberate warm-editorial identity and mark its source lines `unslop-ignore`.
### Untouched shadcn / Tailwind (`shadcn-default-card`)
Shipping the stock Card and theme makes unrelated products resemble the same starter. The tools themselves are fine. (source: Reddit study, 2026-10)
- Card signature: at least four of five class groups in one quoted string or CSS `@apply` directive, in any order: `rounded-lg` or `rounded-xl`, `border`, `bg-card`, `text-card-foreground`, `shadow-sm`. Extra layout classes and nested quote characters in arbitrary utilities are allowed. The current registry uses `rounded-xl`. (source: shadcn Card, 2026-10)
- Theme signatures: `--radius: 0.5rem`, or a file literally named `components.json` with `baseColor` set to slate, zinc, neutral, gray, or stone and `cssVariables: true` (also accepts `cssVars: true`). Configuration fields can be under `tailwind` or at the root. Other JSON files are not included in directory scans.
- Fix: choose primary, radius, neutrals, and spacing for the project. The signature is a review gate, not proof that tokens are unthemed.
### AI purple (`ai-purple`)
Indigo/violet/purple used as the fallback primary is a recurring complaint. (source: Reddit study, 2026-10)
- Scanner: Tailwind indigo/violet/purple/fuchsia colour utilities at 400-800 and the listed common hex values. It cannot determine the actual primary role; platform/brand/social swatch lines are suppressed.
- Fix: use the real brand colour. A deliberate purple identity gets `unslop-ignore`, not a replacement default.
### Gradient text and purple-blue gradients (`gradient-text`, `purple-blue-gradient`)
Gradient headings and purple-to-blue/pink hero fills recur across generated landing pages. (source: Reddit study, 2026-10)
- Scanner: `bg-clip-text` with `text-transparent`, CSS text background clipping, purple-family `from-*` stops followed by blue/indigo/pink/cyan/sky `to-*`, or a linear gradient containing one of the listed purple hexes. It does not detect every gradient.
- Fix: use solid text and fills unless the brief gives the gradient a role.
## Medium
- **Repeated eyebrow chrome (`eyebrow-chrome`).** Three or more labels in one file, each with `uppercase` (a class or inline `text-transform`) and `tracking-wide`, `tracking-wider`, `tracking-widest`, or `letter-spacing`, directly preceding an `h1`-`h6`. The scanner recognizes `p`, `span`, `div`, or `small` labels containing plain text; attributes can span lines. Static React `style={{letterSpacing:".1em"}}` and `textTransform:"uppercase"` are supported, as are inline JSX comments between label and heading. Dynamic style values, spread attributes, computed properties and intervening components are not resolved. Keep an eyebrow only when it adds information. (source: Anthropic frontend-design, 2026-10)
- **Tinted icon tiles (`tinted-icon-tiles`).** Three or more rounded `div`/`span` wrappers with `bg-primary/10` or `bg-*-500/10`, directly containing an icon component imported by name from a Lucide package. Repeating the tile can substitute decoration for product-specific imagery. Static class strings and `className={cn("...", "...")}` or `clsx` calls with only string literal arguments are supported. Conditional arguments, objects, variables, spreads, interpolated templates, nested icon wrappers and default/deep imports are not resolved. The scanner recognizes direct, self-closing icon components, including named import aliases, not arbitrary component trees. (source: stop-design-slop/references/imagery-icons.md, 2026-10)
- **Too many animations (`fade-in-animations`).** Fade-in on every section and scale-up on every card can compete with the task. The scanner flags `initial={{ opacity: 0 }}`, `whileInView`, `whileHover={{ scale }}`, `data-aos`, and `hover:scale-1xx` individually; it does not measure motion density. Keep motion that explains a change and honour `prefers-reduced-motion`. (source: Reddit study, 2026-10)
- **Rounded everything (`rounded-everything`).** The scanner flags `rounded-2xl`, `rounded-3xl`, `rounded-full`, and huge pill radii. Small `h-`/`w-` boxes are suppressed so dots and avatars pass. Choose a radius scale by role. (source: Reddit study, 2026-10)
- **Unprompted neon glow (`neon-glow`).** Zero-offset saturated shadows are candidates; achromatic and inset shadows are suppressed. Dark mode itself is fine. Remove glow without a purpose. (source: Reddit study, 2026-10)
- **Emoji icons (`emoji-as-icons`).** Rocket, sparkle, lightning, lock and related emoji used as feature icons can read as placeholders. The scanner flags its listed characters anywhere in source, so review body-copy uses before changing them. Use a meaningful SVG icon or none. (source: Reddit study, 2026-10)
- **Default fonts (`generic-font`).** The scanner catches Inter, Geist, and Roboto declarations or font-loader calls, not whether the choice was deliberate. Choose one family or two for a reason; if two, make them distinct. A chosen font gets `unslop-ignore`. (source: Reddit study, 2026-10)
- **Hero and three-card skeleton (`hero-three-cards`).** The scanner catches `grid-cols-1` followed by optional `sm:grid-cols-2` and `md:grid-cols-3`; it cannot establish the hero structure. Review whether content actually benefits from three equal cards. Structure the page around its task. (source: Reddit study, 2026-10)
## Low
- **Middle-dot metadata (`middle-dot-meta`).** Two or more distinct markup text runs containing `word · word · word` in one file produce one LOW finding. Multiple triplets within one run count once. JavaScript strings, JSX escaped examples, attributes, and script/style bodies do not count. Archive rows shaped like `2026 · October · Archive` are excluded. The rule matches literal middle dots, not `·`, and does not evaluate dynamic expressions. Keep separators when they help read real metadata. (source: Anthropic frontend-design, 2026-10)
- **Appended arrows (`appended-arrow`).** Three or more link/button labels ending in `→` produce one LOW finding per file. The scanner recognizes `a`, `button` and `Link`, decodes `→` and numeric entities, accepts static JSX `{"→"}` or `{'→'}`, and flattens child markup such as accessibility spans. Prefix arrows, arrows in the middle of labels, attributes and arbitrary source strings do not count. Dynamic text expressions, custom action components, CSS pseudo-elements, icon components and runtime translations are not resolved. CSS visibility and accessibility naming can change which source text readers encounter. Keep arrows that clarify navigation. (source: Anthropic frontend-design, 2026-10)
- **Hype copy (`hype-copy`).** `Transform your`, `Supercharge`, `Unleash`, `Effortlessly`, `reimagined`, and similar canned claims. Say what the product does. (source: Reddit study, 2026-10)
- **Stock illustrations (`stock-illustration`).** The scanner catches undraw, storyset, and drawkit source names. Check whether the image explains this product; prefer real screenshots where useful. (source: Reddit study, 2026-10)
Repetition rules produce one finding per file at the first occurrence. Their source patterns do not establish rendered DOM relationships. Keep intentional choices with `unslop-ignore` on the contributing lines.
## Human audit checks
- **Decorative numbering.** `01 / 02 / 03` section labels belong on real sequences, such as steps or timelines. Remove numbers from unrelated sections. (source: Anthropic frontend-design, 2026-10)
- **Dark acid-accent default.** Near-black `#0B0B0B`, `#111`, or `#111111` with one acid-green or vermilion accent can become another fallback. Check the brief and the whole palette; no scanner rule. (source: Anthropic frontend-design, 2026-10)
- **Hairline broadsheet.** Dense newspaper columns, hairline rules, and zero radius need a content reason. Do not substitute this look for every rounded-card design; no scanner rule. (source: Anthropic frontend-design, 2026-10)
- **Fabricated trust.** Verify logo clouds, testimonials, ratings, compliance badges, and rows claiming `10x`, `99.9%`, or `10,000+ users` against supplied sources, quote originals, relationships, and metric definitions. If unsupported, remove them or ask for evidence. Missing provenance is a verification gap, not proof of fabrication. No stat-row regex. (source: stop-design-slop, 2026-10)
- **Sparkles / Wand2 on non-AI actions.** Check whether the icon explains the action. NN/g discusses ambiguous sparkles as an AI signifier, not an AI-authorship detector. No scanner rule for action meaning. (source: NN/g sparkles, 2026-10)
- **Overflow and clipping.** Test headings and labels with real strings at narrow widths. Give text room and let it wrap. (house preference)
- **Spacing, alignment, hierarchy.** Use a consistent spacing scale and gutters; make the primary task visually clear. A clean scan cannot establish layout coherence. (house preference)
- **Centred everything and endless whitespace.** Review density and alignment against the content rather than applying either everywhere. (source: Reddit study, 2026-10)
## Do not chase without context
- **Mesh/blob/aurora backgrounds.** Advisory when repeated reflexively or unrelated to content. The original Reddit keyword analysis rejected an artifact involving `/blob/` URLs; it cannot prove absence as a tell. Current catalogs list these backgrounds. No scanner rule. (source: signs-of-ai-design, 2026-10)
- **Bento grids.** Advisory when every section becomes a bento regardless of its content. The original Reddit study cannot prove absence as a tell; current catalogs list the pattern. No scanner rule. (source: signs-of-ai-design, 2026-10)
- **Glassmorphism.** Advisory when glass panels recur without a layering need. Review purpose and readability; no scanner rule. (source: Impeccable, 2026-10)
- **Dark mode and shadcn/Tailwind.** Tools and modes do not establish authorship. Review defaults and fit to the brief. (house preference)
skills/a-unslop-ui/scripts/devibe_scan.py26.6 KB
#!/usr/bin/env python3
"""
devibe_scan.py - scan a web codebase for "vibe-coded" / AI-generated design tells.
Forked (MIT) from github.com/JCarterJohnson/vibecoded-design-tells.
Plain Python, standard library only. Adapted from the credited Reddit study, with current design guidance added. Severity reflects judged risk and pattern precision, not complaint frequency or a calibrated probability of AI authorship.
Usage:
python3 devibe_scan.py <path> # scan a dir or file
python3 devibe_scan.py <path> --severity high # only high-signal tells
python3 devibe_scan.py <path> --json # machine-readable (for CI)
python3 devibe_scan.py <path> --max 8 # cap examples shown per rule
Exit code is the number of HIGH-severity findings (0 = none), so CI can gate on it.
"""
import os, re, sys, json, argparse
from html import unescape
EXTS = {".html", ".htm", ".css", ".scss", ".sass", ".less", ".js", ".jsx",
".ts", ".tsx", ".vue", ".svelte", ".astro", ".mdx"}
SKIP_DIRS = {"node_modules", ".git", "dist", "build", ".next", "out", "vendor",
"coverage", ".svelte-kit", ".astro", ".turbo", ".cache", "__pycache__",
# Not shipped UI. Design comps, palette swatch pages and superseded
# redesigns describe a look rather than serve it, so a tell inside one
# is a quotation, not a defect. Scanning them buried the real findings.
"docs", "_archive", "archive", "mockups", "examples", "_demo", "demo", "demos",
".storybook", "storybook-static", "__snapshots__", "fixtures"}
# Keep source offsets when masking so every finding still points at its original line.
LITERAL = re.compile(r'''"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`''', re.DOTALL)
COMMENT = re.compile(r"/\*.*?(?:\*/|\Z)|<!--.*?(?:-->|\Z)|//[^\r\n]*", re.DOTALL)
VOID_TAGS = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"}
ATTRS = r'''(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|[^>"'`])*'''
W = {"high": 3, "medium": 2, "low": 1}
# Each rule: id, label, severity, fix, and patterns (case-insensitive by default).
# Keep patterns specific enough to avoid drowning the report in false positives.
RULES = [
# ---- HIGH: the top concrete tells ----
{"id": "shadcn-default-card", "label": "Untouched shadcn default Card / theme", "sev": "high",
"fix": "Theme the tokens (primary, radius, neutrals, spacing). Stock defaults are the giveaway, not shadcn.",
"pats": [r"--radius\s*:\s*0\.5rem"],
"card": True, "config": True},
{"id": "ai-purple", "label": "AI purple / indigo / violet as primary color", "sev": "high",
"fix": "Pick a brand color outside the violet/indigo/purple band. It is Tailwind's default, so it reads as 'nobody chose this'.",
"pats": [r"\b(bg|text|from|via|to|border|ring|fill|stroke|decoration|outline)-(indigo|violet|purple|fuchsia)-(400|500|600|700|800)\b",
r"#(6366f1|4f46e5|818cf8|7c3aed|6d28d9|8b5cf6|a855f7|9333ea|7e22ce|c026d3|d946ef)\b"],
# Someone else's brand is a fact, not a default. Hashnode, dev.to, Twitch and
# Figma really are purple, so a platform/social swatch is not this tell.
"suppress": r"\b(platform|brand|social|logo|icon)\b|devto|dev-to|hashnode|twitch|figma|discord|slack|viber|nubank|roku"},
{"id": "gradient-text", "label": "Gradient-filled text (heading/hero)", "sev": "high",
"fix": "Solid color on headings and copy. Gradient body text is one of the strongest AI tells.",
"pats": [r"bg-clip-text\s+[^\"'`]*text-transparent", r"text-transparent\s+[^\"'`]*bg-clip-text",
r"-webkit-background-clip\s*:\s*text", r"\bbackground-clip\s*:\s*text"]},
{"id": "purple-blue-gradient", "label": "Purple-to-blue/pink gradient", "sev": "high",
"fix": "Default to solid fills. If you must gradient, keep stops analogous and low-contrast, never the rainbow purple-to-blue.",
"pats": [r"from-(purple|violet|indigo|fuchsia)-\d+\s+(via-[a-z]+-\d+\s+)?to-(blue|indigo|pink|cyan|sky)-\d+",
r"linear-gradient\([^)]*#(6366f1|7c3aed|8b5cf6|a855f7)[^)]*\)"]},
{"id": "claude-default-look", "label": "The 'tasteful default' cluster (cream / serif / green or clay)", "sev": "high",
"fix": "Anchor color and type to the real brand or a reference. Mark deliberate choices unslop-ignore on their source lines.",
"pats": [r"(?:background(?:-color)?|--background)\s*:\s*#(faf8f5|f5f1e8|f3eee3|fdfbf7|f7f3ec|faf6ef|f6f1e7|fbf7f0|f4efe4|f4f1ea)\b|\bbg-(stone|amber|orange)-(50|100)\b",
r"\b(Instrument\s*Serif|Fraunces|Playfair\s*Display|Cormorant|Spectral|DM\s*Serif)\b",
r"\b(?:bg|text|border|ring|fill|stroke)-(emerald|green)-(700|800|900)\b|#(d97757|c96442|cc785c|9caf88|87a878|2d4a3e|264e36)\b"],
"min_signals": 2,
"suppress": r"\b(warning|caution|alert|notice|error|danger|success|info|badge|toast|status|pending|tag|chip|highlight|mark)\b"},
# ---- MEDIUM ----
{"id": "hero-three-cards", "label": "Centered hero + three-feature-card grid skeleton", "sev": "medium",
"fix": "Break the grid. Asymmetric hero with a real screenshot; vary sections instead of stacked 3-up icon cards.",
"pats": [r"grid-cols-1\s+(sm:grid-cols-2\s+)?md:grid-cols-3"]},
{"id": "rounded-everything", "label": "Large rounded corners / pill buttons everywhere", "sev": "medium",
"fix": "Use a small, intentional radius scale by role. Not everything maximally rounded; pills only occasionally.",
"pats": [r"\brounded-(2xl|3xl|full)\b", r"border-radius\s*:\s*(999\d*px|9999px)"],
# rounded-full on a small sized box is a status dot / avatar / icon, not a pill button. Skip those.
"suppress": r"\b[hw]-(\d|10|11|12|14|16)(\.5)?\b"},
{"id": "fade-in-animations", "label": "Boilerplate fade-in / hover-grow / scroll animation", "sev": "medium",
"fix": "Motion only when it communicates something; gate behind prefers-reduced-motion. Minor tell, noisier signal.",
"pats": [r"initial=\{\{\s*opacity:\s*0", r"whileInView", r"whileHover=\{\{\s*scale",
r"data-aos\s*=", r"\bhover:scale-1\d{2}\b"]},
{"id": "neon-glow", "label": "Unprompted neon glow shadow", "sev": "medium",
"fix": "Remove glow you did not deliberately design. Dark mode should rely on contrast, not glow.",
# A glow is a zero-offset shadow in a saturated color. The old patterns matched any
# shadow with a blur, so an ordinary soft drop shadow scored as neon: on one real
# site that was 78 of 87 findings, every one of them black.
"pats": [r"shadow-\[0_0_", r"drop-shadow-\[0_0_",
r"text-shadow\s*:\s*0\s+0\s+\d{2,}px",
r"box-shadow\s*:\s*0\s+0\s+\d{2,}px"],
# Achromatic means soft shadow, not glow. `inset` is a fill or an inner border.
"suppress": r"inset|rgba?\(\s*(\d{1,3})\s*,\s*\1\s*,\s*\1\b|#([0-9a-f])\2{2}\b|#([0-9a-f]{2})\3{2}\b"},
{"id": "emoji-as-icons", "label": "Emoji used as icons / section bullets", "sev": "medium",
"fix": "Use a real SVG icon set (Lucide/Phosphor/Heroicons) or none. Emoji-as-UI signals low effort.",
"pats": [r"[\U0001F680✨⚡\U0001F525\U0001F4A1\U0001F512✅\U0001F3AF\U0001F31F\U0001F6E1\U0001F4C8\U0001F511\U0001F389\U0001F680]"]},
{"id": "generic-font", "label": "Generic default font (Inter / Geist / Roboto / system)", "sev": "medium",
"fix": "Choose one family or two for a reason. If two, make them clearly distinct. The starter font reads as 'no choice made'.",
"pats": [r"font-family\s*:\s*['\"]?(Inter|Geist|Roboto)\b",
r"\b(Inter|Geist|Geist_Mono|Roboto)\s*\(",
r"fontFamily\s*:\s*\{[^}]*['\"](Inter|Geist|Roboto)"]},
{"id": "eyebrow-chrome", "label": "Repeated tracked uppercase labels above headings", "sev": "medium",
"fix": "Keep labels only when they add information; remove repeated decorative eyebrows.",
"pats": [r"<(?P<eyebrow>p|span|div|small)\b(?P<attrs>" + ATTRS + r")>[^<]*</(?P=eyebrow)>\s*<h[1-6]\b"],
"min_count": 3},
{"id": "tinted-icon-tiles", "label": "Repeated rounded tinted icon tiles", "sev": "medium",
"fix": "Use icons where they explain a feature; avoid repeating the same decorative tile.",
"pats": [r"<(?P<tile>div|span)\b(?P<attrs>" + ATTRS + r")>\s*<(?P<icon>[A-Z][A-Za-z0-9]*)\b" + ATTRS + r"/\s*>\s*</(?P=tile)>"],
"case_sensitive": True, "min_count": 3},
# ---- LOW: copy + minor ----
{"id": "middle-dot-meta", "label": "Repeated middle-dot metadata strings", "sev": "low",
"fix": "Use metadata separators when the content needs them, not as template decoration.",
"pats": [r"\b\w+ · \w+ · \w+\b"],
"markup_text": True, "min_count": 2},
{"id": "appended-arrow", "label": "Repeated arrows appended to links or buttons", "sev": "low",
"fix": "Keep arrows when they clarify navigation; remove automatic arrows on every action.",
"pats": [],
"min_count": 3},
{"id": "hype-copy", "label": "Generated marketing copy cliche", "sev": "low",
"fix": "Say what the product literally does, with specifics. Cut the template hype words.",
"pats": [r"\bTransform your\b", r"\bSupercharge\b", r"\bUnleash\b", r"\bEffortlessly\b",
r"\breimagined\b", r"take your [^.]{0,30}to the next level", r"\bGame-?changer\b"]},
{"id": "stock-illustration", "label": "Generic blob / stock illustration source", "sev": "low",
"fix": "Use real screenshots or commissioned art instead of undraw-style blobs.",
"pats": [r"undraw", r"storyset", r"\bdrawkit\b"]},
]
def compile_rules(min_sev):
order = ["high", "medium", "low"]
floor = order.index(min_sev) if min_sev else len(order) - 1
out = []
for r in RULES:
if order.index(r["sev"]) > floor:
continue
r = dict(r)
r["rx"] = [re.compile(p, 0 if r.get("case_sensitive") else re.IGNORECASE) for p in r["pats"]]
r["suppress_rx"] = re.compile(r["suppress"], re.IGNORECASE) if r.get("suppress") else None
out.append(r)
return out
def iter_files(path):
if os.path.isfile(path):
yield path; return
for root, dirs, files in os.walk(path):
dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
for f in files:
if f.endswith(".min.js") or f.endswith(".min.css"):
continue
if os.path.splitext(f)[1].lower() in EXTS or f == "components.json":
yield os.path.join(root, f)
def blank(text):
return re.sub(r"[^\r\n]", " ", text)
def code_comments(text):
tokens = re.compile(LITERAL.pattern + "|" + COMMENT.pattern, re.DOTALL)
return tokens.sub(lambda m: blank(m.group()) if COMMENT.fullmatch(m.group()) else m.group(), text)
def brace_end(text, start):
depth, i = 1, start + 1
while i < len(text):
token = LITERAL.match(text, i) or COMMENT.match(text, i)
if token:
i = token.end()
continue
if text[i] == "{":
depth += 1
elif text[i] == "}":
depth -= 1
if not depth:
return i + 1
i += 1
return len(text)
def tag_at(text, start):
opener = re.match(r"<(/?)([A-Za-z][\w:.-]*|)(?=[\s/>])", text[start:])
if not opener:
return None
i = start + opener.end()
attrs_start = i
while i < len(text):
token = LITERAL.match(text, i) or COMMENT.match(text, i)
if token:
i = token.end()
continue
if text[i] == "{":
i = brace_end(text, i)
continue
if text[i] == ">":
return (i + 1, opener.group(2), text[attrs_start:i], bool(opener.group(1)))
i += 1
return None
def source_views(text, code):
"""Mask comments everywhere and code literals outside markup in a second view."""
clean, markup = [], []
stack = []
i = 0
while i < len(text):
in_code = (code and not stack) or (stack and stack[-1].lower() in {"script", "style"})
comment = COMMENT.match(text, i)
if comment and (not comment.group().startswith("//") or in_code):
masked = blank(comment.group())
clean.append(masked)
markup.append(masked)
i = comment.end()
continue
literal = LITERAL.match(text, i) if in_code else None
if literal:
clean.append(literal.group())
markup.append("?" + blank(literal.group())[1:])
i = literal.end()
continue
tag = tag_at(text, i) if text[i] == "<" else None
if tag:
end, name, attrs, closing = tag
chunk = code_comments(text[i:end])
clean.append(chunk)
markup.append(chunk)
if closing:
if name in stack:
del stack[stack.index(name):]
elif name not in VOID_TAGS and not attrs.rstrip().endswith("/"):
stack.append(name)
i = end
continue
if text[i] == "{" and re.match(r"\{\s*/\*", text[i:]):
end = brace_end(text, i)
chunk = code_comments(text[i:end])
if not chunk[1:-1].strip():
clean.append(blank(chunk))
markup.append(blank(chunk))
i = end
continue
if not in_code and text[i] == "{":
end = brace_end(text, i)
chunk = code_comments(text[i:end])
if not chunk[1:-1].strip():
chunk = blank(chunk)
clean.append(chunk)
# Only the cheap, static arrow expression is needed by the suffix rule.
static_arrow = re.fullmatch(r'''\{\s*(["'])→\1\s*\}''', chunk)
masked = blank(chunk)
if static_arrow:
offset = chunk.index("→")
masked = masked[:offset] + "→" + masked[offset + 1:]
elif chunk.strip():
masked = "?" + masked[1:]
markup.append(masked)
i = end
continue
clean.append(text[i])
markup.append(text[i] if not in_code or text[i].isspace() else "?")
i += 1
return "".join(clean), "".join(markup)
def tags(text):
i = 0
while i < len(text):
start = text.find("<", i)
if start < 0:
return
tag = tag_at(text, start)
if tag:
yield (start, *tag)
i = tag[0]
else:
i = start + 1
def attributes(attrs):
"""Read whole attribute values, never attributes quoted inside another value."""
values = {}
i = 0
while i < len(attrs):
m = re.match(r"\s*([\w:-]+)(?:\s*=\s*)?", attrs[i:])
if not m:
i += 1
continue
name = m.group(1)
end = i + m.end()
if "=" not in m.group():
i = end
continue
literal = LITERAL.match(attrs, end)
if literal:
values[name] = ("literal", literal.group()[1:-1])
i = literal.end()
elif end < len(attrs) and attrs[end] == "{":
i = brace_end(attrs, end)
values[name] = ("expression", attrs[end + 1:i - 1])
else:
m = re.match(r"[^\s>]+", attrs[end:])
i = end + len(m.group()) if m else end
return values
def static_classes(attrs):
values = attributes(attrs)
kind, value = values.get("className", values.get("class", ("literal", "")))
if kind == "expression":
value = value.strip()
call = re.fullmatch(r"(?:cn|clsx)\s*\((.*)\)\s*", value, re.DOTALL)
if call:
value = call.group(1)
literals = list(LITERAL.finditer(value))
remainder = LITERAL.sub("", value)
if not literals or (remainder.strip(" \t\r\n,") if call else remainder.strip()):
return set()
value = " ".join(m.group()[1:-1] for m in literals)
return set(value.split()) if "${" not in value else set()
def attribute_value(attrs, name):
return attributes(attrs).get(name, ("literal", ""))[1]
def is_eyebrow(m):
classes = static_classes(m.group("attrs"))
style = attribute_value(m.group("attrs"), "style")
uppercase = "uppercase" in classes or re.search(r'''(?:text-transform\s*:\s*uppercase\b|textTransform\s*:\s*["']uppercase["'])''', style)
tracking = classes & {"tracking-wide", "tracking-wider", "tracking-widest"} or re.search(r'''(?:letter-spacing\s*:|letterSpacing\s*:\s*(?:["'][^"']+["']|[0-9.]+))''', style)
return uppercase and tracking
def is_icon_tile(m, icons):
classes = static_classes(m.group("attrs"))
return (m.group("icon") in icons
and any(re.fullmatch(r"bg-(?:primary|[a-z]+-500)/10", c) for c in classes)
and any(re.fullmatch(r"rounded-[a-z0-9]+", c) for c in classes))
def accent_context(text, markup, match, rx):
role = r"(?<![A-Za-z0-9])(?:primary|accent|brand|cta|btn|button|link|heading)(?![A-Za-z0-9])"
for start, end, name, attrs, closing in tags(markup):
if start <= match.start() < end and not closing:
classes = static_classes(attrs)
badge = any({f"bg-{c}-100", f"text-{c}-700"} <= classes for c in ("green", "emerald"))
badge |= name.lower() == "span" and {"rounded-full", "text-xs"} <= classes
if badge:
return False
value = " ".join(classes) + " " + attribute_value(attrs, "style")
has_role = re.search(role, " ".join(classes), re.IGNORECASE) or name.lower() in {"a", "button", "link", "h1", "h2", "h3", "h4", "h5", "h6"}
return bool(has_role and rx.search(value))
left = text.rfind("{", 0, match.start())
if left < 0 or text.rfind("}", 0, match.start()) > left:
return False
declaration = text[max(left, text.rfind(";", left, match.start())) + 1:match.end()]
if re.match(r"\s*--(?:primary|accent|brand)(?:-[\w-]+)?\s*:", declaration):
return True
selector = text[max(text.rfind("}", 0, left), text.rfind("{", 0, left)) + 1:left]
return bool(re.search(role, selector, re.IGNORECASE) or re.search(r"(?<![\w-])(?:a|button|h[1-6])(?![\w-])", selector, re.IGNORECASE))
def middle_dot_hits(text, rx):
hits = []
previous = 0
for start, end, *_ in tags(text):
run = text[previous:start]
archive = re.fullmatch(r"\s*\d{4}\s*·\s*\w+\s*·\s*Archive\s*", run, re.IGNORECASE)
hit = rx.search(text, previous, start)
if hit and not archive:
hits.append(hit)
previous = end
return hits
def arrow_positions(text):
actions = []
hits = []
for start, end, name, attrs, closing in tags(text):
if name.lower() not in {"a", "button", "link"}:
continue
if not closing and not attrs.rstrip().endswith("/"):
actions.append((name, start, end))
elif closing and actions and actions[-1][0] == name:
_, action_start, body_start = actions.pop()
body = text[body_start:start]
pieces = []
previous = 0
for child_start, child_end, *_ in tags(body):
pieces.append(body[previous:child_start])
previous = child_end
pieces.append(body[previous:])
label = unescape("".join(pieces)).strip()
if label.endswith("→") and label[:-1].strip():
hits.append(action_start)
return hits
def scan(path, min_sev):
rules = compile_rules(min_sev)
findings = []
for fp in iter_files(path):
try:
with open(fp, "r", encoding="utf-8", errors="ignore") as fh:
lines = fh.readlines()
except OSError:
continue # unreadable file: skip, not fatal
if len(lines) == 1 and len(lines[0]) > 5000: # likely minified
continue
source, markup_source = source_views("".join(lines), os.path.splitext(fp)[1].lower() in {".css", ".scss", ".sass", ".less", ".js", ".jsx", ".ts", ".tsx", ".json"})
source_lines = source.splitlines(keepends=True)
markup_lines = markup_source.splitlines(keepends=True)
for r in rules:
ignored = {i for i, line in enumerate(lines) if "unslop-ignore" in line.lower()
or (r["suppress_rx"] and r["suppress_rx"].search(source_lines[i]))}
eligible = [blank(line) if i in ignored else line for i, line in enumerate(source_lines)]
text = "".join(eligible)
markup = "".join(blank(line) if i in ignored else line for i, line in enumerate(markup_lines))
matches = []
if r.get("min_signals") or r.get("min_count"):
target = text if r.get("min_signals") else markup
groups = [list(rx.finditer(target)) for rx in r["rx"]]
if r["id"] == "claude-default-look":
groups[2] = [m for m in groups[2] if accent_context(text, markup, m, r["rx"][2])]
if r.get("min_signals") and sum(bool(g) for g in groups) < r["min_signals"]:
continue
hits = sorted((m for g in groups for m in g), key=lambda m: m.start())
if r.get("markup_text"):
hits = middle_dot_hits(markup, r["rx"][0])
if r["id"] == "eyebrow-chrome":
hits = [m for m in hits if is_eyebrow(m)]
if r["id"] == "tinted-icon-tiles":
imports = re.findall(r"import\s*\{([^}]+)\}\s*from\s*[\"']lucide(?:-[a-z]+)*[\"']", text)
icons = {item.strip().split()[-1] for names in imports
for item in names.split(",") if item.strip()}
hits = [m for m in hits if is_icon_tile(m, icons)]
positions = arrow_positions(markup) if r["id"] == "appended-arrow" else [m.start() for m in hits]
if len(positions) < r.get("min_count", 1):
continue
matches = [text.count("\n", 0, min(positions)) + 1]
else:
for i, line in enumerate(eligible, 1):
if any(rx.search(line) for rx in r["rx"]):
matches.append(i)
if r.get("card"):
literals = [(m.start(), m.group()[1:-1]) for m in LITERAL.finditer(text)]
applies = [(m.start(), m.group(1)) for m in re.finditer(r"@apply\s+([^;{}]+)", text)]
for start, value in literals + applies:
classes = set(value.split())
count = bool(classes & {"rounded-lg", "rounded-xl"})
count += len(classes & {"border", "bg-card", "text-card-foreground", "shadow-sm"})
if count >= 4:
matches.append(text.count("\n", 0, start) + 1)
if r.get("config") and os.path.basename(fp) == "components.json":
try:
config = json.loads(text)
except ValueError:
config = None
if isinstance(config, dict):
theme = config.get("tailwind", config)
if (isinstance(theme, dict)
and theme.get("baseColor") in ("slate", "zinc", "neutral", "gray", "stone")
and theme.get("cssVariables", theme.get("cssVars")) is True):
m = re.search(r'"baseColor"\s*:', text)
matches.append(text.count("\n", 0, m.start() if m else 0) + 1)
for i in sorted(set(matches)):
findings.append({"rule": r["id"], "label": r["label"], "sev": r["sev"],
"fix": r["fix"], "file": fp, "line": i,
"snippet": lines[i - 1].strip()[:160]})
return findings
def verdict(by_sev, weighted):
# Severity mix decides, not the weighted total. The total let a pile of low findings
# read as STRONG with zero high ones, which is how the scanner lost its credibility.
high, med = by_sev.get("high", 0), by_sev.get("medium", 0)
if high >= 3 or (high >= 1 and med >= 5):
return "STRONG AI-default look"
if high >= 1 or med >= 3:
return "Some AI defaults present"
if weighted > 0:
return "Mostly clean, minor tells"
return "Clean, no tells detected"
def main():
ap = argparse.ArgumentParser(description="Scan a web codebase for vibe-coded design tells.")
ap.add_argument("path")
ap.add_argument("--severity", choices=["high", "medium", "low"], default="low",
help="minimum severity to report (default: low = everything)")
ap.add_argument("--json", action="store_true", help="machine-readable output")
ap.add_argument("--max", type=int, default=10, help="max examples shown per rule (text mode)")
args = ap.parse_args()
if not os.path.exists(args.path):
print(f"path not found: {args.path}", file=sys.stderr); sys.exit(2)
findings = scan(args.path, args.severity)
by_sev = {}
by_rule = {}
for f in findings:
by_sev[f["sev"]] = by_sev.get(f["sev"], 0) + 1
by_rule.setdefault(f["rule"], []).append(f)
weighted = sum(W[s] * n for s, n in by_sev.items())
files_scanned = sum(1 for _ in iter_files(args.path))
if args.json:
print(json.dumps({"path": args.path, "files_scanned": files_scanned,
"counts": by_sev, "vibe_score": weighted,
"verdict": verdict(by_sev, weighted), "findings": findings}, indent=2))
sys.exit(by_sev.get("high", 0))
sev_order = {"high": 0, "medium": 1, "low": 2}
rule_ids = sorted(by_rule, key=lambda rid: (sev_order[by_rule[rid][0]["sev"]], -len(by_rule[rid])))
print(f"\n unslop-ui scan: {args.path}")
print(f" files scanned: {files_scanned} findings: {len(findings)} vibe score: {weighted}")
print(f" verdict: {verdict(by_sev, weighted)}")
print(f" high: {by_sev.get('high',0)} medium: {by_sev.get('medium',0)} low: {by_sev.get('low',0)}\n")
if not findings:
print(" Nothing flagged. Either it is clean or the tells are layout/motion ones a regex"
"\n cannot see. Eyeball the hero layout and animations against references/tells.md.\n")
return
for rid in rule_ids:
items = by_rule[rid]
f0 = items[0]
tag = f0["sev"].upper()
print(f" [{tag}] {f0['label']} ({len(items)} hit{'s' if len(items)!=1 else ''})")
print(f" fix: {f0['fix']}")
for it in items[:args.max]:
print(f" {it['file']}:{it['line']} {it['snippet']}")
if len(items) > args.max:
print(f" ... +{len(items) - args.max} more")
print()
top = [by_rule[rid][0]['label'] for rid in rule_ids[:3]]
print(" Top things to change: " + "; ".join(top))
print(" Layout and motion tells need eyes too. See references/tells.md.\n")
sys.exit(by_sev.get("high", 0))
if __name__ == "__main__":
main()
skills/a-unslop-ui/tests/fixtures/clean/StationAccess.tsx667 B
import { MapPin, Accessibility } from "lucide-react";
export function StationAccess() {
return (
<section aria-labelledby="access-title">
<h2 id="access-title">Find the entrance</h2>
<div className="flex gap-3">
<span className="rounded-lg bg-primary/10"><MapPin aria-hidden="true" /></span>
<p>The main entrance faces Station Square.</p>
</div>
<div className="flex gap-3">
<span className="rounded-lg bg-primary/10"><Accessibility aria-hidden="true" /></span>
<p>Step-free access is beside the ticket office.</p>
</div>
<a href="/station-map">View station map →</a>
</section>
);
}
skills/a-unslop-ui/tests/fixtures/clean/base.css797 B
:root { color: #263643; font-family: "Source Sans 3", sans-serif; line-height: 1.5; }
body { background: #faf8f5; margin: 0; }
header, main { max-width: 64rem; margin-inline: auto; padding: 1.5rem; }
nav { display: flex; gap: 1rem; }
h1 { font-size: clamp(1.75rem, 4vw, 3rem); line-height: 1.1; }
a { color: #174d78; text-underline-offset: .2em; }
input, button { font: inherit; border: 1px solid #647789; border-radius: .25rem; padding: .5rem .75rem; }
button { color: white; background: #174d78; cursor: pointer; }
:focus-visible { outline: 3px solid #174d78; outline-offset: 3px; }
table { border-collapse: collapse; width: 100%; margin-block: 2rem; }
th, td { text-align: left; border-bottom: 1px solid #c8ced3; padding: .75rem; }
@media (max-width: 40rem) { header, main { padding: 1rem; } }
skills/a-unslop-ui/tests/fixtures/clean/station.html933 B
<!doctype html> <html lang="en"> <head><meta charset="utf-8"><title>Station departures</title><link rel="stylesheet" href="base.css"></head> <body> <header><a href="/">Rail desk</a><nav aria-label="Main"><a href="/departures">Departures</a><a href="/tickets">Tickets</a></nav></header> <main> <h1>Departures from Central</h1> <form action="/departures"><label for="destination">Destination</label><input id="destination" name="destination" autocomplete="off"><button type="submit">Find trains</button></form> <table><caption>Scheduled departures</caption><thead><tr><th scope="col">Time</th><th scope="col">Destination</th><th scope="col">Platform</th></tr></thead><tbody><tr><td><time>09:15</time></td><td>North station</td><td>2</td></tr></tbody></table> <section><h2>Before you travel</h2><p>Check the platform on the station board before boarding.</p><a href="/accessibility">Station access</a></section> </main> </body> </html>
skills/a-unslop-ui/tests/fixtures/dirty/Features.tsx310 B
import { Zap, Shield, BarChart3 } from "lucide-react";
export function Features() {
return <section>
<div className="rounded-lg bg-primary/10"><Zap /></div>
<div className="rounded-lg bg-primary/10"><Shield /></div>
<div className="rounded-lg bg-blue-500/10"><BarChart3 /></div>
</section>;
}
skills/a-unslop-ui/tests/fixtures/dirty/components.json100 B
{
"style": "new-york",
"tailwind": {
"baseColor": "neutral",
"cssVariables": true
}
}
skills/a-unslop-ui/tests/fixtures/dirty/landing.html854 B
<!doctype html> <html lang="en"> <head><meta charset="utf-8"><title>Starter</title></head> <body> <h1 class="bg-clip-text text-transparent from-purple-600 to-blue-500">Supercharge your workflow</h1> <button class="bg-indigo-600 rounded-full hover:scale-105">Get started</button> <div class="grid grid-cols-1 md:grid-cols-3"> <article class="shadow-sm p-6 bg-card border rounded-xl text-card-foreground"><h2>⚡ Fast</h2></article> </div> <img src="/undraw-workflow.svg" alt="Workflow illustration"> <p class="uppercase tracking-widest">Overview</p><h2>Plan</h2> <p class="uppercase tracking-widest">Overview</p><h2>Build</h2> <p class="uppercase tracking-widest">Overview</p><h2>Grow</h2> <p>Design · Tools · 2026</p> <p>Teams · Work · 2026</p> <a href="/plan">Plan →</a> <a href="/build">Build →</a> <a href="/grow">Grow →</a> </body> </html>
skills/a-unslop-ui/tests/fixtures/dirty/theme.css179 B
body { background: #F4F1EA; font-family: Inter, sans-serif; }
h1 { font-family: "Instrument Serif", serif; }
button { color: #D97757; }
.feature { box-shadow: 0 0 20px #00ffff; }
skills/a-unslop-ui/tests/test_devibe_scan.py29.7 KB
"""Regression tests for devibe_scan.
Every case here is a false positive that shipped, or the true positive its fix had to
keep. A scanner that reports black drop shadows as neon glow stops being run, so each
false positive here is pinned.
"""
import importlib.util
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
SCRIPT = Path(__file__).parents[1] / "scripts" / "devibe_scan.py"
SPEC = importlib.util.spec_from_file_location("devibe_scan", SCRIPT)
SCANNER = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(SCANNER)
class ScannerTests(unittest.TestCase):
def scan(self, text, name="sample.css"):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
path = Path(tmp) / name
path.write_text(text, encoding="utf-8")
return SCANNER.scan(str(path), "low")
def rules(self, text, name="sample.css"):
return sorted({f["rule"] for f in self.scan(text, name)})
# ---- neon-glow: the colour is what makes it a glow ----
def test_black_soft_shadow_is_not_neon_glow(self):
self.assertEqual([], self.rules(
".a{box-shadow: 0 0 10px rgba(0, 0, 0, .08)}\n"
".b{text-shadow: 0 0 50px rgba(0,0,0,.9)}\n"
".c{text-shadow: 0 0 20px #333}\n"
))
def test_inset_fill_is_not_neon_glow(self):
self.assertEqual([], self.rules(
".t{box-shadow: inset 0 0 0 9999px var(--bs-table-accent-bg)}\n"))
def test_saturated_glow_is_still_caught(self):
self.assertEqual(["neon-glow"], self.rules(
".g{box-shadow: 0 0 20px #00ffff}\n"
".h{text-shadow: 0 0 12px rgba(0,255,200,.8)}\n"))
def test_tailwind_arbitrary_glow_is_still_caught(self):
self.assertEqual(["neon-glow"], self.rules(
'<div class="shadow-[0_0_15px_rgba(139,92,246,0.5)]">x</div>\n', "a.html"))
# ---- ai-purple: someone else's brand is a fact, not a default ----
def test_platform_brand_purple_is_allowed(self):
self.assertEqual([], self.rules(
".brand-twitch { @apply text-violet-700; }\n"
".social-discord { @apply text-indigo-700; }\n"))
def test_purple_as_site_primary_is_still_caught(self):
self.assertEqual(["ai-purple"], self.rules(
'<button class="bg-indigo-600">Go</button>\n', "a.html"))
# ---- claude-default-look: amber status chrome is not a cream page ----
def test_amber_warning_badge_is_allowed(self):
self.assertEqual([], self.rules(
".status-pending { @apply bg-amber-100 text-amber-700; }\n"))
def test_cream_page_background_alone_is_allowed(self):
self.assertEqual([], self.rules("body{background:#faf6ef}\n"))
def test_instrument_serif_alone_is_allowed(self):
self.assertEqual([], self.rules("body{font-family:'Instrument Serif',serif}\n"))
# ---- comments describe tells, they do not commit them ----
def test_rule_written_in_a_comment_is_not_a_finding(self):
self.assertEqual([], self.rules(
"/*\n * No rounded-full anywhere. No bare rounded (4px).\n */\n"))
def test_same_text_as_real_css_is_a_finding(self):
self.assertEqual(["rounded-everything"], self.rules(".pill{border-radius:9999px}\n"))
# ---- escape hatch ----
def test_unslop_ignore_line_is_skipped(self):
self.assertEqual([], self.rules("body{background:#faf6ef} /* unslop-ignore */\n"))
# ---- scope: design comps and archives are not shipped UI ----
def test_docs_and_archive_directories_are_skipped(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
root = Path(tmp)
for sub in ("docs", "_archive", "mockups"):
(root / sub).mkdir()
(root / sub / "spec.css").write_text(".cta{background:#6366f1}", encoding="utf-8")
(root / "app.css").write_text(".cta{background:#6366f1}", encoding="utf-8")
findings = SCANNER.scan(str(root), "low")
self.assertEqual(1, len(findings), "only the shipped stylesheet should be scanned")
# ---- palette/type signals combine only within one file ----
def test_cream_and_serif_together_are_high(self):
findings = self.scan("body{background:#F4F1EA}\nh1{font-family:Fraunces}\n")
self.assertEqual([("claude-default-look", "high", 1)],
[(f["rule"], f["sev"], f["line"]) for f in findings])
def test_all_palette_signal_pairs_are_caught(self):
signals = ["body{background:#faf8f5}", "h1{font-family:'Instrument Serif'}",
'.cta{color:#D97757}']
for a, b in ((0, 1), (0, 2), (1, 2)):
with self.subTest(pair=(a, b)):
self.assertEqual(["claude-default-look"], self.rules(signals[a] + "\n" + signals[b]))
def test_supported_accent_swatches_and_utilities(self):
for accent in ("#D97757", "#C96442", "#CC785C", "#9caf88", "#264e36",
"bg-emerald-700", "text-green-900"):
with self.subTest(accent=accent):
self.assertEqual(["claude-default-look"], self.rules(
'h1{font-family:Fraunces}\n.cta{color:' + accent + '}'))
self.assertEqual([], self.rules('.cta{color:' + accent + '}'))
def test_green_and_clay_are_only_one_signal(self):
self.assertEqual([], self.rules('.cta{color:#d97757}\n.other{color:#264e36}'))
def test_status_colour_does_not_complete_cluster(self):
self.assertEqual([], self.rules(
"h1{font-family:Fraunces}\n.warning{background:#faf8f5}\n"))
def test_cream_text_colour_is_not_background_signal(self):
self.assertEqual([], self.rules("h1{font-family:Fraunces;color:#faf8f5}"))
def test_cluster_respects_comments_and_escape(self):
for ignored in ("/* body{background:#f4f1ea} */", "body{background:#f4f1ea} /* unslop-ignore */"):
with self.subTest(ignored=ignored):
self.assertEqual([], self.rules("h1{font-family:Fraunces}\n" + ignored))
def test_signals_do_not_combine_across_files(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
root = Path(tmp)
(root / "base.css").write_text("body{background:#f4f1ea}", encoding="utf-8")
(root / "type.css").write_text("h1{font-family:Fraunces}", encoding="utf-8")
self.assertEqual([], SCANNER.scan(str(root), "low"))
# ---- repeated template chrome ----
def test_three_direct_eyebrows_are_medium(self):
label = '<p class="tracking-widest uppercase">Overview</p>\n<h2>Routes</h2>\n'
findings = self.scan(label * 3, "page.html")
self.assertEqual([("eyebrow-chrome", "medium", 1)],
[(f["rule"], f["sev"], f["line"]) for f in findings])
def test_eyebrow_class_order_and_inline_letter_spacing(self):
for style in ('uppercase tracking-wide', 'tracking-wider uppercase',
'uppercase" style="letter-spacing: .1em'):
with self.subTest(style=style):
self.assertEqual(["eyebrow-chrome"], self.rules(
('<span class="' + style + '">Area</span><h3>Detail</h3>') * 3, "page.tsx"))
def test_inline_css_eyebrows_are_caught(self):
self.assertEqual(["eyebrow-chrome"], self.rules(
'<small style="text-transform:uppercase;letter-spacing:.1em">Area</small><h2>Routes</h2>' * 3,
"page.html"))
self.assertEqual([], self.rules(
'<small style="text-transform:lowercase;letter-spacing:.1em">Area</small><h2>Routes</h2>' * 3,
"page.html"))
def test_eyebrows_need_repetition_both_styles_and_adjacency(self):
for label in ('<p class="uppercase tracking-wide">Area</p><h2>Detail</h2>\n' * 2,
'<p class="uppercase">Area</p><h2>Detail</h2>\n' * 3,
'<p class="tracking-wide">Area</p><h2>Detail</h2>\n' * 3,
'<p class="uppercase tracking-wide">Area</p><hr/><h2>Detail</h2>\n' * 3,
'<p class="not-uppercase not-tracking-wide">Area</p><h2>Detail</h2>\n' * 3,
'<p data-label="uppercase tracking-wide">Area</p><h2>Detail</h2>\n' * 3):
with self.subTest(label=label):
self.assertEqual([], self.rules(label, "page.html"))
def test_two_middle_dot_meta_runs_are_low(self):
findings = self.scan('<p>London · Design · 2026</p>\n' * 2, "page.html")
self.assertEqual([("middle-dot-meta", "low")], [(f["rule"], f["sev"]) for f in findings])
def test_two_meta_strings_in_one_text_run_do_not_meet_threshold(self):
self.assertEqual([], self.rules(
'<p>London · Design · 2026 / Paris · Art · 2025</p>', "page.html"))
def test_middle_dot_needs_repetition_and_markup_text(self):
for text in ('<p>London · Design · 2026</p>',
'const tags = ["London · Design · 2026", "Paris · Art · 2025"];',
'<p data-meta="London · Design · 2026">Event</p>\n' * 2,
'<p>London · Design</p>\n' * 2,
'<script>const a="London · Design · 2026";const b="Paris · Art · 2025";</script>'):
with self.subTest(text=text):
self.assertEqual([], self.rules(text, "page.tsx"))
def test_three_appended_arrows_are_low(self):
for text in ('<a href="/routes">Routes →</a>', '<button>Open →</button>',
'<Link to="/routes">Routes →</Link>'):
with self.subTest(text=text):
findings = self.scan(text * 3, "page.tsx")
self.assertEqual([("appended-arrow", "low")], [(f["rule"], f["sev"]) for f in findings])
def test_arrows_need_repetition_and_action_suffix(self):
for text in ('<a>Open →</a>' * 2, '<p>A → B</p>' * 3, '<span>Open →</span>' * 3):
with self.subTest(text=text):
self.assertEqual([], self.rules(text, "page.html"))
def test_three_lucide_tiles_are_medium(self):
text = ('import { MapPin as Pin } from "lucide-react";\n' +
'<div className="bg-primary/10 rounded-lg"><Pin /></div>\n' * 3)
findings = self.scan(text, "page.tsx")
self.assertEqual([("tinted-icon-tiles", "medium", 2)],
[(f["rule"], f["sev"], f["line"]) for f in findings])
def test_icon_tiles_allow_reordered_classes_and_coloured_tint(self):
self.assertEqual(["tinted-icon-tiles"], self.rules(
'import { MapPin } from "lucide-react";\n' +
'<span className="rounded-lg p-3 bg-blue-500/10">\n<MapPin size={20} />\n</span>\n' * 3,
"page.tsx"))
def test_icon_tiles_need_three_tinted_rounded_lucide_wrappers(self):
prefix = 'import { MapPin } from "lucide-react";\n'
tile = '<div className="bg-primary/10 rounded-lg"><MapPin /></div>\n'
for text in (prefix + tile * 2, prefix + tile.replace(' rounded-lg', '') * 3,
prefix + tile.replace('bg-primary/10 ', '') * 3,
prefix + tile.replace('<MapPin />', 'Map') * 3,
prefix + tile.replace('<MapPin />', '<Weather />') * 3,
prefix + tile.replace('bg-primary/10', 'hover:bg-primary/10') * 3,
prefix + tile.replace('rounded-lg', 'hover:rounded-lg') * 3,
prefix + tile.replace('className=', 'data-label=') * 3, tile * 3):
with self.subTest(text=text):
self.assertEqual([], self.rules(text, "page.tsx"))
def test_repetition_ignores_comments_and_escaped_lines(self):
samples = [('<p class="uppercase tracking-wide">Area</p><h2>Routes</h2>', 3),
('<p>London · Design · 2026</p>', 2), ('<a>Open →</a>', 3),
('<div className="bg-primary/10 rounded-lg"><MapPin /></div>', 3)]
for sample, threshold in samples:
for ignored in ('<!-- ' + sample + ' -->', sample + ' /* unslop-ignore */'):
with self.subTest(sample=sample, ignored=ignored):
text = 'import { MapPin } from "lucide-react";\n' + (sample + '\n') * (threshold - 1) + ignored
self.assertEqual([], self.rules(text, "page.tsx"))
# ---- shadcn signatures and configuration discovery ----
def test_current_and_reordered_card_classes_are_caught(self):
for classes in ('flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm',
'shadow-sm text-card-foreground p-4 border rounded-lg',
'bg-card border shadow-sm text-card-foreground',
'rounded-xl border bg-card shadow-sm'):
with self.subTest(classes=classes):
self.assertEqual(["shadcn-default-card"], self.rules(
'<div className="' + classes + '">Content</div>', "card.tsx"))
def test_card_needs_four_distinct_exact_classes_in_one_literal(self):
for text in ('<div className="rounded-lg border bg-card">Content</div>',
'<div className="rounded-lg border border border">Content</div>',
'<div className="rounded-lg border"/><div className="bg-card shadow-sm"/>',
'<div className="hover:rounded-lg border-b bg-cardinal shadow-sm">Content</div>'):
with self.subTest(text=text):
self.assertEqual([], self.rules(text, "card.tsx"))
def test_card_class_literal_can_span_lines(self):
self.assertEqual(["shadcn-default-card"], self.rules(
'const card = `rounded-xl\n border\n bg-card\n shadow-sm`;', "card.tsx"))
def test_components_json_is_scanned_in_directories(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
root = Path(tmp)
config = '{"tailwind":{"baseColor":"zinc","cssVariables":true}}'
(root / "components.json").write_text(config, encoding="utf-8")
(root / "package.json").write_text(config, encoding="utf-8")
findings = SCANNER.scan(str(root), "low")
self.assertEqual(["components.json"], [Path(f["file"]).name for f in findings])
self.assertEqual(["shadcn-default-card"], [f["rule"] for f in findings])
self.assertEqual([str(root / "components.json")], list(SCANNER.iter_files(str(root))))
def test_default_config_colours_and_cssvars_alias(self):
for colour in ('slate', 'zinc', 'neutral', 'gray', 'stone'):
with self.subTest(colour=colour):
self.assertEqual(["shadcn-default-card"], self.rules(
'{"baseColor":"' + colour + '","cssVars":true}', "components.json"))
def test_custom_or_invalid_configs_are_allowed(self):
for config in ('{"tailwind":{"baseColor":"blue","cssVariables":true}}',
'{"baseColor":"zinc","cssVars":false}', '{"baseColor":"zinc"}',
'{"tailwind":null}', '[]', '{invalid json}'):
with self.subTest(config=config):
self.assertEqual([], self.rules(config, "components.json"))
def test_config_escape_suppresses_finding(self):
self.assertEqual([], self.rules(
'{"baseColor":"zinc","cssVars":true,"note":"unslop-ignore"}', "components.json"))
# ---- verifier round: paired positive and negative controls ----
def test_card_apply_and_nested_quotes_are_caught(self):
for text, name in (
('.card { @apply rounded-lg border bg-card text-card-foreground shadow-sm; }', "card.css"),
('<div className="rounded-lg border bg-card text-card-foreground shadow-sm after:content-[\'\']"/>', "card.tsx"),
('<div className="rounded-lg border bg-card shadow-sm after:content-[\'/*\']"/>', "card.tsx"),
):
with self.subTest(text=text):
self.assertEqual(["shadcn-default-card"], self.rules(text, name))
def test_card_apply_and_nested_quotes_still_need_four_groups(self):
for text, name in (
('.card { @apply rounded-lg border bg-card; }', "card.css"),
('.a { @apply rounded-lg border; } .b { @apply bg-card shadow-sm; }', "card.css"),
('<div className="rounded-lg border bg-card after:content-[\'shadow-sm\']"/>', "card.tsx"),
):
with self.subTest(text=text):
self.assertEqual([], self.rules(text, name))
def test_multiline_comments_cannot_contribute_to_any_rule(self):
for text, name in (
('/* archived:\nbody {background:#f4f1ea}\nh1 {font-family:Fraunces}\n--radius:0.5rem\n*/', "page.css"),
('<!-- archived:\n' + '<a>Open →</a>\n' * 3 + '--radius:0.5rem\n--primary:#6366f1\n-->', "page.html"),
('/* archived:\n' + '<a>Open →</a>\n' * 3 + '*/', "page.tsx"),
('// --radius:0.5rem\n// <a>Open →</a>\n' * 3, "page.js"),
('<div className={ /* --radius:0.5rem */ "plain" }/>', "page.tsx"),
):
with self.subTest(text=text):
self.assertEqual([], self.rules(text, name))
def test_comment_masking_preserves_live_code_and_line_numbers(self):
text = '/* --radius:0.5rem\nnot live */\n/* note */ .card { @apply rounded-lg border bg-card shadow-sm; }'
self.assertEqual([("shadcn-default-card", 3)],
[(f["rule"], f["line"]) for f in self.scan(text)])
for text in ('const url = "https://example.test/*path*/";\nconst card = "rounded-lg border bg-card shadow-sm";',
'<p>It\'s live</p><style>/* note */ :root{--radius:0.5rem}</style>'):
with self.subTest(text=text):
self.assertEqual(["shadcn-default-card"], self.rules(text, "page.tsx"))
def test_escaped_default_config_key_produces_valid_cli_json(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
path = Path(tmp) / "components.json"
path.write_text(r'{"tailwind":{"base\u0043olor":"zinc","cssVariables":true}}', encoding="utf-8")
result = subprocess.run([sys.executable, str(SCRIPT), str(path), "--json"], capture_output=True, text=True)
self.assertEqual(1, result.returncode)
self.assertEqual("", result.stderr)
data = json.loads(result.stdout)
self.assertEqual([("shadcn-default-card", 1)],
[(f["rule"], f["line"]) for f in data["findings"]])
def test_escaped_custom_config_and_nonscalar_values_are_clean(self):
for config in (r'{"tailwind":{"base\u0043olor":"blue","cssVariables":true}}',
r'{"tailwind":{"base\u0043olor":"zinc","cssVariables":false}}',
'{"baseColor":[],"cssVars":true}', '{"baseColor":{},"cssVars":true}'):
with self.subTest(config=config):
self.assertEqual([], self.rules(config, "components.json"))
def test_tooltip_examples_are_not_applied_eyebrow_styles(self):
for attrs in ('''title='Example: class="uppercase tracking-wide"' ''',
'''title='class="uppercase" style="letter-spacing:.1em"' ''',
'''data-example='className={cn("uppercase tracking-wide")}' '''):
with self.subTest(attrs=attrs):
self.assertEqual([], self.rules(('<p ' + attrs + '>CSS</p><h2>Classes</h2>') * 3, "page.html"))
def test_real_eyebrow_attributes_survive_quoted_tooltips(self):
text = '''<p title='Example: class="lowercase" >' class="uppercase tracking-wide">CSS</p><h2>Classes</h2>'''
self.assertEqual(["eyebrow-chrome"], self.rules(text * 3, "page.html"))
def test_static_react_letter_spacing_and_jsx_comments_are_caught(self):
for spacing in ('".1em"', "'.1em'", "2"):
with self.subTest(spacing=spacing):
text = '<p className="uppercase" style={{letterSpacing:' + spacing + '}}>Area</p>{/* note\n continued */}<h2>Routes</h2>\n'
self.assertEqual(["eyebrow-chrome"], self.rules(text * 3, "page.tsx"))
def test_react_eyebrows_need_applied_static_spacing_and_adjacency(self):
for text in ('<p className="uppercase" data-style={{letterSpacing:".1em"}}>Area</p><h2>Routes</h2>',
'<p className="uppercase" style={{letterSpacing:spacing}}>Area</p><h2>Routes</h2>',
'<p className="uppercase" style={{letterSpacing:".1em"}}>Area</p>{divider}<h2>Routes</h2>'):
with self.subTest(text=text):
self.assertEqual([], self.rules(text * 3, "page.tsx"))
def test_static_cn_and_clsx_icon_tiles_are_caught(self):
for expression in ('cn("bg-primary/10 rounded-lg")',
'clsx("rounded-lg", "bg-primary/10",)',
"cn('bg-blue-500/10', 'rounded-lg')"):
with self.subTest(expression=expression):
text = 'import { MapPin as Pin } from "lucide-react";\n' + ('<div className={' + expression + '}><Pin /></div>\n') * 3
self.assertEqual(["tinted-icon-tiles"], self.rules(text, "page.tsx"))
def test_cn_icon_tiles_still_need_static_applied_tint_and_lucide(self):
for attrs, icon in (('className={cn("rounded-lg")}', 'MapPin'),
('data-class={clsx("rounded-lg bg-primary/10")}', 'MapPin'),
('className={cn(flag && "rounded-lg bg-primary/10")}', 'MapPin'),
('className={clsx("rounded-lg bg-primary/10")}', 'Weather')):
with self.subTest(attrs=attrs, icon=icon):
text = 'import { MapPin } from "lucide-react";\n' + ('<div ' + attrs + '><' + icon + ' /></div>\n') * 3
self.assertEqual([], self.rules(text, "page.tsx"))
def test_javascript_and_jsx_escaped_markup_do_not_count_as_metadata(self):
for text, name in (
('const examples = ["<p>A · B · C</p>", "<p>D · E · F</p>"];', "page.js"),
('const example = `<p>A · B · C</p>\n<p>D · E · F</p>`;', "page.tsx"),
('<pre>{"<p>A · B · C</p><p>D · E · F</p>"}</pre>', "page.tsx"),
('<p title="<p>A · B · C</p><p>D · E · F</p>">Example</p>', "page.html"),
('<script>const examples=["<p>A · B · C</p>","<p>D · E · F</p>"];</script>', "page.html"),
):
with self.subTest(text=text):
self.assertEqual([], self.rules(text, name))
def test_real_jsx_metadata_after_code_examples_is_caught(self):
text = 'const example = "<p>A · B · C</p>";\nexport const Page = () => <><p>London · Design · 2026</p>\n<p>Paris · Art · 2025</p></>;'
self.assertEqual([("middle-dot-meta", 2)], [(f["rule"], f["line"]) for f in self.scan(text, "page.tsx")])
def test_calendar_archive_metadata_is_not_template_chrome(self):
self.assertEqual([], self.rules('<li>2026 · September · Archive</li>\n<li>2026 · October · Archive</li>', "page.html"))
def test_nonarchive_metadata_triplets_still_count(self):
self.assertEqual(["middle-dot-meta"], self.rules('<li>2026 · London · Design</li>\n<li>2025 · Paris · Art</li>', "page.html"))
def test_rendered_static_arrow_suffixes_are_caught(self):
for suffix in ('→', '{"→"}', "{'→'}", '<span aria-hidden="true">→</span>',
'<span class="sr-only">→</span>'):
for tag in ("a", "button", "Link"):
with self.subTest(suffix=suffix, tag=tag):
text = '<' + tag + '>Open ' + suffix + '</' + tag + '>\n'
self.assertEqual(["appended-arrow"], self.rules(text * 3, "page.tsx"))
def test_arrows_in_strings_prefixes_attributes_and_midtext_are_clean(self):
for text in ('const states = ["Queued →", "Running →", "Completed →"];',
'const example = "<a>Open →</a>";' * 3,
'<a>→ Open</a>' * 3, '<button>→ Open</button>' * 3,
'<a>Open → more</a>' * 3, '<button title="Open →">Open</button>' * 3,
'<a>Open →{count}</a>' * 3, '<span>Open {"→"}</span>' * 3):
with self.subTest(text=text):
self.assertEqual([], self.rules(text, "page.tsx"))
def test_small_green_status_pills_cannot_complete_palette_cluster(self):
for classes in ('bg-emerald-100 text-emerald-700', 'text-green-700 bg-green-100',
'rounded-full text-xs text-emerald-800', 'text-green-900 text-xs rounded-full'):
with self.subTest(classes=classes):
text = '<style>h1{font-family:Fraunces}</style>\n<span class="' + classes + '">Published</span>'
self.assertNotIn("claude-default-look", self.rules(text, "page.html"))
def test_primary_green_and_clay_accents_complete_palette_cluster(self):
for accent in ('<button class="bg-emerald-700">Go</button>', '<a class="text-green-800">Read</a>',
'<h1 class="text-emerald-900">Title</h1>', '<div class="btn-primary bg-green-700">Go</div>',
'<div class="CTA bg-green-700">Go</div>',
'<style>:root{--primary:#264e36}</style>', '<style>:root{--accent:#d97757}</style>',
'<style>:root{--brand-color:#9caf88}</style>', '<style>.btn-primary{@apply bg-emerald-700;}</style>'):
with self.subTest(accent=accent):
self.assertIn("claude-default-look", self.rules('<style>h1{font-family:Fraunces}</style>\n' + accent, "page.html"))
def test_green_in_unrelated_elements_is_not_a_brand_signal(self):
for accent in ('<div class="text-emerald-700">Count</div>', '<span class="text-green-900">Published</span>',
'<p class="bg-green-700">Aside</p>', '<style>.chart{color:#264e36}</style>'):
with self.subTest(accent=accent):
self.assertEqual([], self.rules('<style>h1{font-family:Fraunces}</style>\n' + accent, "page.html"))
def test_demo_fixture_and_storybook_trees_are_skipped(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
root = Path(tmp)
for sub in ("_demo", "demo", "demos", "fixtures", "storybook-static"):
(root / sub / "nested").mkdir(parents=True)
(root / sub / "nested" / "theme.css").write_text(':root{--radius:0.5rem}', encoding="utf-8")
self.assertEqual([], list(SCANNER.iter_files(str(root))))
self.assertEqual([], SCANNER.scan(str(root), "low"))
def test_shipped_ui_and_explicit_demo_paths_are_still_scanned(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
root = Path(tmp)
for sub in ("src", "demo"):
(root / sub).mkdir()
(root / sub / "theme.css").write_text(':root{--radius:0.5rem}', encoding="utf-8")
self.assertEqual([str(root / "src" / "theme.css")], [f["file"] for f in SCANNER.scan(str(root), "low")])
self.assertEqual(["shadcn-default-card"], [f["rule"] for f in SCANNER.scan(str(root / "demo"), "low")])
# ---- fixtures: explicit paths exercise directories skipped in normal scans ----
def test_clean_fixtures_have_zero_findings(self):
root = Path(__file__).parent / "fixtures" / "clean"
self.assertTrue(2 <= len(list(SCANNER.iter_files(str(root)))) <= 4)
self.assertEqual([], SCANNER.scan(str(root), "low"))
def test_every_rule_fires_on_dirty_fixtures(self):
root = Path(__file__).parent / "fixtures" / "dirty"
found = {f["rule"] for f in SCANNER.scan(str(root), "low")}
self.assertEqual({r["id"] for r in SCANNER.RULES}, found)
def test_fixtures_stay_excluded_from_skill_scan(self):
paths = list(SCANNER.iter_files(str(Path(__file__).parents[1])))
self.assertFalse(any("fixtures" in Path(p).parts for p in paths))
def test_cli_json_shape_severity_and_high_exit_count(self):
root = Path(__file__).parent / "fixtures" / "dirty"
for severity in ("low", "high"):
with self.subTest(severity=severity):
result = subprocess.run([sys.executable, str(SCRIPT), str(root), "--json",
"--severity", severity, "--max", "1"],
capture_output=True, text=True)
data = json.loads(result.stdout)
self.assertEqual({"path", "files_scanned", "counts", "vibe_score", "verdict", "findings"}, set(data))
self.assertEqual(data["counts"]["high"], result.returncode)
for finding in data["findings"]:
self.assertEqual({"rule", "label", "sev", "fix", "file", "line", "snippet"}, set(finding))
if severity == "high":
self.assertEqual({"high"}, {f["sev"] for f in data["findings"]})
else:
self.assertEqual({"high", "medium", "low"}, {f["sev"] for f in data["findings"]})
def test_cli_clean_and_missing_path_exit_codes(self):
root = Path(__file__).parent / "fixtures" / "clean"
clean = subprocess.run([sys.executable, str(SCRIPT), str(root), "--max", "1"],
capture_output=True, text=True)
self.assertEqual(0, clean.returncode)
self.assertIn("Clean, no tells detected", clean.stdout)
missing = subprocess.run([sys.executable, str(SCRIPT), str(root / "absent.css")],
capture_output=True, text=True)
self.assertEqual(2, missing.returncode)
self.assertIn("path not found", missing.stderr)
# ---- verdict: low-severity noise must not read as STRONG ----
def test_many_low_findings_never_reach_strong(self):
self.assertEqual("Mostly clean, minor tells",
SCANNER.verdict({"low": 40}, 40))
def test_three_highs_reach_strong(self):
self.assertEqual("STRONG AI-default look", SCANNER.verdict({"high": 3}, 9))
def test_clean_is_clean(self):
self.assertEqual("Clean, no tells detected", SCANNER.verdict({}, 0))
if __name__ == "__main__":
unittest.main()