diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 000000000..ee6399ad4 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,3 @@ +{ + "env": { "HUMANIZER_HOOK": "off" } +} diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 3c5e8be5b..f82e5868a 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -21,6 +21,8 @@ jobs: python-version: "3.12" - name: Check package files run: python3 scripts/validate-package.py + - name: Test scorer and hooks + run: python3 -m unittest discover -s tests - name: Check skill discovery run: npx --yes skills@1.5.20 add . --list - name: Check Claude marketplace diff --git a/AGENTS.md b/AGENTS.md index 11878e4d2..777cd3207 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,6 +18,11 @@ Keep the skill portable. Do not write instructions that limit it to one or two a - `.cursor-plugin/plugin.json` describes the Cursor plugin. Omit a `skills` path so Cursor loads the root `SKILL.md`. - `package.json` makes the repo a pi package. Its `pi.skills` entry points at the repo root so pi loads the root `SKILL.md`. Do not add a `version` field; pi installs from git. - `agents/openai.yaml` holds the display name, short description, and default prompt for OpenAI-compatible agents. +- `hooks/hooks.json` holds the Claude plugin hooks. Claude Code loads it from the plugin root, so do not also list it in `plugin.json`. It runs `scripts/humanizer-hook.py` on `SessionStart`, `UserPromptSubmit`, `PreToolUse` (`Write|Edit|MultiEdit`), and `Stop`. +- `scripts/humanizer-hook.py` routes each hook event. It adds the rules to context, blocks prose writes and final replies that the scorer flags (exit code 2), and carries thinking findings to the next prompt. +- `scripts/humanizer-lint.py` scores text with a weighted linear model over the `SKILL.md` patterns, in the style of `ste-lint`. Use only the Python standard library. Mark a feature `hard` only for a tell that justifies an edit on one sighting. If you renumber a pattern, update the `§` labels; the validator checks them. +- `tests/test_hooks.py` and `tests/fixtures.json` test the scorer and every hook event. A new feature must keep the human fixtures unflagged. +- `.claude/settings.json` turns the hooks off in this repo, because `SKILL.md` lists every tell. - `scripts/validate-package.py` checks package files and shared values. ## Rules for changes @@ -30,7 +35,7 @@ Keep `SKILL.md` and `README.md` in sync. - **Description:** The plugin manifests use the first sentence of the `SKILL.md` description. - **Length:** Every word of `SKILL.md` is read on each use. The validator caps it at 5,500 words; a change that adds words should earn them. - **History:** Add a short `CHANGELOG.md` note for any behavior change or non-obvious fix. -- **Checks:** Before publishing, run `python3 scripts/validate-package.py`, `npx skills add . --list`, and `claude plugin validate .`. +- **Checks:** Before publishing, run `python3 scripts/validate-package.py`, `python3 -m unittest discover -s tests`, `npx skills add . --list`, and `claude plugin validate .`. ## Writing style diff --git a/CHANGELOG.md b/CHANGELOG.md index 776474ad6..0669db234 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- Reordered `README.md` so Usage follows Installation and the hook settings come after it. The intro now names both parts: the rewrite skill and the Claude Code hooks that the plugin enables in Claude Code settings. +- The scorer no longer counts a one-line lead-in that ends in a colon as a closer paragraph. + +- Restructured `README.md` to the RWS application profile: added Status, Requirements, Configuration, Testing, and Support sections, an install check with `/hooks`, and the scorer sources. Corrected the hook scoring notes (20-word floor; §12 words are weighted, not one-sighting). + +- Replaced both README "After" examples with fresh rewrites of the same "Before" text, made with the hooks on and checked for dropped or changed facts. The blind-test note now says it tested an earlier rewrite. + +- The Claude Code plugin now enforces Humanizer with hooks, on prose files, chat replies, and thinking. `PreToolUse` blocks prose writes that the scorer flags. `Stop` sends a flagged reply back for a rewrite. `SessionStart` and `UserPromptSubmit` add the rules to context and report tells found in the last turn's thinking. Set `HUMANIZER_HOOK=off` to turn them off. +- Added `scripts/humanizer-lint.py`, a weighted linear scorer over the `SKILL.md` patterns, modeled on `ste-lint`. Stock-word weights follow published frequency ratios (Kobak et al. 2025; Reinhart et al. 2025); passive voice and type-token ratio are left out because they do not point reliably at AI text (El Attar et al. 2026). One-sighting tells flag a text alone; weaker lexical and structural signals flag it together. Added `tests/` with fixtures for the scorer and each hook event. + - Tightened `SKILL.md` and `README.md` for clarity, concision, and readability. Reworded four "After" examples (§6, §13, §15, §25) so they read naturally and avoid stock academic phrasing. - Added "the part" as a stand-in to §4: "the hard part is X" stages X, and "the part that doesn't" or "the part worth sharing" points at something the text never names (#338). - `scripts/validate-package.py` now fails when a pattern number appears twice in `SKILL.md` or in the README tables. Before, the second one replaced the first and the check passed (#340). diff --git a/README.md b/README.md index 86dc45f76..9c6234a20 100644 --- a/README.md +++ b/README.md @@ -4,21 +4,32 @@ sponsored by [cfo.ai](https://cfo.ai/?utm_source=github&utm_medium=sponsorship&u [![GitHub stars](https://img.shields.io/github/stars/blader/humanizer?style=flat)](https://github.com/blader/humanizer/stargazers) [![skills.sh installs](https://skills.sh/b/blader/humanizer)](https://skills.sh/blader/humanizer) -Humanizer makes AI-written text sound like a person wrote it, without changing what it says. It is built on Wikipedia's [Signs of AI writing](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing), the guide Wikipedia editors use to catch AI-generated text, and it works in Claude Code, Codex, and any other agent that supports skills. +Humanizer makes AI-written text sound like a person wrote it, without changing what it says. It has two parts: + +- A skill that rewrites text when you ask. Run `/humanizer` in Claude Code, Codex, or any other agent that supports skills. +- Hooks that come with the Claude Code plugin. Installing the plugin enables them in your Claude Code settings. From then on, Claude Code checks everything Claude writes, in every session and project: prose files, chat replies, and thinking. Text with AI tells goes back to Claude for a rewrite. You can turn the hooks off in [Configuration](#configuration). + +The patterns come from Wikipedia's [Signs of AI writing](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing), the guide Wikipedia editors use to catch AI-generated text. + +Here is a product announcement before and after a rewrite: **Before:** > I'm thrilled to announce that shared drafts are finally here! 🚀 For months, our own team was drowning in files named final_v7.docx — and we knew there had to be a better way. Now two people can edit the same doc at once, with every change appearing live for both of them. It's not just a feature; it's a whole new way to collaborate. Comments stay anchored to the exact sentence they reference, even as the text around them evolves. And the best part? It's available today on every plan, completely free. Let that sink in. **After:** -> Shared drafts are out today. For months our own team passed around files named final_v7.docx, and we got sick of it. Now two people can edit the same doc at once and see each other's changes as they type. Comments stay attached to the sentence they're about, even when the text around it changes. It's free on every plan. +> Shared drafts are here. For months, our own team kept losing track of files named final_v7.docx, and we wanted a better way to work on one document together. Now two people can edit the same doc at once, and each of them sees the other's changes as they happen. Comments stay attached to the sentence they refer to, even when the text around that sentence changes. Shared drafts are available today and free on every plan. -In a blind test, judges preferred Humanizer's rewrite over the original AI text 16 times out of 16 ([#229](https://github.com/blader/humanizer/issues/229)). +In a blind test of an earlier rewrite of this text, judges preferred Humanizer's version 16 times out of 16 ([#229](https://github.com/blader/humanizer/issues/229)). + +## Status + +Humanizer is active. The current release is 4.0.0, and [CHANGELOG.md](CHANGELOG.md) lists the changes made since. Humanizer edits for human readers. It does not try to get past AI detectors, and detectors still flag most of its output. ## The five strongest tells -These are the most common signs of AI writing, and Humanizer rewrites any of them on sight: +These are the most common signs of AI writing. Humanizer rewrites any of them on sight: 1. **Not X but Y:** "It's not just a feature, it's a shift." 2. **One-line closers:** "Let that sink in." @@ -26,11 +37,18 @@ These are the most common signs of AI writing, and Humanizer rewrites any of the 4. **A staged run-up:** "Here's the thing." "Honestly?" "The hard part is..." 5. **Arguing with no one:** "I'm not saying X, but..." -Humanizer checks for [26 patterns](#the-26-patterns) in all. +They are the first five of the [26 patterns](#the-26-patterns) Humanizer checks. + +## Requirements + +You need an agent that supports skills, such as Claude Code, Codex, pi, or Claude.ai. Some install paths need more: + +- The Claude Code plugin needs Claude Code 2.1.142 or newer. Its hooks need `python3` on your `PATH`; without it, they let text through unchecked. +- The `npx skills` installs need Node.js with `npx`. ## Installation -Once installed, run it with `/humanizer`. +Pick the section for your agent. After you install, run the skill with `/humanizer`. ### Claude Code @@ -39,7 +57,9 @@ Once installed, run it with `/humanizer`. /plugin install humanizer@humanizer ``` -The plugin requires Claude Code 2.1.142 or newer; on older versions, run `npx skills add blader/humanizer --global --agent claude-code`. +The plugin installs the skill and the hooks described in [Configuration](#configuration). To check that the hooks loaded, start a new session and run `/hooks`. You should see `SessionStart`, `UserPromptSubmit`, `PreToolUse`, and `Stop` entries that run `scripts/humanizer-hook.py`. + +On Claude Code older than 2.1.142, run `npx skills add blader/humanizer --global --agent claude-code` instead. That command installs the skill without the hooks. ### Codex @@ -65,37 +85,37 @@ Download this repository as a ZIP (**Code → Download ZIP**) and upload it as a npx skills add blader/humanizer --global --agent '*' ``` -This installs Humanizer for every agent the Skills CLI supports, including Gemini CLI, GitHub Copilot, and Windsurf. Omit `--global` in any command above to install it only in the current project. For an agent the Skills CLI does not cover, copy `SKILL.md` into its skill folder. +This command installs Humanizer for every agent the Skills CLI supports, including Gemini CLI, GitHub Copilot, and Windsurf. To install for the current project only, leave out `--global` in any `npx skills` command above. For an agent the Skills CLI does not cover, copy `SKILL.md` into its skill folder. ## Usage -Call the skill directly: +Call the skill and paste your text: -``` +```text /humanizer [paste your text here] ``` -Or ask in plain language: +You can also ask in plain language: -``` +```text Please humanize this text: [your text] ``` -To rewrite a file, pass its path: +To rewrite a file, give its path: -``` +```text Humanize the prose in docs/launch-post.md ``` -Humanizer reads the current file in full before editing, including files it wrote earlier in the session. Its summary states how many sections it reviewed and names any it could not cover. +Humanizer reads the whole file before it edits, even a file it wrote earlier in the session. Its summary says how many sections it reviewed and names any it could not cover. ### Match your voice -To make the rewrite sound like you, include a writing sample: +To make the rewrite sound like you, add a sample of your own writing: -``` +```text /humanizer Here's a sample of my writing for voice matching: @@ -105,22 +125,71 @@ Now humanize this text: [paste AI text to humanize] ``` -Humanizer follows the sample's rhythm, word choice, punctuation, and deliberate quirks, including dashes if you use them. +Humanizer then follows the sample's rhythm, word choice, punctuation, and quirks, including dashes if you use them. + +## Configuration + +The skill itself has no settings. The Claude Code plugin adds hooks that apply Humanizer even when the agent does not call the skill. The `npx skills` and ZIP installs do not include them. + +Each hook covers one kind of text: + +| Text | Hook | What happens | +| --- | --- | --- | +| Prose files (`.md`, `.mdx`, `.markdown`, `.txt`, `.rst`, `.adoc`) | `PreToolUse` on `Write`, `Edit`, `MultiEdit` | Claude Code blocks a write with AI tells until Claude rewrites it. | +| Chat replies | `Stop` | The hook sends a reply with AI tells back, and Claude posts a rewritten reply. You see both. | +| Thinking | `SessionStart`, `UserPromptSubmit`, `Stop` | The hooks add the rules to Claude's context each session and each prompt. They report tells in stored thinking at the next prompt. | + +Hooks can steer thinking, but they cannot rewrite it. Claude Code also often stores thinking without its text, and then the `Stop` hook has nothing to check. + +### Scoring + +The hooks decide with [`scripts/humanizer-lint.py`](scripts/humanizer-lint.py), which scores text from 0 to 1. It treats each tell from `SKILL.md` as a weighted feature, like a small linear model: + +- One-sighting tells flag the text alone: §1 to §5, §8 dashes, §22 chatbot residue, and §23 disclaimers. +- Weaker signals flag the text only together. Examples are stock AI words such as "delve", triads, bold labels, and flat sentence rhythm. +- Texts under 20 words are flagged only for one-sighting tells. +- The scorer skips code, URLs, blockquotes, and quoted phrases, so text that discusses a pattern passes. + +You can run the scorer yourself on a file, or pipe text to it for a JSON report: + +```bash +python3 scripts/humanizer-lint.py docs/launch-post.md +``` + +### Turn the hooks off + +Set `HUMANIZER_HOOK` to `off`. To do that for one project, add it to the project's `.claude/settings.json`: + +```json +{ "env": { "HUMANIZER_HOOK": "off" } } +``` + +This repository does that for itself, because `SKILL.md` lists every tell and would trip the hooks. ## How it works -A language model writes whatever is most likely to come next, so by default it makes the choice that fits the widest range of readers and subjects. A person chooses for one reader and one subject. Every tell Humanizer looks for is a form of that default choice: a sentence that signals importance instead of adding a fact, rhythm or formatting applied by rule, an ordinary fact dressed as a pivotal one, text left over from the chat, or a reply that re-explains what the reader already knows. +A language model writes whatever is most likely to come next. Its default is the choice that fits the widest range of readers and subjects. A person chooses for one reader and one subject instead. + +Every tell Humanizer looks for is one form of that default: + +- A sentence that signals importance instead of adding a fact. +- Rhythm or formatting applied by rule. +- An ordinary fact dressed as a pivotal one. +- Text left over from the chat. +- A reply that re-explains what the reader already knows. > "LLMs use statistical algorithms to guess what should come next. The result tends toward the most statistically likely result that applies to the widest variety of cases." > Wikipedia, ["Signs of AI writing"](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing) -Humanizer marks every tell it finds, strongest first. It drafts a rewrite, merging, splitting, or reordering sentences and paragraphs as needed, then checks the draft against the patterns and the original claims before writing the final version. Where the text is generic, it adds a specific detail it knows to be true, and it keeps every claim the original made. +To rewrite, Humanizer first marks every tell it finds, strongest first. It drafts a new version, merging, splitting, or reordering sentences as needed, and checks it against the patterns and the original claims. Only then does it write the final version. Where the text is generic, it adds a specific detail it knows to be true, and it keeps every claim the original made. -When you paste text, Humanizer shows its work: the first rewrite, a short list of tells that survived it, and the final version. Point it at a file and it edits only the prose, leaving code, data, frontmatter, and link targets alone. Personal writing keeps the writer's opinions and quirks; technical and reference prose stays neutral and plain. Informal human text, such as chat messages, rants, and angry reviews, is left alone unless two unrelated tells appear together, and Humanizer keeps the writer's anger at full strength. +With pasted text, you see the first rewrite, a short list of tells that survived it, and the final version. With a file, Humanizer edits only the prose and leaves code, data, frontmatter, and link targets alone. + +Humanizer also adjusts to the kind of writing. Personal writing keeps the writer's opinions and quirks, and technical prose stays neutral and plain. Informal human text, such as chat messages and angry reviews, stays as it is unless two unrelated tells appear together. Even then, the writer's anger keeps its full strength. ## The 26 patterns -Humanizer numbers the patterns from strongest and most common to weakest. It edits any of the first five on one sighting, and acts on a pattern marked *weak alone* only when other tells appear in the same passage, because a careful writer may use any one of them on purpose. +Humanizer numbers the patterns from strongest and most common to weakest. It edits any of the first five on one sighting. It acts on a pattern marked *weak alone* only when other tells appear in the same passage. A careful writer may use any one of them on purpose. ### A. Staging instead of stating @@ -194,21 +263,45 @@ Humanizer numbers the patterns from strongest and most common to weakest. It edi > Would I go back? Absolutely — next time in spring, and with better shoes! Lisbon isn't just a place to visit; it's a place to fall in love with, again and again. ✨ **After:** -> I spent five days in Lisbon last October. My hotel was up in Alfama, with a lot of stairs between it and everything else. My legs felt every one of them, but the views from the top made up for it. +> I spent five days in Lisbon last October and loved it. My hotel was high up in the Alfama district, and I liked the place from the day I checked in. +> +> The hills are hard work. There were a lot of stairs between my hotel and everything else, and my legs felt every one of them. The views from the top make up for it, though, and you get one after almost every climb. > -> Everyone tells you to ride Tram 28, so I did. It took about forty minutes, and most of the car was other tourists taking pictures out the windows. +> I rode Tram 28, which takes about forty minutes and was full of other tourists holding up their phones. The food was excellent. Everyone goes to Pastéis de Belém for pastéis de nata, and theirs are good, but my favorite came from a place in Graça, still warm from the oven. > -> The custard tarts at Pastéis de Belém are the famous ones. The best one I had came from a place in Graça, still warm from the oven. +> What I liked most was how quickly the city calms down. Walk a block or two uphill from the main squares and the crowds thin out and the streets go quiet, so you can take your time. > -> The part of Lisbon I liked most starts a block or two above the main squares, where the streets go quiet and nobody is in a hurry. São Jorge Castle has good views over the rooftops and a long queue to get them. +> I also went to São Jorge Castle, which has a great view over the rooftops. The line was long, but if you like history, it's worth the wait. > -> I'd go back, in spring next time, and with better shoes. +> I'd go back. Next time I'll go in spring, and I'll bring better shoes. + +## Testing + +Before you publish a change, run the package checks: + +```bash +python3 scripts/validate-package.py +python3 -m unittest discover -s tests +npx skills add . --list +claude plugin validate . +``` + +A passing run prints `Humanizer package v4.0.0 is valid` from the validator and `OK` from the tests. [AGENTS.md](AGENTS.md) lists the rules a change must follow. + +## Support + +- Report a missed tell with the **New tell** issue form. +- Report a rewrite that kept a tell, changed the meaning, or over-edited with the **Rewrite problem** issue form. +- Ask questions in [Discussions](https://github.com/blader/humanizer/discussions). + +Open both forms from [Issues](https://github.com/blader/humanizer/issues/new/choose). ## Sources - [Wikipedia: Signs of AI writing](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing) is the source for the pattern list. - [WikiProject AI Cleanup](https://en.wikipedia.org/wiki/Wikipedia:WikiProject_AI_Cleanup) maintains the page. - El Attar, Dönmez, Maurer, and Falenska, ["A Systematic Analysis of Linguistic Features in AI-Generated English Text Detection Across Domains and Models"](https://arxiv.org/abs/2606.04177) (2026) is the source for the caution that most signals change with the model and the text type. +- Kobak et al., ["Delving into LLM-assisted writing in biomedical publications through excess vocabulary"](https://arxiv.org/abs/2406.07016) (2025), and Reinhart et al., ["Do LLMs write like humans?"](https://arxiv.org/abs/2410.16107) (2025), are the sources for the scorer's word weights. ## Version history @@ -216,6 +309,6 @@ See [CHANGELOG.md](CHANGELOG.md). ## License -MIT +Humanizer is released under the [MIT License](LICENSE). If Humanizer helps you, a star helps other people find it. diff --git a/hooks/hooks.json b/hooks/hooks.json new file mode 100644 index 000000000..67fd129f7 --- /dev/null +++ b/hooks/hooks.json @@ -0,0 +1,50 @@ +{ + "description": "Enforce Humanizer on prose files, final replies, and thinking.", + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "python3 \"${CLAUDE_PLUGIN_ROOT}/scripts/humanizer-hook.py\"", + "timeout": 10 + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "python3 \"${CLAUDE_PLUGIN_ROOT}/scripts/humanizer-hook.py\"", + "timeout": 10 + } + ] + } + ], + "PreToolUse": [ + { + "matcher": "Write|Edit|MultiEdit", + "hooks": [ + { + "type": "command", + "command": "python3 \"${CLAUDE_PLUGIN_ROOT}/scripts/humanizer-hook.py\"", + "timeout": 10 + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "python3 \"${CLAUDE_PLUGIN_ROOT}/scripts/humanizer-hook.py\"", + "timeout": 10 + } + ] + } + ] + } +} diff --git a/scripts/__pycache__/humanizer-lint.cpython-314.pyc b/scripts/__pycache__/humanizer-lint.cpython-314.pyc new file mode 100644 index 000000000..adef51acc Binary files /dev/null and b/scripts/__pycache__/humanizer-lint.cpython-314.pyc differ diff --git a/scripts/humanizer-hook.py b/scripts/humanizer-hook.py new file mode 100755 index 000000000..a300303b4 --- /dev/null +++ b/scripts/humanizer-hook.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Enforce Humanizer in Claude Code through plugin hooks. + +hooks/hooks.json runs this script on four events. It reads the event as JSON +on stdin and scores text with humanizer-lint.py. + +- SessionStart, UserPromptSubmit: add the writing rules to the agent's + context, so replies and thinking follow them from the start. Also report + tells found in the previous turn's thinking, which cannot be rewritten. +- PreToolUse (Write, Edit, MultiEdit): score the text about to be written to + a prose file. Exit code 2 blocks the write until the agent rewrites it. +- Stop: score the agent's final reply. Exit code 2 makes the agent send a + rewritten reply. Score its thinking too and save the findings for the + next prompt. + +Set HUMANIZER_HOOK=off to turn every hook off. +""" + +from __future__ import annotations + +import importlib.util +import json +import os +import re +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +_spec = importlib.util.spec_from_file_location("humanizer_lint", HERE / "humanizer-lint.py") +lint_module = importlib.util.module_from_spec(_spec) +sys.modules["humanizer_lint"] = lint_module +_spec.loader.exec_module(lint_module) +lint = lint_module.lint +format_findings = lint_module.format_findings + +PROSE_EXTENSIONS = {".md", ".mdx", ".markdown", ".txt", ".rst", ".adoc"} + +RULES = """Humanizer is on. Write replies, thinking, and prose files so they read like a person wrote them: +- State each point directly. No "not X but Y" contrasts, staged openers ("Here's the thing", "Let's dive in"), or one-line closers that repeat the point. +- No em dashes or en dashes; use a period, comma, colon, or parentheses. +- No chatbot wrappers ("Great question!", "I hope this helps"), no inflated words (delve, pivotal, crucial, tapestry, testament). +- Vary sentence length. Use lists of three only when there are three things. Bold only what the reader must not miss. +Prose writes and final replies with these tells are blocked until rewritten.""" + +REMINDER = "Humanizer is on: direct statements, no dashes, no staged openers or closers, no chatbot wrappers, in replies, thinking, and files." + + +def state_path(session_id: str) -> Path: + base = os.environ.get("CLAUDE_PLUGIN_DATA") or tempfile.gettempdir() + safe = re.sub(r"[^A-Za-z0-9_-]", "_", session_id or "default") + return Path(base) / f"humanizer-{safe}.json" + + +def add_context(event_name: str, text: str) -> int: + print(json.dumps({"hookSpecificOutput": {"hookEventName": event_name, "additionalContext": text}})) + return 0 + + +def on_context(event: dict, event_name: str) -> int: + text = RULES if event_name == "SessionStart" else REMINDER + path = state_path(event.get("session_id", "")) + if path.exists(): + try: + note = json.loads(path.read_text(encoding="utf-8")).get("thinking", "") + except (OSError, json.JSONDecodeError): + note = "" + path.unlink(missing_ok=True) + if note: + text += "\n\nYour thinking in the last turn had AI tells. Avoid them this turn:\n" + note + return add_context(event_name, text) + + +def written_text(tool_input: dict) -> str: + if "content" in tool_input: + return str(tool_input["content"]) + if "new_string" in tool_input: + return str(tool_input["new_string"]) + return "\n".join(str(e.get("new_string", "")) for e in tool_input.get("edits", [])) + + +def on_write(event: dict) -> int: + tool_input = event.get("tool_input") or {} + path = str(tool_input.get("file_path", "")) + if Path(path).suffix.lower() not in PROSE_EXTENSIONS: + return 0 + report = lint(written_text(tool_input)) + if not report["flagged"]: + return 0 + print( + f"Humanizer blocked this write to {path} (AI score {report['score']:.2f}):\n" + f"{format_findings(report)}\n\n" + "Rewrite the text with the humanizer skill so it states each point directly, " + "then write it again. Keep every fact. A watched phrase is fine inside a quotation or code.", + file=sys.stderr, + ) + return 2 + + +def last_turn(transcript_path: str) -> tuple[str, str]: + """Return the text and thinking the agent wrote since the last user prompt.""" + texts: list[str] = [] + thinking: list[str] = [] + try: + lines = Path(transcript_path).read_text(encoding="utf-8").splitlines() + except OSError: + return "", "" + for line in reversed(lines): + try: + entry = json.loads(line) + except json.JSONDecodeError: + continue + message = entry.get("message") or {} + content = message.get("content") + if entry.get("type") == "user": + # A tool result is part of the same turn; a typed prompt ends it. + if isinstance(content, str) or any( + isinstance(b, dict) and b.get("type") == "text" for b in content or [] + ): + break + continue + if entry.get("type") != "assistant" or not isinstance(content, list): + continue + for block in reversed(content): + if block.get("type") == "text": + texts.insert(0, block.get("text", "")) + elif block.get("type") == "thinking" and block.get("thinking"): + thinking.insert(0, block["thinking"]) + return "\n\n".join(texts), "\n\n".join(thinking) + + +def on_stop(event: dict) -> int: + if event.get("stop_hook_active"): + return 0 # The agent is already answering a block; do not loop. + text, thinking = last_turn(event.get("transcript_path", "")) + # The transcript holds every text block of the turn. Fall back to the + # event field when the transcript is not written yet. + reply = text or str(event.get("last_assistant_message") or "") + + if thinking: + report = lint(thinking) + if report["flagged"]: + path = state_path(event.get("session_id", "")) + try: + path.write_text(json.dumps({"thinking": format_findings(report, 6)}), encoding="utf-8") + except OSError: + pass + + if not reply.strip(): + return 0 + report = lint(reply) + if not report["flagged"]: + return 0 + print( + f"Humanizer: your last reply reads as AI-written (score {report['score']:.2f}):\n" + f"{format_findings(report)}\n\n" + "Send the reply again, rewritten with the humanizer skill. Keep every fact, " + "command, path, and result. Do not mention this check.", + file=sys.stderr, + ) + return 2 + + +def main() -> int: + if os.environ.get("HUMANIZER_HOOK", "").lower() in {"off", "0", "false"}: + return 0 + try: + event = json.load(sys.stdin) + except json.JSONDecodeError: + return 0 + name = event.get("hook_event_name", "") + if name in {"SessionStart", "UserPromptSubmit"}: + return on_context(event, name) + if name == "Stop": + return on_stop(event) + if name == "PreToolUse" or "tool_input" in event: + return on_write(event) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/humanizer-lint.py b/scripts/humanizer-lint.py new file mode 100644 index 000000000..b86a6a272 --- /dev/null +++ b/scripts/humanizer-lint.py @@ -0,0 +1,330 @@ +#!/usr/bin/env python3 +"""Score prose for Humanizer's AI tells with a small linear model. + +The approach follows ste-lint: strip code and quotations, count each tell as +a feature, normalize by length, and report. Each feature has a weight. The +weighted sum plus a bias gives a logistic score from 0 to 1. + +A text is flagged when it has a hard tell (one that justifies an edit on one +sighting, per SKILL.md) or when its score reaches THRESHOLD. Under MIN_WORDS, +only hard tells count, because rates are noisy in short texts. + +Weights for stock AI words come from published frequency ratios (Kobak et +al., Sci. Adv. 2025; Reinhart et al., PNAS 2025). Other weights follow the +strength order in SKILL.md. Passive voice and type-token ratio are left out +on purpose: AI text uses less passive voice than people do, and the +direction of type-token ratio changes with the model (El Attar et al. 2026). + +Usage: + humanizer-lint.py FILE... one summary line per file; exit 1 if any is flagged + humanizer-lint.py < text full JSON report +""" + +from __future__ import annotations + +import json +import math +import re +import statistics +import sys +from dataclasses import dataclass + +BIAS = -3.0 +THRESHOLD = 0.5 +MIN_WORDS = 20 # below this, only hard tells count +RHYTHM_WORDS = 40 # below this, skip rhythm and paragraph features +SCALE_WORDS = 200 # non-hard features count per this many words + + +@dataclass(frozen=True) +class Lexical: + ref: str # SKILL.md pattern, such as "§1" + name: str + pattern: re.Pattern[str] + weight: float + cap: int = 2 # hits past this add nothing + hard: bool = False # flags the text on one sighting + + +def rx(*alternatives: str, flags: int = re.I | re.M) -> re.Pattern[str]: + return re.compile("|".join(alternatives), flags) + + +START = r"(?:^|[.!?]\s+)" # start of a sentence + +LEXICAL: list[Lexical] = [ + Lexical("§1", "Not X but Y", rx( + r"\bnot (?:just|only|merely|simply)\b[^.!?\n]{1,80}?\bbut\b", + r"\b(?:it'?s|this is|that'?s|it is|is|are|was) not\b[^.!?;\n]{1,60}?[,;]\s*(?:it'?s|this is|that'?s|it is|but)\b", + r"\b(?:isn'?t|aren'?t|wasn'?t)\b[^.!?;\n]{1,60}?[,;]\s*(?:it'?s|they'?re|this is|that'?s|it was)\b", + r"\b(?:isn'?t|is not|aren'?t|wasn'?t) (?:the|a|an|about)\b[^.!?\n]{1,60}\.\s+(?:It'?s|It is|It was|They'?re)\b", + r"\b(?:does not|doesn'?t) mean\b[^.!?\n]{1,80}[.!?]\s+(?:it|this|that) means\b", + r"\bnot because\b[^.!?\n]{1,80}[.,]\s+(?:but )?because\b", + ), 2.5, hard=True), + Lexical("§2", "One-line closer", rx( + r"\blet that sink in\b", r"\bread that again\b", r"\bthat(?: is|'s) the real (?:win|story|lesson)\b", + r"\bthat distinction matters\b", r"\bevery\. single\. \w+", r"\bthe message was clear\b", + START + r"(?:problem solved|full stop|end of story)\.(?=\s|$)", + ), 2.5, hard=True), + Lexical("§2", "Fragment run", re.compile( + r"(?:\b(?:No|Not|Zero|Just) \w+(?: \w+)?\.\s+){2,}(?:No|Not|Zero|Just) \w+" + ), 2.0, hard=True), + Lexical("§3", "Saying that sounds deep", rx( + r"\bthe real (?:question|issue|problem|story) (?:is|here)\b", r"\bat its core\b", + r"\bwhat (?:really|truly) matters\b", r"\bthe heart of the matter\b", + r"\bthe deeper (?:issue|question|problem)\b", r"\bis the (?:language|currency|architecture) of\b", + r"\bthe (?:uncomfortable )?truth is\b", r"\bthe reality is\b", r"\bat the end of the day\b", + ), 2.0, hard=True), + Lexical("§4", "Staged run-up", rx( + r"\blet'?s (?:dive in|dive into|break (?:this|it) down|be honest|explore|unpack)\b", + r"\bhere'?s (?:what you need to know|the thing|the kicker|the catch|the deal)\b", + r"\bwithout further ado\b", r"\breal talk\b", START + r"the thing is\b", + r"\bmake no mistake\b", r"\blet me (?:walk you through|be clear)\b", + r"\bin today'?s (?:fast-paced|digital|modern|ever)", START + r"(?:honestly|look)\?(?=\s|$)", + r"\bthe (?:hard|tricky|interesting|new|best) part(?: is\b|\?)", + START + r"(?:the|our) (?:result|catch|answer|kicker|twist|culprit)\?", + ), 2.0, hard=True), + Lexical("§4", "Rhetorical question setup", rx( + START + r"(?:Why|What|How|So what|Sound familiar)[^.?!\n]{0,50}\?\s+(?:Because|It'?s|The answer|Simple|Here'?s|That'?s)\b", + START + r"what if\b", + ), 1.5), + Lexical("§5", "Arguing with no one", rx( + r"\bI'?m not saying\b", r"\bdon'?t get me wrong\b", r"\bthis is not to say\b", + START + r"to be clear,", r"\ba tempting approach would be\b", r"\bone might be tempted to\b", + r"\bthis isn'?t (?:mainly |really |just )?about\b", r"\bsome might (?:say|argue)\b", + ), 2.0, hard=True), + Lexical("§12", "Strong AI word", rx( + r"\bdelv(?:e|es|ed|ing)\b", r"\btapestr(?:y|ies)\b", r"\btestament\b", + r"\bunderscor(?:e|es|ed|ing)\b(?! (?:character|prefix|separator))", r"\bshowcas(?:e|es|ed|ing)\b", + ), 1.5, cap=3), + Lexical("§12", "Common AI word", rx( + r"\bcrucial(?:ly)?\b", r"\bpivotal\b", r"\bintricat(?:e|ely|acies)\b", r"\bmeticulous(?:ly)?\b", + r"\binterplay\b", r"\bgarner\w*", r"\bbolster\w*", r"\bvibrant\b", r"\benduring\b", + START + r"additionally,", r"\bnotably\b", r"\bcomprehensive\b", r"\benhanc(?:e|es|ed|ing)\b", + r"\bfoster(?:s|ed|ing)?\b", r"\brealm\b", r"\bmultifaceted\b", r"\binvaluable\b", r"\bnuanced\b", + r"\blandscape\b", r"\bleverag\w*", r"\bseamless(?:ly)?\b", r"\brobust\b", r"\bholistic\b", r"\bparamount\b", + ), 0.6, cap=5), + Lexical("§13", "Inflated significance", rx( + r"\bstands? as a\b", r"\bmark(?:s|ed|ing)? a (?:pivotal|significant|new|major|key|turning)\b", + r"\bpivotal moment\b", r"\bplays? a (?:crucial|vital|key|pivotal|significant) role\b", + r"\bsetting the stage\b", r"\bindelible\b", r"\blasting legacy\b", r"\bevolving landscape\b", + r"\bthe future looks bright\b", r"\bstep in the right direction\b", r"\bcommitment to\b", + r"\bgame[- ]chang(?:er|ing)\b", r"\bparadigm shift\b", + ), 1.5, cap=3), + Lexical("§15", "Shallow -ing tail", rx( + r",\s+(?:highlighting|underscoring|emphasizing|ensuring|reflecting|symbolizing|contributing to|" + r"cultivating|fostering|encompassing|showcasing|enhancing|solidifying|paving the way)\b", + ), 1.0, cap=3), + Lexical("§16", "Sales language", rx( + r"\bnestled\b", r"\bin the heart of\b", r"\bbreathtaking\b", r"\bmust-visit\b", r"\bstunning\b", + r"\brenowned\b", r"\bdiverse array\b", r"\bworld-class\b", r"\bcutting-edge\b", + r"\beffortless(?:ly)?\b", r"\bunlock(?:s|ing)? (?:the|new|your)\b", r"\bempower(?:s|ing)?\b", + r"\bsupercharg\w*", r"\bgroundbreaking\b", r"\becosystem\b", + ), 1.0, cap=3), + Lexical("§17", "Borrowed authority", rx( + r"\bexperts (?:argue|believe|say|agree)\b", r"\bobservers have\b", r"\bindustry reports\b", + r"\bsome critics\b", r"\bstudies show\b", + ), 1.0), + Lexical("§18", "Avoiding is and has", rx(r"\b(?:serves|stands|functions|acts) as\b", r"\bboasts\b"), 0.7, cap=3), + Lexical("§9", "Stacked qualifiers", rx( + r"\bcould potentially\b", r"\bmight (?:arguably|possibly|potentially)\b", + r"\bmay (?:possibly|potentially)\b", r"\bto be fair\b", + ), 0.7, cap=3), + Lexical("§22", "Chatbot residue", rx( + r"\bI hope this helps\b", r"\bgreat question\b", r"\byou'?re (?:absolutely|totally|completely) right\b", + r"^\s*(?:certainly|of course|absolutely|sure)!", r"\bhappy to help\b", + ), 3.0, hard=True), + Lexical("§22", "Chatbot offer", rx( + r"\bwould you like me to\b", START + r"want me to\b", + r"\blet me know if you(?:'d| would)? (?:like|want|need|have)\b", r"\bfeel free to\b", + r"\bshould I (?:continue|proceed|go ahead)\?", + ), 1.0), + Lexical("§23", "Knowledge-limit disclaimer", rx( + r"\bas of my (?:last|latest) (?:update|training)\b", r"\bas an AI\b", r"\bknowledge cutoff\b", + r"\bbased on (?:the )?available information\b", + r"\bnot (?:widely|publicly|extensively) (?:available|documented|disclosed)\b", + ), 2.0, hard=True), + Lexical("§25", "Writing about the document", rx( + r"\bthe (?:table|list|section|diagram) below (?:shows|compares|lists|outlines)\b", + r"\bin this (?:section|guide|document|post|article),? (?:we|I)(?:'ll| will)\b", + r"\bthis (?:section|document|guide) (?:covers|explains|outlines|is organized)\b", + ), 0.8), + Lexical("§2", "Summary closer", rx(START + r"(?:in summary|in conclusion|ultimately|to sum up),"), 0.8), +] + +# Dashes are scored and also blocked as a hard rule (§8 in SKILL.md). +DASH = re.compile(r"[—–]|\s--\s") + +STRIP = [ + re.compile(r"\A---\n.*?\n---\n", re.S), # front matter + re.compile(r"(?:```|~~~).*?(?:```|~~~|\Z)", re.S), # fenced code, even unclosed + re.compile(r"(?:\A|\n\s*\n)(?:(?: {4}|\t).*(?:\n|\Z))+"), # indented code + re.compile(r"", re.S), # HTML comments + re.compile(r"<[^>\n]+>"), # HTML tags + re.compile(r"`[^`\n]*`"), # inline code + re.compile(r"https?://\S+"), # URLs + re.compile(r"(?.*$"), # blockquotes + re.compile(r"\"[^\"\n]{1,200}\"|“[^”\n]{1,200}”|‘[^’\n]{1,60}’"), # quotes +] + +# A word named as an example ("adjectives such as robust") is a mention, not +# a use. Only weak features get this exception, so it cannot hide a hard tell. +MENTION = re.compile(r"\b(?:such as|(?:words?|phrases?|terms?) like|e\.g\.|for example)\b[^.\n]{0,80}$", re.I) + +WORD = re.compile(r"[A-Za-z0-9][A-Za-z0-9'’\-]*") +TRIAD = re.compile(r"\b[\w-]+(?: [\w-]+){0,2}, [\w-]+(?: [\w-]+){0,2},? (?:and|or) [\w-]+", re.I) +BOLD_LABEL = re.compile(r"(?m)^\s*(?:[-*+]|\d+[.)])\s+\*\*([^*\n]{1,40})\*\*\s*:?") +LIST_OR_BLOCK = ("#", "-", "*", "+", "|") + + +def clean(text: str) -> str: + """Blank out skipped spans but keep newlines so line numbers stay right.""" + for pattern in STRIP: + text = pattern.sub(lambda m: re.sub(r"[^\n]", " ", m.group(0)), text) + return text + + +def sentences(text: str) -> list[str]: + found = [] + for line in text.split("\n"): + if line.lstrip().startswith("|"): + continue # table row + line = re.sub(r"^\s*(?:#{1,6}|[-*+]|\d+[.)])\s+", "", line.strip()) + if line: + found.extend(s for s in re.split(r"(?<=[.!?])\s+(?=[A-Z0-9\"'])", line) if s.strip()) + return found + + +def structural(cleaned: str, sents: list[str], words: int) -> dict[str, float]: + """Return raw feature values; weights live in STRUCTURAL.""" + labels = [ + label for label in BOLD_LABEL.findall(cleaned) + if not re.match(r"\s*[-`]", label) and not re.search(r"[_./]|--", label) + ] + out = { + "dashes": float(len(DASH.findall(cleaned))), + "triads": float(len(TRIAD.findall(cleaned))), + "bold_labels": float(len(labels)) if len(labels) >= 2 else 0.0, + } + if words < RHYTHM_WORDS: + return out + + lengths = [n for n in (len(WORD.findall(s)) for s in sents) if n] + cv = statistics.pstdev(lengths) / statistics.mean(lengths) if len(lengths) >= 6 else 1.0 + out["flat_rhythm"] = max(0.0, 0.40 - cv) + + openers = [s.split()[0].lower().strip("\"'") for s in sents if s.split()] + runs, streak = 0, 1 + for prev, cur in zip(openers, openers[1:]): + streak = streak + 1 if cur == prev and cur != "the" else 1 + runs += streak == 3 + out["repeated_openers"] = float(runs) + + paragraphs = [p.strip() for p in re.split(r"\n\s*\n", cleaned) if p.strip()] + closers = sum( + 1 for prev, cur in zip(paragraphs, paragraphs[1:]) + # A line ending in a colon introduces what follows; it is not a closer. + if not cur.startswith(LIST_OR_BLOCK) and not prev.startswith("#") and not cur.endswith(":") + and len(sentences(cur)) == 1 and len(WORD.findall(cur)) <= 10 and len(sentences(prev)) >= 2 + ) + out["short_closers"] = float(closers) + return out + + +# key: (ref, name, weight, cap, scaled by length) +STRUCTURAL = { + "dashes": ("§8", "Dashes", 0.9, 4, True), + "triads": ("§6", "Forced triads", 0.6, 3, True), + "bold_labels": ("§19", "Bold labels", 0.8, 5, True), + "flat_rhythm": ("§7", "Flat sentence rhythm", 3.0, 1, False), + "repeated_openers": ("§7", "Repeated sentence openings", 0.6, 3, False), + "short_closers": ("§2", "Short closer paragraphs", 0.9, 3, False), +} + + +def lint(text: str) -> dict: + cleaned = clean(text) + lines = text.splitlines() + sents = sentences(cleaned) + words = len(WORD.findall(cleaned)) + scale = 1.0 / max(1.0, words / SCALE_WORDS) + + z = BIAS + hard: set[str] = set() + findings: list[dict] = [] + + def add(ref: str, name: str, is_hard: bool, match: str, start: int | None) -> None: + line_no = cleaned.count("\n", 0, start) + 1 if start is not None else 0 + excerpt = lines[line_no - 1].strip() if 0 < line_no <= len(lines) else "" + findings.append({ + "ref": ref, "name": name, "hard": is_hard, "match": match, "line": line_no, + "excerpt": excerpt if len(excerpt) <= 120 else excerpt[:117] + "...", + }) + + for feature in LEXICAL: + matches = [ + m for m in feature.pattern.finditer(cleaned) + if feature.hard or not MENTION.search(cleaned, cleaned.rfind("\n", 0, m.start()) + 1, m.start()) + ] + if not matches: + continue + z += feature.weight * min(len(matches), feature.cap) * (1.0 if feature.hard else scale) + if feature.hard: + hard.add(feature.ref) + for match in matches: + add(feature.ref, feature.name, feature.hard, match.group(0).strip(" .!?\n\t"), match.start()) + + for match in DASH.finditer(cleaned): + hard.add("§8") + add("§8", "Dash as connector", True, match.group(0).strip(), match.start()) + + features = structural(cleaned, sents, words) + for key, value in features.items(): + ref, name, weight, cap, scaled = STRUCTURAL[key] + contribution = weight * min(value, cap) * (scale if scaled else 1.0) + z += contribution + if contribution >= 0.5 and key != "dashes": + add(ref, name, False, f"{key}={value:.2f}", None) + + probability = 1.0 / (1.0 + math.exp(-z)) + flagged = bool(hard) or (words >= MIN_WORDS and probability >= THRESHOLD) + return { + "words": words, + "sentences": len(sents), + "score": round(probability, 3), + "flagged": flagged, + "hard_tells": sorted(hard, key=lambda r: int(r[1:])), + "features": {k: round(v, 3) for k, v in features.items()}, + "findings": findings, + } + + +def format_findings(report: dict, limit: int = 12) -> str: + rows = [] + for f in report["findings"][:limit]: + where = f" (line {f['line']}: {f['excerpt']})" if f["line"] else "" + rows.append(f"- {f['ref']} {f['name']}: {f['match']!r}{where}") + extra = len(report["findings"]) - limit + if extra > 0: + rows.append(f"- ...and {extra} more") + return "\n".join(rows) + + +def main() -> int: + files = sys.argv[1:] + if not files: + print(json.dumps(lint(sys.stdin.read()), indent=2)) + return 0 + flagged_any = False + for name in files: + with open(name, encoding="utf-8") as source: + report = lint(source.read()) + flagged_any |= report["flagged"] + print(f"{name:40} words={report['words']:5d} score={report['score']:.2f} " + f"flagged={str(report['flagged']).lower():5} hard={','.join(report['hard_tells']) or '-'}") + return 1 if flagged_any else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/validate-package.py b/scripts/validate-package.py index 0e329376f..8c00ffd82 100755 --- a/scripts/validate-package.py +++ b/scripts/validate-package.py @@ -151,4 +151,34 @@ def numbered_patterns(matches: list[tuple[str, str]], where: str) -> dict[int, s if skill_words > 5500: raise SystemExit(f"Keep SKILL.md at 5,500 words or fewer; it has {skill_words}") +# The plugin hook must stay valid JSON and point at a script that exists. +try: + HOOKS = json.loads(read_package_file(ROOT / "hooks" / "hooks.json")) +except json.JSONDecodeError as error: + raise SystemExit(f"Fix the JSON in hooks/hooks.json: {error}") +if "hooks" in PLUGIN: + raise SystemExit("Omit hooks from plugin.json; Claude Code loads hooks/hooks.json itself") +hook_commands = [ + hook.get("command", "") + for groups in HOOKS.get("hooks", {}).values() + for group in groups + for hook in group.get("hooks", []) +] +if not hook_commands: + raise SystemExit("Add at least one command to hooks/hooks.json") +for command in hook_commands: + for script in re.findall(r"\$\{CLAUDE_PLUGIN_ROOT\}/([^\"'\s]+)", command): + if not (ROOT / script).is_file(): + raise SystemExit(f"hooks/hooks.json runs a missing file: {script}") + +# Hook labels must point at real patterns after a renumber. +hook_source = read_package_file(ROOT / "scripts" / "humanizer-lint.py") +hook_references = sorted({int(n) for n in re.findall(r'"§([0-9]+)"', hook_source)}) +bad_hook_refs = [n for n in hook_references if not 1 <= n <= pattern_count] +if bad_hook_refs: + raise SystemExit( + f"Point every feature label in scripts/humanizer-lint.py at a pattern from 1 to " + f"{pattern_count}: {bad_hook_refs}" + ) + print(f"Humanizer package v{skill_version} is valid") diff --git a/tests/__pycache__/test_hooks.cpython-314.pyc b/tests/__pycache__/test_hooks.cpython-314.pyc new file mode 100644 index 000000000..687b0a69f Binary files /dev/null and b/tests/__pycache__/test_hooks.cpython-314.pyc differ diff --git a/tests/fixtures.json b/tests/fixtures.json new file mode 100644 index 000000000..f5d7ad154 --- /dev/null +++ b/tests/fixtures.json @@ -0,0 +1,40 @@ +{ + "ai": [ + "I'm thrilled to announce that shared drafts are finally here! For months, our own team was drowning in files named final_v7.docx, and we knew there had to be a better way. Now two people can edit the same doc at once. It's not just a feature; it's a whole new way to collaborate. Comments stay anchored to the exact sentence they reference, even as the text around them evolves. And the best part? It's available today on every plan, completely free. Let that sink in.", + "Great question! Caching in Next.js is a crucial topic. Let's dive in.", + "The real question is whether teams can adapt. At its core, what really matters is organizational readiness, cultural alignment, and leadership buy-in.", + "I fixed the parser — the bug was in the tokenizer — and now everything works.", + "This isn't mainly about prompt length. I'm not saying documentation doesn't matter. The issue is whether the agent can use the instruction.", + "The new dashboard showcases a vibrant, intricate interplay of metrics, a testament to the team's meticulous work. It underscores our pivotal commitment to robust, seamless reporting. The landscape of analytics has shifted, and this tool plays a crucial role in it. Teams garner insights, bolster decisions, and leverage data across every function of the business today.", + "Great question! The issue isn't the cache, it's the stale index. Once you rebuild the index, lookups return the right rows again. That's the real win.", + "- **Performance:** The new parser delivers robust, scalable, and maintainable performance.\n- **Security:** Additionally, it leverages crucial safeguards to enhance resilience.\n- **Usability:** It showcases a seamless experience for developers.", + "Let's dive in. Here's the thing — the build is slow because every job reinstalls dependencies — and that adds up fast. Here's what you need to know: caching the package directory fixes it.", + "The migration to Postgres 16 marks a pivotal moment in the evolution of our data layer, underscoring our commitment to reliability and setting the stage for future growth. It stands as a testament to the team's dedication.", + "At its core, this isn't about test coverage. To be clear, I'm not saying coverage doesn't matter. The real question is whether the tests catch regressions, and what really matters is the feedback loop.", + "Why does this matter? Because every retry doubles the load on the database.\n\nNo backoff. No jitter. No ceiling.\n\nThe fix is simple: add exponential backoff with a cap.\n\nProblem solved.", + "The dashboard offers a comprehensive view of deployments, highlighting failure trends, fostering accountability, and ensuring that teams stay aligned with organizational goals. It is seamlessly integrated with the vibrant ecosystem of internal tools.", + "Certainly! Based on available information, the function could potentially be called from multiple threads, which might arguably cause a race. I hope this helps! Let me know if you'd like me to expand on any section.", + "- **Root cause:** The retry loop had no cap.\n- **Fix:** Added exponential backoff with a ceiling.\n- **Testing:** Ran the integration suite three times.\n\nWant me to open a PR?", + "Here's what I found. The flaky test isn't a timing issue, it's a shared fixture. Each test now builds its own fixture, ensuring clean state every run." + ], + "human": [ + "Shared drafts are out today. For months our own team passed around files named final_v7.docx, and we got sick of it. Now two people can edit the same doc at once and see each other's changes as they type. Comments stay attached to the sentence they're about, even when the text around it changes. It's free on every plan.", + "Next.js caches data at several layers, including request memoization, the data cache, and the router cache.", + "All 12 tests pass. The fix is in parser.py: the tokenizer dropped the last character when a line ended without a newline.", + "I cloned both repos into ~/Documents/dev. Neither existed there before, so nothing was overwritten.", + "Session tokens rotate in place every 24 hours, and clients refresh transparently.", + "The question is whether teams can adapt. That mostly depends on whether the organization is ready to change its habits, which in our case took about two quarters and one painful reorg that nobody enjoyed.", + "yeah that's the flaky test again, rerun it. if it fails twice lmk and I'll look", + "The build was slow because each job reinstalled dependencies. I added a cache keyed on the lockfile hash, and CI time dropped from 11 minutes to 4.", + "Run `npm ci --prefer-offline` before the test step. The flag stops npm from hitting the registry when the cache already has the package.\n\n```sh\nnpm ci --prefer-offline -- robust, seamless, and crucial\n```", + "## Configuration\n\nThe server reads `config.toml` from the working directory. Set `port` to change the listen port; the default is 8080. If the file is missing, the server exits with code 2.", + "Agreed, this is a workaround. I'd rather keep this PR account-specific and open a separate ticket for the MergeService fix and the backfill.", + "I tried three things: clearing the cache, pinning the version, and rolling back the kernel. Only the rollback worked, which still bugs me, because nothing in the changelog touches the driver.", + "The test fails only on CI. Locally TZ is Asia/Manila, CI uses UTC, so the date boundary shifts. Check whether parseDate uses local time. It does, line 42. Switch it to Date.UTC and rerun.", + "The reviewer flagged \"delve\" and \"tapestry\" in the draft. I removed both and rewrote the intro so it starts with the benchmark numbers.", + "Options:\n\n- **`--force`** overwrites existing files.\n- **`--dry-run`** prints the plan without writing.\n- **--verbose** logs each step.", + "Retries use exponential backoff starting at 200 ms and doubling up to a 30 second ceiling. After five failed attempts the job moves to the dead-letter queue, where an operator can inspect it. This keeps the worker robust against brief network drops without hammering a database that is already struggling. Jitter of up to 20 percent spreads retries from many workers so they do not arrive together.", + "Fixed. The off-by-one was in the pager.", + "Look, the deadline is Friday, the reviewer is out, and the CI box is down. We ship what we have." + ] +} diff --git a/tests/test_hooks.py b/tests/test_hooks.py new file mode 100644 index 000000000..6b2b45c82 --- /dev/null +++ b/tests/test_hooks.py @@ -0,0 +1,153 @@ +"""Tests for scripts/humanizer-lint.py and scripts/humanizer-hook.py. + +Run with: python3 -m unittest discover -s tests +""" + +from __future__ import annotations + +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +HOOK = ROOT / "scripts" / "humanizer-hook.py" +FIXTURES = json.loads((ROOT / "tests" / "fixtures.json").read_text(encoding="utf-8")) + +_spec = importlib.util.spec_from_file_location("humanizer_lint", ROOT / "scripts" / "humanizer-lint.py") +lint_module = importlib.util.module_from_spec(_spec) +sys.modules["humanizer_lint"] = lint_module +_spec.loader.exec_module(lint_module) + + +def run_hook(event: dict, env: dict | None = None) -> subprocess.CompletedProcess: + full_env = {k: v for k, v in os.environ.items() if k != "HUMANIZER_HOOK"} + full_env.update(CLAUDE_PLUGIN_DATA=tempfile.gettempdir(), **(env or {})) + return subprocess.run( + [sys.executable, str(HOOK)], input=json.dumps(event), + capture_output=True, text=True, env=full_env, timeout=10, + ) + + +def transcript(*entries: dict) -> str: + handle = tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False) + for entry in entries: + handle.write(json.dumps(entry) + "\n") + handle.close() + return handle.name + + +def user(text: str) -> dict: + return {"type": "user", "message": {"role": "user", "content": text}} + + +def assistant(*blocks: dict) -> dict: + return {"type": "assistant", "message": {"role": "assistant", "content": list(blocks)}} + + +class LintFixtures(unittest.TestCase): + def test_ai_passages_are_flagged(self): + for text in FIXTURES["ai"]: + with self.subTest(text=text[:50]): + self.assertTrue(lint_module.lint(text)["flagged"], lint_module.lint(text)) + + def test_human_passages_pass(self): + for text in FIXTURES["human"]: + with self.subTest(text=text[:50]): + self.assertFalse(lint_module.lint(text)["flagged"], lint_module.lint(text)) + + def test_code_quotes_and_blockquotes_are_skipped(self): + text = 'Avoid "Let that sink in." and `at its core`.\n\n> Here\'s the thing.\n\n```\na — b\n```\n' + self.assertFalse(lint_module.lint(text)["flagged"]) + + def test_lead_in_line_is_not_a_closer(self): + para = "The server reads its config at start. It exits with code 2 if the file is missing." + text = "\n\n".join([para, "Each option is listed below:", para, "Pick one of these:", para, "Run it like this:", para]) + self.assertEqual(lint_module.lint(text)["features"]["short_closers"], 0.0) + + def test_repo_docs_pass(self): + for name in ("README.md", "AGENTS.md", "CHANGELOG.md"): + with self.subTest(name=name): + report = lint_module.lint((ROOT / name).read_text(encoding="utf-8")) + self.assertEqual(report["hard_tells"], [], report["findings"][:5]) + + +class HookEvents(unittest.TestCase): + def test_write_to_prose_file_is_blocked(self): + result = run_hook({"hook_event_name": "PreToolUse", "tool_name": "Write", + "tool_input": {"file_path": "a.md", "content": "Let that sink in."}}) + self.assertEqual(result.returncode, 2) + self.assertIn("§2", result.stderr) + + def test_edit_and_multiedit_text_is_checked(self): + edit = run_hook({"hook_event_name": "PreToolUse", "tool_input": { + "file_path": "b.txt", "old_string": "x", "new_string": "Great question! Here it is."}}) + multi = run_hook({"hook_event_name": "PreToolUse", "tool_input": { + "file_path": "c.rst", "edits": [{"new_string": "fine"}, {"new_string": "Don't get me wrong, we ship Friday."}]}}) + self.assertEqual((edit.returncode, multi.returncode), (2, 2)) + + def test_code_file_is_ignored(self): + result = run_hook({"hook_event_name": "PreToolUse", "tool_input": { + "file_path": "a.py", "content": "# Let that sink in — at its core"}}) + self.assertEqual(result.returncode, 0) + + def test_off_switch(self): + result = run_hook({"hook_event_name": "PreToolUse", "tool_input": { + "file_path": "a.md", "content": "Let that sink in."}}, env={"HUMANIZER_HOOK": "off"}) + self.assertEqual(result.returncode, 0) + + def test_stop_blocks_ai_reply(self): + path = transcript(user("fix it"), assistant( + {"type": "text", "text": "Great question! It's not just a bug, it's a design flaw."})) + result = run_hook({"hook_event_name": "Stop", "session_id": "t1", + "transcript_path": path, "stop_hook_active": False}) + self.assertEqual(result.returncode, 2) + self.assertIn("reply", result.stderr) + + def test_stop_passes_plain_reply_and_reads_whole_turn(self): + path = transcript( + user("old prompt"), assistant({"type": "text", "text": "Let that sink in."}), + user("fix it"), + assistant({"type": "text", "text": "Running the tests."}, + {"type": "tool_use", "id": "1", "name": "Bash", "input": {}}), + {"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": "1", "content": "ok"}]}}, + assistant({"type": "text", "text": "All 12 tests pass. The fix is in parser.py line 40."}), + ) + result = run_hook({"hook_event_name": "Stop", "session_id": "t2", "transcript_path": path}) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_stop_does_not_loop(self): + path = transcript(user("x"), assistant({"type": "text", "text": "Let that sink in."})) + result = run_hook({"hook_event_name": "Stop", "transcript_path": path, "stop_hook_active": True}) + self.assertEqual(result.returncode, 0) + + def test_stop_falls_back_to_event_field(self): + result = run_hook({"hook_event_name": "Stop", "transcript_path": "/nonexistent", + "last_assistant_message": "I hope this helps!"}) + self.assertEqual(result.returncode, 2) + + def test_thinking_tells_reach_next_prompt(self): + path = transcript(user("x"), assistant( + {"type": "thinking", "thinking": "Let's dive in. At its core, this is simple."}, + {"type": "text", "text": "Done. The file is saved."})) + stop = run_hook({"hook_event_name": "Stop", "session_id": "t3", "transcript_path": path}) + self.assertEqual(stop.returncode, 0, stop.stderr) + prompt = run_hook({"hook_event_name": "UserPromptSubmit", "session_id": "t3", "prompt": "next"}) + context = json.loads(prompt.stdout)["hookSpecificOutput"]["additionalContext"] + self.assertIn("thinking in the last turn", context) + again = run_hook({"hook_event_name": "UserPromptSubmit", "session_id": "t3", "prompt": "next"}) + self.assertNotIn("thinking in the last turn", again.stdout) + + def test_session_start_injects_rules(self): + result = run_hook({"hook_event_name": "SessionStart", "session_id": "t4"}) + out = json.loads(result.stdout)["hookSpecificOutput"] + self.assertEqual(out["hookEventName"], "SessionStart") + self.assertIn("Humanizer is on", out["additionalContext"]) + + +if __name__ == "__main__": + unittest.main()