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.
Files changed (219) hide show
  1. traceforge/__init__.py +3 -0
  2. traceforge/__main__.py +3 -0
  3. traceforge/acp_server.py +570 -0
  4. traceforge/agent.py +680 -0
  5. traceforge/altium/__init__.py +6 -0
  6. traceforge/altium/cfb.py +70 -0
  7. traceforge/altium/cli.py +60 -0
  8. traceforge/altium/model.py +163 -0
  9. traceforge/altium/outputs.py +24 -0
  10. traceforge/altium/pcb.py +301 -0
  11. traceforge/altium/project.py +328 -0
  12. traceforge/altium/schematic.py +400 -0
  13. traceforge/altium/tools.py +166 -0
  14. traceforge/approval.py +219 -0
  15. traceforge/attachments.py +346 -0
  16. traceforge/background.py +253 -0
  17. traceforge/bench/__init__.py +5 -0
  18. traceforge/bench/adapters.py +337 -0
  19. traceforge/bench/checks.py +410 -0
  20. traceforge/bench/cli.py +121 -0
  21. traceforge/bench/design.py +439 -0
  22. traceforge/bench/kicad.py +99 -0
  23. traceforge/bench/partscheck.py +159 -0
  24. traceforge/bench/review.py +100 -0
  25. traceforge/bench/runner.py +226 -0
  26. traceforge/bench/score.py +204 -0
  27. traceforge/bench/tasks.py +102 -0
  28. traceforge/chat.py +1185 -0
  29. traceforge/checks.py +328 -0
  30. traceforge/checks_sides.py +118 -0
  31. traceforge/cli.py +2224 -0
  32. traceforge/clipboard.py +107 -0
  33. traceforge/config.py +299 -0
  34. traceforge/context.py +276 -0
  35. traceforge/design/__init__.py +1 -0
  36. traceforge/design/constraints.py +397 -0
  37. traceforge/design/generate.py +1789 -0
  38. traceforge/design/outline.py +905 -0
  39. traceforge/design/schematic_layout.py +932 -0
  40. traceforge/design/schematic_lint.py +329 -0
  41. traceforge/design/schematic_route.py +207 -0
  42. traceforge/design/sheets.py +854 -0
  43. traceforge/design/sides.py +328 -0
  44. traceforge/design/spec.py +462 -0
  45. traceforge/design/specsheet.py +2351 -0
  46. traceforge/design/specsheet_render.py +183 -0
  47. traceforge/desktop/__init__.py +109 -0
  48. traceforge/desktop/keys.py +90 -0
  49. traceforge/desktop/project.py +443 -0
  50. traceforge/desktop/review.py +20 -0
  51. traceforge/desktop/server.py +1277 -0
  52. traceforge/desktop/static/app.css +223 -0
  53. traceforge/desktop/static/app.js +683 -0
  54. traceforge/desktop/static/highlight.js +77 -0
  55. traceforge/desktop/static/index.html +89 -0
  56. traceforge/desktop/static/md.js +90 -0
  57. traceforge/desktop/static/viewer.js +213 -0
  58. traceforge/desktop/symbols.py +212 -0
  59. traceforge/desktop/update.py +65 -0
  60. traceforge/diagnostics.py +67 -0
  61. traceforge/errata.py +219 -0
  62. traceforge/fab.py +108 -0
  63. traceforge/fab_layers.py +44 -0
  64. traceforge/features/__init__.py +6 -0
  65. traceforge/features/candidates.py +117 -0
  66. traceforge/features/cli.py +200 -0
  67. traceforge/features/package.py +433 -0
  68. traceforge/features/revdiff.py +224 -0
  69. traceforge/features/sarif.py +145 -0
  70. traceforge/features/viewer.py +265 -0
  71. traceforge/firmware/__init__.py +3 -0
  72. traceforge/firmware/cli.py +174 -0
  73. traceforge/firmware/drivers.py +372 -0
  74. traceforge/firmware/drivers_data.py +256 -0
  75. traceforge/firmware/mcus.py +177 -0
  76. traceforge/firmware/netlist.py +55 -0
  77. traceforge/firmware/pinmap.py +296 -0
  78. traceforge/firmware/scaffold.py +466 -0
  79. traceforge/firmware/toolchain.py +262 -0
  80. traceforge/hooks.py +237 -0
  81. traceforge/kicad/__init__.py +0 -0
  82. traceforge/kicad/cli.py +519 -0
  83. traceforge/kicad/diffpair.py +174 -0
  84. traceforge/kicad/edgegeom.py +191 -0
  85. traceforge/kicad/edit.py +405 -0
  86. traceforge/kicad/escape.py +1410 -0
  87. traceforge/kicad/formats.py +1073 -0
  88. traceforge/kicad/impedance.py +320 -0
  89. traceforge/kicad/install.py +75 -0
  90. traceforge/kicad/libraries.py +490 -0
  91. traceforge/kicad/models3d.py +942 -0
  92. traceforge/kicad/outputs.py +81 -0
  93. traceforge/kicad/pcb.py +787 -0
  94. traceforge/kicad/planes.py +1242 -0
  95. traceforge/kicad/project.py +136 -0
  96. traceforge/kicad/route.py +2698 -0
  97. traceforge/kicad/routegeom.py +164 -0
  98. traceforge/kicad/schematic.py +268 -0
  99. traceforge/kicad/sides.py +34 -0
  100. traceforge/kicad/stackup.py +424 -0
  101. traceforge/kicad_plugin/__init__.py +12 -0
  102. traceforge/kicad_plugin/actions.py +92 -0
  103. traceforge/kicad_plugin/cli.py +66 -0
  104. traceforge/kicad_plugin/client.py +86 -0
  105. traceforge/kicad_plugin/context.py +257 -0
  106. traceforge/kicad_plugin/discovery.py +81 -0
  107. traceforge/kicad_plugin/install.py +203 -0
  108. traceforge/kicad_plugin/overlay.py +60 -0
  109. traceforge/kicad_plugin/payload/action_plugin.py +65 -0
  110. traceforge/kicad_plugin/payload/ipc_main.py +42 -0
  111. traceforge/kicad_plugin/payload/plugin.json +90 -0
  112. traceforge/kicad_plugin/payload/requirements.txt +1 -0
  113. traceforge/kicad_plugin/views.py +202 -0
  114. traceforge/langchain.py +57 -0
  115. traceforge/local.py +580 -0
  116. traceforge/mcp_server.py +304 -0
  117. traceforge/models.py +310 -0
  118. traceforge/next_steps.py +110 -0
  119. traceforge/parts/__init__.py +52 -0
  120. traceforge/parts/alternates.py +488 -0
  121. traceforge/parts/bom.py +423 -0
  122. traceforge/parts/brief.py +705 -0
  123. traceforge/parts/catalog.py +297 -0
  124. traceforge/parts/cli_sourcing.py +156 -0
  125. traceforge/parts/data/duty_rates.yaml +37 -0
  126. traceforge/parts/data/hs_codes.yaml +103 -0
  127. traceforge/parts/datasheet.py +278 -0
  128. traceforge/parts/fx.py +100 -0
  129. traceforge/parts/model.py +185 -0
  130. traceforge/parts/net.py +187 -0
  131. traceforge/parts/offers.py +46 -0
  132. traceforge/parts/packages.py +397 -0
  133. traceforge/parts/pinout.py +714 -0
  134. traceforge/parts/providers/__init__.py +17 -0
  135. traceforge/parts/providers/base.py +100 -0
  136. traceforge/parts/providers/jlc.py +364 -0
  137. traceforge/parts/providers/keyed.py +661 -0
  138. traceforge/parts/report.py +508 -0
  139. traceforge/parts/supply.py +330 -0
  140. traceforge/parts/verify.py +455 -0
  141. traceforge/parts/web.py +575 -0
  142. traceforge/plans.py +70 -0
  143. traceforge/preferences.py +127 -0
  144. traceforge/prices.py +130 -0
  145. traceforge/prices.yaml +28 -0
  146. traceforge/prompts/__init__.py +54 -0
  147. traceforge/prompts/system.md +103 -0
  148. traceforge/providers.py +764 -0
  149. traceforge/remote/__init__.py +33 -0
  150. traceforge/remote/client.py +422 -0
  151. traceforge/remote/oidc.py +240 -0
  152. traceforge/remote/orgs.py +510 -0
  153. traceforge/remote/server.py +690 -0
  154. traceforge/remote/store.py +100 -0
  155. traceforge/review_changes.py +187 -0
  156. traceforge/routing.py +99 -0
  157. traceforge/runtime.py +435 -0
  158. traceforge/sessions.py +324 -0
  159. traceforge/sexpr.py +279 -0
  160. traceforge/sim/__init__.py +17 -0
  161. traceforge/sim/acmath.py +234 -0
  162. traceforge/sim/circuit.py +499 -0
  163. traceforge/sim/cli.py +162 -0
  164. traceforge/sim/engine.py +172 -0
  165. traceforge/sim/ltspice.py +175 -0
  166. traceforge/sim/measure.py +123 -0
  167. traceforge/sim/models.py +76 -0
  168. traceforge/sim/project.py +218 -0
  169. traceforge/sim/rawfile.py +123 -0
  170. traceforge/sim/results.py +298 -0
  171. traceforge/sim/tune.py +172 -0
  172. traceforge/skill_commands.py +165 -0
  173. traceforge/skill_library/circuit-simulation/SKILL.md +30 -0
  174. traceforge/skill_library/compliance-review/SKILL.md +51 -0
  175. traceforge/skill_library/design-review/SKILL.md +47 -0
  176. traceforge/skill_library/errata-hunt/SKILL.md +30 -0
  177. traceforge/skill_library/firmware/SKILL.md +26 -0
  178. traceforge/skill_library/power-budget/SKILL.md +27 -0
  179. traceforge/skill_library/release-package/SKILL.md +29 -0
  180. traceforge/skill_library/sourcing-brief/SKILL.md +24 -0
  181. traceforge/skill_library/thermal-review/SKILL.md +15 -0
  182. traceforge/skills.py +131 -0
  183. traceforge/thermal.py +557 -0
  184. traceforge/tools/__init__.py +48 -0
  185. traceforge/tools/agent_tools.py +213 -0
  186. traceforge/tools/base.py +303 -0
  187. traceforge/tools/batch.py +155 -0
  188. traceforge/tools/connections.py +245 -0
  189. traceforge/tools/files.py +777 -0
  190. traceforge/tools/firmware_tools.py +218 -0
  191. traceforge/tools/kicad_tools.py +1072 -0
  192. traceforge/tools/models3d_tools.py +141 -0
  193. traceforge/tools/parts_tools.py +473 -0
  194. traceforge/tools/processes.py +246 -0
  195. traceforge/tools/review_tools.py +178 -0
  196. traceforge/tools/sim_tools.py +230 -0
  197. traceforge/tui.py +620 -0
  198. traceforge/updates.py +124 -0
  199. traceforge/validate/__init__.py +77 -0
  200. traceforge/validate/builtins.py +1091 -0
  201. traceforge/validate/circuits.py +1240 -0
  202. traceforge/validate/config.py +410 -0
  203. traceforge/validate/default.yaml +113 -0
  204. traceforge/validate/design.py +191 -0
  205. traceforge/validate/explain.py +112 -0
  206. traceforge/validate/grounding.py +169 -0
  207. traceforge/validate/ipc2221.py +350 -0
  208. traceforge/validate/multilayer.py +805 -0
  209. traceforge/validate/netmodel.py +261 -0
  210. traceforge/validate/partcheck.py +472 -0
  211. traceforge/validate/report.py +280 -0
  212. traceforge/validate/review.py +322 -0
  213. traceforge/validate/runner.py +662 -0
  214. traceforge/workspace.py +171 -0
  215. traceforge_pcb-1.0.0.dist-info/METADATA +463 -0
  216. traceforge_pcb-1.0.0.dist-info/RECORD +219 -0
  217. traceforge_pcb-1.0.0.dist-info/WHEEL +4 -0
  218. traceforge_pcb-1.0.0.dist-info/entry_points.txt +2 -0
  219. traceforge_pcb-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,212 @@
1
+ """Click-target boxes for placed schematic symbols, from the symbol graphics in the file.
2
+
3
+ A ``.kicad_sch`` embeds every library symbol it uses in ``lib_symbols`` (rectangles, polylines,
4
+ circles, arcs and pins). The box of a placed symbol is the extent of those graphics, moved to the
5
+ placed position with the symbol's rotation and mirroring. A symbol whose library entry is missing
6
+ or has no graphics gets a size estimated from its reference prefix, and the item says so
7
+ (``"estimated": true``) so the viewer can tell the two apart.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ import re
14
+ from pathlib import Path
15
+
16
+ from traceforge import sexpr
17
+ from traceforge.sexpr import Node, find, find_all, num, prop, value
18
+
19
+ Box = tuple[float, float, float, float] # x0, y0, x1, y1 in library units (mm, y up)
20
+
21
+ _ESTIMATE = {
22
+ ("U", "IC"): (14.0, 12.0),
23
+ ("J", "P", "CN"): (8.0, 8.0),
24
+ ("Q", "D", "LED", "SW", "F", "Y"): (5.0, 4.0),
25
+ }
26
+
27
+
28
+ def estimate_half(reference: str) -> tuple[float, float]:
29
+ """Half extent guessed from the reference prefix, for symbols without usable graphics."""
30
+ match = re.match(r"[A-Za-z]+", reference)
31
+ kind = match.group(0) if match else ""
32
+ for prefixes, half in _ESTIMATE.items():
33
+ if kind in prefixes:
34
+ return half
35
+ return 3.5, 4.0
36
+
37
+
38
+ def _xy(node: Node | None) -> tuple[float, float] | None:
39
+ if node is None or len(node) < 3:
40
+ return None
41
+ return num(node[1]), num(node[2])
42
+
43
+
44
+ def _arc_points(start: tuple[float, float], mid: tuple[float, float], end: tuple[float, float]):
45
+ """The three defining points plus any axis extreme the arc passes through."""
46
+ pts = [start, mid, end]
47
+ (x1, y1), (x2, y2), (x3, y3) = start, mid, end
48
+ d = 2 * (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2))
49
+ if abs(d) < 1e-9:
50
+ return pts
51
+ ux = (
52
+ (x1**2 + y1**2) * (y2 - y3) + (x2**2 + y2**2) * (y3 - y1) + (x3**2 + y3**2) * (y1 - y2)
53
+ ) / d
54
+ uy = (
55
+ (x1**2 + y1**2) * (x3 - x2) + (x2**2 + y2**2) * (x1 - x3) + (x3**2 + y3**2) * (x2 - x1)
56
+ ) / d
57
+ r = math.hypot(x1 - ux, y1 - uy)
58
+ a1, am, a3 = (math.atan2(p[1] - uy, p[0] - ux) for p in (start, mid, end))
59
+
60
+ def between(a: float, lo: float, hi: float, ccw: bool) -> bool:
61
+ if not ccw:
62
+ lo, hi = hi, lo
63
+ span = (hi - lo) % (2 * math.pi)
64
+ return (a - lo) % (2 * math.pi) <= span
65
+
66
+ ccw = between(am, a1, a3, True)
67
+ for k in range(4):
68
+ angle = k * math.pi / 2
69
+ if between(angle, a1, a3, ccw):
70
+ pts.append((ux + r * math.cos(angle), uy + r * math.sin(angle)))
71
+ return pts
72
+
73
+
74
+ def _graphics(node: Node, unit: int) -> list[tuple[float, float]]:
75
+ """Every point that bounds the drawing of ``node`` for one unit (units 0 and ``unit``)."""
76
+ pts: list[tuple[float, float]] = []
77
+ for child in node:
78
+ if not isinstance(child, list) or not child:
79
+ continue
80
+ kind = child[0]
81
+ if kind == "symbol":
82
+ parts = str(child[1]).rsplit("_", 2)
83
+ if len(parts) == 3 and parts[1].isdigit() and parts[2].isdigit():
84
+ if int(parts[1]) not in {0, unit}:
85
+ continue
86
+ if int(parts[2]) > 1: # alternate (De Morgan) body style
87
+ continue
88
+ pts += _graphics(child, unit)
89
+ elif kind == "rectangle":
90
+ for key in ("start", "end"):
91
+ p = _xy(find(child, key))
92
+ if p:
93
+ pts.append(p)
94
+ elif kind == "circle":
95
+ c, radius = _xy(find(child, "center")), num(value(child, "radius"))
96
+ if c:
97
+ pts += [(c[0] - radius, c[1] - radius), (c[0] + radius, c[1] + radius)]
98
+ elif kind == "arc":
99
+ start, mid, end = (_xy(find(child, k)) for k in ("start", "mid", "end"))
100
+ if start and mid and end:
101
+ pts += _arc_points(start, mid, end)
102
+ elif kind in {"polyline", "bezier"}:
103
+ for p in find_all(find(child, "pts") or [], "xy"):
104
+ pts.append((num(p[1]), num(p[2])))
105
+ elif kind == "pin":
106
+ p = find(child, "at")
107
+ if p and len(p) >= 3:
108
+ pts.append((num(p[1]), num(p[2])))
109
+ return pts
110
+
111
+
112
+ def library_boxes(root: Node) -> dict[str, list[Node]]:
113
+ """``lib_id`` -> its ``(symbol ...)`` definition (base symbol first when it extends one)."""
114
+ library = find(root, "lib_symbols")
115
+ if library is None:
116
+ return {}
117
+ defs = {str(s[1]): s for s in find_all(library, "symbol") if len(s) > 1}
118
+ out: dict[str, list[Node]] = {}
119
+ for name, node in defs.items():
120
+ chain = [node]
121
+ base = value(node, "extends")
122
+ if base:
123
+ parent = defs.get(str(base)) or defs.get(f"{name.split(':')[0]}:{base}")
124
+ if parent is not None:
125
+ chain.append(parent)
126
+ out[name] = chain
127
+ return out
128
+
129
+
130
+ def library_box(chain: list[Node], unit: int) -> Box | None:
131
+ for node in chain:
132
+ pts = _graphics(node, unit)
133
+ if pts:
134
+ xs, ys = [p[0] for p in pts], [p[1] for p in pts]
135
+ return min(xs), min(ys), max(xs), max(ys)
136
+ return None
137
+
138
+
139
+ def place(box: Box, x: float, y: float, angle: float, mirror: str | None) -> Box:
140
+ """Move a library box (y up) to a placed symbol at ``(x, y)`` on the sheet (y down)."""
141
+ cos, sin = math.cos(math.radians(angle)), math.sin(math.radians(angle))
142
+ xs: list[float] = []
143
+ ys: list[float] = []
144
+ for lx, ly in ((box[0], box[1]), (box[0], box[3]), (box[2], box[1]), (box[2], box[3])):
145
+ px, py = lx, -ly
146
+ if mirror == "x":
147
+ py = -py
148
+ elif mirror == "y":
149
+ px = -px
150
+ xs.append(x + px * cos + py * sin)
151
+ ys.append(y - px * sin + py * cos)
152
+ return min(xs), min(ys), max(xs), max(ys)
153
+
154
+
155
+ def schematic_items(path: Path, symbols) -> tuple[list[dict], dict[str, int]]:
156
+ """Click-target boxes for ``symbols`` (from ``read_schematic``) and counts by source."""
157
+ libs: dict[str, list[Node]] = {}
158
+ placed: dict[tuple[str, str], Node] = {}
159
+ seen: set[Path] = set()
160
+
161
+ def visit(file: Path) -> None:
162
+ file = file.resolve()
163
+ if file in seen or not file.is_file():
164
+ return
165
+ seen.add(file)
166
+ root = sexpr.parse(file.read_text(encoding="utf-8"))
167
+ for name, chain in library_boxes(root).items():
168
+ libs.setdefault(name, chain)
169
+ for node in find_all(root, "symbol"):
170
+ lib_id = value(node, "lib_id")
171
+ if lib_id is None:
172
+ continue
173
+ key = (str(value(node, "uuid", "")), str(lib_id))
174
+ placed[key] = node
175
+ for sheet in find_all(root, "sheet"):
176
+ child = prop(sheet, "Sheetfile") or prop(sheet, "Sheet file")
177
+ if child:
178
+ visit(file.parent / child)
179
+
180
+ visit(path)
181
+ counts = {"graphics": 0, "estimated": 0}
182
+ items: list[dict] = []
183
+ for s in symbols:
184
+ if s.reference.startswith("#") or s.is_power:
185
+ continue
186
+ node = placed.get((s.uuid, s.lib_id))
187
+ mirror = None
188
+ if node is not None:
189
+ m = find(node, "mirror")
190
+ mirror = str(m[1]) if m is not None and len(m) > 1 else None
191
+ box = library_box(libs[s.lib_id], s.unit or 1) if s.lib_id in libs else None
192
+ if box is not None:
193
+ x0, y0, x1, y1 = place(box, s.x, s.y, s.angle, mirror)
194
+ counts["graphics"] += 1
195
+ estimated = False
196
+ else:
197
+ hw, hh = estimate_half(s.reference)
198
+ x0, y0, x1, y1 = s.x - hw, s.y - hh, s.x + hw, s.y + hh
199
+ counts["estimated"] += 1
200
+ estimated = True
201
+ items.append(
202
+ {
203
+ "ref": s.reference,
204
+ "value": s.value,
205
+ "x": x0,
206
+ "y": y0,
207
+ "w": x1 - x0,
208
+ "h": y1 - y0,
209
+ "estimated": estimated,
210
+ }
211
+ )
212
+ return items, counts
@@ -0,0 +1,65 @@
1
+ """Update check: compare the running version with the latest GitHub release tag.
2
+
3
+ ``traceforge app --check-update`` asks a URL (default: the GitHub "latest release" API of the
4
+ project; override with ``--update-url`` or ``TRACEFORGE_UPDATE_URL``) for a JSON object with
5
+ ``tag_name`` and, optionally, ``html_url``. Nothing is downloaded or installed. Any network or
6
+ format problem gives ``status: "unavailable"`` instead of an exception, so an offline machine is fine.
7
+ The app never checks on its own; the check runs only when asked.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import re
15
+ import urllib.request
16
+ from typing import Any
17
+
18
+ from traceforge import __version__
19
+
20
+ DEFAULT_URL = "https://api.github.com/repos/ashutosh-rath02/traceforge/releases/latest"
21
+ RELEASES_PAGE = "https://github.com/ashutosh-rath02/traceforge/releases"
22
+
23
+
24
+ def parse_version(text: str) -> tuple[int, ...] | None:
25
+ """``v1.2.3`` / ``1.2`` -> (1, 2, 3); None when there is no leading number. Suffixes like rc1 are ignored."""
26
+ match = re.match(r"\s*[vV]?(\d+(?:\.\d+)*)", text or "")
27
+ if not match:
28
+ return None
29
+ parts = [int(p) for p in match.group(1).split(".")]
30
+ while len(parts) > 1 and parts[-1] == 0:
31
+ parts.pop()
32
+ return tuple(parts)
33
+
34
+
35
+ def check_update(
36
+ url: str | None = None, current: str = __version__, timeout: float = 5.0
37
+ ) -> dict[str, Any]:
38
+ """``{"status": "newer"|"current"|"unavailable", "current", "latest", "url", "message"}``."""
39
+ target = url or os.environ.get("TRACEFORGE_UPDATE_URL") or DEFAULT_URL
40
+ out: dict[str, Any] = {"status": "unavailable", "current": current, "latest": None, "url": None}
41
+ if not target.startswith(("http://", "https://")):
42
+ out["message"] = "the update URL must start with http:// or https://"
43
+ return out
44
+ request = urllib.request.Request(
45
+ target, headers={"Accept": "application/vnd.github+json", "User-Agent": "traceforge"}
46
+ )
47
+ try:
48
+ with urllib.request.urlopen(request, timeout=timeout) as response: # noqa: S310 - scheme checked
49
+ data = json.loads(response.read(1 << 20).decode("utf-8"))
50
+ tag = str(data["tag_name"])
51
+ except Exception as exc: # noqa: BLE001 - offline, DNS, HTTP error, bad JSON: all "unavailable"
52
+ out["message"] = f"could not check for updates ({type(exc).__name__})"
53
+ return out
54
+ latest, running = parse_version(tag), parse_version(current)
55
+ out["latest"] = tag
56
+ out["url"] = str(data.get("html_url") or RELEASES_PAGE)
57
+ if latest is None or running is None:
58
+ out["message"] = f"latest release tag {tag!r} is not a version number"
59
+ elif latest > running:
60
+ out["status"] = "newer"
61
+ out["message"] = f"version {tag} is available (you have {current}): {out['url']}"
62
+ else:
63
+ out["status"] = "current"
64
+ out["message"] = f"up to date ({current})"
65
+ return out
@@ -0,0 +1,67 @@
1
+ """A small local log for troubleshooting, with credentials and content redacted.
2
+
3
+ Written to ``~/.local/share/traceforge/logs/traceforge.log`` (rotated at 2 MB, three
4
+ files kept). Nothing is sent anywhere. Messages are cut to their first line so
5
+ prompts, file contents and tool output do not end up in the log.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import re
12
+ from logging.handlers import RotatingFileHandler
13
+ from pathlib import Path
14
+
15
+ from traceforge.config import data_home
16
+
17
+ _SECRETS = (
18
+ re.compile(r"\btf_[A-Za-z0-9_-]{16,}"),
19
+ re.compile(r"\bsk-(?:ant-)?[A-Za-z0-9_-]{16,}"),
20
+ re.compile(r"(?i)(authorization[\"']?\s*[:=]\s*[\"']?bearer\s+)[^\s\"']+"),
21
+ re.compile(r"(?i)(server_key[\"']?\s*[:=]\s*[\"']?)[^\s\"']+"),
22
+ )
23
+
24
+
25
+ def redact(value: object) -> str:
26
+ text = str(value)
27
+ for pattern in _SECRETS:
28
+ text = pattern.sub(r"\1[REDACTED]" if pattern.groups else "[REDACTED]", text)
29
+ if "\n" in text:
30
+ first, *rest = text.splitlines()
31
+ text = f"{first} … [{len(rest)} lines omitted]"
32
+ return text[:2_000]
33
+
34
+
35
+ class RedactingFormatter(logging.Formatter):
36
+ def format(self, record: logging.LogRecord) -> str:
37
+ copy = logging.makeLogRecord(record.__dict__.copy())
38
+ copy.msg = redact(copy.getMessage())
39
+ copy.args = None
40
+ copy.exc_info = None
41
+ copy.exc_text = None
42
+ return super().format(copy)
43
+
44
+
45
+ def log_path() -> Path:
46
+ return data_home() / "logs" / "traceforge.log"
47
+
48
+
49
+ def configure(level: int = logging.INFO) -> Path | None:
50
+ """Attach the redacting file handler to the ``traceforge`` logger (once)."""
51
+ logger = logging.getLogger("traceforge")
52
+ if any(getattr(handler, "_traceforge", False) for handler in logger.handlers):
53
+ return log_path()
54
+ path = log_path()
55
+ try:
56
+ path.parent.mkdir(parents=True, exist_ok=True)
57
+ handler = RotatingFileHandler(
58
+ path, maxBytes=2 * 1024 * 1024, backupCount=3, encoding="utf-8"
59
+ )
60
+ except OSError:
61
+ return None
62
+ handler._traceforge = True # type: ignore[attr-defined]
63
+ handler.setFormatter(RedactingFormatter("%(asctime)s %(levelname)s %(name)s %(message)s"))
64
+ logger.addHandler(handler)
65
+ logger.setLevel(level)
66
+ logger.propagate = False
67
+ return path
traceforge/errata.py ADDED
@@ -0,0 +1,219 @@
1
+ """Errata hunt: candidate errata items from datasheet and errata documents, with citations.
2
+
3
+ Extraction is heuristic (keyword and heading based): it proposes candidates with page and section
4
+ references for a human or the agent to confirm; it does not prove an erratum applies to a design.
5
+ Items whose source could not be retrieved are marked ``verified: false``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from traceforge.parts.datasheet import fetch_datasheet
15
+ from traceforge.parts.net import Net, ProviderError
16
+
17
+ # A numbered item heading ("2.1.3 I2C hangs", "ES0394 2.4.1 ...", "Erratum 12") starts a block.
18
+ _HEADING = re.compile(
19
+ r"^\s*(?P<id>(?:ES|ER|ERR|SiliconErrata|Erratum|Errata|Issue|Problem)\s*[-#]?\s*\d+[\w.]*"
20
+ r"|\d+(?:\.\d+){1,3})\s+(?P<title>[A-Z][^\n]{8,120})$",
21
+ re.M,
22
+ )
23
+ _TRIGGER = re.compile(
24
+ r"\b(errata|erratum|silicon (?:bug|limitation|issue)|workaround|work-around|limitation|"
25
+ r"known issue|does not work|may (?:not|fail|hang|lock)|can (?:fail|hang|lock|damage)|"
26
+ r"not (?:supported|functional|recommended)|do not|must not|never)\b",
27
+ re.I,
28
+ )
29
+ _SEVERE = re.compile(
30
+ r"damage|destroy|latch-?up|overheat|permanent|short circuit|over-?voltage|brown-?out|"
31
+ r"lock(?:s|ed)? up|bricks?|data (?:loss|corruption)|no workaround",
32
+ re.I,
33
+ )
34
+ _MODERATE = re.compile(
35
+ r"hang|stall|incorrect|wrong|fails?|corrupt|glitch|spurious|missed|not (?:work|function)",
36
+ re.I,
37
+ )
38
+ _WORKAROUND = re.compile(r"work-?around", re.I)
39
+
40
+
41
+ def severity_of(text: str) -> str:
42
+ if _SEVERE.search(text):
43
+ return (
44
+ "P0"
45
+ if re.search(r"damage|destroy|latch-?up|permanent|no workaround", text, re.I)
46
+ else "P1"
47
+ )
48
+ if _MODERATE.search(text):
49
+ return "P2" if _WORKAROUND.search(text) else "P1"
50
+ return "P3"
51
+
52
+
53
+ def _norm(text: str) -> set[str]:
54
+ return {w for w in re.findall(r"[a-z0-9]{3,}", text.lower())}
55
+
56
+
57
+ def _similar(a: set[str], b: set[str]) -> bool:
58
+ return bool(a and b) and len(a & b) / len(a | b) >= 0.6
59
+
60
+
61
+ def extract_items(pages: list[str], source: str, *, doc_kind: str = "datasheet") -> list[dict]:
62
+ """Candidate errata items from the page texts of one document."""
63
+ items: list[dict] = []
64
+ for number, page in enumerate(pages, start=1):
65
+ headings = list(_HEADING.finditer(page))
66
+ blocks: list[tuple[str, str, str]] = []
67
+ for index, match in enumerate(headings):
68
+ end = headings[index + 1].start() if index + 1 < len(headings) else len(page)
69
+ blocks.append(
70
+ (match.group("id").strip(), match.group("title").strip(), page[match.start() : end])
71
+ )
72
+ if not blocks: # no headings: paragraphs containing trigger words
73
+ for paragraph in re.split(r"\n\s*\n", page):
74
+ if _TRIGGER.search(paragraph) and re.search(
75
+ r"errat|silicon|workaround|limitation", paragraph, re.I
76
+ ):
77
+ first = " ".join(paragraph.split())[:100]
78
+ blocks.append(("", first, paragraph))
79
+ for ident, title, body in blocks:
80
+ body_clean = " ".join(body.split())
81
+ if doc_kind == "datasheet" and not _TRIGGER.search(body_clean):
82
+ continue
83
+ if doc_kind == "errata" and not (_TRIGGER.search(body_clean) or ident):
84
+ continue
85
+ items.append(
86
+ {
87
+ "id": ident,
88
+ "title": title,
89
+ "summary": body_clean[:500],
90
+ "severity": severity_of(body_clean),
91
+ "has_workaround": bool(_WORKAROUND.search(body_clean)),
92
+ "source": source,
93
+ "doc_kind": doc_kind,
94
+ "page": number,
95
+ "section": ident if re.match(r"\d", ident) else "",
96
+ "verified": True,
97
+ }
98
+ )
99
+ return items
100
+
101
+
102
+ def dedupe(items: list[dict]) -> list[dict]:
103
+ """Merge items describing the same issue; the merged item lists every citation."""
104
+ kept: list[dict] = []
105
+ for item in items:
106
+ words = _norm(item["title"] + " " + item["summary"][:200])
107
+ for existing in kept:
108
+ if _similar(words, existing["_words"]):
109
+ existing["citations"].append(_citation(item))
110
+ if item["severity"] < existing["severity"]:
111
+ existing["severity"] = item["severity"]
112
+ existing["verified"] = existing["verified"] or item["verified"]
113
+ break
114
+ else:
115
+ kept.append({**item, "_words": words, "citations": [_citation(item)]})
116
+ for item in kept:
117
+ item.pop("_words")
118
+ return kept
119
+
120
+
121
+ def _citation(item: dict) -> dict:
122
+ return {"source": item["source"], "page": item.get("page"), "section": item.get("section", "")}
123
+
124
+
125
+ def rank(items: list[dict]) -> list[dict]:
126
+ """Severity first, then verified, then number of independent citations."""
127
+ return sorted(
128
+ items,
129
+ key=lambda i: (
130
+ i["severity"],
131
+ not i["verified"],
132
+ -len(i.get("citations", [])),
133
+ i.get("page") or 0,
134
+ ),
135
+ )
136
+
137
+
138
+ def hunt(
139
+ sources: list[dict[str, Any]],
140
+ folder: Path,
141
+ *,
142
+ net: Net | None = None,
143
+ ) -> dict[str, Any]:
144
+ """``sources``: dicts with ``url`` or ``path`` and ``kind`` (datasheet|errata) plus optional ``title``.
145
+
146
+ A source that cannot be fetched yields an unverified placeholder item pointing at it."""
147
+ collected: list[dict] = []
148
+ fetched: list[dict] = []
149
+ for src in sources:
150
+ kind = src.get("kind", "datasheet")
151
+ label = src.get("url") or str(src.get("path"))
152
+ try:
153
+ _, pages, _ = fetch_datasheet(
154
+ folder,
155
+ url=src.get("url"),
156
+ local=Path(src["path"]) if src.get("path") else None,
157
+ net=net,
158
+ )
159
+ except Exception as exc: # noqa: BLE001 - network and PDF failures are all "unretrievable"
160
+ fetched.append(
161
+ {"source": label, "kind": kind, "retrieved": False, "error": str(exc)[:200]}
162
+ )
163
+ collected.append(
164
+ {
165
+ "id": "",
166
+ "title": src.get("title") or f"{kind} listed but not retrievable",
167
+ "summary": src.get("snippet", "")[:500],
168
+ "severity": severity_of(src.get("snippet", "")) if src.get("snippet") else "P3",
169
+ "has_workaround": False,
170
+ "source": label,
171
+ "doc_kind": kind,
172
+ "page": None,
173
+ "section": "",
174
+ "verified": False,
175
+ }
176
+ )
177
+ continue
178
+ fetched.append({"source": label, "kind": kind, "retrieved": True, "pages": len(pages)})
179
+ collected += extract_items(pages, label, doc_kind=kind)
180
+ ranked = rank(dedupe(collected))
181
+ return {
182
+ "items": ranked,
183
+ "sources": fetched,
184
+ "unverified": sum(1 for i in ranked if not i["verified"]),
185
+ "note": (
186
+ "Candidates extracted heuristically from the cited pages; confirm each against the "
187
+ "cited page and the silicon revision actually used. Items marked verified=false have "
188
+ "no retrievable source text."
189
+ ),
190
+ }
191
+
192
+
193
+ def find_sources(part: str, datasheet_url: str | None, search: Any) -> list[dict]:
194
+ """Datasheet plus errata documents found by web search (``search(query) -> WebAnswer``)."""
195
+ sources: list[dict] = []
196
+ if datasheet_url:
197
+ sources.append({"url": datasheet_url, "kind": "datasheet", "title": f"{part} datasheet"})
198
+ seen = {datasheet_url}
199
+ for query in (f"{part} errata", f"{part} silicon errata sheet"):
200
+ try:
201
+ answer = search(query)
202
+ except (ProviderError, OSError):
203
+ continue
204
+ for result in answer.results:
205
+ haystack = f"{result.title} {result.url} {result.snippet}".lower()
206
+ if result.url in seen or "errat" not in haystack:
207
+ continue
208
+ seen.add(result.url)
209
+ sources.append(
210
+ {
211
+ "url": result.url,
212
+ "kind": "errata",
213
+ "title": result.title,
214
+ "snippet": result.snippet,
215
+ }
216
+ )
217
+ if len(sources) >= 5:
218
+ break
219
+ return sources[:5]
traceforge/fab.py ADDED
@@ -0,0 +1,108 @@
1
+ """Manufacturing capability profiles for common PCB fabs (standard 2/4-layer service)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict, dataclass
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class FabProfile:
10
+ name: str
11
+ min_track: float
12
+ min_clearance: float
13
+ min_via_diameter: float
14
+ min_drill: float
15
+ min_annular_ring: float
16
+ min_copper_edge: float
17
+ min_silk_text_height: float
18
+ min_silk_line: float
19
+ default_track: float
20
+ default_clearance: float
21
+ default_via_diameter: float
22
+ default_via_drill: float
23
+ max_board_mm: tuple[float, float]
24
+ notes: str = ""
25
+
26
+ def to_dict(self) -> dict:
27
+ return asdict(self)
28
+
29
+
30
+ # Values are conservative standard-service capabilities; check your fab's current
31
+ # capability page before ordering and override in .traceforge/config.yaml if needed.
32
+ FABS: dict[str, FabProfile] = {
33
+ "jlcpcb": FabProfile(
34
+ name="jlcpcb",
35
+ min_track=0.127,
36
+ min_clearance=0.127,
37
+ min_via_diameter=0.45,
38
+ min_drill=0.3,
39
+ min_annular_ring=0.13,
40
+ min_copper_edge=0.3,
41
+ min_silk_text_height=1.0,
42
+ min_silk_line=0.153,
43
+ default_track=0.25,
44
+ default_clearance=0.2,
45
+ default_via_diameter=0.6,
46
+ default_via_drill=0.3,
47
+ max_board_mm=(500.0, 400.0),
48
+ notes="JLCPCB standard 2-layer, 1 oz copper",
49
+ ),
50
+ "pcbway": FabProfile(
51
+ name="pcbway",
52
+ min_track=0.127,
53
+ min_clearance=0.127,
54
+ min_via_diameter=0.45,
55
+ min_drill=0.3,
56
+ min_annular_ring=0.15,
57
+ min_copper_edge=0.3,
58
+ min_silk_text_height=0.8,
59
+ min_silk_line=0.15,
60
+ default_track=0.25,
61
+ default_clearance=0.2,
62
+ default_via_diameter=0.6,
63
+ default_via_drill=0.3,
64
+ max_board_mm=(500.0, 1100.0),
65
+ notes="PCBWay standard service",
66
+ ),
67
+ "oshpark": FabProfile(
68
+ name="oshpark",
69
+ min_track=0.152,
70
+ min_clearance=0.152,
71
+ min_via_diameter=0.508,
72
+ min_drill=0.254,
73
+ min_annular_ring=0.127,
74
+ min_copper_edge=0.381,
75
+ min_silk_text_height=0.8,
76
+ min_silk_line=0.127,
77
+ default_track=0.25,
78
+ default_clearance=0.2,
79
+ default_via_diameter=0.6,
80
+ default_via_drill=0.3,
81
+ max_board_mm=(406.0, 406.0),
82
+ notes="OSH Park 2-layer prototype service",
83
+ ),
84
+ "generic": FabProfile(
85
+ name="generic",
86
+ min_track=0.15,
87
+ min_clearance=0.15,
88
+ min_via_diameter=0.6,
89
+ min_drill=0.3,
90
+ min_annular_ring=0.15,
91
+ min_copper_edge=0.5,
92
+ min_silk_text_height=1.0,
93
+ min_silk_line=0.15,
94
+ default_track=0.25,
95
+ default_clearance=0.2,
96
+ default_via_diameter=0.6,
97
+ default_via_drill=0.3,
98
+ max_board_mm=(400.0, 400.0),
99
+ notes="Conservative limits most fabs can build",
100
+ ),
101
+ }
102
+
103
+
104
+ def get_fab(name: str | None) -> FabProfile:
105
+ key = (name or "jlcpcb").lower()
106
+ if key not in FABS:
107
+ raise ValueError(f"unknown fab {name!r}; choose from {sorted(FABS)}")
108
+ return FABS[key]