# patent-audit

Adopt this skill: https://proskills.md/skills/other/gfodor-legal-skills-patent-audit

Page: https://proskills.md/skills/other/gfodor-legal-skills-patent-audit
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: patent-audit/SKILL.md
size: 11828
sha: cfadc694317fd54372819c55fab077dc464c1bd0
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/SKILL.md

````text
---
name: patent-audit
description: Audit a draft U.S. utility patent application before it is filed, against a 316-item checklist grounded in 35 U.S.C., 37 CFR, the MPEP, and current USPTO practice. Runs a deterministic pre-pass over the draft, gates on patentability, inventorship and deadlines, then fans out parallel review agents over the specification, claims, drawings and filing packet, adversarially verifies every fatal finding, and reports ranked defects with honest coverage accounting. Use when asked to audit, review, check, or pre-flight a patent application, provisional, specification, or claim set before filing.
---

# Pre-filing patent application audit

Audit a draft utility patent application against 316 checklist items and return a
ranked defect list with coverage accounting.

**Not legal advice.** The checklist is grounded in 35 U.S.C., 37 CFR, the MPEP,
and current USPTO materials. Fee amounts, form names and filing mechanics must
be re-verified against current PTO practice, and §101 case law moves. Say so
in the report; the template already does.

## What ships with this skill

| Path | Purpose |
|---|---|
| `reference/checklist_index.json` | All 316 items with routing: `id, part, section, title, check, severity, applies_to, inputs, automation, owner, blocking` |
| `reference/parts/{A..I}_*.md` | Full item text per part — **these are the agent payloads** |
| `scripts/prepass.py` | One command for all of Phase 1 |
| `scripts/parse_application.py` | Draft → structured `parsed.json` |
| `scripts/mechanical_checks.py` | Deterministic checks → `findings_mechanical.json` |
| `scripts/deadlines.py` | Intake → `deadlines.json` with weekend/holiday rollover |
| `scripts/synthesize.py` | All findings → ranked report + coverage |
| `assets/intake.yaml` | The intake questionnaire template |
| `assets/sample_draft.md` | A draft with planted defects, for testing the harness |

Routing is precomputed. Every item carries:

- **`inputs`** — what evidence it consumes: `draft_text` (210 items), `intake_facts` (99),
  `forms_packet` (68), `drawings` (47), `search_report` (40), `prior_art_refs` (20),
  `ppa_text` (20), `parent_app` (13).
- **`automation`** — `mechanical` (28), `assisted` (169), `judgment` (119).
- **`owner`** — which agent runs it.
- **`blocking`** — 105 items halt the audit on failure.

**26 items are answerable only from intake facts.** No document review reaches them:
`A19 A20 A22–A25 A36 C05 C08–C12 C21 D19–D26 D28 D29 I38 I42`. If intake is
skipped, those are `cannot_assess` — never `pass`.

## Core principles

**The draft fits in one context. Parallelize for attention, not capacity.** Every
agent gets the whole application. Never chunk the document across agents —
enablement, antecedent basis and numeral consistency are whole-document properties.

**Never let a model do arithmetic or exhaustive cross-referencing.** Dates, claim
counts, fee tiers, dependency graphs and numeral reconciliation run in code. Models
find 19 of 20 numerals and report "all consistent."

**Silence is not a pass.** Every item ends as `pass`, `fail`, `cannot_assess`,
`not_applicable`, or `not_reached`. An agent that omits an item has not passed it.

**`cannot_assess` is a correct answer.** Some items — the duty of candour above all
— cannot be established from any document. Guessing is worse than admitting.

---

## Phase 0 — Intake (blocking)

Run `prepass.py` with no `--intake`; it writes the questionnaire into the working
directory. Have the user fill it. Parts A, C and D are unanswerable without it.

Do not proceed past the gates on assumed facts. If the user wants to start anyway,
run Phases 1 and 3 only, and mark every intake-dependent item `cannot_assess`.

The most consequential fields are the disclosure and bar dates, and
`disclosure_made_by` — post-AIA, only an inventor-derived disclosure gets the
one-year grace period. A third party's independent disclosure before filing means
the U.S. right is already gone, and no amount of drafting fixes it.

## Phase 1 — Deterministic pre-pass

```bash
python scripts/prepass.py --draft DRAFT --drawings DRAWINGS \
    --intake intake.yaml --workdir audit_run
```

Exit 1 means intake is missing; exit 2 means the draft did not parse and the run
must stop. Individual steps if you need them:

```bash
python scripts/parse_application.py DRAFT --drawings D -o parsed.json
python scripts/mechanical_checks.py parsed.json --intake intake.yaml -o findings/findings_mechanical.json
python scripts/deadlines.py intake.yaml -o deadlines.json [--asof YYYY-MM-DD]
```

`parse_application.py` accepts `.txt`, `.md`, `.pdf`, `.docx`. `prepass.py` refuses
to continue when no claims parsed, fewer than four sections were recognised, or the
detailed description yielded no reference numerals — all signs the draft uses
headings the parser did not expect. Fix the parse before dispatching agents;
otherwise they confidently audit a document that isn't there.

The mechanical checks credit the checklist items they cover, so those items are not
reported as unaudited. A mechanical `pass` never suppresses a later agent `fail` on
the same item — the synthesizer keeps the worst verdict.

Hand `parsed.json` to every agent. It carries the claim dependency graph, element
decomposition, antecedent-basis candidates, reference-numeral tables and figure
inventory, so no agent has to recompute them.

## Phase 2 — Gates (sequential, fail fast)

Run in order. Each gets `intake.yaml`, `parsed.json`, `deadlines.json`, the draft,
and only its own part file.

| Agent | Part file | Also needs |
|---|---|---|
| `gate_threshold` | `A_threshold.md` | search report, closest prior art |
| `gate_inventorship` | `C_inventorship.md` | — |
| `gate_priority` | `D_priority_deadlines.md` | `deadlines.json`, PPA text, parent |

**If any gate returns a `fail` on an item tagged `blocking: true`, stop.** Report
the blocker and do not spend tokens auditing the prose of an application that is
statutorily barred, names the wrong inventors, or has already lost its priority
date. Tell the user what would have run.

`gate_priority` must not compute dates. `deadlines.json` already has them, with
rollover applied. Its job is to interpret them and catch the conflicts the script
flags in `warnings`.

## Phase 3 — Document fan-out (parallel, single message)

Eight agents, all with the full draft and `parsed.json`. Launch together.

| Agent | Part file | Lens to put in the prompt |
|---|---|---|
| `doc_enablement` | `E_disclosure.md` (own items) | Read as a skilled artisan *trying to build it*. Every point where you'd have to invent something is a gap. |
| `doc_narrowing` | `E_disclosure.md` + `F_spec_sections.md` (own items) | Read as opposing counsel hunting for admissions, essentiality language, and claim-construction traps. |
| `doc_spec_sections` | `F_spec_sections.md` | Walk the spec section by section in PTO order. |
| `doc_claims_law` | `G_claims.md` (own items) | §112 form, definiteness, antecedent basis, means-plus-function. Adjudicate the `candidates` lists from the mechanical pass — do not re-derive them. |
| `doc_claims_arch` | `G_claims.md` (own items) | Set architecture: is claim 1 the broadest? Does each dependent add real scope? Are the statutory classes covered? |
| `doc_drawings` | `H_drawings.md` + I05, I33 | **Multimodal — attach the sheets as images.** Text-only, this agent silently passes. |
| `doc_filing` | `I_filing_packet.md` | Formalities, ADS, declaration, fees, IDS, nonpublication request. |
| `doc_search` | `B_search.md` | Was the search adequate, were the references read correctly, does the draft answer what was found? |

Split `E`/`F`/`G` between their agents using the `owner` field in
`checklist_index.json`, not by file — owners deliberately cross file boundaries. An
item about narrowing language belongs to `doc_narrowing` wherever it sits, and the
claim-support items in Part G belong to `doc_enablement`.

Filter each agent's payload to its own IDs:

```bash
python -c "import json,sys; \
 ids={i['id'] for i in json.load(open('reference/checklist_index.json',encoding='utf-8')) \
      if i['owner']==sys.argv[1]}; print(' '.join(sorted(ids)))" doc_narrowing
```

Workload is uneven by design: `gate_priority` 48, `doc_filing` 46,
`doc_claims_law` 39, `gate_threshold` 35, `doc_enablement` 25, `doc_drawings` 24,
`doc_claims_arch` 23, `doc_search` 22, `gate_inventorship` 21,
`doc_spec_sections` 19, `doc_narrowing` 14.

### Red team (launch with the same batch)

The highest-value output, and not checklist-shaped. Each returns prose, not findings.

- **`redteam_examiner`** — You are the examiner. Given these claims and this search
  report, write the first Office Action you would actually issue: every §101, §102,
  §103 and §112 rejection, with the reference and the mapping.
- **`redteam_design_around`** — Given claim 1, design three products that capture
  the commercial value and do not infringe. If this is easy, claim 1 is too narrow —
  no checklist item will tell you that.
- **`redteam_invalidity`** — Assume it issued and you are the accused infringer.
  Attack it: priority defects, §112 gaps, prior art the applicant missed.

## Phase 4 — Adversarial verification

For **every** `fail` on a `blocking` item, spawn a fresh verifier that receives the
draft and the claim **but not the finding's reasoning**, and is prompted to refute
it. Three verifiers; the finding survives on two. Record survivors in the finding's
`verified_by` field and drop the rest to `cannot_assess` with a note.

This is where surplus budget goes. A 93-item fatal list with a 20% false-positive
rate is worse than a clean 60-item list — attorneys stop reading audits that cry wolf.

## Phase 5 — Synthesis

```bash
python scripts/synthesize.py findings/ --deadlines deadlines.json \
    -o audit_report.md --json audit_report.json
```

Exits non-zero when a fatal item failed. Reports `not_reached` for any item no agent
touched — check that number is zero before calling the audit complete. If it isn't,
an agent skipped work; re-run that agent.

Append the three red-team outputs as appendices.

---

## Finding schema

Every agent returns **only** a JSON array to `findings/<agent>.json`. No prose.

```json
[{
  "item_id": "G14",
  "verdict": "fail",
  "severity": "Serious",
  "location": "claim 3",
  "evidence": "the said locking member",
  "explanation": "No earlier claim introduces a locking member.",
  "suggested_fix": "Introduce 'a locking member' in claim 1, or recite it in claim 3.",
  "confidence": "high"
}]
```

`verdict` ∈ `pass | fail | cannot_assess | not_applicable`. Rules to put in every
agent prompt:

1. Emit exactly one entry per item in your part file. Count them before writing.
2. `evidence` must be a **verbatim quote from the draft**, never a paraphrase. A
   finding with no quote is not a finding.
3. Use `cannot_assess` when the input is missing. Never infer a date, an inventor's
   knowledge, or a fact not in the materials.
4. `not_applicable` needs a reason in `explanation`.
5. Do not edit the draft. This is an audit; remediation is a separate pass.

## Scaling

Typical case (20–60 pages, ~20 claims): 11 agents in Phase 3, wall clock ≈ the
slowest, 5–10 minutes. Large claim sets (100+) — fan `doc_claims_law` out per claim,
since form checks are claim-independent; keep `doc_claims_arch` whole-set.

## Do not

- Run one agent per checklist item. 316 agents each re-reading the draft buys
  nothing; items share reading effort.
- Chunk the draft across agents.
- Let an audit agent edit the draft — you lose the evidence trail.
- Report a `pass` for anything an agent stayed silent about.
- Recompute in a model what `parsed.json` already computed exactly.
````

## File: patent-audit/scripts/deadlines.py
size: 12820
sha: cc7714e4e8d16ff82a0d16407f5f8d7ad4525890
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/scripts/deadlines.py

```text
#!/usr/bin/env python3
"""Compute every pre-filing-relevant date from the intake facts.

Date arithmetic is the single thing in this audit a language model is least
suited to and a script is best at, so no agent is asked to compute a deadline.
The agent interprets what the script returns.

    python deadlines.py intake.yaml [-o deadlines.json] [--asof YYYY-MM-DD]

Intervals implemented are those in 35 U.S.C. §§ 102, 119, 120, 122, 184 and
37 CFR 1.7, 1.78, 1.97, 1.213, 5.11 that are set, triggered, or foreclosed at
or before the filing of a regular utility application. Re-verify against the
current official text before relying on any date.
"""
from __future__ import annotations

import argparse
import json
import sys
from datetime import date, timedelta

FITF = date(2013, 3, 16)   # America Invents Act first-inventor-to-file cutover

# US federal holidays that fall on fixed dates. Floating holidays are resolved
# below. The PTO also rolls a deadline that lands on a DC-closed day.
FIXED_HOLIDAYS = [(1, 1), (6, 19), (7, 4), (11, 11), (12, 25)]

def nth_weekday(year, month, weekday, n):
    d = date(year, month, 1)
    d += timedelta(days=(weekday - d.weekday()) % 7)
    return d + timedelta(weeks=n - 1)

def last_weekday(year, month, weekday):
    d = date(year, month + 1, 1) - timedelta(days=1) if month < 12 else date(year, 12, 31)
    return d - timedelta(days=(d.weekday() - weekday) % 7)

def federal_holidays(year):
    out = set()
    for m, d in FIXED_HOLIDAYS:
        h = date(year, m, d)
        if h.weekday() == 5:          # Saturday -> observed Friday
            h -= timedelta(days=1)
        elif h.weekday() == 6:        # Sunday -> observed Monday
            h += timedelta(days=1)
        out.add(h)
    out.add(nth_weekday(year, 1, 0, 3))    # MLK Day
    out.add(nth_weekday(year, 2, 0, 3))    # Presidents' Day
    out.add(last_weekday(year, 5, 0))      # Memorial Day
    out.add(nth_weekday(year, 9, 0, 1))    # Labor Day
    out.add(nth_weekday(year, 10, 0, 2))   # Columbus Day
    out.add(nth_weekday(year, 11, 3, 4))   # Thanksgiving
    return out

def roll(d):
    """Roll a deadline forward off weekends and DC federal holidays."""
    hol = federal_holidays(d.year) | federal_holidays(d.year + 1)
    moved = False
    while d.weekday() >= 5 or d in hol:
        d += timedelta(days=1)
        moved = True
    return d, moved

def add_months(d, months):
    y, m = divmod(d.month - 1 + months, 12)
    y, m = d.year + y, m + 1
    day = d.day
    while True:
        try:
            return date(y, m, day)
        except ValueError:
            day -= 1        # 31 Jan + 1 month -> 28/29 Feb

def parse_date(v, field):
    if v in (None, "", "none", "None"):
        return None
    if isinstance(v, date):
        return v
    try:
        y, m, d = (int(x) for x in str(v).strip().split("-"))
        return date(y, m, d)
    except Exception:
        sys.exit("intake.%s is not an ISO date (YYYY-MM-DD): %r" % (field, v))

def entry(name, trigger, trigger_date, due, consequence, blocking, asof, authority):
    due_rolled, moved = roll(due)
    days = (due_rolled - asof).days
    return {
        "deadline": name,
        "trigger": trigger,
        "trigger_date": trigger_date.isoformat(),
        "due": due_rolled.isoformat(),
        "raw_due": due.isoformat(),
        "rolled_off_weekend_or_holiday": moved,
        "days_remaining": days,
        "status": "MISSED" if days < 0 else ("URGENT" if days <= 30 else "ok"),
        "consequence_if_missed": consequence,
        "blocking": blocking,
        "authority": authority,
    }

def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("intake")
    ap.add_argument("-o", "--out", default="deadlines.json")
    ap.add_argument("--asof", help="evaluate as of this date (default: today)")
    args = ap.parse_args()

    raw = open(args.intake, encoding="utf-8").read()
    try:
        import yaml
        cfg = yaml.safe_load(raw) or {}
    except ImportError:
        try:
            cfg = json.loads(raw)
        except ValueError:
            sys.exit("intake is YAML but PyYAML is missing: pip install pyyaml")

    asof = parse_date(args.asof, "asof") if args.asof else date.today()

    first_disc = parse_date(cfg.get("first_public_disclosure_date"),
                            "first_public_disclosure_date")
    first_sale = parse_date(cfg.get("first_offer_for_sale_date"),
                            "first_offer_for_sale_date")
    first_use = parse_date(cfg.get("first_public_use_date"), "first_public_use_date")
    ppa = parse_date(cfg.get("ppa_filing_date"), "ppa_filing_date")
    parent = parse_date(cfg.get("parent_filing_date"), "parent_filing_date")
    planned = parse_date(cfg.get("planned_filing_date"), "planned_filing_date")
    foreign_intent = bool(cfg.get("foreign_filing_intended"))
    nonpub = bool(cfg.get("nonpublication_request_planned"))
    disclosure_by = (cfg.get("disclosure_made_by") or "").strip().lower()

    out, warnings = [], []

    # ---- grace period on the inventor's own disclosure
    triggers = [("public disclosure", first_disc), ("offer for sale", first_sale),
                ("public use", first_use)]
    earliest = sorted([(d, n) for n, d in triggers if d], key=lambda t: t[0])
    if earliest:
        d0, label = earliest[0]
        if d0 >= FITF:
            if disclosure_by in ("inventor", "from_inventor", "obtained_from_inventor"):
                out.append(entry(
                    "AIA grace period expires", label, d0, add_months(d0, 12),
                    "The one-year grace period lapses and the inventor's own "
                    "disclosure becomes prior art barring the application.",
                    True, asof, "35 U.S.C. § 102(b)(1)"))
            else:
                warnings.append(
                    "A %s occurred on %s (post-FITF) and intake does not record it "
                    "as made by, or derived from, the inventor. If a third party "
                    "disclosed independently, there is NO grace period and U.S. "
                    "rights may already be lost. Resolve before filing."
                    % (label, d0.isoformat()))
                out.append(entry(
                    "AIA grace period expires (ONLY if inventor-derived)", label, d0,
                    add_months(d0, 12),
                    "If the disclosure was not the inventor's or derived from the "
                    "inventor, it is prior art immediately and no grace period applies.",
                    True, asof, "35 U.S.C. § 102(a)(1), (b)(1)"))
        else:
            out.append(entry(
                "Pre-FITF one-year statutory bar", label, d0, add_months(d0, 12),
                "The pre-AIA one-year grace period lapses; the U.S. application "
                "is barred.", True, asof, "pre-AIA 35 U.S.C. § 102(b)"))

        if foreign_intent:
            out.append({
                "deadline": "Foreign rights already at risk",
                "trigger": label, "trigger_date": d0.isoformat(),
                "due": "BEFORE " + d0.isoformat(),
                "raw_due": d0.isoformat(),
                "rolled_off_weekend_or_holiday": False,
                "days_remaining": None,
                "status": "MISSED",
                "consequence_if_missed":
                    "Most countries apply absolute novelty with no grace period. A "
                    "public disclosure before the U.S. filing forfeits rights in "
                    "those countries. Confirm which jurisdictions remain available.",
                "blocking": True, "authority": "Paris Convention; 35 U.S.C. § 119",
            })

    # ---- PPA
    if ppa:
        out.append(entry(
            "PPA -> regular application (U.S.)", "PPA filing", ppa,
            add_months(ppa, 12),
            "Benefit of the PPA filing date is lost entirely; the PPA becomes "
            "worthless.", True, asof, "35 U.S.C. § 119(e)"))
        out.append(entry(
            "PPA -> foreign / PCT Convention year", "PPA filing", ppa,
            add_months(ppa, 12),
            "Loss of the PPA priority date for all foreign filings.",
            bool(foreign_intent), asof, "35 U.S.C. § 119; Paris Art. 4"))

    # ---- dates that run from the filing itself
    if planned:
        out.append(entry(
            "Paris Convention year (foreign filings)", "planned U.S. filing", planned,
            add_months(planned, 12),
            "Loss of the U.S. priority date for Convention filings.",
            bool(foreign_intent), asof, "35 U.S.C. § 119; Paris Art. 4"))
        out.append(entry(
            "PCT national phase (30 months from priority)", "planned U.S. filing",
            planned, add_months(planned, 30),
            "National-phase entry barred in PCT states.", False, asof, "PCT Arts. 22, 39"))
        out.append(entry(
            "Statutory publication at 18 months", "planned U.S. filing", planned,
            add_months(planned, 18),
            "The application publishes unless a Nonpublication Request was filed "
            "WITH the application, or it has issued or gone abandoned.",
            False, asof, "35 U.S.C. § 122(b); 37 CFR 1.211"))
        out.append(entry(
            "Information Disclosure Statement due", "planned U.S. filing", planned,
            add_months(planned, 3),
            "After three months an IDS needs a fee or a certification; the duty of "
            "candour runs from filing regardless.", False, asof, "37 CFR 1.56, 1.97"))
        out.append(entry(
            "Foreign filing licence / 6-month wait", "planned U.S. filing", planned,
            add_months(planned, 6),
            "Filing abroad before a licence issues (normally granted on the filing "
            "receipt) or before six months elapse risks penalties and loss of the "
            "U.S. patent.", bool(foreign_intent), asof, "35 U.S.C. §§ 184–186; 37 CFR 5.11"))

    if parent:
        out.append({
            "deadline": "Copendency with parent application",
            "trigger": "parent filing", "trigger_date": parent.isoformat(),
            "due": "before parent issues or goes abandoned",
            "raw_due": None, "rolled_off_weekend_or_holiday": False,
            "days_remaining": None,
            "status": "check",
            "consequence_if_missed":
                "A continuation, divisional or CIP must be filed while the parent "
                "is still pending. Confirm the parent's current status.",
            "blocking": True, "authority": "35 U.S.C. § 120",
        })

    # ---- conflicts that are not date arithmetic but are date-adjacent
    if nonpub and foreign_intent:
        warnings.append(
            "CONFLICT: a Nonpublication Request is planned AND foreign filing is "
            "intended. The request certifies the invention will not be the subject "
            "of an application filed abroad. Filing abroad without rescinding it "
            "within 45 days abandons the U.S. application. Drop one or the other.")
    if planned and ppa and planned > add_months(ppa, 12):
        warnings.append(
            "The planned filing date %s is AFTER the PPA's 12-month anniversary %s. "
            "The PPA priority claim is already lost."
            % (planned.isoformat(), add_months(ppa, 12).isoformat()))

    result = {
        "as_of": asof.isoformat(),
        "fitf_cutover": FITF.isoformat(),
        "deadlines": sorted(out, key=lambda e: (e["days_remaining"] is None,
                                                e["days_remaining"])),
        "warnings": warnings,
        "missing_intake_fields": [k for k in (
            "first_public_disclosure_date", "planned_filing_date",
            "foreign_filing_intended", "entity_status") if k not in cfg],
        "note": "Intervals from 35 U.S.C. §§ 102, 119, 120, 122, 184 and "
                "37 CFR 1.7, 1.78, 1.97, 1.213, 5.11. Weekend/holiday rollover "
                "applied under 37 CFR 1.7. Confirm against current official text "
                "before relying on any date.",
    }
    json.dump(result, open(args.out, "w", encoding="utf-8"), indent=1)

    print("as of %s\n" % asof)
    for e in result["deadlines"]:
        dr = e["days_remaining"]
        print("  [%-6s] %-46s due %-12s %s" % (
            e["status"], e["deadline"][:46], e["due"],
            "" if dr is None else "(%+d days)" % dr))
    for w in warnings:
        print("\n  !! %s" % w)
    if result["missing_intake_fields"]:
        print("\n  missing intake fields: %s"
              % ", ".join(result["missing_intake_fields"]))
    print("\nwrote %s" % args.out)

if __name__ == "__main__":
    main()
```

## File: patent-audit/scripts/mechanical_checks.py
size: 24805
sha: 449e3519fdeb753d9c1c0745bfa4071703adb077
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/scripts/mechanical_checks.py

```text
#!/usr/bin/env python3
"""Deterministic checks over parsed.json — the checks a model should never run.

Models are unreliable at exhaustive cross-referencing (they find 19 of 20
numerals and report "all consistent") and at arithmetic. Those checks belong
here, where they are exact. Everything requiring judgment is left to the agents.

    python mechanical_checks.py parsed.json [-o findings_mechanical.json]
                                [--intake intake.yaml]

Each check emits a finding in the shared schema:
    {item_id, verdict, severity, location, evidence, explanation, suggested_fix,
     source: "mechanical"}

verdict is one of: pass | fail | cannot_assess | not_applicable
A check that lacks its input emits `cannot_assess`, never `pass`.
"""
from __future__ import annotations

import argparse
import json
import re
import sys

# Checks that narrow a search but cannot decide it emit `cannot_assess` with a
# populated `candidates` field for the owning agent to adjudicate.
CHECKS = []

def check(item_id, severity, title, covers=()):
    """Register a check.

    `covers` lists the checklist item IDs this check contributes a verdict to.
    A contribution is not necessarily the whole item: synthesize.py keeps the
    worst verdict per item, so a mechanical `pass` never suppresses a later
    `fail` from the agent that owns the judgment half of the same item.
    """
    def deco(fn):
        CHECKS.append((item_id, severity, title, tuple(covers), fn))
        return fn
    return deco

def finding(item_id, severity, verdict, explanation, location="", evidence="",
            fix="", candidates=None):
    f = {"item_id": item_id, "verdict": verdict, "severity": severity,
         "location": location, "evidence": evidence, "explanation": explanation,
         "suggested_fix": fix, "source": "mechanical"}
    if candidates is not None:
        f["candidates"] = candidates
    return f

# ------------------------------------------------------------------ claim form

@check("G_DEP_GRAPH", "Fatal", "Claim dependency graph is valid",
       covers=["G04", "G53"])
def dependency_graph(p, intake):
    claims = p["claims"]
    if not claims:
        return finding("G_DEP_GRAPH", "Fatal", "cannot_assess",
                       "No claims were parsed from the draft.")
    bad = []
    for c in claims:
        if c["dangling_parents"]:
            bad.append("claim %d depends on non-existent claim(s) %s"
                       % (c["number"], c["dangling_parents"]))
        if c["forward_reference"]:
            bad.append("claim %d refers to claim %s, which does not precede it"
                       % (c["number"], c["forward_reference"]))
    nums = [c["number"] for c in claims]
    if nums != list(range(1, len(nums) + 1)):
        bad.append("claims are not numbered consecutively from 1: %s" % nums)
    if not any(c["type"] == "independent" for c in claims):
        bad.append("no independent claim found")
    if bad:
        return finding("G_DEP_GRAPH", "Fatal", "fail", "; ".join(bad),
                       location="claims",
                       fix="Renumber and repoint claim dependencies so every "
                           "dependent claim refers back to an earlier claim.")
    return finding("G_DEP_GRAPH", "Fatal", "pass",
                   "%d claims, all dependencies resolve to earlier claims, "
                   "numbering consecutive." % len(claims))

@check("G_ONE_SENTENCE", "Serious", "Each claim is a single sentence",
       covers=["G06", "G47"])
def one_sentence(p, intake):
    bad = [c for c in p["claims"] if c["internal_periods"] > 0]
    if not p["claims"]:
        return finding("G_ONE_SENTENCE", "Serious", "cannot_assess", "No claims parsed.")
    if bad:
        return finding(
            "G_ONE_SENTENCE", "Serious", "fail",
            "Claims with a sentence-ending period mid-claim: %s"
            % ", ".join(str(c["number"]) for c in bad),
            location="claims " + ", ".join(str(c["number"]) for c in bad),
            fix="Recast as a single sentence; use semicolons between elements.")
    return finding("G_ONE_SENTENCE", "Serious", "pass",
                   "All %d claims are single sentences." % len(p["claims"]))

@check("G_CLAIM_PUNCT", "Quality", "Claim punctuation and closing period",
       covers=["G06", "G47"])
def claim_punct(p, intake):
    if not p["claims"]:
        return finding("G_CLAIM_PUNCT", "Quality", "cannot_assess", "No claims parsed.")
    bad = [c["number"] for c in p["claims"] if not c["ends_with_period"]]
    if bad:
        return finding("G_CLAIM_PUNCT", "Quality", "fail",
                       "Claims not terminated by a period: %s" % bad,
                       location="claims %s" % bad,
                       fix="End every claim with a single period.")
    return finding("G_CLAIM_PUNCT", "Quality", "pass", "All claims end with a period.")

@check("G_TRANSITION", "Serious", "Every independent claim has a recognised transition",
       covers=["G46"])
def transitions(p, intake):
    if not p["claims"]:
        return finding("G_TRANSITION", "Serious", "cannot_assess", "No claims parsed.")
    # A dependent claim inherits its parent's transition; only independent
    # claims must carry one of their own.
    missing = [c["number"] for c in p["claims"]
               if not c["transition"] and c["type"] == "independent"]
    closed = [c["number"] for c in p["claims"]
              if c["transition"] in ("consisting_of", "consisting_essentially_of")]
    notes = []
    if closed:
        notes.append("closed transition ('consisting of') narrows scope to the "
                     "recited elements only, in claims %s" % closed)
    if missing:
        return finding("G_TRANSITION", "Serious", "fail",
                       "No transition phrase found in claims %s. %s"
                       % (missing, "; ".join(notes)),
                       location="claims %s" % missing,
                       fix="Insert an explicit transition, normally 'comprising'.")
    return finding("G_TRANSITION", "Serious", "pass",
                   "All claims carry a transition. %s" % ("; ".join(notes) or ""))

@check("G_ANTECEDENT", "Serious", "Antecedent basis candidates",
       covers=["G08", "G09", "G42"])
def antecedents(p, intake):
    cands = []
    for c in p["claims"]:
        for a in c.get("antecedent_candidates", []):
            cands.append({"claim": c["number"], "phrase": a["phrase"], "noun": a["noun"]})
    if not p["claims"]:
        return finding("G_ANTECEDENT", "Serious", "cannot_assess", "No claims parsed.")
    if not cands:
        return finding("G_ANTECEDENT", "Serious", "pass",
                       "No definite reference lacks an earlier indefinite "
                       "introduction in its claim or ancestry.")
    return finding(
        "G_ANTECEDENT", "Serious", "cannot_assess",
        "%d definite references have no earlier antecedent in scope. A model must "
        "adjudicate: an inherent property ('the length of the rod') needs no "
        "antecedent, a missing element does." % len(cands),
        location="claims", candidates=cands,
        fix="For each genuine gap, introduce the element with 'a'/'an' first.")

# Claim language that is structural glue rather than a claimed element. A term
# from this set appearing only in the claims proves nothing.
CLAIM_GLUE = {
    "claim", "claims", "wherein", "comprising", "comprises", "further",
    "according", "consisting", "essentially", "including", "includes", "having",
    "whereby", "means", "said", "configured", "adapted", "thereof", "therein",
    "thereto", "thereon", "respectively", "least", "plurality", "which", "that",
    "being", "generally", "substantially", "approximately", "about", "relatively",
    "disposed", "positioned", "arranged", "coupled", "connected", "attached",
    "mounted", "secured", "provided", "formed", "defined", "extending",
    "operable", "capable", "wherein", "method", "system", "apparatus", "device",
    "assembly", "wherein", "allowing", "causing", "sliding", "moving", "first",
    "second", "third", "fourth", "upper", "lower", "inner", "outer", "material",
}

@check("G_CLAIM_SUPPORT", "Fatal", "Claim terms appear in the specification",
       covers=["G28"])
def claim_support(p, intake):
    """Literal absence of a claim term from the description.

    Deliberately emits `cannot_assess`, not `fail`: a synonym or a described
    genus can support a claim term that never appears verbatim, so only a model
    can tell a real §112 support gap from a wording difference. The script's job
    is to produce an exhaustive candidate list, which it can do exactly.
    """
    spec = " ".join(s.get("text", "") for k, s in p["sections"].items()
                    if k != "claims").lower()
    if not spec.strip():
        return finding("G_CLAIM_SUPPORT", "Fatal", "cannot_assess",
                       "No specification text outside the claims was found.")
    if not p["claims"]:
        return finding("G_CLAIM_SUPPORT", "Fatal", "cannot_assess", "No claims parsed.")
    missing = []
    for c in p["claims"]:
        terms = {t.lower() for t in re.findall(r"\b[a-z][a-z\-]{4,}\b", c["text"], re.I)}
        for t in sorted(terms - CLAIM_GLUE):
            if t not in spec and t.rstrip("s") not in spec:
                missing.append({"claim": c["number"], "term": t})
    if missing:
        return finding(
            "G_CLAIM_SUPPORT", "Fatal", "cannot_assess",
            "%d claim term(s) do not appear verbatim in the description: %s. A "
            "model must decide whether each is genuinely unsupported or merely "
            "worded differently from the specification."
            % (len(missing), ", ".join(sorted({m["term"] for m in missing}))[:400]),
            location="claims", candidates=missing,
            fix="Where support is genuinely absent, add it to the description "
                "before filing — afterwards it is new matter and cannot be added.")
    return finding("G_CLAIM_SUPPORT", "Fatal", "pass",
                   "Every substantive claim term appears verbatim in the description.")

@check("G_MPF", "Serious", "Means-plus-function claims have disclosed structure",
       covers=["G21", "G45"])
def mpf(p, intake):
    mpfs = [c["number"] for c in p["claims"] if c["means_plus_function"]]
    if not mpfs:
        return finding("G_MPF", "Serious", "not_applicable",
                       "No claim uses 'means for' or 'step for'.")
    return finding(
        "G_MPF", "Serious", "cannot_assess",
        "Claims %s invoke means-plus-function treatment. A model must confirm the "
        "specification discloses corresponding structure for each recited function "
        "and links it explicitly." % mpfs,
        location="claims %s" % mpfs, candidates=mpfs,
        fix="For each 'means for X', ensure the spec names the structure that "
            "performs X and ties it to that language.")

# ----------------------------------------------------------- numerals & drawings

@check("H_NUMERAL_XREF", "Serious", "Reference numerals reconcile with the drawings",
       covers=["H03", "F13"])
def numeral_xref(p, intake):
    spec_nums = set(p["reference_numerals"]["numerals"])
    dwg = p.get("drawings")
    if not dwg:
        return finding("H_NUMERAL_XREF", "Serious", "cannot_assess",
                       "No drawings supplied; rerun parse_application.py with "
                       "--drawings to enable this check.")
    if dwg.get("error"):
        return finding("H_NUMERAL_XREF", "Serious", "cannot_assess", dwg["error"])
    sheets = dwg.get("sheets") or []
    if sheets and isinstance(sheets[0], dict):
        dwg_nums = set()
        textless = 0
        for s in sheets:
            dwg_nums |= set(s.get("numerals", []))
            textless += 0 if s.get("has_text_layer") else 1
        if textless == len(sheets):
            return finding("H_NUMERAL_XREF", "Serious", "cannot_assess",
                           "Drawing sheets have no text layer (scanned or vector "
                           "outlines); numerals must be read visually by the "
                           "drawings agent.")
        only_spec = sorted(spec_nums - dwg_nums, key=lambda s: (len(s), s))
        only_dwg = sorted(dwg_nums - spec_nums, key=lambda s: (len(s), s))
        if only_spec or only_dwg:
            return finding(
                "H_NUMERAL_XREF", "Serious", "fail",
                "In specification but not in drawings: %s. In drawings but not "
                "described: %s." % (only_spec or "none", only_dwg or "none"),
                location="drawings",
                candidates={"spec_only": only_spec, "drawing_only": only_dwg},
                fix="Every numeral must appear in both. Add the missing labels or "
                    "delete the orphaned ones.")
        return finding("H_NUMERAL_XREF", "Serious", "pass",
                       "All %d numerals appear in both the specification and the "
                       "drawings." % len(spec_nums))
    return finding("H_NUMERAL_XREF", "Serious", "cannot_assess",
                   "Drawings supplied as images; numerals must be read visually.")

@check("H_FIGURE_LIST", "Serious", "Every figure is described and every described figure exists",
       covers=["H15"])
def figure_list(p, intake):
    described = set(p["reference_numerals"]["figures_referenced"])
    dwg = p.get("drawings") or {}
    labelled = set(dwg.get("figures_labelled") or [])
    if not described and not labelled:
        return finding("H_FIGURE_LIST", "Serious", "cannot_assess",
                       "No figure references found in the text and no drawings parsed.")
    if not labelled:
        return finding("H_FIGURE_LIST", "Serious", "cannot_assess",
                       "Text references figures %s but no drawing labels were "
                       "readable." % sorted(described))
    miss_dwg = sorted(described - labelled)
    miss_txt = sorted(labelled - described)
    if miss_dwg or miss_txt:
        return finding("H_FIGURE_LIST", "Serious", "fail",
                       "Described but not drawn: %s. Drawn but not described: %s."
                       % (miss_dwg or "none", miss_txt or "none"),
                       location="drawings / brief description",
                       fix="Reconcile the Brief Description of the Drawings with "
                           "the sheets actually filed.")
    return finding("H_FIGURE_LIST", "Serious", "pass",
                   "Figures %s are both described and drawn." % sorted(described))

@check("H_NUMERAL_CONSISTENCY", "Serious", "Each numeral labels one part consistently",
       covers=["H03"])
def numeral_consistency(p, intake):
    inc = p["reference_numerals"]["inconsistent_labels"]
    if not p["reference_numerals"]["numerals"]:
        return finding("H_NUMERAL_CONSISTENCY", "Serious", "cannot_assess",
                       "No reference numerals detected in the detailed description.")
    if inc:
        return finding(
            "H_NUMERAL_CONSISTENCY", "Serious", "cannot_assess",
            "%d numerals are preceded by more than one noun. Some are legitimate "
            "(adjectives vary: 'upper housing 10' / 'housing 10'); a model must "
            "confirm none labels two different parts." % len(inc),
            location="detailed description", candidates=inc,
            fix="One numeral, one part, one name, throughout.")
    return finding("H_NUMERAL_CONSISTENCY", "Serious", "pass",
                   "Every numeral is used with a single consistent label.")

# --------------------------------------------------------------- spec formalities

@check("F_SECTIONS", "Serious", "Required specification sections present and ordered",
       covers=["E23"])
def sections_present(p, intake):
    required = ["field", "background", "summary", "drawing_description",
                "detailed_description", "claims", "abstract"]
    missing = [s for s in required if s not in p["sections_found"]]
    order = [s for s in p["section_order"] if s in required]
    expected = [s for s in required if s in order]
    if missing:
        return finding("F_SECTIONS", "Serious", "fail",
                       "Missing required section(s): %s" % ", ".join(missing),
                       location="specification",
                       fix="Add the missing section headings and content.")
    if order != expected:
        return finding("F_SECTIONS", "Serious", "fail",
                       "Sections are out of the conventional order. Found: %s"
                       % " > ".join(order), location="specification",
                       fix="Reorder to: %s" % " > ".join(expected))
    return finding("F_SECTIONS", "Serious", "pass",
                   "All required sections present in conventional order.")

@check("F_ABSTRACT_LENGTH", "Serious", "Abstract is a single paragraph under 150 words",
       covers=["F26"])
def abstract_length(p, intake):
    a = p["abstract"]
    if not a["text"].strip():
        return finding("F_ABSTRACT_LENGTH", "Serious", "fail",
                       "No abstract found.", location="abstract",
                       fix="Add an abstract of a single paragraph, under 150 words.")
    if a["word_count"] > 150:
        return finding("F_ABSTRACT_LENGTH", "Serious", "fail",
                       "Abstract is %d words; the limit is 150." % a["word_count"],
                       location="abstract", evidence=a["text"][:200],
                       fix="Cut to 150 words or fewer.")
    return finding("F_ABSTRACT_LENGTH", "Serious", "pass",
                   "Abstract is %d words." % a["word_count"])

@check("I_PAGE_FORMAT", "Serious", "Sheet size and margins",
       covers=["I01", "I02"])
def page_format(p, intake):
    pdf = p.get("pdf")
    if not pdf:
        return finding("I_PAGE_FORMAT", "Serious", "cannot_assess",
                       "Draft was not supplied as PDF; sheet size and margins "
                       "cannot be measured.")
    LETTER = (612.0, 792.0)
    A4 = (595.0, 842.0)
    sizes = {(round(pg["width_pt"]), round(pg["height_pt"])) for pg in pdf["pages"]}
    if len(sizes) > 1:
        return finding("I_PAGE_FORMAT", "Serious", "fail",
                       "Mixed sheet sizes in one document: %s" % sorted(sizes),
                       location="whole document",
                       fix="Use one uniform sheet size throughout.")
    w, h = next(iter(sizes))
    ok = (abs(w - LETTER[0]) < 6 and abs(h - LETTER[1]) < 6) or \
         (abs(w - A4[0]) < 6 and abs(h - A4[1]) < 6)
    if not ok:
        return finding("I_PAGE_FORMAT", "Serious", "fail",
                       "Sheet is %dx%d pt, neither US Letter (612x792) nor A4 "
                       "(595x842)." % (w, h), location="whole document",
                       fix="Reformat to US Letter or A4.")
    return finding("I_PAGE_FORMAT", "Serious", "pass",
                   "%d sheets, uniform %dx%d pt." % (len(pdf["pages"]), w, h))

# ----------------------------------------------------------------- fees & entity

# Illustrative 37 CFR 1.16 tiers used only to check claim-count arithmetic.
# Dollar amounts go stale. Re-verify against the current USPTO fee schedule
# before relying on a computed total.
FEE_SCHEDULE = {
    "basic_filing": {"large": 320, "small": 160, "micro": 80},
    "search": {"large": 700, "small": 350, "micro": 175},
    "examination": {"large": 800, "small": 400, "micro": 200},
    "each_claim_over_20": {"large": 100, "small": 50, "micro": 25},
    "each_indep_over_3": {"large": 480, "small": 240, "micro": 120},
    "multiple_dependent": {"large": 860, "small": 430, "micro": 215},
}

@check("I_FEE_ARITHMETIC", "Serious", "Claim-count fee arithmetic",
       covers=["I14"])
def fees(p, intake):
    entity = (intake or {}).get("entity_status")
    if entity not in ("large", "small", "micro"):
        return finding("I_FEE_ARITHMETIC", "Serious", "cannot_assess",
                       "entity_status not supplied in intake (large|small|micro); "
                       "fee tier cannot be computed.")
    cc = p["claim_counts"]
    over20 = max(0, cc["total"] - 20)
    over3 = max(0, cc["independent"] - 3)
    lines, total = [], 0
    for key, qty in (("basic_filing", 1), ("search", 1), ("examination", 1),
                     ("each_claim_over_20", over20), ("each_indep_over_3", over3),
                     ("multiple_dependent", 1 if cc["multiple_dependent"] else 0)):
        if qty:
            amt = FEE_SCHEDULE[key][entity] * qty
            total += amt
            lines.append("%s x%d = $%d" % (key, qty, amt))
    return finding(
        "I_FEE_ARITHMETIC", "Serious", "cannot_assess",
        "Computed from %d claims (%d independent) at %s entity: %s. TOTAL $%d "
        "using illustrative 37 CFR 1.16 tiers — these MUST be re-verified against "
        "the current USPTO fee schedule before filing."
        % (cc["total"], cc["independent"], entity, "; ".join(lines), total),
        location="fee transmittal",
        candidates={"entity": entity, "counts": cc, "lines": lines,
                    "illustrative_total_dollars": total},
        fix="Confirm each amount at uspto.gov/learning-and-resources/fees-and-payment.")

@check("I_EXCESS_CLAIMS", "Quality", "Claim count against the fee thresholds",
       covers=["G63", "G64", "I14"])
def excess_claims(p, intake):
    cc = p["claim_counts"]
    msgs = []
    if cc["total"] > 20:
        msgs.append("%d total claims exceeds the 20 included" % cc["total"])
    if cc["independent"] > 3:
        msgs.append("%d independent claims exceeds the 3 included" % cc["independent"])
    if cc["multiple_dependent"]:
        msgs.append("%d multiple-dependent claim(s) incur a separate surcharge and "
                    "count as their several dependencies" % cc["multiple_dependent"])
    if msgs:
        return finding("I_EXCESS_CLAIMS", "Quality", "fail", "; ".join(msgs),
                       location="claims",
                       fix="Either accept the excess-claim fees deliberately or "
                           "consolidate before filing.")
    return finding("I_EXCESS_CLAIMS", "Quality", "pass",
                   "%d claims, %d independent — within the fee-included limits."
                   % (cc["total"], cc["independent"]))

# --------------------------------------------------------------------------- main

def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("parsed", help="parsed.json from parse_application.py")
    ap.add_argument("-o", "--out", default="findings_mechanical.json")
    ap.add_argument("--intake", help="intake.yaml/json for entity status etc.")
    args = ap.parse_args()

    p = json.load(open(args.parsed, encoding="utf-8"))
    intake = {}
    if args.intake:
        raw = open(args.intake, encoding="utf-8").read()
        try:
            import yaml
            intake = yaml.safe_load(raw) or {}
        except ImportError:
            try:
                intake = json.loads(raw)
            except ValueError:
                sys.exit("intake file is YAML but PyYAML is not installed: "
                         "pip install pyyaml (or supply JSON)")

    results, diagnostics = [], []
    for item_id, severity, title, covers, fn in CHECKS:
        try:
            r = fn(p, intake)
        except Exception as exc:                      # a broken check must not pass
            r = finding(item_id, severity, "cannot_assess",
                        "check raised %s: %s" % (type(exc).__name__, exc))
        r["covers"] = list(covers)
        diagnostics.append(r)
        # Credit the checklist items this check contributes to, so coverage
        # accounting reflects the mechanical pass.
        for cid in covers:
            c = dict(r, item_id=cid, source="mechanical:%s" % item_id)
            c.pop("covers", None)
            results.append(c)
    results.extend(diagnostics)
    json.dump(results, open(args.out, "w", encoding="utf-8"), indent=1,
              ensure_ascii=False)

    tally = {}
    for r in diagnostics:
        tally[r["verdict"]] = tally.get(r["verdict"], 0) + 1
    width = max(len(r["item_id"]) for r in diagnostics)
    for r in diagnostics:
        mark = {"pass": "PASS", "fail": "FAIL", "cannot_assess": "????",
                "not_applicable": " n/a"}[r["verdict"]]
        print("%s  %-*s  %s" % (mark, width, r["item_id"], r["explanation"][:150]))
    print("\n%s  ->  %s" % (", ".join("%s=%d" % kv for kv in sorted(tally.items())),
                            args.out))

if __name__ == "__main__":
    main()
```

## File: patent-audit/scripts/parse_application.py
size: 16428
sha: fb303dbf88e9bb62f9b5a267193ad5c8d69b360c
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/scripts/parse_application.py

```text
#!/usr/bin/env python3
"""Parse a draft patent application into a structured JSON fact-pack.

Every downstream agent reads this instead of raw text, so the expensive,
error-prone bookkeeping (claim dependency graphs, reference-numeral
cross-referencing, antecedent-basis candidates) happens once, in code, exactly.

    python parse_application.py DRAFT [-o parsed.json] [--drawings DIR_OR_PDF]

DRAFT may be .txt, .md, .pdf or .docx. PDF needs PyMuPDF; .docx needs python-docx.
Missing optional dependencies degrade to a clear error, never to silent partial
output.
"""
from __future__ import annotations

import argparse
import json
import os
import re
import sys

# Canonical specification sections, in the order the PTO expects them.
SECTION_PATTERNS = [
    ("title", r"^\s*(?:TITLE(?:\s+OF\s+THE\s+INVENTION)?)\s*:?\s*$"),
    ("cross_reference", r"^\s*CROSS[- ]REFERENCES?\s+TO\s+RELATED\s+APPLICATIONS?\s*:?\s*$"),
    ("federal_research", r"^\s*(?:STATEMENT\s+REGARDING\s+)?FEDERALLY[- ]SPONSORED\s+"
                         r"(?:RESEARCH|R\s*&\s*D).*$"),
    ("sequence_listing", r"^\s*(?:REFERENCE\s+TO\s+)?SEQUENCE\s+LISTING.*$"),
    ("field", r"^\s*(?:TECHNICAL\s+)?FIELD(?:\s+OF\s+THE\s+INVENTION)?\s*:?\s*$"),
    ("background", r"^\s*BACKGROUND(?:\s+OF\s+THE\s+INVENTION)?.*$"),
    ("summary", r"^\s*(?:BRIEF\s+)?SUMMARY(?:\s+OF\s+THE\s+INVENTION)?.*$"),
    ("drawing_description", r"^\s*BRIEF\s+DESCRIPTION\s+OF\s+THE\s+(?:SEVERAL\s+VIEWS\s+OF\s+THE\s+)?"
                            r"DRAWINGS?.*$"),
    ("detailed_description", r"^\s*DETAILED\s+DESCRIPTION.*$"),
    ("claims", r"^\s*(?:CLAIMS?|(?:I|WE)\s+CLAIM|WHAT\s+IS\s+CLAIMED\s+IS|"
               r"THE\s+INVENTION\s+CLAIMED\s+IS)\s*:?\s*$"),
    ("abstract", r"^\s*ABSTRACT(?:\s+OF\s+THE\s+DISCLOSURE)?\s*:?\s*$"),
]

TRANSITIONS = [
    ("comprising", r"\bcompris(?:ing|es)\b"),
    ("consisting_essentially_of", r"\bconsisting\s+essentially\s+of\b"),
    ("consisting_of", r"\bconsisting\s+of\b"),
    ("including", r"\binclud(?:ing|es)\b"),
    ("having", r"\bhaving\b"),
    ("which_comprises", r"\bwhich\s+comprises\b"),
]

# "the widget", "said upper housing" -- candidate antecedent references.
DEF_REF = re.compile(r"\b(?:the|said)\s+((?:[a-z][a-z\-]+\s+){0,4}[a-z][a-z\-]+)", re.I)
INDEF_REF = re.compile(r"\b(?:a|an)\s+((?:[a-z][a-z\-]+\s+){0,4}[a-z][a-z\-]+)", re.I)

# A noun phrase ends at any of these; without truncation "a cylindrical body of
# insulating material" registers its head as "material" and the later "said
# body" is wrongly flagged as lacking an antecedent.
NP_STOP = {
    "of", "with", "for", "that", "which", "is", "are", "was", "were", "be",
    "being", "been", "has", "have", "having", "and", "or", "to", "in", "into",
    "on", "at", "by", "from", "within", "between", "through", "over", "under",
    "comprising", "comprises", "including", "includes", "wherein", "whereby",
    "said", "the", "a", "an", "disposed", "positioned", "arranged", "coupled",
    "connected", "attached", "mounted", "secured", "formed", "extending",
    "adapted", "configured", "operable", "capable", "when", "while", "then",
    "so", "such", "thereby", "further", "also", "may", "can", "will", "shall",
}

# Words that are never the head of a claim element, so a "the <word>" hit is not
# a real antecedent-basis candidate.
NON_ELEMENT_HEADS = {
    "art", "invention", "embodiment", "figure", "drawing", "specification",
    "same", "other", "first", "second", "third", "one", "another", "above",
    "following", "present", "prior", "group", "claim", "claims", "steps",
    "step", "method", "process", "case", "event", "time", "order", "number",
    "amount", "way", "art-recognized", "user", "art recognized",
}

# --------------------------------------------------------------------------- io

def load_text(path):
    ext = os.path.splitext(path)[1].lower()
    if ext in (".txt", ".md"):
        return open(path, encoding="utf-8", errors="replace").read(), None
    if ext == ".pdf":
        try:
            import fitz
        except ImportError:
            sys.exit("PDF input needs PyMuPDF:  pip install pymupdf")
        doc = fitz.open(path)
        pages = [doc[i].get_text("text") for i in range(len(doc))]
        geom = [{"page": i + 1, "width_pt": doc[i].rect.width,
                 "height_pt": doc[i].rect.height} for i in range(len(doc))]
        return "\n".join(pages), {"pages": geom, "page_texts": pages}
    if ext == ".docx":
        try:
            import docx
        except ImportError:
            sys.exit("DOCX input needs python-docx:  pip install python-docx")
        return "\n".join(p.text for p in docx.Document(path).paragraphs), None
    sys.exit("unsupported input type: %s (use .txt, .md, .pdf or .docx)" % ext)

# ---------------------------------------------------------------------- sections

def split_sections(text):
    """Locate canonical headings; return {name: {...}} plus anything before the first."""
    lines = text.split("\n")
    hits = []
    for idx, line in enumerate(lines):
        for name, pat in SECTION_PATTERNS:
            if re.match(pat, line.strip(), re.I):
                hits.append((idx, name))
                break
    out, missing = {}, []
    for i, (idx, name) in enumerate(hits):
        end = hits[i + 1][0] if i + 1 < len(hits) else len(lines)
        body = "\n".join(lines[idx + 1:end]).strip()
        # A heading may legitimately repeat (e.g. BACKGROUND then a subheading);
        # keep the first, longest occurrence.
        if name not in out or len(body) > len(out[name]["text"]):
            out[name] = {"line": idx + 1, "heading": lines[idx].strip(), "text": body}
    for name, _ in SECTION_PATTERNS:
        if name not in out:
            missing.append(name)
    preamble = "\n".join(lines[:hits[0][0]]).strip() if hits else text.strip()
    return out, missing, preamble

# ------------------------------------------------------------------------ claims

def parse_claims(claims_text):
    """Split the claim set and decompose each claim."""
    if not claims_text:
        return []
    # A claim starts at a line-leading number followed by . or )
    parts = re.split(r"(?m)^\s*(\d{1,3})\s*[\.\)]\s+", "\n" + claims_text)
    claims = []
    for i in range(1, len(parts) - 1, 2):
        num, body = int(parts[i]), parts[i + 1].strip()
        claims.append(build_claim(num, body))
    return claims

def build_claim(num, body):
    flat = re.sub(r"\s+", " ", body).strip()

    dep = re.search(
        r"\b(?:of|in|to|according\s+to|as\s+(?:set\s+forth|recited|claimed)\s+in|defined\s+in)\s+"
        r"(?:any\s+(?:one\s+)?of\s+)?claims?\s+(\d+)(?:\s*(?:-|to|through|,|or|and)\s*(\d+))?",
        flat, re.I)
    parents, multiple = [], False
    if dep:
        parents = [int(dep.group(1))]
        if dep.group(2):
            multiple = True
            parents.append(int(dep.group(2)))
        if re.search(r"any\s+(?:one\s+)?of\s+claims", flat, re.I):
            multiple = True

    transition, t_pos = None, None
    for name, pat in TRANSITIONS:
        m = re.search(pat, flat, re.I)
        if m and (t_pos is None or m.start() < t_pos):
            transition, t_pos = name, m.start()

    preamble = flat[:t_pos].strip() if t_pos is not None else flat
    rest = flat[t_pos:] if t_pos is not None else ""
    elements = [e.strip() for e in re.split(r";\s*(?:and\s+)?", rest) if e.strip()]

    return {
        "number": num,
        "text": flat,
        "type": "dependent" if parents else "independent",
        "parents": parents,
        "multiple_dependent": multiple,
        "preamble": preamble,
        "transition": transition,
        "elements": elements,
        "element_count": len(elements),
        "word_count": len(flat.split()),
        "sentence_count": flat.count(".") if flat.endswith(".") else flat.count(".") + 1,
        "ends_with_period": flat.rstrip().endswith("."),
        "internal_periods": len(re.findall(r"\.(?=\s+[A-Za-z])", flat)),
        "means_plus_function": bool(re.search(r"\bmeans\s+for\b|\bstep\s+for\b", flat, re.I)),
        "uses_whereby": bool(re.search(r"\bwhereby\b", flat, re.I)),
        "relative_terms": sorted({w.lower() for w in re.findall(
            r"\b(?:about|approximately|substantially|relatively|essentially|"
            r"generally|preferably|optionally|such\s+as|thin|thick|large|small|"
            r"strong|light|heavy|near|close)\b", flat, re.I)}),
    }

def claim_ancestry(claims):
    """Resolve each claim's full parent chain, marking cycles and dangling refs."""
    by_num = {c["number"]: c for c in claims}
    for c in claims:
        chain, seen, cur = [], set(), c
        while cur["parents"]:
            p = cur["parents"][0]
            if p in seen or p not in by_num:
                break
            seen.add(p)
            chain.append(p)
            cur = by_num[p]
        c["ancestry"] = chain
        c["dangling_parents"] = [p for p in c["parents"] if p not in by_num]
        c["forward_reference"] = [p for p in c["parents"] if p >= c["number"]]
    return claims

# -------------------------------------------------------------- antecedent basis

def noun_phrase(raw):
    """Trim a captured span down to the noun phrase itself."""
    words = []
    for w in re.split(r"\s+", raw.strip().lower()):
        if not w or w in NP_STOP:
            break
        words.append(w)
    return " ".join(words)

def phrase_forms(np):
    """Every suffix of a noun phrase, so 'a tension band' also introduces 'band'."""
    words = np.split()
    return {" ".join(words[i:]) for i in range(len(words))} if words else set()

def antecedent_candidates(claim, ancestry_text):
    """Definite references with no earlier indefinite introduction.

    Deliberately over-inclusive: a model adjudicates the list. An inherent
    property ("the length of the rod") is legitimate without an antecedent, and
    only a reader can tell that from a genuine missing element.
    """
    scope = ancestry_text + " " + claim["text"]
    introduced = set()
    for m in INDEF_REF.finditer(scope):
        introduced |= phrase_forms(noun_phrase(m.group(1)))
    # A claim's own preamble introduces its subject without an article.
    introduced |= phrase_forms(noun_phrase(
        re.sub(r"^(?:an?|the)\s+", "", claim["preamble"].strip().lower())))

    flagged, seen = [], set()
    for m in DEF_REF.finditer(claim["text"]):
        np = noun_phrase(m.group(1))
        if not np:
            continue
        head = np.split()[-1]
        if head in NON_ELEMENT_HEADS or np in NON_ELEMENT_HEADS:
            continue
        if phrase_forms(np) & introduced:
            continue
        if np in seen:
            continue
        seen.add(np)
        flagged.append({"phrase": "%s %s" % (m.group(0).split()[0], np),
                        "noun": np, "offset": m.start()})
    return flagged

# ------------------------------------------------------------ reference numerals

def reference_numerals(sections):
    """Numerals used in the description vs. those introduced in the drawing list."""
    desc = " ".join(sections.get(k, {}).get("text", "")
                    for k in ("detailed_description", "summary", "drawing_description"))
    detail_only = sections.get("detailed_description", {}).get("text", "")

    # A reference numeral follows a noun: "housing 10", "the upper plate 12a".
    pat = re.compile(r"\b([a-z][a-z\-]{2,})\s+(\d{1,3}[a-z]?)\b")
    found = {}
    for m in pat.finditer(detail_only):
        found.setdefault(m.group(2), set()).add(m.group(1).lower())
    counts = {}
    for m in re.finditer(r"\b(\d{1,3}[a-z]?)\b", detail_only):
        counts[m.group(1)] = counts.get(m.group(1), 0) + 1

    figs = sorted({m.group(1) for m in re.finditer(
        r"\bFIGS?\.?\s*(\d+[A-Za-z]?)", desc, re.I)})

    return {
        "numerals": sorted(found, key=lambda s: (len(s), s)),
        "numeral_labels": {k: sorted(v) for k, v in sorted(found.items())},
        "numeral_mention_counts": {k: counts.get(k, 0) for k in sorted(found)},
        "single_use_numerals": sorted(k for k in found if counts.get(k, 0) < 2),
        "inconsistent_labels": {k: sorted(v) for k, v in sorted(found.items())
                                if len(v) > 1},
        "figures_referenced": figs,
    }

# ----------------------------------------------------------------------- drawings

def drawing_inventory(path):
    if not path:
        return None
    if os.path.isdir(path):
        sheets = sorted(f for f in os.listdir(path)
                        if os.path.splitext(f)[1].lower()
                        in (".png", ".jpg", ".jpeg", ".tif", ".tiff", ".pdf"))
        return {"source": path, "sheet_count": len(sheets), "sheets": sheets}
    try:
        import fitz
    except ImportError:
        return {"source": path, "error": "PyMuPDF not installed; cannot inspect"}
    doc = fitz.open(path)
    sheets, labels = [], set()
    for i in range(len(doc)):
        t = doc[i].get_text("text")
        labels |= {m.group(1) for m in re.finditer(r"\bFIGS?\.?\s*(\d+[A-Za-z]?)", t, re.I)}
        sheets.append({"sheet": i + 1,
                       "width_pt": doc[i].rect.width, "height_pt": doc[i].rect.height,
                       "numerals": sorted({m.group(1) for m in
                                           re.finditer(r"\b(\d{1,3}[a-z]?)\b", t)}),
                       "has_text_layer": bool(t.strip())})
    return {"source": path, "sheet_count": len(sheets), "sheets": sheets,
            "figures_labelled": sorted(labels)}

# --------------------------------------------------------------------------- main

def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("draft")
    ap.add_argument("-o", "--out", default="parsed.json")
    ap.add_argument("--drawings", help="drawing sheets: a PDF or a directory of images")
    args = ap.parse_args()

    text, pdfmeta = load_text(args.draft)
    sections, missing, preamble = split_sections(text)
    claims = claim_ancestry(parse_claims(sections.get("claims", {}).get("text", "")))

    by_num = {c["number"]: c for c in claims}
    for c in claims:
        anc = " ".join(by_num[p]["text"] for p in c["ancestry"] if p in by_num)
        c["antecedent_candidates"] = antecedent_candidates(c, anc)

    abstract = sections.get("abstract", {}).get("text", "")
    out = {
        "source": os.path.abspath(args.draft),
        "char_count": len(text),
        "word_count": len(text.split()),
        "sections_found": sorted(sections),
        "sections_missing": missing,
        "section_order": [n for n, _ in sorted(
            ((n, s["line"]) for n, s in sections.items()), key=lambda kv: kv[1])],
        "preamble_before_first_heading": preamble[:2000],
        "sections": sections,
        "title": (sections.get("title", {}).get("text", "") or preamble).strip()[:300],
        "abstract": {
            "text": abstract,
            "word_count": len(abstract.split()),
            "sentence_count": len([s for s in re.split(r"(?<=[.!?])\s+", abstract) if s.strip()]),
        },
        "claims": claims,
        "claim_counts": {
            "total": len(claims),
            "independent": sum(1 for c in claims if c["type"] == "independent"),
            "dependent": sum(1 for c in claims if c["type"] == "dependent"),
            "multiple_dependent": sum(1 for c in claims if c["multiple_dependent"]),
        },
        "reference_numerals": reference_numerals(sections),
        "drawings": drawing_inventory(args.drawings),
        "pdf": pdfmeta and {"pages": pdfmeta["pages"]},
    }
    json.dump(out, open(args.out, "w", encoding="utf-8"), indent=1, ensure_ascii=False)

    print("parsed  %s" % args.draft)
    print("  sections found   : %s" % ", ".join(out["sections_found"]))
    if missing:
        print("  sections missing : %s" % ", ".join(missing))
    print("  claims           : %d (%d independent, %d dependent)" % (
        out["claim_counts"]["total"], out["claim_counts"]["independent"],
        out["claim_counts"]["dependent"]))
    print("  numerals         : %d" % len(out["reference_numerals"]["numerals"]))
    print("  abstract words   : %d" % out["abstract"]["word_count"])
    print("  wrote            : %s" % args.out)

if __name__ == "__main__":
    main()
```

## File: patent-audit/scripts/prepass.py
size: 4145
sha: c3f6e2d475a31076edc8668e71ada96465c09aee
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/scripts/prepass.py

```text
#!/usr/bin/env python3
"""Run the whole deterministic pre-pass and scaffold the working directory.

    python prepass.py --draft DRAFT [--drawings D] [--intake intake.yaml]
                      [--workdir audit_run] [--asof YYYY-MM-DD]

With no --intake, copies the questionnaire template in and stops, because the
gates cannot run on assumed facts. Everything it produces lands in --workdir:

    parsed.json                 structured draft — every agent reads this
    deadlines.json              computed dates, rollover applied
    findings/findings_mechanical.json
    intake.yaml                 (template, if you did not supply one)
    findings/                   agents write <agent>.json here

Exits 2 if the parse looks wrong, so a bad parse cannot silently produce a
confident audit of nothing.
"""
from __future__ import annotations

import argparse
import json
import os
import shutil
import subprocess
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)

def run(script, *args):
    cmd = [sys.executable, os.path.join(HERE, script)] + [str(a) for a in args]
    # flush, or this banner lands after the child's output
    print("\n$ %s %s" % (script, " ".join(str(a) for a in args)), flush=True)
    return subprocess.run(cmd).returncode

def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--draft", required=True)
    ap.add_argument("--drawings")
    ap.add_argument("--intake")
    ap.add_argument("--workdir", default="audit_run")
    ap.add_argument("--asof")
    args = ap.parse_args()

    wd = os.path.abspath(args.workdir)
    os.makedirs(os.path.join(wd, "findings"), exist_ok=True)
    parsed = os.path.join(wd, "parsed.json")

    pa = ["parse_application.py", args.draft, "-o", parsed]
    if args.drawings:
        pa += ["--drawings", args.drawings]
    if run(*pa) != 0:
        return 2

    p = json.load(open(parsed, encoding="utf-8"))
    problems = []
    if not p["claims"]:
        problems.append("no claims were parsed")
    if len(p["sections_found"]) < 4:
        problems.append("only %d sections recognised: %s"
                        % (len(p["sections_found"]), p["sections_found"]))
    if not p["reference_numerals"]["numerals"] and p["sections"].get("detailed_description"):
        problems.append("no reference numerals found in the detailed description")
    if problems:
        print("\n!! The draft did not parse cleanly:")
        for x in problems:
            print("     - %s" % x)
        print("   Every downstream agent reads parsed.json, so fix the parse before\n"
              "   dispatching them — otherwise they audit a document that isn't there.\n"
              "   Usually the draft uses unusual section headings or claim numbering.")
        return 2

    intake = args.intake
    if not intake:
        dest = os.path.join(wd, "intake.yaml")
        if not os.path.exists(dest):
            shutil.copy(os.path.join(ROOT, "assets", "intake.yaml"), dest)
        print("\n!! No intake supplied. Template written to:\n     %s\n"
              "   Parts A, C and D cannot run until it is filled in. %d checklist\n"
              "   items are answerable ONLY from intake facts — no document review\n"
              "   can reach them." % (dest, count_intake_only()))
        return 1

    run("mechanical_checks.py", parsed, "--intake", intake,
        "-o", os.path.join(wd, "findings", "findings_mechanical.json"))
    dl = ["deadlines.py", intake, "-o", os.path.join(wd, "deadlines.json")]
    if args.asof:
        dl += ["--asof", args.asof]
    run(*dl)

    print("\npre-pass complete. Working directory: %s" % wd)
    print("Next: dispatch the gate agents (Phase 2), then the fan-out (Phase 3).")
    return 0

def count_intake_only():
    idx = json.load(open(os.path.join(ROOT, "reference", "checklist_index.json"),
                         encoding="utf-8"))
    return sum(1 for it in idx if it.get("inputs") == ["intake_facts"])

if __name__ == "__main__":
    raise SystemExit(main())
```

## File: patent-audit/scripts/synthesize.py
size: 8605
sha: 8e6706c36a16fbfd56fb053466435d3fb413ba95
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/scripts/synthesize.py

```text
#!/usr/bin/env python3
"""Merge all findings into one ranked report with honest coverage accounting.

    python synthesize.py FINDINGS_DIR [-o audit_report.md] [--json report.json]
                         [--deadlines deadlines.json]

Reads every *.json in FINDINGS_DIR (agent output plus findings_mechanical.json),
joins them to the checklist by item_id, and reports what was assessed, what
failed, and — the part most audits omit — what could not be assessed and why.

An item with no finding from any source is reported as `not_reached`. Silence
is never counted as a pass.
"""
from __future__ import annotations

import argparse
import glob
import json
import os
from collections import Counter, defaultdict

HERE = os.path.dirname(os.path.abspath(__file__))
INDEX = os.path.join(HERE, "..", "reference", "checklist_index.json")

SEV_ORDER = {"Fatal": 0, "Serious": 1, "Quality": 2}
VERDICTS = ("fail", "cannot_assess", "pass", "not_applicable", "not_reached")

def load_findings(d):
    out = []
    for fn in sorted(glob.glob(os.path.join(d, "*.json"))):
        if os.path.basename(fn) in ("deadlines.json", "parsed.json"):
            continue
        try:
            data = json.load(open(fn, encoding="utf-8"))
        except ValueError as e:
            print("  ! skipping %s: %s" % (os.path.basename(fn), e))
            continue
        if isinstance(data, dict):
            data = data.get("findings", [])
        for f in data:
            if isinstance(f, dict) and f.get("item_id"):
                f.setdefault("source", os.path.basename(fn).replace(".json", ""))
                out.append(f)
    return out

def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("findings_dir")
    ap.add_argument("-o", "--out", default="audit_report.md")
    ap.add_argument("--json", dest="jsonout")
    ap.add_argument("--deadlines")
    ap.add_argument("--title", default="Pre-filing patent application audit")
    args = ap.parse_args()

    index = {it["id"]: it for it in json.load(open(INDEX, encoding="utf-8"))}
    findings = load_findings(args.findings_dir)

    # An item may be reported by more than one agent; keep the worst verdict.
    worst = {}
    extra = []
    for f in findings:
        iid = f["item_id"]
        if iid not in index:
            extra.append(f)          # e.g. the mechanical checks' own IDs
            continue
        prev = worst.get(iid)
        if prev is None or VERDICTS.index(f.get("verdict", "not_reached")) < \
                VERDICTS.index(prev.get("verdict", "not_reached")):
            worst[iid] = f

    rows = []
    for iid, it in index.items():
        f = worst.get(iid)
        rows.append({
            "id": iid, "part": it["part"], "part_title": it["part_title"],
            "section": it["section"], "title": it["title"], "check": it["check"],
            "severity": it["severity"],
            "verdict": (f or {}).get("verdict", "not_reached"),
            "location": (f or {}).get("location", ""),
            "evidence": (f or {}).get("evidence", ""),
            "explanation": (f or {}).get("explanation", ""),
            "suggested_fix": (f or {}).get("suggested_fix", ""),
            "source": (f or {}).get("source", ""),
            "verified_by": (f or {}).get("verified_by", ""),
        })
    rows.sort(key=lambda r: (VERDICTS.index(r["verdict"]),
                             SEV_ORDER.get(r["severity"], 3), r["id"]))

    tally = Counter(r["verdict"] for r in rows)
    bypart = defaultdict(Counter)
    for r in rows:
        bypart[r["part"]][r["verdict"]] += 1

    fails = [r for r in rows if r["verdict"] == "fail"]
    blockers = [r for r in fails if r["severity"] == "Fatal"]
    unknown = [r for r in rows if r["verdict"] == "cannot_assess"]
    unreached = [r for r in rows if r["verdict"] == "not_reached"]

    dl = json.load(open(args.deadlines, encoding="utf-8")) if args.deadlines else None

    L = []
    w = L.append
    w("# %s\n" % args.title)
    if blockers:
        w("> **DO NOT FILE.** %d fatal item(s) failed. See *Blocking* below.\n"
          % len(blockers))
    elif fails:
        w("> %d item(s) failed, none fatal. Resolve or accept each before filing.\n"
          % len(fails))
    elif unreached or unknown:
        w("> No failures, but %d item(s) could not be assessed and %d were never "
          "reached. Coverage is incomplete.\n" % (len(unknown), len(unreached)))
    else:
        w("> All %d items assessed and passed.\n" % len(rows))

    w("## Coverage\n")
    w("| Verdict | Count |\n|---|---:|")
    for v in VERDICTS:
        w("| %s | %d |" % (v, tally.get(v, 0)))
    w("| **total** | **%d** |\n" % len(rows))

    w("| Part | fail | cannot_assess | not_reached | pass | n/a |\n"
      "|---|---:|---:|---:|---:|---:|")
    for p in sorted(bypart):
        c = bypart[p]
        w("| %s %s | %d | %d | %d | %d | %d |" % (
            p, index and next(r["part_title"] for r in rows if r["part"] == p),
            c["fail"], c["cannot_assess"], c["not_reached"], c["pass"],
            c["not_applicable"]))
    w("")

    if dl:
        w("## Deadlines\n")
        bad = [e for e in dl["deadlines"] if e["status"] in ("MISSED", "URGENT")]
        if bad:
            w("| Status | Deadline | Due | Days | Consequence |\n|---|---|---|---:|---|")
            for e in bad:
                w("| **%s** | %s | %s | %s | %s |" % (
                    e["status"], e["deadline"], e["due"],
                    "" if e["days_remaining"] is None else e["days_remaining"],
                    e["consequence_if_missed"]))
            w("")
        for wn in dl.get("warnings", []):
            w("> %s\n" % wn)

    def block(title, items, body=True):
        if not items:
            return
        w("---\n\n## %s (%d)\n" % (title, len(items)))
        for r in items:
            w("### `%s` %s — %s" % (r["id"], r["title"], r["severity"]))
            w("*Part %s · %s*  \n**Check:** %s\n" % (r["part"], r["section"], r["check"]))
            if body:
                if r["location"]:
                    w("**Where:** %s  " % r["location"])
                if r["explanation"]:
                    w("**Finding:** %s  " % r["explanation"])
                if r["evidence"]:
                    w("\n> %s\n" % r["evidence"].replace("\n", "\n> "))
                if r["suggested_fix"]:
                    w("**Fix:** %s  " % r["suggested_fix"])
                if r["verified_by"]:
                    w("*Independently verified by: %s*  " % r["verified_by"])
            w("")

    block("Blocking — must be resolved before filing", blockers)
    block("Failed — not fatal", [r for r in fails if r["severity"] != "Fatal"])
    block("Could not be assessed", unknown)

    if unreached:
        w("---\n\n## Not reached (%d)\n" % len(unreached))
        w("No agent reported on these. Either the owning agent did not run, or it "
          "silently skipped them. Treat as unaudited, not as passing.\n")
        w("| ID | Severity | Check |\n|---|---|---|")
        for r in unreached:
            w("| `%s` | %s | %s |" % (r["id"], r["severity"], r["check"][:110]))
        w("")

    if extra:
        w("---\n\n## Mechanical pre-pass results\n")
        w("Deterministic checks that do not map onto a single checklist item.\n")
        w("| Check | Verdict | Detail |\n|---|---|---|")
        for f in extra:
            w("| `%s` | %s | %s |" % (f["item_id"], f.get("verdict", ""),
                                      f.get("explanation", "")[:160].replace("|", "\\|")))
        w("")

    w("---\n\n*Checklist: %d items grounded in 35 U.S.C., 37 CFR, the MPEP, "
      "and current USPTO practice. Fee amounts and form names must be "
      "re-verified against the current official fee schedule and forms page. "
      "Not legal advice.*" % len(rows))

    open(args.out, "w", encoding="utf-8").write("\n".join(L))
    if args.jsonout:
        json.dump({"summary": dict(tally), "rows": rows,
                   "mechanical_extra": extra, "deadlines": dl},
                  open(args.jsonout, "w", encoding="utf-8"), indent=1,
                  ensure_ascii=False)

    print("coverage: " + ", ".join("%s=%d" % (v, tally.get(v, 0)) for v in VERDICTS))
    print("blocking: %d   failed: %d   unknown: %d   unreached: %d"
          % (len(blockers), len(fails), len(unknown), len(unreached)))
    print("wrote %s" % args.out)
    return 1 if blockers else 0

if __name__ == "__main__":
    raise SystemExit(main())
```

## File: patent-audit/scripts/test_primary_source_hygiene.py
size: 7974
sha: 576b83e423ff3165e458cc24c8f5c0fd2672f54c
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/scripts/test_primary_source_hygiene.py

```text
#!/usr/bin/env python3
"""Drive the shipped audit scripts and reject book-extraction residue.

This is not a string-list unit test of a reimplementation. It:
  1. walks the shipped skill tree for forbidden attribution strings
  2. checks every checklist item in the part files has a Primary source cite
  3. runs parse_application / mechanical_checks / deadlines / synthesize
     (the same entry points prepass.py shells out to) on assets/sample_draft.md
"""
from __future__ import annotations

import json
import os
import re
import subprocess
import sys
import tempfile

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
REPO = os.path.dirname(ROOT)
# Live installs that must stay in lockstep with this skill.
SIBLING_TREES = [
    os.path.join(os.path.expanduser("~"), ".grok", "skills", "patent-audit"),
    os.path.join(os.path.expanduser("~"), "skills", "patent-audit"),
    os.path.join(os.path.expanduser("~"), ".codex", "skills", "patent-audit"),
]

# Patterns assembled at runtime so this test file itself is not a hit list.
FORBIDDEN = [
    "".join(("Patent", " It ", "Yourself")),
    "".join(("Press", "man")),
    r"\b" + "No" + "lo" + r"\b",
    "".join(("Book", " support")),
    "Inventor.?" + "s Commandment",
    r"\b" + "Le" + "Roy" + r"\b",
    r"\b" + "Grisel" + "da" + r"\b",
    r"\b" + "Mil" + "lie" + r"\b",
    "Sam " + "Searcher",
    r"\b" + "Pre" + "witt" + r"\b",
    "extracted" + " from",
    "book " + "Appendix",
    "book" + "_page",
    r"\(p\. \d",
    r"pp\. \d{2,}",
]

SKIP_DIR_NAMES = {".git", "__pycache__", ".venv", "venv"}
SKIP_FILES = {os.path.basename(__file__)}

def die(msg):
    print("FAIL:", msg, file=sys.stderr)
    raise SystemExit(1)

def walk_tree(root):
    if not os.path.isdir(root):
        return
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = [d for d in dirnames if d not in SKIP_DIR_NAMES]
        for name in filenames:
            if name in SKIP_FILES:
                continue
            path = os.path.join(dirpath, name)
            if os.path.splitext(name)[1].lower() in {
                ".md", ".py", ".yaml", ".yml", ".json", ".txt"
            } or name in {".gitignore"}:
                yield path

def shipped_files():
    seen = set()
    for root in [REPO] + SIBLING_TREES:
        for path in walk_tree(root):
            key = os.path.normcase(os.path.abspath(path))
            if key in seen:
                continue
            seen.add(key)
            yield path

def test_no_forbidden_strings():
    hits = []
    compiled = [(pat, re.compile(pat, re.I)) for pat in FORBIDDEN]
    for path in shipped_files():
        try:
            text = open(path, encoding="utf-8").read()
        except (OSError, UnicodeDecodeError):
            continue
        for pat, rx in compiled:
            for m in rx.finditer(text):
                line = text.count("\n", 0, m.start()) + 1
                rel = os.path.relpath(path, REPO)
                hits.append("%s:%d: %s" % (rel, line, pat))
    if hits:
        die("forbidden attribution still present:\n  " + "\n  ".join(hits[:40]))
    print("ok  no forbidden attribution strings in shipped tree")

def test_part_files_are_primary_source():
    index = json.load(open(os.path.join(ROOT, "reference", "checklist_index.json"),
                           encoding="utf-8"))
    by_part = {}
    for item in index:
        by_part.setdefault(item["part"], []).append(item["id"])

    parts_dir = os.path.join(ROOT, "reference", "parts")
    sampled = []
    for part, ids in sorted(by_part.items()):
        matches = [n for n in os.listdir(parts_dir) if n.startswith(part + "_")]
        if len(matches) != 1:
            die("expected one part file for %s, found %s" % (part, matches))
        text = open(os.path.join(parts_dir, matches[0]), encoding="utf-8").read()
        if "".join(("Book", " support")) in text:
            die("%s still has quoted-guide support blocks" % matches[0])
        found_ids = re.findall(r"^### `([A-Z]\d+)`", text, re.M)
        if found_ids != ids:
            die("%s item ids %s != index %s" % (matches[0], found_ids, ids))
        for item_id in ids:
            chunk = text.split("### `%s`" % item_id, 1)[1]
            next_h = re.search(r"\n### `", chunk)
            if next_h:
                chunk = chunk[:next_h.start()]
            if "**Primary source:**" not in chunk:
                die("%s has no Primary source cite" % item_id)
            if not re.search(r"35 U\.S\.C\.|37 CFR|MPEP|USPTO|uspto\.gov|Alice|Paris|PCT|EPC",
                             chunk):
                die("%s Primary source does not name a statute/rule/MPEP/official page"
                    % item_id)
        sampled.append("%s:%s" % (part, ids[0]))
    print("ok  %d items across parts %s have Primary source cites"
          % (sum(len(v) for v in by_part.values()), ", ".join(sampled)))

def run_script(name, *args):
    cmd = [sys.executable, os.path.join(HERE, name), *args]
    proc = subprocess.run(cmd, capture_output=True, text=True)
    if proc.returncode not in (0, 1):
        die("%s exited %s\n%s\n%s" % (name, proc.returncode, proc.stdout, proc.stderr))
    return proc

def test_shipped_scripts_on_sample_draft():
    draft = os.path.join(ROOT, "assets", "sample_draft.md")
    if not os.path.exists(draft):
        die("missing sample draft %s" % draft)

    intake_body = """\
planned_filing_date: 2026-09-01
application_type: utility
entity_status: small
first_public_disclosure_date: 2025-10-01
disclosure_made_by: inventor
ppa_filing_date: 2025-11-01
foreign_filing_intended: false
nonpublication_request_planned: false
"""
    with tempfile.TemporaryDirectory() as wd:
        intake = os.path.join(wd, "intake.yaml")
        open(intake, "w", encoding="utf-8").write(intake_body)
        parsed = os.path.join(wd, "parsed.json")
        findings_dir = os.path.join(wd, "findings")
        os.makedirs(findings_dir)
        mechanical = os.path.join(findings_dir, "findings_mechanical.json")
        deadlines = os.path.join(wd, "deadlines.json")
        report = os.path.join(wd, "audit_report.md")

        p = run_script("parse_application.py", draft, "-o", parsed)
        print(p.stdout.strip() or "parse_application ran")
        data = json.load(open(parsed, encoding="utf-8"))
        if not data.get("claims"):
            die("parse_application produced no claims")

        run_script("mechanical_checks.py", parsed, "--intake", intake, "-o", mechanical)
        run_script("deadlines.py", intake, "-o", deadlines, "--asof", "2026-08-12")
        dl = json.load(open(deadlines, encoding="utf-8"))
        dumped = json.dumps(dl)
        if "book" + "_page" in dumped:
            die("deadlines.json still embeds guide-page provenance")
        if "Patent" + " It" in dumped:
            die("deadlines.json still embeds popular-guide attribution")
        if not dl.get("deadlines"):
            die("deadlines.py produced no deadline rows")

        syn = run_script("synthesize.py", findings_dir, "--deadlines", deadlines,
                         "-o", report)
        print(syn.stdout.strip())
        body = open(report, encoding="utf-8").read()
        title = "".join(("Patent", " It ", "Yourself"))
        author = "".join(("Press", "man"))
        if re.search(r"\b%s\b|\b%s\b" % (re.escape(title), re.escape(author)),
                     body, re.I):
            die("synthesize report still attributes the checklist to a popular guide")
        if "grounded in 35 U.S.C." not in body:
            die("synthesize footer does not describe a primary-source checklist")
        print("ok  shipped scripts ran on sample_draft; report has no book footer")
        return body, syn.stdout, dl

def main():
    test_no_forbidden_strings()
    test_part_files_are_primary_source()
    test_shipped_scripts_on_sample_draft()
    print("all checks passed")

if __name__ == "__main__":
    main()
```

## File: patent-audit/assets/intake.yaml
size: 5440
sha: 2d3082d111000d575595554f8e7c9ec7481d1f60
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/assets/intake.yaml

```text
# Pre-filing patent audit — intake facts
#
# Parts A, C and D of the checklist ask about things that are NOT in the draft.
# Without these the audit cannot answer them, and an audit that guesses a
# disclosure date is worse than no audit.
#
# Leave a value as `null` if genuinely unknown. Never guess. Anything left null
# produces a `cannot_assess` verdict, which is the correct and honest outcome.

# ---------------------------------------------------------------- the filing
planned_filing_date: null          # YYYY-MM-DD
application_type: utility          # utility | design | plant
entity_status: null                # large | small | micro
entity_status_basis: null          # why the applicant qualifies (headcount, income, prior filings)

# ------------------------------------------------- disclosure and bar dates
# The most consequential facts in the whole audit. Every "public" event counts:
# a conference talk, a paper, a web page, a Kickstarter, a trade-show demo, a
# quote to a customer, a sale, a beta release. Experimental use may be excepted.
first_public_disclosure_date: null # YYYY-MM-DD — earliest of ANY public disclosure
first_public_disclosure_what: null # what was disclosed, to whom, under what terms
first_offer_for_sale_date: null
first_public_use_date: null
disclosure_made_by: null           # inventor | obtained_from_inventor | third_party | none
                                   # decisive post-AIA: only inventor-derived
                                   # disclosures get the one-year grace period
all_disclosures_under_nda: null    # true | false — an NDA'd disclosure is not public

# --------------------------------------------------------------- inventorship
# Name every person who contributed to the CONCEPTION of at least one claim.
# Not people who only built or tested to instruction, and not the person who
# paid for it. Both over- and under-naming can invalidate the patent.
inventors:
  - name: null
    contribution: null             # which claim(s), and what they conceived
    citizenship: null
    employer_at_conception: null
    has_assignment_obligation: null    # true | false | unknown
    employed_to_invent: null           # true | false — shop-right exposure
    used_employer_resources: null      # true | false

# ------------------------------------------------------------------ ownership
applicant: null                    # who applies: inventor(s) or an assignee entity
assignment_executed: null          # true | false
assignment_recorded: null          # true | false
joint_owners_agreement: null       # true | false | n/a — each co-owner can
                                   # otherwise license the whole patent alone

# ------------------------------------------------------- earlier applications
ppa_filing_date: null              # YYYY-MM-DD if claiming provisional priority
ppa_file: null                     # path to the PPA text — needed to verify the
                                   # regular application's claims are supported
parent_filing_date: null           # YYYY-MM-DD for a continuation/divisional/CIP
parent_file: null                  # path to parent text
parent_status: null                # pending | issued | abandoned — copendency
relationship_to_parent: null       # continuation | divisional | cip | none
adds_new_matter_over_parent: null  # true | false — CIP claims to new matter lose
                                   # the parent's priority date

# ---------------------------------------------------------------- foreign
foreign_filing_intended: null      # true | false | undecided
foreign_countries: []              # e.g. [EP, JP, CN, KR]
nonpublication_request_planned: null  # true | false — CONFLICTS with foreign
                                      # filing; the two are mutually exclusive
foreign_inventors_or_work_abroad: null # true | false — foreign filing licence

# ----------------------------------------------------------------- prior art
search_performed: null             # true | false
search_report_file: null           # path to the search report
search_performed_by: null          # self | professional searcher | attorney
searched_non_patent_literature: null   # true | false
searched_foreign_patents: null         # true | false
closest_prior_art: []              # identifiers of the closest references found
prior_art_files: []                # paths to full texts of key references

# ------------------------------- duty of candour (cannot be checked from docs)
# This is the one item no document review can verify. It depends on what the
# inventor personally knows and can only be established by asking them.
inventor_aware_of_other_art: null  # true | false — anything the inventor knows of
                                   # that is material: their own earlier work, a
                                   # competitor's product, a paper they read, art
                                   # cited in a related application
other_art_known: []                # list everything, however unwelcome
ids_prepared: null                 # true | false

# ------------------------------------------------------------------ artifacts
draft_file: null                   # path to the specification/claims
drawings: null                     # path to a drawings PDF or a directory of images
forms_packet: null                 # path to ADS/declaration/transmittal/IDS if drafted
```

## File: patent-audit/assets/sample_draft.md
size: 3242
sha: 4c4b1b8c156eaf3560a5b879a315f13b27a39264
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/assets/sample_draft.md

```text
TITLE

Adjustable Beverage Container Insulator

CROSS-REFERENCE TO RELATED APPLICATIONS

This application claims the benefit of provisional application 63/111,222 filed
2024-02-01.

TECHNICAL FIELD

This invention relates to insulating sleeves for beverage containers.

BACKGROUND

Prior art beverage sleeves are of fixed diameter and therefore fit only one size
of container. Applicant is aware that U.S. Pat. 5,000,000 to Smith discloses a
foam sleeve, which fails completely to retain heat and is universally regarded
as a poor product. The essential problem with all prior sleeves is that they
cannot adjust.

SUMMARY

The invention is an adjustable insulating sleeve. It is the object of this
invention to provide a sleeve that fits multiple container sizes. It is a
further object to provide a sleeve that is cheap. The preferred embodiment uses
a nitinol tension band, which is essential to the invention.

BRIEF DESCRIPTION OF THE DRAWINGS

FIG. 1 is a perspective view of the sleeve.
FIG. 2 is a cross-section along line 2-2 of FIG. 1.
FIG. 4 is an exploded view of the tension mechanism.

DETAILED DESCRIPTION

Referring to FIG. 1, the sleeve 10 comprises a body 12 of closed-cell foam and a
tension band 14. The body 12 is generally cylindrical. The tension band 14 is
fitted within a channel 16 formed in the body 12.

The band 14 is made of Thermalok, a proprietary shape-memory alloy. The channel
16 receives the band 14. A clasp 18 secures the two ends of the band 14.

In FIG. 2, the cross-section shows the body 12 surrounding the channel 16. The
retaining ring 22 holds the assembly together.

OPERATION

In operation, the user slides the sleeve 10 over a container. The band 14
contracts, gripping the container. The clasp 18 may be released to remove the
sleeve 10.

CLAIMS

1. An adjustable insulating sleeve, comprising a cylindrical body of insulating
material, and a tension band disposed within said body, wherein the band is
substantially resilient.

2. The sleeve of claim 1, wherein the tension band comprises a shape-memory
alloy.

3. The sleeve of claim 1, wherein said clasp secures the ends of the tension
band.

4. The sleeve of claim 6, wherein the body is closed-cell foam.

5. A method of insulating a beverage container. The method comprises sliding the
sleeve of claim 1 over the container and allowing the band to contract.

ABSTRACT

An adjustable insulating sleeve for beverage containers is disclosed. The sleeve
has a cylindrical body of insulating material and a tension band disposed within
a channel in the body. The band is made of a shape-memory alloy and contracts to
grip containers of differing diameters. A clasp secures the ends of the band and
may be released to remove the sleeve from the container. The invention provides
an insulating sleeve that accommodates multiple container sizes, unlike prior
fixed-diameter sleeves which fit only a single container size and which are
therefore of limited utility to consumers who own beverage containers of more
than one diameter, a situation which is extremely common in ordinary households
and in commercial settings such as offices and restaurants where many different
vessels are in simultaneous use throughout the working day and evening.
```

## File: patent-audit/.gitignore
size: 19
sha: 7a60b85e148f80966a550e5ab6a762a907c69ca6
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/.gitignore

```text
__pycache__/
*.pyc
```

## File: patent-audit/agents/openai.yaml
size: 205
sha: e09fb2c39380690e710502c8c1c884954f1b64f3
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/agents/openai.yaml

```text
interface:
  display_name: "Patent Audit"
  short_description: "Audit a draft patent application before filing"
  default_prompt: "Use $patent-audit to audit my draft patent application before I file it."
```

## File: patent-audit/reference/checklist_index.json
size: 226816
sha: 2f90893aa580344400be156d07192b6219ee0dfb
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/checklist_index.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/checklist_index.json

## File: patent-audit/reference/parts/A_threshold.md
size: 33944
sha: 71540d939068eacd70c42da5b108d4f0d039a36d
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/A_threshold.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/A_threshold.md

## File: patent-audit/reference/parts/B_search.md
size: 18674
sha: d7813be4961dd2fca25493789f7192bb241d3083
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/B_search.md

```text
# Part B — Prior-art search adequacy

22 items (1 Fatal).

Grounded in 35 U.S.C. §§ 102–103, 37 CFR 1.56 and 1.97–1.98, MPEP 900 / 2100 / 2001, and current USPTO search resources. A search is not legally required to file, but an uninformed filing is how claims get written broader than the art allows.

## Was a search done at all

### `B01` Confirm a patentability search preceded the decision to file
- **Check:** Verify that a documented patentability search of the invention exists and was completed before the decision to file this draft was made.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** A search report, worksheets, saved queries, or annotated hit lists dated before claim lock. A marketing survey, an FTO opinion on in-force claims, or a single web query is not a patentability search. A search run after the claims were frozen, and never used to revise them, is the same defect.
- **Why it matters:** Filing without a search risks an immediate § 102/§ 103 rejection on art the drafter never saw, and wasted fees on claims the art does not permit.
- **Primary source:** 35 U.S.C. §§ 102–103; MPEP 904 (Office search practice as the coverage standard to emulate); 37 CFR 1.56.

### `B02` Test any decision to skip the search against documented coverage
- **Check:** If no search was made, verify the file records a reason that the relevant art is already known to the applicant with documented coverage — for example a field the applicant actually monitors, or an improvement already covered by an earlier search of the same concept.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Vague industry tenure is not coverage. Test whether the applicant actually tracks the journals, patents, and products of this subclass. For an "already searched" improvement, locate the earlier search and confirm its classes and keywords reach the new feature. Fast-moving fields make a skip harder to justify, not easier.
- **Why it matters:** A skipped search rationalized after the fact leaves the draft exposed to art the applicant assumed away.
- **Primary source:** 35 U.S.C. §§ 102–103; MPEP 904; 37 CFR 1.56 (duty attaches to what the applicant actually knows).

## Search scope and sources

### `B03` Verify the searcher was given every embodiment and the broad concept
- **Check:** Confirm the search request (or the DIY search plan) disclosed all embodiments, variations, and ramifications of the invention, and asked for the broad concept as well as the specific form.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Compare the search request against the specification. Embodiments added after the request went out are unsearched. A request that describes only the commercial prototype, or a sketch with no written description, searched a different invention than the one being claimed.
- **Why it matters:** Unsearched embodiments are drafted blind. Claims covering them can be knocked out by references a complete request would have surfaced.
- **Primary source:** 35 U.S.C. § 112(a) (the claimed embodiments must be enabled — and should be searched); MPEP 904.02.

### `B04` Verify the search record states exactly what was searched
- **Check:** Confirm the search record identifies the classes, subclasses, keywords, and databases actually searched, plus any examiner consulted, and a restatement of the invention as searched.
- **Severity:** Quality
- **Applies to:** all applications
- **What to look for:** A competent record has the invention as understood by the searcher, the hit list, a discussion of close references, and the classes/keywords used. A bare list of patent numbers is unauditable. If the searcher's restatement omits a claimed feature, that feature was not searched.
- **Why it matters:** Without a coverage record there is no way to know which classes were never opened.
- **Primary source:** MPEP 719.05, 904.02 (what a documented search contains).

### `B05` Confirm pre-grant published applications were searched, not just issued patents
- **Check:** Verify the search covered U.S. pre-grant application publications in the same classes and subclasses as the issued-patent search.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** A hit list of only issued patent numbers is the tell that PGPub was never run. Abandoned published applications remain prior art. Applications younger than 18 months, or under a nonpublication request, remain invisible — record that residual limit.
- **Why it matters:** A published application is § 102 art the examiner will find even if it never issued.
- **Primary source:** 35 U.S.C. § 122(b); 35 U.S.C. § 102(a)(2); MPEP 1120, 2154.

### `B06` Confirm non-patent literature and foreign documents were covered
- **Check:** Verify the search extended beyond the U.S. patent database to non-patent literature and to foreign patent documents where the technology warrants it.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Journals, standards, manuals, theses, archived websites, and Espacenet / PATENTSCOPE / national-office hits. USPTO Patent Public Search does not replace a foreign or NPL pass. Date-verify every NPL item used as art.
- **Why it matters:** An article, standard, or foreign patent anticipates as completely as a U.S. patent.
- **Primary source:** 35 U.S.C. § 102(a)(1); MPEP 2126–2128; MPEP 904.02(c).

### `B07` Grade the search by its source and discount what cannot be searched
- **Check:** Verify that the confidence placed in the search matches the source used, and that the draft is not written as if the search were exhaustive.
- **Severity:** Quality
- **Applies to:** all applications
- **What to look for:** Unpublished pending applications cannot be searched. Recent filings may not be loaded. Public use and sales rarely appear in patent databases. A cheap, same-week internet search in a crowded field is not an examiner-grade search. Record those limits in the audit.
- **Why it matters:** Over-trusting a shallow search produces broad claims the later Office search will destroy.
- **Primary source:** 35 U.S.C. § 102(a)(2) (secret art); MPEP 904.

## Classification and keyword coverage

### `B08` Confirm both a classification search and a keyword search were run
- **Check:** Verify the search record shows both a CPC classification search and a keyword/Boolean search, each used to check the other.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Keyword-only and classification-only records have opposite blind spots: wrong vocabulary, or wrong class. Overlap — the keyword pass re-finding classification hits — is the best coverage sign. New classes surfaced by keywords should then be searched.
- **Why it matters:** Either method alone can miss the closest reference, which then appears for the first time in an Office Action.
- **Primary source:** MPEP 904.02; CPC Scheme and Definitions (uspto.gov).

### `B09` Confirm all plausible CPC codes, including analogous fields, were checked
- **Check:** Verify the classification search covered more than one CPC code and reached analogous arts, not just the single most obvious subclass.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** A worksheet with exactly one subclass is almost always under-searched. Follow informative references in the CPC definitions. Search analogous apparatus that solves the same mechanical or data problem in another field.
- **Why it matters:** The closest reference often sits one subclass away.
- **Primary source:** MPEP 904.02(a); CPC Definitions.

### `B10` Confirm backward and forward citation chaining from the closest references
- **Check:** Verify that for each closely relevant reference the searcher followed its cited art backward and its citing art forward, and mined its field of search for further classes.
- **Severity:** Quality
- **Applies to:** all applications
- **What to look for:** Close hits used as seeds, not endpoints. Backward chaining reaches examiner-vetted art; forward chaining catches recent publications. Pre-1950 U.S. patents often lack a modern cited-references list — classification must carry older art.
- **Why it matters:** Skipping the citation tree leaves the art an examiner is most likely to cite unexamined.
- **Primary source:** MPEP 904.02; USPTO Patent Public Search citation tools.

### `B11` Check database date coverage against the age of the technology
- **Check:** Verify that the databases searched actually reach back far enough to cover the era in which prior art for this technology would have been published.
- **Severity:** Serious
- **Applies to:** all applications; especially low-tech / long-established fields
- **What to look for:** Full-text U.S. keyword search is reliable only for modern text. Older mechanical and household art requires classification search back to the early patent corpus. If the basic idea could predate full-text coverage, a keyword-only search is incomplete.
- **Why it matters:** Century-old art anticipates modern claims. An examiner running classification will find the patent the keyword search never returned.
- **Primary source:** USPTO Patent Public Search coverage notes; MPEP 904.02.

### `B12` Check the keyword set for synonyms, jargon, and pre-adoption terminology
- **Check:** Verify the recorded search terms include alternative words, technical jargon equivalents, wildcards, and the terminology that would have been used before the technology acquired its modern name.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Claim terms that never appear in the search record. Two or three obvious nouns with no synonyms. Patents often use legal or functional language instead of the marketplace name. Early foundational patents may predate the common name entirely.
- **Why it matters:** A vocabulary mismatch returns a clean result on art that plainly anticipates the claims.
- **Primary source:** MPEP 904.02(b) (search queries); CPC catchword index practice.

## Analysing the references found

### `B13` Confirm each reference was read as a disclosure, not as a set of claims
- **Check:** Verify that the analysis of each close reference addressed its description and drawings, and did not conclude non-relevance because the reference's claims do not cover the invention.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Notes that say "claims don't cover us." A patent is prior art for everything it enables, as of its relevant date, whether or not it claims that subject matter. Infringement of an in-force patent is a separate clearance question the Office does not examine.
- **Why it matters:** Dismissing a reference on its claims leaves an anticipating disclosure unaccounted for.
- **Primary source:** 35 U.S.C. § 102; MPEP 2121, 2131; MPEP 2103 (Office does not determine infringement).

### `B14` Verify the effective date and document type of every cited reference
- **Check:** Confirm each reference's date and kind were correctly determined, including expired patents, patents effective as of their filing or publication date, and pre-grant publications distinguished from granted patents.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Treating an expired patent as irrelevant; using only the issue date when the AIA filing date controls; confusing a PGPub with a patent. Record kind codes, publication dates, and effective prior-art dates.
- **Why it matters:** A reference wrongly written off as "expired" or "too late" stays out of claim drafting and out of the IDS.
- **Primary source:** 35 U.S.C. § 102(a), (d); MPEP 2152, 2154; WIPO ST.16 kind codes.

### `B15` Confirm close references were studied in full
- **Check:** Verify that every reference retained as relevant was obtained in full and analysed, rather than judged from an abstract page, a single figure, or a title.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Screening from abstracts is fine for elimination. Stopping there is not. A figure not shown on the abstract page may be the anticipating embodiment. Write a short technical summary of each retained reference.
- **Why it matters:** A reference dismissed on a partial view is the one the examiner cites after the fee is paid.
- **Primary source:** MPEP 2121, 2131 (the whole reference is available as a disclosure).

### `B16` Confirm a written patentability analysis exists, run in the correct direction
- **Check:** Verify the file contains the applicant's own novelty and nonobviousness analysis against the closest references, listing the differences the invention has over the art — not the differences the art has over the invention — and addressing combinations of references.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** The required list is what the claim has that no one reference shows. Then ask whether those differences would have been obvious, including combinations. A searcher's silence is not clearance. Lay searchers often cannot give a patentability opinion; their omission means nothing.
- **Why it matters:** Without this analysis the drafter cannot know which features must appear in the independent claims.
- **Primary source:** 35 U.S.C. §§ 102–103; MPEP 2131, 2141.

## Feeding the search back into the draft

### `B17` Confirm the specification is aimed at the novel features and the closest art's deficiencies
- **Check:** Verify the draft specification recites and stresses the features found novel in the search, and explains their advantages against the deficiencies of the closest references.
- **Severity:** Quality
- **Applies to:** all applications
- **What to look for:** Generic background that never engages the closest reference. A passing draft identifies what the closest art fails to do and directs the description and quantitative results at that gap. Every feature relied on for novelty must appear in the written description.
- **Why it matters:** Missing support cannot be added later without new matter. The first Office Action will demand a distinction the specification never prepared.
- **Primary source:** 35 U.S.C. § 112(a); MPEP 608.01, 2163.

### `B18` Confirm claim scope was set against the found art
- **Check:** Verify the independent claims recite the fewest/broadest features that both distinguish over the closest references under § 102 and supply a nonobvious difference under § 103 — and that the resulting scope is still worth filing on.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Claims left at pre-search breadth, or narrowed further than the art requires. Walk the independent claim: add limitations only until novelty and nonobviousness are facially present. If many very specific features are required, a competitor can avoid the claim easily — question whether filing is worth it.
- **Why it matters:** Claims broader than the art supports are invalid or unallowable. Claims narrower than necessary give away scope.
- **Primary source:** 35 U.S.C. §§ 102, 103, 112; MPEP 2173.05.

### `B19` Confirm any teach-away reference found is preserved and used
- **Check:** Verify that references found in the search which teach away from the invention are identified in the file and reflected in the draft's discussion of unexpected results.
- **Severity:** Quality
- **Applies to:** all applications
- **What to look for:** References stating the approach will not work, should not be used, or failed. These are often discarded as "not relevant" because they do not show the invention. They are often the strongest § 103 evidence.
- **Why it matters:** Losing a teach-away forfeits the best available argument against an obviousness rejection.
- **Primary source:** MPEP 2145 (teaching away); *In re Gurley*.

### `B20` Confirm every material reference is queued for the Information Disclosure Statement
- **Check:** Verify that every relevant reference the search produced is on a list to be recorded in the PTO's file of this application, and that the search did not conclude with zero references.
- **Severity:** Fatal
- **Applies to:** all applications
- **What to look for:** Reconcile the search record against the IDS working list item by item. References judged "not close enough" are the ones most often dropped — that judgment is not the applicant's alone under 37 CFR 1.56. A search that ended with no references is not finished; cite the closest art even if it is not anticipating.
- **Why it matters:** A material reference known to the applicant and never disclosed can support inequitable-conduct unenforceability. Disclosing it lets the claims be tailored around it.
- **Primary source:** 37 CFR 1.56, 1.97, 1.98; MPEP 2001, 609; *Therasense v. Becton, Dickinson*.

### `B21` Confirm named-only components are documented in the found art or described
- **Check:** Verify that each component the specification passes over by its well-known name — rather than describing and drawing it — is in fact already described in a prior-art publication located by the search.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Parts mentioned but not illustrated or explained, especially outside the inventor's expertise. The license to name rather than describe depends on the component being known. Proprietary or novel parts must be drawn and described.
- **Why it matters:** A component neither described nor documented in the art is an enablement hole that cannot be cured after filing.
- **Primary source:** 35 U.S.C. § 112(a); MPEP 2164.01.

### `B22` Discount and supplement the search for software and business-method inventions
- **Check:** For a software or business-method draft, verify the search went beyond the PTO patent database and that the claims are not resting on the absence of hits in it.
- **Severity:** Serious
- **Applies to:** software / business method
- **What to look for:** Software and business methods are poorly and inconsistently classified. Compensate with NPL, product manuals, archived sites, source repositories, and specialist databases. Treat "nothing found in USPTO search" as the weakest form of clearance in this field.
- **Why it matters:** These claims are disproportionately invalidated by art that never appeared in the original patent search.
- **Primary source:** 35 U.S.C. §§ 102–103; MPEP 2106 (eligibility is separate from search quality); MPEP 904.02.
```

## File: patent-audit/reference/parts/C_inventorship.md
size: 18173
sha: 194df4a8af4dc490fa7339f03010736b35524799
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/C_inventorship.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/C_inventorship.md

## File: patent-audit/reference/parts/D_priority_deadlines.md
size: 35291
sha: 2874e2389469bafa79505311ba7f97cdf8c331e1
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/D_priority_deadlines.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/D_priority_deadlines.md

## File: patent-audit/reference/parts/E_disclosure.md
size: 21042
sha: 8405338423fde094086daece0960442653143cd0
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/E_disclosure.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/E_disclosure.md

## File: patent-audit/reference/parts/F_spec_sections.md
size: 22408
sha: 1f072ced40de2fa322fd2cf2152528298128c262
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/F_spec_sections.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/F_spec_sections.md

## File: patent-audit/reference/parts/G_claims.md
size: 46184
sha: 3227adae5d0beac64345811535adee88c27fcb10
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/G_claims.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/G_claims.md

## File: patent-audit/reference/parts/H_drawings.md
size: 16111
sha: 5f8ab36602e6e6be8ed0e9a3fac744f550034024
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/H_drawings.md

```text
# Part H — Drawings

22 items (3 Fatal).

Grounded in 35 U.S.C. § 113; 37 CFR 1.81–1.85; MPEP 608.02. Color, photo, and paper-size rules move — confirm the current rule text and OPAP checklist before filing.

## Drawing–specification–claim consistency

### `H01` Confirm drawings exist and show every feature recited in the claims
- **Check:** Verify that a drawing is filed wherever one is needed to understand the invention, and that every element and limitation recited in the claims is actually depicted in at least one figure.
- **Severity:** Fatal
- **Applies to:** all applications
- **What to look for:** Walk each claim element to a figure and numeral. Late-added claim elements (a spring, a controller, a second aperture) are the usual misses. Flowcharts count for process cases. **This agent must see the sheets as images.**
- **Why it matters:** A claimed limitation with no drawing support draws an objection. Because new matter cannot be added, the missing structure may not be curable.
- **Primary source:** 35 U.S.C. § 113; 37 CFR 1.81, 1.83; MPEP 608.02.

### `H02` Verify the drawings are complete enough to stand alone
- **Check:** Verify that the drawings contain everything technically necessary to disclose the invention, on the assumption that nothing can be added to them after the filing date.
- **Severity:** Fatal
- **Applies to:** all applications
- **What to look for:** Informal execution is curable; missing technical content is not. Assemblies drawn as an undifferentiated blob, and internal structure described in the text but never illustrated, fail. A reader who has not read the text should still understand the invention from the sheets.
- **Why it matters:** Omitted technical content is new matter. The only alternative is refiling and losing the original date.
- **Primary source:** 35 U.S.C. §§ 113, 132; 37 CFR 1.81; MPEP 608.04.

### `H03` Verify every reference numeral is mentioned in the specification and used consistently
- **Check:** Verify that each reference numeral on the sheets appears in the specification, that the same part carries the same numeral in every figure, and that no numeral designates two different parts.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** A two-column reconciliation both ways. Primed and letter-suffixed numbers count as different numbers. Recycled numbers after a revision are a common defect.
- **Why it matters:** Unmentioned or duplicated numerals are on the OPAP defect list and can undermine claim support.
- **Primary source:** 37 CFR 1.84(p); MPEP 608.02(e).

### `H04` Verify graphic symbols and labeled boxes are defined in the specification
- **Check:** Verify that every graphical symbol, encircled letter, or labeled rectangular box standing in for a conventional component is expressly explained in the specification.
- **Severity:** Serious
- **Applies to:** utility
- **What to look for:** An encircled "M," a box labeled "CPU," IEEE symbols, logic symbols. Each needs a definitional sentence. Arrows should show direction of movement where needed.
- **Why it matters:** An undefined symbol leaves a claimed conventional element unillustrated and unexplained.
- **Primary source:** 37 CFR 1.84(n), (o); MPEP 608.02.

### `H05` Verify improvement inventions separate the new portion and label prior-art figures
- **Check:** Verify that where the invention is an improvement on an existing machine, the improved portion is shown apart from the old structure and any figure depicting prior art is labeled as such.
- **Severity:** Serious
- **Applies to:** utility
- **What to look for:** The improvement buried inside a fully detailed host device. One undetailed prior-art figure tagged "(prior art)" plus a detailed figure of the improved region is the usual pattern.
- **Why it matters:** Failing to label prior-art figures misrepresents the contribution. Burying the improvement makes the drawing fail to show what is claimed.
- **Primary source:** 37 CFR 1.83–1.84; MPEP 608.02.

## Sheet and format requirements

### `H06` Verify every drawing sheet is one of the two permitted sizes and all sheets match
- **Check:** Verify that all drawing sheets are exactly the same size and are either U.S. letter or A4.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Mixed letter and A4 from combining CAD and scans. Undersized or oversized paper. Drawing sheets need not match the specification size, but they must match each other. A4 is safer if foreign filing is contemplated.
- **Why it matters:** Wrong size is an express OPAP ground for replacement drawings.
- **Primary source:** 37 CFR 1.84(f); MPEP 608.02.

### `H07` Verify the margins are clear of all lines and writing
- **Check:** Verify that nothing is drawn or written in the margins, that no margin border lines are present, and that crosshairs mark two diagonally opposite margin corners.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** CAD exports scaled to the full page. A drawn rectangle framing the sight. Confirm current 37 CFR 1.84(g) margin dimensions; when uncertain, use a wider margin.
- **Why it matters:** Incorrect margins are an OPAP defect, and content in the margin may be cropped at publication.
- **Primary source:** 37 CFR 1.84(g); MPEP 608.02.

### `H08` Verify sheet physical integrity, paper quality, single-sided use, and identification
- **Check:** Verify the sheets are clean, hole-free, unwrinkled, printed on one side only on suitable paper, and carry identifying information as currently required.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Punch holes, fold creases, gray copier lines, printing on the reverse. For paper filings, confirm current identification-on-back practice in 37 CFR 1.84(c) and ship sheets flat.
- **Why it matters:** Physical defects produce a drawing objection. Unidentified sheets can be lost if separated from the file.
- **Primary source:** 37 CFR 1.84(a)–(e); MPEP 608.02.

## Line work, shading, and sectioning

### `H09` Verify all lines are crisp, black, instrument-made, and free of solid black areas
- **Check:** Verify every line is sharp, uniformly dense, and black, drawn with drafting tools or CAD rather than freehand, with no solid black fills.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Pale gray lines, jagged bitmapped slants, crowded lines that will merge on reduction, filled black regions used as shading.
- **Why it matters:** Lines too light to reproduce are an express OPAP ground for replacement drawings.
- **Primary source:** 37 CFR 1.84(a), (l); MPEP 608.02.

### `H10` Verify each line type carries its correct meaning
- **Check:** Verify that solid, hidden, projection, and phantom lines are used only for their defined purposes, that broken lines never depict actual parts of the invention, and that no construction, center, or figure-connecting lines appear.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Dashes used for a lightly emphasized real component. Construction leftovers. Figures joined by a line. Movable parts: main position in full lines, secondary in phantom, or a separate view.
- **Why it matters:** Misused line types change what the drawing is understood to disclose.
- **Primary source:** 37 CFR 1.84(h), (n); MPEP 608.02.

### `H11` Verify sectioned parts are hatched correctly and shading follows a consistent light convention
- **Check:** Verify every part shown in section is filled with adequately spaced slanted parallel hatching, and that any surface or edge shading is consistent (conventionally light from the upper left).
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Unhatched or solid-filled sections. Crisscross hatching. Inconsistent shade directions. Shading is mandatory in design applications and optional in utility applications.
- **Why it matters:** Hatching and shading defects are on the frequent-objection list.
- **Primary source:** 37 CFR 1.84(h), (m); MPEP 608.02; 37 CFR 1.152 (design).

### `H12` Verify the scale and lettering survive two-thirds reduction
- **Check:** Verify each figure is drawn at a scale large enough that no detail is crowded when the sheet is reduced for reproduction, and that all lettering is legible at that reduction.
- **Severity:** Quality
- **Applies to:** all applications
- **What to look for:** Print or view at two-thirds scale. Touching lines, numerals that merge into hatching. Use a larger-scale detail view rather than crowding.
- **Why it matters:** Crowded work becomes illegible in the printed patent and can obscure the detail a claim depends on.
- **Primary source:** 37 CFR 1.84(k), (p); MPEP 608.02.

## Views, figures, and orientation

### `H13` Verify enough views of the right kinds
- **Check:** Verify the drawings include as many views as are needed, prefer perspective over unexplained engineering views, bracket exploded parts, show modifications in separate figures, and include one comprehensive view suitable for the Official Gazette.
- **Severity:** Serious
- **Applies to:** utility
- **What to look for:** A single elevation of a three-dimensional mechanism. Alternative embodiments overlaid in broken lines. Identify the Gazette figure.
- **Why it matters:** Too few or poorly chosen views leave claimed structure unillustrated.
- **Primary source:** 37 CFR 1.83–1.84; MPEP 608.02.

### `H14` Verify sectional and enlarged views are designated on the parent figure
- **Check:** Verify every sectional view has its cutting plane marked on the general figure with a broken line, numerals matching the sectional figure number, and arrows showing the viewing direction, and that every enlarged view's area is circled and numbered on the parent figure.
- **Severity:** Serious
- **Applies to:** utility
- **What to look for:** A cross-section figure with no section line on the parent. Inconsistent arrow labels.
- **Why it matters:** Undesignated sections leave the examiner unable to relate the views.
- **Primary source:** 37 CFR 1.84(h); MPEP 608.02.

### `H15` Verify figures are separately and consecutively numbered, unconnected, and assemblable
- **Check:** Verify every view carries its own consecutive figure number, that no figure touches or is nested inside another, and that any drawing spanning multiple sheets can be assembled without concealing parts.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Multiple views sharing one caption. Unlabeled insets. A large machine whose sheet edges do not register.
- **Why it matters:** Unnumbered or connected figures are named OPAP defects.
- **Primary source:** 37 CFR 1.84(u); MPEP 608.02.

### `H16` Verify sheet orientation, lettering orientation, and sheet numbering
- **Check:** Verify all views on a sheet share one orientation, that lettering follows that orientation, that the sheet number and total appear at the top, and that figure legends are correctly placed.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Mixed portrait and landscape on one sheet. Sheet numbers that move with landscape rotation. Confirm current 37 CFR 1.84(i) and (t) placement.
- **Why it matters:** Inconsistent orientation and missing sheet numbers produce objections and misassembly risk.
- **Primary source:** 37 CFR 1.84(i), (t); MPEP 608.02.

## Reference numerals and lead lines

### `H17` Verify reference numerals are plain, large enough, uncircled, and clear of hatching
- **Check:** Verify every reference numeral is plainly formed, at least the current minimum height, not encircled, not crossing other lines, and not sitting on hatched surfaces unless unavoidable.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** CAD defaults smaller than 1/8 inch / 0.32 cm. Circled numbers borrowed from engineering practice. Where a numeral must sit on hatching, underline it in a cleared blank.
- **Why it matters:** Unreadable numerals break the link between the specification and the illustrated structure.
- **Primary source:** 37 CFR 1.84(p); MPEP 608.02.

### `H18` Verify every reference numeral has a lead line; arrowheads only for assemblies
- **Check:** Verify each reference numeral is connected by a lead line to the feature it designates, with no arrowhead on lead lines pointing to individual parts.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** Floating numbers. Arrowheads on single-part lead lines. Assembly references may use an arrowhead or underlining. Lead lines to phantom parts should themselves be broken.
- **Why it matters:** A missing lead line is an express OPAP ground for a Notice requiring replacement drawings.
- **Primary source:** 37 CFR 1.84(q); MPEP 608.02.

## Descriptive and extraneous matter

### `H19` Verify the sheets carry no descriptive or extraneous matter beyond permitted legends
- **Check:** Verify each figure is captioned with its figure number alone, that any descriptive legends appear only where the rules permit, and that nothing unrelated to the claimed invention appears on the sheets.
- **Severity:** Serious
- **Applies to:** all applications
- **What to look for:** "Fig. 1 — Apparatus in Ready State." Company logos, confidentiality notices, dimension tables, drafter stamps. Use-demonstrating matter (a hand on a grip) is permitted. Text must be in English and not excessive.
- **Why it matters:** Extraneous matter and excess or non-English text are OPAP defects.
- **Primary source:** 37 CFR 1.84(o), (p), (u); MPEP 608.02.

## Photographs and color

### `H20` Verify color drawings or photos are accompanied by the petition, fee, and specification statement
- **Check:** Verify that if any drawing or photo is in color, the filing includes the current petition, fee, required specification statement, and the correct number of sets or EFS document code.
- **Severity:** Fatal
- **Applies to:** photographs, colour drawings
- **What to look for:** Color is permitted only when necessary. Confirm current 37 CFR 1.84(a)(2) petition, fee, and the first-paragraph statement in the brief description of the drawings. Color is not acceptable in a PCT international application.
- **Why it matters:** Color filed without the required petition is an express OPAP ground for replacement drawings.
- **Primary source:** 37 CFR 1.84(a)(2); MPEP 608.02; PCT Rule 11.

### `H21` Verify photographs are used only where necessary
- **Check:** Verify that no photograph is used where a line drawing would suffice, that any black-and-white photo is supported by a petition explaining its necessity, and that all photos reproduce every detail and illustrate all features of the invention.
- **Severity:** Serious
- **Applies to:** photographs
- **What to look for:** The accepted justification is fine detail a drawing cannot carry (for example a photomicrograph). Soft focus, poor lighting, and shadowed claimed features fail. Prefer tracing or CAD conversion.
- **Why it matters:** A photo used where a figure would suffice is an OPAP defect. A photo that hides a claimed feature leaves that feature unillustrated with no way to add it later.
- **Primary source:** 37 CFR 1.84(b); MPEP 608.02.

## Overall drawing execution

### `H22` Verify the drawing set as a whole is well executed
- **Check:** Verify the drawings are of a standard the auditor would be willing to put in front of an examiner or a judge, rather than merely the minimum that might slip through.
- **Severity:** Quality
- **Applies to:** all applications
- **What to look for:** Inconsistent style, weight, and detail. One polished CAD figure beside three scanned pencil sketches. Observed leniency in some issued patents is not a license — the examiner still has discretion.
- **Why it matters:** Sloppy drawings make a lasting negative impression and invite objections, replacement-drawing cycles, and delay.
- **Primary source:** 37 CFR 1.84; MPEP 608.02; 35 U.S.C. § 113.
```

## File: patent-audit/reference/parts/I_filing_packet.md
size: 39091
sha: 017b35bcbbf5f4d835fdf40f34f8541fbeb5d31f
upstream: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/I_filing_packet.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/gfodor/legal-skills/blob/main/patent-audit/reference/parts/I_filing_packet.md

## File: README.md
upstream: https://github.com/gfodor/legal-skills/blob/main/README.md

````text
# legal-skills

**Replace billable hours with markdown files and an AI that actually follows them.**

This repository is a public, executable playbook for U.S. utility-patent work. Not a chatbot wrapper. Not a "talk to a lawyer" landing page. A set of agent skills — `SKILL.md` files, checklists, examiner/adversary protocols, intake questionnaires, and deterministic Python — that make a language model do the work a patent boutique currently invoices at several hundred dollars an hour.

The goal is not to "assist" counsel. The goal is to **displace legal fees**. If an inventor, founder, or in-house engineer can run a 316-item pre-filing audit, a simulated USPTO prosecution loop, and an adversarial design-around attack without opening a matter, that is a win. If a firm that used to charge $18,000 to draft and file a utility application is now competing with a checkout of this repo and a model that costs less than lunch, that is also a win.

Lawyers who are good at judgment, strategy, and courtroom work will still have work. Lawyers whose product is walking a known statute, filling known forms, and billing the walk — this repo is aimed at that product.

---

## This is not legal advice

**Read this before you use anything in this repository.**

This project is **not a law firm**. It does not create an attorney–client relationship. Nothing here is legal advice, a legal opinion, a patentability opinion, an infringement opinion, a freedom-to-operate opinion, or a representation that any application will be allowed, valid, enforceable, or commercially useful.

- These skills **do not file** applications, **do not sign** inventor declarations, **do not submit** Information Disclosure Statements, **do not contact** the USPTO, and **do not appear** before any tribunal.
- Outputs are **AI simulations** grounded in 35 U.S.C., 37 CFR, the MPEP, current official USPTO texts the agent is instructed to re-fetch, and whatever facts you put in the intake. Models hallucinate cites, miss art, and invent confidence. The scripts exist because models also cannot count, cannot do date arithmetic, and will report "all numerals consistent" after finding 19 of 20.
- Fee amounts, form names, PTO mechanics, and §101 case law **move**. The audit checklist is a primary-source pre-filing checklist — statutes, rules, MPEP, and current Office practice — not a substitute for the official text. The examination and workaround skills require the agent to refresh statutes, rules, MPEP pages, and examination memoranda on every run. Verify those sources yourself before you rely on a result.
- Some acts remain reserved to a human with the right credentials: signing a declaration under penalty of perjury, making the ultimate duty-of-candor / IDS materiality call, recording an assignment, paying the PTO, and anything that requires a registered practitioner. The skills **refuse** to do those things without your separate, explicit authorization, and even then they will not pretend they *are* you.
- **You** own the consequences. A bad claim set, a missed statutory bar, a false entity-status claim, or an omitted material reference can destroy rights. If the stakes are high enough that you would sue someone over a missed deadline, hire a registered practitioner and use this repo as the thing that makes that person cheaper, faster, and harder to snow.

The GPL-3.0 license already disclaims warranty. This paragraph is the same idea in English: **use at your own risk.**

That disclaimer is required because the work is real enough to hurt you if you treat it as magic. It is **not** a retreat from the pitch. The pitch is that most of what you were paying for was process, and process belongs in files.

---

## Why markdown, not a firm

Patent work is already a document pipeline:

1. Facts that are not in the draft (disclosure dates, inventorship, entity status).
2. A specification and claims that either enable the invention or do not.
3. A search that either found the dead-ringer or did not.
4. An examiner who will reject under 35 U.S.C. 101 / 102 / 103 / 112 until the claims are allowable or you give up.
5. A competitor who will keep the value proposition and drop the limitation you accidentally treated as essential.

Firms wrap that pipeline in scarcity, letterhead, and a rate card. This repo unwraps it.

| What you used to buy | What this repo is |
|---|---|
| A $400/hr associate reading the draft once | 11 specialized agents, each with the **whole** application and a part-file of checklist items they are forbidden to skip |
| A partner "doing the claims" from muscle memory | A 64-item claims part, a mechanical parser that builds the dependency graph, and a red-team examiner who has to write a real Office Action |
| A design-around "gut check" in a conference room | Fresh competitor subagents plus an outer-agent umbrella classification that will not let you claim a result you did not disclose |
| An invoice | `git clone` |

The files are the product. If a better model ships next quarter, the same files get cheaper and sharper. If the PTO changes a form, you edit a markdown file instead of waiting for a CLE.

---

## What's here

Three skills. They are designed to be run in order. Each one is a complete agent skill: a `SKILL.md` the orchestrator reads as its contract, plus the payloads, templates, and scripts that keep the model honest.

```
legal-skills/
├── patent-audit/         Pre-filing audit. 316 checklist items. Deterministic pre-pass.
├── patent-examine/       Recurrent simulated USPTO examination until two independent examiners clear the same version.
├── patent-workaround/    Adversarial design-around testing. Strengthen only what is supported and patentable.
├── LICENSE               GNU GPL v3
└── README.md             This file
```

**Suggested pipeline**

```
     inventor facts + draft
              │
              ▼
      ┌───────────────┐
      │ patent-audit  │  Is this even fileable? Stop on statutory bars.
      └───────┬───────┘
              │ ranked defects + parsed.json
              ▼
      ┌───────────────┐
      │patent-examine │  Mock prosecution. Amend only after a simulated OA.
      └───────┬───────┘
              │ version-locked "allowable" candidate
              ▼
      ┌──────────────────┐
      │patent-workaround │  Can a competitor keep the value and miss the claims?
      └────────┬─────────┘
               │
               └── iterate examine ↔ workaround until two examiners
                   and two adversaries clear the same packet
```

`patent-examine` and `patent-workaround` will use `patent-audit`'s parser and mechanical checks if that sibling skill is installed. A prior audit is **not** a substitute for examination. A prior examination is **not** a substitute for workaround testing.

---

## Install

These are [agent skills](https://docs.anthropic.com/en/docs/agents-and-tools/agent-skills): a directory with a `SKILL.md` the model is instructed to follow. Copy the three skill folders into the skills directory of whatever agent you run.

| Agent | Typical location |
|---|---|
| Grok | `~/.grok/skills/` |
| Claude Code | `~/.claude/skills/` or project `.claude/skills/` |
| Codex / Cursor / other skill hosts | that product's skills directory |

On Windows, from this repo:

```powershell
Copy-Item -Recurse .\patent-audit, .\patent-examine, .\patent-workaround $HOME\.grok\skills\
```

Then tell the agent, in plain language:

- *Use `$patent-audit` to audit this draft before I file it.*
- *Use `$patent-examine` until two fresh examiners independently find the same version allowable.*
- *Use `$patent-workaround` to pressure-test this draft against credible design-arounds.*

Python 3 is required for the scripts. The audit parser accepts `.txt`, `.md`, `.pdf`, and `.docx`. PDF needs [PyMuPDF](https://pymupdf.readthedocs.io/); `.docx` needs [python-docx](https://python-docx.readthedocs.io/). Missing optional dependencies fail loudly instead of silently producing a h
````
