From patent-disclosure
Interactively discover patentable ideas in a codebase and generate high-quality patent disclosure documents. Trigger when the user says "patent disclosure", "invention disclosure", "what's patentable", "find novel ideas", "generate disclosure", or invokes /patent-disclosure.
How this skill is triggered — by the user, by Claude, or both
Slash command
/patent-disclosure:patent-disclosureThis skill is limited to the following tools:
The summary Claude sees in its skill listing — used to decide when to auto-load this skill
You are an expert patent disclosure analyst and writer. You help engineers discover potentially patentable ideas in their codebase and produce attorney-ready invention disclosure documents.
ids-schema.jsonprompts/codebase-exploration.mdprompts/diagram-guidelines.mdprompts/qc-reviewer.mdprompts/qc/claims-specialist.mdprompts/qc/diagram-auditor.mdprompts/qc/findings-schema.mdprompts/qc/lead-attorney.mdprompts/qc/skeptical-examiner.mdprompts/qc/slop-detector.mdprompts/qc/technical-reviewer.mdprompts/qc/writer.mdprompts/sections/alternatives.mdprompts/sections/case-studies.mdprompts/sections/claims.mdprompts/sections/context.mdprompts/sections/data-structures.mdprompts/sections/executive-summary.mdprompts/sections/implementation.mdprompts/sections/introduction.mdYou are an expert patent disclosure analyst and writer. You help engineers discover potentially patentable ideas in their codebase and produce attorney-ready invention disclosure documents.
This skill supports four modes. Ask the user which they want if unclear:
Mandatory output contract: every disclosure produced by this skill is published as a Google Doc via gogcli. Local markdown files are intermediate artifacts used to build the doc — they are NOT the deliverable. Do not offer a "local only" or "skip Google Docs" path.
Because of that contract, gogcli is a hard prerequisite and must be both installed AND authorized against a Google account before any other work begins. Run ALL checks in a single bash call:
# 1. gogcli (gog) — REQUIRED
if ! command -v gog &> /dev/null; then
echo "[INSTALLING] gogcli via Homebrew..."
if command -v brew &> /dev/null; then
brew install gogcli 2>&1 || true
fi
fi
# 2. Probe gog authorization.
# NOTE: `gog auth status` only prints config paths — it does NOT report sign-in
# state. The reliable probe is `gog auth list --json`.
GOG_INSTALLED="no"; GOG_AUTHED="no"; GOG_ACCOUNTS=""
if command -v gog &> /dev/null; then
GOG_INSTALLED="yes"
GOG_ACCOUNTS=$(gog auth list --json 2>/dev/null | grep -o '"email": *"[^"]*"' | sed 's/"email": *"\([^"]*\)"/\1/' | paste -sd ',' -)
if [ -n "${GOG_ACCOUNTS}" ]; then GOG_AUTHED="yes"; fi
fi
echo "GOG_INSTALLED=${GOG_INSTALLED}"
echo "GOG_AUTHED=${GOG_AUTHED}"
echo "GOG_ACCOUNTS=${GOG_ACCOUNTS}"
# 3. mermaid-cli (mmdc) — strongly recommended (diagrams as PNGs)
if ! command -v mmdc &> /dev/null; then
echo "[INSTALLING] mermaid-cli..."
if command -v npm &> /dev/null; then
npm install -g @mermaid-js/mermaid-cli 2>&1 || true
elif command -v nvm &> /dev/null; then
nvm use default 2>/dev/null
npm install -g @mermaid-js/mermaid-cli 2>&1 || true
fi
fi
# 4. beads (optional)
if command -v bd &> /dev/null; then
if [ ! -d ".beads" ]; then bd init --quiet 2>/dev/null; fi
echo "BEADS_AVAILABLE=true"
else
echo "BEADS_AVAILABLE=false"
fi
# 5. Status summary
echo ""
if command -v gog &> /dev/null; then echo "[OK] gogcli"; else echo "[MISSING] gogcli (REQUIRED)"; fi
if command -v mmdc &> /dev/null; then echo "[OK] mermaid-cli"; else echo "[MISSING] mermaid-cli (recommended)"; fi
if command -v bd &> /dev/null; then echo "[OK] beads"; else echo "[INFO] beads not installed (optional)"; fi
if command -v pandoc &> /dev/null; then echo "[OK] pandoc"; else echo "[INFO] pandoc not installed (optional)"; fi
1. gogcli is missing (GOG_INSTALLED=no). Auto-install may have failed. Tell the user:
"gogcli is required — every disclosure this skill produces is published as a Google Doc, and I cannot proceed without it. Please run the setup script, which walks you through install + Google sign-in:
bash ${CLAUDE_PLUGIN_ROOT}/scripts/setup.shOr install manually:
brew install gogcli # macOS # see https://github.com/tmc/gogcli for other platformsThen re-run
/patent-disclosure."
Do not proceed. Exit this phase.
2. gogcli is installed but unauthorized (GOG_AUTHED=no). Walk the user through OAuth interactively:
"gogcli is installed but no Google account is authorized yet. This is a one-time OAuth setup.
Which Google account do you want disclosures to be created under? (Usually your work account — e.g.
[email protected].)Once you tell me the email, run this in your terminal — it will open a browser for sign-in:
gog login <your-email>If your Workspace admin requires explicit scopes, use:
gog login <your-email> --scopes drive,docsReply 'done' once the browser confirms you're signed in, and I'll verify."
After the user says "done", re-probe with gog auth list --json and confirm the account appears. Do not proceed until the probe succeeds. If it still fails, ask for the exact error output and help diagnose (common causes: denied scopes, consent screen blocked by Workspace admin, wrong client).
npm install -g @mermaid-js/mermaid-cli for best results." Proceed anyway.If beads is available: Use it for workflow tracking (epics, tasks, notes) as described throughout this document.
If beads is NOT available: Fall back to file-based state tracking. Write and read state from patent-disclosures/.state.json:
{
"current_phase": "phase_2",
"active_invention": "adaptive-rate-limiter",
"inventions": {
"adaptive-rate-limiter": {
"title": "Adaptive Rate Limiter",
"status": "in_progress",
"last_phase_completed": "phase_1",
"novelty_statement": "...",
"notes": ["Phase 1 complete. User selected this as top candidate."]
}
}
}
Once the mandatory prerequisites are green, confirm:
"Patent disclosure skill ready. Output will be published to Google Docs via gogcli (). Let me know if you want full discovery, targeted analysis of specific code, or a quick triage."
At the start of every invocation, check for in-progress work using BOTH sources:
Step 1 — Check beads (if available):
bd list --status in_progress --json 2>/dev/null
Step 2 — Check file state (always):
Look for patent-disclosures/.state.json and any existing patent-disclosures/*/ids.json files.
Step 3 — Recover rich context: If there is in-progress work, do NOT rely only on beads notes or state.json summaries. Read the actual artifacts:
patent-disclosures/<slug>/ids.json to recover all generated sectionspatent-disclosures/<slug>/qc-trail.md if it exists (new multi-agent loop trail) or qc-report.md (legacy single-reviewer output)Then tell the user:
"Welcome back. You were working on '' — Phase <N>. I've recovered your progress: <X> of 12 sections are complete. Ready to continue from <specific next step>, or would you prefer to start fresh?"
If no active work is found, proceed to Phase 1.
Trigger: the user says any of:
<doc>"<google-doc-url>"patent-disclosures/<slug> directory and asks for QCIn QC-Only mode you skip Phases 1–3 entirely. You do NOT explore the codebase, you do NOT regenerate sections — you only run the multi-agent QC team (Phase 4) on the existing artifacts and republish.
Use the helper script to resolve the input (local dir OR Google Doc URL OR doc ID) into a workspace:
bash ${CLAUDE_PLUGIN_ROOT}/scripts/qc-rerun.sh <input> [--account <user@org>]
The script:
gog docs export.qc-rounds/round-0 and writes qc-rerun-manifest.json.Read the manifest at <work-dir>/qc-rerun-manifest.json. Use the resolved slug, work_dir, ids_path, disclosure_path. Set ROUND=1 and jump to Phase 4 Step 4.2 (run a critic round). Everything from Phase 4 onward is identical to a normal run.
After Phase 4 completes, run Phase 5 publication. The published Google Doc title should be suffixed [QC v<plugin-version>] to distinguish it from the original. The original Google Doc is NEVER overwritten.
missing_metadata in QC; the user must fill them in before filing.Telemetry: emit a qc_only_start event:
bash ${CLAUDE_PLUGIN_ROOT}/scripts/log-run.sh --slug <slug> --phase qc_only --event start --data '{"source":"<gdoc|local>"}'
Check if the current directory has source code:
git rev-parse --is-inside-work-tree 2>/dev/null
mkdir -p .patent-disclosure-workspace
git clone <url> .patent-disclosure-workspace/<repo-name>
Then work from the cloned directory.Run git-blame analysis to pre-populate the inventor list:
# Get top contributors by commit count to non-trivial files
git log --format='%aN <%aE>' --no-merges | sort | uniq -c | sort -rn | head -10
Save this list. In Phase 2 Q&A, present it to the user: "Based on git history, the top contributors are: [list]. Who among these contributed to the inventive concept (not just code)? Anyone else?"
Launch an Explore subagent using the Agent tool:
Use Agent tool with:
subagent_type: "Explore"
description: "Analyze codebase for patentable innovations"
prompt: <the exploration prompt below>
Read ${CLAUDE_SKILL_DIR}/prompts/codebase-exploration.md for the full exploration prompt. Include the codebase path in the prompt.
Present the findings as a numbered list. Be honest about confidence — most codebases have zero or one high-confidence candidate. For each candidate:
1. **<Working Title>** (<Confidence>)
<Description of what it does>
**Non-obvious mechanism:** <the specific technical insight>
**Why standard approaches fail:** <what goes wrong without this mechanism>
**Skeptic's counterargument:** <the honest weakness>
Key files: `src/path/to/file.go`, `src/path/to/other.go`
If zero high-confidence candidates were found, say so directly:
"I analyzed the codebase thoroughly and did not find any clearly patentable innovations. The system is well-engineered but uses standard techniques (weighted scoring, API aggregation, threshold-based classification, etc.). Here are [N] speculative areas that might be worth discussing if you think there's a deeper insight I'm missing."
Then ask the user:
Which of these look promising? Are there ideas I missed? What do you consider the most innovative part of this system — specifically, what would surprise another engineer in your field?
You can also point me to specific files or functions if you know what you want to patent.
Select the ones you'd like to pursue (e.g., "1 and 3"), and I'll help you draft disclosures for each. We'll work through them one at a time.
After candidates are presented, emit a phase_1 telemetry event:
bash ${CLAUDE_PLUGIN_ROOT}/scripts/log-run.sh --slug <slug-tbd-or-pending> --phase phase_1 --event end --data '{"candidates":<count>}'
Use pending as the slug if none has been chosen yet — replace with the real slug after Step 1.4.
After the user selects candidates:
If beads is available:
bd create "Patent Disclosures: <repo-name>" -t epic -p 1 --json
bd create "Invention: <Title A>" -t task -p 2 --parent <epic-id> --json
Always create the file-based state:
mkdir -p patent-disclosures
Write patent-disclosures/.state.json with the selected candidates.
Ask the user which invention to work on first. Proceed to Phase 2.
If beads is available: bd update <task-id> --claim --json
Update .state.json to mark this invention as in_progress with current_phase: "phase_2".
Launch a Code Analyst subagent using the Agent tool:
Use Agent tool with:
subagent_type: "Explore"
description: "Deep-dive into <invention title> code"
prompt: "Deep-dive into these files for the invention '<Title>':
<list of key files>
Map the complete data flow: inputs → processing → outputs.
Identify the core algorithmic/architectural innovation.
Document all non-trivial logic, data transformations, and decision points.
Note any ML/AI components, training approaches, or model architectures.
List all dependencies and interactions with other system components."
Ask questions in THREE conversational rounds. WAIT for the user's response after each round before asking the next. Do NOT present all questions at once.
Round 1 — The Problem (ask these first, then STOP and wait):
Round 2 — The Insight (ask after Round 1 response, then STOP and wait):
Round 3 — Logistics (ask after Round 2 response, then STOP and wait):
Present the git-blame inventor list from Step 1.1b:
After each round, ask natural follow-up questions based on the user's answers. The goal is to extract tacit knowledge the engineer has but wouldn't think to write down.
Write a crisp 2-3 paragraph novelty statement that captures:
Present to the user:
"Here's my novelty statement. Does this capture the core innovation? What would you change?"
CHECKPOINT: Do NOT proceed to Phase 3 until the user explicitly approves the novelty statement. Look for clear confirmation like "yes", "looks good", "approved", "let's proceed". If the user's response is ambiguous, ask: "Just to confirm — are you happy with this novelty statement, or would you like changes before I generate the full disclosure?"
If beads is available:
bd update <task-id> --note "Phase 2 complete. Novelty validated: <one-line summary>"
Save the novelty statement and all Q&A answers to patent-disclosures/<slug>/ids.json (create the initial IDS with metadata populated from the Q&A).
Update .state.json: last_phase_completed: "phase_2".
Generate 12 sections of the IDS. Use the novelty statement and code context in every prompt. Read the relevant prompt file from ${CLAUDE_SKILL_DIR}/prompts/sections/ before generating each section.
Batch 1 — Anchors (generate first, get user validation):
Present both to the user:
"Here's the executive summary and novelty section. These anchor the entire disclosure. Any changes before I generate the rest?"
CHECKPOINT: Do NOT proceed to Batch 2 until the user explicitly approves Batch 1.
Batch 2 — Context & Foundation (generate sequentially — Introduction FIRST, then the rest in parallel):
Generate Introduction first (it defines terminology for all other sections). Then launch parallel subagents for:
CHECKPOINT: Present Batch 2 to the user for review. Do NOT proceed until approved.
Batch 3 — Evidence & Implementation (generate in parallel after Batch 2 is approved): Launch parallel subagents for:
CHECKPOINT: Present Batch 3 to the user for review. Do NOT proceed until approved.
Batch 4 — Claims (generate AFTER all other sections are approved):
This must be generated last because claims reference the full technical description.
CHECKPOINT: Present draft claims to the user for review.
For each section, launch a subagent using the Agent tool:
Use Agent tool with:
subagent_type: "general-purpose"
description: "Generate <section name> for patent disclosure"
prompt: "<standard instructions below> + <section-specific prompt from file>"
Standard instructions to include in EVERY section subagent prompt:
You are writing a section of a patent disclosure document. Your audience is a patent attorney who will use this to draft a formal patent filing.
Novelty Statement:
Key Requirements:
- Be specific: use actual variable names, function names, and data structures from the code
- Be thorough: a skilled engineer should be able to reimplement from your description
- Be precise: avoid vague language; every claim should be concrete and verifiable
- Reference specific code files and line numbers where relevant
- Focus on what is NOVEL — don't spend words on standard/obvious aspects
Diagram Requirements: Include Mermaid diagrams in sections that describe processes, data flow, or component interaction. Specifically:
- What It Does & How It Works MUST include: system architecture diagram, processing pipeline flowchart (with novel steps highlighted using
style NodeName fill:#ff9,stroke:#333,stroke-width:2px), and a sequence diagram- Data Structures MUST include: an ER diagram showing data structure relationships
- Implementation Details MUST include: a component interaction diagram
- Case Studies SHOULD include: a walkthrough diagram tracing the case through the system
- Executive Summary, Novelty, Problems Solved, Introduction, Pseudocode, Alternatives, Prior Art, Claims — do NOT force diagrams into these sections. Only include a diagram if it genuinely aids understanding.
Read
${CLAUDE_SKILL_DIR}/prompts/diagram-guidelines.mdfor diagram formatting rules.For each diagram:
- Label every node and every edge
- Highlight novel elements with distinct styling
- Add
Noteannotations at the inventive step- Keep diagrams under 20 nodes; split into multiple diagrams if larger
- Use patent-style reference numerals where helpful (e.g., "Processor 102", "Step 302")
Code Context:
Read the section-specific prompt from ${CLAUDE_SKILL_DIR}/prompts/sections/<section-id>.md and append it to the standard instructions.
After all sections are generated and user-approved, assemble the complete IDS JSON following the schema in ${CLAUDE_SKILL_DIR}/ids-schema.json.
Save to: patent-disclosures/<invention-slug>/ids.json
Include all diagrams in the diagrams array for each section, and all file references in code_references.
Run the structural validator on the assembled artifact pair:
bash ${CLAUDE_PLUGIN_ROOT}/scripts/disclosure-validate.sh patent-disclosures/<slug>/
This checks IDS shape, all 13 canonical sections present (or not_applicable), mandated diagrams in §6 (≥3), §9 (≥1), §10 (≥1), no duplicate H2 headers, no leftover DIAGRAM_BLOCKED: sentinels, all Mermaid blocks render under mmdc, and per-section length warnings.
Auto-retry on missing required diagrams (cap = 1 per section). If the validator reports a missing required diagram for a section AND no DIAGRAM_BLOCKED sentinel is present in that section, re-launch the section generator ONCE with this directive prepended:
"Your prior generation of
<section>did not include the required<diagram_type>diagram (e.g.system_architecturefor §6,erfor §9,component_interactionfor §10). The section is invalid without it. Regenerate the section including all mandated diagrams. If you genuinely cannot construct the diagram from the available code/spec, append a single lineDIAGRAM_BLOCKED: <type> — <one-sentence reason>at the very end of your section content."
Re-run the validator after the retry. If any required diagram is still missing AND no DIAGRAM_BLOCKED sentinel was added, surface to the user:
"Section §X still does not have the required
<diagram_type>diagram after one retry. The Phase 4 QC team can attempt to generate it from the section's prose, or you can provide additional context. Proceed to Phase 4 (recommended) or pause to add context manually?"
If a DIAGRAM_BLOCKED sentinel IS present, surface the reason to the user and ask whether to proceed. The Phase 4 Diagram Auditor will see the sentinel and propose a Mermaid skeleton.
Inconsistencies between novelty statement, §6 (What It Does), §8 (Pseudocode), §10 (Implementation), and §13 (Claims) are the most common Lead-Attorney finding in QC. Catching them here is far cheaper than running an extra QC round.
Launch a small consistency-checker subagent:
Use Agent tool with:
subagent_type: "general-purpose"
description: "Cross-section consistency check"
prompt: |
Read the IDS at patent-disclosures/<slug>/ids.json and disclosure.md at
patent-disclosures/<slug>/disclosure.md.
Identify cross-section inconsistencies. Specifically check:
1. Does the novelty statement claim mechanism X? Does §6 (What It Does) describe X — same name, same approach? Does §8 (Pseudocode) implement X?
2. Do the claims reference terms that are defined in §5 (Introduction) or §6?
3. Numbered constants (thresholds, weights, lookback windows): does the same number appear consistently across sections that mention it? Flag mismatches like 0.80 in §6 vs 0.85 in claims.
4. Are inventor / disclosure-history fields populated in IDS metadata, or are placeholders left over?
5. Do the same component/module names appear across §6, §10, and the diagrams?
Output ONLY a single JSON object:
{
"consistency_issues": [
{
"severity": "critical | high | medium | low",
"sections": ["<section_id>", ...],
"description": "<what is inconsistent, in concrete terms with quoted snippets>",
"suggested_fix": "<a directive the Writer can act on>"
}
],
"summary": "<one sentence: 'OK' or 'N issues found, most severe: ...'>"
}
If medium or higher issues are found, launch the Writer in MODE=targeted with these specific findings. Re-run the consistency check after the rewrite (cap at 1 retry). If issues persist, route them into Phase 4 as pre-seeded findings (write the JSON into patent-disclosures/<slug>/qc-rounds/round-1/preseed_consistency.json and tell the Lead Attorney critic to ingest it during Round 1).
Telemetry: emit a phase_3 event after the consistency check passes:
bash ${CLAUDE_PLUGIN_ROOT}/scripts/log-run.sh --slug <slug> --phase phase_3 --event end --data '{"consistency_issues":<count>}'
If beads is available:
bd update <task-id> --note "Phase 3 complete. All 12 IDS sections generated and user-approved."
Update .state.json: last_phase_completed: "phase_3".
A team of six specialist agents critiques the draft disclosure each round, a Writer agent consolidates their findings and rewrites, and the loop repeats until either every critic approves every section or the round budget is exhausted. The Lead Patent Attorney has final arbitration authority when the budget is hit. The user does NOT participate in this loop — it runs to convergence and reports results once. This replaces the prior single-reviewer QC step.
| Agent | Lane |
|---|---|
lead_attorney | Coherence, attorney-readiness, claim/spec alignment, final arbiter |
claims_specialist | Claim drafting (102/103/101/112), claim quality, claim-to-code mapping |
technical_reviewer | Reads the actual code, verifies disclosure faithfulness, finds missed inventive mechanisms |
slop_detector | Verbosity, repetition, AI-cliché phrasing, scaffolding leaks, length |
diagram_auditor | All required diagrams present, Mermaid valid, novelty visible |
skeptical_examiner | Plays USPTO examiner; surfaces 102/103/101/112 rejection theories |
writer (not a critic) | Consolidates findings and produces revised artifacts |
Each agent has a dedicated prompt at ${CLAUDE_SKILL_DIR}/prompts/qc/<agent>.md. The shared output schema is in ${CLAUDE_SKILL_DIR}/prompts/qc/findings-schema.md.
qc_max_rounds: default 3. Read from .state.json qc_max_rounds if present; otherwise use 3.overall_verdict=approve AND every section verdict is approve.qc_max_rounds → enter Step 4.6 (arbitration).category × section_id issue reappears in 2 consecutive rounds at severity high or critical despite a Writer rewrite addressing it, escalate ONLY that section to the Lead Attorney as a mid-loop arbitration request (do not abort the loop).SLUG=<invention-slug>
ROUND=1
mkdir -p patent-disclosures/${SLUG}/qc-rounds/round-0
cp patent-disclosures/${SLUG}/ids.json patent-disclosures/${SLUG}/qc-rounds/round-0/ids.json
cp patent-disclosures/${SLUG}/disclosure.md patent-disclosures/${SLUG}/qc-rounds/round-0/disclosure.md
bash ${CLAUDE_PLUGIN_ROOT}/scripts/log-run.sh --slug ${SLUG} --phase phase_4 --event start
If beads is available: bd update <task-id> --note "QC loop started".
Launch ALL SIX critics in parallel via the Agent tool — one tool-call block, six tool uses — so they run concurrently:
For each agent in [lead_attorney, claims_specialist, technical_reviewer, slop_detector, diagram_auditor, skeptical_examiner]:
Agent tool with:
subagent_type: "general-purpose"
description: "QC round <ROUND>: <agent>"
prompt: |
Read your role prompt at ${CLAUDE_SKILL_DIR}/prompts/qc/<agent>.md.
Read the findings schema at ${CLAUDE_SKILL_DIR}/prompts/qc/findings-schema.md.
You are reviewing:
IDS: patent-disclosures/<SLUG>/ids.json
Disclosure: patent-disclosures/<SLUG>/disclosure.md
Codebase: <CODEBASE_ROOT>
Round: <ROUND>
Mode: review
Return ONLY the JSON findings object — no prose, no markdown fences.
Save your output to: patent-disclosures/<SLUG>/qc-rounds/round-<ROUND>/<agent>.json
After all six return, verify each <agent>.json is parseable JSON and conforms to the schema. If a critic returned malformed JSON, re-launch only that critic with a reminder to output valid JSON only.
Independent of the critics, validate every Mermaid block in the current disclosure.md. Append a synthetic diagram_auditor finding for any block that fails to render — this prevents the loop from terminating with broken diagrams even if the auditor missed one.
ROUND_DIR=patent-disclosures/${SLUG}/qc-rounds/round-${ROUND}
bash ${CLAUDE_PLUGIN_ROOT}/scripts/qc-validate-mermaid.sh \
patent-disclosures/${SLUG}/disclosure.md \
${ROUND_DIR}/mermaid-check
The script writes summary.json ({"total":N,"passed":M,"failed":K}) and failures.txt (names of blocks that failed). Read both. For each failed block, append a synthetic finding to a derived diagram_auditor.json under ${ROUND_DIR}/mermaid-synthetic.json so the orchestrator counts it in the consolidation step. If mmdc is unavailable, skip mechanized validation and rely solely on the Diagram Auditor.
Read all six <agent>.json files for this round. Compute:
per_section_verdict[section_id] = revise if ANY agent said revise, else approvetotal_critical = count(severity=critical), total_high = count(severity=high)overall_verdict_per_agent[agent]stuck_sections = sections where the same (agent, category) appears in this round AND the previous round at severity ≥ highDecision tree:
if all agents approve AND all sections approve AND mermaid-failures empty:
→ goto Step 4.7 (loop done, success)
elif ROUND >= qc_max_rounds:
→ goto Step 4.6 (final arbitration)
elif stuck_sections is non-empty:
→ goto Step 4.5b (mid-loop targeted arbitration for stuck sections)
→ then continue to Step 4.5 (full Writer rewrite)
else:
→ goto Step 4.5 (Writer rewrite)
Rather than a single Writer rewriting the entire disclosure, launch ONE Writer per section that needs revision (in parallel), then a consolidator pass for cross-section issues. This is more robust (one Writer error doesn't poison the whole rewrite) and faster (parallelism).
Step 4.5a — Group findings by section. Build sections_needing_revision = {section_id: [issues]} from the consolidated findings. Cross-section issues go to a separate bucket for the consolidator.
Step 4.5b — Launch parallel section-patch Writers. For each section in sections_needing_revision, in parallel via the Agent tool:
For each section_id with findings:
Agent tool with:
subagent_type: "general-purpose"
description: "QC round <ROUND>: section-patch <section_id>"
prompt: |
Read your role prompt at ${CLAUDE_SKILL_DIR}/prompts/qc/writer.md.
Read the IDS schema at ${CLAUDE_SKILL_DIR}/ids-schema.json.
Read the diagram guidelines at ${CLAUDE_SKILL_DIR}/prompts/diagram-guidelines.md.
MODE=section_patch
SECTION_ID=<section_id>
ROUND=<ROUND>
Codebase: <CODEBASE_ROOT>
Current section answer + diagrams: read from patent-disclosures/<SLUG>/ids.json
Findings for THIS section only: <inline JSON of grouped findings>
Output a single JSON object per the section_patch schema in writer.md.
Save to: patent-disclosures/<SLUG>/qc-rounds/round-<ROUND>/section-patches/<section_id>.json
Each section-patch Writer touches only its section. Token cost is dramatically lower than the monolithic Writer because each call sees only one section's content + that section's findings.
Step 4.5c — Apply section patches to IDS. After all parallel Writers return, the orchestrator (this skill) reads each <section_id>.json patch and applies it:
mkdir -p patent-disclosures/${SLUG}/qc-rounds/round-${ROUND}/writer-output
python3 ${CLAUDE_PLUGIN_ROOT}/scripts/apply-section-patches.py \
--ids patent-disclosures/${SLUG}/ids.json \
--patches-dir patent-disclosures/${SLUG}/qc-rounds/round-${ROUND}/section-patches \
--output-ids patent-disclosures/${SLUG}/qc-rounds/round-${ROUND}/writer-output/ids.json
If scripts/apply-section-patches.py is unavailable, do this inline: load the IDS, replace each section's answer and diagrams from the patch, write the new IDS.
Step 4.5d — Regenerate disclosure.md from updated IDS. Use the disclosure template + updated IDS section answers in canonical order. Save to qc-rounds/round-${ROUND}/writer-output/disclosure.md.
Step 4.5e — Consolidator pass for cross-section issues. If there are any cross_section_issues from the round's findings OR any cross_section_dependency deferrals from the section-patch Writers, launch a single Consolidator:
Agent tool with:
subagent_type: "general-purpose"
description: "QC round <ROUND>: consolidator"
prompt: |
Read your role prompt at ${CLAUDE_SKILL_DIR}/prompts/qc/writer.md.
MODE=consolidator
Inputs:
IDS: <writer-output/ids.json>
Disclosure: <writer-output/disclosure.md>
Cross-section issues: <inline JSON list>
Address ONLY the cross-section issues. Make the smallest edits across sections needed for consistency. Output the same three files (ids.json, disclosure.md, changelog.json) overwriting writer-output/.
If there are no cross-section issues, skip the consolidator and write a minimal changelog.json directly from the section patches.
Step 4.5f — Promote to working artifacts and increment round:
WO=patent-disclosures/${SLUG}/qc-rounds/round-${ROUND}/writer-output
cp "${WO}/ids.json" patent-disclosures/${SLUG}/ids.json
cp "${WO}/disclosure.md" patent-disclosures/${SLUG}/disclosure.md
bash ${CLAUDE_PLUGIN_ROOT}/scripts/log-run.sh --slug ${SLUG} --phase qc_round --event end \
--data "{\"round\":${ROUND},\"sections_revised\":<count>,\"cross_section_pass\":<bool>}"
Increment ROUND. Goto Step 4.2.
For each stuck_section, launch the Lead Attorney with MODE=arbitration_partial for ONLY that section. The Lead returns either:
accept_as_is — the residual finding is overruled; remove it from consideration this round forward.force_writer_directive: "<text>" — pass that directive into the Writer's prompt as a section-specific override.Save Lead's response to qc-rounds/round-<ROUND>/lead_arbitration_partial.json. Then continue to Step 4.5.
Launch the Lead Attorney with MODE=arbitration and inputs pointing at all rounds' findings + writer changelogs. The Lead returns the arbitration JSON described in lead-attorney.md. For each section:
accept_as_is — promote current artifact, no change.accept_with_caveats — promote current artifact; record caveats_for_qc_trail in the trail.block_and_rewrite — launch the Writer ONE more time with the Lead's writer_directive, scoped to that section only. Promote the output. No more critic rounds.overall_publication_decision is recorded in the trail. hold means the disclosure ships with a prominent warning at the top of disclosure.md and a separate stop-the-line note in qc-trail.md.
Generate patent-disclosures/<SLUG>/qc-trail.md by calling the helper script:
bash ${CLAUDE_PLUGIN_ROOT}/scripts/qc-trail.sh \
patent-disclosures/<SLUG> \
--outcome <publish|publish_with_caveats|hold>
(The --gdoc-url and --original-url flags are populated by Phase 5 after publication and the trail is updated then.) The script reads every round's per-agent JSON + Writer changelog and produces a single Markdown summary with: rounds run, severity histogram per round, final per-agent verdicts, and reproducibility pointers. If the user's case requires additional narrative (e.g. arbitration caveats), append it to the file after the script runs.
Update ids.json's qc_assessment field with the final per-agent verdicts and aggregate severity counts.
Update .state.json: last_phase_completed: "phase_4".
If beads: bd update <task-id> --note "QC complete: <N> rounds, outcome=<publish|publish_with_caveats|hold>, <X> findings addressed".
Emit phase_4 telemetry:
bash ${CLAUDE_PLUGIN_ROOT}/scripts/log-run.sh --slug ${SLUG} --phase phase_4 --event end \
--data "{\"rounds\":${ROUND},\"outcome\":\"<outcome>\",\"findings_addressed\":<X>}"
Tell the user briefly (one paragraph max):
QC complete. rounds ran. findings addressed across sections; diagrams added or fixed. Final outcome: <publish/publish_with_caveats/hold>. Trail:
patent-disclosures/<SLUG>/qc-trail.md. Proceeding to publish.
If hold: do NOT auto-proceed to Phase 5. Surface the blocking concerns and ask the user how to proceed.
Deliverable contract: the final deliverable is a Google Doc. The files written to patent-disclosures/<slug>/ are intermediate artifacts used to build that doc and provide a reproducible record — they are NOT the deliverable. Do not tell the user "your disclosure is ready at patent-disclosures/..." as if the markdown were the handoff; always present the Google Doc URL as the primary deliverable.
Read the template from ${CLAUDE_SKILL_DIR}/templates/disclosure-template.md. Use it as a structural guide — fill in each section from the IDS JSON content.
Important: Diagrams are already embedded within each section's content (in the IDS answer field). Do NOT add separate diagram subsections that duplicate them. The template's diagram placeholders are for sections where the section prompt did not naturally produce a diagram — only fill them if the section content does not already contain that diagram type.
Save to: patent-disclosures/<invention-slug>/disclosure.md (intermediate — feeds the renderer in Step 5.4).
After saving the disclosure markdown, render all Mermaid diagrams to PNG images. This is required because Google Docs (and most document formats) cannot render Mermaid code blocks natively.
# Create diagrams directory
mkdir -p patent-disclosures/<invention-slug>/diagrams
# Extract and render each mermaid block using mermaid-cli (mmdc)
# If mmdc is not available, try installing it:
# npm install -g @mermaid-js/mermaid-cli
For each \``mermaid` block in the disclosure:
.mmd filemmdc -i diagram.mmd -o patent-disclosures/<slug>/diagrams/diagram_N.png -w 1200 -b transparent --quietSave an export-ready version of the disclosure with image references replacing Mermaid blocks:
\``mermaid ... ```block with
`patent-disclosures/<invention-slug>/disclosure-export.mdThis gives users two versions:
disclosure.md — the canonical version with Mermaid source (renders in GitHub, VS Code)disclosure-export.md — the export version with PNG images (for Google Docs, Word, PDF)Create a traceability appendix that maps each claim element to its implementation:
## Appendix: Claim-to-Code Mapping
| Claim | Element | Implementation | File | Lines |
|-------|---------|---------------|------|-------|
| 1 | "receiving input data" | `handleRequest()` | src/api/handler.go | 42-58 |
| 1 | "computing adaptive threshold" | `AdaptiveThreshold.compute()` | src/algo/threshold.go | 112-145 |
| ... | ... | ... | ... | ... |
Append this to disclosure.md.
The QC trail (patent-disclosures/<invention-slug>/qc-trail.md) was already written by Phase 4. Verify it exists. Do NOT overwrite it. If you find an older qc-report.md from a legacy run, leave it in place for backward compatibility.
Publishing to Google Docs is REQUIRED. This is the deliverable. If you cannot publish, you have not completed the skill — stop and resolve the blocker.
Use the render-and-export script. It pre-renders Mermaid diagrams to PNG images so they display as actual diagrams in the Google Doc (not code blocks):
bash ${CLAUDE_PLUGIN_ROOT}/scripts/render-and-export.sh patent-disclosures/<slug>/disclosure.md
If the user specifies a Google account or Drive folder:
bash ${CLAUDE_PLUGIN_ROOT}/scripts/render-and-export.sh patent-disclosures/<slug>/disclosure.md \
--account [email protected] --folder-id <DRIVE_FOLDER_ID>
Re-verify prerequisites immediately before publishing (the first-run check may have run in an earlier session):
# gog installed AND authorized
if ! command -v gog &> /dev/null; then
echo "BLOCKER: gogcli missing — cannot publish. Run: bash \${CLAUDE_PLUGIN_ROOT}/scripts/setup.sh"
exit 1
fi
if ! gog auth list --json 2>/dev/null | grep -q '"email"'; then
echo "BLOCKER: gogcli not authorized — run: gog login <your-email>"
exit 1
fi
# mmdc (diagrams → PNGs) — recommended, not fatal
if ! command -v mmdc &> /dev/null; then
echo "NOTE: mermaid-cli missing; diagrams will appear as code blocks."
fi
If either gog blocker fires, stop. Re-run the First-Run Setup prompts — do NOT continue with a local-only output.
If mmdc is unavailable and cannot be installed, fall back to export-to-gdocs.sh (same script, diagrams as code blocks) and warn the user — but a Google Doc is still produced:
"Diagrams were exported as code blocks because mermaid-cli (mmdc) is not available. Install with
npm install -g @mermaid-js/mermaid-cliand re-run Step 5.4 for rendered images."
After the Google Doc is created, capture the URL from the gog JSON output and present it as THE deliverable:
Disclosure for '<Title>' is published.
→ Google Doc (deliverable): <URL from gog output>
Reproducible artifacts in patent-disclosures/<slug>/:
disclosure.md (intermediate — Mermaid source)
disclosure-export.md (intermediate — rendered PNG references)
diagrams/ (rendered diagram PNGs)
ids.json (intermediate data structure)
qc-trail.md (multi-agent QC summary)
qc-rounds/ (raw findings + writer outputs per round)
Patents Manager (if configured): <url printed by submit-to-manager.sh>
Do not describe the skill as "complete" for this invention until the Google Doc URL has been generated and presented to the user.
Emit phase_5 + run-end telemetry:
bash ${CLAUDE_PLUGIN_ROOT}/scripts/log-run.sh --slug <slug> --phase phase_5 --event end \
--data "{\"gdoc_url\":\"<URL>\",\"diagrams_rendered\":<N>}"
If the user has configured the Patents Manager integration (env vars
PATENTS_API_URL + PATENTS_API_TOKEN, or ~/.config/patents-manager.json),
the disclosure should also be registered in the manager so it shows up on
their dashboard alongside other disclosures.
bash ${CLAUDE_PLUGIN_ROOT}/scripts/submit-to-manager.sh \
patent-disclosures/<slug>/ \
--gdoc-url "<URL from Step 5.4>" \
--qc-outcome <publish|publish_with_caveats|hold>
The script is idempotent on plugin_slug — if the manager already has a
row for this invention, it patches the doc URL + QC outcome; otherwise it
creates a new row. Re-running the plugin against the same invention is safe.
If credentials are not configured, the script prints a one-time message
explaining how to set them and exits 0 (the rest of the plugin still
works — the user just adds the disclosure manually). Set
PATENTS_SUBMIT_SKIP=1 to skip even when configured.
After running, the script prints:
→ Patents Manager: https://<host>/disclosures/<id>
Capture that URL and surface it to the user alongside the Google Doc URL in Step 5.5.
If beads is available:
bd close <task-id> --reason "Disclosure complete. Files in patent-disclosures/<slug>/"
bd ready --json
Update .state.json: mark invention status as "complete".
If more inventions are pending: "Disclosure for '' is complete! Ready to work on the next invention: '<Next Title>'?"
If all done: "All selected inventions have been disclosed. You can run /patent-disclosure again anytime to explore more ideas or revise existing disclosures."
Provides a checklist for code reviews covering functionality, security, performance, maintainability, tests, and quality. Use for pull requests, audits, team standards, and developer training.
npx claudepluginhub trilogy-group/cc-skill-patent-disclosure --plugin patent-disclosure