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
traceforge/sessions.py ADDED
@@ -0,0 +1,324 @@
1
+ """Persistent conversation threads (SQLite)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sqlite3
7
+ import time
8
+ import uuid
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from traceforge.config import data_home
14
+
15
+
16
+ @dataclass
17
+ class Thread:
18
+ id: str
19
+ workspace: str
20
+ title: str
21
+ mode: str
22
+ created: float
23
+ updated: float
24
+ messages: list[dict[str, Any]] = field(default_factory=list)
25
+ usage: dict[str, int] = field(default_factory=dict)
26
+ meta: dict[str, Any] = field(default_factory=dict) # branch, model, effort, ...
27
+
28
+ def summary(self) -> dict[str, Any]:
29
+ return {
30
+ "id": self.id,
31
+ "title": self.title,
32
+ "workspace": self.workspace,
33
+ "mode": self.mode,
34
+ "updated": time.strftime("%Y-%m-%d %H:%M", time.localtime(self.updated)),
35
+ "ago": relative_time(self.updated),
36
+ "messages": len(self.messages),
37
+ "branch": self.meta.get("branch", ""),
38
+ "model": self.meta.get("model", ""),
39
+ }
40
+
41
+ def first_prompt(self) -> str:
42
+ for message in self.messages:
43
+ if message.get("role") != "user":
44
+ continue
45
+ for text in reversed(_texts(message.get("content"))):
46
+ if not text.startswith("<workspace>"):
47
+ return text
48
+ return self.title
49
+
50
+
51
+ def is_user_prompt(message: dict[str, Any]) -> bool:
52
+ """A message the person typed (not a tool result that the API carries as role 'user')."""
53
+ if message.get("role") != "user":
54
+ return False
55
+ content = message.get("content")
56
+ if isinstance(content, str):
57
+ return True
58
+ return isinstance(content, list) and any(
59
+ isinstance(b, dict) and b.get("type") in {"text", "image"} for b in content
60
+ )
61
+
62
+
63
+ def prompt_indexes(thread: Thread) -> list[int]:
64
+ """Message indexes of the user's prompts, in order (prompt N is ``result[N - 1]``)."""
65
+ return [i for i, m in enumerate(thread.messages) if is_user_prompt(m)]
66
+
67
+
68
+ def prompt_text(message: dict[str, Any]) -> str:
69
+ """What the person wrote in a prompt message, without the injected workspace context."""
70
+ parts = [t for t in _texts(message.get("content")) if not t.startswith("<workspace>")]
71
+ return "\n".join(parts).strip()
72
+
73
+
74
+ def _texts(content: Any) -> list[str]:
75
+ if isinstance(content, str):
76
+ return [content]
77
+ if not isinstance(content, list):
78
+ return []
79
+ return [
80
+ str(block.get("text", ""))
81
+ for block in content
82
+ if isinstance(block, dict) and block.get("type") == "text"
83
+ ]
84
+
85
+
86
+ def relative_time(timestamp: float, now: float | None = None) -> str:
87
+ seconds = int((now or time.time()) - timestamp)
88
+ if seconds < 60:
89
+ return "just now" if seconds < 5 else f"{seconds}s ago"
90
+ for size, unit in (
91
+ (86400 * 365, "y"),
92
+ (86400 * 30, "mo"),
93
+ (86400, "d"),
94
+ (3600, "h"),
95
+ (60, "m"),
96
+ ):
97
+ if seconds >= size:
98
+ return f"{seconds // size}{unit} ago"
99
+ return "just now" # pragma: no cover
100
+
101
+
102
+ def to_markdown(thread: Thread) -> str:
103
+ """A readable transcript: prompts, answers and tool calls (inputs abbreviated)."""
104
+ lines = [
105
+ f"# {thread.title}",
106
+ "",
107
+ f"- thread: `{thread.id}`",
108
+ f"- workspace: `{thread.workspace}`",
109
+ ]
110
+ lines += [f"- mode: {thread.mode}", f"- updated: {thread.summary()['updated']}", ""]
111
+ for message in thread.messages:
112
+ content = message.get("content")
113
+ blocks = content if isinstance(content, list) else [{"type": "text", "text": str(content)}]
114
+ for block in blocks:
115
+ if not isinstance(block, dict):
116
+ continue
117
+ kind = block.get("type")
118
+ if kind == "text" and str(block.get("text", "")).startswith("<workspace>"):
119
+ continue
120
+ if kind == "text" and block.get("text"):
121
+ who = "You" if message.get("role") == "user" else "Traceforge"
122
+ lines += [f"## {who}", "", str(block["text"]).strip(), ""]
123
+ elif kind == "tool_use":
124
+ arguments = json.dumps(block.get("input") or {})[:300]
125
+ lines += [f"- tool `{block.get('name')}` {arguments}"]
126
+ elif kind == "tool_result":
127
+ result = block.get("content")
128
+ text = result if isinstance(result, str) else json.dumps(result)[:300]
129
+ first = (text.strip().splitlines() or [""])[0][:200]
130
+ flag = " (error)" if block.get("is_error") else ""
131
+ lines += [f" - result{flag}: {first}", ""]
132
+ elif kind == "image":
133
+ lines += ["*(image)*", ""]
134
+ return "\n".join(lines).rstrip() + "\n"
135
+
136
+
137
+ class AmbiguousThread(LookupError):
138
+ """A thread id prefix matched more than one thread."""
139
+
140
+ def __init__(self, prefix: str, matches: list[str]):
141
+ super().__init__(f"{prefix!r} matches several threads: {', '.join(matches)}")
142
+ self.matches = matches
143
+
144
+
145
+ class SessionStore:
146
+ def __init__(self, path: Path | None = None):
147
+ self.path = path or data_home() / "sessions.db"
148
+ self.path.parent.mkdir(parents=True, exist_ok=True)
149
+ with self._connect() as db:
150
+ db.execute(
151
+ "CREATE TABLE IF NOT EXISTS threads (id TEXT PRIMARY KEY, workspace TEXT, title TEXT, mode TEXT,"
152
+ " created REAL, updated REAL, messages TEXT, usage TEXT)"
153
+ )
154
+ db.execute("CREATE INDEX IF NOT EXISTS threads_ws ON threads(workspace, updated)")
155
+ columns = {row[1] for row in db.execute("PRAGMA table_info(threads)")}
156
+ if "meta" not in columns:
157
+ db.execute("ALTER TABLE threads ADD COLUMN meta TEXT")
158
+ try:
159
+ self.path.chmod(0o600)
160
+ except OSError: # pragma: no cover
161
+ pass
162
+
163
+ def _connect(self) -> sqlite3.Connection:
164
+ db = sqlite3.connect(self.path, timeout=10)
165
+ db.execute("PRAGMA journal_mode=WAL")
166
+ return db
167
+
168
+ def create(
169
+ self, workspace: Path, title: str, mode: str = "agent", meta: dict[str, Any] | None = None
170
+ ) -> Thread:
171
+ now = time.time()
172
+ thread = Thread(
173
+ uuid.uuid4().hex[:12],
174
+ str(workspace),
175
+ title[:120],
176
+ mode,
177
+ now,
178
+ now,
179
+ meta=dict(meta or {}),
180
+ )
181
+ self.save(thread)
182
+ return thread
183
+
184
+ def save(self, thread: Thread) -> None:
185
+ thread.updated = time.time()
186
+ with self._connect() as db:
187
+ db.execute(
188
+ "INSERT OR REPLACE INTO threads (id, workspace, title, mode, created, updated,"
189
+ " messages, usage, meta) VALUES (?,?,?,?,?,?,?,?,?)",
190
+ (
191
+ thread.id,
192
+ thread.workspace,
193
+ thread.title,
194
+ thread.mode,
195
+ thread.created,
196
+ thread.updated,
197
+ json.dumps(thread.messages, default=str),
198
+ json.dumps(thread.usage),
199
+ json.dumps(thread.meta, default=str),
200
+ ),
201
+ )
202
+
203
+ def load(self, thread_id: str) -> Thread | None:
204
+ """A thread by id or unique id prefix (an ambiguous prefix raises AmbiguousThread)."""
205
+ columns = "id, workspace, title, mode, created, updated, messages, usage, meta"
206
+ with self._connect() as db:
207
+ row = db.execute(f"SELECT {columns} FROM threads WHERE id = ?", (thread_id,)).fetchone()
208
+ if row is None and thread_id:
209
+ rows = db.execute(
210
+ f"SELECT {columns} FROM threads WHERE id LIKE ? LIMIT 5",
211
+ ("".join(c for c in thread_id if c.isalnum()) + "%",),
212
+ ).fetchall()
213
+ if len(rows) > 1:
214
+ raise AmbiguousThread(thread_id, [r[0] for r in rows])
215
+ row = rows[0] if rows else None
216
+ if row is None:
217
+ return None
218
+ return Thread(
219
+ row[0],
220
+ row[1],
221
+ row[2],
222
+ row[3],
223
+ row[4],
224
+ row[5],
225
+ json.loads(row[6] or "[]"),
226
+ json.loads(row[7] or "{}"),
227
+ json.loads(row[8] or "{}"),
228
+ )
229
+
230
+ # ------------------------------------------------------------- branches
231
+ # A branch is a thread whose meta records ``parent`` (the thread it forked from),
232
+ # ``fork`` (how many messages it shares with the parent), ``root`` (the first thread of the
233
+ # tree) and ``branch`` (its name). A thread without those keys is a tree of one branch, so
234
+ # older threads need no migration.
235
+
236
+ def root_id(self, thread: Thread) -> str:
237
+ return str(thread.meta.get("root") or thread.id)
238
+
239
+ def fork(self, thread: Thread, keep_messages: int, name: str = "") -> Thread:
240
+ """A new thread holding the first ``keep_messages`` messages of ``thread``."""
241
+ root = self.root_id(thread)
242
+ if "root" not in thread.meta: # first fork: the original becomes the named trunk
243
+ thread.meta["root"] = root
244
+ thread.meta.setdefault("branch_name", "main")
245
+ self.save(thread)
246
+ child = self.create(
247
+ Path(thread.workspace),
248
+ thread.title,
249
+ thread.mode,
250
+ meta={
251
+ **{k: v for k, v in thread.meta.items() if k not in {"branch_name"}},
252
+ "root": root,
253
+ "parent": thread.id,
254
+ "fork": keep_messages,
255
+ "branch_name": name or f"branch-{len(self.branches(thread)) + 1}",
256
+ },
257
+ )
258
+ child.messages = [
259
+ json.loads(json.dumps(m, default=str)) for m in thread.messages[:keep_messages]
260
+ ]
261
+ self.save(child)
262
+ return child
263
+
264
+ def branches(self, thread: Thread) -> list[Thread]:
265
+ """Every thread of the tree ``thread`` belongs to, oldest first (always includes it)."""
266
+ root = self.root_id(thread)
267
+ with self._connect() as db:
268
+ ids = [
269
+ r[0]
270
+ for r in db.execute(
271
+ "SELECT id FROM threads WHERE id = ? OR meta LIKE ? ORDER BY created",
272
+ (root, f'%"root": "{root}"%'),
273
+ ).fetchall()
274
+ ]
275
+ found = [t for t in (self.load(i) for i in ids) if t is not None]
276
+ found = [t for t in found if self.root_id(t) == root]
277
+ if not any(t.id == thread.id for t in found):
278
+ found.append(thread)
279
+ return found
280
+
281
+ def rename(self, thread_id: str, title: str) -> bool:
282
+ with self._connect() as db:
283
+ cursor = db.execute(
284
+ "UPDATE threads SET title = ? WHERE id = ?", (title[:120], thread_id)
285
+ )
286
+ return cursor.rowcount > 0
287
+
288
+ def search(self, text: str, workspace: Path | None = None, limit: int = 20) -> list[Thread]:
289
+ """Threads whose title or messages contain ``text`` (case-insensitive)."""
290
+ query = "SELECT id FROM threads WHERE (title LIKE ? OR messages LIKE ?)"
291
+ needle = f"%{text}%"
292
+ params: list[Any] = [needle, needle]
293
+ if workspace is not None:
294
+ query += " AND workspace = ?"
295
+ params.append(str(workspace))
296
+ query += " ORDER BY updated DESC LIMIT ?"
297
+ params.append(limit)
298
+ with self._connect() as db:
299
+ ids = [r[0] for r in db.execute(query, params).fetchall()]
300
+ return [t for t in (self.load(i) for i in ids) if t is not None]
301
+
302
+ def latest(self, workspace: Path) -> Thread | None:
303
+ with self._connect() as db:
304
+ row = db.execute(
305
+ "SELECT id FROM threads WHERE workspace = ? ORDER BY updated DESC LIMIT 1",
306
+ (str(workspace),),
307
+ ).fetchone()
308
+ return self.load(row[0]) if row else None
309
+
310
+ def list(self, workspace: Path | None = None, limit: int = 20) -> list[Thread]:
311
+ query = "SELECT id FROM threads"
312
+ params: tuple = ()
313
+ if workspace is not None:
314
+ query += " WHERE workspace = ?"
315
+ params = (str(workspace),)
316
+ query += " ORDER BY updated DESC LIMIT ?"
317
+ with self._connect() as db:
318
+ ids = [r[0] for r in db.execute(query, (*params, limit)).fetchall()]
319
+ return [t for t in (self.load(i) for i in ids) if t is not None]
320
+
321
+ def delete(self, thread_id: str) -> bool:
322
+ with self._connect() as db:
323
+ cursor = db.execute("DELETE FROM threads WHERE id = ?", (thread_id,))
324
+ return cursor.rowcount > 0
traceforge/sexpr.py ADDED
@@ -0,0 +1,279 @@
1
+ """Parser and writer for KiCad S-expression files.
2
+
3
+ KiCad stores schematics, boards, symbol libraries and footprints as
4
+ S-expressions. Two kinds of atoms matter: bare symbols (``kicad_sch``,
5
+ ``yes``, ``F.Cu``) and quoted strings (``"R1"``). Round-tripping a file must
6
+ keep that distinction, so bare atoms are :class:`Sym` and quoted atoms are
7
+ plain :class:`str`. Numbers are kept as :class:`Sym` holding their original
8
+ text so ``1.270`` is written back exactly; :func:`num` converts on demand.
9
+
10
+ A node is a Python ``list`` whose first element is a :class:`Sym` naming it.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ from collections.abc import Iterator
17
+ from typing import Any
18
+
19
+ __all__ = [
20
+ "Sym",
21
+ "Node",
22
+ "parse",
23
+ "dumps",
24
+ "find",
25
+ "find_all",
26
+ "walk",
27
+ "value",
28
+ "num",
29
+ "prop",
30
+ "set_prop",
31
+ "fmt",
32
+ ]
33
+
34
+
35
+ class Sym(str):
36
+ """A bare (unquoted) atom."""
37
+
38
+ __slots__ = ()
39
+
40
+ def __repr__(self) -> str: # pragma: no cover - debugging aid
41
+ return f"Sym({str(self)!r})"
42
+
43
+
44
+ Atom = Sym | str
45
+ Node = list # list[Sym | str | Node]
46
+
47
+ _TOKEN = re.compile(r'\s*(?:(\()|(\))|"((?:[^"\\]|\\.)*)"|([^\s()"]+))', re.S)
48
+ _ESCAPES = {"n": "\n", "t": "\t", "r": "\r", "\\": "\\", '"': '"'}
49
+
50
+
51
+ def _unescape(text: str) -> str:
52
+ if "\\" not in text:
53
+ return text
54
+ return re.sub(r"\\(.)", lambda m: _ESCAPES.get(m.group(1), m.group(1)), text, flags=re.S)
55
+
56
+
57
+ def _escape(text: str) -> str:
58
+ return text.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\t", "\\t")
59
+
60
+
61
+ class ParseError(ValueError):
62
+ """The text is not a well-formed S-expression."""
63
+
64
+
65
+ def parse(text: str) -> Node:
66
+ """Parse one top-level S-expression."""
67
+ stack: list[Node] = []
68
+ root: Node | None = None
69
+ pos = 0
70
+ length = len(text)
71
+ while pos < length:
72
+ match = _TOKEN.match(text, pos)
73
+ if match is None:
74
+ if text[pos:].strip():
75
+ raise ParseError(f"unexpected text at offset {pos}: {text[pos : pos + 20]!r}")
76
+ break
77
+ pos = match.end()
78
+ opened, closed, quoted, bare = match.groups()
79
+ if opened:
80
+ node: Node = []
81
+ if stack:
82
+ stack[-1].append(node)
83
+ stack.append(node)
84
+ elif closed:
85
+ if not stack:
86
+ raise ParseError(f"unbalanced ')' at offset {pos - 1}")
87
+ done = stack.pop()
88
+ if not stack:
89
+ root = done
90
+ break
91
+ elif quoted is not None:
92
+ if not stack:
93
+ raise ParseError("atom outside of a list")
94
+ stack[-1].append(_unescape(quoted))
95
+ elif bare is not None:
96
+ if not stack:
97
+ raise ParseError("atom outside of a list")
98
+ stack[-1].append(Sym(bare))
99
+ if stack:
100
+ raise ParseError("unexpected end of input: unclosed '('")
101
+ if root is None:
102
+ raise ParseError("no S-expression found")
103
+ if text[pos:].strip():
104
+ raise ParseError(
105
+ f"unexpected text after the expression at offset {pos}: {text[pos : pos + 20]!r}"
106
+ )
107
+ return root
108
+
109
+
110
+ # Nodes whose children are always written on their own lines. Everything else
111
+ # is written inline when it is short, which mirrors KiCad's own layout well
112
+ # enough that diffs of edited files stay readable.
113
+ _BLOCK_NODES = frozenset(
114
+ {
115
+ "kicad_sch",
116
+ "kicad_pcb",
117
+ "kicad_symbol_lib",
118
+ "footprint",
119
+ "module",
120
+ "symbol",
121
+ "lib_symbols",
122
+ "layers",
123
+ "setup",
124
+ "pcbplotparams",
125
+ "sheet_instances",
126
+ "symbol_instances",
127
+ "instances",
128
+ "project",
129
+ "zone",
130
+ "polygon",
131
+ "filled_polygon",
132
+ "property",
133
+ "pad",
134
+ "net_class",
135
+ "title_block",
136
+ "sheet",
137
+ "label",
138
+ "global_label",
139
+ "hierarchical_label",
140
+ "wire",
141
+ "junction",
142
+ "no_connect",
143
+ "fp_text",
144
+ "general",
145
+ "pts",
146
+ "model",
147
+ }
148
+ )
149
+ _INLINE_LIMIT = 100
150
+
151
+
152
+ def _atom(atom: Atom) -> str:
153
+ if isinstance(atom, Sym):
154
+ return str(atom)
155
+ return f'"{_escape(atom)}"'
156
+
157
+
158
+ def _inline(node: Node) -> str:
159
+ return "(" + " ".join(_inline(c) if isinstance(c, list) else _atom(c) for c in node) + ")"
160
+
161
+
162
+ def _write(node: Node, indent: int, out: list[str]) -> None:
163
+ head = str(node[0]) if node and isinstance(node[0], str) else ""
164
+ flat = _inline(node)
165
+ has_children = any(isinstance(c, list) for c in node)
166
+ if not has_children or (head not in _BLOCK_NODES and len(flat) + indent <= _INLINE_LIMIT):
167
+ out.append(flat)
168
+ return
169
+ pad = "\t" * (indent + 1)
170
+ atoms: list[str] = []
171
+ index = 0
172
+ while index < len(node) and not isinstance(node[index], list):
173
+ atoms.append(_atom(node[index]))
174
+ index += 1
175
+ out.append("(" + " ".join(atoms))
176
+ for child in node[index:]:
177
+ out.append("\n" + pad)
178
+ if isinstance(child, list):
179
+ _write(child, indent + 1, out)
180
+ else:
181
+ out.append(_atom(child))
182
+ out.append("\n" + "\t" * indent + ")")
183
+
184
+
185
+ def dumps(node: Node) -> str:
186
+ """Serialize a node in a KiCad-like layout, ending with a newline."""
187
+ out: list[str] = []
188
+ _write(node, 0, out)
189
+ return "".join(out) + "\n"
190
+
191
+
192
+ def name(node: Any) -> str | None:
193
+ if isinstance(node, list) and node and isinstance(node[0], str):
194
+ return str(node[0])
195
+ return None
196
+
197
+
198
+ def find(node: Node, key: str) -> Node | None:
199
+ """First direct child named ``key``."""
200
+ for child in node:
201
+ if isinstance(child, list) and child and child[0] == key:
202
+ return child
203
+ return None
204
+
205
+
206
+ def find_all(node: Node, key: str) -> list[Node]:
207
+ """All direct children named ``key``."""
208
+ return [c for c in node if isinstance(c, list) and c and c[0] == key]
209
+
210
+
211
+ def walk(node: Node, key: str | None = None) -> Iterator[Node]:
212
+ """Depth-first iteration over all descendant nodes (optionally by name)."""
213
+ for child in node:
214
+ if isinstance(child, list):
215
+ if key is None or (child and child[0] == key):
216
+ yield child
217
+ yield from walk(child, key)
218
+
219
+
220
+ def value(node: Node | None, key: str, default: Any = None) -> Any:
221
+ """``(key value ...)`` -> value, for a direct child of ``node``."""
222
+ if node is None:
223
+ return default
224
+ child = find(node, key)
225
+ if child is None or len(child) < 2:
226
+ return default
227
+ return child[1]
228
+
229
+
230
+ def num(atom: Any, default: float = 0.0) -> float:
231
+ try:
232
+ return float(atom)
233
+ except (TypeError, ValueError):
234
+ return default
235
+
236
+
237
+ def fmt(number: float) -> Sym:
238
+ """Format a coordinate the way KiCad does: no trailing zeros, max 6 decimals."""
239
+ text = f"{number:.6f}".rstrip("0").rstrip(".")
240
+ if text in {"-0", ""}:
241
+ text = "0"
242
+ return Sym(text)
243
+
244
+
245
+ def prop(node: Node, key: str, default: str | None = None) -> str | None:
246
+ """Value of ``(property "key" "value" ...)`` on a symbol or footprint."""
247
+ for child in find_all(node, "property"):
248
+ if len(child) >= 3 and child[1] == key:
249
+ return str(child[2])
250
+ return default
251
+
252
+
253
+ def set_prop(node: Node, key: str, new_value: str, *, template: Node | None = None) -> bool:
254
+ """Set a property value. Adds the property (hidden) when missing.
255
+
256
+ Returns True when an existing property was updated.
257
+ """
258
+ for child in find_all(node, "property"):
259
+ if len(child) >= 3 and child[1] == key:
260
+ child[2] = str(new_value)
261
+ return True
262
+ at = find(node, "at")
263
+ position: Node = [Sym("at"), *(at[1:3] if at else [Sym("0"), Sym("0")]), Sym("0")]
264
+ new: Node = template or [
265
+ Sym("property"),
266
+ key,
267
+ str(new_value),
268
+ position,
269
+ [
270
+ Sym("effects"),
271
+ [Sym("font"), [Sym("size"), Sym("1.27"), Sym("1.27")]],
272
+ [Sym("hide"), Sym("yes")],
273
+ ],
274
+ ]
275
+ # Insert after the last existing property so KiCad's ordering is kept.
276
+ props = [i for i, c in enumerate(node) if isinstance(c, list) and c and c[0] == "property"]
277
+ index = props[-1] + 1 if props else len(node)
278
+ node.insert(index, new)
279
+ return False
@@ -0,0 +1,17 @@
1
+ """Circuit simulation: SPICE netlists, ngspice runs, results, tuning and LTspice export."""
2
+
3
+ from traceforge.sim.circuit import Circuit, Element, SimError, format_value, parse_value
4
+ from traceforge.sim.engine import Analysis, SimRun, find_ngspice, parse_analysis, run_ngspice
5
+
6
+ __all__ = [
7
+ "Analysis",
8
+ "Circuit",
9
+ "Element",
10
+ "SimError",
11
+ "SimRun",
12
+ "find_ngspice",
13
+ "format_value",
14
+ "parse_analysis",
15
+ "parse_value",
16
+ "run_ngspice",
17
+ ]