traceforge-pcb 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- traceforge/__init__.py +3 -0
- traceforge/__main__.py +3 -0
- traceforge/acp_server.py +570 -0
- traceforge/agent.py +680 -0
- traceforge/altium/__init__.py +6 -0
- traceforge/altium/cfb.py +70 -0
- traceforge/altium/cli.py +60 -0
- traceforge/altium/model.py +163 -0
- traceforge/altium/outputs.py +24 -0
- traceforge/altium/pcb.py +301 -0
- traceforge/altium/project.py +328 -0
- traceforge/altium/schematic.py +400 -0
- traceforge/altium/tools.py +166 -0
- traceforge/approval.py +219 -0
- traceforge/attachments.py +346 -0
- traceforge/background.py +253 -0
- traceforge/bench/__init__.py +5 -0
- traceforge/bench/adapters.py +337 -0
- traceforge/bench/checks.py +410 -0
- traceforge/bench/cli.py +121 -0
- traceforge/bench/design.py +439 -0
- traceforge/bench/kicad.py +99 -0
- traceforge/bench/partscheck.py +159 -0
- traceforge/bench/review.py +100 -0
- traceforge/bench/runner.py +226 -0
- traceforge/bench/score.py +204 -0
- traceforge/bench/tasks.py +102 -0
- traceforge/chat.py +1185 -0
- traceforge/checks.py +328 -0
- traceforge/checks_sides.py +118 -0
- traceforge/cli.py +2224 -0
- traceforge/clipboard.py +107 -0
- traceforge/config.py +299 -0
- traceforge/context.py +276 -0
- traceforge/design/__init__.py +1 -0
- traceforge/design/constraints.py +397 -0
- traceforge/design/generate.py +1789 -0
- traceforge/design/outline.py +905 -0
- traceforge/design/schematic_layout.py +932 -0
- traceforge/design/schematic_lint.py +329 -0
- traceforge/design/schematic_route.py +207 -0
- traceforge/design/sheets.py +854 -0
- traceforge/design/sides.py +328 -0
- traceforge/design/spec.py +462 -0
- traceforge/design/specsheet.py +2351 -0
- traceforge/design/specsheet_render.py +183 -0
- traceforge/desktop/__init__.py +109 -0
- traceforge/desktop/keys.py +90 -0
- traceforge/desktop/project.py +443 -0
- traceforge/desktop/review.py +20 -0
- traceforge/desktop/server.py +1277 -0
- traceforge/desktop/static/app.css +223 -0
- traceforge/desktop/static/app.js +683 -0
- traceforge/desktop/static/highlight.js +77 -0
- traceforge/desktop/static/index.html +89 -0
- traceforge/desktop/static/md.js +90 -0
- traceforge/desktop/static/viewer.js +213 -0
- traceforge/desktop/symbols.py +212 -0
- traceforge/desktop/update.py +65 -0
- traceforge/diagnostics.py +67 -0
- traceforge/errata.py +219 -0
- traceforge/fab.py +108 -0
- traceforge/fab_layers.py +44 -0
- traceforge/features/__init__.py +6 -0
- traceforge/features/candidates.py +117 -0
- traceforge/features/cli.py +200 -0
- traceforge/features/package.py +433 -0
- traceforge/features/revdiff.py +224 -0
- traceforge/features/sarif.py +145 -0
- traceforge/features/viewer.py +265 -0
- traceforge/firmware/__init__.py +3 -0
- traceforge/firmware/cli.py +174 -0
- traceforge/firmware/drivers.py +372 -0
- traceforge/firmware/drivers_data.py +256 -0
- traceforge/firmware/mcus.py +177 -0
- traceforge/firmware/netlist.py +55 -0
- traceforge/firmware/pinmap.py +296 -0
- traceforge/firmware/scaffold.py +466 -0
- traceforge/firmware/toolchain.py +262 -0
- traceforge/hooks.py +237 -0
- traceforge/kicad/__init__.py +0 -0
- traceforge/kicad/cli.py +519 -0
- traceforge/kicad/diffpair.py +174 -0
- traceforge/kicad/edgegeom.py +191 -0
- traceforge/kicad/edit.py +405 -0
- traceforge/kicad/escape.py +1410 -0
- traceforge/kicad/formats.py +1073 -0
- traceforge/kicad/impedance.py +320 -0
- traceforge/kicad/install.py +75 -0
- traceforge/kicad/libraries.py +490 -0
- traceforge/kicad/models3d.py +942 -0
- traceforge/kicad/outputs.py +81 -0
- traceforge/kicad/pcb.py +787 -0
- traceforge/kicad/planes.py +1242 -0
- traceforge/kicad/project.py +136 -0
- traceforge/kicad/route.py +2698 -0
- traceforge/kicad/routegeom.py +164 -0
- traceforge/kicad/schematic.py +268 -0
- traceforge/kicad/sides.py +34 -0
- traceforge/kicad/stackup.py +424 -0
- traceforge/kicad_plugin/__init__.py +12 -0
- traceforge/kicad_plugin/actions.py +92 -0
- traceforge/kicad_plugin/cli.py +66 -0
- traceforge/kicad_plugin/client.py +86 -0
- traceforge/kicad_plugin/context.py +257 -0
- traceforge/kicad_plugin/discovery.py +81 -0
- traceforge/kicad_plugin/install.py +203 -0
- traceforge/kicad_plugin/overlay.py +60 -0
- traceforge/kicad_plugin/payload/action_plugin.py +65 -0
- traceforge/kicad_plugin/payload/ipc_main.py +42 -0
- traceforge/kicad_plugin/payload/plugin.json +90 -0
- traceforge/kicad_plugin/payload/requirements.txt +1 -0
- traceforge/kicad_plugin/views.py +202 -0
- traceforge/langchain.py +57 -0
- traceforge/local.py +580 -0
- traceforge/mcp_server.py +304 -0
- traceforge/models.py +310 -0
- traceforge/next_steps.py +110 -0
- traceforge/parts/__init__.py +52 -0
- traceforge/parts/alternates.py +488 -0
- traceforge/parts/bom.py +423 -0
- traceforge/parts/brief.py +705 -0
- traceforge/parts/catalog.py +297 -0
- traceforge/parts/cli_sourcing.py +156 -0
- traceforge/parts/data/duty_rates.yaml +37 -0
- traceforge/parts/data/hs_codes.yaml +103 -0
- traceforge/parts/datasheet.py +278 -0
- traceforge/parts/fx.py +100 -0
- traceforge/parts/model.py +185 -0
- traceforge/parts/net.py +187 -0
- traceforge/parts/offers.py +46 -0
- traceforge/parts/packages.py +397 -0
- traceforge/parts/pinout.py +714 -0
- traceforge/parts/providers/__init__.py +17 -0
- traceforge/parts/providers/base.py +100 -0
- traceforge/parts/providers/jlc.py +364 -0
- traceforge/parts/providers/keyed.py +661 -0
- traceforge/parts/report.py +508 -0
- traceforge/parts/supply.py +330 -0
- traceforge/parts/verify.py +455 -0
- traceforge/parts/web.py +575 -0
- traceforge/plans.py +70 -0
- traceforge/preferences.py +127 -0
- traceforge/prices.py +130 -0
- traceforge/prices.yaml +28 -0
- traceforge/prompts/__init__.py +54 -0
- traceforge/prompts/system.md +103 -0
- traceforge/providers.py +764 -0
- traceforge/remote/__init__.py +33 -0
- traceforge/remote/client.py +422 -0
- traceforge/remote/oidc.py +240 -0
- traceforge/remote/orgs.py +510 -0
- traceforge/remote/server.py +690 -0
- traceforge/remote/store.py +100 -0
- traceforge/review_changes.py +187 -0
- traceforge/routing.py +99 -0
- traceforge/runtime.py +435 -0
- traceforge/sessions.py +324 -0
- traceforge/sexpr.py +279 -0
- traceforge/sim/__init__.py +17 -0
- traceforge/sim/acmath.py +234 -0
- traceforge/sim/circuit.py +499 -0
- traceforge/sim/cli.py +162 -0
- traceforge/sim/engine.py +172 -0
- traceforge/sim/ltspice.py +175 -0
- traceforge/sim/measure.py +123 -0
- traceforge/sim/models.py +76 -0
- traceforge/sim/project.py +218 -0
- traceforge/sim/rawfile.py +123 -0
- traceforge/sim/results.py +298 -0
- traceforge/sim/tune.py +172 -0
- traceforge/skill_commands.py +165 -0
- traceforge/skill_library/circuit-simulation/SKILL.md +30 -0
- traceforge/skill_library/compliance-review/SKILL.md +51 -0
- traceforge/skill_library/design-review/SKILL.md +47 -0
- traceforge/skill_library/errata-hunt/SKILL.md +30 -0
- traceforge/skill_library/firmware/SKILL.md +26 -0
- traceforge/skill_library/power-budget/SKILL.md +27 -0
- traceforge/skill_library/release-package/SKILL.md +29 -0
- traceforge/skill_library/sourcing-brief/SKILL.md +24 -0
- traceforge/skill_library/thermal-review/SKILL.md +15 -0
- traceforge/skills.py +131 -0
- traceforge/thermal.py +557 -0
- traceforge/tools/__init__.py +48 -0
- traceforge/tools/agent_tools.py +213 -0
- traceforge/tools/base.py +303 -0
- traceforge/tools/batch.py +155 -0
- traceforge/tools/connections.py +245 -0
- traceforge/tools/files.py +777 -0
- traceforge/tools/firmware_tools.py +218 -0
- traceforge/tools/kicad_tools.py +1072 -0
- traceforge/tools/models3d_tools.py +141 -0
- traceforge/tools/parts_tools.py +473 -0
- traceforge/tools/processes.py +246 -0
- traceforge/tools/review_tools.py +178 -0
- traceforge/tools/sim_tools.py +230 -0
- traceforge/tui.py +620 -0
- traceforge/updates.py +124 -0
- traceforge/validate/__init__.py +77 -0
- traceforge/validate/builtins.py +1091 -0
- traceforge/validate/circuits.py +1240 -0
- traceforge/validate/config.py +410 -0
- traceforge/validate/default.yaml +113 -0
- traceforge/validate/design.py +191 -0
- traceforge/validate/explain.py +112 -0
- traceforge/validate/grounding.py +169 -0
- traceforge/validate/ipc2221.py +350 -0
- traceforge/validate/multilayer.py +805 -0
- traceforge/validate/netmodel.py +261 -0
- traceforge/validate/partcheck.py +472 -0
- traceforge/validate/report.py +280 -0
- traceforge/validate/review.py +322 -0
- traceforge/validate/runner.py +662 -0
- traceforge/workspace.py +171 -0
- traceforge_pcb-1.0.0.dist-info/METADATA +463 -0
- traceforge_pcb-1.0.0.dist-info/RECORD +219 -0
- traceforge_pcb-1.0.0.dist-info/WHEEL +4 -0
- traceforge_pcb-1.0.0.dist-info/entry_points.txt +2 -0
- traceforge_pcb-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Workspace files for validation: what each check reads, their hashes, and intent documents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
# Directories never part of the design (tool state, VCS, environments, our own output).
|
|
10
|
+
_SKIP_DIRS = {
|
|
11
|
+
".git",
|
|
12
|
+
".hg",
|
|
13
|
+
".svn",
|
|
14
|
+
".venv",
|
|
15
|
+
"venv",
|
|
16
|
+
"node_modules",
|
|
17
|
+
"__pycache__",
|
|
18
|
+
".pytest_cache",
|
|
19
|
+
".ruff_cache",
|
|
20
|
+
".mypy_cache",
|
|
21
|
+
}
|
|
22
|
+
_SKIP_SUFFIXES = {".lck", ".kicad_prl", ".pyc", ".bak"}
|
|
23
|
+
_SKIP_NAMES = {"fp-info-cache", ".DS_Store", "Thumbs.db"}
|
|
24
|
+
_LIB_SUFFIXES = {".kicad_sym", ".kicad_mod", ".step", ".stp", ".wrl"}
|
|
25
|
+
_LIB_TABLES = {"fp-lib-table", "sym-lib-table"}
|
|
26
|
+
_OUTPUT_SUFFIXES = {".csv", ".gbr", ".drl", ".gbrjob", ".zip", ".pos"}
|
|
27
|
+
_MAX_HASH_BYTES = 64 * 1024 * 1024
|
|
28
|
+
|
|
29
|
+
# Documents that say what the board is meant to be. Paths are relative to the
|
|
30
|
+
# workspace; directories are scanned for Markdown. Other tools' plan folders are not read.
|
|
31
|
+
INTENT_FILES = (
|
|
32
|
+
"TRACEFORGE.md",
|
|
33
|
+
".traceforge/instructions.md",
|
|
34
|
+
".traceforge/README.md",
|
|
35
|
+
"README.md",
|
|
36
|
+
"REQUIREMENTS.md",
|
|
37
|
+
"requirements.md",
|
|
38
|
+
"SPEC.md",
|
|
39
|
+
)
|
|
40
|
+
INTENT_DIRS = (".traceforge/plans", ".traceforge/notes")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _skip_dir(name: str) -> bool:
|
|
44
|
+
return name in _SKIP_DIRS or name.endswith("-backups") or name == "backups"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def iter_files(root: Path) -> list[Path]:
|
|
48
|
+
"""Every file of the workspace except tool state, sorted for stable hashes.
|
|
49
|
+
|
|
50
|
+
``.traceforge`` is skipped except for the files that describe intent or
|
|
51
|
+
configure validation; validation's own output must never invalidate its cache.
|
|
52
|
+
"""
|
|
53
|
+
found: list[Path] = []
|
|
54
|
+
for current, dirs, files in os.walk(root):
|
|
55
|
+
rel = Path(current).relative_to(root)
|
|
56
|
+
keep = []
|
|
57
|
+
for name in sorted(dirs):
|
|
58
|
+
if _skip_dir(name):
|
|
59
|
+
continue
|
|
60
|
+
if rel == Path(".") and name == ".traceforge":
|
|
61
|
+
continue # handled below
|
|
62
|
+
keep.append(name)
|
|
63
|
+
dirs[:] = keep
|
|
64
|
+
for name in sorted(files):
|
|
65
|
+
if name in _SKIP_NAMES or name.startswith("~") or name.startswith(".#"):
|
|
66
|
+
continue
|
|
67
|
+
if Path(name).suffix.lower() in _SKIP_SUFFIXES:
|
|
68
|
+
continue
|
|
69
|
+
found.append(Path(current) / name)
|
|
70
|
+
state = root / ".traceforge"
|
|
71
|
+
for name in ("instructions.md", "README.md", "validate.yaml", "config.yaml"):
|
|
72
|
+
if (state / name).is_file():
|
|
73
|
+
found.append(state / name)
|
|
74
|
+
for sub in ("plans", "notes"):
|
|
75
|
+
if (state / sub).is_dir():
|
|
76
|
+
found.extend(sorted(p for p in (state / sub).rglob("*.md") if p.is_file()))
|
|
77
|
+
return found
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def file_sha256(path: Path) -> str:
|
|
81
|
+
digest = hashlib.sha256()
|
|
82
|
+
try:
|
|
83
|
+
with path.open("rb") as handle:
|
|
84
|
+
remaining = _MAX_HASH_BYTES
|
|
85
|
+
for chunk in iter(lambda: handle.read(1 << 20), b""):
|
|
86
|
+
digest.update(chunk)
|
|
87
|
+
remaining -= len(chunk)
|
|
88
|
+
if remaining <= 0:
|
|
89
|
+
digest.update(str(path.stat().st_size).encode())
|
|
90
|
+
break
|
|
91
|
+
except OSError:
|
|
92
|
+
return "unreadable"
|
|
93
|
+
return digest.hexdigest()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _matches(relative: str, kind: str) -> bool:
|
|
97
|
+
path = Path(relative)
|
|
98
|
+
suffix = path.suffix.lower()
|
|
99
|
+
if kind == "all":
|
|
100
|
+
return True
|
|
101
|
+
if kind == "sch":
|
|
102
|
+
return suffix == ".kicad_sch"
|
|
103
|
+
if kind == "pcb":
|
|
104
|
+
return suffix == ".kicad_pcb"
|
|
105
|
+
if kind == "pro":
|
|
106
|
+
return suffix in {".kicad_pro", ".kicad_dru"}
|
|
107
|
+
if kind == "libs":
|
|
108
|
+
return suffix in _LIB_SUFFIXES or path.name in _LIB_TABLES
|
|
109
|
+
if kind == "intent":
|
|
110
|
+
return is_intent_file(relative)
|
|
111
|
+
if kind == "outputs":
|
|
112
|
+
return suffix in _OUTPUT_SUFFIXES or (suffix.startswith(".g") and len(suffix) <= 4)
|
|
113
|
+
return False
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def is_intent_file(relative: str) -> bool:
|
|
117
|
+
if relative in INTENT_FILES:
|
|
118
|
+
return True
|
|
119
|
+
if relative.endswith(".md") and any(relative.startswith(d + "/") for d in INTENT_DIRS):
|
|
120
|
+
return True
|
|
121
|
+
# Design specs live in the workspace root; any root YAML may be one.
|
|
122
|
+
return relative.endswith((".yaml", ".yml")) and "/" not in relative
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def input_hashes(root: Path, inputs: list[str]) -> dict[str, str]:
|
|
126
|
+
"""Hashes of the files a check reads, by input kind."""
|
|
127
|
+
root = Path(root)
|
|
128
|
+
hashes: dict[str, str] = {}
|
|
129
|
+
for path in iter_files(root):
|
|
130
|
+
relative = path.relative_to(root).as_posix()
|
|
131
|
+
if any(_matches(relative, kind) for kind in inputs):
|
|
132
|
+
hashes[relative] = file_sha256(path)
|
|
133
|
+
return hashes
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def combined_hash(hashes: dict[str, str]) -> str:
|
|
137
|
+
digest = hashlib.sha256()
|
|
138
|
+
for key in sorted(hashes):
|
|
139
|
+
digest.update(f"{key}\0{hashes[key]}\n".encode())
|
|
140
|
+
return digest.hexdigest()
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def design_hash(root: Path) -> str:
|
|
144
|
+
return combined_hash(input_hashes(root, ["sch", "pcb", "pro", "libs"]))
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
# ------------------------------------------------------------------------- intent
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def find_spec_files(root: Path) -> list[Path]:
|
|
151
|
+
"""Traceforge design specs (YAML with a top-level ``parts`` list) in the workspace root."""
|
|
152
|
+
import yaml
|
|
153
|
+
|
|
154
|
+
specs = []
|
|
155
|
+
for path in sorted([*root.glob("*.yaml"), *root.glob("*.yml")]):
|
|
156
|
+
try:
|
|
157
|
+
data = yaml.safe_load(path.read_text(encoding="utf-8"))
|
|
158
|
+
except (OSError, yaml.YAMLError, UnicodeDecodeError):
|
|
159
|
+
continue
|
|
160
|
+
if isinstance(data, dict) and isinstance(data.get("parts"), list):
|
|
161
|
+
specs.append(path)
|
|
162
|
+
return specs
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def load_intent(root: Path, limit: int = 60_000) -> dict[str, str]:
|
|
166
|
+
"""Intent documents keyed by workspace-relative path (largest files truncated)."""
|
|
167
|
+
root = Path(root)
|
|
168
|
+
found: dict[str, str] = {}
|
|
169
|
+
candidates: list[Path] = [root / name for name in INTENT_FILES]
|
|
170
|
+
for directory in INTENT_DIRS:
|
|
171
|
+
base = root / directory
|
|
172
|
+
if base.is_dir():
|
|
173
|
+
candidates += sorted(base.rglob("*.md"), key=lambda p: p.stat().st_mtime, reverse=True)
|
|
174
|
+
candidates += find_spec_files(root)
|
|
175
|
+
total = 0
|
|
176
|
+
for path in candidates:
|
|
177
|
+
if not path.is_file():
|
|
178
|
+
continue
|
|
179
|
+
relative = path.relative_to(root).as_posix()
|
|
180
|
+
if relative in found:
|
|
181
|
+
continue
|
|
182
|
+
try:
|
|
183
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
184
|
+
except OSError:
|
|
185
|
+
continue
|
|
186
|
+
text = text[:20_000]
|
|
187
|
+
if total + len(text) > limit:
|
|
188
|
+
break
|
|
189
|
+
found[relative] = text
|
|
190
|
+
total += len(text)
|
|
191
|
+
return found
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Describe the validation graph: ``traceforge validate list | graph | explain <id>``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from traceforge.validate.config import ValidationConfig
|
|
8
|
+
from traceforge.validate.runner import stage_waves
|
|
9
|
+
|
|
10
|
+
# What the circuit rules look at, for `validate explain sch.circuit_rules`.
|
|
11
|
+
_DETAILS = {
|
|
12
|
+
"circuits": (
|
|
13
|
+
"LED: polarity against the symbol/footprint pinout; current = (rail - Vf) / R with Vf "
|
|
14
|
+
"from the catalogue (else typical for the colour), flagged under ~1 mA (dim) or above "
|
|
15
|
+
"the LED's rating or the driving MCU pin's limit. USB-C: CC pull-down 5.1 kOhm. "
|
|
16
|
+
"Buttons: pull-ups and floating inputs. Decoupling: a capacitor near each IC supply pin. "
|
|
17
|
+
"Regulators: input/output capacitors, output capacitor type, capacitance and ESR against "
|
|
18
|
+
"the regulator's part data or a built-in table (AMS1117, LM1117, LD1117, AP2112, XC6206, "
|
|
19
|
+
"MCP1700, ...), dropout and maximum input. Part data is optional: offline runs fall back "
|
|
20
|
+
"to values, footprints and typical figures."
|
|
21
|
+
),
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _builtin(check_id: str, name: str) -> Any:
|
|
26
|
+
from traceforge.validate.builtins import BUILTINS
|
|
27
|
+
|
|
28
|
+
return BUILTINS.get(name or check_id)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def list_checks(config: ValidationConfig) -> list[dict[str, Any]]:
|
|
32
|
+
rows = []
|
|
33
|
+
for check in config.checks:
|
|
34
|
+
rows.append(
|
|
35
|
+
{
|
|
36
|
+
"id": check.id,
|
|
37
|
+
"stage": check.stage,
|
|
38
|
+
"kind": check.kind,
|
|
39
|
+
"gate": check.gate,
|
|
40
|
+
"enabled": check.enabled,
|
|
41
|
+
"title": check.title,
|
|
42
|
+
}
|
|
43
|
+
)
|
|
44
|
+
return rows
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def graph_text(config: ValidationConfig) -> str:
|
|
48
|
+
"""Stages in order, each with its checks in dependency waves and their prerequisites."""
|
|
49
|
+
by_stage: dict[str, list] = {}
|
|
50
|
+
for check in config.enabled_checks():
|
|
51
|
+
by_stage.setdefault(check.stage, []).append(check)
|
|
52
|
+
lines: list[str] = []
|
|
53
|
+
for stage, title in config.stages.items():
|
|
54
|
+
checks = by_stage.get(stage, [])
|
|
55
|
+
lines.append(f"{stage} {title}" + ("" if checks else " (no checks)"))
|
|
56
|
+
for n, wave in enumerate(stage_waves(checks), 1):
|
|
57
|
+
for check in wave:
|
|
58
|
+
deps = ", ".join(check.needs)
|
|
59
|
+
order = ", ".join(check.after)
|
|
60
|
+
extra = (f" needs: {deps}" if deps else "") + (
|
|
61
|
+
f" after: {order}" if order else ""
|
|
62
|
+
)
|
|
63
|
+
tag = "" if check.gate == "blocking" else " [advisory]"
|
|
64
|
+
lines.append(f" {n}. {check.id} ({check.kind}){tag}{extra}")
|
|
65
|
+
return "\n".join(lines)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def explain(config: ValidationConfig, check_id: str) -> dict[str, Any]:
|
|
69
|
+
"""Everything known about one check; raises KeyError for an unknown id."""
|
|
70
|
+
check = config.check(check_id)
|
|
71
|
+
data: dict[str, Any] = {
|
|
72
|
+
"id": check.id,
|
|
73
|
+
"stage": f"{check.stage} {config.stages.get(check.stage, '')}".strip(),
|
|
74
|
+
"kind": check.kind,
|
|
75
|
+
"gate": check.gate,
|
|
76
|
+
"enabled": check.enabled,
|
|
77
|
+
"title": check.title,
|
|
78
|
+
"needs": check.needs,
|
|
79
|
+
"after": check.after,
|
|
80
|
+
"inputs": check.inputs,
|
|
81
|
+
"needed_by": [c.id for c in config.checks if check.id in c.needs],
|
|
82
|
+
}
|
|
83
|
+
if check.kind == "builtin":
|
|
84
|
+
builtin = _builtin(check.id, check.builtin)
|
|
85
|
+
name = check.builtin or check.id
|
|
86
|
+
data["implementation"] = name if builtin else f"{name} (unknown builtin)"
|
|
87
|
+
if builtin is not None:
|
|
88
|
+
data["what"] = builtin.description
|
|
89
|
+
data["cached"] = builtin.cacheable
|
|
90
|
+
detail = _DETAILS.get("circuits") if builtin and "circuit" in name else None
|
|
91
|
+
if detail:
|
|
92
|
+
data["details"] = detail
|
|
93
|
+
else:
|
|
94
|
+
data["repeat"] = check.repeat
|
|
95
|
+
data["prompt"] = check.prompt.strip()
|
|
96
|
+
return {k: v for k, v in data.items() if v not in (None, "", [])}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def explain_text(data: dict[str, Any]) -> str:
|
|
100
|
+
lines = [f"{data['id']}: {data['title']}"]
|
|
101
|
+
for key in ("stage", "kind", "gate", "needs", "after", "needed_by", "inputs"):
|
|
102
|
+
if key in data:
|
|
103
|
+
value = data[key]
|
|
104
|
+
lines.append(f" {key}: {', '.join(value) if isinstance(value, list) else value}")
|
|
105
|
+
for key in ("implementation", "what", "details", "repeat"):
|
|
106
|
+
if key in data:
|
|
107
|
+
lines.append(f" {key}: {data[key]}")
|
|
108
|
+
if not data.get("enabled", True):
|
|
109
|
+
lines.append(" (disabled in this project)")
|
|
110
|
+
if data.get("prompt"):
|
|
111
|
+
lines += ["", data["prompt"]]
|
|
112
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Grounding of AI review findings: every cited net, part, pin and file line must exist.
|
|
2
|
+
|
|
3
|
+
A finding that cites something the design does not contain is marked UNGROUNDED. It is demoted to
|
|
4
|
+
a P3 warning (the claimed severity is kept in ``claimed_severity``) and can never fail a gate.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from traceforge.validate.netmodel import DesignModel
|
|
13
|
+
|
|
14
|
+
_PIN_SUFFIX = re.compile(r"[_-]\d+$")
|
|
15
|
+
_NET_WRAP = re.compile(r"^NET-\((.*)\)$", re.I)
|
|
16
|
+
_FILE_LINE = re.compile(r"^(?P<file>[^\s:]+\.[A-Za-z0-9_]+):(?P<line>\d+)(?:-\d+)?$")
|
|
17
|
+
_PIN_CITE = re.compile(
|
|
18
|
+
r"^(?P<ref>[A-Za-z]+\d+[A-Za-z]?)\s*[.:/\- ]\s*(?:pin\s*)?(?P<pin>\S+)$", re.I
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def net_keys(name: str) -> set[str]:
|
|
23
|
+
"""Spellings under which one net can be cited: sheet path stripped, hierarchical label,
|
|
24
|
+
``Net-(U1-VCC_2)`` wrapper removed, KiCad pin-name suffix (``VCC_2`` -> ``VCC``)."""
|
|
25
|
+
text = name.strip()
|
|
26
|
+
if not text:
|
|
27
|
+
return set()
|
|
28
|
+
keys = {text.upper(), text.upper().lstrip("/")}
|
|
29
|
+
keys.add(text.upper().rsplit("/", 1)[-1])
|
|
30
|
+
for key in list(keys):
|
|
31
|
+
wrapped = _NET_WRAP.match(key)
|
|
32
|
+
if wrapped:
|
|
33
|
+
keys.add(wrapped.group(1))
|
|
34
|
+
keys.add(wrapped.group(1).split("-", 1)[-1])
|
|
35
|
+
for key in list(keys):
|
|
36
|
+
stripped = _PIN_SUFFIX.sub("", key)
|
|
37
|
+
if stripped:
|
|
38
|
+
keys.add(stripped)
|
|
39
|
+
return {k for k in keys if k}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Grounder:
|
|
43
|
+
def __init__(self, model: DesignModel | None, workspace: Path | None = None):
|
|
44
|
+
self.model = model
|
|
45
|
+
self.workspace = workspace
|
|
46
|
+
self.parts = {r.upper(): r for r in (model.parts if model else {})}
|
|
47
|
+
self.net_index: dict[str, str] = {}
|
|
48
|
+
for net in model.nets if model else {}:
|
|
49
|
+
for key in net_keys(net):
|
|
50
|
+
self.net_index.setdefault(key, net)
|
|
51
|
+
|
|
52
|
+
def active(self) -> bool:
|
|
53
|
+
return self.model is not None and bool(self.model.parts or self.model.nets)
|
|
54
|
+
|
|
55
|
+
def find_net(self, name: str) -> str | None:
|
|
56
|
+
"""The design's net a cited name refers to, or None."""
|
|
57
|
+
text = name.strip()
|
|
58
|
+
for key in (
|
|
59
|
+
text.upper(),
|
|
60
|
+
text.upper().lstrip("/"),
|
|
61
|
+
text.upper().rsplit("/", 1)[-1],
|
|
62
|
+
):
|
|
63
|
+
if key in self.net_index:
|
|
64
|
+
return self.net_index[key]
|
|
65
|
+
for key in net_keys(text):
|
|
66
|
+
if key in self.net_index:
|
|
67
|
+
return self.net_index[key]
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
def check_pin(self, ref: str, pin: str) -> str | None:
|
|
71
|
+
"""None when ``ref``/``pin`` exists, otherwise the problem."""
|
|
72
|
+
actual = self.parts.get(ref.upper())
|
|
73
|
+
if actual is None or self.model is None:
|
|
74
|
+
return f"unknown part {ref}"
|
|
75
|
+
part = self.model.parts[actual]
|
|
76
|
+
wanted = pin.strip().upper().replace("~{", "").replace("}", "")
|
|
77
|
+
known = set()
|
|
78
|
+
for number, definition in part.pin_defs.items():
|
|
79
|
+
known.add(number.upper())
|
|
80
|
+
known.add(definition.name.upper().replace("~{", "").replace("}", ""))
|
|
81
|
+
known |= {
|
|
82
|
+
pin_.upper() for nodes in self.model.nets.values() for r, pin_ in nodes if r == actual
|
|
83
|
+
}
|
|
84
|
+
footprint = self.model.footprint(actual)
|
|
85
|
+
if footprint is not None:
|
|
86
|
+
known |= {pad.number.upper() for pad in footprint.pads}
|
|
87
|
+
if not known:
|
|
88
|
+
return None # no pin data to contradict the citation
|
|
89
|
+
if wanted in known or _PIN_SUFFIX.sub("", wanted) in known:
|
|
90
|
+
return None
|
|
91
|
+
return f"{actual} has no pin {pin}"
|
|
92
|
+
|
|
93
|
+
def check_file_line(self, name: str, line: int) -> str | None:
|
|
94
|
+
if self.workspace is None:
|
|
95
|
+
return None
|
|
96
|
+
base = Path(name)
|
|
97
|
+
candidates = [self.workspace / name]
|
|
98
|
+
if not base.is_absolute():
|
|
99
|
+
candidates += [
|
|
100
|
+
p for p in self.workspace.rglob(base.name) if ".traceforge" not in p.parts
|
|
101
|
+
]
|
|
102
|
+
for path in candidates:
|
|
103
|
+
if path.is_file():
|
|
104
|
+
try:
|
|
105
|
+
total = sum(1 for _ in path.open(encoding="utf-8", errors="replace"))
|
|
106
|
+
except OSError:
|
|
107
|
+
return None
|
|
108
|
+
return None if 1 <= line <= total else f"{name} has no line {line} ({total} lines)"
|
|
109
|
+
return f"file {name} not found"
|
|
110
|
+
|
|
111
|
+
def check_cite(self, cite: str) -> str | None:
|
|
112
|
+
"""Problem with one free-form citation, or None when it resolves (or is not checkable)."""
|
|
113
|
+
text = cite.strip()
|
|
114
|
+
if not text:
|
|
115
|
+
return None
|
|
116
|
+
kind, _, rest = text.partition(":")
|
|
117
|
+
kind_l = kind.lower()
|
|
118
|
+
if kind_l in {"net", "ref", "part", "pin", "file"} and rest:
|
|
119
|
+
text = rest.strip()
|
|
120
|
+
else:
|
|
121
|
+
kind_l = ""
|
|
122
|
+
if kind_l == "net":
|
|
123
|
+
return None if self.find_net(text) else f"unknown net {text}"
|
|
124
|
+
if kind_l in {"ref", "part"}:
|
|
125
|
+
return None if text.upper() in self.parts else f"unknown part {text}"
|
|
126
|
+
match = _PIN_CITE.match(text)
|
|
127
|
+
if match and (kind_l == "pin" or match.group("ref").upper() in self.parts):
|
|
128
|
+
return self.check_pin(match.group("ref"), match.group("pin"))
|
|
129
|
+
file_line = _FILE_LINE.match(text)
|
|
130
|
+
if file_line:
|
|
131
|
+
return self.check_file_line(file_line.group("file"), int(file_line.group("line")))
|
|
132
|
+
if text.upper() in self.parts or self.find_net(text):
|
|
133
|
+
return None
|
|
134
|
+
return None # free text (datasheet section, calculation) is not checkable here
|
|
135
|
+
|
|
136
|
+
def problems(self, finding: dict) -> list[str]:
|
|
137
|
+
problems: list[str] = []
|
|
138
|
+
for ref in finding.get("refs", []):
|
|
139
|
+
if ref.upper() not in self.parts:
|
|
140
|
+
problems.append(f"unknown part {ref}")
|
|
141
|
+
for net in finding.get("nets", []):
|
|
142
|
+
if not self.find_net(net):
|
|
143
|
+
problems.append(f"unknown net {net}")
|
|
144
|
+
for cite in finding.get("cites", []):
|
|
145
|
+
issue = self.check_cite(cite)
|
|
146
|
+
if issue and issue not in problems:
|
|
147
|
+
problems.append(issue)
|
|
148
|
+
return problems
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def ground_findings(
|
|
152
|
+
findings: list[dict], model: DesignModel | None, workspace: Path | None = None
|
|
153
|
+
) -> None:
|
|
154
|
+
"""Mark every finding grounded or UNGROUNDED, in place."""
|
|
155
|
+
grounder = Grounder(model, workspace)
|
|
156
|
+
for finding in findings:
|
|
157
|
+
if not grounder.active():
|
|
158
|
+
finding["grounded"] = True
|
|
159
|
+
continue
|
|
160
|
+
problems = grounder.problems(finding)
|
|
161
|
+
if not (finding.get("refs") or finding.get("nets") or finding.get("cites")):
|
|
162
|
+
problems.append("no citations (refs, nets or cites)")
|
|
163
|
+
finding["grounded"] = not problems
|
|
164
|
+
if problems:
|
|
165
|
+
finding["claimed_severity"] = finding["severity"]
|
|
166
|
+
finding["severity"] = "P3"
|
|
167
|
+
finding["confidence"] = "low"
|
|
168
|
+
finding["ungrounded"] = problems
|
|
169
|
+
finding["message"] = f"[UNGROUNDED: {'; '.join(problems)}] {finding['message']}"
|