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,705 @@
1
+ """Sourcing brief: one part or a whole BOM as a cited Markdown and JSON document.
2
+
3
+ Sections per part: identity, suppliers and stock (each cited), HS code with the
4
+ rule that matched, authorised distributors by region, single-source risk, volume
5
+ price bands (measured from price breaks, extrapolated beyond them with the
6
+ assumptions printed), and a landed-cost estimate whose arithmetic is shown step
7
+ by step. HS codes and duty rates come from editable YAML tables
8
+ (``parts/data``); they are a guide to confirm with the customs broker, and a
9
+ destination with no table row gets the goods cost only, never a guessed rate.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import math
15
+ import re
16
+ import time
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ import yaml
22
+
23
+ from traceforge.parts.alternates import AlternatesResult, find_alternates
24
+ from traceforge.parts.catalog import Catalog, default_catalog
25
+ from traceforge.parts.fx import FxTable
26
+ from traceforge.parts.model import PartInfo
27
+ from traceforge.parts.net import Offline
28
+ from traceforge.parts.supply import (
29
+ PartSourcing,
30
+ offer_label,
31
+ quote,
32
+ source_part,
33
+ )
34
+
35
+ DATA = Path(__file__).parent / "data"
36
+ DEFAULT_BAND_QTYS = (1, 10, 100, 1000, 10000, 100000)
37
+ DEFAULT_FREIGHT_USD = 25.0 # one express shipment; editable per call
38
+ DEFAULT_INSURANCE_PCT = 0.5 # of goods value; editable per call
39
+
40
+ # Authorised distributors by region: general knowledge of who sells in which region, to be
41
+ # confirmed on the manufacturer's own "authorised distributor" page. "Seen" in a brief means the
42
+ # supplier's API returned an offer in this run; "also typically" is NOT checked.
43
+ DISTRIBUTORS: dict[str, list[str]] = {
44
+ "North America": [
45
+ "DigiKey",
46
+ "Mouser",
47
+ "Arrow",
48
+ "Newark",
49
+ "Avnet",
50
+ "Future Electronics",
51
+ "Verical",
52
+ ],
53
+ "Europe": [
54
+ "DigiKey",
55
+ "Mouser",
56
+ "Farnell",
57
+ "RS Components",
58
+ "TME",
59
+ "Rutronik",
60
+ "Arrow",
61
+ "Distrelec",
62
+ ],
63
+ "India": [
64
+ "DigiKey",
65
+ "Mouser",
66
+ "Arrow",
67
+ "Avnet",
68
+ "Rutronik",
69
+ "element14 India",
70
+ "Robu / Ktron (hobby)",
71
+ ],
72
+ "China / APAC": ["LCSC", "JLCPCB parts", "Arrow Asia", "Digi-Key", "Mouser", "element14 APAC"],
73
+ }
74
+ _REGION_BY_COUNTRY = {
75
+ "US": "North America",
76
+ "CA": "North America",
77
+ "MX": "North America",
78
+ "IN": "India",
79
+ "CN": "China / APAC",
80
+ "HK": "China / APAC",
81
+ "SG": "China / APAC",
82
+ "JP": "China / APAC",
83
+ "KR": "China / APAC",
84
+ "TW": "China / APAC",
85
+ "AU": "China / APAC",
86
+ "DE": "Europe",
87
+ "FR": "Europe",
88
+ "GB": "Europe",
89
+ "UK": "Europe",
90
+ "NL": "Europe",
91
+ "IT": "Europe",
92
+ "ES": "Europe",
93
+ "SE": "Europe",
94
+ "PL": "Europe",
95
+ "CH": "Europe",
96
+ }
97
+
98
+
99
+ def load_yaml(path: str | Path | None, default: str) -> dict[str, Any]:
100
+ target = Path(path) if path else DATA / default
101
+ return yaml.safe_load(target.read_text(encoding="utf-8")) or {}
102
+
103
+
104
+ # ------------------------------------------------------------------------- HS
105
+
106
+
107
+ @dataclass
108
+ class HsResult:
109
+ code: str
110
+ name: str
111
+ why: str
112
+ matched: str
113
+ supplier_declared: list[str] = field(default_factory=list) # e.g. "DigiKey HTSUS 8542.31.0001"
114
+ agrees: bool | None = None
115
+
116
+ def to_dict(self) -> dict[str, Any]:
117
+ return self.__dict__.copy()
118
+
119
+
120
+ def classify_hs(part: PartInfo, table: dict[str, Any] | None = None) -> HsResult:
121
+ table = table or load_yaml(None, "hs_codes.yaml")
122
+ text = (
123
+ f" {part.category} {part.description} {part.mpn} {part.attributes.get('Type', '')} ".lower()
124
+ )
125
+ result = None
126
+ for rule in table.get("rules", []):
127
+
128
+ def has(word: str, text: str = text) -> bool:
129
+ return re.search(r"(?<![a-z0-9])" + re.escape(word.lower().strip()), text) is not None
130
+
131
+ if any(has(w) for w in rule.get("any", [])) and not any(
132
+ has(w) for w in rule.get("not", [])
133
+ ):
134
+ matched = next(w for w in rule["any"] if has(w))
135
+ result = HsResult(
136
+ rule["hs"],
137
+ rule["name"],
138
+ " ".join(str(rule["why"]).split()),
139
+ f"text contains {matched!r}",
140
+ )
141
+ break
142
+ if result is None:
143
+ fb = table.get("fallback", {})
144
+ result = HsResult(
145
+ fb.get("hs", ""), fb.get("name", "unclassified"), fb.get("why", ""), "no rule matched"
146
+ )
147
+ declared = []
148
+ for key, value in part.attributes.items():
149
+ if key in {"HTSUS", "Compliance USHTS", "Compliance TARIC", "Compliance CNHTS"}:
150
+ declared.append(f"{key.replace('Compliance ', '')} {value}")
151
+ result.supplier_declared = declared
152
+ digits = result.code.replace(".", "")
153
+ if declared and digits:
154
+ result.agrees = any(
155
+ re.sub(r"\D", "", d.split()[-1]).startswith(digits[:6]) for d in declared
156
+ )
157
+ return result
158
+
159
+
160
+ # ------------------------------------------------------------------ price bands
161
+
162
+
163
+ def _log_slope(breaks: list[tuple[int, float]]) -> float:
164
+ """Price-vs-quantity exponent from the last two breaks, clamped to a plausible discount."""
165
+ if len(breaks) < 2:
166
+ return 0.0
167
+ (q1, p1), (q2, p2) = breaks[-2], breaks[-1]
168
+ if q2 <= q1 or p1 <= 0 or p2 <= 0:
169
+ return 0.0
170
+ return max(-0.2, min(0.0, math.log(p2 / p1) / math.log(q2 / q1)))
171
+
172
+
173
+ def price_bands(s: PartSourcing, qtys: tuple[int, ...]) -> tuple[list[dict[str, Any]], list[str]]:
174
+ """Unit price per target volume: measured where a break covers it, a band beyond."""
175
+ assumptions = [
176
+ "Measured prices come straight from the suppliers' price breaks (cheapest eligible offer).",
177
+ "Beyond the highest published break the band runs from 'flat' (last break price, i.e. no "
178
+ "further discount) to 'trend' (log-log slope of the last two breaks, clamped to between "
179
+ "0 and -0.2, applied for at most 10x the last break quantity). Treat as indicative: a quote is needed.",
180
+ ]
181
+ priced = [o for o in s.offers if o.price_breaks]
182
+ rows = []
183
+ # reference offer for extrapolation: lowest converted price at its own last break
184
+ ref = None
185
+ ref_unit = math.inf
186
+ for o in priced:
187
+ q = quote(o, o.price_breaks[-1].quantity, s.fx, s.currency)
188
+ if q.unit_price is not None and q.unit_price < ref_unit:
189
+ ref, ref_unit = o, q.unit_price
190
+ for qty in qtys:
191
+ best = s.best_at(qty)
192
+ top_break = max((b.quantity for o in priced for b in o.price_breaks), default=0)
193
+ if best is not None and (qty <= top_break or not ref):
194
+ rows.append(
195
+ {
196
+ "quantity": qty,
197
+ "kind": "measured",
198
+ "unit_price": best.unit_price,
199
+ "supplier": best.label,
200
+ "note": best.note,
201
+ }
202
+ )
203
+ continue
204
+ if ref is None:
205
+ rows.append({"quantity": qty, "kind": "none", "note": "no priced offer"})
206
+ continue
207
+ brk = sorted(
208
+ (b.quantity, s.fx.convert(b.unit_price, b.currency, s.currency))
209
+ for b in ref.price_breaks
210
+ )
211
+ last_q, last_p = brk[-1]
212
+ slope = _log_slope(brk)
213
+ reach = min(qty, last_q * 10)
214
+ trend = last_p * (reach / last_q) ** slope
215
+ stock = ref.stock
216
+ note = f"above the highest break ({last_q}) of {offer_label(ref)}"
217
+ if stock is not None and qty > stock:
218
+ note += f"; listed stock {stock} is below {qty}, so lead time and allocation matter"
219
+ if qty > last_q * 10:
220
+ note += "; trend capped at 10x the last break"
221
+ rows.append(
222
+ {
223
+ "quantity": qty,
224
+ "kind": "extrapolated",
225
+ "unit_price_low": trend,
226
+ "unit_price_high": last_p,
227
+ "supplier": offer_label(ref),
228
+ "slope": round(slope, 4),
229
+ "note": note,
230
+ }
231
+ )
232
+ return rows, assumptions
233
+
234
+
235
+ # ------------------------------------------------------------------ landed cost
236
+
237
+
238
+ def landed_cost(
239
+ goods: float,
240
+ currency: str,
241
+ destination: str,
242
+ hs_code: str,
243
+ fx: FxTable,
244
+ duty_table: dict[str, Any] | None = None,
245
+ freight_usd: float = DEFAULT_FREIGHT_USD,
246
+ insurance_pct: float = DEFAULT_INSURANCE_PCT,
247
+ quantity: int | None = None,
248
+ ) -> dict[str, Any]:
249
+ """Landed cost with the arithmetic as readable steps. Rates are never guessed."""
250
+ duty_table = duty_table or load_yaml(None, "duty_rates.yaml")
251
+ dest = (duty_table.get("destinations") or {}).get(destination.upper())
252
+ steps: list[str] = []
253
+ out: dict[str, Any] = {"destination": destination.upper(), "currency": currency, "steps": steps}
254
+ goods = round(goods, 2)
255
+ freight = round(fx.convert(freight_usd, "USD", currency), 2)
256
+ insurance = round(goods * insurance_pct / 100, 2)
257
+ cif = round(
258
+ goods + freight + insurance, 2
259
+ ) # every step rounded to 2 decimals, as a customs entry is
260
+ steps.append(f"Goods: {goods:.2f} {currency}")
261
+ steps.append(
262
+ f"Freight (assumed flat {freight_usd:.2f} USD = {freight:.2f} {currency}, {fx.describe()}): {freight:.2f}"
263
+ )
264
+ steps.append(
265
+ f"Insurance (assumed {insurance_pct:g}% of goods): {goods:.2f} x {insurance_pct:g}% = {insurance:.2f}"
266
+ )
267
+ steps.append(f"Customs value (CIF) = {goods:.2f} + {freight:.2f} + {insurance:.2f} = {cif:.2f}")
268
+ out.update(
269
+ goods=round(goods, 4),
270
+ freight=round(freight, 4),
271
+ insurance=round(insurance, 4),
272
+ cif=round(cif, 4),
273
+ )
274
+ if dest is None or not hs_code:
275
+ reason = (
276
+ "no HS code"
277
+ if not hs_code
278
+ else f"no duty data for {destination.upper()} in the duty table"
279
+ )
280
+ steps.append(
281
+ f"Duty and taxes: not estimated ({reason}). Add the country to duty_rates.yaml."
282
+ )
283
+ out.update(duty=None, taxes={}, total=round(cif, 4), complete=False, verified=False)
284
+ out["per_unit"] = round(cif / quantity, 6) if quantity else None
285
+ return out
286
+ digits = hs_code.replace(".", "")
287
+ prefix = max(
288
+ (p for p in dest.get("duty", {}) if digits.startswith(str(p))), key=len, default=None
289
+ )
290
+ if prefix is None:
291
+ steps.append(f"Duty: no rate for HS {hs_code} in the {dest['name']} table; not estimated.")
292
+ out.update(duty=None, taxes={}, total=round(cif, 4), complete=False, verified=False)
293
+ out["per_unit"] = round(cif / quantity, 6) if quantity else None
294
+ return out
295
+ rate = dest["duty"][prefix]
296
+ amounts = {"cif": cif}
297
+ duty = round(cif * rate["pct"] / 100, 2)
298
+ amounts["duty"] = duty
299
+ label = dest.get("duty_label", "Duty")
300
+ steps.append(
301
+ f"{label} on HS {prefix}* ({rate.get('note', '')}): {cif:.2f} x {rate['pct']:g}% = {duty:.2f}"
302
+ )
303
+ total = round(cif + duty, 2)
304
+ taxes: dict[str, float] = {}
305
+ for tax in dest.get("taxes", []):
306
+ base = sum(amounts[name] for name in tax["of"])
307
+ value = round(base * tax["pct"] / 100, 2)
308
+ amounts[tax["name"]] = value
309
+ taxes[tax["name"]] = round(value, 4)
310
+ total = round(total + value, 2)
311
+ steps.append(
312
+ f"{tax['name']}: ({' + '.join(f'{n} {amounts[n]:.2f}' for n in tax['of'])}) = {base:.2f} x {tax['pct']:g}% = {value:.2f} [{tax.get('note', '')}]"
313
+ )
314
+ steps.append(
315
+ f"Landed total = {cif:.2f} + {duty:.2f}"
316
+ + "".join(f" + {v:.2f}" for v in taxes.values())
317
+ + f" = {total:.2f} {currency}"
318
+ )
319
+ per_unit = total / quantity if quantity else None
320
+ if per_unit is not None:
321
+ steps.append(f"Per unit = {total:.2f} / {quantity} = {per_unit:.4f} {currency}")
322
+ verified = bool(dest.get("verified"))
323
+ note = (
324
+ ""
325
+ if verified
326
+ else f"Rates for {dest['name']} are UNVERIFIED example values (table dated {dest.get('as_of')}); confirm with the customs broker."
327
+ )
328
+ if note:
329
+ steps.append(note)
330
+ out.update(
331
+ duty=round(duty, 4),
332
+ duty_rate_pct=rate["pct"],
333
+ duty_label=label,
334
+ taxes=taxes,
335
+ total=round(total, 4),
336
+ per_unit=round(per_unit, 6) if per_unit else None,
337
+ complete=True,
338
+ verified=verified,
339
+ table_as_of=dest.get("as_of"),
340
+ )
341
+ return out
342
+
343
+
344
+ # ------------------------------------------------------------------------ risk
345
+
346
+
347
+ def single_source_risk(
348
+ part: PartInfo, s: PartSourcing, alts: AlternatesResult | None, qty: int
349
+ ) -> dict[str, Any]:
350
+ makers = {part.manufacturer.lower()} - {""}
351
+ seconds = []
352
+ if alts:
353
+ for a in alts.alternates:
354
+ if (
355
+ a.verdict in {"equivalent", "compatible"}
356
+ and a.part.manufacturer.lower() not in makers
357
+ ):
358
+ seconds.append(a.part.mpn)
359
+ suggestions = [a.part.mpn for a in alts.alternates if a.verdict == "suggestion"]
360
+ else:
361
+ suggestions = []
362
+ distributors = {o.supplier for o in s.offers if o.authorised is not False}
363
+ reasons = []
364
+ score = 0
365
+ if not seconds:
366
+ score += 2
367
+ reasons.append("no verified drop-in from another manufacturer was found")
368
+ elif len(seconds) == 1:
369
+ score += 1
370
+ reasons.append("only one verified second source")
371
+ if len(distributors) < 2:
372
+ score += 1
373
+ reasons.append(f"offered by {len(distributors)} supplier(s) in this run")
374
+ if part.lifecycle in {"nrnd", "last_time_buy", "obsolete", "discontinued"}:
375
+ score += 2
376
+ reasons.append(f"lifecycle {part.lifecycle}")
377
+ stocks = [o.stock for o in s.offers if o.stock is not None]
378
+ if stocks and sum(stocks) < qty * 3:
379
+ score += 1
380
+ reasons.append(f"total listed stock {sum(stocks)} is under 3x the target quantity {qty}")
381
+ level = "high" if score >= 3 else ("medium" if score >= 1 else "low")
382
+ return {
383
+ "level": level,
384
+ "manufacturer": part.manufacturer,
385
+ "second_sources_other_manufacturers": seconds,
386
+ "pin_compatible_suggestions_unverified": suggestions,
387
+ "suppliers_seen": sorted(distributors),
388
+ "reasons": reasons or ["multiple sources and verified second sources found"],
389
+ "method": "heuristic: second sources from the alternates tool (parametric match for passives; "
390
+ "LCSC-listed or family-table suggestions are NOT counted as verified), supplier count, "
391
+ "lifecycle and stock cover",
392
+ }
393
+
394
+
395
+ # ----------------------------------------------------------------------- brief
396
+
397
+
398
+ @dataclass
399
+ class PartBrief:
400
+ query: str
401
+ sourcing: PartSourcing
402
+ hs: HsResult | None
403
+ alternates: AlternatesResult | None
404
+ risk: dict[str, Any] | None
405
+ bands: list[dict[str, Any]]
406
+ band_assumptions: list[str]
407
+ landed: dict[str, Any] | None
408
+ landed_qty: int
409
+ citations: list[dict[str, str]]
410
+ distributors: dict[str, Any]
411
+ generated: str
412
+
413
+ def to_dict(self) -> dict[str, Any]:
414
+ s = self.sourcing.to_dict()
415
+ return {
416
+ "generated_utc": self.generated,
417
+ "query": self.query,
418
+ "part": s["part"],
419
+ "offers": s["offers"],
420
+ "recommended": s["recommended"],
421
+ "fx": s["fx"],
422
+ "hs": self.hs.to_dict() if self.hs else None,
423
+ "authorised_distributors": self.distributors,
424
+ "single_source_risk": self.risk,
425
+ "alternates": self.alternates.to_dict() if self.alternates else None,
426
+ "price_bands": {"rows": self.bands, "assumptions": self.band_assumptions},
427
+ "landed_cost": {"quantity": self.landed_qty, **(self.landed or {})},
428
+ "citations": self.citations,
429
+ "notes": s["notes"],
430
+ "disclaimer": "HS codes and duty rates are a guide, not a ruling; confirm with the customs broker.",
431
+ }
432
+
433
+ def to_markdown(self) -> str:
434
+ s = self.sourcing
435
+ p = s.part
436
+ cur = s.currency
437
+ out = [f"# Sourcing brief: {p.mpn if p and p.mpn else self.query}", ""]
438
+ out.append(f"Generated {self.generated} UTC. Prices in {cur} ({s.fx.describe()}).")
439
+ out.append("")
440
+ if p:
441
+ out.append(f"**{p.manufacturer}** {p.mpn} - {p.description} ")
442
+ out.append(
443
+ f"Package {p.package or '?'}; lifecycle {p.lifecycle or 'unknown'}; LCSC {p.lcsc or '-'} {p.library_type or ''}."
444
+ )
445
+ else:
446
+ out.append("Part not found in any catalogue. " + " ".join(s.notes))
447
+ out += ["", "## Suppliers and stock", ""]
448
+ out.append("| supplier | sku | stock | MOQ | lead | @1 | @100 | @1000 | cite |")
449
+ out.append("|---|---|---|---|---|---|---|---|---|")
450
+ for o in s.offers:
451
+ cells = []
452
+ for q in (1, 100, 1000):
453
+ qt = quote(o, q, s.fx, cur)
454
+ cells.append("-" if qt.unit_price is None else f"{qt.unit_price:.4f}")
455
+ cite = next((c["n"] for c in self.citations if c["label"] == offer_label(o)), "")
456
+ out.append(
457
+ f"| {offer_label(o)} | {o.sku or '-'} | {'-' if o.stock is None else o.stock} | {o.moq or 1} | {str(o.lead_time_days) + ' d' if o.lead_time_days else '-'} | "
458
+ + " | ".join(cells)
459
+ + f" | [{cite}] |"
460
+ )
461
+ rec = s.to_dict()["recommended"]
462
+ out.append("")
463
+ out.append(
464
+ f"Recommended at {rec['quantity']} pcs: **{rec['supplier'] or 'none'}** ({rec['reason']})."
465
+ )
466
+ out += ["", "## HS code (guide)", ""]
467
+ if self.hs and self.hs.code:
468
+ out.append(f"**{self.hs.code}** - {self.hs.name}. ")
469
+ out.append(f"Rationale: {self.hs.why} Matched because {self.hs.matched}. ")
470
+ if self.hs.supplier_declared:
471
+ agree = {True: "agrees with", False: "DIFFERS from", None: "not comparable to"}[
472
+ self.hs.agrees
473
+ ]
474
+ out.append(
475
+ f"Supplier-declared: {'; '.join(self.hs.supplier_declared)} ({agree} the guide above) [cited supplier data]. "
476
+ )
477
+ else:
478
+ out.append("No HS code rule matched; classify with the customs broker. ")
479
+ out.append("*A guide only - confirm with the customs broker before declaring.*")
480
+ out += ["", "## Authorised distributors by region", ""]
481
+ d = self.distributors
482
+ out.append(
483
+ "Seen in this run (the API returned an offer; authorised where the API says so): "
484
+ + (", ".join(d["seen"]) or "none")
485
+ + "."
486
+ )
487
+ out.append("")
488
+ for region, names in d["typical_by_region"].items():
489
+ out.append(f"- {region}: {', '.join(names)}")
490
+ out.append(
491
+ "\nThe regional list is general knowledge, not checked against this part; confirm on the manufacturer's authorised-distributor page."
492
+ )
493
+ if self.risk:
494
+ r = self.risk
495
+ out += [
496
+ "",
497
+ "## Single-source risk",
498
+ "",
499
+ f"**{r['level'].upper()}** - " + "; ".join(r["reasons"]) + ".",
500
+ ]
501
+ out.append(
502
+ f"Manufacturer: {r['manufacturer'] or '?'}; verified second sources from other manufacturers: {', '.join(r['second_sources_other_manufacturers']) or 'none'}."
503
+ )
504
+ if r["pin_compatible_suggestions_unverified"]:
505
+ out.append(
506
+ f"Unverified pin-compatible suggestions: {', '.join(r['pin_compatible_suggestions_unverified'])}."
507
+ )
508
+ out += ["", "## Volume price bands", ""]
509
+ out.append("| quantity | unit price | basis |")
510
+ out.append("|---|---|---|")
511
+ for row in self.bands:
512
+ if row["kind"] == "measured":
513
+ out.append(
514
+ f"| {row['quantity']} | {row['unit_price']:.4f} | measured, {row['supplier']} |"
515
+ )
516
+ elif row["kind"] == "extrapolated":
517
+ out.append(
518
+ f"| {row['quantity']} | {row['unit_price_low']:.4f} - {row['unit_price_high']:.4f} | extrapolated: {row['note']} |"
519
+ )
520
+ else:
521
+ out.append(f"| {row['quantity']} | - | {row['note']} |")
522
+ out.append("")
523
+ out += [f"- {a}" for a in self.band_assumptions]
524
+ out += [
525
+ "",
526
+ f"## Landed cost estimate ({self.landed_qty} pcs to {s.destination or '?'})",
527
+ "",
528
+ ]
529
+ if self.landed:
530
+ out += [f" {line}" for line in self.landed["steps"]]
531
+ else:
532
+ out.append(
533
+ "No destination given; pass --country (for example IN) for a duty and landed-cost estimate."
534
+ )
535
+ out += ["", "## Sources", ""]
536
+ out += [
537
+ f"[{c['n']}] {c['label']} - {c['detail']} ({c['url'] or 'no URL'})"
538
+ for c in self.citations
539
+ ]
540
+ out += ["", "Asked: " + "; ".join(s.asked)]
541
+ for n in s.notes:
542
+ out.append(f"\nNote: {n}")
543
+ out.append(
544
+ "\n*HS codes and duty rates are a guide to confirm with the customs broker; nothing here is a customs ruling.*"
545
+ )
546
+ return "\n".join(out)
547
+
548
+
549
+ def _citations(s: PartSourcing, hs: HsResult | None) -> list[dict[str, str]]:
550
+ cites = []
551
+
552
+ def when(source: str) -> str:
553
+ t = s.fetched.get(source)
554
+ return (
555
+ time.strftime("retrieved %Y-%m-%d %H:%M UTC", time.gmtime(t))
556
+ if t
557
+ else "retrieval time not recorded"
558
+ )
559
+
560
+ for o in s.offers:
561
+ cites.append(
562
+ {
563
+ "n": str(len(cites) + 1),
564
+ "label": offer_label(o),
565
+ "detail": f"provider {o.source}, {when(o.source)}"
566
+ + (
567
+ f"; also {', '.join(n for n in o.notes if n.startswith('also'))}"
568
+ if any(n.startswith("also") for n in o.notes)
569
+ else ""
570
+ ),
571
+ "url": o.url,
572
+ }
573
+ )
574
+ if s.part and s.part.datasheet_url:
575
+ cites.append(
576
+ {
577
+ "n": str(len(cites) + 1),
578
+ "label": "datasheet",
579
+ "detail": "linked by the catalogue",
580
+ "url": s.part.datasheet_url,
581
+ }
582
+ )
583
+ if hs and hs.code:
584
+ cites.append(
585
+ {
586
+ "n": str(len(cites) + 1),
587
+ "label": "HS rule",
588
+ "detail": "built-in guide table parts/data/hs_codes.yaml (WCO HS 2022 subheadings)",
589
+ "url": "",
590
+ }
591
+ )
592
+ cites.append(
593
+ {
594
+ "n": str(len(cites) + 1),
595
+ "label": "exchange rates",
596
+ "detail": s.fx.describe(),
597
+ "url": "https://api.frankfurter.app" if s.fx.source != "builtin" else "",
598
+ }
599
+ )
600
+ return cites
601
+
602
+
603
+ def build_brief(
604
+ query: str,
605
+ *,
606
+ catalog: Catalog | None = None,
607
+ country: str = "",
608
+ currency: str = "USD",
609
+ qty: int = 1000,
610
+ band_qtys: tuple[int, ...] = DEFAULT_BAND_QTYS,
611
+ fx: FxTable | None = None,
612
+ hs_table: dict[str, Any] | None = None,
613
+ duty_table: dict[str, Any] | None = None,
614
+ freight_usd: float = DEFAULT_FREIGHT_USD,
615
+ insurance_pct: float = DEFAULT_INSURANCE_PCT,
616
+ with_alternates: bool = True,
617
+ ) -> PartBrief:
618
+ catalog = catalog or default_catalog()
619
+ s = source_part(
620
+ query,
621
+ catalog=catalog,
622
+ qtys=tuple(sorted({1, 10, 100, 1000, qty})),
623
+ currency=currency,
624
+ fx=fx,
625
+ destination=country.upper(),
626
+ )
627
+ hs = classify_hs(s.part, hs_table) if s.part else None
628
+ alts = None
629
+ if s.part and with_alternates:
630
+ try:
631
+ alts = find_alternates(s.part.lcsc or s.part.mpn, catalog=catalog, limit=5)
632
+ except Offline:
633
+ alts = None
634
+ risk = single_source_risk(s.part, s, alts, qty) if s.part else None
635
+ bands, assumptions = price_bands(s, tuple(band_qtys)) if s.part else ([], [])
636
+ landed = None
637
+ best = s.best_at(qty)
638
+ if country and best is not None and best.total is not None:
639
+ landed = landed_cost(
640
+ best.total,
641
+ s.currency,
642
+ country,
643
+ hs.code if hs else "",
644
+ s.fx,
645
+ duty_table,
646
+ freight_usd,
647
+ insurance_pct,
648
+ quantity=best.buy_qty,
649
+ )
650
+ landed["supplier"] = best.label
651
+ region = _REGION_BY_COUNTRY.get(country.upper())
652
+ typical = {region: DISTRIBUTORS[region]} if region else DISTRIBUTORS
653
+ seen = sorted(
654
+ {
655
+ offer_label(o).split(" (")[0]
656
+ + ("" if o.authorised is not False else " (not authorised)")
657
+ for o in s.offers
658
+ }
659
+ )
660
+ return PartBrief(
661
+ query,
662
+ s,
663
+ hs,
664
+ alts,
665
+ risk,
666
+ bands,
667
+ assumptions,
668
+ landed,
669
+ qty,
670
+ _citations(s, hs),
671
+ {"seen": seen, "typical_by_region": typical},
672
+ time.strftime("%Y-%m-%d %H:%M", time.gmtime()),
673
+ )
674
+
675
+
676
+ def build_bom_brief(
677
+ items,
678
+ sourcings: dict[str, PartSourcing],
679
+ rollup_md: str,
680
+ briefs: dict[str, PartBrief],
681
+ ) -> str:
682
+ out = [
683
+ "# BOM sourcing brief",
684
+ "",
685
+ "## Cost roll-up (cheapest eligible supplier per line)",
686
+ "",
687
+ rollup_md,
688
+ "",
689
+ "## Per-line summary",
690
+ "",
691
+ ]
692
+ out.append("| line | MPN | HS (guide) | risk | recommended supplier |")
693
+ out.append("|---|---|---|---|---|")
694
+ for item in items:
695
+ b = briefs.get(item.query)
696
+ if not b or not b.sourcing.part:
697
+ out.append(
698
+ f"| {item.label[:30]} | {item.mpn or item.lcsc or item.value} | - | not found | - |"
699
+ )
700
+ continue
701
+ rec = b.sourcing.to_dict()["recommended"]["supplier"] or "-"
702
+ out.append(
703
+ f"| {item.label[:30]} | {b.sourcing.part.mpn} | {b.hs.code if b.hs else '-'} | {b.risk['level'] if b.risk else '-'} | {rec} |"
704
+ )
705
+ return "\n".join(out)