@yasaswy.nagavolu/agents 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,216 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ ai_attribution_guard.py — PreToolUse(Bash) guard: DENY any command that would
4
+ write an AI-attribution trailer into a commit message, tag message, PR/MR
5
+ body, or issue note.
6
+
7
+ The user never wants these trailers, on this machine, ever. The normal path
8
+ is the harness setting `includeCoAuthoredBy: false` (in ~/.claude/settings.json,
9
+ not this repo). This hook is the codified backstop for everything that setting
10
+ can't reach: a subagent building its own message, a script that pastes a
11
+ template, or a future harness change. Code-is-law, same shape as
12
+ `web_search_guard.py` and `no_openrouter_guard.py` in proxy/ — a rule that
13
+ previously lived only in prose becomes a hook that enforces it.
14
+
15
+ WHAT IS DENIED (message text, wherever it appears — see _scan below):
16
+ - `noreply@anthropic.com` anywhere at all — never a legitimate address for
17
+ a human co-author, so no anchoring or context check is needed.
18
+ - A `https://claude.ai/code` URL, or a "Generated with Claude Code" /
19
+ robot-emoji generated-with marker — the two markers our own commit
20
+ template historically appended.
21
+ - A line beginning (ignoring leading whitespace/quote/comment characters)
22
+ with `Co-Authored-By:` whose VALUE names Claude/Anthropic/another AI
23
+ assistant. A human co-author trailer (`Co-Authored-By: Jane Doe
24
+ <jane@example.com>`) is legitimate and NOT denied — only the value is
25
+ checked against `_AI_MARKERS`.
26
+ - A line beginning the same way with `Claude-Session:` — always denied,
27
+ it's never a legitimate non-AI header.
28
+
29
+ These checks run against the raw command text split on real newlines, which
30
+ already covers heredoc bodies (`git commit -F - <<'EOF' ... EOF`) for free —
31
+ the heredoc content is literal text inside the command string, one line per
32
+ scan iteration, no special-casing needed. They ALSO run against the contents
33
+ of any file referenced by `git commit -F/--file/-t/--template <file>` or
34
+ `gh ... create --body-file <file>` (scoped to those subcommands specifically,
35
+ so an unrelated `grep -F` doesn't trigger a spurious file read) — if the file
36
+ exists it's read and scanned the same way; if not, that check is skipped.
37
+
38
+ WHAT IS NOT DENIED (the failure mode that matters — a previous guard in
39
+ proxy/ shipped exactly this bug and blocked routine work, see
40
+ html_mocker_monitor_guard.py's docstring): a command that merely MENTIONS
41
+ one of these strings mid-sentence — `git log --grep="Co-Authored-By"`,
42
+ `git commit -m "fix: stop emitting Co-Authored-By trailers"`, a grep, a docs
43
+ edit, an echo describing this very guard. Only the anchored trailer forms
44
+ (Co-Authored-By / Claude-Session) require line-start anchoring; the
45
+ noreply@anthropic.com / claude.ai/code / "Generated with Claude Code"
46
+ markers are treated as never having an innocent reason to appear literally
47
+ in a Bash command at all, so they're substring-matched anywhere.
48
+
49
+ Fails OPEN (prints nothing, exit 0; never wedges Claude Code) on: malformed
50
+ stdin, wrong hook/tool, missing tool_input.command, no trigger match, or any
51
+ unexpected exception. In the last-resort uncaught-exception case ONLY, the
52
+ failure reason is appended as one timestamped line to
53
+ ~/.claude/logs/ai_attribution_guard.log — same pattern as the sibling guards.
54
+
55
+ Wiring (settings.json), matcher "Bash":
56
+ python ~/.claude/hooks/ai_attribution_guard.py
57
+ """
58
+ from __future__ import annotations
59
+
60
+ import json
61
+ import re
62
+ import shlex
63
+ import sys
64
+ import time
65
+ from pathlib import Path
66
+
67
+ LOG = Path.home() / ".claude" / "logs" / "ai_attribution_guard.log"
68
+
69
+ # Value markers that flag a Co-Authored-By trailer as AI (not human).
70
+ _AI_MARKERS = re.compile(
71
+ r"claude|anthropic|chatgpt|gpt[-\s]?\d|openai|copilot|gemini"
72
+ r"|\bai assistant\b|\bai agent\b|\blanguage model\b",
73
+ re.IGNORECASE,
74
+ )
75
+
76
+ # Anchored (line-start, ignoring leading whitespace/quote/comment chars) trailers.
77
+ _LEADING = r'^[\s"\'`>#*\-]*'
78
+ _CO_AUTHORED_BY_RE = re.compile(_LEADING + r"co-authored-by\s*:(.*)$", re.IGNORECASE)
79
+ _CLAUDE_SESSION_RE = re.compile(_LEADING + r"claude-session\s*:", re.IGNORECASE)
80
+
81
+ # Substring-anywhere markers — never a legitimate thing for a Bash command to contain.
82
+ _NOREPLY_RE = re.compile(r"noreply@anthropic\.com", re.IGNORECASE)
83
+ _CLAUDE_URL_RE = re.compile(r"https?://claude\.ai/code", re.IGNORECASE)
84
+ _GENERATED_MARKER_RE = re.compile(r"generated\s+with\s+claude\s+code", re.IGNORECASE)
85
+ _ROBOT_GENERATED_RE = re.compile(r"\U0001F916.{0,60}generated\s+with", re.IGNORECASE | re.DOTALL)
86
+
87
+ REASON = (
88
+ "This command would write an AI-attribution trailer (Co-Authored-By naming "
89
+ "an AI, Claude-Session, a 'Generated with Claude Code' marker, a "
90
+ "claude.ai/code URL, or noreply@anthropic.com) into a commit/tag message, "
91
+ "PR/MR body, or issue note. The user never wants these on this machine. "
92
+ "Re-issue the same command with that line/marker removed."
93
+ )
94
+
95
+ # git commit/tag file-message flags, and gh create's file-body flag. Scoped to
96
+ # these subcommands so an unrelated `grep -F` never triggers a stray file read.
97
+ _GIT_FILE_FLAGS = {"-F", "--file", "-t", "--template"}
98
+ _GH_FILE_FLAG = "--body-file"
99
+
100
+
101
+ def _log(reason: str) -> None:
102
+ """Append one audit line (silent-fail). Only called on fail-open paths."""
103
+ try:
104
+ LOG.parent.mkdir(parents=True, exist_ok=True)
105
+ ts = time.strftime("%Y-%m-%dT%H:%M:%S")
106
+ with open(LOG, "a", encoding="utf-8") as f:
107
+ f.write(f"{ts}\tguard\tBash\tfail-open\t{reason[:200]}\n")
108
+ except Exception:
109
+ pass
110
+
111
+
112
+ def _deny(reason: str) -> None:
113
+ print(json.dumps({
114
+ "hookSpecificOutput": {
115
+ "hookEventName": "PreToolUse",
116
+ "permissionDecision": "deny",
117
+ "permissionDecisionReason": reason,
118
+ }
119
+ }))
120
+
121
+
122
+ def _scan(text: str) -> str | None:
123
+ """Return a short reason string if `text` contains a denyable marker, else None."""
124
+ if _NOREPLY_RE.search(text):
125
+ return "contains noreply@anthropic.com"
126
+ if _CLAUDE_URL_RE.search(text):
127
+ return "contains a claude.ai/code URL"
128
+ if _GENERATED_MARKER_RE.search(text) or _ROBOT_GENERATED_RE.search(text):
129
+ return "contains a 'Generated with Claude Code' marker"
130
+ for line in text.split("\n"):
131
+ m = _CO_AUTHORED_BY_RE.match(line)
132
+ if m and _AI_MARKERS.search(m.group(1)):
133
+ return "contains a Co-Authored-By trailer naming an AI"
134
+ if _CLAUDE_SESSION_RE.match(line):
135
+ return "contains a Claude-Session trailer"
136
+ return None
137
+
138
+
139
+ def _referenced_file_texts(command: str) -> list[str]:
140
+ """Read contents of any git -F/-t/--file/--template or gh --body-file target."""
141
+ try:
142
+ tokens = shlex.split(command, posix=True)
143
+ except ValueError:
144
+ return []
145
+
146
+ lower = [t.lower() for t in tokens]
147
+ is_git_commit_or_tag = "git" in lower and ("commit" in lower or "tag" in lower)
148
+ is_gh_create = "gh" in lower and "create" in lower
149
+ if not is_git_commit_or_tag and not is_gh_create:
150
+ return []
151
+
152
+ refs: list[str] = []
153
+ for i, tok in enumerate(tokens[:-1]):
154
+ nxt = tokens[i + 1]
155
+ if is_git_commit_or_tag and tok in _GIT_FILE_FLAGS:
156
+ refs.append(nxt)
157
+ elif is_gh_create and tok == _GH_FILE_FLAG:
158
+ refs.append(nxt)
159
+
160
+ texts: list[str] = []
161
+ cwd = Path.cwd()
162
+ for ref in refs:
163
+ if ref == "-":
164
+ continue # stdin, not a file on disk to scan
165
+ p = Path(ref).expanduser()
166
+ if not p.is_absolute():
167
+ p = cwd / p
168
+ try:
169
+ if p.is_file():
170
+ texts.append(p.read_text(encoding="utf-8", errors="ignore"))
171
+ except Exception:
172
+ pass
173
+ return texts
174
+
175
+
176
+ def _safe_main() -> None:
177
+ try:
178
+ data = json.loads(sys.stdin.read() or "{}")
179
+ except Exception:
180
+ return
181
+ if not isinstance(data, dict):
182
+ return
183
+ if data.get("hook_event_name") != "PreToolUse":
184
+ return
185
+ if data.get("tool_name") != "Bash":
186
+ return
187
+
188
+ tool_input = data.get("tool_input") or {}
189
+ if not isinstance(tool_input, dict):
190
+ return
191
+ command = tool_input.get("command")
192
+ if not isinstance(command, str) or not command.strip():
193
+ return
194
+
195
+ reason = _scan(command)
196
+ if reason is None:
197
+ for text in _referenced_file_texts(command):
198
+ reason = _scan(text)
199
+ if reason:
200
+ break
201
+
202
+ if reason is None:
203
+ return # no trigger match -> allow
204
+
205
+ _deny(f"{REASON}\nDetected: {reason}.")
206
+
207
+
208
+ if __name__ == "__main__":
209
+ try:
210
+ _safe_main()
211
+ except Exception as exc:
212
+ # Last-resort fail-open. Log if we somehow can, but never wedge.
213
+ try:
214
+ _log(f"uncaught exception: {exc!r}")
215
+ except Exception:
216
+ pass
@@ -148,7 +148,7 @@
148
148
  {
149
149
  "key": "skill-authoring",
150
150
  "title": "Skill Authoring",
151
- "summary": "code-is-law: turn skill/agent-file prose rules into an enforced PostToolUse lint",
151
+ "summary": "code-is-law: turn agent/skill/hook/plugin/slash-command prose rules into an enforced prompt-time nudge + PostToolUse lint",
152
152
  "profile": "public",
153
153
  "advanced": false,
154
154
  "items": [
@@ -156,6 +156,15 @@
156
156
  "path": "skills/code-is-law",
157
157
  "kind": "skill"
158
158
  },
159
+ {
160
+ "path": "proxy/code_is_law_prompt_nudge.py",
161
+ "kind": "hook",
162
+ "wiring": {
163
+ "event": "UserPromptSubmit",
164
+ "type": "command",
165
+ "command": "python ~/.claude/proxy/code_is_law_prompt_nudge.py"
166
+ }
167
+ },
159
168
  {
160
169
  "path": "proxy/code_is_law_lint_hook.py",
161
170
  "kind": "hook",
@@ -512,7 +521,7 @@
512
521
  {
513
522
  "key": "harness-hygiene",
514
523
  "title": "Harness Hygiene",
515
- "summary": "Context-protecting large-file Read guard, plus Context7/Terraform authoring rules for any Claude Code session",
524
+ "summary": "Context-protecting large-file Read guard, AI-attribution trailer guard, plus Context7/Terraform authoring rules for any Claude Code session",
516
525
  "profile": "public",
517
526
  "advanced": false,
518
527
  "items": [
@@ -527,6 +536,26 @@
527
536
  "command": "python ~/.claude/hooks/large_file_read_guard.py"
528
537
  }
529
538
  },
539
+ {
540
+ "path": "global/hooks/ai_attribution_guard.py",
541
+ "targetPath": "hooks/ai_attribution_guard.py",
542
+ "kind": "hook",
543
+ "wiring": {
544
+ "event": "PreToolUse",
545
+ "matcher": "Bash",
546
+ "type": "command",
547
+ "command": "python ~/.claude/hooks/ai_attribution_guard.py"
548
+ }
549
+ },
550
+ {
551
+ "path": "global/hooks/ai_attribution_guard.py",
552
+ "kind": "setting",
553
+ "note": "No file of its own -- path points at the guard hook above only to satisfy prepack.js's path-must-exist staging check (see manifest.schema.json's kind:\"setting\" doc). Suppresses AI-attribution trailers at the harness source, so ai_attribution_guard.py's denial is a backstop rather than the only thing standing between the user and a trailer.",
554
+ "wiring": {
555
+ "settingsKey": "includeCoAuthoredBy",
556
+ "value": false
557
+ }
558
+ },
530
559
  {
531
560
  "path": "global/rules/context7.md",
532
561
  "targetPath": "rules/context7.md",
@@ -101,11 +101,11 @@
101
101
  },
102
102
  "kind": {
103
103
  "type": "string",
104
- "enum": ["skill", "agent", "hook", "command", "mcp", "rule", "statusline", "infra"],
105
- "description": "\"infra\" (added npx distribution slice #28) tags a self-profile-only proxy asset that is deployed but never registered as a settings.json hook event — a daemon script, PowerShell launcher, or config/asset directory (e.g. claude_router.py, litellm/config.yaml, portal/). \"hook\" stays reserved for items that either carry a wiring block or are a shared library a wired hook imports (see agents_env.py's existing convention)."
104
+ "enum": ["skill", "agent", "hook", "command", "mcp", "rule", "statusline", "infra", "setting"],
105
+ "description": "\"infra\" (added npx distribution slice #28) tags a self-profile-only proxy asset that is deployed but never registered as a settings.json hook event — a daemon script, PowerShell launcher, or config/asset directory (e.g. claude_router.py, litellm/config.yaml, portal/). \"hook\" stays reserved for items that either carry a wiring block or are a shared library a wired hook imports (see agents_env.py's existing convention). \"setting\" (added npx distribution slice #29) tags a declarative-only item that sets one plain top-level settings.json key ({settingsKey, value} wiring) with no file of its own to install — `path` typically points at a real file another item in the same bundle already claims/copies (e.g. the hook whose behavior the setting complements), purely to satisfy prepack.js's \"every claimed path must exist\" staging check; it is never independently copied (see install.js's file-copy loop, which skips kind:\"setting\" the same way it skips kind:\"mcp\")."
106
106
  },
107
107
  "wiring": {
108
- "description": "Optional wiring spec. For hooks: {event, matcher?, if?, type, command[, timeout]} mirroring the settings.json shape documented in proxy/README.md — or an array of such objects when one item must be registered under more than one matcher block (e.g. a guard hook wired under both \"Bash\" and \"Monitor\"). For the statusline item: {settingsKey: \"statusLine\", type, command}. For mcp items: {name, ...serverDef} — \"name\" is the mcpServers key to write, and the rest is the mcpServers server-entry object itself (type/url/headers, or type/command/args/env for stdio), copied from mcps/mcps.json. \"scope\" may be present (documentation-only convention shared with mcps.json) but is stripped before writing — only \"user\" scope is supported by the executor. A string value of the form \"${VAR_NAME}\" anywhere in the entry is a secret placeholder, resolved at wire time via the shared agentsEnv contract (real env var, else agents.env); an unresolved placeholder is dropped rather than written literally, so an optional secret degrades gracefully instead of blocking install. Execution (packages/cli/lib/wiring.js landed slice #23; packages/cli/lib/mcpWiring.js landed slice #25) acts on kind:\"hook\" items whose wiring object(s) carry {event, type, command}, and on kind:\"mcp\" items whose wiring carries {name, ...}; statusline wiring stays data-only pending a later slice.",
108
+ "description": "Optional wiring spec. For hooks: {event, matcher?, if?, type, command[, timeout]} mirroring the settings.json shape documented in proxy/README.md — or an array of such objects when one item must be registered under more than one matcher block (e.g. a guard hook wired under both \"Bash\" and \"Monitor\"). For the statusline item: {settingsKey: \"statusLine\", type, command}. For kind:\"setting\" items: {settingsKey, value} — settingsKey is the top-level settings.json key to keep in sync with value (any JSON type), independent of the statusline shape above (no type/command). For mcp items: {name, ...serverDef} — \"name\" is the mcpServers key to write, and the rest is the mcpServers server-entry object itself (type/url/headers, or type/command/args/env for stdio), copied from mcps/mcps.json. \"scope\" may be present (documentation-only convention shared with mcps.json) but is stripped before writing — only \"user\" scope is supported by the executor. A string value of the form \"${VAR_NAME}\" anywhere in the entry is a secret placeholder, resolved at wire time via the shared agentsEnv contract (real env var, else agents.env); an unresolved placeholder is dropped rather than written literally, so an optional secret degrades gracefully instead of blocking install. Execution (packages/cli/lib/wiring.js landed slice #23; packages/cli/lib/mcpWiring.js landed slice #25; kind:\"setting\" landed slice #29, also in packages/cli/lib/wiring.js) acts on kind:\"hook\" items whose wiring object(s) carry {event, type, command}, on kind:\"mcp\" items whose wiring carries {name, ...}, and on kind:\"setting\" items whose wiring carries {settingsKey, value}; statusline wiring stays data-only pending a later slice.",
109
109
  "oneOf": [
110
110
  { "type": "object" },
111
111
  { "type": "array", "items": { "type": "object" }, "minItems": 1 }
@@ -166,6 +166,64 @@ First invocation emits a `permissionDecision: "deny"` naming reviewer-subagent;
166
166
 
167
167
  ---
168
168
 
169
+ ## code_is_law_prompt_nudge + code_is_law_lint_hook (code-is-law self-enforcement)
170
+
171
+ **The problem these two hooks solve.** "Apply code-is-law when building an agent/skill/hook/plugin/slash-command" was prose (CLAUDE.md, the `code-is-law` skill's own description) — an agent could start drafting a file and never separate WHAT (prose) from HOW (a script/hook) until reminded, if ever. These two hooks make it law instead: a nudge before the first Write/Edit + a lint gate after every Edit/Write to the artifact files code-is-law governs.
172
+
173
+ ### code_is_law_prompt_nudge (UserPromptSubmit nudge)
174
+
175
+ **What it does.** On `UserPromptSubmit`, fires via two independent paths: (1) a deterministic regex over qualified Claude-Code-artifact vocabulary — `.agent.md`/`SKILL.md`/`.skill.md` file references, a hook-event name (PreToolUse/PostToolUse/UserPromptSubmit/SessionStart/SessionEnd/PreCompact/Notification/Stop) paired with "hook", "hook" paired with "settings.json", "claude (code) hook", "claude (code) plugin"/`plugin.json`/`marketplace.json`/`.claude/plugins`, or "slash command"/"slash-command"/a `commands/*.md` path — independent of SKILL.md; or (2) every double-quoted phrase parsed live from the `code-is-law` skill's OWN frontmatter `description:` field (single source of truth, same technique as `html_mocker_prompt_nudge.py`) plus a literal `code-is-law` / `/code-is-law` mention. On match, injects an `additionalContext` nudge pointing at `~/.claude/skills/code-is-law/SKILL.md` and its `lint_skill.py`. Bare "hook"/"plugin" are deliberately excluded from path 1 to avoid false-firing on git hooks, React hooks, webhooks, VS Code/WordPress plugins, etc. — they only trigger when qualified. It never denies anything (UserPromptSubmit hooks can't) — only adds context.
176
+
177
+ **Escape hatch.** Fails open (prints nothing, exit 0) if SKILL.md is missing (code-is-law not deployed on this machine), stdin is malformed, the prompt is empty, or any exception fires — never wedges Claude Code.
178
+
179
+ **Manual setup**
180
+
181
+ Wire into UserPromptSubmit in `~/.claude/settings.json` (append alongside any existing UserPromptSubmit hooks — do not replace the array):
182
+
183
+ ```json
184
+ "UserPromptSubmit": [{
185
+ "hooks": [
186
+ {"type": "command", "command": "python C:/Users/<you>/.claude/proxy/code_is_law_prompt_nudge.py"}
187
+ ]
188
+ }]
189
+ ```
190
+
191
+ **Verify**
192
+
193
+ ```bash
194
+ echo '{"hook_event_name":"UserPromptSubmit","prompt":"add a PreToolUse hook that blocks this command"}' | python ~/.claude/proxy/code_is_law_prompt_nudge.py
195
+ echo '{"hook_event_name":"UserPromptSubmit","prompt":"add a webhook for Stripe events"}' | python ~/.claude/proxy/code_is_law_prompt_nudge.py
196
+ ```
197
+
198
+ First emits a JSON `additionalContext` nudge. Second (a deliberately excluded false positive — "webhook" is not "hook") emits empty stdout.
199
+
200
+ ### code_is_law_lint_hook (PostToolUse lint gate)
201
+
202
+ **What it does.** On `PostToolUse` for `Edit`/`Write` to a `SKILL.md`/`.skill.md`/`.agent.md` file, runs `lint_skill.py` against it and, on any finding, blocks with the findings listed. Tests: `proxy/tests/test_code_is_law_prompt_nudge.py` (nudge) — the lint hook itself is exercised via `skills/code-is-law/lint_skill.py`'s own CLI contract.
203
+
204
+ **Manual setup**
205
+
206
+ Wire into PostToolUse in `~/.claude/settings.json`:
207
+
208
+ ```json
209
+ "PostToolUse": [{
210
+ "matcher": "Edit|Write",
211
+ "hooks": [
212
+ {"type": "command", "command": "python C:/Users/<you>/.claude/proxy/code_is_law_lint_hook.py"}
213
+ ]
214
+ }]
215
+ ```
216
+
217
+ **Verify**
218
+
219
+ ```bash
220
+ echo '{"tool_name":"Write","tool_input":{"file_path":"C:/Users/<you>/.claude/skills/some-skill/SKILL.md"}}' | python ~/.claude/proxy/code_is_law_lint_hook.py
221
+ ```
222
+
223
+ Empty stdout / exit 0 on a clean file; findings + exit 2 on a lint failure.
224
+
225
+ ---
226
+
169
227
  ## html_mocker_prompt_nudge + artifact_mocker_gate (code-is-law html-mocker routing)
170
228
 
171
229
  **The problem these two hooks solve.** The `html-mocker` skill (`~/.claude/skills/html-mocker/`) runs a deterministic Playwright layout audit (catches real overflow/clip/overlap bugs) and can open an interactive click-to-annotate review loop. Without enforcement, "mock this up / review this HTML"-shaped requests silently fell back to Claude Code's built-in `Artifact` tool alone — the skill got skipped even though it was deployed. These two hooks make the routing law instead of prose: a nudge at prompt time + a hard gate at Artifact-call time.
@@ -0,0 +1,166 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ code_is_law_prompt_nudge.py — UserPromptSubmit nudge for the code-is-law skill.
4
+
5
+ "Apply code-is-law when building an agent/skill/hook" was only ever prose
6
+ (CLAUDE.md's "Codify Over Instruct" section, code-is-law's own SKILL.md
7
+ description) — advisory, not enforced. An LLM can start drafting a
8
+ SKILL.md/.agent.md/hook/plugin/slash-command and only get corrected
9
+ after-the-fact by code_is_law_lint_hook.py's PostToolUse lint. This hook
10
+ makes the reminder fire BEFORE the first Write/Edit, deterministically, via
11
+ two independent trigger paths, either of which is sufficient:
12
+
13
+ 1. A deterministic regex over Claude-Code-artifact-specific vocabulary,
14
+ independent of SKILL.md: `.agent.md`/`SKILL.md`/`.skill.md` file
15
+ references, a hook-event name (PreToolUse/PostToolUse/UserPromptSubmit/
16
+ SessionStart/SessionEnd/PreCompact/Notification/Stop) paired with the
17
+ word "hook", "hook" paired with "settings.json", "claude (code) hook",
18
+ "claude (code) plugin"/`plugin.json`/`marketplace.json`/`.claude/
19
+ plugins`, or "slash command"/"slash-command"/a `commands/*.md` path.
20
+ Bare "hook" / "plugin" alone are deliberately excluded (see false-positive
21
+ notes below) — they only fire when qualified.
22
+ 2. Phrase matching parsed LIVE from SKILL.md's frontmatter `description:`
23
+ line (double-quoted substrings — same technique as
24
+ html_mocker_prompt_nudge.py's `_trigger_phrases()`, single source of
25
+ truth) plus a case-insensitive literal mention of "code-is-law" /
26
+ "/code-is-law".
27
+
28
+ Deliberately excluded false positives (regex requires a qualifier so these
29
+ do NOT fire): "add a pre-commit git hook", "a React useEffect hook", "add a
30
+ webhook for Stripe events" (word-boundary excludes "webhook" containing
31
+ "hook"), "install a VS Code plugin", "add a WordPress plugin". Known,
32
+ accepted residual false positive: "slash command" alone also describes
33
+ Discord/Slack bot commands — kept broad because this is a nudge (adds
34
+ context only, never denies), so the cost of an occasional irrelevant nudge
35
+ is low.
36
+
37
+ This is a nudge, not a gate: it never denies anything (UserPromptSubmit
38
+ hooks can't). It only adds context. The gate is code_is_law_lint_hook.py
39
+ (PostToolUse on Edit/Write to SKILL.md/.skill.md/.agent.md).
40
+
41
+ Fails open (prints nothing, exit 0) on: SKILL.md missing (code-is-law not
42
+ deployed on this machine), malformed stdin, empty prompt, regex/parse
43
+ failure, or any unexpected exception — never wedge Claude Code.
44
+ """
45
+ from __future__ import annotations
46
+
47
+ import json
48
+ import re
49
+ import sys
50
+ from pathlib import Path
51
+
52
+ SKILL_MD = Path.home() / ".claude" / "skills" / "code-is-law" / "SKILL.md"
53
+
54
+ _NUDGE = (
55
+ "CODE-IS-LAW MATCH: this message matches an intent to author or modify a "
56
+ "Claude Code agent, skill, hook, plugin, or slash command. Before writing "
57
+ "any file, apply the code-is-law principle "
58
+ "(~/.claude/skills/code-is-law/SKILL.md): for each behavior, decide "
59
+ "checkable/correctness-critical (-> a script or hook, wired in "
60
+ "settings.json) vs judgment (-> lean prose, < 100 lines). Then lint "
61
+ "before considering it done: "
62
+ "`python ~/.claude/skills/code-is-law/lint_skill.py <file>`."
63
+ )
64
+
65
+ _PHRASE_RE = re.compile(r'"([^"]+)"')
66
+
67
+ _HOOK_EVENTS = (
68
+ r"PreToolUse|PostToolUse|UserPromptSubmit|SessionStart|SessionEnd|"
69
+ r"PreCompact|Notification|Stop"
70
+ )
71
+
72
+ # Deliberately qualified — bare "hook"/"plugin" alone are excluded (see
73
+ # module docstring for the false-positive cases this rules out).
74
+ _DETERMINISTIC_RE = re.compile(
75
+ r"\.agent\.md\b"
76
+ r"|\bskill\.md\b"
77
+ r"|\.skill\.md\b"
78
+ rf"|\b(?:{_HOOK_EVENTS})\b[^.\n]{{0,30}}\bhooks?\b"
79
+ rf"|\bhooks?\b[^.\n]{{0,30}}\b(?:{_HOOK_EVENTS})\b"
80
+ r"|\bclaude(?:\s*code)?\s+hooks?\b"
81
+ r"|\bhooks?\b[^.\n]{0,20}\bsettings\.json\b"
82
+ r"|\bsettings\.json\b[^.\n]{0,20}\bhooks?\b"
83
+ r"|\bclaude(?:\s*code)?\s+plugins?\b"
84
+ r"|\bplugin\.json\b"
85
+ r"|\bmarketplace\.json\b"
86
+ r"|\.claude[/\\]plugins\b"
87
+ r"|\bslash[- ]commands?\b"
88
+ r"|\bcustom\s+(?:slash\s+)?commands?\b"
89
+ r"|\bcommands?/[\w-]+\.md\b",
90
+ re.IGNORECASE,
91
+ )
92
+
93
+
94
+ def _trigger_phrases() -> list[str]:
95
+ """Parse every double-quoted phrase from SKILL.md's description: line.
96
+
97
+ Single source of truth: as SKILL.md's description evolves, the trigger
98
+ set evolves with it — this script never carries its own hardcoded phrase
99
+ list for the agent/skill/"code is law" wording.
100
+ """
101
+ if not SKILL_MD.exists():
102
+ return []
103
+ try:
104
+ text = SKILL_MD.read_text(encoding="utf-8", errors="ignore")
105
+ except Exception:
106
+ return []
107
+ desc = None
108
+ in_frontmatter = False
109
+ for line in text.splitlines():
110
+ if line.strip() == "---":
111
+ in_frontmatter = not in_frontmatter
112
+ if not in_frontmatter and desc is not None:
113
+ break
114
+ continue
115
+ if in_frontmatter and re.match(r"^description\s*:\s*", line):
116
+ desc = re.sub(r"^description\s*:\s*", "", line, count=1)
117
+ break
118
+ if not desc:
119
+ return []
120
+ return _PHRASE_RE.findall(desc)
121
+
122
+
123
+ def _emit() -> None:
124
+ print(json.dumps({
125
+ "hookSpecificOutput": {
126
+ "hookEventName": "UserPromptSubmit",
127
+ "additionalContext": _NUDGE,
128
+ }
129
+ }))
130
+
131
+
132
+ def _safe_main() -> None:
133
+ try:
134
+ data = json.loads(sys.stdin.read() or "{}")
135
+ except Exception:
136
+ return # bad input — let Claude Code proceed
137
+ if data.get("hook_event_name") != "UserPromptSubmit":
138
+ return
139
+ prompt = (data.get("prompt") or "").strip()
140
+ if not prompt:
141
+ return
142
+
143
+ # Path 1: deterministic, qualified-vocabulary regex — independent of
144
+ # SKILL.md.
145
+ if _DETERMINISTIC_RE.search(prompt):
146
+ _emit()
147
+ return
148
+
149
+ # Path 2: literal skill-name mention or a phrase parsed live from
150
+ # SKILL.md's description.
151
+ prompt_lower = prompt.lower()
152
+ if "code-is-law" in prompt_lower or "/code-is-law" in prompt_lower:
153
+ _emit()
154
+ return
155
+
156
+ for phrase in _trigger_phrases():
157
+ if phrase and phrase.lower() in prompt_lower:
158
+ _emit()
159
+ return
160
+
161
+
162
+ if __name__ == "__main__":
163
+ try:
164
+ _safe_main()
165
+ except Exception:
166
+ pass # never wedge Claude Code
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: code-is-law
3
- description: The principle for deciding what goes in prose vs code when building agents/skills/hooks. Use when designing, writing, or editing any agent (.agent.md) or skill (SKILL.md/.skill.md), wiring a hook, or when the user says "make this a skill/agent", "design an agent", "codify this", "enforce this so it always happens", "code is law", or invokes /code-is-law.
3
+ description: The principle for deciding what goes in prose vs code when building agents/skills/hooks/plugins/slash-commands. Use when designing, writing, or editing any agent (.agent.md), skill (SKILL.md/.skill.md), hook, plugin, or slash command, or when the user says "make this a skill/agent", "design an agent", "codify this", "enforce this so it always happens", "code is law", "build a plugin", "add a slash command", or invokes /code-is-law.
4
4
  ---
5
5
 
6
6
  # Code Is Law
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: ship-the-code
3
- description: Ship a verified fix end-to-end in one deterministic step — sync a global-file change to its deployed ~/.claude/ copy (running install.ps1 for covered categories, flat-copy for hooks/), run the affected tests as a fail-closed gate, commit exactly the named paths (caller authors the message), push, then find-or-create a GitLab tracking issue and append a note with the commit SHA + push status + test summary. Use when the user says "ship this", "ship the code", "land this", "finalize this fix", or invokes /ship-the-code — but ONLY after the diff has been reviewed and tests confirmed green. This script commits and pushes, so invoke it once, not as a routine commit.
3
+ description: Ship a verified fix end-to-end in one deterministic step — sync a global-file change to its deployed ~/.claude/ copy (via `node packages/cli/bin/cli.js update --yes --theirs`, verified against manifest.json's claimed-file map), run the affected tests as a fail-closed gate, commit exactly the named paths (caller authors the message), push, then find-or-create a GitLab tracking issue and append a note with the commit SHA + push status + test summary. Use when the user says "ship this", "ship the code", "land this", "finalize this fix", or invokes /ship-the-code — but ONLY after the diff has been reviewed and tests confirmed green. This script commits and pushes, so invoke it once, not as a routine commit.
4
4
  ---
5
5
 
6
6
  # ship-the-code
@@ -26,7 +26,7 @@ python ~/.claude/skills/ship-the-code/ship.py \
26
26
  --commit-message "<caller-authored message>" \
27
27
  --issue-title "<GitLab issue title>" \
28
28
  --issue-note "<note body>" \
29
- [--issue-labels label...] [--close-issue] [--issue-iid IID] [--skip-tests] [--no-push] [--install-ps1 PATH]
29
+ [--issue-labels label...] [--close-issue] [--issue-iid IID] [--skip-tests] [--no-push] [--cli-js PATH]
30
30
  ```
31
31
 
32
32
  | Arg | Meaning |
@@ -40,12 +40,12 @@ python ~/.claude/skills/ship-the-code/ship.py \
40
40
  | `--issue-iid` | Post directly to this issue IID, bypassing find-or-create search entirely (fails if it doesn't exist). Use when the target issue is already known, to avoid any risk of a title-search misfile. |
41
41
  | `--skip-tests` | Bypass the test gate. Logs a loud warning. |
42
42
  | `--no-push` | Skip `git push`. Default: push IS performed (the point of "ship" is landing on the remote). |
43
- | `--install-ps1` | Override install.ps1 path (default: `<repo>/install.ps1`). |
43
+ | `--cli-js` | Override `packages/cli/bin/cli.js` path (default: `<repo>/packages/cli/bin/cli.js`). |
44
44
 
45
45
  ## What it does, in order
46
46
 
47
47
  1. **Validate** — refuse if any `--files` path has no change in `git status --porcelain`, or if the repo has OTHER uncommitted changes not in `--files`. Never `git add -A`. A rename/copy ("R"/"C" porcelain lines) counts as covered if either its old or new path is named.
48
- 2. **Global sync** — for files under `skills/`/`agents/`/`commands/`/`proxy/`/`scripts/`/`statusline/`, run `install.ps1` (idempotent, owns the authoritative file lists). For `hooks/<subdir>/<file>`, copy flat to `~/.claude/hooks/<file>` (install.ps1 doesn't cover hooks/, and conclusion-scribe's subdir is stripped on deploy). Then byte-compare every touched global file source-vs-deployed — **fail loudly on any mismatch**, never claim "synced" without verifying. A file under an install.ps1-covered category that install.ps1's own file-list array doesn't mention (a repo-only tool with no deployed twin) is warned and skipped, not failed. A deleted source file removes its deployed twin instead of demanding a byte-compare — but only when the twin still matches the last-committed content; a drifted twin is left in place with a warning. No-op (with a warning) if no `--files` path is global.
48
+ 2. **Global sync** — for any `--files` path the manifest CLAIMS (found via `manifest.json`'s bundle/component items, honoring each item's `exclude` list and `targetPath` relocation — e.g. `hooks/conclusion-scribe/*` flattens to `~/.claude/hooks/*`) or lists under `manifest["internal"]`, run `node packages/cli/bin/cli.js update --yes --theirs` (idempotent; `--theirs` resolves any conflict toward the repo source — shipping means the repo wins). Then byte-compare every claimed touched file source-vs-deployed — **fail loudly on any mismatch**, never claim "synced" without verifying. A touched file the manifest doesn't claim (internal, or excluded by an item's own rules) is warned and skipped, not failed. A deleted claimed source file is checked for its deployed twin's removal — the CLI itself already deletes a pristine (unedited) twin during `update`; a twin still present after `update` ran is left in place with a warning (user-edited). No-op (with a warning) if no `--files` path is manifest-relevant.
49
49
  3. **Tests** — walk up from each file to find the nearest `tests/` dir or sibling `test_*.py`. Run `pytest` once per unique target. Fail-closed: a failed test run blocks the commit. Missing coverage is an explicit warning, not a silent pass. `--skip-tests` overrides (loud).
50
50
  4. **Commit** — `git add` exactly `--files`, commit with the verbatim message. Returns the SHA.
51
51
  5. **Push** — `git push` the current branch (unless `--no-push`).