copperhead 0.5.0 → 0.6.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.
- package/README.md +34 -1
- package/dist/agent/loop.js +13 -0
- package/dist/agent/loop.js.map +1 -1
- package/dist/agent/providers/claude-code.js +286 -0
- package/dist/agent/providers/claude-code.js.map +1 -0
- package/dist/agent/providers/openai.js +30 -10
- package/dist/agent/providers/openai.js.map +1 -1
- package/dist/cli.js +47 -2
- package/dist/cli.js.map +1 -1
- package/dist/commands/create.js +16 -0
- package/dist/commands/create.js.map +1 -1
- package/dist/commands/export.js +90 -0
- package/dist/commands/export.js.map +1 -0
- package/dist/config.js +14 -6
- package/dist/config.js.map +1 -1
- package/dist/kicad/bom-export.js +240 -0
- package/dist/kicad/bom-export.js.map +1 -0
- package/dist/kicad/fab.js +94 -0
- package/dist/kicad/fab.js.map +1 -0
- package/dist/memory/bom-table.js +61 -0
- package/dist/memory/bom-table.js.map +1 -0
- package/dist/memory/drift.js +1 -17
- package/dist/memory/drift.js.map +1 -1
- package/package.json +6 -2
- package/src/agent/loop.ts +13 -0
- package/src/agent/providers/claude-code.ts +367 -0
- package/src/agent/providers/openai.ts +33 -16
- package/src/agent/types.ts +1 -0
- package/src/cli.ts +52 -2
- package/src/commands/create.ts +15 -0
- package/src/commands/export.ts +117 -0
- package/src/config.ts +20 -6
- package/src/kicad/bom-export.ts +321 -0
- package/src/kicad/fab.ts +121 -0
- package/src/memory/bom-table.ts +78 -0
- package/src/memory/drift.ts +1 -22
package/src/cli.ts
CHANGED
|
@@ -8,6 +8,14 @@ import { runInit, InitError } from './memory/scaffold.js';
|
|
|
8
8
|
import { runCheck } from './commands/check.js';
|
|
9
9
|
import { syncVerify, syncResolve, formatSyncReport } from './commands/sync.js';
|
|
10
10
|
import { runCreate } from './commands/create.js';
|
|
11
|
+
import {
|
|
12
|
+
runExportBom,
|
|
13
|
+
parseSupplier,
|
|
14
|
+
parseBoards,
|
|
15
|
+
parseSpares,
|
|
16
|
+
ExportError,
|
|
17
|
+
} from './commands/export.js';
|
|
18
|
+
import { DEFAULT_BOARDS, DEFAULT_SPARES } from './kicad/bom-export.js';
|
|
11
19
|
import { runAgentLoop, type BudgetExhaustedStats } from './agent/loop.js';
|
|
12
20
|
import { makeRenderer } from './agent/render.js';
|
|
13
21
|
import { kicadCliVersion } from './kicad/cli.js';
|
|
@@ -117,7 +125,7 @@ program
|
|
|
117
125
|
.command('do')
|
|
118
126
|
.description('the core loop: propose, edit, verify, propagate, commit')
|
|
119
127
|
.argument('<request>', 'the change request in natural language')
|
|
120
|
-
.option('--model <model>', 'codex | gpt-5 | claude (or a provider-specific model id)')
|
|
128
|
+
.option('--model <model>', 'codex | gpt-5 | claude | claude-code (or a provider-specific model id)')
|
|
121
129
|
.option('--max-turns <n>', 'turn budget for this run')
|
|
122
130
|
.option('--allow-dirty', 'allow a dirty tree (snapshot via git stash create)')
|
|
123
131
|
.option('--dry-run', 'propose the diff, write nothing')
|
|
@@ -195,7 +203,7 @@ program
|
|
|
195
203
|
.command('create')
|
|
196
204
|
.description('Mode A: full pipeline from a product brief to the output package')
|
|
197
205
|
.requiredOption('--brief <file>', 'product brief (markdown)')
|
|
198
|
-
.option('--model <model>', 'codex | gpt-5 | claude')
|
|
206
|
+
.option('--model <model>', 'codex | gpt-5 | claude | claude-code (or a provider-specific model id)')
|
|
199
207
|
.option('--interactive', 're-enable the human gates (spec approval, pre-export)')
|
|
200
208
|
.action(async (opts: { brief: string; model?: string; interactive?: boolean }) => {
|
|
201
209
|
const repo = repoOf(program.opts());
|
|
@@ -221,6 +229,48 @@ program
|
|
|
221
229
|
}
|
|
222
230
|
});
|
|
223
231
|
|
|
232
|
+
const exportCmd = program
|
|
233
|
+
.command('export')
|
|
234
|
+
.description('emit supplier-ready files from repo state (deterministic; no LLM, no network)');
|
|
235
|
+
|
|
236
|
+
exportCmd
|
|
237
|
+
.command('bom')
|
|
238
|
+
.description('write a supplier-format BOM (jlcpcb | digikey | mouser) from docs/BOM.md')
|
|
239
|
+
.requiredOption('--supplier <name>', 'jlcpcb | digikey | mouser')
|
|
240
|
+
.option('--boards <n>', 'number of boards to order', String(DEFAULT_BOARDS))
|
|
241
|
+
.option('--spares <percent>', 'spare parts percentage', String(DEFAULT_SPARES))
|
|
242
|
+
.option('--include-unverified', 'include UNVERIFIED rows that carry an MPN (never MPN-less rows)')
|
|
243
|
+
.action(async (opts: { supplier: string; boards: string; spares: string; includeUnverified?: boolean }) => {
|
|
244
|
+
const repo = repoOf(program.opts());
|
|
245
|
+
const json = Boolean(program.opts().json);
|
|
246
|
+
try {
|
|
247
|
+
const supplier = parseSupplier(opts.supplier);
|
|
248
|
+
const boards = parseBoards(opts.boards);
|
|
249
|
+
const spares = parseSpares(opts.spares);
|
|
250
|
+
const res = await runExportBom({
|
|
251
|
+
repoRoot: repo,
|
|
252
|
+
supplier,
|
|
253
|
+
boards,
|
|
254
|
+
spares,
|
|
255
|
+
includeUnverified: opts.includeUnverified ?? false,
|
|
256
|
+
});
|
|
257
|
+
// Warnings go to stderr so a `> file` redirect of stdout stays clean and
|
|
258
|
+
// the excluded-rows report is still seen.
|
|
259
|
+
for (const w of res.warnings) console.error(w);
|
|
260
|
+
if (json) {
|
|
261
|
+
console.log(JSON.stringify(res, null, 2));
|
|
262
|
+
} else {
|
|
263
|
+
console.log(`wrote ${res.outPath} (${res.included.length} part(s), ${res.excluded.length} excluded)`);
|
|
264
|
+
}
|
|
265
|
+
process.exit(0);
|
|
266
|
+
} catch (err) {
|
|
267
|
+
// ExportError carries an actionable message (bad flag, missing BOM, drift);
|
|
268
|
+
// anything else is unexpected. Both exit non-zero with no stack trace.
|
|
269
|
+
console.error(err instanceof ExportError ? err.message : (err as Error).message);
|
|
270
|
+
process.exit(1);
|
|
271
|
+
}
|
|
272
|
+
});
|
|
273
|
+
|
|
224
274
|
program.parseAsync().catch((err: Error) => {
|
|
225
275
|
console.error(err.message);
|
|
226
276
|
process.exit(1);
|
package/src/commands/create.ts
CHANGED
|
@@ -10,6 +10,7 @@ import type { RunMetaInput } from '../agent/runmeta.js';
|
|
|
10
10
|
import type { ProgressRenderer } from '../agent/render.js';
|
|
11
11
|
import { openspecInit } from '../openspec/cli.js';
|
|
12
12
|
import { runCheck } from './check.js';
|
|
13
|
+
import { emitCreateJlcpcbBom } from './export.js';
|
|
13
14
|
|
|
14
15
|
/**
|
|
15
16
|
* Mode A (`copperhead create`, SPEC §2.5): staged pipeline, each stage a
|
|
@@ -122,6 +123,18 @@ export interface CreateOptions {
|
|
|
122
123
|
meta?: Omit<RunMetaInput, 'stage' | 'brief'>;
|
|
123
124
|
}
|
|
124
125
|
|
|
126
|
+
/**
|
|
127
|
+
* Stage 6 emits the JLCPCB assembly BOM deterministically alongside the agent's
|
|
128
|
+
* outputs package (create-pipeline delta). Called whenever the outputs stage is
|
|
129
|
+
* confirmed complete — on the pass that finishes it and on any later resume — so
|
|
130
|
+
* the file tracks the current BOM.md.
|
|
131
|
+
*/
|
|
132
|
+
async function emitJlcpcbAfterOutputs(stageName: string, opts: CreateOptions): Promise<void> {
|
|
133
|
+
if (stageName !== 'outputs') return;
|
|
134
|
+
const out = await emitCreateJlcpcbBom(opts.repoRoot);
|
|
135
|
+
if (out) opts.log(`stage outputs: emitted ${out} (JLCPCB assembly BOM)`);
|
|
136
|
+
}
|
|
137
|
+
|
|
125
138
|
export async function runCreate(opts: CreateOptions): Promise<{ ok: boolean; completed: string[] }> {
|
|
126
139
|
const brief = await readFile(path.resolve(opts.briefPath), 'utf8');
|
|
127
140
|
// Hashed from the content already in hand: a brief edited mid-pipeline shows
|
|
@@ -135,6 +148,7 @@ export async function runCreate(opts: CreateOptions): Promise<{ ok: boolean; com
|
|
|
135
148
|
if (await stage.isComplete(opts.repoRoot, config.docs)) {
|
|
136
149
|
opts.log(`stage ${stage.name}: already complete (resuming past it)`);
|
|
137
150
|
completed.push(stage.name);
|
|
151
|
+
await emitJlcpcbAfterOutputs(stage.name, opts);
|
|
138
152
|
continue;
|
|
139
153
|
}
|
|
140
154
|
opts.log(`stage ${stage.name}: running`);
|
|
@@ -174,6 +188,7 @@ export async function runCreate(opts: CreateOptions): Promise<{ ok: boolean; com
|
|
|
174
188
|
return { ok: false, completed };
|
|
175
189
|
}
|
|
176
190
|
completed.push(stage.name);
|
|
191
|
+
await emitJlcpcbAfterOutputs(stage.name, opts);
|
|
177
192
|
}
|
|
178
193
|
|
|
179
194
|
const check = await runCheck(opts.repoRoot, opts.log);
|
|
@@ -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
|
@@ -14,6 +14,12 @@ export interface CopperheadConfig {
|
|
|
14
14
|
budgets: Record<string, number>;
|
|
15
15
|
/** Content hashes of generated docs, for init idempotency (AC-1.4). */
|
|
16
16
|
generatedHashes?: Record<string, string>;
|
|
17
|
+
/**
|
|
18
|
+
* How the repo was bootstrapped. `"create"` marks a Mode A pipeline repo
|
|
19
|
+
* (fab gate requires DEVPLAN.md). Written by `copperhead create`; absent on
|
|
20
|
+
* init-only / hand-maintained repos.
|
|
21
|
+
*/
|
|
22
|
+
origin?: 'create' | 'init';
|
|
17
23
|
}
|
|
18
24
|
|
|
19
25
|
export const CONFIG_DIR = '.copperhead';
|
|
@@ -51,6 +57,7 @@ export async function loadConfig(repoRoot: string): Promise<CopperheadConfig> {
|
|
|
51
57
|
maxRepairCycles: raw.maxRepairCycles ?? DEFAULTS.maxRepairCycles,
|
|
52
58
|
budgets: raw.budgets ?? {},
|
|
53
59
|
...(raw.generatedHashes ? { generatedHashes: raw.generatedHashes } : {}),
|
|
60
|
+
...(raw.origin === 'create' || raw.origin === 'init' ? { origin: raw.origin } : {}),
|
|
54
61
|
};
|
|
55
62
|
}
|
|
56
63
|
|
|
@@ -70,8 +77,12 @@ export interface ResolvedModel {
|
|
|
70
77
|
* Accepted values (same set for `--model`, COPPERHEAD_MODEL, and `model` in
|
|
71
78
|
* .copperhead/config.json):
|
|
72
79
|
*
|
|
73
|
-
* - `claude`
|
|
74
|
-
*
|
|
80
|
+
* - `claude-code` : the Claude Code saved-login provider on its default
|
|
81
|
+
* model. Needs NO API key — it reuses the logged-in Claude
|
|
82
|
+
* Code CLI / CLAUDE_CODE_OAUTH_TOKEN via the Agent SDK.
|
|
83
|
+
* - `claude-code:<id>`: the same provider on a specific model id.
|
|
84
|
+
* - `claude` : the Anthropic API provider on its default model.
|
|
85
|
+
* - `claude-*`: any Anthropic API model id, passed through verbatim, e.g.
|
|
75
86
|
* `claude-opus-4-5`. Anything starting with `claude` routes here.
|
|
76
87
|
* - `codex` : the locally installed Codex CLI using its saved ChatGPT login.
|
|
77
88
|
* - `codex:*` : Codex CLI with an explicit model id, e.g. `codex:gpt-5.6`.
|
|
@@ -80,10 +91,13 @@ export interface ResolvedModel {
|
|
|
80
91
|
* `gpt-5-mini` or `o3`.
|
|
81
92
|
*
|
|
82
93
|
* Routing is prefix-based, not a fixed list (see makeProvider in agent/loop.ts),
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
94
|
+
* matched top to bottom: `claude-code`/`claude-code:<id>` is checked BEFORE the
|
|
95
|
+
* `claude*` prefix, so it is never captured by the Anthropic API route. A model
|
|
96
|
+
* released after this build still works without a code change. The cost is that
|
|
97
|
+
* a typo like `claud-sonnet-5` silently routes to OpenAI and fails there.
|
|
98
|
+
* Anthropic and direct OpenAI providers require their API keys; `codex` requires
|
|
99
|
+
* a locally installed and authenticated Codex CLI, and `claude-code` requires a
|
|
100
|
+
* Claude Code login (CLAUDE_CODE_OAUTH_TOKEN); neither needs a model API key.
|
|
87
101
|
*/
|
|
88
102
|
export function resolveModel(flag: string | undefined, config: CopperheadConfig, env = process.env): ResolvedModel {
|
|
89
103
|
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
|
+
}
|