@huaqiu/dsh-pcb-initial-placement 0.0.0-stage → 0.7.18

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.
@@ -0,0 +1,109 @@
1
+ #!/usr/bin/env python3
2
+ """FALLBACK ONLY: write a placed board as a NEW .kicad_pcb file, offline.
3
+
4
+ python write_board_file.py --board board.kicad_pcb --plan placement_plan.json
5
+ # -> <board dir>/placement/board-placed-preview.kicad_pcb
6
+ # (override with --out / --outdir; the source board is never the target)
7
+
8
+ Use this only when KiCad IPC is genuinely unavailable AND the user has accepted an
9
+ offline file instead - prefer apply_via_ipc.py. Reasons this is the worse path:
10
+ the result is not in the editor's undo stack, KiCad will not reload it by itself,
11
+ and the file stops being the single source of truth the moment someone types in
12
+ the GUI.
13
+
14
+ Safety properties kept anyway:
15
+ * the SOURCE board is never modified - a new file is written
16
+ * only the depth-1 ``(at x y [rot])`` span of each footprint is replaced, so every
17
+ other byte (UUIDs, nets, pad stacks, 3D models, text effects) survives verbatim
18
+ * the rewritten text is re-parsed and every pose is read back before the file is
19
+ written; a mismatch aborts
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import json
25
+ import os
26
+ import sys
27
+
28
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
29
+ import projpaths # noqa: E402
30
+ import sexpr # noqa: E402
31
+
32
+
33
+ def num(v):
34
+ """Format like KiCad does: 4 decimals, trailing zeros stripped."""
35
+ s = "%.4f" % v
36
+ s = s.rstrip("0").rstrip(".")
37
+ return s if s not in ("", "-0") else "0"
38
+
39
+
40
+ def main() -> None:
41
+ ap = argparse.ArgumentParser(description=__doc__,
42
+ formatter_class=argparse.RawDescriptionHelpFormatter)
43
+ ap.add_argument("--board", required=True, help="source .kicad_pcb (never modified)")
44
+ ap.add_argument("--plan", required=True)
45
+ ap.add_argument("--out", help="new .kicad_pcb to write (default "
46
+ "<placement dir>/<board>-placed-preview.kicad_pcb)")
47
+ projpaths.add_outdir(ap)
48
+ args = ap.parse_args()
49
+
50
+ stem = os.path.splitext(os.path.basename(args.board))[0]
51
+ out_path = projpaths.resolve_out(
52
+ args.out, "%s-placed-preview.kicad_pcb" % stem,
53
+ board=args.board, refs=(args.plan,), outdir=args.outdir)
54
+
55
+ if os.path.abspath(args.board) == os.path.abspath(out_path):
56
+ raise SystemExit("refusing to overwrite the source board; choose another --out")
57
+
58
+ text = open(args.board, encoding="utf-8").read()
59
+ pos = json.load(open(args.plan, encoding="utf-8"))["positions"]
60
+ fps = list(sexpr.root(text).kids("footprint"))
61
+
62
+ edits, seen = [], set()
63
+ for fp in fps:
64
+ ref = sexpr.property_value(fp, "Reference")
65
+ if ref not in pos:
66
+ print("!! no planned position for", ref)
67
+ continue
68
+ seen.add(ref)
69
+ at = fp.first("at") # first *direct* child named "at"
70
+ assert at is not None, ref
71
+ p = pos[ref]
72
+ r = p["rot"] % 360
73
+ new = ("(at %s %s)" % (num(p["x"]), num(p["y"])) if r == 0
74
+ else "(at %s %s %s)" % (num(p["x"]), num(p["y"]), num(r)))
75
+ edits.append((at.start, at.end, new))
76
+
77
+ print("footprints in file :", len(fps))
78
+ print("poses applied :", len(edits))
79
+ print("planned but not found:", sorted(set(pos) - seen))
80
+
81
+ out = text
82
+ for start, end, new in sorted(edits, reverse=True): # back to front
83
+ out = out[:start] + new + out[end:]
84
+
85
+ chk = sexpr.root(out)
86
+ assert len(list(chk.kids("footprint"))) == len(fps), "footprint count changed"
87
+ bad = 0
88
+ for fp in chk.kids("footprint"):
89
+ ref = sexpr.property_value(fp, "Reference")
90
+ a = fp.first("at").nums()
91
+ p = pos[ref]
92
+ if abs(a[0] - p["x"]) > 1e-4 or abs(a[1] - p["y"]) > 1e-4:
93
+ print(" position mismatch", ref, a[:2], p["x"], p["y"])
94
+ bad += 1
95
+ got = round(a[2]) % 360 if len(a) > 2 else 0
96
+ if got != (p["rot"] % 360):
97
+ print(" rotation mismatch", ref, a, p["rot"])
98
+ bad += 1
99
+ print("read-back mismatches :", bad)
100
+ if bad:
101
+ raise SystemExit("not writing: the rewritten text does not read back as planned")
102
+
103
+ open(out_path, "w", encoding="utf-8", newline="").write(out)
104
+ print("wrote %s (%d bytes, source %d)" % (out_path, len(out), len(text)))
105
+ print("reload it in KiCad with File > Open; the original file is untouched")
106
+
107
+
108
+ if __name__ == "__main__":
109
+ main()
package/src/config.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Configuration for `@huaqiu/dsh-pcb-initial-placement`.
3
+ *
4
+ * The plugin carries one knowledge skill plus its Python helpers. Nothing here
5
+ * connects to KiCad: the skill tells the agent how to drive the KiCad IPC API
6
+ * itself, so there is no host/port/timeout configuration to resolve.
7
+ *
8
+ * @module
9
+ */
10
+
11
+ /** Canonical skill directory name shipped by this package. */
12
+ export const PCB_INITIAL_PLACEMENT_SKILL_NAME = 'pcb-initial-placement'
13
+
14
+ /** Configuration accepted by the plugin's `apply()`. */
15
+ export interface PcbInitialPlacementConfig {
16
+ /** Bundled skill directory override (defaults to this package's skills/). */
17
+ skillsDir?: string
18
+ }
19
+
20
+ export type PcbInitialPlacementConfigInput = Partial<PcbInitialPlacementConfig>
21
+
22
+ /** Environment variable mirroring {@link PcbInitialPlacementConfig.skillsDir}. */
23
+ export const SKILLS_DIR_ENV = 'DSH_PCB_INITIAL_PLACEMENT_SKILLS_DIR'
24
+
25
+ /** Whether any skill-directory override was supplied (used for startup logging). */
26
+ export function hasSkillsDirOverride(input: PcbInitialPlacementConfigInput = {}): boolean {
27
+ return Boolean(input.skillsDir ?? process.env[SKILLS_DIR_ENV])
28
+ }
package/src/index.ts ADDED
@@ -0,0 +1,216 @@
1
+ /**
2
+ * `@huaqiu/dsh-pcb-initial-placement` — node plugin entry.
3
+ *
4
+ * Ships ONE DSH bundled skill: `pcb-initial-placement` (Phase-1 initial PCB
5
+ * placement for a board that has a netlist but no layout). It registers no
6
+ * tools — the skill's executable half is its own Python helpers under
7
+ * `skills/pcb-initial-placement/scripts/`, which the agent invokes itself
8
+ * through the KiCad IPC API.
9
+ *
10
+ * ── Why this is its own package ────────────────────────────────────────────
11
+ * `pcb-initial-placement` used to ride inside `@huaqiu/dsh-kicad`, so anyone
12
+ * installing the KiCad plugin got the whole skill tree whether they wanted it
13
+ * or not. Splitting it out makes the skill installable on its own:
14
+ *
15
+ * - HQ Edge bundles it from `plugins-release-manifest.json` (discovery is
16
+ * driven by that catalog, not by this repo's bundles);
17
+ * - the standalone desktop bundle (`@huaqiu/hardware-engineering`) encodes
18
+ * the opposite choice by NOT depending on this package, so desktop users
19
+ * stay opt-in.
20
+ *
21
+ * @module @huaqiu/dsh-pcb-initial-placement
22
+ */
23
+ import type { Context } from '@deepseek-ai/cordis'
24
+ import { getLogger } from '@huaqiu/dsh-plugin-log'
25
+ import { readFileSync } from 'node:fs'
26
+ import { join } from 'node:path'
27
+
28
+ import {
29
+ hasSkillsDirOverride,
30
+ PCB_INITIAL_PLACEMENT_SKILL_NAME,
31
+ type PcbInitialPlacementConfigInput,
32
+ } from './config.js'
33
+ import { requireSkillDir, resolveSkillDir } from './paths.js'
34
+
35
+ /** Plugin id — matches package.json. */
36
+ export const name = '@huaqiu/dsh-pcb-initial-placement'
37
+
38
+ /**
39
+ * `skills` is REQUIRED: it is the DSH runtime's plugin-bundled skill registry,
40
+ * and registering the skill is this plugin's entire job.
41
+ */
42
+ export const inject = ['skills'] as const
43
+
44
+ export type { PcbInitialPlacementConfig, PcbInitialPlacementConfigInput } from './config.js'
45
+ export { PCB_INITIAL_PLACEMENT_SKILL_NAME } from './config.js'
46
+ export { requireSkillDir, resolveSkillDir } from './paths.js'
47
+
48
+ /** The `skills` service shape consumed by this plugin. */
49
+ export interface SkillRegistration {
50
+ /** Skill id — must match DSH's discoverable skill id format. */
51
+ name: string
52
+ /** Catalog description shown to the model. */
53
+ description: string
54
+ /** Full SKILL.md body. */
55
+ content: string
56
+ /** Discovery source for plugin-bundled skills. */
57
+ source: 'runtime'
58
+ /** Where `references/` and `scripts/` live for progressive disclosure. */
59
+ resourceBase: { kind: 'directory'; path: string }
60
+ }
61
+
62
+ declare module '@deepseek-ai/cordis' {
63
+ interface Context {
64
+ /** DSH skill registry, provided by the runtime skill service. */
65
+ skills: {
66
+ /** Register a plugin-bundled skill; returns its unregister disposer. */
67
+ register(skill: SkillRegistration): () => void
68
+ }
69
+ }
70
+ }
71
+
72
+ const COMPONENT = 'dsh-pcb-initial-placement'
73
+ const log = getLogger(COMPONENT)
74
+
75
+ log.info('dsh-pcb-initial-placement: module loaded (waiting for the skills service)')
76
+
77
+ /**
78
+ * Fallback catalogue description, used only when SKILL.md frontmatter has no
79
+ * parseable `description` (the shipped file is authoritative).
80
+ */
81
+ const FALLBACK_SKILL_DESCRIPTION =
82
+ 'Phase-1 initial placement for a KiCad PCB that has a netlist but no layout: ' +
83
+ 'functional clustering, anchor placement, zone partitioning, overlap-free ' +
84
+ 'packing and a handover report, applied through the KiCad IPC API.'
85
+
86
+ /**
87
+ * Extract the `description` field from SKILL.md YAML frontmatter.
88
+ *
89
+ * Supports single-line quoted values and the folded block form
90
+ * (`description: >-` followed by indented lines).
91
+ */
92
+ export function skillDescription(markdown: string): string | undefined {
93
+ const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---/.exec(markdown)
94
+ if (!frontmatter?.[1]) return undefined
95
+
96
+ const lines = frontmatter[1].split(/\r?\n/)
97
+ const lineIndex = lines.findIndex((candidate) => /^\s*description\s*:/.test(candidate))
98
+ if (lineIndex < 0) return undefined
99
+
100
+ const raw = lines[lineIndex]!.slice(lines[lineIndex]!.indexOf(':') + 1).trim()
101
+ if (raw === '>-' || raw === '>' || raw === '|-' || raw === '|') {
102
+ const block: string[] = []
103
+ for (const line of lines.slice(lineIndex + 1)) {
104
+ if (/^\s+\S/.test(line)) {
105
+ block.push(line.trim())
106
+ continue
107
+ }
108
+ if (line.trim().length === 0) continue
109
+ break
110
+ }
111
+ const text = block.join(' ').trim()
112
+ return text.length > 0 ? text : undefined
113
+ }
114
+
115
+ const unquoted = raw.replace(/^["']/, '').replace(/["']$/, '')
116
+ return unquoted.length > 0 ? unquoted : undefined
117
+ }
118
+
119
+ /** Read the bundled skill as a ready-to-register record. */
120
+ export function readBundledSkill(moduleUrl: string, override?: string): {
121
+ dir: string
122
+ name: string
123
+ description: string
124
+ content: string
125
+ } {
126
+ const dir = requireSkillDir(moduleUrl, override)
127
+ const content = readFileSync(join(dir, 'SKILL.md'), 'utf8')
128
+ return {
129
+ dir,
130
+ name: PCB_INITIAL_PLACEMENT_SKILL_NAME,
131
+ description: skillDescription(content) ?? FALLBACK_SKILL_DESCRIPTION,
132
+ content,
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Read the bundled skill, or `null` when the installed package does not carry
138
+ * it.
139
+ *
140
+ * A missing `skills/` tree is a packaging failure, but the right blast radius
141
+ * is "this skill is unavailable", not "the whole DSH plugin tree aborts": the
142
+ * same rule `@huaqiu/dsh-kicad` follows, so a bad tarball never takes the EDA
143
+ * session down with it.
144
+ */
145
+ export function tryReadBundledSkill(moduleUrl: string, override?: string): {
146
+ dir: string
147
+ name: string
148
+ description: string
149
+ content: string
150
+ } | null {
151
+ try {
152
+ return readBundledSkill(moduleUrl, override)
153
+ } catch (err) {
154
+ log.error(
155
+ 'dsh-pcb-initial-placement: bundled skill unavailable — the plugin stays ' +
156
+ 'loaded without registering it; reinstall the package to restore it',
157
+ {
158
+ expectedDir: resolveSkillDir(moduleUrl, override),
159
+ error: String((err as Error)?.message ?? err),
160
+ },
161
+ )
162
+ return null
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Host plugin body — register the bundled skill.
168
+ *
169
+ * @param ctx - real cordis context (node side).
170
+ * @param config - plugin overlay config (skills directory override).
171
+ * @returns disposer — unregisters the skill on plugin dispose.
172
+ */
173
+ export function apply(ctx: Context, config: PcbInitialPlacementConfigInput = {}): () => void {
174
+ if (!ctx.skills || typeof ctx.skills.register !== 'function') {
175
+ throw new Error('@huaqiu/dsh-pcb-initial-placement requires the DSH `skills` service (ctx.skills.register).')
176
+ }
177
+
178
+ const skill = tryReadBundledSkill(import.meta.url, config.skillsDir)
179
+
180
+ log.info('applying dsh-pcb-initial-placement node half', {
181
+ hasSkillsDirOverride: hasSkillsDirOverride(config),
182
+ skillDir: skill?.dir ?? resolveSkillDir(import.meta.url, config.skillsDir),
183
+ skillPresent: skill !== null,
184
+ })
185
+
186
+ const disposers: Array<() => void> = []
187
+
188
+ if (skill) {
189
+ disposers.push(
190
+ ctx.skills.register({
191
+ name: skill.name,
192
+ description: skill.description,
193
+ content: skill.content,
194
+ source: 'runtime',
195
+ resourceBase: { kind: 'directory', path: skill.dir },
196
+ }),
197
+ )
198
+ }
199
+
200
+ log.info('dsh-pcb-initial-placement node half ready', {
201
+ skill: skill?.name ?? null,
202
+ degraded: skill === null,
203
+ })
204
+
205
+ return () => {
206
+ for (const dispose of disposers.reverse()) {
207
+ try {
208
+ dispose()
209
+ } catch (err) {
210
+ log.warn('dsh-pcb-initial-placement disposer failed', {
211
+ error: String((err as Error)?.message ?? err),
212
+ })
213
+ }
214
+ }
215
+ }
216
+ }
package/src/paths.ts ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Resolution of the bundled `pcb-initial-placement` skill directory.
3
+ *
4
+ * The skill ships inside the installed package
5
+ * (`<pkg>/skills/pcb-initial-placement/`). Resolving relative to the loaded
6
+ * module works for source tests, built artifacts and npm installs alike.
7
+ *
8
+ * @module
9
+ */
10
+ import { existsSync } from 'node:fs'
11
+ import { dirname, join, resolve } from 'node:path'
12
+ import { fileURLToPath } from 'node:url'
13
+
14
+ import { PCB_INITIAL_PLACEMENT_SKILL_NAME, SKILLS_DIR_ENV } from './config.js'
15
+
16
+ /**
17
+ * Absolute path of the bundled skill directory.
18
+ *
19
+ * Resolution order: explicit override, `DSH_PCB_INITIAL_PLACEMENT_SKILLS_DIR`,
20
+ * then the package-relative location.
21
+ */
22
+ export function resolveSkillDir(moduleUrl: string, override?: string): string {
23
+ if (override && override.trim().length > 0) return resolve(override)
24
+ const envOverride = process.env[SKILLS_DIR_ENV]
25
+ if (envOverride && envOverride.trim().length > 0) return resolve(envOverride)
26
+
27
+ const here = dirname(fileURLToPath(moduleUrl))
28
+ return resolve(here, '..', 'skills', PCB_INITIAL_PLACEMENT_SKILL_NAME)
29
+ }
30
+
31
+ /**
32
+ * Resolve the skill directory and assert the skill is actually present.
33
+ *
34
+ * @throws when `SKILL.md` is missing.
35
+ */
36
+ export function requireSkillDir(moduleUrl: string, override?: string): string {
37
+ const dir = resolveSkillDir(moduleUrl, override)
38
+ const skillFile = join(dir, 'SKILL.md')
39
+ if (!existsSync(skillFile)) {
40
+ throw new Error(
41
+ `@huaqiu/dsh-pcb-initial-placement: bundled skill missing at ${skillFile}. ` +
42
+ 'The installed package is incomplete; reinstall ' +
43
+ '@huaqiu/dsh-pcb-initial-placement so that its skills/ directory is present.',
44
+ )
45
+ }
46
+ return dir
47
+ }