ThomasMoreAI/legal-skills-open / au/general/skills/legal-writing-mblauberg
legal-writing-mblauberg
VerifiedUse for drafting, reviewing, condensing, or source-checking Australian legal documents (forms, affidavits, submissions and orders), legal decision overviews, or correspondence. Not for academic, engineering, or general prose; use its specialist.
scripts/lint_legal_style.py
View on GitHub#!/usr/bin/env python3
"""Lightweight style lint for Australian filing-facing legal markdown.
This checker keeps its own FAIL/WARN severity model and structural checks
(heading-blank-line, HTML-comment leak tokens, long-sentence detection,
directory recursion) because they are legal-specific and have no equivalent
in natural-writing or engineering-writing. It imports the shared word
vocabulary from the `natural-writing`-owned engine
(`skills/natural-writing/scripts/style_lint.py`) for the regex content that
used to be hand-duplicated across all three domain checkers (em dash,
puffery/inflation vocabulary, wordy fillers, -ly-adverb hyphenation) rather
than re-typing those word lists a third time.
"""
from __future__ import annotations
import argparse
import importlib.util
import os
import re
import sys
from pathlib import Path
_STYLE_LINT_PATH = Path(__file__).resolve().parents[2] / "natural-writing" / "scripts" / "style_lint.py"
_spec = importlib.util.spec_from_file_location("style_lint", _STYLE_LINT_PATH)
assert _spec and _spec.loader
style_lint = importlib.util.module_from_spec(_spec)
sys.modules.setdefault("style_lint", style_lint)
_spec.loader.exec_module(style_lint)
# Legal-only additions to the shared Tier-2 puffery/inflation vocabulary
# (bare stems this domain warns on that the other two checkers do not use in
# this exact form): vital, delve, leverage, realm, foster, nuanced, intricate.
_LEGAL_ONLY_TIER2_WORDS = ("vital", "delve", "leverage", "realm", "foster", "nuanced", "intricate")
_SHARED_TIER2_WORDS = sorted(
{*style_lint.TIER2_PUFFERY_WORDS, *style_lint.TIER2_INFLATION_WORDS, *_LEGAL_ONLY_TIER2_WORDS}
- {"seamlessly", "in the realm of", "delves into", "cutting-edge"}
)
_INFLATED_WORD_PATTERN = re.compile(
r"\b(?:" + "|".join(re.escape(w) for w in _SHARED_TIER2_WORDS) + r")\b", re.I
)
FAIL_PATTERNS = [
("em dash (banned in all output)", style_lint.EM_DASH_PATTERN),
("US legalese: COMES NOW", re.compile(r"\bCOMES NOW\b", re.I)),
("US legalese: wherefore", re.compile(r"\bwherefore\b", re.I)),
("US legalese: herein", re.compile(r"\bherein\b", re.I)),
("US legalese: therein", re.compile(r"\btherein\b", re.I)),
("US legalese: heretofore", re.compile(r"\bheretofore\b", re.I)),
("US legalese: aforementioned", re.compile(r"\baforementioned\b", re.I)),
("US legalese: the undersigned", re.compile(r"\bthe undersigned\b", re.I)),
("US legalese: respectfully prays", re.compile(r"\brespectfully prays\b", re.I)),
("US legalese: Honorable Court", re.compile(r"\bHonorable Court\b", re.I)),
("US legalese: pro se", re.compile(r"\bpro se\b", re.I)),
("US legalese: esq.", re.compile(r"\besq\.", re.I)),
("banned evidence path: .work", re.compile(r"(^|[/` ])\.work(/|`| |$)")),
("banned evidence path: docs/audits", re.compile(r"(^|[/` ])docs/audits(/|`| |$)")),
("banned evidence path: _audit", re.compile(r"(^|[/` ])_audit(/|`| |$)")),
("internal marker: TODO", re.compile(r"\bTODO\b")),
("internal marker: TBD", re.compile(r"\bTBD\b")),
("internal marker: TBC", re.compile(r"\bTBC\b")),
("internal marker: FIXME", re.compile(r"\bFIXME\b")),
("internal marker: drafting note", re.compile(r"\bdrafting note\b", re.I)),
("agent or AI process language", re.compile(r"\b(agent note|AI-generated|generated by AI|hallucination)\b", re.I)),
(
"safety-instrument overstatement",
re.compile(
r"\b(?:protective|protection|intervention|safety|police-issued)\b"
r".{0,50}\b(?:notice|direction|order|instrument|application|material)\b"
r".{0,80}\b(?:proves?|establish(?:es|ed))\b"
r".{0,80}\b(?:family|domestic) violence\b",
re.I,
),
),
]
WARN_PATTERNS = [
("en dash (allowed; use sparingly, e.g. number/date/page ranges)", re.compile("–")),
("AI tell / inflated word", _INFLATED_WORD_PATTERN),
("AI tell / prestige verb", re.compile(r"\b(showcases?|underscores?|highlights?|facilitates?|enhances?|drives?|leverages?)\b", re.I)),
("AI tell / empty transition", re.compile(r"\b(it is worth noting that|in light of the foregoing|having regard to the above|as outlined above)\b", re.I)),
("AI tell / notability opener", re.compile(r"\b(importantly|notably|interestingly),", re.I)),
("AI tell / additive transition chain (name the real relation or omit)", re.compile(r"\b(moreover|furthermore|additionally|in addition)\b", re.I)),
("AI tell / additive background padding (cut or move to the owning document)", re.compile(r"\b(broader background context|ongoing dispute|sets? out the broader background|additional context)\b", re.I)),
("AI tell / copula avoidance", re.compile(r"\b(serves as|serves to|stands as|plays a role in|is indicative of|represents)\b", re.I)),
("AI tell / negative parallelism padding", re.compile(r"\b(not only|not just|not merely|is not merely|isn't merely)\b", re.I)),
("AI tell / empty ing-tail", re.compile(r",\s+(ensuring|enhancing|highlighting|showcasing|driving|facilitating)\s+(fairness|reliability|concerns|evidence|impact|performance|compliance|clarity|efficiency|outcomes?)\b", re.I)),
(
"hyphenation / -ly adverb compound",
re.compile(rf"\b(?:{style_lint.LY_ADVERBS}|legally|procedurally|factually)-[A-Za-z]+\b", re.I),
),
("AI tell / stock document opener", re.compile(r"\b(this (?:application|submission|affidavit|letter|section|document) (?:explores|delves|sets out to|highlights|underscores|showcases|demonstrates))\b", re.I)),
("internal process language in filing text", re.compile(r"\b(agent summary|review set|render check|manifest proves|router status|gate fired|source pack|audit found)\b", re.I)),
("weak abstraction (name the act, source, order or consequence)", re.compile(r"\b(concerns regarding|issues surrounding|matters pertaining to|in relation to|with respect to|with regard to|in respect of)\b", re.I)),
("legal noun-stack risk (unpack abstract head and keep one defined term)", re.compile(r"\b(?:cross-proceeding|source-boundary|filing-facing|safety-context|family-violence|case-management|enforcement|relationship-finance|document-function|protected-address)\s+(?:[a-z]+-)?[a-z]+\s+(?:context|framework|posture|material|risk|issue|position|process|concern|boundary|interface)\b", re.I)),
("wordy filler: in order to (prefer to unless source-bound)", re.compile(r"\bin order to\b", re.I)),
("wordy filler: for the purpose of (prefer for or the specific purpose)", re.compile(r"\bfor the purpose of\b", re.I)),
("wordy filler: the fact that (name the fact directly)", re.compile(r"\bthe fact that\b", re.I)),
("wordy filler: question as to whether (prefer whether)", re.compile(r"\bquestion as to whether\b", re.I)),
("wordy filler: is able to / has the ability to (prefer can unless capacity is the issue)", re.compile(r"\b(is able to|has the ability to)\b", re.I)),
("wordy filler: in circumstances where (prefer where, when or the actual condition)", re.compile(r"\bin circumstances where\b", re.I)),
("stock submission formula (usually state the submission directly)", re.compile(r"\b(it is submitted that|respectfully submits?|respectfully requests?)\b", re.I)),
("proposed order vagueness (needs actor, act, object and deadline or trigger)", re.compile(r"\b(as soon as practicable|appropriate to make orders|ensure that the parties understand)\b", re.I)),
("dated legalism: at all material times (state the date range if it matters)", re.compile(r"\bat all material times\b", re.I)),
("empty hedge", re.compile(r"\b(clearly|obviously)\b", re.I)),
("overstatement intensifier (assert the proposition and pin it to a source instead)", re.compile(r"\b(overwhelmingly|incontrovertibly|indisputably|undoubtedly|unquestionably|beyond (?:any )?doubt)\b", re.I)),
("modal hedge stack (keep one accurate qualifier)", re.compile(r"\b(?:may|might|could)\s+(?:arguably|possibly|perhaps|potentially)\b|\b(?:arguably|possibly|perhaps)\s+(?:may|might|could)\b", re.I)),
("ceremonial doublet (collapse to the operative word unless quoted or statutory)", re.compile(r"\b(null and void|each and every|any and all|cease and desist|full and complete|aid and abet)\b", re.I)),
("self-narration opener (cut drafting meta-discourse)", re.compile(r"\b(this (?:part|section|document) (?:gathers|establishes the)|is stated once, here|is not reproduced here|is not restated here|as (?:mentioned|noted) (?:earlier|above))\b", re.I)),
("empty opener", re.compile(r"\bit is important to note that\b", re.I)),
("email throat-clearing", re.compile(r"\b(I trust this email finds you well|I hope you are well|please be advised|for the avoidance of doubt|kindly|as previously stated|we note with concern|thank you for your understanding|at your earliest convenience)\b", re.I)),
("rights-reservation formula (check instruction and legal effect)", re.compile(r"\b(we reserve all rights|all rights are reserved|without prejudice)\b", re.I)),
("dated wording: telephone (prefer phone unless quoted, source-bound, form-field or rule/title wording)", re.compile(r"\btelephone\b", re.I)),
("dated wording: pursuant to (prefer under unless quoted, source-bound, form-field or rule/title wording)", re.compile(r"\bpursuant to\b", re.I)),
("dated wording: prior to (prefer before unless quoted, source-bound or a defined legal phrase)", re.compile(r"\bprior to\b", re.I)),
("dated wording: subsequent to (prefer after unless quoted, source-bound or a defined legal phrase)", re.compile(r"\bsubsequent to\b", re.I)),
("dated wording: whilst (prefer while)", re.compile(r"\bwhilst\b", re.I)),
("dated wording: utilise/utilize (prefer use)", re.compile(r"\butili[sz]e[sd]?\b", re.I)),
("dated wording: furnish/furnished (prefer send, give or provide unless rule-bound)", re.compile(r"\bfurnish(?:ed|es|ing)?\b", re.I)),
("dated wording: hereby/thereof/thereafter (name the act, thing or date)", re.compile(r"\b(hereby|thereof|thereafter)\b", re.I)),
("dated wording: said as adjective (prefer the/that/defined noun)", re.compile(r"\bthe said\b|\bsaid (?:application|affidavit|agreement|amount|appeal|court|decision|document|email|form|hearing|material|order|party|proceeding|request|rule|sum)\b", re.I)),
("US prose date", re.compile(r"\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec)[a-z]* \d{1,2}, \d{4}\b")),
("US numeric date", re.compile(r"\b\d{1,2}/\d{1,2}/\d{4}\b")),
("relative date", re.compile(r"\b(today|yesterday|tomorrow|currently|recently)\b", re.I)),
("placeholder", re.compile(r"\[(?:insert|to come|confirm|check)[^\]]*\]", re.I)),
("possible affidavit advocacy", re.compile(r"\b(jurisdictional error|plainly wrong|bad faith|abuse of process)\b", re.I)),
# House style (Headings, Numbering And Document Structure): bold only headings,
# the deponent name at commencement/jurat, and exhibit labels on first mention.
("emphasis-bolded money amount (do not bold amounts in prose)", re.compile(r"^(?!\s*\|).*\*\*\$\d")),
("bolded party short-form (define once with single quotes, then plain)", re.compile(r"\*\*(?:Mr|Ms|Mrs|Dr|Justice|Adjudicator|Member) [A-Z][a-z]+\*\*")),
("sub-list marker should be ((a)) / ((i)) form, not 'a.' / 'a)'", re.compile(r"^ {4}[a-z]{1,4}[.\)]\s")),
]
# Navigation/meta files that are never filing prose (don't lint them as such).
_NON_FILING = {"readme.md", "index.md"}
def iter_files(paths: list[Path], include_readme: bool) -> tuple[list[Path], int]:
files: list[Path] = []
failures = 0
for path in paths:
if path.is_dir():
try:
# Path.rglob suppresses some traversal errors on newer Python
# versions. Walk explicitly so an unreadable root or child
# directory cannot become a false-green empty scan.
pending = [path]
discovered: list[Path] = []
while pending:
directory = pending.pop()
with os.scandir(directory) as entries:
rows = sorted(entries, key=lambda entry: entry.name)
child_dirs: list[Path] = []
for entry in rows:
if entry.is_dir(follow_symlinks=False):
child_dirs.append(Path(entry.path))
elif (
entry.is_file(follow_symlinks=False)
and entry.name.lower().endswith(".md")
and (include_readme or entry.name.lower() not in _NON_FILING)
):
discovered.append(Path(entry.path))
pending.extend(reversed(child_dirs))
files.extend(sorted(discovered))
except OSError as exc:
print(f"FAIL unreadable directory: {path}: {exc}", file=sys.stderr)
failures += 1
elif path.is_file():
if include_readme or path.name.lower() not in _NON_FILING:
files.append(path)
else:
print(f"FAIL missing path: {path}", file=sys.stderr)
failures += 1
return files, failures
def strip_markdown_code_spans(line: str) -> str:
return re.sub(r"`[^`]*`", "", line)
def is_markdown_code_fence(line: str) -> bool:
stripped = line.lstrip()
return stripped.startswith("```") or stripped.startswith("~~~")
LONG_SENTENCE_WORDS = 60
LONG_SENTENCE_REPORT_CAP = 3 # worst offenders per file; the rest are counted, not printed
_SENTENCE_SPLIT = re.compile(r"(?<=[.!?])\s+(?=[A-Z(])")
_NON_PROSE_PREFIXES = ("|", "#", "```", "~~~", ">", "---")
_LIST_MARKER = re.compile(r"^(?:[-*+]\s|\d{1,3}[.)]\s|\(?[a-z]{1,4}[.)]\s|\([ivx]+\)\s)")
def check_long_sentences(path: Path, text: str) -> int:
"""WARN on prose sentences over LONG_SENTENCE_WORDS words (paragraphs reassembled across
hard-wrapped lines; tables, headings, fences and blockquotes skipped; each list item is its
own prose unit). Abbreviation false splits only shorten detected sentences, so this under-
rather than over-fires. Only the LONG_SENTENCE_REPORT_CAP worst per file are printed."""
hits: list[tuple[int, int, str]] = [] # (words, line_no, excerpt)
para_lines: list[str] = []
para_start = 0
in_fence = False
def flush() -> None:
if not para_lines:
return
paragraph = strip_markdown_code_spans(" ".join(para_lines))
for sentence in _SENTENCE_SPLIT.split(paragraph):
words = len(sentence.split())
if words > LONG_SENTENCE_WORDS:
hits.append((words, para_start, sentence.strip()[:90]))
for line_no, line in enumerate(text.splitlines(), start=1):
stripped = line.strip()
if is_markdown_code_fence(line):
in_fence = not in_fence
flush()
para_lines = []
continue
if in_fence or not stripped or any(stripped.startswith(p) for p in _NON_PROSE_PREFIXES):
flush()
para_lines = []
continue
if _LIST_MARKER.match(stripped):
flush()
para_lines = []
if not para_lines:
para_start = line_no
para_lines.append(stripped)
flush()
for words, line_no, excerpt in sorted(hits, reverse=True)[:LONG_SENTENCE_REPORT_CAP]:
print(
f"WARN {path}:{line_no}: long sentence ({words} words; split or tabulate "
f"unless precision requires it): {excerpt}..."
)
remainder = len(hits) - LONG_SENTENCE_REPORT_CAP
if remainder > 0:
print(f"WARN {path}: {remainder} more sentence(s) over {LONG_SENTENCE_WORDS} words (not printed)")
return min(len(hits), LONG_SENTENCE_REPORT_CAP) + (1 if remainder > 0 else 0)
# --- Internal leak tokens hidden in HTML comments ---------------------------------------------
# pandoc strips <!-- --> comments, so a leak token parked in one never renders and slips past a
# visual/PDF review, yet it still ships in the source markdown. Ban the leak TOKENS, never the
# comment mechanism: a plain "<!-- editor note -->" carrying none of these fires nothing.
_HTML_COMMENT = re.compile(r"<!--(.*?)-->", re.DOTALL)
_COMMENT_LEAK_TOKENS = [
("run-dir / audit path", re.compile(r"\bdocs/audits/")),
("scratch / build path", re.compile(r"(?<![A-Za-z.])\.work/|\breview_set/|/scratchpad|/private/tmp/")),
("absolute repo path", re.compile(r"/Users/[^\s`)>\]]+")),
("internal task id", re.compile(r"\bTASK-[A-Z]+-\d+\b")),
]
def check_html_comment_leaks(path: Path, text: str, allow_quoted_examples: bool = False) -> int:
"""FAIL on internal leak tokens hidden inside HTML comments: run-dir/audit paths, .work/
scratchpad/build paths, absolute repo paths and TASK-<AREA>-<n> ids. Scope is the comment body
only, so a plain "<!-- editor note -->" with no leak token never fires. Skipped under
--allow-quoted-examples (the skill's own reference docs quote these tokens as examples)."""
if allow_quoted_examples:
return 0
failures = 0
for match in _HTML_COMMENT.finditer(text):
body = match.group(1)
line_no = text.count("\n", 0, match.start()) + 1
for label, pattern in _COMMENT_LEAK_TOKENS:
hit = pattern.search(body)
if hit:
print(f"FAIL {path}:{line_no}: internal leak token in HTML comment ({label}): {hit.group(0).strip()}")
failures += 1
return failures
# --- Headings glued to the previous line -------------------------------------------------------
# The build renders markdown via pandoc with blank_before_header: an ATX heading whose previous
# line is non-blank is NOT parsed as a heading and renders as body text, silently demoting a whole
# Part/section in the filed PDF (observed live on file 10 Parts D/H and file 51 Part C before the
# 2026-07-05 sweep). Code fences are skipped (# is a comment there).
_ATX_HEADING = re.compile(r"^ {0,3}#{1,6}\s")
def check_heading_blank_lines(path: Path, text: str) -> int:
"""FAIL on an ATX heading not preceded by a blank line (pandoc blank_before_header renders it
as body text). First line of the file is exempt; fenced code blocks are skipped."""
failures = 0
lines = text.splitlines()
in_fence = False
for idx, line in enumerate(lines):
if is_markdown_code_fence(line):
in_fence = not in_fence
continue
if in_fence:
continue
if _ATX_HEADING.match(line) and idx > 0 and lines[idx - 1].strip():
print(
f"FAIL {path}:{idx + 1}: heading without preceding blank line "
f"(renders as body text under blank_before_header): {line.strip()[:80]}"
)
failures += 1
return failures
def check_file(path: Path, allow_quoted_examples: bool = False) -> tuple[int, int]:
failures = 0
warnings = 0
try:
text = path.read_text(encoding="utf-8")
except UnicodeDecodeError:
try:
text = path.read_text(encoding="utf-8", errors="replace")
except OSError as exc:
print(f"FAIL {path}: unreadable input: {exc}", file=sys.stderr)
return 1, 0
except OSError as exc:
print(f"FAIL {path}: unreadable input: {exc}", file=sys.stderr)
return 1, 0
in_code_fence = False
for line_no, line in enumerate(text.splitlines(), start=1):
if allow_quoted_examples and is_markdown_code_fence(line):
in_code_fence = not in_code_fence
continue
if allow_quoted_examples and in_code_fence:
continue
if allow_quoted_examples and line.lstrip().startswith(">"):
continue
scan_line = strip_markdown_code_spans(line) if allow_quoted_examples else line
for label, pattern in FAIL_PATTERNS:
if pattern.search(scan_line):
print(f"FAIL {path}:{line_no}: {label}: {line.strip()}")
failures += 1
for label, pattern in WARN_PATTERNS:
if pattern.search(scan_line):
print(f"WARN {path}:{line_no}: {label}: {line.strip()}")
warnings += 1
warnings += check_long_sentences(path, text)
failures += check_html_comment_leaks(path, text, allow_quoted_examples)
failures += check_heading_blank_lines(path, text)
return failures, warnings
def main() -> int:
parser = argparse.ArgumentParser(description="Lint filing-facing Australian legal markdown for style risks.")
parser.add_argument(
"paths",
nargs="+",
type=Path,
help="One or more explicit project files or directories to scan (no project defaults).",
)
parser.add_argument("--include-readme", action="store_true", help="Include README.md files in scans.")
parser.add_argument(
"--allow-empty",
action="store_true",
help="Allow an existing input set to resolve to no Markdown files; missing or unreadable explicit paths still fail.",
)
parser.add_argument(
"--allow-quoted-examples",
action="store_true",
help="Ignore text inside Markdown code spans; useful when checking skill references that quote banned phrases.",
)
args = parser.parse_args()
total_failures = 0
total_warnings = 0
files, resolution_failures = iter_files(args.paths, args.include_readme)
total_failures += resolution_failures
if not files and not args.allow_empty:
print("FAIL no Markdown files resolved from the explicit inputs.", file=sys.stderr)
total_failures += 1
for path in files:
failures, warnings = check_file(path, args.allow_quoted_examples)
total_failures += failures
total_warnings += warnings
print(f"Scanned {len(files)} markdown file(s): {total_failures} failure(s), {total_warnings} warning(s).")
return 1 if total_failures else 0
if __name__ == "__main__":
raise SystemExit(main())
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |
| requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirements | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |
| using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |
| verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |