copperhead 0.6.0 → 0.7.0

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 (58) hide show
  1. package/dist/agent/loop.js +118 -16
  2. package/dist/agent/loop.js.map +1 -1
  3. package/dist/agent/prompts.js +2 -1
  4. package/dist/agent/prompts.js.map +1 -1
  5. package/dist/agent/providers/claude-code.js +207 -27
  6. package/dist/agent/providers/claude-code.js.map +1 -1
  7. package/dist/agent/recovery.js +148 -0
  8. package/dist/agent/recovery.js.map +1 -0
  9. package/dist/agent/render.js +17 -2
  10. package/dist/agent/render.js.map +1 -1
  11. package/dist/agent/response-cache.js +81 -0
  12. package/dist/agent/response-cache.js.map +1 -0
  13. package/dist/agent/tools.js +61 -4
  14. package/dist/agent/tools.js.map +1 -1
  15. package/dist/agent/transcript.js.map +1 -1
  16. package/dist/commands/create.js +470 -35
  17. package/dist/commands/create.js.map +1 -1
  18. package/dist/config.js +19 -0
  19. package/dist/config.js.map +1 -1
  20. package/dist/kicad/bootstrap.js +166 -0
  21. package/dist/kicad/bootstrap.js.map +1 -0
  22. package/dist/kicad/spice.js +306 -0
  23. package/dist/kicad/spice.js.map +1 -0
  24. package/dist/kicad/symlib.js +228 -0
  25. package/dist/kicad/symlib.js.map +1 -0
  26. package/dist/memory/bom-table.js +193 -22
  27. package/dist/memory/bom-table.js.map +1 -1
  28. package/dist/memory/drift.js +33 -11
  29. package/dist/memory/drift.js.map +1 -1
  30. package/dist/util/git.js +37 -1
  31. package/dist/util/git.js.map +1 -1
  32. package/dist/util/preflight.js +37 -0
  33. package/dist/util/preflight.js.map +1 -1
  34. package/dist/util/retry.js +23 -0
  35. package/dist/util/retry.js.map +1 -1
  36. package/dist/util/tmp.js +119 -0
  37. package/dist/util/tmp.js.map +1 -0
  38. package/package.json +1 -1
  39. package/src/agent/loop.ts +136 -16
  40. package/src/agent/prompts.ts +2 -1
  41. package/src/agent/providers/claude-code.ts +207 -24
  42. package/src/agent/recovery.ts +162 -0
  43. package/src/agent/render.ts +28 -1
  44. package/src/agent/response-cache.ts +80 -0
  45. package/src/agent/tools.ts +62 -4
  46. package/src/agent/transcript.ts +1 -0
  47. package/src/agent/types.ts +17 -0
  48. package/src/commands/create.ts +528 -38
  49. package/src/config.ts +34 -0
  50. package/src/kicad/bootstrap.ts +181 -0
  51. package/src/kicad/spice.ts +399 -0
  52. package/src/kicad/symlib.ts +248 -0
  53. package/src/memory/bom-table.ts +191 -20
  54. package/src/memory/drift.ts +42 -11
  55. package/src/util/git.ts +37 -1
  56. package/src/util/preflight.ts +44 -0
  57. package/src/util/retry.ts +29 -0
  58. package/src/util/tmp.ts +113 -0
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Cross-check the schematic's `lib_symbols` against the KiCad symbol libraries
3
+ * installed on the machine (I9).
4
+ *
5
+ * The create pipeline currently has the model hand-author every `lib_symbols`
6
+ * entry — pins, names, electrical types, geometry — under a `lib_id` that
7
+ * *claims* to be a canonical KiCad part (`Device:R`, `Connector:USB_C_...`).
8
+ * ERC only checks the net graph as drawn, so an entry whose pins silently
9
+ * diverge from the real library part (wrong pin count, a missing shield/CC pin,
10
+ * swapped numbers) passes every gate while being wrong. This module reads the
11
+ * real `(symbol …)` out of the installed `.kicad_sym` and reports divergences so
12
+ * the model — or a reviewer — can reconcile them.
13
+ *
14
+ * It is deliberately a *checker*, not an auto-replacer: KiCad renames symbols
15
+ * across versions (e.g. `USB_C_Receptacle_USB2.0` became `…_14P`/`…_16P` in
16
+ * KiCad 10), so blindly splicing by lib_id would fail on exactly the parts that
17
+ * matter most. When the exact name is absent, we surface close candidates
18
+ * instead of guessing.
19
+ */
20
+
21
+ import { readFile, readdir, access } from 'node:fs/promises';
22
+ import path from 'node:path';
23
+ import { parseSexp, children, child, isList, type SexpNode } from './sexp.js';
24
+
25
+ const tag = (n: SexpNode): string | null => (isList(n) && typeof n[0] === 'string' ? n[0] : null);
26
+ const atomAt = (node: SexpNode[] | undefined, idx: number): string | undefined => {
27
+ const v = node?.[idx];
28
+ return typeof v === 'string' ? v : undefined;
29
+ };
30
+
31
+ // KiCad has two spellings for an unnamed pin: the legacy `~` sentinel and, in
32
+ // newer library format, an empty string. They are semantically identical, so
33
+ // normalize before comparing or the check floods with phantom `~` vs "" diffs.
34
+ const normPinName = (n: string): string => (n === '~' ? '' : n);
35
+
36
+ export interface LibPin {
37
+ number: string;
38
+ name: string;
39
+ /** electrical type: passive | power_in | bidirectional | input | … */
40
+ type: string;
41
+ }
42
+
43
+ /**
44
+ * Candidate directories holding KiCad's stock `.kicad_sym` libraries, most
45
+ * specific first. Env overrides win (KiCad exports these), then the standard
46
+ * install locations for Linux/macOS/Windows. Only existing dirs are returned.
47
+ */
48
+ export async function symbolSearchDirs(env = process.env): Promise<string[]> {
49
+ const fromEnv = [
50
+ env.KICAD_SYMBOL_DIR,
51
+ env.KICAD10_SYMBOL_DIR,
52
+ env.KICAD9_SYMBOL_DIR,
53
+ env.KICAD8_SYMBOL_DIR,
54
+ ].filter((v): v is string => !!v);
55
+ const defaults = [
56
+ '/usr/share/kicad/symbols',
57
+ '/usr/local/share/kicad/symbols',
58
+ '/Applications/KiCad/KiCad.app/Contents/SharedSupport/symbols',
59
+ 'C:/Program Files/KiCad/share/kicad/symbols',
60
+ ];
61
+ const out: string[] = [];
62
+ for (const dir of [...fromEnv, ...defaults]) {
63
+ try {
64
+ await access(dir);
65
+ if (!out.includes(dir)) out.push(dir);
66
+ } catch {
67
+ // not present on this machine; skip
68
+ }
69
+ }
70
+ return out;
71
+ }
72
+
73
+ /** Path to `<lib>.kicad_sym` in the first search dir that has it, or null. */
74
+ export async function findLibraryFile(lib: string, dirs: string[]): Promise<string | null> {
75
+ for (const dir of dirs) {
76
+ const p = path.join(dir, `${lib}.kicad_sym`);
77
+ try {
78
+ await access(p);
79
+ return p;
80
+ } catch {
81
+ // try next dir
82
+ }
83
+ }
84
+ return null;
85
+ }
86
+
87
+ /** Collect pins (number, name, electrical type) from a `(symbol …)` node,
88
+ * including its nested unit sub-symbols. Same walk `libPinDefs` uses, plus the
89
+ * electrical-type atom that pin-position parsing does not need. */
90
+ export function pinsOfSymbolNode(sym: SexpNode[]): LibPin[] {
91
+ const pins: LibPin[] = [];
92
+ const walk = (n: SexpNode): void => {
93
+ if (!isList(n)) return;
94
+ if (tag(n) === 'pin') {
95
+ const num = atomAt(child(n, 'number'), 1);
96
+ if (num !== undefined) {
97
+ pins.push({
98
+ number: num,
99
+ name: atomAt(child(n, 'name'), 1) ?? '~',
100
+ type: typeof n[1] === 'string' ? n[1] : '?',
101
+ });
102
+ }
103
+ }
104
+ for (const c of n) walk(c);
105
+ };
106
+ walk(sym);
107
+ return pins;
108
+ }
109
+
110
+ /** The top-level `(symbol "name" …)` entries of a parsed `.kicad_sym` root. */
111
+ function librarySymbols(root: SexpNode[]): Map<string, SexpNode[]> {
112
+ const map = new Map<string, SexpNode[]>();
113
+ for (const sym of children(root, 'symbol')) {
114
+ const name = atomAt(sym, 1);
115
+ if (name) map.set(name, sym);
116
+ }
117
+ return map;
118
+ }
119
+
120
+ /**
121
+ * Resolve a `lib_id` (e.g. `Device:R`) to the real library part's pins.
122
+ * `extends` derived symbols inherit their base's pins, so we follow one such
123
+ * link (loop-guarded). Returns the pins, or — when the exact symbol is absent —
124
+ * the closest-named candidates so a caller can suggest the real name.
125
+ */
126
+ export async function resolveLibrarySymbol(
127
+ libId: string,
128
+ dirs: string[],
129
+ ): Promise<
130
+ | { status: 'ok'; pins: LibPin[] }
131
+ | { status: 'no-symbol'; candidates: string[] }
132
+ | { status: 'no-library' }
133
+ > {
134
+ const [lib, name] = libId.includes(':') ? [libId.slice(0, libId.indexOf(':')), libId.slice(libId.indexOf(':') + 1)] : ['', libId];
135
+ const file = await findLibraryFile(lib, dirs);
136
+ if (!file) return { status: 'no-library' };
137
+ const root = parseSexp(await readFile(file, 'utf8'))[0];
138
+ if (root === undefined || !isList(root)) return { status: 'no-library' };
139
+ const symbols = librarySymbols(root);
140
+
141
+ let current = name;
142
+ const seen = new Set<string>();
143
+ while (current && !seen.has(current)) {
144
+ seen.add(current);
145
+ const sym = symbols.get(current);
146
+ if (!sym) break;
147
+ const pins = pinsOfSymbolNode(sym);
148
+ if (pins.length) return { status: 'ok', pins };
149
+ // no pins of its own → follow an `extends` base if present
150
+ const base = atomAt(child(sym, 'extends'), 1);
151
+ if (!base) return { status: 'ok', pins }; // genuinely pinless (e.g. a graphic)
152
+ current = base;
153
+ }
154
+
155
+ // exact name not found: offer near matches (case-insensitive substring both ways)
156
+ const q = name.toLowerCase();
157
+ const candidates = [...symbols.keys()]
158
+ .filter((k) => {
159
+ const lk = k.toLowerCase();
160
+ return lk.includes(q) || q.includes(lk);
161
+ })
162
+ .slice(0, 8);
163
+ return { status: 'no-symbol', candidates };
164
+ }
165
+
166
+ export interface SymbolFinding {
167
+ libId: string;
168
+ kind: 'no-library' | 'no-symbol' | 'pin-count' | 'pin-mismatch';
169
+ detail: string;
170
+ }
171
+
172
+ /** A schematic lib_symbols entry: its lib_id and the pins as authored. */
173
+ function schematicLibSymbols(root: SexpNode[]): { libId: string; pins: LibPin[] }[] {
174
+ const libs = child(root, 'lib_symbols');
175
+ if (!libs) return [];
176
+ return children(libs, 'symbol').map((sym) => ({
177
+ libId: atomAt(sym, 1) ?? '',
178
+ pins: pinsOfSymbolNode(sym),
179
+ }));
180
+ }
181
+
182
+ /**
183
+ * Compare every lib_symbols entry in a schematic against the installed library.
184
+ * Returns one finding per divergence; an empty array means every resolvable
185
+ * symbol matched. A part whose library is not installed is reported once (so
186
+ * the model knows the check could not run for it) but never treated as a
187
+ * mismatch — absence of the library is not evidence of wrong pins.
188
+ */
189
+ export async function verifySchematicSymbols(
190
+ schPath: string,
191
+ env = process.env,
192
+ ): Promise<{ findings: SymbolFinding[]; checked: number; skipped: number }> {
193
+ const dirs = await symbolSearchDirs(env);
194
+ const root = parseSexp(await readFile(schPath, 'utf8'))[0];
195
+ const findings: SymbolFinding[] = [];
196
+ if (root === undefined || !isList(root)) return { findings, checked: 0, skipped: 0 };
197
+
198
+ let checked = 0;
199
+ let skipped = 0;
200
+ for (const entry of schematicLibSymbols(root)) {
201
+ if (!entry.libId) continue;
202
+ const resolved = await resolveLibrarySymbol(entry.libId, dirs);
203
+ if (resolved.status === 'no-library') {
204
+ skipped++;
205
+ findings.push({
206
+ libId: entry.libId,
207
+ kind: 'no-library',
208
+ detail: `library for "${entry.libId}" is not installed on this machine; cannot verify its pins`,
209
+ });
210
+ continue;
211
+ }
212
+ if (resolved.status === 'no-symbol') {
213
+ findings.push({
214
+ libId: entry.libId,
215
+ kind: 'no-symbol',
216
+ detail: resolved.candidates.length
217
+ ? `"${entry.libId}" does not exist in the installed library — closest real symbols: ${resolved.candidates.join(', ')}. Use one of these lib_ids (KiCad renames symbols across versions).`
218
+ : `"${entry.libId}" does not exist in the installed library and no close match was found; confirm the lib_id.`,
219
+ });
220
+ continue;
221
+ }
222
+ checked++;
223
+ const real = resolved.pins;
224
+ const authored = entry.pins;
225
+ const realByNum = new Map(real.map((p) => [p.number, p]));
226
+ const authByNum = new Map(authored.map((p) => [p.number, p]));
227
+ if (real.length !== authored.length) {
228
+ findings.push({
229
+ libId: entry.libId,
230
+ kind: 'pin-count',
231
+ detail: `pin count differs: schematic has ${authored.length} pin(s) [${[...authByNum.keys()].join(',')}], the real ${entry.libId} has ${real.length} [${[...realByNum.keys()].join(',')}]`,
232
+ });
233
+ }
234
+ // per-pin name/type divergence on shared pin numbers
235
+ for (const [num, rp] of realByNum) {
236
+ const ap = authByNum.get(num);
237
+ if (!ap) continue; // count mismatch already reported the gap
238
+ if (normPinName(ap.name) !== normPinName(rp.name) || ap.type !== rp.type) {
239
+ findings.push({
240
+ libId: entry.libId,
241
+ kind: 'pin-mismatch',
242
+ detail: `pin ${num}: schematic has (name "${ap.name}", ${ap.type}), real part has (name "${rp.name}", ${rp.type})`,
243
+ });
244
+ }
245
+ }
246
+ }
247
+ return { findings, checked, skipped };
248
+ }
@@ -34,7 +34,161 @@ export interface TableRow {
34
34
  * Refdes or Pin column, so one check covers both doc types. */
35
35
  export const isHeader = (row: TableRow): boolean =>
36
36
  row.cells.some((c) => /^(refdes|pin)$/i.test(c));
37
-
37
+
38
+ /**
39
+ * Data rows of the CANONICAL table(s) only — those introduced by a Refdes/Pin
40
+ * header row (`isHeader`). BOM.md and PINOUT.md legitimately carry supporting
41
+ * tables (a quiescent-current roll-up, a net-meaning legend); their rows are
42
+ * NOT parts/pins and must never be compared against the schematic. The flat
43
+ * `parseMarkdownTables(md).filter(!isHeader)` does exactly that — it merges
44
+ * every table's rows — so a second table's first cell gets read as a refdes and
45
+ * flagged "not in schematic", which pushes the agent to degrade good docs into
46
+ * bullet lists just to appease the drift gate.
47
+ *
48
+ * This groups lines into tables (a run of pipe-rows, ended by any non-pipe
49
+ * line), keeps only the groups whose first row is a Refdes/Pin header, and
50
+ * returns those groups' data rows (header dropped). A table with no recognized
51
+ * header — including a bare data-only block — is ignored, preserving the
52
+ * fixed-column contract (design D9) while letting docs hold extra tables.
53
+ */
54
+ export function parseCanonicalRows(md: string): TableRow[] {
55
+ return parseCanonicalTables(md).flatMap((t) => t.rows);
56
+ }
57
+
58
+ /**
59
+ * Like parseCanonicalRows, but keeps each kept table's header row so a caller
60
+ * can resolve columns by *name* instead of a fixed position. PINOUT.md's
61
+ * column count is not fixed in practice: the scaffold writes
62
+ * `Refdes | Pin | Name | Net | Notes`, but a hand- or LLM-authored table may
63
+ * legitimately drop the optional Name/Notes columns and write
64
+ * `Refdes | Pin | Net`. A fixed positional net index then reads the wrong cell
65
+ * and reports every pin as net "NC" against a doc that is in fact correct —
66
+ * a false drift the agent cannot diagnose (the doc plainly shows the net), so
67
+ * it loops on finish forever. Resolving by header name fixes that.
68
+ */
69
+ export function parseCanonicalTables(md: string): Array<{ header: TableRow; rows: TableRow[] }> {
70
+ const groups: TableRow[][] = [];
71
+ let current: TableRow[] | null = null;
72
+ for (const line of md.split('\n')) {
73
+ const t = line.trim();
74
+ if (!t.startsWith('|')) {
75
+ current = null; // a blank or prose line terminates the current table
76
+ continue;
77
+ }
78
+ const cells = t
79
+ .split('|')
80
+ .slice(1, -1)
81
+ .map((c) => c.trim());
82
+ if (cells.every((c) => /^:?-+:?$/.test(c))) continue; // separator row: stays within the table
83
+ if (!current) {
84
+ current = [];
85
+ groups.push(current);
86
+ }
87
+ current.push({ cells });
88
+ }
89
+ const tables: Array<{ header: TableRow; rows: TableRow[] }> = [];
90
+ for (const g of groups) {
91
+ if (g.length && isHeader(g[0]!)) tables.push({ header: g[0]!, rows: g.slice(1) });
92
+ }
93
+ return tables;
94
+ }
95
+
96
+ /**
97
+ * PINOUT.md pin assignments, resolved by column *name* and tolerant of the
98
+ * optional Name/Notes columns (see parseCanonicalTables). Only the canonical
99
+ * table that carries both a Pin and a Net header is read; a supporting table
100
+ * (e.g. a `Net | Role` legend) is ignored. Net names are compared bare, so the
101
+ * common `` `VBUS` `` markdown-backtick styling is stripped — the schematic
102
+ * stores plain net names, and a backtick-only difference is not real drift.
103
+ */
104
+ export function parsePinoutRows(md: string): Array<{ ref: string; pin: string; net: string }> {
105
+ const out: Array<{ ref: string; pin: string; net: string }> = [];
106
+ const strip = (s: string | undefined): string => (s ?? '').replace(/`/g, '').trim();
107
+ for (const { header, rows } of parseCanonicalTables(md)) {
108
+ const col = (re: RegExp): number => header.cells.findIndex((c) => re.test(c));
109
+ const refI = col(/^refdes$/i);
110
+ const pinI = col(/^pin$/i);
111
+ const netI = col(/^net$/i);
112
+ if (pinI < 0 || netI < 0) continue; // not the pin-assignment table
113
+ for (const row of rows) {
114
+ out.push({
115
+ ref: refI >= 0 ? strip(row.cells[refI]) : '',
116
+ pin: strip(row.cells[pinI]),
117
+ net: strip(row.cells[netI]),
118
+ });
119
+ }
120
+ }
121
+ return out;
122
+ }
123
+
124
+ /**
125
+ * Fold the semantically-identical encodings that the model and KiCad render
126
+ * differently, so a value that differs only in *encoding* is not flagged as
127
+ * drift (#I11). A design that reached ERC-clean once churned for turns on
128
+ * `Ihold≥3A` vs `Ihold>=3A` and `0.1"` vs `0.1in` — byte differences with zero
129
+ * electrical meaning. Folded here: ≥/>=, ≤/<=, Ω/ohm(s), µ/μ/u, smart quotes,
130
+ * and the inch mark (`"` / `″` / a trailing `in`/`inch` after a number). NFKC
131
+ * first collapses width/compatibility variants; the explicit rules cover the
132
+ * cases NFKC leaves alone (≥, smart quotes, the ohm/inch words).
133
+ */
134
+ export function foldEncodings(s: string | undefined): string {
135
+ if (!s) return '';
136
+ return s
137
+ .normalize('NFKC')
138
+ .replace(/≥/g, '>=')
139
+ .replace(/≤/g, '<=')
140
+ .replace(/[ΩΩ]/g, 'ohm') // ohm sign U+2126 / greek capital omega U+03A9
141
+ .replace(/\bohms\b/gi, 'ohm')
142
+ .replace(/[µμ]/g, 'u') // micro sign U+00B5 / greek small mu U+03BC
143
+ .replace(/[“”″]/g, '"') // smart double quotes and double-prime → "
144
+ .replace(/[‘’′]/g, "'") // smart single quotes and prime → '
145
+ .replace(/(?<=[\d.])\s*(?:inches|inch|in)\b/gi, '"') // 0.1in / 0.1 inch → 0.1"
146
+ .trim();
147
+ }
148
+
149
+ /**
150
+ * Value-cell equality key: `foldEncodings` plus case- and whitespace-folding.
151
+ * Used to compare BOM.md value/footprint cells against schematic symbol values
152
+ * so an encoding/case/spacing-only difference is not reported as drift.
153
+ */
154
+ export function normalizeValue(s: string | undefined): string {
155
+ return foldEncodings(s).replace(/\s+/g, '').toLowerCase();
156
+ }
157
+
158
+ /**
159
+ * Footprint equality key: like `normalizeValue` but WITHOUT case-folding (F6).
160
+ * A footprint is a KiCad library reference (`Resistor_SMD:R_0603_1608Metric`)
161
+ * whose casing is significant — `R_0603` and `r_0603` are not the same library
162
+ * id — so lowercasing it would hide a real footprint difference. Encoding and
163
+ * spacing are still folded (a stray space or unicode variant is not real drift).
164
+ */
165
+ export function normalizeFootprint(s: string | undefined): string {
166
+ return foldEncodings(s).replace(/\s+/g, '');
167
+ }
168
+
169
+ /**
170
+ * Which of the canonical pin-assignment columns PINOUT.md actually provides.
171
+ * `checkDrift` uses this to emit ONE explicit "no Net column" message when the
172
+ * doc omits the column entirely, instead of silently checking nothing (a
173
+ * correct doc then looks unverified) or — the old positional bug (#I12) —
174
+ * reading the wrong cell and reporting every pin as a false `NC` mismatch.
175
+ * `hasTable` is false when the doc has no Refdes/Pin-headed table at all.
176
+ */
177
+ export function pinoutColumnReport(md: string): { hasTable: boolean; pin: boolean; net: boolean; refdes: boolean } {
178
+ let hasTable = false;
179
+ let pin = false;
180
+ let net = false;
181
+ let refdes = false;
182
+ for (const { header } of parseCanonicalTables(md)) {
183
+ hasTable = true;
184
+ const has = (re: RegExp): boolean => header.cells.some((c) => re.test(c));
185
+ if (has(/^pin$/i)) pin = true;
186
+ if (has(/^net$/i)) net = true;
187
+ if (has(/^refdes$/i)) refdes = true;
188
+ }
189
+ return { hasTable, pin, net, refdes };
190
+ }
191
+
38
192
  /**
39
193
  * A typed BOM.md data row, per the fixed column contract that `init` writes
40
194
  * (Refdes | Value | Footprint | MPN | Rationale — see scaffold.ts's
@@ -51,28 +205,45 @@ export interface TableRow {
51
205
  }
52
206
 
53
207
  /**
54
- * Parses BOM.md's data rows into typed rows. Rows without a refdes in
55
- * column 1 are dropped rather than thrown on: a hand-edited doc with a
56
- * ragged or partial table shouldn't crash `check` or `export bom`, it
57
- * should just be skipped (drift/export callers report the gaps that
58
- * matter through their own comparisons against the schematic).
208
+ * Parses BOM.md's data rows into typed rows. Columns are resolved by header
209
+ * *name* (Refdes/Value/Footprint/MPN), falling back to the canonical position
210
+ * when a header is absent the same header-name discipline `parsePinoutRows`
211
+ * uses (#I12), so a doc that reorders or drops an optional column is still read
212
+ * correctly instead of silently shifting every cell. Rows without a refdes are
213
+ * dropped rather than thrown on: a hand-edited doc with a ragged or partial
214
+ * table shouldn't crash `check` or `export bom`, it should just be skipped
215
+ * (drift/export callers report the gaps that matter against the schematic).
59
216
  */
60
217
  export function parseBomTable(md: string): BomRow[] {
61
- const rows = parseMarkdownTables(md).filter((r) => !isHeader(r));
62
218
  const out: BomRow[] = [];
63
- for (const row of rows) {
64
- const [refdes, value, footprint, mpn] = row.cells;
65
- if (!refdes) continue;
66
- const flags: string[] = [];
67
- if (mpn === 'UNVERIFIED') flags.push('UNVERIFIED');
68
- else if (!mpn) flags.push('MISSING_MPN');
69
- out.push({
70
- refdes,
71
- value: value || undefined,
72
- footprint: footprint || undefined,
73
- mpn: mpn || undefined,
74
- flags,
75
- });
219
+ for (const { header, rows } of parseCanonicalTables(md)) {
220
+ // Resolve by header name; -1 means "not found", so fall back to the
221
+ // canonical index for that column (Refdes 0, Value 1, Footprint 2, MPN 3).
222
+ const col = (re: RegExp, fallback: number): number => {
223
+ const i = header.cells.findIndex((c) => re.test(c));
224
+ return i >= 0 ? i : fallback;
225
+ };
226
+ const refI = col(/^refdes$/i, 0);
227
+ const valI = col(/^value$/i, 1);
228
+ const fpI = col(/^footprint$/i, 2);
229
+ const mpnI = col(/^mpn$/i, 3);
230
+ for (const row of rows) {
231
+ const refdes = row.cells[refI];
232
+ if (!refdes) continue;
233
+ const value = row.cells[valI];
234
+ const footprint = row.cells[fpI];
235
+ const mpn = row.cells[mpnI];
236
+ const flags: string[] = [];
237
+ if (mpn === 'UNVERIFIED') flags.push('UNVERIFIED');
238
+ else if (!mpn) flags.push('MISSING_MPN');
239
+ out.push({
240
+ refdes,
241
+ value: value || undefined,
242
+ footprint: footprint || undefined,
243
+ mpn: mpn || undefined,
244
+ flags,
245
+ });
246
+ }
76
247
  }
77
248
  return out;
78
249
  }
@@ -2,7 +2,14 @@ import { readFile } from 'node:fs/promises';
2
2
  import { existsSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { listSymbols, pinNets, type SchematicSymbol } from '../kicad/sexp.js';
5
- import { parseMarkdownTables, isHeader } from './bom-table.js';
5
+ import {
6
+ parseCanonicalRows,
7
+ parseBomTable,
8
+ parsePinoutRows,
9
+ pinoutColumnReport,
10
+ normalizeValue,
11
+ normalizeFootprint,
12
+ } from './bom-table.js';
6
13
 
7
14
  /**
8
15
  * Doc-vs-schematic drift check (AC-2.3). BOM.md and PINOUT.md use fixed table
@@ -31,8 +38,7 @@ export async function emptySchematicWarning(
31
38
  if (symbols.length) return null;
32
39
  const bomPath = path.join(repoRoot, docsDir, 'BOM.md');
33
40
  if (!existsSync(bomPath)) return null;
34
- const refs = parseMarkdownTables(await readFile(bomPath, 'utf8'))
35
- .filter((r) => !isHeader(r))
41
+ const refs = parseCanonicalRows(await readFile(bomPath, 'utf8'))
36
42
  .map((r) => r.cells[0])
37
43
  .filter(Boolean);
38
44
  if (!refs.length) return null;
@@ -54,10 +60,11 @@ export async function checkDrift(repoRoot: string, docsDir: string, schematic: s
54
60
 
55
61
  const bomPath = path.join(repoRoot, docsDir, 'BOM.md');
56
62
  if (existsSync(bomPath)) {
57
- const rows = parseMarkdownTables(await readFile(bomPath, 'utf8')).filter((r) => !isHeader(r));
63
+ // Resolve BOM columns by header name via the shared parseBomTable (F5), so
64
+ // the drift reader and `export bom` never disagree on a reordered table.
65
+ const rows = parseBomTable(await readFile(bomPath, 'utf8'));
58
66
  const seen = new Set<string>();
59
- for (const row of rows) {
60
- const [ref, value, footprint] = row.cells;
67
+ for (const { refdes: ref, value, footprint } of rows) {
61
68
  if (!ref) continue;
62
69
  seen.add(ref);
63
70
  const sym = byRef.get(ref);
@@ -65,10 +72,18 @@ export async function checkDrift(repoRoot: string, docsDir: string, schematic: s
65
72
  mismatches.push({ doc: 'BOM.md', claim: `${ref} exists`, actual: `${ref} not in schematic` });
66
73
  continue;
67
74
  }
68
- if (value !== undefined && value !== sym.value) {
75
+ // Compare on the semantic value, not the byte-exact string: `Ihold≥3A` and
76
+ // `Ihold>=3A` are the same value written two ways (#I11). Raw `!==` flagged
77
+ // them as drift and whack-a-moled the agent across finish attempts.
78
+ if (value !== undefined && normalizeValue(value) !== normalizeValue(sym.value)) {
69
79
  mismatches.push({ doc: 'BOM.md', claim: `${ref} value ${value}`, actual: `${ref} value ${sym.value}` });
70
80
  }
71
- if (footprint !== undefined && footprint !== '' && footprint !== sym.footprint) {
81
+ // Footprint compare folds encoding/spacing but keeps case (F6): a footprint
82
+ // library id is case-sensitive, so lowercasing would hide a real mismatch.
83
+ if (
84
+ footprint !== undefined &&
85
+ normalizeFootprint(footprint) !== normalizeFootprint(sym.footprint)
86
+ ) {
72
87
  mismatches.push({
73
88
  doc: 'BOM.md',
74
89
  claim: `${ref} footprint ${footprint}`,
@@ -85,11 +100,27 @@ export async function checkDrift(repoRoot: string, docsDir: string, schematic: s
85
100
 
86
101
  const pinoutPath = path.join(repoRoot, docsDir, 'PINOUT.md');
87
102
  if (existsSync(pinoutPath)) {
103
+ const pinoutMd = await readFile(pinoutPath, 'utf8');
88
104
  const nets = await pinNets(schPath);
89
105
  const netOf = new Map(nets.map((p) => [`${p.ref}:${p.pinNumber}`, p.net]));
90
- const rows = parseMarkdownTables(await readFile(pinoutPath, 'utf8')).filter((r) => !isHeader(r));
91
- for (const row of rows) {
92
- const [ref, pinNumber, , net] = row.cells;
106
+ // If the doc has a Refdes/Pin table but no Net column, say so once and
107
+ // explicitly, rather than silently checking nothing (a correct doc then
108
+ // reads as unverified) the counterpart to the old positional bug that
109
+ // reported every pin as a false NC (#I12). This tells the model what to fix
110
+ // (add the column) instead of leaving it guessing why nets aren't verified.
111
+ const cols = pinoutColumnReport(pinoutMd);
112
+ if (cols.hasTable && !cols.net) {
113
+ mismatches.push({
114
+ doc: 'PINOUT.md',
115
+ claim: 'the pin table has a Net column (expected header: Refdes | Pin | Net)',
116
+ actual: 'no Net column in the pin table, so pin-to-net assignments cannot be checked; add a Net column',
117
+ });
118
+ }
119
+ // Resolve columns by header name, not position: the PINOUT table may be
120
+ // `Refdes | Pin | Net` or the scaffold's `Refdes | Pin | Name | Net | Notes`.
121
+ // A fixed net index read every pin as "NC" on the 3-column form (#I12).
122
+ const rows = parsePinoutRows(pinoutMd);
123
+ for (const { ref, pin: pinNumber, net } of rows) {
93
124
  if (!ref || !pinNumber) continue;
94
125
  const k = `${ref}:${pinNumber}`;
95
126
  if (!netOf.has(k)) {
package/src/util/git.ts CHANGED
@@ -1,10 +1,44 @@
1
1
  import { execa } from 'execa';
2
- import { cp, mkdir, mkdtemp, rm } from 'node:fs/promises';
2
+ import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
3
3
  import { existsSync } from 'node:fs';
4
4
  import { tmpdir } from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { PreflightError } from './preflight.js';
7
7
 
8
+ /**
9
+ * Paths copperhead must keep out of `git add -A`. KiCad ≥9 writes a
10
+ * git-backed local-history directory (`.history/`, complete with its own nested
11
+ * `.git`) into the project the first time kicad-cli touches it. Left untracked,
12
+ * that nested repo has an unborn HEAD, so a plain `git add -A` in the parent
13
+ * aborts with `error: '.history/' does not have a commit checked out` (exit
14
+ * 128) — which fails the commit at the end of every KiCad-touching stage
15
+ * (schematic, layout, outputs). Ignoring it is both correct (local history is
16
+ * never a project artifact) and the fix for that abort. Kept as a list so other
17
+ * KiCad transients can join it if they surface.
18
+ */
19
+ const GIT_ADD_EXCLUDES = ['.history/'];
20
+
21
+ /**
22
+ * Ensure the repo's root .gitignore lists each entry, appending only the
23
+ * missing ones. Idempotent and best-effort: a failure here must never block a
24
+ * commit, so it swallows its own errors. Run before any `git add -A` so a
25
+ * git-backed KiCad `.history/` (or similar nested repo) is skipped instead of
26
+ * aborting the add.
27
+ */
28
+ export async function ensureIgnored(repo: string, entries: string[]): Promise<void> {
29
+ try {
30
+ const p = path.join(repo, '.gitignore');
31
+ const text = existsSync(p) ? await readFile(p, 'utf8') : '';
32
+ const present = new Set(text.split('\n').map((l) => l.trim()));
33
+ const missing = entries.filter((e) => !present.has(e));
34
+ if (!missing.length) return;
35
+ const prefix = text.length && !text.endsWith('\n') ? '\n' : '';
36
+ await writeFile(p, text + prefix + missing.join('\n') + '\n', 'utf8');
37
+ } catch {
38
+ // best-effort: .gitignore maintenance must never be the thing that fails a run
39
+ }
40
+ }
41
+
8
42
  export interface GitSnapshot {
9
43
  head: string;
10
44
  stash: string | null;
@@ -147,6 +181,7 @@ export async function restore(repo: string, snap: GitSnapshot): Promise<void> {
147
181
  export async function preserveFailedRun(repo: string, runId: string): Promise<string | null> {
148
182
  try {
149
183
  if (!(await isDirty(repo))) return null;
184
+ await ensureIgnored(repo, GIT_ADD_EXCLUDES);
150
185
  // Never leave the audit trail staged: a staged-but-not-in-HEAD path is
151
186
  // deleted by restore()'s `reset --hard`, which silently defeats its
152
187
  // `clean -e .copperhead/runs` protection (that flag only spares untracked
@@ -181,6 +216,7 @@ export async function uncommittedCount(repo: string): Promise<number> {
181
216
  }
182
217
 
183
218
  export async function commitAll(repo: string, message: string): Promise<string> {
219
+ await ensureIgnored(repo, GIT_ADD_EXCLUDES);
184
220
  await git(repo, ['add', '-A']);
185
221
  await git(repo, ['commit', '-m', message]);
186
222
  return git(repo, ['rev-parse', 'HEAD']);