copperhead 0.5.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 (74) hide show
  1. package/README.md +34 -1
  2. package/dist/agent/loop.js +130 -15
  3. package/dist/agent/loop.js.map +1 -1
  4. package/dist/agent/prompts.js +2 -1
  5. package/dist/agent/prompts.js.map +1 -1
  6. package/dist/agent/providers/claude-code.js +466 -0
  7. package/dist/agent/providers/claude-code.js.map +1 -0
  8. package/dist/agent/providers/openai.js +30 -10
  9. package/dist/agent/providers/openai.js.map +1 -1
  10. package/dist/agent/recovery.js +148 -0
  11. package/dist/agent/recovery.js.map +1 -0
  12. package/dist/agent/render.js +17 -2
  13. package/dist/agent/render.js.map +1 -1
  14. package/dist/agent/response-cache.js +81 -0
  15. package/dist/agent/response-cache.js.map +1 -0
  16. package/dist/agent/tools.js +61 -4
  17. package/dist/agent/tools.js.map +1 -1
  18. package/dist/agent/transcript.js.map +1 -1
  19. package/dist/cli.js +47 -2
  20. package/dist/cli.js.map +1 -1
  21. package/dist/commands/create.js +486 -35
  22. package/dist/commands/create.js.map +1 -1
  23. package/dist/commands/export.js +90 -0
  24. package/dist/commands/export.js.map +1 -0
  25. package/dist/config.js +33 -6
  26. package/dist/config.js.map +1 -1
  27. package/dist/kicad/bom-export.js +240 -0
  28. package/dist/kicad/bom-export.js.map +1 -0
  29. package/dist/kicad/bootstrap.js +166 -0
  30. package/dist/kicad/bootstrap.js.map +1 -0
  31. package/dist/kicad/fab.js +94 -0
  32. package/dist/kicad/fab.js.map +1 -0
  33. package/dist/kicad/spice.js +306 -0
  34. package/dist/kicad/spice.js.map +1 -0
  35. package/dist/kicad/symlib.js +228 -0
  36. package/dist/kicad/symlib.js.map +1 -0
  37. package/dist/memory/bom-table.js +232 -0
  38. package/dist/memory/bom-table.js.map +1 -0
  39. package/dist/memory/drift.js +33 -27
  40. package/dist/memory/drift.js.map +1 -1
  41. package/dist/util/git.js +37 -1
  42. package/dist/util/git.js.map +1 -1
  43. package/dist/util/preflight.js +37 -0
  44. package/dist/util/preflight.js.map +1 -1
  45. package/dist/util/retry.js +23 -0
  46. package/dist/util/retry.js.map +1 -1
  47. package/dist/util/tmp.js +119 -0
  48. package/dist/util/tmp.js.map +1 -0
  49. package/package.json +6 -2
  50. package/src/agent/loop.ts +148 -15
  51. package/src/agent/prompts.ts +2 -1
  52. package/src/agent/providers/claude-code.ts +550 -0
  53. package/src/agent/providers/openai.ts +33 -16
  54. package/src/agent/recovery.ts +162 -0
  55. package/src/agent/render.ts +28 -1
  56. package/src/agent/response-cache.ts +80 -0
  57. package/src/agent/tools.ts +62 -4
  58. package/src/agent/transcript.ts +1 -0
  59. package/src/agent/types.ts +18 -0
  60. package/src/cli.ts +52 -2
  61. package/src/commands/create.ts +543 -38
  62. package/src/commands/export.ts +117 -0
  63. package/src/config.ts +54 -6
  64. package/src/kicad/bom-export.ts +321 -0
  65. package/src/kicad/bootstrap.ts +181 -0
  66. package/src/kicad/fab.ts +121 -0
  67. package/src/kicad/spice.ts +399 -0
  68. package/src/kicad/symlib.ts +248 -0
  69. package/src/memory/bom-table.ts +249 -0
  70. package/src/memory/drift.ts +42 -32
  71. package/src/util/git.ts +37 -1
  72. package/src/util/preflight.ts +44 -0
  73. package/src/util/retry.ts +29 -0
  74. package/src/util/tmp.ts +113 -0
@@ -0,0 +1,117 @@
1
+ import path from 'node:path';
2
+ import { existsSync } from 'node:fs';
3
+ import { readFile, writeFile, mkdir } from 'node:fs/promises';
4
+ import { loadConfig } from '../config.js';
5
+ import { checkDrift } from '../memory/drift.js';
6
+ import { buildExport, parseBom, SUPPLIERS, isSupplier, type Supplier, type ExportResult } from '../kicad/bom-export.js';
7
+
8
+ /**
9
+ * `copperhead export bom` (capability supplier-bom-export): deterministic,
10
+ * LLM-free, network-free — safe anywhere `check` is safe. This module must never
11
+ * import a provider.
12
+ */
13
+ export class ExportError extends Error {}
14
+
15
+ export interface ExportBomOptions {
16
+ repoRoot: string;
17
+ supplier: Supplier;
18
+ boards: number;
19
+ spares: number;
20
+ includeUnverified: boolean;
21
+ }
22
+
23
+ export interface ExportBomResult extends ExportResult {
24
+ supplier: Supplier;
25
+ /** Repo-relative path the CSV was written to. */
26
+ outPath: string;
27
+ }
28
+
29
+ const OUT_DIR = 'outputs';
30
+
31
+ export function outFileFor(supplier: Supplier): string {
32
+ return path.join(OUT_DIR, `${supplier}-bom.csv`);
33
+ }
34
+
35
+ /**
36
+ * Read BOM.md, refuse on drift, and write the supplier CSV to
37
+ * outputs/<supplier>-bom.csv. Throws ExportError with an actionable message for
38
+ * the caller to print and exit non-zero.
39
+ */
40
+ export async function runExportBom(opts: ExportBomOptions): Promise<ExportBomResult> {
41
+ const config = await loadConfig(opts.repoRoot);
42
+ const bomPath = path.join(opts.repoRoot, config.docs, 'BOM.md');
43
+ if (!existsSync(bomPath)) {
44
+ throw new ExportError(
45
+ `no ${path.join(config.docs, 'BOM.md')} to export — run copperhead init on an existing project, or copperhead create`,
46
+ );
47
+ }
48
+
49
+ // BOM.md is the sole input, but it must agree with the schematic before it can
50
+ // be trusted as an ordering source (requirement "BOM.md is the sole input").
51
+ // Refuse loudly here rather than let a drifted BOM become a wrong order.
52
+ if (config.schematic && existsSync(path.join(opts.repoRoot, config.schematic))) {
53
+ const drift = await checkDrift(opts.repoRoot, config.docs, config.schematic);
54
+ if (drift.length) {
55
+ const lines = drift.map((m) => ` - ${m.doc} claims "${m.claim}" but actual is "${m.actual}"`).join('\n');
56
+ throw new ExportError(
57
+ `BOM.md drifts from the schematic; run \`copperhead check\` and resolve drift before ordering:\n${lines}`,
58
+ );
59
+ }
60
+ }
61
+
62
+ const rows = parseBom(await readFile(bomPath, 'utf8'));
63
+ const result = buildExport(rows, opts.supplier, {
64
+ boards: opts.boards,
65
+ spares: opts.spares,
66
+ includeUnverified: opts.includeUnverified,
67
+ });
68
+
69
+ const outPath = outFileFor(opts.supplier);
70
+ await mkdir(path.join(opts.repoRoot, OUT_DIR), { recursive: true });
71
+ await writeFile(path.join(opts.repoRoot, outPath), result.csv, 'utf8');
72
+
73
+ return { ...result, supplier: opts.supplier, outPath };
74
+ }
75
+
76
+ /**
77
+ * Deterministically emit the JLCPCB assembly BOM alongside the create stage-6
78
+ * outputs (create-pipeline delta). No-op when there is no BOM.md yet; never
79
+ * throws on drift here — the pipeline's own gates own that.
80
+ */
81
+ export async function emitCreateJlcpcbBom(repoRoot: string): Promise<string | null> {
82
+ const config = await loadConfig(repoRoot);
83
+ const bomPath = path.join(repoRoot, config.docs, 'BOM.md');
84
+ if (!existsSync(bomPath)) return null;
85
+ const rows = parseBom(await readFile(bomPath, 'utf8'));
86
+ const { csv } = buildExport(rows, 'jlcpcb', { boards: 1, spares: 10, includeUnverified: false });
87
+ const outPath = outFileFor('jlcpcb');
88
+ await mkdir(path.join(repoRoot, OUT_DIR), { recursive: true });
89
+ await writeFile(path.join(repoRoot, outPath), csv, 'utf8');
90
+ return outPath;
91
+ }
92
+
93
+ /** Validate `--supplier`; throws ExportError listing the supported values. */
94
+ export function parseSupplier(value: string): Supplier {
95
+ if (!isSupplier(value)) {
96
+ throw new ExportError(`unknown supplier "${value}"; supported: ${SUPPLIERS.join(', ')}`);
97
+ }
98
+ return value;
99
+ }
100
+
101
+ /** Validate `--boards`: a positive integer. */
102
+ export function parseBoards(value: string): number {
103
+ const n = Number(value);
104
+ if (!Number.isInteger(n) || n < 1) {
105
+ throw new ExportError(`--boards must be a positive integer, got "${value}"`);
106
+ }
107
+ return n;
108
+ }
109
+
110
+ /** Validate `--spares`: a non-negative percentage. */
111
+ export function parseSpares(value: string): number {
112
+ const n = Number(value);
113
+ if (!Number.isFinite(n) || n < 0) {
114
+ throw new ExportError(`--spares must be a non-negative number, got "${value}"`);
115
+ }
116
+ return n;
117
+ }
package/src/config.ts CHANGED
@@ -12,8 +12,28 @@ export interface CopperheadConfig {
12
12
  stageMaxTurns?: Record<string, number>;
13
13
  maxRepairCycles: number;
14
14
  budgets: Record<string, number>;
15
+ /** Per-turn watchdog (ms). A provider turn exceeding this is aborted and
16
+ * retried, so a hung call can't stall the run forever. <=0 disables it. */
17
+ turnTimeoutMs: number;
18
+ /** How often (ms) to emit a liveness heartbeat while a provider turn is in
19
+ * flight, so a slow large-output turn is distinguishable from a hung one
20
+ * (5.1). Fires only after the first interval, so quick turns stay silent.
21
+ * <=0 disables it. */
22
+ heartbeatMs: number;
23
+ /** How many times the create pipeline may auto-retry a stage that failed or
24
+ * ended without meeting its contract, gated by an LLM diagnosis each time. */
25
+ maxStageRetries: number;
26
+ /** Cache each turn's LLM response to disk and replay it on identical inputs,
27
+ * so retries/restarts reuse work already paid for. Default on. */
28
+ llmCache: boolean;
15
29
  /** Content hashes of generated docs, for init idempotency (AC-1.4). */
16
30
  generatedHashes?: Record<string, string>;
31
+ /**
32
+ * How the repo was bootstrapped. `"create"` marks a Mode A pipeline repo
33
+ * (fab gate requires DEVPLAN.md). Written by `copperhead create`; absent on
34
+ * init-only / hand-maintained repos.
35
+ */
36
+ origin?: 'create' | 'init';
17
37
  }
18
38
 
19
39
  export const CONFIG_DIR = '.copperhead';
@@ -24,6 +44,19 @@ export const DEFAULTS: Omit<CopperheadConfig, 'schematic' | 'board'> = {
24
44
  maxTurns: 40,
25
45
  maxRepairCycles: 5,
26
46
  budgets: {},
47
+ // 10 min. A single large capture turn (a full lib_symbols + instances edit,
48
+ // ~40k output tokens) on the claude-code provider legitimately runs several
49
+ // minutes; the old 5-min deadline killed those mid-flight and, because the
50
+ // watchdog budget is spent per stage, could fail a stage that was only slow,
51
+ // not hung. 10 min clears the largest observed turns while still catching a
52
+ // genuinely stuck subprocess.
53
+ turnTimeoutMs: 600000,
54
+ // 30s: within one interval an operator knows a turn is alive, and a full
55
+ // 10-min turn emits ~20 lines — enough to distinguish slow from hung without
56
+ // flooding the log. Quick turns (< 30s) emit nothing.
57
+ heartbeatMs: 30000,
58
+ maxStageRetries: 2,
59
+ llmCache: true,
27
60
  };
28
61
 
29
62
  export function configPath(repoRoot: string): string {
@@ -50,7 +83,15 @@ export async function loadConfig(repoRoot: string): Promise<CopperheadConfig> {
50
83
  ...(Object.keys(stageMaxTurns).length ? { stageMaxTurns } : {}),
51
84
  maxRepairCycles: raw.maxRepairCycles ?? DEFAULTS.maxRepairCycles,
52
85
  budgets: raw.budgets ?? {},
86
+ turnTimeoutMs: typeof raw.turnTimeoutMs === 'number' ? raw.turnTimeoutMs : DEFAULTS.turnTimeoutMs,
87
+ heartbeatMs: typeof raw.heartbeatMs === 'number' ? raw.heartbeatMs : DEFAULTS.heartbeatMs,
88
+ maxStageRetries:
89
+ Number.isInteger(raw.maxStageRetries) && (raw.maxStageRetries as number) >= 0
90
+ ? (raw.maxStageRetries as number)
91
+ : DEFAULTS.maxStageRetries,
92
+ llmCache: raw.llmCache !== false,
53
93
  ...(raw.generatedHashes ? { generatedHashes: raw.generatedHashes } : {}),
94
+ ...(raw.origin === 'create' || raw.origin === 'init' ? { origin: raw.origin } : {}),
54
95
  };
55
96
  }
56
97
 
@@ -70,8 +111,12 @@ export interface ResolvedModel {
70
111
  * Accepted values (same set for `--model`, COPPERHEAD_MODEL, and `model` in
71
112
  * .copperhead/config.json):
72
113
  *
73
- * - `claude` : the Anthropic provider on its default model.
74
- * - `claude-*`: any Anthropic model id, passed through verbatim, e.g.
114
+ * - `claude-code` : the Claude Code saved-login provider on its default
115
+ * model. Needs NO API key it reuses the logged-in Claude
116
+ * Code CLI / CLAUDE_CODE_OAUTH_TOKEN via the Agent SDK.
117
+ * - `claude-code:<id>`: the same provider on a specific model id.
118
+ * - `claude` : the Anthropic API provider on its default model.
119
+ * - `claude-*`: any Anthropic API model id, passed through verbatim, e.g.
75
120
  * `claude-opus-4-5`. Anything starting with `claude` routes here.
76
121
  * - `codex` : the locally installed Codex CLI using its saved ChatGPT login.
77
122
  * - `codex:*` : Codex CLI with an explicit model id, e.g. `codex:gpt-5.6`.
@@ -80,10 +125,13 @@ export interface ResolvedModel {
80
125
  * `gpt-5-mini` or `o3`.
81
126
  *
82
127
  * Routing is prefix-based, not a fixed list (see makeProvider in agent/loop.ts),
83
- * so a model released after this build still works without a code change. The
84
- * cost is that a typo like `claud-sonnet-5` silently routes to OpenAI and fails
85
- * there. Anthropic and direct OpenAI providers require their API keys; `codex`
86
- * instead requires a locally installed and authenticated Codex CLI.
128
+ * matched top to bottom: `claude-code`/`claude-code:<id>` is checked BEFORE the
129
+ * `claude*` prefix, so it is never captured by the Anthropic API route. A model
130
+ * released after this build still works without a code change. The cost is that
131
+ * a typo like `claud-sonnet-5` silently routes to OpenAI and fails there.
132
+ * Anthropic and direct OpenAI providers require their API keys; `codex` requires
133
+ * a locally installed and authenticated Codex CLI, and `claude-code` requires a
134
+ * Claude Code login (CLAUDE_CODE_OAUTH_TOKEN); neither needs a model API key.
87
135
  */
88
136
  export function resolveModel(flag: string | undefined, config: CopperheadConfig, env = process.env): ResolvedModel {
89
137
  if (flag) return { model: flag, source: 'flag' };
@@ -0,0 +1,321 @@
1
+ import { parseMarkdownTables, type TableRow } from '../memory/bom-table.js';
2
+
3
+ /**
4
+ * Supplier-format BOM export (capability supplier-bom-export). Deterministic,
5
+ * LLM-free, network-free: a pure transformation of BOM.md into files a supplier
6
+ * accepts without hand-editing. BOM.md is the sole input (design D1) — it is
7
+ * already drift-checked against the schematic, so exports inherit that
8
+ * consistency guarantee.
9
+ */
10
+
11
+ export type Supplier = 'jlcpcb' | 'digikey' | 'mouser';
12
+
13
+ export const SUPPLIERS: readonly Supplier[] = ['jlcpcb', 'digikey', 'mouser'];
14
+
15
+ /** CLI defaults for the quantity flags, shared so the "ignored for jlcpcb"
16
+ * note fires only when the user actually set a non-default value. */
17
+ export const DEFAULT_BOARDS = 1;
18
+ export const DEFAULT_SPARES = 10;
19
+
20
+ export function isSupplier(s: string): s is Supplier {
21
+ return (SUPPLIERS as readonly string[]).includes(s);
22
+ }
23
+
24
+ export interface BomRow {
25
+ refdes: string;
26
+ value: string;
27
+ footprint: string;
28
+ /** MPN column value as written (may be a placeholder like "UNVERIFIED"). */
29
+ mpn: string;
30
+ manufacturer: string;
31
+ /** LCSC part number when a column carries it, else ''. */
32
+ lcsc: string;
33
+ /** True when any cell carries the standalone token UNVERIFIED. */
34
+ unverified: boolean;
35
+ /** True when the MPN column carries an orderable part number (not a placeholder). */
36
+ hasMpn: boolean;
37
+ }
38
+
39
+ // Header aliases → canonical field. Matched after normalizing a header cell to
40
+ // lowercase alphanumerics, so "LCSC Part #" and "lcsc_part" both hit `lcsc`.
41
+ const HEADER_ALIASES: Record<string, keyof Pick<BomRow, 'refdes' | 'value' | 'footprint' | 'mpn' | 'manufacturer' | 'lcsc'>> = {
42
+ refdes: 'refdes',
43
+ ref: 'refdes',
44
+ designator: 'refdes',
45
+ reference: 'refdes',
46
+ value: 'value',
47
+ comment: 'value',
48
+ val: 'value',
49
+ footprint: 'footprint',
50
+ package: 'footprint',
51
+ mpn: 'mpn',
52
+ manufacturerpartnumber: 'mpn',
53
+ mfrpartnumber: 'mpn',
54
+ mfrpart: 'mpn',
55
+ partnumber: 'mpn',
56
+ manufacturer: 'manufacturer',
57
+ mfr: 'manufacturer',
58
+ lcsc: 'lcsc',
59
+ lcscpart: 'lcsc',
60
+ lcscpartnumber: 'lcsc',
61
+ };
62
+
63
+ const norm = (s: string): string => s.toLowerCase().replace(/[^a-z0-9]/g, '');
64
+
65
+ // MPN cells that mean "no orderable part number yet". `UNVERIFIED` is the
66
+ // init/scaffold placeholder (src/memory/scaffold.ts writes it into the MPN
67
+ // column for every extracted symbol); the rest are common human shorthand.
68
+ const MPN_PLACEHOLDERS = new Set(['', 'unverified', 'tbd', 'todo', 'tbc', 'na', 'none', '-', '—', '?']);
69
+
70
+ const isMpnPlaceholder = (mpn: string): boolean => MPN_PLACEHOLDERS.has(mpn.trim().toLowerCase());
71
+
72
+ const UNVERIFIED_RE = /\bUNVERIFIED\b/i;
73
+
74
+ /**
75
+ * Parse BOM.md into rows by column header, tolerating extra/reordered columns.
76
+ * Only the header row and data rows of the first parts table are used; a table
77
+ * without a recognizable Refdes header yields no rows.
78
+ *
79
+ * NOTE: the drift gate this exporter runs behind (checkDrift in
80
+ * ../memory/drift.ts) reads Refdes|Value|Footprint *by position*, not by header.
81
+ * So while this parser tolerates reordering those base columns, reordering them
82
+ * makes checkDrift compare the wrong cells and the export refuses with a bogus
83
+ * drift message. Keep the base three columns first and in order; only append.
84
+ */
85
+ export function parseBom(md: string): BomRow[] {
86
+ const tableRows = parseMarkdownTables(md);
87
+ const headerIdx = tableRows.findIndex((r) => r.cells.some((c) => HEADER_ALIASES[norm(c)] === 'refdes'));
88
+ const header = headerIdx === -1 ? undefined : tableRows[headerIdx];
89
+ if (!header) return [];
90
+ const col: Partial<Record<keyof BomRow, number>> = {};
91
+ header.cells.forEach((c, i) => {
92
+ const field = HEADER_ALIASES[norm(c)];
93
+ // First occurrence wins, so a stray later column never shadows the real one.
94
+ if (field && col[field] === undefined) col[field] = i;
95
+ });
96
+
97
+ const at = (row: TableRow, field: keyof BomRow): string => {
98
+ const i = col[field];
99
+ return i === undefined ? '' : (row.cells[i] ?? '').trim();
100
+ };
101
+
102
+ const rows: BomRow[] = [];
103
+ for (const row of tableRows.slice(headerIdx + 1)) {
104
+ const refdes = at(row, 'refdes');
105
+ if (!refdes) continue; // blank line / stray row
106
+ const mpn = at(row, 'mpn');
107
+ rows.push({
108
+ refdes,
109
+ value: at(row, 'value'),
110
+ footprint: at(row, 'footprint'),
111
+ mpn,
112
+ manufacturer: at(row, 'manufacturer'),
113
+ lcsc: at(row, 'lcsc'),
114
+ unverified: row.cells.some((c) => UNVERIFIED_RE.test(c)),
115
+ hasMpn: !isMpnPlaceholder(mpn),
116
+ });
117
+ }
118
+ return rows;
119
+ }
120
+
121
+ /**
122
+ * Passive footprint classifier (design D4): the library item after the `:` in a
123
+ * KiCad footprint id starts with `R_`, `C_`, or `L_` for the passive classes
124
+ * that lose parts to handling. Bare footprint names (no library) are matched
125
+ * too, so `R_0603` and `Resistor_SMD:R_0603_1608Metric` both classify.
126
+ */
127
+ export function isPassiveFootprint(footprint: string): boolean {
128
+ const item = footprint.includes(':') ? footprint.slice(footprint.lastIndexOf(':') + 1) : footprint;
129
+ return /^[RCL]_/.test(item.trim());
130
+ }
131
+
132
+ /**
133
+ * Order quantity for one BOM line (requirement "Quantity arithmetic"):
134
+ * `ceil(perBoardCount × boards × (1 + spares/100))`, raised to
135
+ * `perBoardCount × boards + 2` for passive lines when the percentage yields
136
+ * less — losing two 0402s to tweezers is the norm and percentage-only spares
137
+ * under-order low-count passive lines (design D4).
138
+ */
139
+ export function orderQuantity(
140
+ perBoardCount: number,
141
+ boards: number,
142
+ sparesPercent: number,
143
+ isPassive: boolean,
144
+ ): number {
145
+ const base = perBoardCount * boards;
146
+ // `base * (100 + spares) / 100` keeps the multiply in whole units before the
147
+ // divide, and the epsilon absorbs IEEE-754 dust so an exact result like 110
148
+ // does not ceil to 111 (100 × 1.1 is 110.00000000000001 in float). The dust is
149
+ // ~1e-13; 1e-9 is far below any real fractional quantity, so genuine fractions
150
+ // (44.5 → 45) are unaffected.
151
+ const withSpares = Math.ceil((base * (100 + sparesPercent)) / 100 - 1e-9);
152
+ return isPassive ? Math.max(withSpares, base + 2) : withSpares;
153
+ }
154
+
155
+ /** Natural refdes ordering: R2 before R10, and R* before U*. */
156
+ function naturalCompare(a: string, b: string): number {
157
+ const pa = a.match(/^([A-Za-z]*)(\d*)/);
158
+ const pb = b.match(/^([A-Za-z]*)(\d*)/);
159
+ const alpha = (pa?.[1] ?? '').localeCompare(pb?.[1] ?? '');
160
+ if (alpha !== 0) return alpha;
161
+ const na = pa?.[2] ? parseInt(pa[2], 10) : 0;
162
+ const nb = pb?.[2] ? parseInt(pb[2], 10) : 0;
163
+ if (na !== nb) return na - nb;
164
+ return a.localeCompare(b);
165
+ }
166
+
167
+ /** RFC-4180 field quoting: quote when the field holds a comma, quote, or newline. */
168
+ function csvField(value: string): string {
169
+ return /[",\n\r]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
170
+ }
171
+
172
+ const csvRow = (fields: string[]): string => fields.map(csvField).join(',');
173
+
174
+ export interface ExportOptions {
175
+ boards: number;
176
+ spares: number;
177
+ includeUnverified: boolean;
178
+ }
179
+
180
+ export interface ExportResult {
181
+ /** The supplier CSV, ending in a newline. */
182
+ csv: string;
183
+ /** Rows that made it into the file, in emit order. */
184
+ included: BomRow[];
185
+ /** Rows excluded, with the reason, for the warnings footer. */
186
+ excluded: { row: BomRow; reason: string }[];
187
+ /** Human-readable warning/notice lines (stderr + --json). */
188
+ warnings: string[];
189
+ }
190
+
191
+ interface Line {
192
+ rows: BomRow[];
193
+ /** Representative row (first, in refdes order) for value/footprint/mpn/etc. */
194
+ head: BomRow;
195
+ designators: string[];
196
+ }
197
+
198
+ /**
199
+ * Split rows into included/excluded by the ordering rules (requirement
200
+ * "Unorderable rows are excluded and reported"): MPN-less rows are always
201
+ * excluded; UNVERIFIED rows are excluded unless `includeUnverified`, and even
202
+ * then only when they carry a real MPN.
203
+ */
204
+ function partition(
205
+ rows: BomRow[],
206
+ includeUnverified: boolean,
207
+ ): { included: BomRow[]; excluded: ExportResult['excluded'] } {
208
+ const included: BomRow[] = [];
209
+ const excluded: ExportResult['excluded'] = [];
210
+ for (const row of rows) {
211
+ if (!row.hasMpn) {
212
+ excluded.push({ row, reason: 'no MPN' });
213
+ } else if (row.unverified && !includeUnverified) {
214
+ excluded.push({ row, reason: 'UNVERIFIED' });
215
+ } else {
216
+ included.push(row);
217
+ }
218
+ }
219
+ return { included, excluded };
220
+ }
221
+
222
+ function groupBy(rows: BomRow[], key: (r: BomRow) => string): Line[] {
223
+ const map = new Map<string, BomRow[]>();
224
+ for (const r of rows) {
225
+ const k = key(r);
226
+ const arr = map.get(k);
227
+ if (arr) arr.push(r);
228
+ else map.set(k, [r]);
229
+ }
230
+ const lines: Line[] = [];
231
+ for (const groupRows of map.values()) {
232
+ const sorted = [...groupRows].sort((a, b) => naturalCompare(a.refdes, b.refdes));
233
+ // Groups are never empty (a key exists because a row produced it).
234
+ lines.push({ rows: sorted, head: sorted[0]!, designators: sorted.map((r) => r.refdes) });
235
+ }
236
+ // Deterministic line order: by the first designator of each line.
237
+ return lines.sort((a, b) => naturalCompare(a.designators[0]!, b.designators[0]!));
238
+ }
239
+
240
+ function buildWarnings(
241
+ supplier: Supplier,
242
+ included: BomRow[],
243
+ excluded: ExportResult['excluded'],
244
+ opts: ExportOptions,
245
+ ): string[] {
246
+ const { includeUnverified } = opts;
247
+ const warnings: string[] = [];
248
+ for (const { row, reason } of excluded) {
249
+ const hint =
250
+ reason === 'no MPN'
251
+ ? 'add an MPN in BOM.md — unorderable without one'
252
+ : 'verify against the datasheet or re-run with --include-unverified';
253
+ warnings.push(`EXCLUDED (${reason}): ${row.refdes} (${row.value || 'no value'}) — ${hint}`);
254
+ }
255
+ if (includeUnverified) {
256
+ for (const row of included) {
257
+ if (row.unverified) {
258
+ warnings.push(`INCLUDED but UNVERIFIED (--include-unverified): ${row.refdes} (${row.mpn}) — confirm before ordering`);
259
+ }
260
+ }
261
+ }
262
+ if (supplier === 'jlcpcb') {
263
+ // The JLCPCB assembly format has no quantity column — quantity is set from
264
+ // the board count entered at upload — so --boards/--spares never reach this
265
+ // file. Say so when the user supplied a non-default value, or they may order
266
+ // the wrong count expecting the flags to have taken effect.
267
+ if (opts.boards !== DEFAULT_BOARDS || opts.spares !== DEFAULT_SPARES) {
268
+ warnings.push(
269
+ 'NOTE: --boards/--spares are ignored for jlcpcb — quantity is set from the board count you enter at JLCPCB upload',
270
+ );
271
+ }
272
+ const blank = included.filter((r) => !r.lcsc).map((r) => r.refdes);
273
+ if (blank.length) {
274
+ warnings.push(
275
+ `NOTE: no LCSC part # for ${blank.join(', ')} — JLCPCB accepts the upload but needs manual matching for these`,
276
+ );
277
+ }
278
+ }
279
+ return warnings;
280
+ }
281
+
282
+ function emitJlcpcb(lines: Line[]): string {
283
+ // JLCPCB assembly-service BOM: one line per Comment+Footprint+LCSC, designators
284
+ // grouped. Quantity is derived by JLCPCB from the designator count × the board
285
+ // count entered at upload, so there is no quantity column here (design/proposal).
286
+ const header = 'Comment,Designator,Footprint,LCSC Part #';
287
+ const body = lines.map((l) =>
288
+ csvRow([l.head.value, l.designators.join(','), l.head.footprint, l.head.lcsc]),
289
+ );
290
+ return [header, ...body].join('\n') + '\n';
291
+ }
292
+
293
+ function emitCart(lines: Line[], opts: ExportOptions, mpnHeader: string): string {
294
+ // DigiKey / Mouser cart upload: one line per MPN with a computed order
295
+ // quantity and the designators as the customer reference.
296
+ const header = `${mpnHeader},Manufacturer,Quantity,Customer Reference`;
297
+ const body = lines.map((l) => {
298
+ const qty = orderQuantity(l.designators.length, opts.boards, opts.spares, isPassiveFootprint(l.head.footprint));
299
+ return csvRow([l.head.mpn, l.head.manufacturer, String(qty), l.designators.join(',')]);
300
+ });
301
+ return [header, ...body].join('\n') + '\n';
302
+ }
303
+
304
+ /**
305
+ * Build the supplier CSV plus its warnings from parsed BOM rows. Pure: no I/O,
306
+ * so the emitters are golden-file testable in isolation (design D5).
307
+ */
308
+ export function buildExport(rows: BomRow[], supplier: Supplier, opts: ExportOptions): ExportResult {
309
+ const { included, excluded } = partition(rows, opts.includeUnverified);
310
+ const lines =
311
+ supplier === 'jlcpcb'
312
+ ? groupBy(included, (r) => `${r.value}${r.footprint}${r.lcsc}`)
313
+ : groupBy(included, (r) => r.mpn);
314
+
315
+ let csv: string;
316
+ if (supplier === 'jlcpcb') csv = emitJlcpcb(lines);
317
+ else if (supplier === 'digikey') csv = emitCart(lines, opts, 'Manufacturer Part Number');
318
+ else csv = emitCart(lines, opts, 'Mfr. Part Number');
319
+
320
+ return { csv, included, excluded, warnings: buildWarnings(supplier, included, excluded, opts) };
321
+ }