copperhead 0.9.0 → 0.11.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 (142) hide show
  1. package/NOTICE +1 -1
  2. package/README.md +47 -8
  3. package/dist/agent/context.js +2 -0
  4. package/dist/agent/context.js.map +1 -0
  5. package/dist/agent/dock-renderer.js +2 -2
  6. package/dist/agent/dock-renderer.js.map +1 -1
  7. package/dist/agent/envelope.js +105 -0
  8. package/dist/agent/envelope.js.map +1 -0
  9. package/dist/agent/filetools.js +24 -1
  10. package/dist/agent/filetools.js.map +1 -1
  11. package/dist/agent/ledger.js +24 -0
  12. package/dist/agent/ledger.js.map +1 -1
  13. package/dist/agent/loop.js +63 -72
  14. package/dist/agent/loop.js.map +1 -1
  15. package/dist/agent/prompts.js +4 -3
  16. package/dist/agent/prompts.js.map +1 -1
  17. package/dist/agent/providers/claude-code.js +17 -1
  18. package/dist/agent/providers/claude-code.js.map +1 -1
  19. package/dist/agent/providers/codex.js +84 -39
  20. package/dist/agent/providers/codex.js.map +1 -1
  21. package/dist/agent/providers/tool-protocol.js +21 -0
  22. package/dist/agent/providers/tool-protocol.js.map +1 -1
  23. package/dist/agent/recovery.js +186 -15
  24. package/dist/agent/recovery.js.map +1 -1
  25. package/dist/agent/registry.js +49 -0
  26. package/dist/agent/registry.js.map +1 -0
  27. package/dist/agent/render.js +2 -2
  28. package/dist/agent/render.js.map +1 -1
  29. package/dist/agent/theme.js +10 -5
  30. package/dist/agent/theme.js.map +1 -1
  31. package/dist/agent/tools.js +100 -586
  32. package/dist/agent/tools.js.map +1 -1
  33. package/dist/agent/transcript.js +2 -0
  34. package/dist/agent/transcript.js.map +1 -1
  35. package/dist/capabilities/define.js +35 -0
  36. package/dist/capabilities/define.js.map +1 -0
  37. package/dist/capabilities/handlers.js +744 -0
  38. package/dist/capabilities/handlers.js.map +1 -0
  39. package/dist/capabilities/helpers.js +39 -0
  40. package/dist/capabilities/helpers.js.map +1 -0
  41. package/dist/capabilities/index.js +50 -0
  42. package/dist/capabilities/index.js.map +1 -0
  43. package/dist/capabilities/skills/generate-report.js +23 -0
  44. package/dist/capabilities/skills/generate-report.js.map +1 -0
  45. package/dist/cli.js +158 -0
  46. package/dist/cli.js.map +1 -1
  47. package/dist/commands/check.js +33 -1
  48. package/dist/commands/check.js.map +1 -1
  49. package/dist/commands/create.js +181 -26
  50. package/dist/commands/create.js.map +1 -1
  51. package/dist/commands/doctor.js +83 -6
  52. package/dist/commands/doctor.js.map +1 -1
  53. package/dist/commands/skill.js +109 -0
  54. package/dist/commands/skill.js.map +1 -0
  55. package/dist/commands/sync.js +3 -1
  56. package/dist/commands/sync.js.map +1 -1
  57. package/dist/config.js +19 -6
  58. package/dist/config.js.map +1 -1
  59. package/dist/kicad/bootstrap.js +24 -3
  60. package/dist/kicad/bootstrap.js.map +1 -1
  61. package/dist/kicad/cli.js +106 -18
  62. package/dist/kicad/cli.js.map +1 -1
  63. package/dist/kicad/dossier.js +207 -0
  64. package/dist/kicad/dossier.js.map +1 -0
  65. package/dist/kicad/draft/draft.js +135 -0
  66. package/dist/kicad/draft/draft.js.map +1 -0
  67. package/dist/kicad/draft/engine.js +5310 -0
  68. package/dist/kicad/draft/engine.js.map +1 -0
  69. package/dist/kicad/draft/ir.js +368 -0
  70. package/dist/kicad/draft/ir.js.map +1 -0
  71. package/dist/kicad/draft/symsource.js +504 -0
  72. package/dist/kicad/draft/symsource.js.map +1 -0
  73. package/dist/kicad/emit.js +220 -0
  74. package/dist/kicad/emit.js.map +1 -0
  75. package/dist/kicad/fab.js +13 -0
  76. package/dist/kicad/fab.js.map +1 -1
  77. package/dist/kicad/legibility.js +608 -0
  78. package/dist/kicad/legibility.js.map +1 -0
  79. package/dist/kicad/score.js +431 -0
  80. package/dist/kicad/score.js.map +1 -0
  81. package/dist/kicad/sexp.js +265 -6
  82. package/dist/kicad/sexp.js.map +1 -1
  83. package/dist/kicad/symlib.js +346 -16
  84. package/dist/kicad/symlib.js.map +1 -1
  85. package/dist/mcp/server.js +485 -0
  86. package/dist/mcp/server.js.map +1 -0
  87. package/dist/memory/bom-table.js +75 -39
  88. package/dist/memory/bom-table.js.map +1 -1
  89. package/dist/memory/scaffold.js +14 -1
  90. package/dist/memory/scaffold.js.map +1 -1
  91. package/dist/util/redact.js +6 -0
  92. package/dist/util/redact.js.map +1 -1
  93. package/package.json +13 -8
  94. package/src/agent/context.ts +35 -0
  95. package/src/agent/dock-renderer.ts +3 -2
  96. package/src/agent/envelope.ts +124 -0
  97. package/src/agent/filetools.ts +26 -1
  98. package/src/agent/ledger.ts +24 -0
  99. package/src/agent/loop.ts +73 -78
  100. package/src/agent/prompts.ts +4 -3
  101. package/src/agent/providers/claude-code.ts +22 -1
  102. package/src/agent/providers/codex.ts +91 -42
  103. package/src/agent/providers/tool-protocol.ts +22 -0
  104. package/src/agent/recovery.ts +183 -13
  105. package/src/agent/registry.ts +58 -0
  106. package/src/agent/render.ts +4 -3
  107. package/src/agent/theme.ts +15 -5
  108. package/src/agent/tools.ts +124 -628
  109. package/src/agent/transcript.ts +6 -0
  110. package/src/agent/types.ts +10 -5
  111. package/src/capabilities/define.ts +88 -0
  112. package/src/capabilities/handlers.ts +769 -0
  113. package/src/capabilities/helpers.ts +37 -0
  114. package/src/capabilities/index.ts +53 -0
  115. package/src/capabilities/skills/generate-report.ts +25 -0
  116. package/src/cli.ts +154 -0
  117. package/src/commands/check.ts +51 -1
  118. package/src/commands/create.ts +183 -21
  119. package/src/commands/doctor.ts +85 -6
  120. package/src/commands/skill.ts +127 -0
  121. package/src/commands/sync.ts +5 -3
  122. package/src/config.ts +56 -8
  123. package/src/kicad/bootstrap.ts +24 -3
  124. package/src/kicad/cli.ts +129 -18
  125. package/src/kicad/dossier.ts +217 -0
  126. package/src/kicad/draft/draft.ts +173 -0
  127. package/src/kicad/draft/engine.ts +5274 -0
  128. package/src/kicad/draft/ir.ts +416 -0
  129. package/src/kicad/draft/symsource.ts +549 -0
  130. package/src/kicad/emit.ts +300 -0
  131. package/src/kicad/fab.ts +15 -0
  132. package/src/kicad/legibility.ts +695 -0
  133. package/src/kicad/score.ts +502 -0
  134. package/src/kicad/sexp.ts +346 -6
  135. package/src/kicad/symlib.ts +364 -18
  136. package/src/mcp/server.ts +560 -0
  137. package/src/memory/bom-table.ts +85 -38
  138. package/src/memory/scaffold.ts +14 -1
  139. package/src/util/redact.ts +6 -0
  140. package/dist/memory/synap.js +0 -152
  141. package/dist/memory/synap.js.map +0 -1
  142. package/src/memory/synap.ts +0 -217
@@ -1,597 +1,111 @@
1
- import path from 'node:path';
2
- import { writeFile, mkdir, appendFile, readFile } from 'node:fs/promises';
3
- import { toolReadFile, toolWriteFile, toolEditFile, toolSearch } from './filetools.js';
4
- import { resolveInRepo, isKicadFile } from '../util/paths.js';
5
- import { runErc, runDrc, exportSvg, exportFab, kicadLoadError, isProbeableKicadFile } from '../kicad/cli.js';
6
- import { formatViolations } from '../kicad/report.js';
7
- import { listSymbols, listNets } from '../kicad/sexp.js';
8
- import { verifySchematicSymbols } from '../kicad/symlib.js';
9
- import { checkDrift } from '../memory/drift.js';
10
- import { saveConstraint, classifyAffectsTarget, affectsTargetExists } from '../memory/constraints.js';
11
- import { openspecValidate } from '../openspec/cli.js';
12
- import { existsSync } from 'node:fs';
13
- const str = (args, key) => {
14
- const v = args[key];
15
- if (typeof v !== 'string' || v === '')
16
- throw new Error(`missing required string arg "${key}"`);
17
- return v;
18
- };
19
- // U+FFFD (the Unicode replacement character) is what a byte sequence becomes
20
- // when UTF-8 decoding fails — most often a multibyte glyph (Ω, µ, ±, °) split
21
- // across a streaming chunk boundary and decoded per-chunk upstream in the
22
- // provider SDK (I2). It never appears in a legitimately authored PCB doc, so
23
- // its presence in a content-bearing tool arg means the value arrived corrupted.
24
- // Reject the call before it lands on disk so the model re-emits; the corruption
25
- // is nondeterministic (it depends on where a chunk boundary fell), so the retry
26
- // almost always comes through clean — far cheaper than shipping a mangled value
27
- // like "5.1kΩ" → "5.1k�" into DECISIONS.md and only noticing on review.
28
- const REPLACEMENT_CHAR = '�';
29
- export function corruptionError(fields) {
30
- const bad = Object.entries(fields)
31
- .filter(([, v]) => typeof v === 'string' && v.includes(REPLACEMENT_CHAR))
32
- .map(([k]) => k);
33
- if (!bad.length)
34
- return null;
35
- return `rejected: the ${bad.join(', ')} value contains U+FFFD (�), the replacement character that signals a UTF-8 decoding error — a special character (e.g. Ω, µ, ±, °) was likely mangled in transit. Re-send this exact call with the intended character written correctly, or spell it in ASCII (e.g. "ohm", "uF", "+/-", "deg").`;
1
+ import { corruptionError } from '../capabilities/helpers.js';
2
+ import { flatten, failResult, seal, unavailable } from './envelope.js';
3
+ import { registry } from './registry.js';
4
+ import { withRetry, isRateLimit } from '../util/retry.js';
5
+ import { MAX_TURN_TIMEOUTS, TurnTimeoutError, withWatchdog } from './recovery.js';
6
+ export { corruptionError, registry };
7
+ export function availableTools(ctx) {
8
+ return registry.list(ctx);
36
9
  }
37
- function markTouched(ctx, rel) {
38
- ctx.filesTouched.add(rel);
39
- if (isKicadFile(rel)) {
40
- ctx.ledger.onKicadEdit(rel);
41
- if (rel.endsWith('.kicad_sch'))
42
- ctx.lastErc = null;
43
- if (rel.endsWith('.kicad_pcb'))
44
- ctx.lastDrc = null;
10
+ export async function dispatchToolResult(ctx, name, args, opts = {}) {
11
+ if (opts.only && !opts.only.has(name))
12
+ return unavailable(name, ctx.editsUnlocked, 'not part of this skill');
13
+ const entry = availableTools(ctx).find((e) => e.name === name);
14
+ if (!entry)
15
+ return unavailable(name, ctx.editsUnlocked);
16
+ try {
17
+ if (entry.kind === 'skill') {
18
+ if (!opts.provider)
19
+ return failResult('validation', `skill "${name}" requires a provider`, 'diagnostic');
20
+ return await runSkillSubRun({ ctx, skill: entry, args, provider: opts.provider });
21
+ }
22
+ // Unified retry policy (design D10): a thrown 429 backs off through the
23
+ // same withRetry/isRateLimit pair the provider path uses. Typed envelope
24
+ // failures (validation/refusal/unavailable) return, so they never retry;
25
+ // local tool errors are not 429s, so they surface on the first throw.
26
+ return await withRetry(() => entry.handler(ctx, args), { isRetryable: isRateLimit, baseMs: 250 });
45
27
  }
46
- else if (rel.endsWith('.md')) {
47
- ctx.ledger.onDocEdit(rel);
28
+ catch (err) {
29
+ return failResult('exception', `error: ${err.message}`);
48
30
  }
49
31
  }
50
- export const TOOLS = [
51
- {
52
- schema: {
53
- name: 'read_file',
54
- description: 'Read a repo-relative file, optionally a line range. Returns text (line-numbered when ranged).',
55
- parameters: {
56
- type: 'object',
57
- properties: {
58
- path: { type: 'string' },
59
- start_line: { type: 'number' },
60
- end_line: { type: 'number' },
61
- },
62
- required: ['path'],
63
- },
64
- },
65
- requiresUnlock: false,
66
- handler: (ctx, args) => toolReadFile(ctx.repoRoot, str(args, 'path'), args.start_line, args.end_line),
67
- },
68
- {
69
- schema: {
70
- name: 'search',
71
- description: 'Regex search over the repo (ripgrep-style). Optional glob filter, e.g. "**/*.kicad_sch".',
72
- parameters: {
73
- type: 'object',
74
- properties: { pattern: { type: 'string' }, glob: { type: 'string' } },
75
- required: ['pattern'],
76
- },
77
- },
78
- requiresUnlock: false,
79
- handler: async (ctx, args) => {
80
- const pattern = args.pattern;
81
- if (typeof pattern !== 'string' || pattern.trim() === '') {
82
- return 'error: search requires a non-empty regex in "pattern" (narrow by file with "glob", e.g. {"pattern": "GPIO", "glob": "**/*.md"}); to list files, use a broad pattern like "." with a glob';
83
- }
84
- const matches = await toolSearch(ctx.repoRoot, pattern, args.glob);
85
- if (!matches.length)
86
- return 'no matches';
87
- return matches.map((m) => `${m.file}:${m.line}: ${m.text}`).join('\n');
88
- },
89
- },
90
- {
91
- schema: {
92
- name: 'list_symbols',
93
- description: 'List schematic symbols: ref, value, footprint, sheet.',
94
- parameters: { type: 'object', properties: {}, required: [] },
95
- },
96
- requiresUnlock: false,
97
- handler: async (ctx) => {
98
- if (!ctx.config.schematic)
99
- return 'no schematic configured';
100
- const syms = await listSymbols(path.join(ctx.repoRoot, ctx.config.schematic));
101
- return JSON.stringify(syms.map(({ ref, value, footprint, sheet }) => ({ ref, value, footprint, sheet })), null, 2);
102
- },
103
- },
104
- {
105
- schema: {
106
- name: 'list_nets',
107
- description: 'List net names found in the schematic.',
108
- parameters: { type: 'object', properties: {}, required: [] },
109
- },
110
- requiresUnlock: false,
111
- handler: async (ctx) => {
112
- if (!ctx.config.schematic)
113
- return 'no schematic configured';
114
- return JSON.stringify(await listNets(path.join(ctx.repoRoot, ctx.config.schematic)));
115
- },
116
- },
117
- {
118
- schema: {
119
- name: 'propose_change',
120
- description: 'Write the OpenSpec change proposal for this run (the plan step). Must be called and validated before edit tools unlock.',
121
- parameters: {
122
- type: 'object',
123
- properties: {
124
- id: { type: 'string', description: 'kebab-case change id' },
125
- why: { type: 'string' },
126
- what_changes: { type: 'string', description: 'markdown bullet list of changes' },
127
- tasks: { type: 'string', description: 'markdown checklist of implementation steps' },
128
- },
129
- required: ['id', 'why', 'what_changes', 'tasks'],
130
- },
131
- },
132
- requiresUnlock: false,
133
- handler: async (ctx, args) => {
134
- const id = str(args, 'id');
135
- const dir = resolveInRepo(ctx.repoRoot, path.join('openspec', 'changes', id));
136
- await mkdir(dir, { recursive: true });
137
- const auto = ctx.interactive ? '' : '\n> Marker: AUTO (autonomous mode; auto-approved, reviewable after the fact)\n';
138
- await writeFile(path.join(dir, 'proposal.md'), `# Proposal: ${id}\n${auto}\n## Why\n\n${str(args, 'why')}\n\n## What Changes\n\n${str(args, 'what_changes')}\n`, 'utf8');
139
- await writeFile(path.join(dir, 'tasks.md'), `# Tasks\n\n${str(args, 'tasks')}\n`, 'utf8');
140
- ctx.changeId = id;
141
- return `proposal written to openspec/changes/${id}/ — now call validate_change`;
142
- },
143
- },
144
- {
145
- schema: {
146
- name: 'validate_change',
147
- description: 'Validate the current change proposal; on success the edit tools unlock.',
148
- parameters: { type: 'object', properties: {}, required: [] },
149
- },
150
- requiresUnlock: false,
151
- handler: async (ctx) => {
152
- if (!ctx.changeId)
153
- return 'no proposal yet: call propose_change first';
154
- let ok;
155
- let detail;
156
- if (existsSync(path.join(ctx.repoRoot, 'openspec', 'config.yaml'))) {
157
- const res = await openspecValidate(ctx.repoRoot, ctx.changeId);
158
- ok = res.ok;
159
- detail = res.output;
160
- }
161
- else {
162
- // No OpenSpec workspace in the target repo: structural validation of the
163
- // proposal files themselves (the invariant is the gate, not the CLI).
164
- const dir = path.join(ctx.repoRoot, 'openspec', 'changes', ctx.changeId);
165
- ok = existsSync(path.join(dir, 'proposal.md')) && existsSync(path.join(dir, 'tasks.md'));
166
- detail = ok ? 'structural validation passed (no openspec workspace)' : 'proposal files missing';
167
- }
168
- if (!ok)
169
- return `validation FAILED:\n${detail}`;
170
- ctx.proposalValidated = true;
171
- if (ctx.interactive) {
172
- const approved = await ctx.confirm(`Proposal ${ctx.changeId} validated. Unlock edit tools and proceed?`);
173
- if (!approved)
174
- return 'proposal validated but human declined; edits remain locked';
175
- }
176
- ctx.editsUnlocked = true;
177
- await ctx.transcript.event('edit-tools-unlocked', { changeId: ctx.changeId });
178
- return `validation passed; edit tools are now unlocked`;
179
- },
180
- },
181
- {
182
- schema: {
183
- name: 'edit_file',
184
- description: 'Exact-match anchored replace in an existing file. Requires a validated change proposal first (call propose_change then validate_change to unlock edits; both may be in the same reply, before this call). The anchor must be unique; widen it with surrounding lines if not. For renames, pass replace_all: true to replace every occurrence in one call.',
185
- parameters: {
186
- type: 'object',
187
- properties: {
188
- path: { type: 'string' },
189
- old_string: { type: 'string' },
190
- new_string: { type: 'string' },
191
- replace_all: { type: 'boolean' },
192
- },
193
- required: ['path', 'old_string', 'new_string'],
194
- },
195
- },
196
- requiresUnlock: true,
197
- handler: async (ctx, args) => {
198
- const corrupt = corruptionError({ new_string: args.new_string });
199
- if (corrupt)
200
- return corrupt;
201
- const rel = str(args, 'path');
202
- const abs = resolveInRepo(ctx.repoRoot, rel);
203
- // Text edits can corrupt an s-expression file in ways the editor cannot
204
- // see; a corrupted file then fails every later ERC/DRC with an opaque
205
- // error. Validate loadability with KiCad itself and roll the edit back
206
- // rather than letting the file drift unusable. Only schematics and
207
- // boards are probeable; .kicad_pro/.kicad_sym/.kicad_mod edits must not
208
- // be probed (a sch/pcb probe rejects them wholesale).
209
- const before = isProbeableKicadFile(rel) ? await readFile(abs, 'utf8') : null;
210
- const res = await toolEditFile(ctx.repoRoot, rel, str(args, 'old_string'), args.new_string, args.replace_all === true);
211
- if (before !== null) {
212
- const loadErr = await kicadLoadError(abs);
213
- if (loadErr) {
214
- const after = await readFile(abs, 'utf8');
215
- await writeFile(abs, before, 'utf8');
216
- if (await kicadLoadError(abs)) {
217
- // The file was already unloadable before this edit. Reverting
218
- // would deadlock incremental repair (every partial fix undone
219
- // unless one edit fixes the whole file), so keep the edit and
220
- // keep the pressure on with the probe output.
221
- await writeFile(abs, after, 'utf8');
222
- markTouched(ctx, rel);
223
- return `${res}\nnote: ${rel} was already unloadable before this edit, so the edit is KEPT. Keep repairing until it loads. kicad-cli says:\n${loadErr}`;
224
- }
225
- return `edit REVERTED: it would make ${rel} unloadable in KiCad. kicad-cli says:\n${loadErr}\nRe-read the surrounding file text and make a smaller, syntactically complete edit.`;
226
- }
227
- }
228
- markTouched(ctx, rel);
229
- return res;
230
- },
231
- },
232
- {
233
- schema: {
234
- name: 'write_file',
235
- description: 'Create a new file (docs, outputs). Requires a validated change proposal first (propose_change then validate_change to unlock edits). Refuses to overwrite anything or to create KiCad files.',
236
- parameters: {
237
- type: 'object',
238
- properties: { path: { type: 'string' }, content: { type: 'string' } },
239
- required: ['path', 'content'],
240
- },
241
- },
242
- requiresUnlock: true,
243
- handler: async (ctx, args) => {
244
- const corrupt = corruptionError({ content: args.content });
245
- if (corrupt)
246
- return corrupt;
247
- const rel = str(args, 'path');
248
- const res = await toolWriteFile(ctx.repoRoot, rel, args.content);
249
- markTouched(ctx, rel);
250
- return res;
251
- },
252
- },
253
- {
254
- schema: {
255
- name: 'run_erc',
256
- description: 'Run kicad-cli ERC on the schematic. Clears the ERC obligation when clean.',
257
- parameters: { type: 'object', properties: {}, required: [] },
258
- },
259
- requiresUnlock: false,
260
- handler: async (ctx) => {
261
- if (!ctx.config.schematic)
262
- return 'no schematic configured; ERC does not apply yet — skip it until a schematic exists and is set in .copperhead/config.json';
263
- const schPath = path.join(ctx.repoRoot, ctx.config.schematic);
264
- const report = await runErc(schPath);
265
- ctx.lastErc = report;
266
- if (report.ok)
267
- ctx.ledger.clear('erc');
268
- else
269
- ctx.repairCycles++;
270
- const out = formatViolations(report);
271
- // A zero-symbol schematic passes ERC with 0 violations — a false green
272
- // (3.2) that lets a premature finish look verified (an empty sheet also
273
- // passes drift). The stage contract already requires symbols>0, but a bare
274
- // "ERC clean" on the empty starting sheet still misleads the model, so warn
275
- // here too: no gate should read as satisfied by the empty starting state.
276
- if (report.ok && !(await listSymbols(schPath)).length) {
277
- return `${out}\nwarning: ERC is clean but the schematic has ZERO symbols — an empty sheet always passes ERC, so this is NOT a verified design. Capture the parts from BOM.md (and re-run run_erc) before calling finish.`;
278
- }
279
- return out;
280
- },
281
- },
282
- {
283
- schema: {
284
- name: 'verify_symbols',
285
- description: "Cross-check every lib_symbols entry in the schematic against the KiCad symbol library installed on this machine. Reports pins that diverge from the real part (wrong count, name, or electrical type) and lib_ids that do not exist in the current KiCad version (with the closest real names). ERC cannot catch these — a symbol whose lib_id claims to be a canonical part but whose pins are wrong passes ERC while being wrong. Run this after capturing symbols and reconcile every finding.",
286
- parameters: { type: 'object', properties: {}, required: [] },
287
- },
288
- requiresUnlock: false,
289
- handler: async (ctx) => {
290
- if (!ctx.config.schematic)
291
- return 'no schematic configured; verify_symbols does not apply yet';
292
- const { findings, checked, skipped } = await verifySchematicSymbols(path.join(ctx.repoRoot, ctx.config.schematic));
293
- if (!findings.length) {
294
- return `verify_symbols: ${checked} symbol(s) match the installed KiCad library. No divergences.`;
295
- }
296
- const lines = findings.map((f) => ` - [${f.kind}] ${f.detail}`);
297
- const mismatches = findings.filter((f) => f.kind !== 'no-library').length;
298
- return `verify_symbols: ${checked} verified, ${skipped} unverifiable (library not installed), ${mismatches} issue(s) to reconcile:\n${lines.join('\n')}`;
299
- },
300
- },
301
- {
302
- schema: {
303
- name: 'run_drc',
304
- description: 'Run kicad-cli DRC on the board. Clears the DRC obligation when clean.',
305
- parameters: { type: 'object', properties: {}, required: [] },
306
- },
307
- requiresUnlock: false,
308
- handler: async (ctx) => {
309
- if (!ctx.config.board)
310
- return 'no board configured; DRC does not apply yet — skip it until a board exists and is set in .copperhead/config.json';
311
- const report = await runDrc(path.join(ctx.repoRoot, ctx.config.board));
312
- ctx.lastDrc = report;
313
- if (report.ok)
314
- ctx.ledger.clear('drc');
315
- else
316
- ctx.repairCycles++;
317
- return formatViolations(report);
318
- },
319
- },
320
- {
321
- schema: {
322
- name: 'export_svg',
323
- description: 'Export an SVG render of the schematic or board into .copperhead/renders/.',
324
- parameters: {
325
- type: 'object',
326
- properties: { kind: { type: 'string', enum: ['sch', 'pcb'] } },
327
- required: ['kind'],
328
- },
329
- },
330
- requiresUnlock: false,
331
- handler: async (ctx, args) => {
332
- const kind = str(args, 'kind');
333
- const file = kind === 'sch' ? ctx.config.schematic : ctx.config.board;
334
- if (!file)
335
- return `no ${kind} configured`;
336
- const outDir = path.join(ctx.repoRoot, '.copperhead', 'renders');
337
- await mkdir(outDir, { recursive: true });
338
- return exportSvg(kind, path.join(ctx.repoRoot, file), outDir);
339
- },
340
- },
341
- {
342
- schema: {
343
- name: 'export_outputs',
344
- description: 'Export the fabrication package into outputs/: gerbers+drill, DXF outline, STEP, SVG renders. Reports per-artifact success/failure.',
345
- parameters: { type: 'object', properties: {}, required: [] },
346
- },
347
- requiresUnlock: true,
348
- handler: async (ctx) => {
349
- if (!ctx.config.board)
350
- return 'no board configured';
351
- const outDir = path.join(ctx.repoRoot, 'outputs');
352
- await mkdir(outDir, { recursive: true });
353
- const res = await exportFab(path.join(ctx.repoRoot, ctx.config.board), ctx.config.schematic ? path.join(ctx.repoRoot, ctx.config.schematic) : null, outDir);
354
- ctx.filesTouched.add('outputs/');
355
- const lines = [`produced: ${res.produced.join(', ') || '(none)'}`];
356
- for (const f of res.failed)
357
- lines.push(`FAILED ${f.artifact}: ${f.reason}`);
358
- return lines.join('\n');
359
- },
360
- },
361
- {
362
- schema: {
363
- name: 'check_drift',
364
- description: 'Compare BOM.md/PINOUT.md tables against the parsed schematic. Clears the drift obligation when clean.',
365
- parameters: { type: 'object', properties: {}, required: [] },
366
- },
367
- requiresUnlock: false,
368
- handler: async (ctx) => {
369
- // No schematic yet means there is nothing for the docs to drift against,
370
- // so the obligation is vacuously satisfied and must be cleared. Returning
371
- // without clearing deadlocks every docs-only stage of the create pipeline
372
- // (spec-seed, architecture, part-selection all run before the schematic
373
- // exists): a doc edit opens the drift obligation, this is the only tool
374
- // that clears it, and finish refuses while any obligation is open.
375
- if (!ctx.config.schematic) {
376
- ctx.ledger.clear('drift');
377
- return 'no schematic configured; drift vacuously clean';
378
- }
379
- const mismatches = await checkDrift(ctx.repoRoot, ctx.config.docs, ctx.config.schematic);
380
- if (!mismatches.length) {
381
- ctx.ledger.clear('drift');
382
- return 'drift: clean';
383
- }
384
- return mismatches.map((m) => `${m.doc}: claims "${m.claim}" but actual is "${m.actual}"`).join('\n');
385
- },
386
- },
387
- {
388
- schema: {
389
- name: 'record_constraint',
390
- description: 'Record a constraint in .copperhead/constraints.json (dual write: put the same fact in the relevant doc in this same turn). Opens revisit obligations for every item in affects.',
391
- parameters: {
392
- type: 'object',
393
- properties: {
394
- key: { type: 'string', description: 'e.g. power.sleep_current_uA' },
395
- min: { type: 'number' },
396
- max: { type: 'number' },
397
- forbidden: { type: 'array', items: { type: 'string' } },
398
- value: { type: 'string' },
399
- source: { type: 'string', description: 'doc/spec location that states this' },
400
- affects: { type: 'array', items: { type: 'string' } },
401
- },
402
- required: ['key', 'source', 'affects'],
403
- },
404
- },
405
- requiresUnlock: true,
406
- handler: async (ctx, args) => {
407
- const key = str(args, 'key');
408
- const affects = args.affects ?? [];
409
- // An affects item whose target artifact is not built yet (no schematic or
410
- // board configured, no BOM.md) has nothing to revisit; opening an
411
- // obligation now only forces a ceremonial "not yet created" resolution.
412
- // Defer it in the registry instead — reopenDeferredAffects re-opens it at
413
- // the start of the first run where the artifact exists, which is when the
414
- // revisit actually means something.
415
- const deferred = [];
416
- const openNow = [];
417
- for (const item of affects) {
418
- const target = classifyAffectsTarget(item);
419
- if (target && !affectsTargetExists(target, ctx.repoRoot, ctx.config))
420
- deferred.push(item);
421
- else
422
- openNow.push(item);
423
- }
424
- await saveConstraint(ctx.repoRoot, key, {
425
- ...(args.min !== undefined ? { min: args.min } : {}),
426
- ...(args.max !== undefined ? { max: args.max } : {}),
427
- ...(args.forbidden !== undefined ? { forbidden: args.forbidden } : {}),
428
- ...(args.value !== undefined ? { value: args.value } : {}),
429
- source: str(args, 'source'),
430
- affects,
431
- ...(deferred.length ? { deferred } : {}),
432
- });
433
- ctx.ledger.onConstraintChange(key, openNow);
434
- ctx.ledger.clear('constraint-dual-write', key);
435
- const parts = [`constraint ${key} recorded`];
436
- parts.push(`revisit obligations opened for: ${openNow.join(', ') || '(none)'}`);
437
- if (deferred.length) {
438
- parts.push(`deferred until the target artifact exists (no resolve_affected needed now): ${deferred.join(', ')}`);
439
- }
440
- return parts.join('; ');
441
- },
442
- },
443
- {
444
- schema: {
445
- name: 'resolve_affected',
446
- description: 'Explicitly resolve affects-revisit obligations: state whether each affected item changed or why no change is needed. Pass resolutions[] to clear many in one call, or the single constraint_key/item/resolution form.',
447
- parameters: {
448
- type: 'object',
449
- properties: {
450
- constraint_key: { type: 'string' },
451
- item: { type: 'string' },
452
- resolution: { type: 'string', description: '"changed: ..." or "no change needed: <reason>"' },
453
- resolutions: {
454
- type: 'array',
455
- description: 'batch form: resolve many obligations in one call',
456
- items: {
457
- type: 'object',
458
- properties: {
459
- constraint_key: { type: 'string' },
460
- item: { type: 'string' },
461
- resolution: { type: 'string' },
462
- },
463
- required: ['constraint_key', 'item', 'resolution'],
464
- },
465
- },
466
- },
467
- required: [],
468
- },
469
- },
470
- requiresUnlock: true,
471
- handler: async (ctx, args) => {
472
- // An item that matches nothing must not read as success: the model would
473
- // move on believing the obligation closed, and only find out at finish.
474
- const resolveOne = (constraintKey, item, resolution) => {
475
- const detail = `${constraintKey} affects ${item}`;
476
- if (!ctx.ledger.clear('affects-revisit', detail)) {
477
- const open = ctx.ledger.openOfKind('affects-revisit');
478
- if (!open.length)
479
- return `error: no open affects-revisit obligation matches "${detail}"`;
480
- return [
481
- `error: no open affects-revisit obligation matches "${detail}".`,
482
- 'Match these exactly:',
483
- ...open.map((o) => ` - ${o.detail}`),
484
- ].join('\n');
32
+ export async function dispatchTool(ctx, name, args, opts = {}) {
33
+ return flatten(await dispatchToolResult(ctx, name, args, opts));
34
+ }
35
+ export async function runSkillSubRun(opts) {
36
+ const { ctx, skill, args, provider } = opts;
37
+ const savedFinish = ctx.finishRequest;
38
+ const only = new Set(skill.tools.filter((n) => n !== 'finish'));
39
+ const results = [];
40
+ const messages = [
41
+ { role: 'system', content: skill.prompt(ctx, args) },
42
+ { role: 'user', content: 'Execute this skill. Use the available tools, then stop when the report is complete.' },
43
+ ];
44
+ try {
45
+ for (let turn = 0; turn < (skill.maxTurns ?? 8); turn++) {
46
+ if (await skill.isComplete(ctx, args))
47
+ break;
48
+ const tools = registry.list(ctx).filter((e) => e.kind === 'tool' && only.has(e.name)).map((e) => e.schema);
49
+ let res;
50
+ let timeoutRetries = 0;
51
+ while (true) {
52
+ try {
53
+ // The main loop's watchdog: streamed progress restarts the idle
54
+ // deadline, and turnMaxMs caps a turn that keeps streaming.
55
+ res = await withRetry(() => withWatchdog((activity) => provider.chat(messages, tools, { onStream: () => activity() }), {
56
+ idleMs: ctx.config.turnTimeoutMs,
57
+ maxMs: ctx.config.turnMaxMs,
58
+ onTimeout: () => provider.close?.(),
59
+ }), { isRetryable: isRateLimit, baseMs: 250 });
60
+ break;
485
61
  }
486
- ctx.decisions.push(`[affects] ${detail}: ${resolution}`);
487
- return `resolved: ${detail}`;
488
- };
489
- const batch = args.resolutions;
490
- if (Array.isArray(batch) && batch.length) {
491
- // Entries resolve independently: one bad key must not waste the call.
492
- return batch
493
- .map((entry, i) => {
494
- const e = entry;
495
- if (typeof e?.constraint_key !== 'string' || typeof e?.item !== 'string' || typeof e?.resolution !== 'string') {
496
- return `error: resolutions[${i}] needs string constraint_key, item, and resolution`;
62
+ catch (err) {
63
+ // Only a hung turn retries: one stopped at the hard cap is too large,
64
+ // and resending it would only run into the cap again.
65
+ if (err instanceof TurnTimeoutError && err.kind === 'idle' && timeoutRetries++ < MAX_TURN_TIMEOUTS) {
66
+ await ctx.transcript.event('skill-turn-timeout', {
67
+ skill: skill.name,
68
+ kind: err.kind,
69
+ ms: err.ms,
70
+ attempt: timeoutRetries,
71
+ });
72
+ continue;
497
73
  }
498
- return resolveOne(e.constraint_key, e.item, e.resolution);
499
- })
500
- .join('\n');
501
- }
502
- if (typeof args.constraint_key === 'string' && typeof args.item === 'string' && typeof args.resolution === 'string') {
503
- return resolveOne(args.constraint_key, args.item, args.resolution);
504
- }
505
- return 'error: pass either resolutions: [{constraint_key, item, resolution}, ...] or the single form constraint_key + item + resolution';
506
- },
507
- },
508
- {
509
- schema: {
510
- name: 'record_decision',
511
- description: 'Append a non-trivial decision to docs/DECISIONS.md: what was decided, the one-line why, and what it affects.',
512
- parameters: {
513
- type: 'object',
514
- properties: {
515
- decision: { type: 'string' },
516
- rationale: { type: 'string' },
517
- affects: { type: 'string', description: 'refdes/nets/docs affected' },
518
- },
519
- required: ['decision', 'rationale'],
520
- },
521
- },
522
- requiresUnlock: true,
523
- handler: async (ctx, args) => {
524
- const corrupt = corruptionError({ decision: args.decision, rationale: args.rationale, affects: args.affects });
525
- if (corrupt)
526
- return corrupt;
527
- const decision = str(args, 'decision');
528
- const rationale = str(args, 'rationale');
529
- const affects = args.affects ?? '';
530
- const date = new Date().toISOString().slice(0, 10);
531
- const entry = `- ${date} [run ${ctx.runId}] ${decision} | why: ${rationale}${affects ? ` | affects: ${affects}` : ''}`;
532
- const p = path.join(ctx.repoRoot, ctx.config.docs, 'DECISIONS.md');
533
- await appendFile(p, entry + '\n', 'utf8');
534
- ctx.decisions.push(`${decision} | why: ${rationale}`);
535
- ctx.filesTouched.add(path.join(ctx.config.docs, 'DECISIONS.md'));
536
- return 'decision recorded';
537
- },
538
- },
539
- {
540
- schema: {
541
- name: 'finish',
542
- description: 'End the run. outcome "done" requires all verification gates and sync obligations to be satisfied; outcome "refuse" ends without edits, citing the violated budget/constraint in summary.',
543
- parameters: {
544
- type: 'object',
545
- properties: {
546
- outcome: { type: 'string', enum: ['done', 'refuse'] },
547
- summary: { type: 'string' },
548
- },
549
- required: ['outcome', 'summary'],
550
- },
551
- },
552
- requiresUnlock: false,
553
- handler: async (ctx, args) => {
554
- const outcome = str(args, 'outcome');
555
- const summary = str(args, 'summary');
556
- if (outcome === 'refuse') {
557
- ctx.finishRequest = { outcome, summary };
558
- return 'refusal recorded; run will end';
559
- }
560
- const problems = [];
561
- const touchedKicad = [...ctx.filesTouched].some((f) => isKicadFile(f));
562
- if (touchedKicad) {
563
- if (!ctx.lastErc?.ok)
564
- problems.push('ERC has not passed since the last schematic edit (run run_erc)');
565
- const touchedPcb = [...ctx.filesTouched].some((f) => f.endsWith('.kicad_pcb'));
566
- if (touchedPcb && !ctx.lastDrc?.ok)
567
- problems.push('DRC has not passed since the last board edit (run run_drc)');
568
- }
569
- // the changelog obligation is cleared by the commit path itself
570
- const blocking = ctx.ledger.openObligations.filter((o) => o.kind !== 'changelog');
571
- if (blocking.length) {
572
- problems.push('open sync obligations:\n' + blocking.map((o) => ` - [${o.kind}] ${o.detail}`).join('\n'));
573
- }
574
- if (problems.length) {
575
- return `cannot finish yet:\n${problems.map((p) => `- ${p}`).join('\n')}`;
74
+ throw err;
75
+ }
576
76
  }
577
- ctx.finishRequest = { outcome, summary };
578
- return 'all gates satisfied; run will commit';
579
- },
580
- },
581
- ];
582
- /** Compose the tool list for the current state (design D2: the lock is structural). */
583
- export function availableTools(ctx) {
584
- return TOOLS.filter((t) => !t.requiresUnlock || ctx.editsUnlocked);
585
- }
586
- export async function dispatchTool(ctx, name, args) {
587
- const tool = availableTools(ctx).find((t) => t.schema.name === name);
588
- if (!tool)
589
- return `tool "${name}" is not available${ctx.editsUnlocked ? '' : ' (edit tools unlock after the proposal validates)'}`;
590
- try {
591
- return await tool.handler(ctx, args);
77
+ messages.push({ role: 'assistant', content: res.text, toolCalls: res.toolCalls });
78
+ if (!res.toolCalls.length) {
79
+ if (await skill.isComplete(ctx, args))
80
+ break;
81
+ messages.push({ role: 'user', content: 'Continue using tools until the report is complete.' });
82
+ continue;
83
+ }
84
+ for (const call of res.toolCalls) {
85
+ const envelope = await dispatchToolResult(ctx, call.name, call.args, { only });
86
+ results.push({ name: call.name, result: envelope });
87
+ const flat = flatten(envelope);
88
+ await ctx.transcript.event('skill-tool', {
89
+ skill: skill.name,
90
+ name: call.name,
91
+ args: call.args,
92
+ result: flat,
93
+ envelope,
94
+ });
95
+ messages.push({ role: 'tool', toolCallId: call.id, content: flat });
96
+ }
97
+ }
592
98
  }
593
- catch (err) {
594
- return `error: ${err.message}`;
99
+ finally {
100
+ ctx.finishRequest = savedFinish;
595
101
  }
102
+ const detail = results.map(({ name, result }) => `${name}:\n${flatten(result)}`).join('\n\n') || 'no tool results';
103
+ const complete = await skill.isComplete(ctx, args);
104
+ return seal({
105
+ ok: complete,
106
+ summary: complete ? 'design report' : 'design report incomplete',
107
+ detail,
108
+ viewHint: 'diagnostic',
109
+ });
596
110
  }
597
111
  //# sourceMappingURL=tools.js.map