hashgraph-online/awesome-codex-plugins / plugins/aklofas/kicad-happy/skills/kicad
kicad
VerifiedAnalyze KiCad projects and PDF schematics: schematics, PCB layouts, Gerbers, footprints, symbols, netlists, and design rules. Reviews designs for bugs, traces nets, cross-references schematic to PCB, extracts BOM data, checks DRC/ERC, DFM, power trees, and regulator circuits. Every finding carries a confidence label and evidence source with trust_summary rollup. Analyzes PDF schematics from dev boards, reference designs, eval kits, and datasheets. Supports KiCad 5–10. Use whenever the user mentions .kicad_sch, .kicad_pcb, .kicad_pro, PCB design review, schematic analysis, PDF schematics, reference designs, Gerber files, DRC/ERC, netlist issues, BOM extraction, signal tracing, power budget, DFM, or wants to understand, debug, compare, or review any hardware design. Also for "check my board", "review before fab", "what's wrong with my schematic", "is this ready to order", "check my power supply", "verify this circuit", OSHWA certification readiness, or any electronics/PCB design question.
scripts/capability_mode.py
View on GitHub"""Canonical run-level capability_mode.json writer.
First-writer-wins pattern: the first analyzer in a run creates
analysis/capability_mode.json; subsequent analyzers in the same run
read it and embed only a capability_mode_ref pointer in their envelopes.
"""
from __future__ import annotations
import json
import os
import sys
import tempfile
import time
from pathlib import Path
from typing import Optional
from run_id import generate_run_id
from kicad_core.fileio import json_loads
from kicad_core.diagnostics import record as record_diagnostic
_SCHEMAS_DIR = Path(__file__).resolve().parent.parent.parent / "datasheets" / "schemas"
CAPABILITY_MODE_FILENAME = "capability_mode.json"
def _read_capability_mode(path: Path) -> Optional[dict]:
"""Read an existing capability_mode.json, tolerating a transient
partial or unreadable file.
Returns the parsed record, or None if the file can't be read as
valid JSON after a few short retries. Caller then falls through to
write its own via os.link — which will succeed (creating a fresh
valid record) only if the corrupt file no longer exists at write
time. **No self-heal under os.link first-writer-wins**: if the
corrupt file persists on disk, os.link raises FileExistsError, the
caller falls back to re-reading, and the retry loop here will keep
returning None on the same corrupt content (unparseable JSON). This
is distinct from valid-but-foreign JSON (e.g. an analyzer envelope
written to this path by external tooling, not through this module)
— that case parses fine here and is no longer treated as a wedge;
see _is_valid_record, which rejects it downstream and the
caller bypasses it with a fresh in-memory record instead of raising
or giving up.
The 5-retry x 5ms sleep window tolerates a file another process is
still writing or has left partial. This module's own writer never
exposes one: it closes the complete record before os.link publishes it.
"""
for _ in range(5):
try:
return json_loads(path.read_text(encoding="utf-8"))
except (ValueError, FileNotFoundError, OSError):
time.sleep(0.005)
return None
def _is_valid_record(rec) -> bool:
"""A capability_mode record is a dict with a non-empty string run_id.
Anything else at the sidecar path (an analyzer envelope, a list, a bare
string) must not be adopted as the run record: indexing
record["run_id"] on such a file crashed every analyzer at startup.
"""
return isinstance(rec, dict) and isinstance(rec.get("run_id"), str) and bool(rec["run_id"])
def _warn_malformed(path: Path, rec) -> None:
kind = type(rec).__name__ if not isinstance(rec, dict) else "dict without a string run_id"
print(f"Warning: {path} is not a capability_mode record ({kind}); "
f"leaving it untouched and using a fresh in-memory run_id",
file=sys.stderr)
def _detect_datasheet_status(cache_dir: Optional[Path] = None) -> str:
"""Return one of 'verified' | 'partial' | 'heuristic_fallback' | 'unavailable'.
A minimal check: it looks only at whether extractions are present, not at
their schema_version.
"""
if cache_dir is None:
cache_dir = Path("datasheets/extracted")
if not cache_dir.exists():
return "unavailable"
extractions = list(cache_dir.glob("*.json"))
if not extractions:
return "heuristic_fallback"
# Heuristic: at least one extraction counts as "partial"
return "partial"
def _compute_coverage_pct(cache_dir: Optional[Path] = None) -> int:
"""Percentage of the parts in the distributor manifest (``datasheets/manifest.json``,
the schematic's parts as the last sync recorded them) that have an extraction in
``cache_dir``. 0 when the manifest, its parts or the folder are missing."""
if cache_dir is None:
cache_dir = Path("datasheets/extracted")
ds_scripts = str(Path(__file__).resolve().parents[2] / "datasheets" / "scripts")
if ds_scripts not in sys.path:
sys.path.insert(0, ds_scripts)
try:
from datasheet_extract_cache import find_extraction
from datasheet_types.cache_reader import read_json_object
except ImportError:
return 0
manifest = read_json_object(Path(cache_dir).parent / "manifest.json")
parts = manifest.get("parts") if manifest else None
if not isinstance(parts, dict) or not parts:
return 0
have = sum(1 for mpn in parts if isinstance(find_extraction(cache_dir, mpn)[0], dict))
return round(100 * have / len(parts))
def _read_schema_versions() -> dict:
"""Read schema_version from each shipped datasheet schema.
Returns dict like {"base": "1.0", "regulator": "0.3", "diode": "1.0", ...}.
Resolved from this file's location so the result does not depend on the cwd.
"""
schemas_dir = _SCHEMAS_DIR
versions: dict = {}
if not schemas_dir.exists():
return versions
for schema_path in schemas_dir.glob("*.schema.json"):
try:
data = json.loads(schema_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
continue
title = schema_path.stem.replace(".schema", "")
# Schemas store version in top-level "x-schema-version" key
sv = data.get("x-schema-version")
if sv:
versions[title] = sv
return versions
def _fresh_record(datasheet_extraction, cache_dir, llm_review_status, schema_versions) -> dict:
return {
"run_id": generate_run_id(),
"datasheet_extraction": datasheet_extraction or _detect_datasheet_status(cache_dir),
"datasheet_coverage_pct": _compute_coverage_pct(cache_dir),
"llm_review": llm_review_status,
"insertion_points_active": [],
"schema_versions": schema_versions or _read_schema_versions(),
"platform": "claude-code",
"tier_map": {},
}
def get_or_create_capability_mode(
analysis_dir,
*,
llm_review_status: str = "disabled",
datasheet_extraction: Optional[str] = None,
schema_versions: Optional[dict] = None,
cache_dir: Optional[Path] = None,
) -> dict:
"""Return the canonical capability_mode record for analysis_dir, creating it if absent.
First-writer-wins: subsequent calls return the existing record verbatim,
NOT updating fields. Updates require explicit refresh by the orchestrator
(e.g., when llm_review transitions from disabled to active mid-run).
"""
analysis_dir = Path(analysis_dir)
path = analysis_dir / CAPABILITY_MODE_FILENAME
if path.exists():
existing = _read_capability_mode(path)
if existing is not None:
if _is_valid_record(existing):
return existing
# Parses, but is not ours — never crash the analysis
# over a sidecar; do not overwrite someone else's file either.
_warn_malformed(path, existing)
return _fresh_record(datasheet_extraction, cache_dir,
llm_review_status, schema_versions)
# exists() is True but the file isn't valid JSON yet — most likely
# another process or external tool left a partial file (our own
# writer never exposes one at this path). Fall through and try to write our own.
# If we win the os.link race, the file is now our valid record.
# If we lose (FileExistsError), we re-read the winner's record —
# which will succeed if the racing writer completed, or return
# the original record stub if the file was externally corrupted
# (no self-heal under os.link first-writer-wins; see
# _read_capability_mode docstring for recovery).
record = _fresh_record(datasheet_extraction, cache_dir, llm_review_status, schema_versions)
try:
analysis_dir.mkdir(parents=True, exist_ok=True)
fd, tmp_path = tempfile.mkstemp(dir=analysis_dir, prefix=".capmode-", suffix=".tmp")
except OSError as exc:
# A read-only directory (sandbox, read-only checkout) must not fail the analysis.
record_diagnostic(None, "capability_mode.get_or_create_capability_mode", exc,
f"{CAPABILITY_MODE_FILENAME} not written, in-memory record used")
return record
# Atomic create: stage the full record to a temp file in the same
# directory, then os.link() it into place. os.link raises
# FileExistsError if the target already exists, so it is an atomic
# exclusive-create — this gives BOTH guarantees the old non-atomic
# write_text() lacked:
# 1. no partial read — the content is fully written before linking,
# so a concurrent reader never sees a half-written file (the old
# code could crash a reader with JSONDecodeError mid-write);
# 2. true first-writer-wins — if two analyzers race past the
# exists() check above, exactly one os.link() succeeds; the loser
# reads the winner's record, so every analyzer in the run shares
# one run_id (HI-7).
try:
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f:
f.write(json.dumps(record, indent=2, sort_keys=True) + "\n")
try:
os.link(tmp_path, path)
except FileExistsError:
# Another analyzer won the race — return its record, not ours.
winner = _read_capability_mode(path)
if _is_valid_record(winner):
return winner
if winner is not None:
_warn_malformed(path, winner)
return record
except OSError as exc:
# Full disk, or a filesystem without hard links (FAT, exFAT).
record_diagnostic(None, "capability_mode.get_or_create_capability_mode", exc,
f"{CAPABILITY_MODE_FILENAME} not written, in-memory record used")
return record
finally:
try:
os.unlink(tmp_path)
except OSError:
pass
return record
def get_capability_mode_ref(analysis_dir, **kwargs) -> dict:
"""Return a {source, run_id} pointer for embedding in analyzer envelopes.
Side-effect: ensures capability_mode.json exists (first-writer-wins).
"""
record = get_or_create_capability_mode(analysis_dir, **kwargs)
return {
"source": f"analysis/{CAPABILITY_MODE_FILENAME}",
"run_id": record["run_id"],
}
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the work | Stars: 321k | Updated | Claude CodeCodex | Verified | Install |
| systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixes | Stars: 321k | Updated | Claude CodeCodex | Verified | Install |
| test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation code | Stars: 321k | Updated | Claude CodeCodex | Verified | Install |
| skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy. | Stars: 197k | Updated | Claude CodeCodex | Verified | Install |