copperhead 0.9.0 → 0.10.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 (90) hide show
  1. package/NOTICE +1 -1
  2. package/README.md +6 -6
  3. package/dist/agent/filetools.js +24 -1
  4. package/dist/agent/filetools.js.map +1 -1
  5. package/dist/agent/ledger.js +24 -0
  6. package/dist/agent/ledger.js.map +1 -1
  7. package/dist/agent/loop.js +29 -58
  8. package/dist/agent/loop.js.map +1 -1
  9. package/dist/agent/prompts.js +4 -3
  10. package/dist/agent/prompts.js.map +1 -1
  11. package/dist/agent/providers/tool-protocol.js +21 -0
  12. package/dist/agent/providers/tool-protocol.js.map +1 -1
  13. package/dist/agent/recovery.js +95 -1
  14. package/dist/agent/recovery.js.map +1 -1
  15. package/dist/agent/tools.js +185 -1
  16. package/dist/agent/tools.js.map +1 -1
  17. package/dist/agent/transcript.js +2 -0
  18. package/dist/agent/transcript.js.map +1 -1
  19. package/dist/cli.js +75 -0
  20. package/dist/cli.js.map +1 -1
  21. package/dist/commands/check.js +33 -1
  22. package/dist/commands/check.js.map +1 -1
  23. package/dist/commands/create.js +177 -25
  24. package/dist/commands/create.js.map +1 -1
  25. package/dist/commands/doctor.js +50 -3
  26. package/dist/commands/doctor.js.map +1 -1
  27. package/dist/config.js +1 -0
  28. package/dist/config.js.map +1 -1
  29. package/dist/kicad/bootstrap.js +24 -3
  30. package/dist/kicad/bootstrap.js.map +1 -1
  31. package/dist/kicad/dossier.js +207 -0
  32. package/dist/kicad/dossier.js.map +1 -0
  33. package/dist/kicad/draft/draft.js +132 -0
  34. package/dist/kicad/draft/draft.js.map +1 -0
  35. package/dist/kicad/draft/engine.js +2389 -0
  36. package/dist/kicad/draft/engine.js.map +1 -0
  37. package/dist/kicad/draft/ir.js +368 -0
  38. package/dist/kicad/draft/ir.js.map +1 -0
  39. package/dist/kicad/draft/symsource.js +490 -0
  40. package/dist/kicad/draft/symsource.js.map +1 -0
  41. package/dist/kicad/emit.js +181 -0
  42. package/dist/kicad/emit.js.map +1 -0
  43. package/dist/kicad/fab.js +13 -0
  44. package/dist/kicad/fab.js.map +1 -1
  45. package/dist/kicad/legibility.js +561 -0
  46. package/dist/kicad/legibility.js.map +1 -0
  47. package/dist/kicad/score.js +261 -0
  48. package/dist/kicad/score.js.map +1 -0
  49. package/dist/kicad/sexp.js +239 -6
  50. package/dist/kicad/sexp.js.map +1 -1
  51. package/dist/kicad/symlib.js +346 -16
  52. package/dist/kicad/symlib.js.map +1 -1
  53. package/dist/memory/bom-table.js +75 -39
  54. package/dist/memory/bom-table.js.map +1 -1
  55. package/dist/memory/scaffold.js +6 -0
  56. package/dist/memory/scaffold.js.map +1 -1
  57. package/dist/util/redact.js +6 -0
  58. package/dist/util/redact.js.map +1 -1
  59. package/package.json +9 -7
  60. package/src/agent/filetools.ts +26 -1
  61. package/src/agent/ledger.ts +24 -0
  62. package/src/agent/loop.ts +28 -61
  63. package/src/agent/prompts.ts +4 -3
  64. package/src/agent/providers/tool-protocol.ts +22 -0
  65. package/src/agent/recovery.ts +94 -1
  66. package/src/agent/tools.ts +189 -1
  67. package/src/agent/transcript.ts +6 -0
  68. package/src/cli.ts +71 -0
  69. package/src/commands/check.ts +51 -1
  70. package/src/commands/create.ts +179 -20
  71. package/src/commands/doctor.ts +51 -3
  72. package/src/config.ts +24 -0
  73. package/src/kicad/bootstrap.ts +24 -3
  74. package/src/kicad/dossier.ts +217 -0
  75. package/src/kicad/draft/draft.ts +171 -0
  76. package/src/kicad/draft/engine.ts +2466 -0
  77. package/src/kicad/draft/ir.ts +416 -0
  78. package/src/kicad/draft/symsource.ts +535 -0
  79. package/src/kicad/emit.ts +236 -0
  80. package/src/kicad/fab.ts +15 -0
  81. package/src/kicad/legibility.ts +646 -0
  82. package/src/kicad/score.ts +323 -0
  83. package/src/kicad/sexp.ts +315 -6
  84. package/src/kicad/symlib.ts +364 -18
  85. package/src/memory/bom-table.ts +85 -38
  86. package/src/memory/scaffold.ts +6 -0
  87. package/src/util/redact.ts +6 -0
  88. package/dist/memory/synap.js +0 -152
  89. package/dist/memory/synap.js.map +0 -1
  90. package/src/memory/synap.ts +0 -217
@@ -3,20 +3,24 @@ import { existsSync } from 'node:fs';
3
3
  import { readFile, mkdir, writeFile, readdir } from 'node:fs/promises';
4
4
  import { createHash } from 'node:crypto';
5
5
  import { loadConfig, resolveCompatSettings } from '../config.js';
6
- import { bootstrapKicadProject } from '../kicad/bootstrap.js';
6
+ import { bootstrapKicadProject, markCreateOrigin } from '../kicad/bootstrap.js';
7
7
  import { exportSvg, runErc } from '../kicad/cli.js';
8
8
  import { listSymbols } from '../kicad/sexp.js';
9
+ import { checkLegibility } from '../kicad/legibility.js';
10
+ import { draftSchematicToText, defaultIntentPath } from '../kicad/draft/draft.js';
9
11
  import { isDirty, commitAll, changedFiles } from '../util/git.js';
10
12
  import type { CompatSettings, CopperheadConfig } from '../config.js';
11
13
  import { checkDrift } from '../memory/drift.js';
12
14
  import { runAgentLoop, makeProvider, type BudgetExhaustedStats } from '../agent/loop.js';
13
- import { diagnoseStageFailure, transcriptExcerpt, withTimeout, type StageDiagnosis } from '../agent/recovery.js';
15
+ import { diagnoseStageFailure, transcriptExcerpt, withTimeout, symbolAvailabilityFacts, type StageDiagnosis } from '../agent/recovery.js';
14
16
  import type { Provider } from '../agent/types.js';
15
17
  import type { RunMetaInput } from '../agent/runmeta.js';
16
18
  import { fmtDuration, fmtTokens, type ProgressRenderer } from '../agent/render.js';
17
19
  import { copper, dim, ok, stageLine, warn } from '../agent/theme.js';
18
20
  import { openspecInit } from '../openspec/cli.js';
19
21
  import { sweepStaleTempDirs, pruneHistoryDir } from '../util/tmp.js';
22
+ import { bomSymbolDossier } from '../kicad/dossier.js';
23
+ import { symbolSearchDirs } from '../kicad/symlib.js';
20
24
  import { assertDiskSpace, DEFAULT_MIN_FREE_BYTES } from '../util/preflight.js';
21
25
  import { runCheck } from './check.js';
22
26
  import { emitCreateJlcpcbBom } from './export.js';
@@ -55,6 +59,32 @@ async function docHasHeading(repoRoot: string, rel: string, word: string): Promi
55
59
  return re.test(await readFile(p, 'utf8'));
56
60
  }
57
61
 
62
+ export async function writeBriefHash(
63
+ repoRoot: string,
64
+ docsDir: string,
65
+ briefMeta: { path: string; sha256: string },
66
+ ): Promise<void> {
67
+ const file = path.join(repoRoot, docsDir, 'BRIEF.sha256');
68
+
69
+ await mkdir(path.dirname(file), { recursive: true });
70
+
71
+ try {
72
+ await writeFile(
73
+ file,
74
+ `brief: ${briefMeta.path}
75
+ sha256: ${briefMeta.sha256}
76
+ `,
77
+ {
78
+ encoding: 'utf8',
79
+ flag: 'wx',
80
+ },
81
+ );
82
+ } catch (err) {
83
+ const e = err as NodeJS.ErrnoException;
84
+ if (e.code !== 'EEXIST') throw err;
85
+ }
86
+ }
87
+
58
88
  /**
59
89
  * Returns true when a directory exists and contains at least one file
60
90
  * matching the optional glob-style extension list (case-insensitive).
@@ -86,16 +116,23 @@ export const STAGES: Stage[] = [
86
116
  const p = path.join(root, docs, 'SPEC.md');
87
117
  if (!existsSync(p)) return false;
88
118
  const text = await readFile(p, 'utf8');
89
- const budgetsMatch = /^#{1,6}\s.*\bBudgets?\b/im.test(text);
90
- if (!budgetsMatch) return false;
91
- // Find the Budgets section and strip HTML comments (single or multi-line)
92
- const afterBudgets = text.split(/^#{1,6}\s.*\bBudgets?\b/im)[1] ?? '';
93
- const firstNewline = afterBudgets.indexOf('\n');
94
- const afterHeadingLine = firstNewline >= 0 ? afterBudgets.slice(firstNewline + 1) : '';
95
- const nextSection = afterHeadingLine.search(/^#{1,6}\s/m);
119
+ const heading = /^(#{1,6})\s.*\bBudgets?\b.*$/im.exec(text);
120
+ if (!heading) return false;
121
+ // The section runs to the next heading of the SAME OR SHALLOWER depth, not to
122
+ // the next heading of any depth (I17): a real spec routinely splits its budgets
123
+ // into subsections — "## 3. Electrical budgets" followed immediately by
124
+ // "### 3.1 Input and rails" which leaves the parent's own body empty and read
125
+ // as an unfilled placeholder. Subheadings are part of the section, not its end.
126
+ const depth = heading[1]!.length;
127
+ const afterHeadingLine = text.slice(heading.index + heading[0].length);
128
+ const nextSection = afterHeadingLine.search(new RegExp(`^#{1,${depth}}\\s`, 'm'));
96
129
  const section = nextSection >= 0 ? afterHeadingLine.slice(0, nextSection) : afterHeadingLine;
130
+ // Strip HTML comments (single or multi-line); headings inside the section are
131
+ // structure, not content, so a section of nothing but subheadings still fails.
97
132
  const cleanSection = section.replace(/<!--[\s\S]*?-->/g, '');
98
- const realLines = cleanSection.split('\n').filter((l) => l.trim().length > 0);
133
+ const realLines = cleanSection
134
+ .split('\n')
135
+ .filter((l) => l.trim().length > 0 && !/^#{1,6}\s/.test(l.trim()));
99
136
  return realLines.length > 0;
100
137
  },
101
138
  prompt: (brief) =>
@@ -148,7 +185,7 @@ export const STAGES: Stage[] = [
148
185
  });
149
186
  },
150
187
  prompt: () =>
151
- 'Stage 3: part selection. Write docs/BOM.md with the fixed table format (| Refdes | Value | Footprint | MPN | Rationale |). Every MPN you introduce is flagged UNVERIFIED with a datasheet-verifiable justification. Check leakage/quiescent current of every part against the power budget. Run check_drift before finishing.',
188
+ 'Stage 3: part selection. Write docs/BOM.md with the fixed table format (| Refdes | Value | Footprint | MPN | Rationale |). The Value column holds the COMPONENT VALUE and nothing else — "4.7uF", "1M", "500mAh Li-Po", "STM32F103C8T6" — because stage 4 draws it on the sheet as that part\'s Value field, where a description ("1S Li-Po cell, 500 mAh, bare leads") collides with neighbouring symbols and fails the legibility gate. Put the prose in the Rationale column instead; that is the column for it, and nothing draws it. One row per refdes: a grouped row ("SW3-SW16", "C5-C8") is not a BOM row and the schematic stage cannot match it. Every MPN you introduce is flagged UNVERIFIED with a datasheet-verifiable justification. Check leakage/quiescent current of every part against the power budget. The design must be capturable with the KiCad symbol libraries installed on THIS machine: run search_symbols for every IC, module, connector and other active part before committing it to the BOM, and if a part has no installed symbol, pick one that has — stage 4 draws only from installed symbols, and a BOM row it cannot resolve makes the whole run unwinnable. Existence is not enough: confirm the chosen symbol with symbol_pins so the pin numbers you wire in stage 4 are real. Multi-unit symbols (gate packs, dual opamps) are fine — the engine places each unit separately under the one refdes, and net endpoints use plain package pin numbers. Run check_drift before finishing.',
152
189
  },
153
190
  {
154
191
  name: 'schematic',
@@ -174,10 +211,35 @@ export const STAGES: Stage[] = [
174
211
  // schematic, advancing the pipeline against unverified work. Returning
175
212
  // false here keeps the stage active so it re-runs, fixes ERC, and commits
176
213
  // through the normal finish gate.
177
- return (await runErc(p)).ok;
214
+ if (!(await runErc(p)).ok) return false;
215
+ // Legibility is the one stage-4 output no electrical gate sees (AC-16.22):
216
+ // an ERC-clean sheet with text over symbol bodies passes everything above
217
+ // while being unreviewable. Error-severity findings keep the stage active;
218
+ // advisories never block.
219
+ const legibility = await checkLegibility(p, {
220
+ docsDir: path.join(root, config.docs),
221
+ ...(config.legibility ? { config: config.legibility } : {}),
222
+ });
223
+ if (legibility.counts.error !== 0) return false;
224
+ // Drafting mode: the schematic must match a re-draft of the current IR
225
+ // (AC-16.20) — an intent edited after the last draft_schematic call means
226
+ // the sheet on disk no longer reflects the design and the stage stays
227
+ // active until a re-draft.
228
+ const intentRel = defaultIntentPath(config.schematic);
229
+ if (existsSync(path.join(root, intentRel))) {
230
+ const dry = await draftSchematicToText({
231
+ repoRoot: root,
232
+ schematic: config.schematic,
233
+ intentPath: intentRel,
234
+ docsDir: config.docs,
235
+ });
236
+ if (!dry.ok) return false;
237
+ if (dry.text !== (await readFile(p, 'utf8'))) return false;
238
+ }
239
+ return true;
178
240
  },
179
241
  prompt: () =>
180
- 'Stage 4: schematic. An empty KiCad project has already been scaffolded and wired into .copperhead/config.json (an empty schematic and a blank board with a default outline). Populate the existing schematic with edit_file write_file refuses KiCad files, so add lib_symbols, symbols, and connectivity by anchored edits into the file that already exists. Work ONE part at a time, not in large blocks: add a symbol (its lib_symbols entry if new, then its placement), run run_erc, fix any violation, then move to the next part small incremental edits keep a geometry or grid slip local instead of forcing a full-block rewrite. When you add a lib_symbols entry, use the exact canonical KiCad lib_id (e.g. Device:R, Connector:USB_C_Receptacle_USB2.0_16P) and reproduce the real part\'s pins faithfully never invent pin numbers, names, or electrical types. Once symbols are placed, run verify_symbols and reconcile every divergence it reports (a wrong lib_id or pin set passes ERC but is still wrong); if it flags a renamed symbol, adopt the real name it suggests. Build subsystem by subsystem from BOM.md and SUBSYSTEMS.md. Same net names and refdes everywhere. Two KiCad rules the pipeline has repeatedly tripped on: (1) a net label placed on a pin only NAMES the netit is NOT an electrical connection unless a wire actually reaches the pin; ERC will report the pin unconnected until you draw the wire. (2) Place every symbol origin and every wire endpoint on the 1.27mm (50mil) grid; an off-grid pin silently fails to connect and costs turns to diagnose. Update PINOUT.md as you assign pins; check the strapping table first.',
242
+ 'Stage 4: schematic. An empty KiCad project has already been scaffolded and wired into .copperhead/config.json. You author INTENT, never geometry: write the netlist-intent IR and call draft_schematic the deterministic engine computes every coordinate, wire, label, power symbol, and group box, and the sheet it draws satisfies the drafting standard by construction (captioned group boxes per SUBSYSTEMS.md subsystem, left-to-right flow, rails up and grounds down, net labels between groups, filled title block). The IR (schematic.intent.json) is JSON: {"version": 1, "parts": [{"ref", "libId", "value", "footprint", "group"}], "nets": [{"name", "pins": ["REF.PIN", …], "kind"?}], "noConnect": ["REF.PIN", …], "hints"?: {"groupOrder"?, "paper"?, "date"?}}. Build it from BOM.md (same refdes and values validation cross-checks and refuses mismatches) and SUBSYSTEMS.md (every non-power part names one subsystem heading as its group). Use exact canonical KiCad lib_ids (e.g. Device:R) and REAL pin numbers from the library: the pin dossier below (when present) already lists every BOM part\'s installed symbol and its real pins — work from it and from symbol_pins rather than reading .kicad_sym files, and validation lists a part\'s actual pins when you name one that does not exist. Declare every deliberately unused pin in noConnect; power rails are recognized from pin types automatically (override with "kind" only when the inference is wrong the draft report lists every net\'s resolved class). Pass the full IR as intent_json to draft_schematic; the report embeds the legibility findings and the score for the fresh sheet. To repair ANY finding (ERC, legibility, validation), fix the IR and call draft_schematic again edit_file is refused on the drafted sheet. Text-collision findings scale with TEXT LENGTH: a net label, part value, or SUBSYSTEMS heading that is shorter draws a smaller box, so renaming a colliding net (and updating PINOUT.md) or tightening a long heading is a real repair lever; paper size and declaration order are not (placement is grid-derived). When the draft is clean run run_erc and check_drift, update PINOUT.md to match the IR\'s pin assignments, and finish.',
181
243
  },
182
244
  {
183
245
  name: 'layout-draft',
@@ -259,6 +321,36 @@ async function emitJlcpcbAfterOutputs(stageName: string, opts: CreateOptions): P
259
321
  if (out) opts.log(stageLine('outputs', `emitted ${out} (JLCPCB assembly BOM)`, 'ok'));
260
322
  }
261
323
 
324
+ /**
325
+ * The generic "contract not met" line names no defect. For the schematic stage
326
+ * the most common gap after the electrical gates go green is legibility, so
327
+ * name the finding counts by kind — the resume then starts on the actual work
328
+ * instead of rediscovering it.
329
+ */
330
+ async function contractGapDetail(stageName: string, root: string, config: CopperheadConfig): Promise<string> {
331
+ const generic = 'the run finished but the stage completion contract is not met — no usable artifact was produced';
332
+ if (stageName !== 'schematic' || !config.schematic) return generic;
333
+ const p = path.join(root, config.schematic);
334
+ if (!existsSync(p)) return generic;
335
+ try {
336
+ const report = await checkLegibility(p, {
337
+ docsDir: path.join(root, config.docs),
338
+ ...(config.legibility ? { config: config.legibility } : {}),
339
+ });
340
+ if (report.counts.error > 0) {
341
+ const byKind = new Map<string, number>();
342
+ for (const f of report.findings.filter((f) => f.severity === 'error')) {
343
+ byKind.set(f.kind, (byKind.get(f.kind) ?? 0) + 1);
344
+ }
345
+ const counts = [...byKind].map(([k, n]) => `${k}: ${n}`).join(', ');
346
+ return `the schematic stage contract is not met: ${report.counts.error} error-severity legibility finding(s) remain (${counts}); resume to reconcile them`;
347
+ }
348
+ } catch {
349
+ // fall through: an unreadable schematic already fails earlier contract steps
350
+ }
351
+ return generic;
352
+ }
353
+
262
354
  /** Stages whose output is a KiCad file worth rendering to an image (5.4). */
263
355
  const KICAD_STAGES = new Set(['schematic', 'layout-draft', 'outputs']);
264
356
 
@@ -278,7 +370,10 @@ function isManagedPath(f: string, config: CopperheadConfig): boolean {
278
370
  f.startsWith('openspec/') ||
279
371
  f.startsWith('outputs/') ||
280
372
  f.startsWith('firmware/') ||
373
+ f.startsWith('sym-lib-cache/') ||
281
374
  f === '.gitignore' ||
375
+ path.basename(f) === 'sym-lib-table' ||
376
+ path.basename(f) === 'schematic.intent.json' ||
282
377
  /\.(kicad_sch|kicad_pcb|kicad_pro|kicad_prl)$/.test(f)
283
378
  );
284
379
  }
@@ -387,15 +482,22 @@ async function diagnose(input: {
387
482
  const p = provider;
388
483
  const excerpt = await transcriptExcerpt(input.transcriptDir);
389
484
  return await withTimeout(
390
- () =>
391
- diagnoseStageFailure(p, {
485
+ async () => {
486
+ // Fact-check symbol-availability claims before the model judges them: a
487
+ // refusal narrating "library not installed" is adjudicated from the
488
+ // machine's actual libraries, not from the narration (I15/#197). Inside
489
+ // the watchdog, so a wedged filesystem scan cannot outlive timeoutMs.
490
+ const symbolFacts = await symbolAvailabilityFacts(`${input.failure}\n${excerpt}`).catch(() => '');
491
+ return diagnoseStageFailure(p, {
392
492
  stageName: input.stageName,
393
493
  stageGoal: input.stageGoal,
394
494
  failure: input.failure,
395
495
  excerpt,
396
496
  attempt: input.attempt,
397
497
  maxAttempts: input.maxAttempts,
398
- }),
498
+ ...(symbolFacts ? { symbolFacts } : {}),
499
+ });
500
+ },
399
501
  input.timeoutMs,
400
502
  () => p.close?.(),
401
503
  );
@@ -643,7 +745,16 @@ export async function runCreate(opts: CreateOptions): Promise<{ ok: boolean; com
643
745
  const brief = await readFile(path.resolve(opts.briefPath), 'utf8');
644
746
  // Hashed from the content already in hand: a brief edited mid-pipeline shows
645
747
  // up as a different sha256 in the next stage's metadata (AC-8.1).
646
- const briefMeta = { path: opts.briefPath, sha256: createHash('sha256').update(brief).digest('hex') };
748
+ const resolvedBrief = path.resolve(opts.briefPath);
749
+ const relativeBrief = path.relative(opts.repoRoot, resolvedBrief);
750
+ const briefPath =
751
+ relativeBrief.startsWith('..') || path.isAbsolute(relativeBrief)
752
+ ? `external:${path.basename(resolvedBrief)}`
753
+ : relativeBrief;
754
+ const briefMeta = {
755
+ path: briefPath,
756
+ sha256: createHash('sha256').update(brief).digest('hex'),
757
+ };
647
758
  const config = await loadConfig(opts.repoRoot);
648
759
  // Fail fast on a nearly-full disk (4.1): a create run writes fab outputs and
649
760
  // KiCad local history and can otherwise fill the disk mid-stage, failing with
@@ -663,6 +774,11 @@ export async function runCreate(opts: CreateOptions): Promise<{ ok: boolean; com
663
774
  const pruned = await pruneHistoryDir(opts.repoRoot);
664
775
  if (pruned) opts.log(dim(`startup: pruned ${pruned} old .history/ entrie(s) to cap local-history growth`));
665
776
  await openspecInit(opts.repoRoot);
777
+ // Stamp the repo create-produced before any stage runs: the marker scopes the
778
+ // legibility finish gate and the fab release gate, and it must hold on
779
+ // resumed runs whose project predates the marker (bootstrapKicadProject
780
+ // no-ops on those, so it cannot be the only writer).
781
+ await markCreateOrigin(opts.repoRoot);
666
782
  const completed: string[] = [];
667
783
  const stageCosts: StageCost[] = [];
668
784
 
@@ -682,6 +798,15 @@ export async function runCreate(opts: CreateOptions): Promise<{ ok: boolean; com
682
798
  opts.log(stageLine(stage.name, 'already complete (resuming past it)', 'ok'));
683
799
  await commitResumedStage(opts, config, stage.name);
684
800
  completed.push(stage.name);
801
+ if (stage.name === 'spec-seed') {
802
+ try {
803
+ await writeBriefHash(opts.repoRoot, config.docs, briefMeta);
804
+ } catch (err) {
805
+ opts.log(
806
+ `warning: could not record brief provenance (${(err as Error).message})`,
807
+ );
808
+ }
809
+ }
685
810
  stageCosts.push({ name: stage.name, resumed: true, wallMs: 0, turns: 0, tokensIn: 0, tokensOut: 0, cacheHits: 0 });
686
811
  await emitJlcpcbAfterOutputs(stage.name, opts);
687
812
  continue;
@@ -721,13 +846,38 @@ export async function runCreate(opts: CreateOptions): Promise<{ ok: boolean; com
721
846
  `running${attempt > 1 ? ` (attempt ${attempt}/${config.maxStageRetries + 1})` : ''}`,
722
847
  ),
723
848
  );
849
+ // The BOM freezes before this stage, so every part's real pins are
850
+ // computable before the first turn — recomputed per attempt, since a
851
+ // rolled-back retry can run against a different BOM than its
852
+ // predecessor. Advisory only: any failure degrades to no block.
853
+ let dossierBlock = '';
854
+ if (stage.name === 'schematic') {
855
+ try {
856
+ const bomPath = path.join(opts.repoRoot, config.docs, 'BOM.md');
857
+ if (existsSync(bomPath)) {
858
+ // Bounded: a slow or wedged library scan must delay the stage by a
859
+ // fixed cost at most — on timeout the stage simply runs dossier-less.
860
+ const dossier = await withTimeout(
861
+ async () => bomSymbolDossier(await readFile(bomPath, 'utf8'), await symbolSearchDirs()),
862
+ 60_000,
863
+ );
864
+ if (dossier) {
865
+ dossierBlock =
866
+ '\n\n## Installed-symbol pin dossier (machine-verified)\nEach BOM part resolved against the KiCad libraries installed on THIS machine: the top name-match lib_id and its REAL pins (number=name/electrical-type). Confirm the match fits the BOM part; alternatives are listed. Passives (R/C/L) draw from their canonical Device symbols and are omitted. Use these pins for REF.PIN endpoints instead of reading .kicad_sym files; for any part not listed, call symbol_pins.\n' +
867
+ dossier;
868
+ }
869
+ }
870
+ } catch {
871
+ // the dossier is context, never a gate — the stage runs without it
872
+ }
873
+ }
724
874
  const res = await runAgentLoop({
725
875
  repoRoot: opts.repoRoot,
726
876
  model: opts.model,
727
877
  request: `create pipeline stage: ${stage.name}`,
728
878
  stagePrompt: guidance
729
- ? `${basePrompt}\n\n## Recovery guidance (a previous attempt did not complete this stage — do this differently)\n${guidance}`
730
- : basePrompt,
879
+ ? `${basePrompt}${dossierBlock}\n\n## Recovery guidance (a previous attempt did not complete this stage — do this differently)\n${guidance}`
880
+ : `${basePrompt}${dossierBlock}`,
731
881
  interactive: opts.interactive ?? false,
732
882
  allowDirty: true, // stages build on each other's uncommitted state within the pipeline
733
883
  ...(stageTurns !== undefined ? { maxTurns: stageTurns } : {}),
@@ -759,7 +909,7 @@ export async function runCreate(opts: CreateOptions): Promise<{ ok: boolean; com
759
909
  res.outcome !== 'success'
760
910
  ? `the run ended as "${res.outcome}" (${res.exitPath})`
761
911
  : !(await stage.isComplete(opts.repoRoot, config.docs))
762
- ? 'the run finished but the stage completion contract is not met — no usable artifact was produced'
912
+ ? await contractGapDetail(stage.name, opts.repoRoot, config)
763
913
  : null;
764
914
  if (!failure) {
765
915
  stageDone = true;
@@ -818,6 +968,15 @@ export async function runCreate(opts: CreateOptions): Promise<{ ok: boolean; com
818
968
  return { ok: false, completed };
819
969
  }
820
970
  completed.push(stage.name);
971
+ if (stage.name === 'spec-seed') {
972
+ try {
973
+ await writeBriefHash(opts.repoRoot, config.docs, briefMeta);
974
+ } catch (err) {
975
+ opts.log(
976
+ `warning: could not record brief provenance (${(err as Error).message})`,
977
+ );
978
+ }
979
+ }
821
980
  await renderStageArtifacts(opts, stage.name, stageTranscriptDir);
822
981
  await emitJlcpcbAfterOutputs(stage.name, opts);
823
982
  logCumulative(opts, stageCosts);
@@ -1,5 +1,6 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
+ import { execa } from 'execa';
3
4
  import { existsSync } from 'node:fs';
4
5
  import path from 'node:path';
5
6
  import {
@@ -14,6 +15,7 @@ import {
14
15
  } from '../config.js';
15
16
  import { kicadCliVersion } from '../kicad/cli.js';
16
17
  import { redactSecrets } from '../util/redact.js';
18
+ import { isNotFoundError } from '../util/preflight.js';
17
19
 
18
20
  const execFileP = promisify(execFile);
19
21
 
@@ -44,6 +46,7 @@ export interface DoctorDeps {
44
46
  nodeVersion: string;
45
47
  kicadVersion: () => Promise<string>;
46
48
  gitVersion: () => Promise<string>;
49
+ openspecVersion: () => Promise<string>;
47
50
  env: NodeJS.ProcessEnv;
48
51
  }
49
52
 
@@ -54,6 +57,15 @@ function defaultDeps(): DoctorDeps {
54
57
  // `git --version` prints "git version 2.34.1"; keep only the number, the
55
58
  // report already labels the row "git".
56
59
  gitVersion: async () => (await execFileP('git', ['--version'])).stdout.trim().replace(/^git version\s+/, ''),
60
+ /**
61
+ * Probes `openspec --version` via execa, the same probe shape as the real
62
+ * call site (src/openspec/cli.ts): execa resolves Windows .cmd/.bat shims
63
+ * via cross-spawn without a shell, so a missing binary still yields ENOENT
64
+ * (what isNotFoundError expects) on every platform, instead of a
65
+ * shell-reported exit 127/"not found".
66
+ * @returns the trimmed stdout of `openspec --version` (e.g. "1.8.0").
67
+ */
68
+ openspecVersion: async () => (await execa('openspec', ['--version'])).stdout.trim(),
57
69
  env: process.env,
58
70
  };
59
71
  }
@@ -99,6 +111,41 @@ async function gitCheck(probe: () => Promise<string>): Promise<DoctorCheck> {
99
111
  }
100
112
  }
101
113
 
114
+ /**
115
+ * Report whether the `openspec` CLI is reachable, needed for `validate_change`
116
+ * and the `create` pipeline. Fails soft like `kicadCheck`/`gitCheck`: a
117
+ * missing or erroring probe is returned as a `fail` check, never thrown.
118
+ * @param probe resolves the openspec version string, or rejects if the CLI
119
+ * can't be run (e.g. not found on PATH).
120
+ * @returns an `ok` check with the version on success; a `fail` check with an
121
+ * install hint when `probe` rejects with a not-found error (per
122
+ * `isNotFoundError`), or a `fail` check with the flattened error message
123
+ * otherwise.
124
+ */
125
+ async function openspecCheck(probe: () => Promise<string>): Promise<DoctorCheck> {
126
+ try {
127
+ return { name: 'openspec', status: 'ok', detail: await probe() };
128
+ } catch (err) {
129
+ if (isNotFoundError(err)) {
130
+ return {
131
+ name: 'openspec',
132
+ status: 'fail',
133
+ detail: 'not found on PATH',
134
+ hint: 'npm i -g @fission-ai/openspec; validate_change and the create pipeline need it.',
135
+ };
136
+ }
137
+ // Collapse embedded newlines/whitespace from a raw shell/subprocess error:
138
+ // formatDoctor's column layout assumes a single-line detail, and wrapWords
139
+ // splits on plain spaces only.
140
+ const rawMessage = (err as Error).message || String(err);
141
+ return {
142
+ name: 'openspec',
143
+ status: 'fail',
144
+ detail: rawMessage.replace(/\s+/g, ' ').trim(),
145
+ };
146
+ }
147
+ }
148
+
102
149
  /**
103
150
  * Map a resolved model to the credential its provider needs, mirroring
104
151
  * makeProvider's prefix routing (agent/loop.ts). Presence-only: it checks that a
@@ -131,9 +178,9 @@ export function checkCredential(
131
178
  const settings = compat ?? { apiKeyEnv: DEFAULT_API_KEY_ENV };
132
179
  // Display only: some endpoints embed a credential in the URL itself (a
133
180
  // query param, userinfo) — Gemini's compat endpoint does this with
134
- // ?key=..., in a format redactSecrets' key-shape patterns don't cover.
135
- // Drop the query and userinfo entirely rather than pattern-matching, so
136
- // this holds regardless of what a given provider's key looks like.
181
+ // ?key=.... redactSecrets covers known key shapes, but a key embedded in
182
+ // a URL query isn't reliably one of them, so drop the query and userinfo
183
+ // entirely rather than pattern-matching, regardless of shape.
137
184
  // isLocalEndpoint() below still runs against the raw settings.baseURL,
138
185
  // never this.
139
186
  const where = (() => {
@@ -380,6 +427,7 @@ export async function runDoctor(opts: RunDoctorOptions): Promise<DoctorReport> {
380
427
  nodeCheck(deps.nodeVersion),
381
428
  await kicadCheck(deps.kicadVersion),
382
429
  await gitCheck(deps.gitVersion),
430
+ await openspecCheck(deps.openspecVersion),
383
431
  providerCheck(opts.model, config, deps.env),
384
432
  ];
385
433
  if (resolvedModel) {
package/src/config.ts CHANGED
@@ -2,9 +2,32 @@ import { readFile } from 'node:fs/promises';
2
2
  import { existsSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
 
5
+ /**
6
+ * Optional `legibility` block: checker thresholds and per-family severity
7
+ * overrides (`off` disables a family). Unknown keys and invalid values are
8
+ * ignored by the checker's own sanitizer, so a config typo cannot crash a run.
9
+ */
10
+ export interface LegibilityUserConfig {
11
+ thresholds?: {
12
+ gridPitch?: number;
13
+ minPitch?: number;
14
+ utilization?: number;
15
+ maxWireLength?: number;
16
+ familyCap?: number;
17
+ };
18
+ severity?: Record<string, 'error' | 'advisory' | 'off'>;
19
+ /** Scorer tuning: per-metric weights and the known-good composite floor. */
20
+ score?: {
21
+ weights?: Record<string, number>;
22
+ floor?: number;
23
+ };
24
+ }
25
+
5
26
  export interface CopperheadConfig {
6
27
  schematic: string | null;
7
28
  board: string | null;
29
+ /** Schematic legibility checker thresholds and severity overrides. */
30
+ legibility?: LegibilityUserConfig;
8
31
  docs: string;
9
32
  model: string | null;
10
33
  maxTurns: number;
@@ -106,6 +129,7 @@ export async function loadConfig(repoRoot: string): Promise<CopperheadConfig> {
106
129
  ...(typeof raw.apiKeyEnv === 'string' && raw.apiKeyEnv.trim() ? { apiKeyEnv: raw.apiKeyEnv.trim() } : {}),
107
130
  ...(raw.generatedHashes ? { generatedHashes: raw.generatedHashes } : {}),
108
131
  ...(raw.origin === 'create' || raw.origin === 'init' ? { origin: raw.origin } : {}),
132
+ ...(raw.legibility && typeof raw.legibility === 'object' ? { legibility: raw.legibility } : {}),
109
133
  };
110
134
  }
111
135
 
@@ -1,8 +1,9 @@
1
1
  import { existsSync } from 'node:fs';
2
- import { writeFile } from 'node:fs/promises';
2
+ import { mkdir, writeFile } from 'node:fs/promises';
3
3
  import { createHash } from 'node:crypto';
4
4
  import path from 'node:path';
5
5
  import { configPath, loadConfig, type CopperheadConfig } from '../config.js';
6
+ import { CREATE_ORIGIN } from './fab.js';
6
7
 
7
8
  /**
8
9
  * The create pipeline starts from a brief with no KiCad files, but the agent
@@ -37,8 +38,8 @@ function uuidFrom(seed: string): string {
37
38
  function emptySchematic(rootUuid: string): string {
38
39
  return `(kicad_sch
39
40
  (version 20231120)
40
- (generator "eeschema")
41
- (generator_version "8.0")
41
+ (generator "copperhead-draft")
42
+ (generator_version "0")
42
43
  (uuid "${rootUuid}")
43
44
  (paper "A4")
44
45
  (lib_symbols)
@@ -147,9 +148,25 @@ function projectFile(slug: string, rootUuid: string): string {
147
148
  }
148
149
 
149
150
  async function persist(repoRoot: string, config: CopperheadConfig): Promise<void> {
151
+ await mkdir(path.dirname(configPath(repoRoot)), { recursive: true });
150
152
  await writeFile(configPath(repoRoot), JSON.stringify(config, null, 2) + '\n', 'utf8');
151
153
  }
152
154
 
155
+ /**
156
+ * Stamp the config as create-produced (`origin: "create"`). The marker is what
157
+ * scopes the legibility finish gate (`isCreateProducedRepo` feeds the
158
+ * obligations ledger) and the fab release gate — a gate hung on a marker
159
+ * nothing writes is silently inert, so `runCreate` stamps it up front and
160
+ * `bootstrapKicadProject` re-stamps on every (re-)scaffold, covering the
161
+ * rollback path that deletes an uncommitted config.
162
+ */
163
+ export async function markCreateOrigin(repoRoot: string): Promise<void> {
164
+ const config = await loadConfig(repoRoot);
165
+ if (config.origin === CREATE_ORIGIN) return;
166
+ config.origin = CREATE_ORIGIN;
167
+ await persist(repoRoot, config);
168
+ }
169
+
153
170
  /**
154
171
  * Ensure a KiCad project exists and is wired into config. No-op (returns null)
155
172
  * when config already points at a schematic on disk. If project files exist but
@@ -160,6 +177,10 @@ async function persist(repoRoot: string, config: CopperheadConfig): Promise<void
160
177
  export async function bootstrapKicadProject(repoRoot: string, brief: string): Promise<string | null> {
161
178
  const config = await loadConfig(repoRoot);
162
179
  if (config.schematic && existsSync(path.join(repoRoot, config.schematic))) return null;
180
+ // Only `create` scaffolds through here, so the repo is create-produced by
181
+ // definition; stamping on every scaffold keeps the marker alive across the
182
+ // rollback-then-rescaffold path (git clean deletes an uncommitted config).
183
+ config.origin = CREATE_ORIGIN;
163
184
 
164
185
  const slug = projectSlug(brief);
165
186
  const schRel = `${slug}.kicad_sch`;