Repository navigation
Expand file tree
/
Copy pathcli.ts
More file actions
651 lines (625 loc) · 28.5 KB
/
Copy pathcli.ts
File metadata and controls
651 lines (625 loc) · 28.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
#!/usr/bin/env node
import { Command } from 'commander';
import { setMaxListeners } from 'node:events';
import { createRequire } from 'node:module';
import { createInterface } from 'node:readline/promises';
import { loadConfig, resolveModel, type ModelSource } from './config.js';
import { pickModel } from './util/select.js';
import { runInit, InitError } from './memory/scaffold.js';
import { runCheck } from './commands/check.js';
import { runDoctor, formatDoctor } from './commands/doctor.js';
import { syncVerify, syncResolve, formatSyncReport } from './commands/sync.js';
import { runCreate } from './commands/create.js';
import { runDemo, demoTourText } from './commands/demo.js';
import { runRepl } from './commands/repl.js';
import {
runExportBom,
parseSupplier,
parseBoards,
parseSpares,
ExportError,
} from './commands/export.js';
import { DEFAULT_BOARDS, DEFAULT_SPARES } from './kicad/bom-export.js';
import { runAgentLoop, type BudgetExhaustedStats } from './agent/loop.js';
import { makeRenderer } from './agent/render.js';
import { kicadCliVersion } from './kicad/cli.js';
import { loadEnvFile } from './util/env.js';
import { budgetExtraTurns, budgetPromptText, parseMaxTurns, repoOf, reviewProviderFactory } from './util/cli-args.js';
// Read .env from the working directory before any command resolves a model or a
// provider. Loaded here rather than per-command so `check` behaves identically,
// though check never reads a key: it stays LLM-free and network-free either way.
// A real environment variable always beats the file.
loadEnvFile(process.cwd());
// Single source of truth for the version. Both src/cli.ts (via tsx) and
// dist/cli.js sit one level below the package root, so the path holds either
// way, and a release can never ship a version string that disagrees with the
// package it was published as.
const { version } = createRequire(import.meta.url)('../package.json') as { version: string };
const program = new Command();
async function confirmTty(question: string): Promise<boolean> {
const rl = createInterface({ input: process.stdin, output: process.stdout });
const answer = await rl.question(`${question} [y/N] `);
rl.close();
return /^y(es)?$/i.test(answer.trim());
}
/**
* Attended runs get a decision point instead of a rollback when the turn
* budget runs out (issue #15). Non-TTY (CI, pipes) keeps fail-and-restore.
*/
function budgetContinuePrompt(): ((stats: BudgetExhaustedStats) => Promise<number>) | undefined {
if (!process.stdin.isTTY || !process.stdout.isTTY) return undefined;
return async (stats) =>
(await confirmTty(budgetPromptText(stats))) ? budgetExtraTurns(stats) : 0;
}
program
.name('copperhead')
.description('Cursor for circuit boards: an AI agent for real KiCad repositories')
.version(version)
.option('--repo <path>', 'target repository (default: cwd)')
.option('--json', 'machine-readable output')
.option('--plain', 'plain log-style output (no interactive status line)');
const rendererOf = () =>
makeRenderer({ json: Boolean(program.opts().json), plain: Boolean(program.opts().plain) });
program
.command('repl', { isDefault: true })
.description('interactive agent shell (default when no command is given)')
.argument('[request...]', 'optional first change request before the prompt loop')
.option('--model <model>', 'codex | cursor | gpt-5 | claude | claude-code (or a provider-specific model id)')
.option('--max-turns <n>', 'turn budget per request')
.option('--allow-dirty', 'let turns run on a dirty working tree')
.option('--interactive', 'pause for approval after each proposal validates')
.action(
async (
requestParts: string[],
opts: { model?: string; maxTurns?: string; allowDirty?: boolean; interactive?: boolean },
) => {
const repo = repoOf(program.opts());
if (program.opts().json) {
console.error(
'copperhead: --json is not supported with the interactive shell. Use `copperhead do "<request>" --json`.',
);
process.exit(1);
}
try {
const kicadVer = await kicadCliVersion();
const config = await loadConfig(repo);
const renderer = rendererOf();
let model: string;
let source: ModelSource;
try {
({ model, source } = resolveModel(opts.model, config));
} catch (err) {
// No model anywhere (flag, COPPERHEAD_MODEL, config, .env keys):
// on a TTY, offer an interactive pick instead of refusing to start.
if (!process.stdin.isTTY || !process.stdout.isTTY) throw err;
console.log('No model configured for this session, pick one:');
const chosen = await pickModel();
if (!chosen) throw err;
model = chosen;
source = 'picker';
}
const continuePrompt = budgetContinuePrompt();
const seed = requestParts.length ? requestParts.join(' ') : undefined;
const res = await runRepl({
repoRoot: repo,
model,
modelSource: source,
version,
kicadCliVersion: kicadVer,
...(opts.maxTurns ? { maxTurns: parseMaxTurns(opts.maxTurns) } : {}),
allowDirty: opts.allowDirty ?? false,
interactive: opts.interactive ?? false,
...(seed ? { seed } : {}),
confirm: confirmTty,
...(continuePrompt ? { onBudgetExhausted: continuePrompt } : {}),
renderer,
});
process.exit(res.ok ? 0 : 1);
} catch (err) {
console.error((err as Error).message);
process.exit(1);
}
},
);
program
.command('init')
.description('scaffold docs/ from an existing schematic; idempotent')
.option('--path <dir>', 'where to look for KiCad files', '.')
.option('--force', 'overwrite hand-edited generated docs')
.option('--no-hooks', 'skip git pre-commit hook installation')
.action(async (opts: { path: string; force?: boolean; hooks: boolean }) => {
const repo = repoOf(program.opts());
try {
await kicadCliVersion();
const res = await runInit({
repoRoot: repo,
searchPath: opts.path,
force: opts.force ?? false,
installHooks: opts.hooks,
});
if (program.opts().json) {
console.log(JSON.stringify(res, null, 2));
} else {
for (const f of res.created) console.log(`created ${f}`);
for (const f of res.skipped) console.log(`unchanged ${f}`);
for (const f of res.refused) console.log(`REFUSED (hand-edited; use --force): ${f}`);
}
process.exit(res.refused.length ? 1 : 0);
} catch (err) {
console.error(err instanceof InitError ? err.message : (err as Error).message);
process.exit(1);
}
});
const checkAction = async (): Promise<void> => {
const repo = repoOf(program.opts());
const json = Boolean(program.opts().json);
try {
await kicadCliVersion();
const res = await runCheck(repo, json ? () => {} : (s) => console.log(s));
if (json) console.log(JSON.stringify(res, null, 2));
process.exit(res.ok ? 0 : 1);
} catch (err) {
console.error((err as Error).message);
process.exit(1);
}
};
program
.command('check')
.alias('verify')
.description('ERC + DRC + doc-drift + spec validation; no LLM calls; CI-safe')
.action(checkAction);
// `draft` and `score` are command groups taking the artifact as a noun
// (`draft schematic` today, `draft pcb` when layout drafting exists), so the
// verb alone never has to guess what it applies to.
const draftGroup = program
.command('draft')
.description('deterministically draft an artifact from its declared intent; no LLM, no network');
draftGroup
.command('schematic')
.description('draft the schematic from schematic.intent.json')
.option('--intent <path>', 'repo-relative intent file (default: schematic.intent.json beside the schematic)')
.action(async (opts: { intent?: string }) => {
const repo = repoOf(program.opts());
const json = Boolean(program.opts().json);
try {
const { loadConfig } = await import('./config.js');
const { draftSchematic, defaultIntentPath, formatSchematicDraftReport } = await import('./kicad/draft/draft.js');
const config = await loadConfig(repo);
if (!config.schematic) {
console.error('no schematic configured in .copperhead/config.json');
process.exit(1);
}
const res = await draftSchematic({
repoRoot: repo,
schematic: config.schematic,
intentPath: opts.intent ?? defaultIntentPath(config.schematic),
docsDir: config.docs,
});
if (!res.ok) {
if (json) console.log(JSON.stringify({ ok: false, findings: res.findings }, null, 2));
else console.error(res.message);
process.exit(1);
}
if (json) console.log(JSON.stringify({ ok: true, report: res.report }, null, 2));
else console.log(formatSchematicDraftReport(res.report));
process.exit(0);
} catch (err) {
console.error((err as Error).message);
process.exit(1);
}
});
const scoreGroup = program
.command('score')
.description('quantitative quality score for an artifact; advisory exit code; no LLM, no network');
scoreGroup
.command('schematic')
.description('legibility and layout score for the schematic')
.option('--file <path>', 'score this .kicad_sch instead of the configured schematic (any sheet, no repo needed)')
.action(async (opts: { file?: string }) => {
const repo = repoOf(program.opts());
const json = Boolean(program.opts().json);
try {
const { loadConfig } = await import('./config.js');
const { scoreSchematic, formatScore } = await import('./kicad/score.js');
const path = await import('node:path');
if (opts.file) {
const report = await scoreSchematic(path.resolve(opts.file), { docsDir: null });
console.log(json ? JSON.stringify(report, null, 2) : formatScore(report));
process.exit(0);
}
const config = await loadConfig(repo);
if (!config.schematic) {
console.error('no schematic configured in .copperhead/config.json');
process.exit(1);
}
const report = await scoreSchematic(path.join(repo, config.schematic), {
docsDir: path.join(repo, config.docs),
...(config.legibility ? { config: config.legibility } : {}),
});
console.log(json ? JSON.stringify(report, null, 2) : formatScore(report));
process.exit(0); // the exit code never depends on the composite (AC-16.26 family)
} catch (err) {
console.error((err as Error).message);
process.exit(1);
}
});
program
.command('doctor')
.description('env preflight: kicad-cli, git, node, and the model provider credential; no LLM, no network')
.option('--model <model>', 'model to check the provider credential for (default: resolved like a run)')
.action(async (opts: { model?: string }) => {
const repo = repoOf(program.opts());
// Unlike other commands, doctor never gates on kicad-cli being present:
// runDoctor probes it and reports a failure instead of throwing, so a user
// with a missing tool still gets the full report.
const report = await runDoctor({ repoRoot: repo, model: opts.model });
if (program.opts().json) console.log(JSON.stringify(report, null, 2));
else {
const color = process.stdout.isTTY === true && !process.env.NO_COLOR;
// || not ??: some non-interactive ptys report columns as 0.
for (const line of formatDoctor(report, process.stdout.columns || 80, color)) console.log(line);
}
process.exit(report.ok ? 0 : 1);
});
program
.command('do')
.description('the core loop: propose, edit, verify, propagate, commit')
.argument('<request>', 'the change request in natural language')
.option('--model <model>', 'codex | cursor | gpt-5 | claude | claude-code | compat:<id> (or a provider-specific model id)')
.option('--max-turns <n>', 'turn budget for this run')
.option('--allow-dirty', 'allow a dirty tree (snapshot via git stash create)')
.option('--dry-run', 'propose the diff, write nothing')
.option('--interactive', 'pause for approval after the proposal validates')
.action(
async (
request: string,
opts: { model?: string; maxTurns?: string; allowDirty?: boolean; dryRun?: boolean; interactive?: boolean },
) => {
const repo = repoOf(program.opts());
try {
const kicadVer = await kicadCliVersion();
const config = await loadConfig(repo);
const { model, source } = resolveModel(opts.model, config);
const continuePrompt = budgetContinuePrompt();
const res = await runAgentLoop({
repoRoot: repo,
request,
model,
...(opts.maxTurns ? { maxTurns: parseMaxTurns(opts.maxTurns) } : {}),
allowDirty: opts.allowDirty ?? false,
dryRun: opts.dryRun ?? false,
interactive: opts.interactive ?? false,
confirm: confirmTty,
...(continuePrompt ? { onBudgetExhausted: continuePrompt } : {}),
renderer: rendererOf(),
meta: { command: 'do', modelSource: source, version, kicadCliVersion: kicadVer },
});
if (program.opts().json) console.log(JSON.stringify(res, null, 2));
process.exit(res.outcome === 'failure' ? 1 : 0);
} catch (err) {
console.error((err as Error).message);
process.exit(1);
}
},
);
const skillCmd = program.command('skill').description('run a registered skill (nested tool loop; no git commit)');
skillCmd
.command('list')
.description('list registered skills (LLM-free, network-free)')
.action(async () => {
const repo = repoOf(program.opts());
try {
const { listSkills } = await import('./commands/skill.js');
const skills = await listSkills(repo);
if (program.opts().json) console.log(JSON.stringify(skills, null, 2));
else {
for (const s of skills) {
console.log(`${s.available ? '·' : '×'} ${s.name.replaceAll('_', '-')} ${s.description.split('\n')[0]}`);
}
}
process.exit(0);
} catch (err) {
console.error((err as Error).message);
process.exit(1);
}
});
skillCmd
.command('run')
.description('run a skill by name (generate-report)')
.argument('<name>', 'skill name (kebab or underscore)')
.option('--model <model>', 'codex | cursor | gpt-5 | claude | claude-code | compat:<id>')
.option('--scope <scope>', 'generate-report scope: power | all', 'all')
.action(async (name: string, opts: { model?: string; scope?: string }) => {
const repo = repoOf(program.opts());
const json = Boolean(program.opts().json);
// `process.exit` skips pending finally blocks, so the provider close has to
// finish before the exit call — hence the code is carried out, not exited on.
let code = 1;
try {
const { runSkillCli, providerForSkillRun } = await import('./commands/skill.js');
const { provider } = await providerForSkillRun(repo, opts.model);
const res = await runSkillCli({
repoRoot: repo,
name,
args: { scope: opts.scope === 'power' ? 'power' : 'all' },
provider,
json,
});
console.log(res.text);
code = res.code;
} catch (err) {
console.error((err as Error).message);
code = 1;
}
process.exit(code);
});
program
.command('sync')
.description('verify the whole design state for inconsistencies and resolve drift')
.option('--model <model>', 'model for the resolve phase')
.option('--dry-run', 'print the inconsistency report, write nothing')
.action(async (opts: { model?: string; dryRun?: boolean }) => {
const repo = repoOf(program.opts());
try {
const kicadVer = await kicadCliVersion();
const report = await syncVerify(repo);
const json = Boolean(program.opts().json);
if (json) console.log(JSON.stringify(report, null, 2));
else console.log(formatSyncReport(report));
if (opts.dryRun) {
process.exit(report.violations.length ? 2 : 0);
}
if (report.violations.length) {
// requirement violations are never auto-resolved (AC-7.3)
process.exit(2);
}
if (!report.resolvable.length) {
process.exit(0);
}
const config = await loadConfig(repo);
const { model, source } = resolveModel(opts.model, config);
const res = await syncResolve(repo, report, model, json ? () => {} : (s) => console.log(s), {
renderer: rendererOf(),
meta: { command: 'sync', modelSource: source, version, kicadCliVersion: kicadVer },
});
process.exit(res.ok ? 0 : 1);
} catch (err) {
console.error((err as Error).message);
process.exit(1);
}
});
program
.command('review')
.description('EXPERIMENTAL: grounded design review: a deterministic sweep, model passes that propose, verifiers that decide (RFC 17)')
.argument('[design]', 'the design directory (default: --repo or cwd); never written')
.option('--out <dir>', 'a new directory, outside the design, for the review record')
.option('--source <path...>', 'retained sources a citation may name: datasheet text, documents, firmware (repeatable; directories are walked)')
.option('--fab <path...>', 'fabrication outputs to review with the design: Gerber and drill directories or zips, BOM and placement files')
.option('--fab-profile <path>', 'a manufacturer capability profile for fab-rules')
.option('--model <model>', 'claude-code | claude | codex | gpt-5 (or a provider-specific model id)')
.option('--domains <list>', 'comma-separated domains: P power, M MCU, S storage/IO, F firmware, L physical, R routing, G fabrication outputs, B BOM', 'P,M,S,F,L,R,G,B')
.option('--max-turns <n>', 'turn budget per domain pass', '40')
.option('--max-minutes <n>', 'wall-clock budget per domain pass', '45')
.option('--parallel <n>', 'domain passes run at once', '3')
.option('--label <text>', 'the design name shown in the report')
.option('--sweep <dir>', 'reuse a copperhead-tools review record instead of running the sweep')
.option('--tools <path>', 'copperhead-tools cli.js or executable (default: COPPERHEAD_TOOLS, then PATH)')
.option('--replay <dir>', 're-verify a recorded review with no model and compare its report byte for byte; run it from the directory the review ran in')
.option('--resume', 'continue the record in --out that a killed run left: keep its sweep, bundle and ended passes')
.addHelpText(
'after',
'\nExit codes: 0 every pass ended and the report was written; 2 the report was written but a pass failed\n' +
'(rerun it with --resume); 1 an error, or a replay that differs; 130 or 143 cancelled by SIGINT or SIGTERM.',
)
.action(
async (
designArg: string | undefined,
opts: { out?: string; source?: string[]; fab?: string[]; fabProfile?: string; model?: string; domains: string; maxTurns: string; maxMinutes: string; parallel: string; label?: string; sweep?: string; tools?: string; replay?: string; resume?: boolean },
) => {
const json = Boolean(program.opts().json);
const log = (line: string) => console.error(line);
// Cancelling stops the passes and the copperhead-tools processes, keeps every sample saved so
// far (a later --resume reruns the interrupted passes), and exits 128 + the signal number.
const cancel = new AbortController();
// Every pass and copperhead-tools process listens on it; --parallel 8 passes more than the default ten.
setMaxListeners(0, cancel.signal);
let cancelCode = 0;
const onSignal = (sig: NodeJS.Signals) => {
if (cancelCode) process.exit(cancelCode);
cancelCode = sig === 'SIGINT' ? 130 : 143;
console.error(`review: ${sig}: cancelling`);
cancel.abort();
setTimeout(() => process.exit(cancelCode), 10_000).unref();
};
process.on('SIGINT', onSignal);
process.on('SIGTERM', onSignal);
try {
const { runReview, replayReview } = await import('./review/run.js');
if (opts.replay) {
const r = await replayReview(opts.replay, { ...(opts.tools ? { tools: opts.tools } : {}), log, signal: cancel.signal });
if (cancelCode) throw new Error('cancelled');
if (json) console.log(JSON.stringify(r, null, 2));
else console.log(r.identical ? `replay identical: ${r.replayReport}` : `replay DIFFERS: compare ${r.report} with ${r.replayReport} (a replay runs from the directory the review ran in)`);
process.exit(r.identical ? 0 : 1);
}
if (!opts.out) throw new Error('--out is required (a new directory for the review record)');
const design = designArg ?? repoOf(program.opts());
const config = await loadConfig(design);
const { model } = resolveModel(opts.model, config);
const { makeProvider } = await import('./agent/loop.js');
const res = await runReview({
design,
out: opts.out,
sources: opts.source ?? [],
model,
domains: opts.domains.split(',').map((d) => d.trim().toUpperCase()).filter(Boolean),
maxTurns: Number(opts.maxTurns),
maxMinutes: Number(opts.maxMinutes),
parallel: Number(opts.parallel),
...(opts.label ? { label: opts.label } : {}),
...(opts.sweep ? { sweep: opts.sweep } : {}),
...(opts.fab ? { fab: opts.fab } : {}),
...(opts.fabProfile ? { fabProfile: opts.fabProfile } : {}),
...(opts.resume ? { resume: true } : {}),
...(opts.tools ? { tools: opts.tools } : {}),
makeProvider: reviewProviderFactory(config, makeProvider),
log,
signal: cancel.signal,
});
if (cancelCode) throw new Error('cancelled');
if (json) console.log(JSON.stringify(res, null, 2));
else {
console.log(`report: ${res.report}`);
console.log(`verification: ${JSON.stringify(res.summary)}`);
for (const p of res.passes) console.log(` ${p.domain}: ${p.outcome}, ${p.turns} turns, ${p.proposals} proposals, ${p.seconds} s${p.error ? ` (${p.error})` : ''}`);
}
const failed = res.passes.filter((p) => p.outcome === 'failed').map((p) => p.domain);
if (failed.length) console.error(`review: ${failed.length} pass(es) failed (${failed.join(', ')}); the report covers the rest. Rerun them with --resume.`);
process.exit(failed.length ? 2 : 0);
} catch (err) {
console.error((err as Error).message);
process.exit(cancelCode || 1);
}
},
);
program
.command('mcp')
.description('EXPERIMENTAL: serve the gated pipeline to MCP hosts over stdio (unstable surface)')
// `--repo` is also a global flag, but a host config reads as
// `args: ["mcp", "--repo", "/path"]`, so the command accepts it locally too.
.option('--repo <path>', 'target repository (default: cwd)')
.action(async (opts: { repo?: string }) => {
const repo = repoOf(opts.repo ? { repo: opts.repo } : program.opts());
try {
// Imported lazily, like `skill`: the MCP SDK and zod are a ~150ms load
// that every other command — including the pre-commit `check` — would
// otherwise pay, and a resolution failure here would take down the whole
// CLI rather than just this command.
const { startMcpServer } = await import('./mcp/server.js');
// Never returns until the host closes stdio. Nothing is printed to
// stdout here or anywhere downstream: it carries JSON-RPC alone.
await startMcpServer({ repoRoot: repo });
} catch (err) {
console.error((err as Error).message);
process.exit(1);
}
});
program
.command('demo')
.description('tour of what copperhead does, or run the USB-C breakout create pipeline')
.option('--model <model>', 'codex | cursor | gpt-5 | claude | claude-code (or a provider-specific model id)')
.option('--interactive', 're-enable the human gates (spec approval, pre-export)')
.option('--dir <path>', 'demo repo directory (default: demo-runs/usb-c-breakout)')
.option('--tour', 'print the overview only; do not run the pipeline')
.action(async (opts: { model?: string; interactive?: boolean; dir?: string; tour?: boolean }) => {
if (opts.tour) {
const { setColorEnabled } = await import('./agent/theme.js');
if (program.opts().json) {
// --json is a contract, not a suggestion: a script that passes it
// unconditionally must never get prose back. Plain lines, no SGR.
setColorEnabled(false);
console.log(JSON.stringify({ tour: demoTourText().split('\n') }, null, 2));
process.exit(0);
}
// Color on for attended TTY tours even without a renderer.
setColorEnabled(Boolean(process.stdout.isTTY) && !program.opts().plain && !process.env.NO_COLOR);
console.log(demoTourText());
process.exit(0);
}
try {
const kicadVer = await kicadCliVersion();
// Resolve model from the caller's cwd config / env / flag; the demo repo
// is scaffolded next and typically has no model of its own yet.
const config = await loadConfig(repoOf(program.opts()));
const { model, source } = resolveModel(opts.model, config);
const continuePrompt = budgetContinuePrompt();
const res = await runDemo({
model,
modelSource: source,
version,
kicadCliVersion: kicadVer,
interactive: opts.interactive ?? false,
...(opts.dir ? { demoDir: opts.dir } : {}),
...(continuePrompt ? { onBudgetExhausted: continuePrompt } : {}),
log: (s) => console.log(s),
renderer: rendererOf(),
});
process.exit(res.ok ? 0 : 1);
} catch (err) {
console.error((err as Error).message);
process.exit(1);
}
});
program
.command('create')
.description('Mode A: full pipeline from a product brief to the output package')
.requiredOption('--brief <file>', 'product brief (markdown)')
.option('--model <model>', 'codex | cursor | gpt-5 | claude | claude-code | compat:<id> (or a provider-specific model id)')
.option('--interactive', 're-enable the human gates (spec approval, pre-export)')
.action(async (opts: { brief: string; model?: string; interactive?: boolean }) => {
const repo = repoOf(program.opts());
try {
const kicadVer = await kicadCliVersion();
const config = await loadConfig(repo);
const { model, source } = resolveModel(opts.model, config);
const continuePrompt = budgetContinuePrompt();
const res = await runCreate({
repoRoot: repo,
briefPath: opts.brief,
model,
interactive: opts.interactive ?? false,
...(continuePrompt ? { onBudgetExhausted: continuePrompt } : {}),
log: (s) => console.log(s),
renderer: rendererOf(),
meta: { command: 'create', modelSource: source, version, kicadCliVersion: kicadVer },
});
process.exit(res.ok ? 0 : 1);
} catch (err) {
console.error((err as Error).message);
process.exit(1);
}
});
const exportCmd = program
.command('export')
.description('emit supplier-ready files from repo state (deterministic; no LLM, no network)');
exportCmd
.command('bom')
.description('write a supplier-format BOM (jlcpcb | digikey | mouser) from docs/BOM.md')
.requiredOption('--supplier <name>', 'jlcpcb | digikey | mouser')
.option('--boards <n>', 'number of boards to order', String(DEFAULT_BOARDS))
.option('--spares <percent>', 'spare parts percentage', String(DEFAULT_SPARES))
.option('--include-unverified', 'include UNVERIFIED rows that carry an MPN (never MPN-less rows)')
.action(async (opts: { supplier: string; boards: string; spares: string; includeUnverified?: boolean }) => {
const repo = repoOf(program.opts());
const json = Boolean(program.opts().json);
try {
const supplier = parseSupplier(opts.supplier);
const boards = parseBoards(opts.boards);
const spares = parseSpares(opts.spares);
const res = await runExportBom({
repoRoot: repo,
supplier,
boards,
spares,
includeUnverified: opts.includeUnverified ?? false,
});
// Warnings go to stderr so a `> file` redirect of stdout stays clean and
// the excluded-rows report is still seen.
for (const w of res.warnings) console.error(w);
if (json) {
console.log(JSON.stringify(res, null, 2));
} else {
console.log(`wrote ${res.outPath} (${res.included.length} part(s), ${res.excluded.length} excluded)`);
}
process.exit(0);
} catch (err) {
// ExportError carries an actionable message (bad flag, missing BOM, drift);
// anything else is unexpected. Both exit non-zero with no stack trace.
console.error(err instanceof ExportError ? err.message : (err as Error).message);
process.exit(1);
}
});
program.parseAsync().catch((err: Error) => {
console.error(err.message);
process.exit(1);
});