tersely 0.0.1__py3-none-any.whl

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.
Files changed (36) hide show
  1. tersely/__init__.py +2 -0
  2. tersely/cli.py +644 -0
  3. tersely/data/ai/agents/comment-reviewer.md +20 -0
  4. tersely/data/ai/skills/tersely/SKILL.md +181 -0
  5. tersely/data/vale/Tersely/Ambiguity.yml +16 -0
  6. tersely/data/vale/Tersely/Anthropomorphism.yml +21 -0
  7. tersely/data/vale/Tersely/Assistant.yml +21 -0
  8. tersely/data/vale/Tersely/British.yml +11 -0
  9. tersely/data/vale/Tersely/Ceremony.yml +32 -0
  10. tersely/data/vale/Tersely/Contractions.yml +14 -0
  11. tersely/data/vale/Tersely/EmDash.yml +8 -0
  12. tersely/data/vale/Tersely/EmptyQualifiers.yml +21 -0
  13. tersely/data/vale/Tersely/Headers.yml +22 -0
  14. tersely/data/vale/Tersely/Hedging.yml +24 -0
  15. tersely/data/vale/Tersely/Metaphor.yml +48 -0
  16. tersely/data/vale/Tersely/Modals.yml +14 -0
  17. tersely/data/vale/Tersely/NegativeParallelism.yml +22 -0
  18. tersely/data/vale/Tersely/Overused.yml +47 -0
  19. tersely/data/vale/Tersely/PassiveVoice.yml +14 -0
  20. tersely/data/vale/Tersely/PhrasalVerbs.yml +113 -0
  21. tersely/data/vale/Tersely/RestatesCode.yml +24 -0
  22. tersely/data/vale/Tersely/SelfPraise.yml +24 -0
  23. tersely/data/vale/Tersely/Semicolon.yml +9 -0
  24. tersely/data/vale/Tersely/SentenceLength.yml +8 -0
  25. tersely/data/vale/Tersely/Transitions.yml +13 -0
  26. tersely/data/vale/Tersely/Tricolon.yml +13 -0
  27. tersely/data/vale/Tersely/VagueReasons.yml +19 -0
  28. tersely/data/vale/Tersely/Vocabulary.yml +48 -0
  29. tersely/lint_comments.py +820 -0
  30. tersely-0.0.1.dist-info/METADATA +345 -0
  31. tersely-0.0.1.dist-info/RECORD +36 -0
  32. tersely-0.0.1.dist-info/WHEEL +4 -0
  33. tersely-0.0.1.dist-info/entry_points.txt +3 -0
  34. tersely-0.0.1.dist-info/licenses/LICENSE +21 -0
  35. tersely-0.0.1.dist-info/licenses/LICENSES/MIT.txt +21 -0
  36. tersely-0.0.1.dist-info/licenses/NOTICE +32 -0
tersely/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """Tersely custom comment linter and CLI package."""
tersely/cli.py ADDED
@@ -0,0 +1,644 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """Unified CLI for tersely: sync Vale, lint comments/prose, check commit messages, or initialize a project."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import platform
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+ import tarfile
16
+ import tempfile
17
+ import tomllib
18
+ import urllib.request
19
+ import zipfile
20
+ from importlib.metadata import PackageNotFoundError, version
21
+ from pathlib import Path
22
+
23
+ VALE_VERSION = "3.29.0"
24
+ VALE_SHA256 = {
25
+ "vale_3.29.0_Linux_64-bit.tar.gz": "00356ae1bacd1160aa415664f3ed0d34ce9ef5319c61d31123a97366ea1a2f64",
26
+ "vale_3.29.0_Linux_arm64.tar.gz": "ffff63b3aaf97ca3c7e0a0c5226a8ddf7c21f21f1695e40461b0037d2189ba74",
27
+ "vale_3.29.0_macOS_64-bit.tar.gz": "5c983d634074ea0a7a9b40e6450dff1035f2b406a3f79b130ec4cddd8ff14675",
28
+ "vale_3.29.0_macOS_arm64.tar.gz": "62b0eb911aa9255ad4520afa5284d0b8a27f11eea5ffe40390a1eaaca9baab73",
29
+ "vale_3.29.0_Windows_64-bit.zip": "5977efcb833248b69c870759c74d368cdaf8845103ac59b986cad1467affc1a0",
30
+ "vale_3.29.0_Windows_arm64.zip": "139641ed5ef31b6a4b05b93570aa1be4246e64816c55fe20724abd07821d2c7c",
31
+ }
32
+ PLATFORMS = ("claude", "codex", "antigravity")
33
+ DEFAULT_REVIEWER_MODELS = {
34
+ "claude": "haiku",
35
+ "codex": "gpt-6-luna",
36
+ "antigravity": "inherit",
37
+ }
38
+ DEFAULT_REASONING_EFFORT = {
39
+ "codex": "low",
40
+ }
41
+ STOP_HOOK_ARGS = "lint comments --hook claude"
42
+ CODE_GLOB = "*.{py,rs,c,h,cpp,hpp,cc,cxx,hh,hxx,go,ts,tsx,mts,cts,js,jsx,mjs,cjs,java,kt,kts,cs,swift,scala,rb,lua}"
43
+
44
+
45
+ def pkg_version() -> str:
46
+ """Return the version of Tersely.
47
+ If Tersely is not installed, read `[project] version` from the `pyproject.toml` of the source.
48
+ Raise RuntimeError if neither gives a version."""
49
+ try:
50
+ return version("tersely")
51
+ except PackageNotFoundError:
52
+ pass
53
+ path = data_root() / "pyproject.toml"
54
+ try:
55
+ found = tomllib.loads(path.read_text(encoding="utf-8"))["project"]["version"]
56
+ except (OSError, KeyError, TypeError, tomllib.TOMLDecodeError) as err:
57
+ raise RuntimeError(f"cannot find the version of tersely: it is not installed, and {path} has none") from err
58
+ if not isinstance(found, str):
59
+ raise RuntimeError(f"cannot find the version of tersely: [project] version in {path} is not a string")
60
+ return found
61
+
62
+
63
+ def vale_cache_dir() -> Path:
64
+ base = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache"))
65
+ return base / "tersely" / "vale" / VALE_VERSION
66
+
67
+
68
+ def cached_vale_bin() -> Path:
69
+ exe = "vale.exe" if platform.system() == "Windows" else "vale"
70
+ return vale_cache_dir() / exe
71
+
72
+
73
+ def find_vale() -> str | None:
74
+ on_path = shutil.which("vale")
75
+ if on_path:
76
+ return on_path
77
+ cached = cached_vale_bin()
78
+ if cached.is_file():
79
+ return str(cached)
80
+ return None
81
+
82
+
83
+ def vale_platform_asset() -> tuple[str, str]:
84
+ sys_name = platform.system()
85
+ machine = platform.machine().lower()
86
+ if machine in ("x86_64", "amd64"):
87
+ arch = "64-bit"
88
+ elif machine in ("arm64", "aarch64"):
89
+ arch = "arm64"
90
+ else:
91
+ raise RuntimeError(f"unsupported architecture for Vale download: {sys_name} {machine}")
92
+ if sys_name == "Linux":
93
+ return f"vale_{VALE_VERSION}_Linux_{arch}.tar.gz", "tar.gz"
94
+ if sys_name == "Darwin":
95
+ return f"vale_{VALE_VERSION}_macOS_{arch}.tar.gz", "tar.gz"
96
+ if sys_name == "Windows":
97
+ return f"vale_{VALE_VERSION}_Windows_{arch}.zip", "zip"
98
+ raise RuntimeError(f"unsupported platform for Vale download: {sys_name} {machine}")
99
+
100
+
101
+ def install_vale(force: bool = False) -> Path:
102
+ dest = cached_vale_bin()
103
+ if dest.is_file() and not force:
104
+ return dest
105
+ asset, kind = vale_platform_asset()
106
+ expected_sha = VALE_SHA256[asset]
107
+ url = f"https://github.com/errata-ai/vale/releases/download/v{VALE_VERSION}/{asset}"
108
+ dest.parent.mkdir(parents=True, exist_ok=True)
109
+ # Stage next to dest, so the final replace stays on one filesystem and is atomic.
110
+ with tempfile.TemporaryDirectory(dir=dest.parent) as tmp:
111
+ tmp_dir = Path(tmp)
112
+ archive = tmp_dir / asset
113
+ with urllib.request.urlopen(url, timeout=30) as resp:
114
+ data = resp.read()
115
+ actual_sha = hashlib.sha256(data).hexdigest()
116
+ if actual_sha != expected_sha:
117
+ raise RuntimeError(f"SHA-256 mismatch for {asset}: expected {expected_sha}, got {actual_sha}")
118
+ archive.write_bytes(data)
119
+ exe_name = "vale.exe" if kind == "zip" else "vale"
120
+ if kind == "tar.gz":
121
+ with tarfile.open(archive, "r:gz") as tf:
122
+ if sys.version_info >= (3, 12):
123
+ tf.extract(exe_name, path=tmp_dir, filter="data")
124
+ else:
125
+ tf.extract(exe_name, path=tmp_dir)
126
+ else:
127
+ with zipfile.ZipFile(archive) as zf:
128
+ zf.extract(exe_name, path=tmp_dir)
129
+ staged = tmp_dir / exe_name
130
+ if platform.system() != "Windows":
131
+ staged.chmod(0o755)
132
+ staged.replace(dest)
133
+ return dest
134
+
135
+
136
+ def vale_ini_text(styles_path: str, min_alert_level: str, packages: str | None = None) -> str:
137
+ pkg_line = f"Packages = {packages}\n" if packages else ""
138
+ return (
139
+ f"StylesPath = {styles_path}\n"
140
+ f"MinAlertLevel = {min_alert_level}\n"
141
+ f"{pkg_line}\n"
142
+ "[*.md]\n"
143
+ "BasedOnStyles = Tersely\n\n"
144
+ f"[{CODE_GLOB}]\n"
145
+ "BasedOnStyles = Tersely\n"
146
+ "Tersely.SentenceLength = NO\n"
147
+ "Tersely.Semicolon = NO\n"
148
+ "Tersely.British = NO\n"
149
+ "Tersely.Modals = NO\n"
150
+ )
151
+
152
+
153
+ def data_root() -> Path:
154
+ packaged = Path(__file__).resolve().parent / "data"
155
+ if packaged.is_dir():
156
+ return packaged
157
+ return Path(__file__).resolve().parents[2]
158
+
159
+
160
+ def render_skill(template: str, platform_name: str, model: str) -> str:
161
+ if platform_name == "claude":
162
+ step = (
163
+ f" - Start the `comment-reviewer` subagent with `model: {model}` and the template below.\n"
164
+ " If Tersely is installed as a plugin, start `tersely:comment-reviewer` instead.\n"
165
+ " Its cost is small, so it needs no separate approval."
166
+ )
167
+ else:
168
+ step = (
169
+ " - If a `comment-reviewer` subagent is available, start it with the template below.\n"
170
+ " Otherwise, read the rule files again and do a second full pass over the batch."
171
+ )
172
+ return template.replace("{{REVIEWER_STEP}}", step)
173
+
174
+
175
+ def skill_dest(platform_name: str, skill_name: str) -> Path:
176
+ """Return the path of a skill under the project root.
177
+ Codex and Antigravity read the same file, so they share one path."""
178
+ folder = ".claude" if platform_name == "claude" else ".agents"
179
+ return Path(folder) / "skills" / skill_name / "SKILL.md"
180
+
181
+
182
+ def agent_dest(platform_name: str, agent_name: str) -> Path:
183
+ """Return the path of a subagent file under the project root."""
184
+ if platform_name == "codex":
185
+ return Path(".codex") / "agents" / f"{agent_name}.toml"
186
+ folder = ".claude" if platform_name == "claude" else ".agents"
187
+ return Path(folder) / "agents" / f"{agent_name}.md"
188
+
189
+
190
+ def toml_basic_string(text: str) -> str:
191
+ """Return `text` as a TOML basic string on one line."""
192
+ out: list[str] = []
193
+ for ch in text:
194
+ if ch in '"\\':
195
+ out.append("\\" + ch)
196
+ elif ord(ch) < 0x20 or ord(ch) == 0x7F:
197
+ out.append({"\n": "\\n", "\t": "\\t", "\r": "\\r"}.get(ch, f"\\u{ord(ch):04x}"))
198
+ else:
199
+ out.append(ch)
200
+ return '"' + "".join(out) + '"'
201
+
202
+
203
+ def toml_multiline_string(text: str) -> str:
204
+ """Return `text` as a TOML multi-line basic string that starts on its own line."""
205
+ out: list[str] = []
206
+ for ch in text:
207
+ if ch == "\\":
208
+ out.append("\\\\")
209
+ elif ch == "\n" or ch == "\t":
210
+ out.append(ch)
211
+ elif ord(ch) < 0x20 or ord(ch) == 0x7F:
212
+ out.append("\\r" if ch == "\r" else f"\\u{ord(ch):04x}")
213
+ else:
214
+ out.append(ch)
215
+ body = "".join(out).replace('"""', '""\\"')
216
+ if body.endswith('"'):
217
+ body = body[:-1] + '\\"'
218
+ return '"""\n' + body + '"""'
219
+
220
+
221
+ def split_agent_template(template: str) -> tuple[dict[str, str], str]:
222
+ """Split the template of an agent into the keys of its frontmatter and its body."""
223
+ parts = template.split("---\n", 2)
224
+ if len(parts) != 3 or parts[0] != "":
225
+ raise ValueError("the agent template has no frontmatter")
226
+ keys: dict[str, str] = {}
227
+ for line in parts[1].splitlines():
228
+ key, _, value = line.partition(":")
229
+ keys[key.strip()] = value.strip()
230
+ return keys, parts[2].lstrip("\n")
231
+
232
+
233
+ def render_agent(template: str, platform_name: str, model: str, effort: str | None = None) -> str:
234
+ """Render the reviewer agent for a platform.
235
+ Claude and Antigravity get Markdown with the model set.
236
+ The Antigravity copy has no `tools` key, because its format is not documented.
237
+ Codex gets a TOML file with the body as `developer_instructions`.
238
+ A Codex file cannot make the agent read-only, so the body must forbid edits."""
239
+ if platform_name == "codex":
240
+ keys, body = split_agent_template(template)
241
+ effort = effort or DEFAULT_REASONING_EFFORT["codex"]
242
+ return (
243
+ f"name = {toml_basic_string(keys['name'])}\n"
244
+ f"description = {toml_basic_string(keys['description'])}\n"
245
+ f"model = {toml_basic_string(model)}\n"
246
+ f"model_reasoning_effort = {toml_basic_string(effort)}\n"
247
+ f"developer_instructions = {toml_multiline_string(body)}\n"
248
+ )
249
+ lines: list[str] = []
250
+ for line in template.splitlines(keepends=True):
251
+ if line.startswith("model:"):
252
+ lines.append(f"model: {model}\n")
253
+ elif not (line.startswith("tools:") and platform_name == "antigravity"):
254
+ lines.append(line)
255
+ return "".join(lines)
256
+
257
+
258
+ def stop_hook_command(tersely_version: str) -> str:
259
+ return f"uvx tersely@{tersely_version} {STOP_HOOK_ARGS}"
260
+
261
+
262
+ def stop_hook_entry(tersely_version: str) -> dict[str, object]:
263
+ return {"hooks": [{"type": "command", "command": stop_hook_command(tersely_version)}]}
264
+
265
+
266
+ def is_tersely_hook(command: object) -> bool:
267
+ return isinstance(command, str) and command.startswith("uvx tersely@") and command.endswith(STOP_HOOK_ARGS)
268
+
269
+
270
+ def detect_indent(text: str) -> str | int:
271
+ """Return the indent of the first indented line, or 2 if no line is indented."""
272
+ match = re.search(r"^([ \t]+)\S", text, re.MULTILINE)
273
+ return match.group(1) if match else 2
274
+
275
+
276
+ def merge_stop_hook(settings_path: Path, tersely_version: str) -> str:
277
+ """Add the Stop hook to a settings file and keep every other key and hook.
278
+ A hook of Tersely with another version gets the new command in place.
279
+ The file never holds two hooks of Tersely.
280
+ Raise ValueError if the file holds bad settings."""
281
+ command = stop_hook_command(tersely_version)
282
+ settings: object = {}
283
+ indent: str | int = 2
284
+ created = not settings_path.is_file()
285
+ if not created:
286
+ text = settings_path.read_text(encoding="utf-8")
287
+ indent = detect_indent(text)
288
+ try:
289
+ settings = json.loads(text)
290
+ except json.JSONDecodeError as err:
291
+ raise ValueError(f"{settings_path} is not valid JSON ({err}); it is not changed") from err
292
+ if not isinstance(settings, dict):
293
+ raise ValueError(f"{settings_path} does not hold a JSON object; it is not changed")
294
+ hooks = settings.setdefault("hooks", {})
295
+ if not isinstance(hooks, dict):
296
+ raise ValueError(f'"hooks" of {settings_path} is not an object; it is not changed')
297
+ stops = hooks.setdefault("Stop", [])
298
+ if not isinstance(stops, list):
299
+ raise ValueError(f'"hooks.Stop" of {settings_path} is not a list; it is not changed')
300
+ changed = False
301
+ found = False
302
+ kept: list[object] = []
303
+ for group in stops:
304
+ inner = group.get("hooks") if isinstance(group, dict) else None
305
+ if not isinstance(inner, list):
306
+ kept.append(group)
307
+ continue
308
+ entries: list[object] = []
309
+ for hook in inner:
310
+ if not isinstance(hook, dict) or not is_tersely_hook(hook.get("command")):
311
+ entries.append(hook)
312
+ elif not found:
313
+ found = True
314
+ if hook["command"] != command:
315
+ hook["command"] = command
316
+ changed = True
317
+ entries.append(hook)
318
+ else:
319
+ changed = True
320
+ if entries or not inner:
321
+ group["hooks"] = entries
322
+ kept.append(group)
323
+ if not found:
324
+ kept.append(stop_hook_entry(tersely_version))
325
+ elif not changed:
326
+ return "skipped (hook exists)"
327
+ status = "updated" if found else "merged"
328
+ stops[:] = kept
329
+ settings_path.parent.mkdir(parents=True, exist_ok=True)
330
+ settings_path.write_text(json.dumps(settings, indent=indent, ensure_ascii=False) + "\n", encoding="utf-8")
331
+ return "created" if created else status
332
+
333
+
334
+ def run_lint_comments(args: argparse.Namespace) -> int:
335
+ from tersely import lint_comments
336
+
337
+ comments_argv: list[str] = []
338
+ if getattr(args, "all", False):
339
+ comments_argv.append("--all")
340
+ if getattr(args, "base", None):
341
+ comments_argv.extend(["--base", args.base])
342
+ for pat in getattr(args, "exclude", []):
343
+ comments_argv.extend(["--exclude", pat])
344
+ if getattr(args, "hook", None):
345
+ comments_argv.extend(["--hook", args.hook])
346
+ comments_argv.extend(getattr(args, "paths", []))
347
+
348
+ old_argv = sys.argv
349
+ try:
350
+ sys.argv = ["lint-comments", *comments_argv]
351
+ return lint_comments.main()
352
+ finally:
353
+ sys.argv = old_argv
354
+
355
+
356
+ def run_lint_vale(args: argparse.Namespace) -> int:
357
+ vale_bin = find_vale()
358
+ if not vale_bin:
359
+ print("error: vale not found; run `tersely vale sync` first.", file=sys.stderr)
360
+ return 1
361
+ vale_targets = getattr(args, "paths", []) or ["."]
362
+ local_ini = Path(".vale.ini")
363
+ if local_ini.is_file() and "Tersely" in local_ini.read_text(encoding="utf-8", errors="ignore"):
364
+ cmd = [vale_bin]
365
+ if getattr(args, "min_alert_level", None):
366
+ cmd.extend(["--minAlertLevel", args.min_alert_level])
367
+ proc = subprocess.run([*cmd, *vale_targets], check=False)
368
+ return 1 if proc.returncode != 0 else 0
369
+
370
+ vale_styles = data_root() / "vale"
371
+ level = getattr(args, "min_alert_level", None) or "error"
372
+ with tempfile.TemporaryDirectory() as tmp:
373
+ ini_path = Path(tmp) / ".vale.ini"
374
+ ini_path.write_text(vale_ini_text(str(vale_styles), level), encoding="utf-8")
375
+ proc = subprocess.run([vale_bin, "--config", str(ini_path), *vale_targets], check=False)
376
+ return 1 if proc.returncode != 0 else 0
377
+
378
+
379
+ def cmd_lint_all(args: argparse.Namespace) -> int:
380
+ rc_comments = run_lint_comments(args)
381
+ if getattr(args, "hook", None) or getattr(args, "no_vale", False):
382
+ return rc_comments
383
+ vale_bin = find_vale()
384
+ if not vale_bin:
385
+ print("note: vale not found; run `tersely vale sync` to enable Vale checks.", file=sys.stderr)
386
+ return rc_comments
387
+ rc_vale = run_lint_vale(args)
388
+ return 1 if (rc_comments != 0 or rc_vale != 0) else 0
389
+
390
+
391
+ def cmd_vale_sync(args: argparse.Namespace) -> int:
392
+ vale_bin = find_vale()
393
+ if not vale_bin or args.force:
394
+ vale_bin = str(install_vale(force=args.force))
395
+ print(f"vale: installed at {vale_bin}")
396
+ else:
397
+ print(f"vale: using {vale_bin}")
398
+ if Path(".vale.ini").is_file():
399
+ proc = subprocess.run([vale_bin, "sync"], check=False)
400
+ return proc.returncode
401
+ return 0
402
+
403
+
404
+ def write_if_missing(dest: Path, content: str, force: bool) -> str:
405
+ if dest.exists() and not force:
406
+ return "skipped (exists)"
407
+ dest.parent.mkdir(parents=True, exist_ok=True)
408
+ dest.write_text(content, encoding="utf-8")
409
+ return "written"
410
+
411
+
412
+ def cmd_init(args: argparse.Namespace) -> int:
413
+ if args.agent == "all" and args.reviewer_model:
414
+ print("error: --reviewer-model needs one platform; run `init` once per --agent", file=sys.stderr)
415
+ return 1
416
+ root = Path(args.dir).resolve()
417
+ src_data = data_root()
418
+ platforms = list(PLATFORMS) if args.agent == "all" else [args.agent]
419
+
420
+ exit_code = 0
421
+ if "claude" in platforms and not args.no_hook:
422
+ settings = root / ".claude" / "settings.json"
423
+ try:
424
+ status = merge_stop_hook(settings, pkg_version())
425
+ except (ValueError, RuntimeError) as err:
426
+ print(f"error: {err}", file=sys.stderr)
427
+ exit_code = 1
428
+ else:
429
+ print(f"{settings.relative_to(root)}: {status}")
430
+
431
+ skill_tpl = (src_data / "ai" / "skills" / "tersely" / "SKILL.md").read_text(encoding="utf-8")
432
+ agent_tpl = (src_data / "ai" / "agents" / "comment-reviewer.md").read_text(encoding="utf-8")
433
+ written: set[Path] = set()
434
+ for p_name in platforms:
435
+ model = args.reviewer_model or DEFAULT_REVIEWER_MODELS[p_name]
436
+ files = {
437
+ skill_dest(p_name, "tersely"): render_skill(skill_tpl, p_name, model),
438
+ agent_dest(p_name, "comment-reviewer"): render_agent(agent_tpl, p_name, model),
439
+ }
440
+ for rel, content in files.items():
441
+ if rel in written:
442
+ continue
443
+ written.add(rel)
444
+ print(f"{rel}: {write_if_missing(root / rel, content, args.force)}")
445
+
446
+ if not args.no_vale_ini:
447
+ vale_ini = root / ".vale.ini"
448
+ ini_content = vale_ini_text(
449
+ "styles",
450
+ "warning",
451
+ "https://github.com/Lynth-KR/tersely/releases/latest/download/Tersely.zip",
452
+ )
453
+ print(f".vale.ini: {write_if_missing(vale_ini, ini_content, args.force)}")
454
+ return exit_code
455
+
456
+
457
+ def git_trailers(lines: list[str]) -> set[str]:
458
+ """Returns the trailers that git finds in the message, each unfolded onto one line.
459
+ Returns no trailer if git is not available."""
460
+ try:
461
+ proc = subprocess.run(
462
+ ["git", "interpret-trailers", "--parse"],
463
+ input="\n".join(lines) + "\n",
464
+ capture_output=True,
465
+ text=True,
466
+ check=False,
467
+ )
468
+ except OSError:
469
+ return set()
470
+ if proc.returncode != 0:
471
+ return set()
472
+ return {line.rstrip() for line in proc.stdout.splitlines() if line.strip()}
473
+
474
+
475
+ DEFAULT_TRAILER_KEYS = frozenset(
476
+ key.lower()
477
+ for key in ("Change-Id", "Fixes", "Closes", "Resolves", "Refs", "See-also", "Cc", "Bug", "Link", "Issue", "Ticket")
478
+ )
479
+
480
+
481
+ def is_known_trailer_key(key: str, extra: frozenset[str]) -> bool:
482
+ """A key is known if it ends in `-by`, is in the default list, or is in the configured keys.
483
+ The comparison ignores case, and `extra` holds lower case keys."""
484
+ lowered = key.strip().lower()
485
+ return lowered.endswith("-by") or lowered in DEFAULT_TRAILER_KEYS or lowered in extra
486
+
487
+
488
+ def strip_trailers(lines: list[str], extra: frozenset[str] = frozenset()) -> list[str]:
489
+ """Removes the trailers from the last paragraph of the message.
490
+ A line is a trailer if git reports it as one and its key is known.
491
+ A continuation line stays with its trailer."""
492
+ if "" not in lines:
493
+ return lines
494
+ trailers = git_trailers(lines)
495
+ if not trailers:
496
+ return lines
497
+ start = len(lines) - lines[::-1].index("")
498
+ entries: list[list[str]] = []
499
+ for line in lines[start:]:
500
+ if line[:1] in (" ", "\t") and entries:
501
+ entries[-1].append(line)
502
+ else:
503
+ entries.append([line])
504
+
505
+ def is_trailer(entry: list[str]) -> bool:
506
+ return " ".join(part.strip() for part in entry) in trailers and is_known_trailer_key(
507
+ entry[0].partition(":")[0], extra
508
+ )
509
+
510
+ kept = [e for e in entries if not is_trailer(e)]
511
+ rest = lines[:start] + [line for e in kept for line in e]
512
+ while rest and not rest[-1].strip():
513
+ rest.pop()
514
+ return rest
515
+
516
+
517
+ def clean_commit_message(raw: str, extra_trailers: frozenset[str] = frozenset()) -> str:
518
+ lines: list[str] = []
519
+ for line in raw.splitlines():
520
+ if line.startswith("# ------------------------ >8 ------------------------"):
521
+ break
522
+ if line.startswith("#"):
523
+ continue
524
+ lines.append(line)
525
+ while lines and not lines[-1].strip():
526
+ lines.pop()
527
+ lines = strip_trailers(lines, extra_trailers)
528
+ if lines:
529
+ lines[0] = re.sub(r"^[A-Za-z][A-Za-z0-9_-]{1,15}(?:\([^)]+\))?!?:\s*", "", lines[0])
530
+ return "\n".join(lines).strip() + "\n"
531
+
532
+
533
+ def configured_trailers() -> frozenset[str]:
534
+ """Reads `[tool.tersely] trailers` from the `pyproject.toml` at the repository root.
535
+ Outside a repository, it returns no keys.
536
+ Raise ValueError if the value is not a list of strings."""
537
+ from tersely import lint_comments
538
+
539
+ root = lint_comments.git_root()
540
+ if root is None:
541
+ return frozenset()
542
+ return frozenset(key.strip().lower() for key in lint_comments.pyproject_list(root, "trailers"))
543
+
544
+
545
+ def cmd_check_msg(args: argparse.Namespace) -> int:
546
+ try:
547
+ extra_trailers = configured_trailers()
548
+ except ValueError as err:
549
+ print(f"error: {err}", file=sys.stderr)
550
+ return 2
551
+ vale_bin = find_vale()
552
+ if not vale_bin:
553
+ print("error: vale not found; run `tersely vale sync` first.", file=sys.stderr)
554
+ return 1
555
+ raw = Path(args.file).read_text(encoding="utf-8")
556
+ cleaned = clean_commit_message(raw, extra_trailers)
557
+ if not cleaned.strip():
558
+ return 0
559
+ vale_styles = data_root() / "vale"
560
+ with tempfile.TemporaryDirectory() as tmp:
561
+ ini_path = Path(tmp) / ".vale.ini"
562
+ msg_path = Path(tmp) / "COMMIT_MSG.md"
563
+ ini_path.write_text(
564
+ f"StylesPath = {vale_styles}\nMinAlertLevel = {args.min_alert_level}\n\n[*.md]\nBasedOnStyles = Tersely\n",
565
+ encoding="utf-8",
566
+ )
567
+ msg_path.write_text(cleaned, encoding="utf-8")
568
+ proc = subprocess.run([vale_bin, "--config", str(ini_path), str(msg_path)], check=False)
569
+ return 1 if proc.returncode != 0 else 0
570
+
571
+
572
+ def add_comments_args(p: argparse.ArgumentParser) -> None:
573
+ p.add_argument("--all", action="store_true", help="Check all comments, not only added lines.")
574
+ p.add_argument("--base", help="Check changes since merge base with this commit.")
575
+ p.add_argument("--exclude", action="append", default=[], help="Glob pattern to exclude.")
576
+ p.add_argument("--hook", nargs="?", const="claude", choices=["claude", "generic"], help="Run as an agent hook.")
577
+
578
+
579
+ def main() -> int:
580
+ parser = argparse.ArgumentParser(prog="tersely", description="Terse, unambiguous English linter and skills CLI.")
581
+ try:
582
+ shown_version = pkg_version()
583
+ except RuntimeError:
584
+ shown_version = "unknown"
585
+ parser.add_argument("--version", action="version", version=f"%(prog)s {shown_version}")
586
+ sub = parser.add_subparsers(dest="command", required=True)
587
+
588
+ p_lint = sub.add_parser("lint", help="Run tersely linters.")
589
+ lint_sub = p_lint.add_subparsers(dest="lint_target", required=True)
590
+
591
+ p_lc = lint_sub.add_parser("comments", help="Run structural comment linter.")
592
+ add_comments_args(p_lc)
593
+ p_lc.add_argument("paths", nargs="*", help="Files or folders to check.")
594
+ p_lc.set_defaults(func=run_lint_comments)
595
+
596
+ p_lv = lint_sub.add_parser("vale", help="Run Vale Tersely rules.")
597
+ p_lv.add_argument("--min-alert-level", default=None, choices=["suggestion", "warning", "error"])
598
+ p_lv.add_argument("paths", nargs="*", help="Files or folders to check.")
599
+ p_lv.set_defaults(func=run_lint_vale)
600
+
601
+ p_la = lint_sub.add_parser("all", help="Run both lint-comments and Vale.")
602
+ add_comments_args(p_la)
603
+ p_la.add_argument("--no-vale", action="store_true", help="Skip Vale checks.")
604
+ p_la.add_argument("--min-alert-level", default=None, choices=["suggestion", "warning", "error"])
605
+ p_la.add_argument("paths", nargs="*", help="Files or folders to check.")
606
+ p_la.set_defaults(func=cmd_lint_all)
607
+
608
+ p_vale = sub.add_parser("vale", help="Manage Vale binary and packages.")
609
+ vale_sub = p_vale.add_subparsers(dest="vale_action", required=True)
610
+ p_vs = vale_sub.add_parser("sync", help="Install Vale into cache if needed and run `vale sync`.")
611
+ p_vs.add_argument("--force", action="store_true", help="Re-download Vale binary even if cached.")
612
+ p_vs.set_defaults(func=cmd_vale_sync)
613
+
614
+ p_check = sub.add_parser("check", help="Alias for `tersely lint all`.")
615
+ add_comments_args(p_check)
616
+ p_check.add_argument("--no-vale", action="store_true", help="Skip Vale checks.")
617
+ p_check.add_argument("--min-alert-level", default=None, choices=["suggestion", "warning", "error"])
618
+ p_check.add_argument("paths", nargs="*", help="Files or folders to check.")
619
+ p_check.set_defaults(func=cmd_lint_all)
620
+
621
+ p_init = sub.add_parser(
622
+ "init", help="Install tersely skills, agents, the Claude Code Stop hook and .vale.ini into a project."
623
+ )
624
+ p_init.add_argument("--agent", default="claude", choices=[*PLATFORMS, "all"])
625
+ p_init.add_argument("--reviewer-model", help="Override the reviewer subagent model. Not allowed with --agent all.")
626
+ p_init.add_argument("--dir", default=".", help="Target project directory.")
627
+ p_init.add_argument("--no-vale-ini", action="store_true", help="Do not create .vale.ini.")
628
+ p_init.add_argument("--no-hook", action="store_true", help="Do not add the Stop hook to .claude/settings.json.")
629
+ p_init.add_argument("--force", action="store_true", help="Overwrite existing files.")
630
+ p_init.set_defaults(func=cmd_init)
631
+
632
+ p_msg = sub.add_parser(
633
+ "check-msg", help="Check a commit message file against Tersely rules, except its known trailers."
634
+ )
635
+ p_msg.add_argument("file", help="Path to the commit message file (e.g., .git/COMMIT_EDITMSG).")
636
+ p_msg.add_argument("--min-alert-level", default="error", choices=["suggestion", "warning", "error"])
637
+ p_msg.set_defaults(func=cmd_check_msg)
638
+
639
+ args = parser.parse_args()
640
+ return args.func(args)
641
+
642
+
643
+ if __name__ == "__main__":
644
+ raise SystemExit(main())
@@ -0,0 +1,20 @@
1
+ ---
2
+ name: comment-reviewer
3
+ description: Reviews code comment batches for tersely form compliance.
4
+ model: haiku
5
+ tools: Read
6
+ ---
7
+
8
+ You review code comments for tersely form rules (project rules override defaults).
9
+ Judge the comments and the code that the prompt gives you.
10
+ Do not read the file from disk to find the comments, because the prompt can hold text that is not on disk yet.
11
+ Read a file only if the prompt lacks the code that you need to judge a comment.
12
+ Never edit a file.
13
+ The rules:
14
+ - Active voice where an agent is clear (note passive voice only when an active subject improves clarity without coupling to callers).
15
+ - Allowed modal verbs only (`can`, `will`, `must`).
16
+ - American spelling, no contractions, no semicolons, no em dashes, no idiomatic phrasal verbs.
17
+ - One fact per sentence, condition before statement, and at most 25 words per sentence.
18
+
19
+ Write each finding as: `file:line | rule | fix`.
20
+ If all comments pass, reply `PASS`.