@typecad/framework-zephyr 1.0.0-alpha.15 → 1.0.0-alpha.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.
Files changed (132) hide show
  1. package/LICENSE +202 -21
  2. package/README.md +49 -87
  3. package/dist/as-built.d.ts +2 -2
  4. package/dist/as-built.js +2 -2
  5. package/dist/boardgen.d.ts +1 -9
  6. package/dist/boardgen.js +228 -45
  7. package/dist/chips/types.d.ts +1 -1
  8. package/dist/debug-codegen.js +1 -1
  9. package/dist/display/touch-adapter.js +1 -1
  10. package/dist/display/ui-adapter.js +549 -549
  11. package/dist/doctor.js +4 -4
  12. package/dist/dt-config/custom-board.js +2 -2
  13. package/dist/dt-config/kconfig.js +18 -12
  14. package/dist/dt-config/overlay.d.ts +2 -2
  15. package/dist/dt-config/overlay.js +2 -2
  16. package/dist/framework.manifest.d.ts +3 -3
  17. package/dist/framework.manifest.js +10 -7
  18. package/dist/index.js +5 -5
  19. package/dist/licenses.d.ts +2 -2
  20. package/dist/licenses.js +8 -8
  21. package/dist/lowering/fs.js +1 -1
  22. package/dist/lowering/gpio.js +0 -32
  23. package/dist/lowering/http.js +264 -32
  24. package/dist/lowering/i2c.js +0 -8
  25. package/dist/lowering/interrupts.js +6 -0
  26. package/dist/lowering/mqtt.js +110 -8
  27. package/dist/lowering/usb.js +11 -11
  28. package/dist/lowering/wdt.js +2 -29
  29. package/dist/sdk/board-catalog-sync.d.ts +1 -3
  30. package/dist/sdk/board-catalog-sync.js +4 -10
  31. package/dist/strategy.d.ts +22 -44
  32. package/dist/strategy.js +152 -155
  33. package/dist/tmp-probe.d.ts +2 -0
  34. package/dist/tmp-probe.js +9 -0
  35. package/dist/toolchain/debug-config.d.ts +50 -90
  36. package/dist/toolchain/debug-config.js +241 -502
  37. package/dist/toolchain/env-check.d.ts +1 -3
  38. package/dist/toolchain/env-check.js +2 -7
  39. package/dist/toolchain/index.d.ts +65 -2
  40. package/dist/toolchain/index.js +432 -55
  41. package/dist/toolchain/runners.d.ts +16 -0
  42. package/dist/toolchain/runners.js +75 -0
  43. package/dist/toolchain/scaffold.d.ts +1 -1
  44. package/dist/toolchain/scaffold.js +12 -12
  45. package/dist/toolchain/west-discover.d.ts +6 -0
  46. package/dist/toolchain/west-discover.js +36 -13
  47. package/dist/toolchain/west-spawn.js +8 -2
  48. package/installer/README.md +328 -328
  49. package/installer/install.sh +2 -2
  50. package/installer/templates/project/.typecad/activate-zephyr.ps1 +1 -1
  51. package/installer/templates/project/.typecad/activate-zephyr.sh +1 -1
  52. package/installer/templates/project/.vscode/settings.json +1 -1
  53. package/installer/templates/project/README.md +2 -2
  54. package/package.json +5 -5
  55. package/src/as-built.ts +206 -206
  56. package/src/boardgen.ts +214 -48
  57. package/src/chips/types.ts +567 -567
  58. package/src/display/touch-adapter.ts +204 -204
  59. package/src/display/ui-adapter.ts +781 -781
  60. package/src/doctor.ts +4 -4
  61. package/src/dt-config/custom-board.ts +2 -2
  62. package/src/dt-config/kconfig.ts +18 -12
  63. package/src/dt-config/overlay.ts +1058 -1058
  64. package/src/framework.manifest.ts +538 -535
  65. package/src/index.ts +5 -5
  66. package/src/licenses.ts +425 -425
  67. package/src/lowering/fs.ts +135 -135
  68. package/src/lowering/gpio.ts +0 -33
  69. package/src/lowering/http.ts +264 -32
  70. package/src/lowering/i2c.ts +0 -9
  71. package/src/lowering/interrupts.ts +6 -0
  72. package/src/lowering/mqtt.ts +109 -8
  73. package/src/lowering/usb.ts +221 -221
  74. package/src/lowering/wdt.ts +2 -25
  75. package/src/sdk/board-catalog-sync.ts +4 -25
  76. package/src/strategy.ts +2265 -2309
  77. package/src/toolchain/debug-config.ts +264 -514
  78. package/src/toolchain/env-check.ts +279 -285
  79. package/src/toolchain/index.ts +1703 -1286
  80. package/src/toolchain/runners.ts +80 -0
  81. package/src/toolchain/scaffold.ts +296 -296
  82. package/src/toolchain/west-discover.ts +35 -13
  83. package/src/toolchain/west-spawn.ts +174 -168
  84. package/dist/async/timer-polyfill.d.ts +0 -10
  85. package/dist/async/timer-polyfill.js +0 -95
  86. package/dist/chips/board-overrides.d.ts +0 -7
  87. package/dist/chips/board-overrides.js +0 -11
  88. package/dist/chips/esp32.d.ts +0 -2
  89. package/dist/chips/esp32.js +0 -71
  90. package/dist/chips/esp32s3.d.ts +0 -2
  91. package/dist/chips/esp32s3.js +0 -103
  92. package/dist/chips/soc/.d.ts +0 -2
  93. package/dist/chips/soc/.js +0 -129
  94. package/dist/chips/soc/esp32.d.ts +0 -2
  95. package/dist/chips/soc/esp32.js +0 -120
  96. package/dist/chips/soc/esp32c3.d.ts +0 -2
  97. package/dist/chips/soc/esp32c3.js +0 -90
  98. package/dist/chips/soc/esp32c6.d.ts +0 -2
  99. package/dist/chips/soc/esp32c6.js +0 -109
  100. package/dist/chips/soc/esp32s3.d.ts +0 -2
  101. package/dist/chips/soc/esp32s3.js +0 -189
  102. package/dist/chips/soc/index.d.ts +0 -2
  103. package/dist/chips/soc/index.js +0 -23
  104. package/dist/chips/soc/nrf52840.d.ts +0 -2
  105. package/dist/chips/soc/nrf52840.js +0 -130
  106. package/dist/chips/soc/rp2040.d.ts +0 -2
  107. package/dist/chips/soc/rp2040.js +0 -141
  108. package/dist/chips/soc/rp2350a.d.ts +0 -2
  109. package/dist/chips/soc/rp2350a.js +0 -145
  110. package/dist/chips/soc/samd21g18a.d.ts +0 -2
  111. package/dist/chips/soc/samd21g18a.js +0 -143
  112. package/dist/chips/soc/stm32f411xe.d.ts +0 -2
  113. package/dist/chips/soc/stm32f411xe.js +0 -251
  114. package/dist/chips/xiao-ble.d.ts +0 -2
  115. package/dist/chips/xiao-ble.js +0 -100
  116. package/dist/lowering/power.d.ts +0 -9
  117. package/dist/lowering/power.js +0 -60
  118. package/dist/lowering/pulse.d.ts +0 -7
  119. package/dist/lowering/pulse.js +0 -51
  120. package/dist/lowering/tone.d.ts +0 -10
  121. package/dist/lowering/tone.js +0 -63
  122. package/dist/lowering/worker-backing.d.ts +0 -14
  123. package/dist/lowering/worker-backing.js +0 -79
  124. package/dist/lowering/worker.d.ts +0 -6
  125. package/dist/lowering/worker.js +0 -14
  126. package/dist/sdk/board-data.generated.d.ts +0 -2
  127. package/dist/sdk/board-data.generated.js +0 -4
  128. package/dist/sdk/catalog-walker.d.ts +0 -90
  129. package/dist/sdk/catalog-walker.js +0 -682
  130. package/dist/sdk/dts-reader.d.ts +0 -83
  131. package/dist/sdk/dts-reader.js +0 -596
  132. package/src/debug-codegen.ts +0 -207
@@ -1,213 +1,47 @@
1
1
  // ---------------------------------------------------------------------------
2
- // debug-config.ts — VS Code / GDB debug artifact generation for `--debug`
2
+ // debug-config.ts — west-driven VS Code debug artifacts (cortex-debug external
3
+ // server mode).
3
4
  //
4
- // After a successful gdb-mode build, writes the artifacts that let the user
5
- // press F5 in VS Code and attach GDB to the running Zephyr target.
5
+ // The board-specific debug knowledge lives in Zephyr, not here: after any
6
+ // successful build, `west debugserver` serves the GDB connection using the
7
+ // board's own runner configuration (resolved in build/zephyr/runners.yaml —
8
+ // the exact arch gdb, the openocd/jlink binaries and flags, the Zephyr RTOS
9
+ // awareness, adapter quirks). The launch.json written here just connects
10
+ // cortex-debug to that server (`servertype: 'external'` +
11
+ // `gdbTarget: localhost:<port>`).
6
12
  //
7
- // Uses the cortex-debug extension (NOT the ESP-IDF gdbtarget adapter) so the
8
- // debug session is self-contained. cortex-debug starts OpenOCD as a child
9
- // process via `servertype: "openocd"`; the preLaunch task handles only the
10
- // build + flash step. After attach we issue `monitor reset init`, set a
11
- // temporary hardware breakpoint at main(), and continue — this ensures the
12
- // breakpoint is deferred until the bootloader maps the app flash region.
13
+ // Lifecycle: F5 runs the preLaunchTask (build + flash, unchanged), the
14
+ // background task `typecad-hal: debug server (west)` starts
15
+ // `typecad-hal debug-server start` (which wraps `west debugserver` and prints
16
+ // a ready marker the task's problem matcher waits for), and VS Code runs the
17
+ // postDebugTask (`typecad-hal: stop debug server`) when the session ends.
13
18
  //
14
- // All generators are deterministic + idempotent so toggling --debug does not
15
- // churn the tree.
19
+ // Everything here is best-effort: a failed artifact write warns and never
20
+ // fails the build (a project without launch.json still builds fine).
16
21
  // ---------------------------------------------------------------------------
17
- import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
22
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
18
23
  import { join, resolve, dirname, relative } from 'node:path';
19
24
  import { ZephyrStrategy } from '../strategy.js';
20
- import { resolveChipFromBoard } from '../chips/resolve.js';
21
- import { resolveProbeMethod } from './index.js';
22
- import { loadCuttlefishConfig } from '@typecad/cuttlefish/config-loader';
23
- /**
24
- * Resolve the GDB binary path for the target from the build cache, falling
25
- * back to a filesystem scan of known Zephyr SDK locations when no build
26
- * exists yet (the create-time starter artifacts path). Zephyr records
27
- * ZEPHYR_SDK_INSTALL_DIR in CMakeCache.txt at configure time, and the
28
- * xtensa GDB lives at <sdk>/xtensa-espressif_esp32s3_zephyr-elf/bin/... (note
29
- * the Zephyr-SDK naming, distinct from the ESP-IDF xtensa-esp32s3-elf-gdb).
30
- *
31
- * Returns the absolute gdb path on success, or undefined (the launch.json then
32
- * omits gdbPath and relies on Cortex-Debug's default resolution).
33
- */
34
- export function resolveGdbPath(buildDir, target) {
35
- const cachePath = join(buildDir, 'CMakeCache.txt');
36
- if (existsSync(cachePath)) {
37
- try {
38
- const cache = readFileSync(cachePath, 'utf-8');
39
- const m = cache.match(/^ZEPHYR_SDK_INSTALL_DIR:PATH=(.+)$/m);
40
- if (m) {
41
- const fromCache = gdbPathFromSdkRoot(m[1].trim(), target);
42
- if (fromCache)
43
- return fromCache;
44
- }
45
- }
46
- catch {
47
- // unreadable cache — fall through to the SDK scan
48
- }
49
- }
50
- // No build dir yet (project just created): probe known SDK locations.
51
- for (const sdkRoot of discoverZephyrSdkRoots()) {
52
- const p = gdbPathFromSdkRoot(sdkRoot, target);
53
- if (p)
54
- return p;
55
- }
56
- return undefined;
57
- }
58
- /** The GDB location inside a Zephyr SDK root, per target architecture:
59
- * ARM boards use the arm-zephyr-eabi toolchain (verified against
60
- * zephyr-sdk-0.17.4), Espressif the xtensa-espressif_esp32s3_zephyr-elf one.
61
- * Returns a forward-slash absolute path or undefined. */
62
- export function gdbPathFromSdkRoot(sdkRoot, target) {
63
- // No target given (legacy callers/tests): the historical Espresif default.
64
- const boardId = (target ?? '').split('/')[0];
65
- const isArm = boardId.length > 0 && !boardId.startsWith('esp32');
66
- const toolchainDir = isArm ? 'arm-zephyr-eabi' : 'xtensa-espressif_esp32s3_zephyr-elf';
67
- const gdbName = isArm ? 'arm-zephyr-eabi-gdb.exe' : 'xtensa-espressif_esp32s3_zephyr-elf-gdb.exe';
68
- const gdbPath = join(sdkRoot, toolchainDir, 'bin', gdbName);
69
- return existsSync(gdbPath) ? gdbPath.replace(/\\/g, '/') : undefined;
70
- }
71
- /** Compare two dotted version strings numerically (0.17.10 > 0.17.4). */
72
- function compareSdkVersions(a, b) {
73
- const segsOf = (v) => v.split('.').map((s) => parseInt(s, 10) || 0);
74
- const aa = segsOf(a);
75
- const bb = segsOf(b);
76
- for (let i = 0; i < Math.max(aa.length, bb.length); i++) {
77
- const d = (aa[i] ?? 0) - (bb[i] ?? 0);
78
- if (d !== 0)
79
- return d;
80
- }
81
- return 0;
82
- }
83
- /**
84
- * Probe the well-known Zephyr SDK install locations, newest version first:
85
- * 1. $ZEPHYR_SDK_INSTALL_DIR (the var board.cmake reads)
86
- * 2. <MAMBA_ROOT_PREFIX | ~/micromamba>/zephyr-sdk/zephyr-sdk-<ver> — the
87
- * the bundled Zephyr installer layout
88
- * 3. ~/zephyr-sdk-<ver> — the standalone download layout
89
- *
90
- * Only roots that actually contain the esp32s3 GDB are useful to callers;
91
- * this returns candidate roots (gdbPathFromSdkRoot does the existence check)
92
- * so tests can inject home/env overrides.
93
- */
94
- export function discoverZephyrSdkRoots(opts) {
95
- const env = opts?.env ?? process.env;
96
- const home = opts?.home ?? (env.USERPROFILE || env.HOME || '');
97
- const scanned = [];
98
- const versionedDirs = (base) => {
99
- try {
100
- return readdirSync(base)
101
- .filter((d) => existsSync(join(base, d)) && d.startsWith('zephyr-sdk-'))
102
- .map((d) => join(base, d));
103
- }
104
- catch {
105
- return []; // dir absent
106
- }
107
- };
108
- const mambaRoot = env.MAMBA_ROOT_PREFIX || (home ? join(home, 'micromamba') : '');
109
- if (mambaRoot)
110
- scanned.push(...versionedDirs(join(mambaRoot, 'zephyr-sdk')));
111
- if (home)
112
- scanned.push(...versionedDirs(home));
113
- // Scanned roots newest version first; the env var stays pinned first
114
- // (explicit user intent outranks any discovered location).
115
- scanned.sort((a, b) => {
116
- const va = a.match(/zephyr-sdk-([\d.]+)/)?.[1] ?? '';
117
- const vb = b.match(/zephyr-sdk-([\d.]+)/)?.[1] ?? '';
118
- return compareSdkVersions(vb, va);
119
- });
120
- const roots = env.ZEPHYR_SDK_INSTALL_DIR
121
- ? [env.ZEPHYR_SDK_INSTALL_DIR, ...scanned]
122
- : scanned;
123
- // De-duplicate (an env var may repeat a scan hit) preserving order.
124
- return roots.filter((r, i) => roots.indexOf(r) === i);
125
- }
126
- /**
127
- * Resolve the OpenOCD binary path. The esp32s3 needs the Espressif OpenOCD
128
- * fork (openocd-esp32) — not the Zephyr SDK's openocd and not a
129
- * generic/GDB-stub build — because only it carries the Xtensa + esp_usb_jtag
130
- * support. ARM targets prefer the Zephyr SDK's own openocd (it ships the
131
- * interface/target cfgs boards reference); the Espressif fork is only
132
- * consulted for esp32 targets.
133
- *
134
- * Discovery order:
135
- * 1. ESPRESSIF_TOOLCHAIN_PATH env (the var board.cmake reads) — esp32
136
- * targets; its openocd-esp32/bin/openocd.exe.
137
- * 2. The standard ESP-IDF install layout: ~/.espressif/tools/openocd-esp32/
138
- * <version>/openocd-esp32/bin/openocd.exe (esp32 targets; newest first).
139
- * 3. A Zephyr SDK root (discoverZephyrSdkRoots) — its
140
- * tools/opt/openocd/bin/openocd(.exe), any target.
141
- * Returns undefined if not found (the launch.json then omits openOCDPath and
142
- * Cortex-Debug falls back to PATH / its openocdPath setting).
143
- */
144
- export function resolveOpenOcdPath(target) {
145
- const isEsp32Target = (target ?? '').split('/')[0].startsWith('esp32');
146
- const candidates = [];
147
- if (isEsp32Target) {
148
- // 1. ESPRESSIF_TOOLCHAIN_PATH env
149
- const envPath = process.env.ESPRESSIF_TOOLCHAIN_PATH;
150
- if (envPath) {
151
- candidates.push(join(envPath, 'openocd-esp32', 'bin', 'openocd.exe'));
152
- }
153
- // 2. ~/.espressif/tools/openocd-esp32/<version>/openocd-esp32/bin/openocd.exe
154
- const home = process.env.USERPROFILE || process.env.HOME;
155
- if (home) {
156
- const base = join(home, '.espressif', 'tools', 'openocd-esp32');
157
- let versions = [];
158
- try {
159
- versions = readdirSync(base).filter((v) => existsSync(join(base, v, 'openocd-esp32', 'bin', 'openocd.exe')));
160
- }
161
- catch {
162
- // dir absent
163
- }
164
- // newest version last — sort then reverse so the highest wins on match.
165
- versions.sort().reverse();
166
- for (const v of versions) {
167
- candidates.push(join(base, v, 'openocd-esp32', 'bin', 'openocd.exe'));
168
- }
169
- }
170
- }
171
- // 3. The Zephyr SDK's openocd (ARM targets' interface/target cfgs ship
172
- // with it — interface/stlink-dap.cfg, target/stm32f4x.cfg, ...). Layout
173
- // differs by SDK generation: 1.0.x hosttools/openocd, 0.17.x
174
- // tools/opt/openocd (when present).
175
- const exe = process.platform === 'win32' ? 'openocd.exe' : 'openocd';
176
- for (const sdkRoot of discoverZephyrSdkRoots()) {
177
- candidates.push(join(sdkRoot, 'hosttools', 'openocd', 'bin', exe));
178
- candidates.push(join(sdkRoot, 'tools', 'opt', 'openocd', 'bin', exe));
179
- }
180
- for (const c of candidates) {
181
- if (existsSync(c))
182
- return resolve(c).replace(/\\/g, '/');
183
- }
184
- return undefined;
185
- }
186
- /**
187
- * Resolve where to write the VS Code debug artifacts and how to express paths
188
- * in them.
189
- *
190
- * VS Code reads `.vscode/` from the folder the user has OPENED — and for a
191
- * cuttlefish project that is almost always the **cuttlefish project root**
192
- * (the directory containing `cuttlefish.config.ts`), NOT the git repo root.
193
- * The toolchain's `projectRoot` is the Zephyr *app* dir (e.g.
194
- * `<projectRoot>/src/out`), which sits below the cuttlefish config dir. So we
195
- * walk up from `projectRoot` to the nearest `cuttlefish.config.ts` and treat
196
- * THAT as the workspace root. This makes F5 work when a user opens the project
197
- * folder directly, and keeps launch.json paths relative to it.
198
- *
199
- * Returns { workspaceRoot, appRel } where workspaceRoot is the cuttlefish
200
- * project root (the `.vscode/` target) and appRel is the Zephyr app dir
201
- * (`projectRoot`) relative to it (e.g. 'src/out').
202
- */
25
+ import { readRunnersFacts } from './runners.js';
26
+ /** The gdb server port west's openocd/jlink runners default to. */
27
+ export const DEBUG_SERVER_PORT = 3333;
28
+ /** west's openocd tcl port — pinned in the debugserver invocation and used
29
+ * as the READINESS probe: its listener opens at the END of openocd's init
30
+ * (after the gdb listener and the startup halt), and probe connections
31
+ * there never consume the gdb server's single client slot. */
32
+ export const DEBUG_SERVER_TCL_PORT = 6333;
33
+ /** Task labels (also the preLaunchTask/postDebugTask references in launch.json). */
34
+ export const DEBUG_BUILD_TASK = 'typecad-hal: build + flash (debug)';
35
+ export const DEBUG_SERVER_TASK = 'typecad-hal: debug server (west)';
36
+ export const DEBUG_SERVER_STOP_TASK = 'typecad-hal: stop debug server';
203
37
  export function resolveDebugLocations(projectRoot) {
204
- // Walk up from the Zephyr app dir to find the cuttlefish project root (the
205
- // nearest ancestor containing cuttlefish.config.ts). Fall back to projectRoot
38
+ // Walk up from the Zephyr app dir to find the typecad-hal project root (the
39
+ // nearest ancestor containing typecad-hal.config.ts). Fall back to projectRoot
206
40
  // itself if none is found (single-dir project where the app sits at root).
207
41
  let workspaceRoot = resolve(projectRoot);
208
42
  let dir = resolve(projectRoot);
209
43
  for (let i = 0; i < 20; i++) {
210
- if (existsSync(join(dir, 'cuttlefish.config.ts'))) {
44
+ if (existsSync(join(dir, 'typecad-hal.config.ts'))) {
211
45
  workspaceRoot = dir;
212
46
  break;
213
47
  }
@@ -220,392 +54,297 @@ export function resolveDebugLocations(projectRoot) {
220
54
  return { workspaceRoot, appRel };
221
55
  }
222
56
  /** Read-merge-write a JSON file, adding/replacing a single config by a key. */
223
- function mergeJsonArrayEntry(filePath, arrayKey, matchKey, entry) {
57
+ function mergeJsonArrayEntry(filePath, arrayKey, nameKey, entry) {
224
58
  let doc = {};
225
59
  if (existsSync(filePath)) {
226
60
  try {
227
- doc = JSON.parse(readFileSync(filePath, 'utf-8'));
61
+ const parsed = JSON.parse(readFileSync(filePath, 'utf-8'));
62
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
63
+ doc = parsed;
64
+ }
228
65
  }
229
66
  catch {
230
67
  // malformed — start fresh
231
68
  }
232
69
  }
233
- const arr = Array.isArray(doc[arrayKey]) ? doc[arrayKey] : [];
234
- const idx = arr.findIndex((e) => e[matchKey] === entry[matchKey]);
70
+ const arr = Array.isArray(doc[arrayKey])
71
+ ? doc[arrayKey]
72
+ : [];
73
+ const name = entry[nameKey];
74
+ const idx = arr.findIndex((e) => e && e[nameKey] === name);
235
75
  if (idx >= 0)
236
76
  arr[idx] = entry;
237
77
  else
238
78
  arr.push(entry);
239
79
  doc[arrayKey] = arr;
240
80
  mkdirSync(dirname(filePath), { recursive: true });
241
- writeFileSync(filePath, JSON.stringify(doc, null, 2) + '\n', 'utf-8');
81
+ writeFileSync(filePath, `${JSON.stringify(doc, null, 2)}\n`, 'utf-8');
242
82
  }
243
83
  /**
244
- * Generate the GDB Python frame-filter that rewrites cuttlefish's hoisted
245
- * lambda frame names (`${prefix}_isr_N`) into readable `<lambda> @ file:line`
246
- * in the call stack. Only emitted when the source map references `_isr_N`
247
- * symbols; otherwise returns null (launch.json omits the `source` initCommand).
248
- *
249
- * Ported verbatim from the deleted framework-esp32/toolchain/gdb-script.ts —
250
- * the filter is cuttlefish-internal (lambda hoisting is framework-agnostic).
84
+ * Whether the workspace's gdb debug artifacts need rewriting: missing, still
85
+ * in an older (self-managed-server) shape, written before a build resolved
86
+ * the gdb path (the create-time starter omits gdbPath), or referencing an app
87
+ * root other than the current one (an outDir rename). Only OUR entries count
88
+ * (`TypeCAD Debug (Zephyr, …)`); user-authored ones are never judged.
251
89
  */
252
- export function generateGdbScript(sourceMapPath) {
253
- if (!sourceMapPath || !existsSync(sourceMapPath))
254
- return null;
255
- let mapText = '';
90
+ export function debugArtifactsNeedRewrite(workspaceRoot, appRel, currentGdb) {
91
+ let doc;
256
92
  try {
257
- mapText = readFileSync(sourceMapPath, 'utf-8');
93
+ doc = JSON.parse(readFileSync(join(workspaceRoot, '.vscode', 'launch.json'), 'utf-8'));
258
94
  }
259
95
  catch {
260
- return null;
96
+ return false; // no launch.json (or unreadable) — plain builds leave it absent
261
97
  }
262
- // Only emit when the emitted code contains hoisted-lambda symbols.
263
- if (!/_isr_\d+/.test(mapText))
264
- return null;
265
- // A GDB Python frame-filter. Registered via the launch.json initCommand
266
- // `source <path>` so GDB auto-loads it on attach.
267
- return [
268
- '# Auto-generated by @typecad/framework-zephyr. GDB frame-filter that',
269
- '# rewrites cuttlefish hoisted-lambda frame names (*_isr_N) into readable',
270
- '# <lambda> form so the VS Code call stack is legible.',
271
- 'import gdb',
272
- 'import re',
273
- '',
274
- 'class CuttlefishLambdaFilter:',
275
- ' def __init__(self):',
276
- ' self.name = "cuttlefish_lambda"',
277
- ' self.priority = 100',
278
- ' self.enabled = True',
279
- '',
280
- ' def filter(self, frame_iter):',
281
- ' isr_re = re.compile(r"(.*)_isr_(\\d+)")',
282
- ' return (CuttlefishFrame(f) for f in frame_iter)',
283
- '',
284
- 'class CuttlefishFrame:',
285
- ' def __init__(self, frame):',
286
- ' self.frame = frame',
287
- ' def __getattr__(self, name):',
288
- ' val = getattr(self.frame, name)',
289
- ' if name == "function":',
290
- ' m = isr_re.match(val)',
291
- ' if m: return "<lambda>"',
292
- ' return val',
293
- '',
294
- 'gdb.frame_filters[CuttlefishLambdaFilter().name] = CuttlefishLambdaFilter()',
295
- '',
296
- ].join('\n');
98
+ const configs = doc.configurations;
99
+ if (!Array.isArray(configs))
100
+ return false;
101
+ const prefix = `\${workspaceFolder}/${appRel ? `${appRel}/` : ''}`;
102
+ for (const c of configs) {
103
+ const e = c;
104
+ if (typeof e.name !== 'string' || !e.name.startsWith('TypeCAD Debug (Zephyr,'))
105
+ continue;
106
+ if (e.servertype !== 'external')
107
+ return true; // pre-west (self-managed server) shape
108
+ if (e.gdbPath === undefined)
109
+ return true; // create-time starter — upgrade on first build
110
+ if (currentGdb !== undefined && typeof e.gdbPath === 'string'
111
+ && e.gdbPath.replace(/\\/g, '/') !== currentGdb) {
112
+ return true; // a wrong create-time silicon guess — west's answer wins
113
+ }
114
+ if (typeof e.executable === 'string'
115
+ && e.executable.startsWith('${workspaceFolder}/')
116
+ && !e.executable.startsWith(prefix)) {
117
+ return true; // outDir moved
118
+ }
119
+ return false; // our entry exists in the current shape — nothing to do
120
+ }
121
+ return false; // no our-entry (deleted launch entry): only --debug recreates
297
122
  }
298
123
  /**
299
- * Build the cortex-debug launch.json config for an ESP32-S3 (built-in USB-JTAG).
300
- * `openOcdCfgRel` is the workspace-relative path to the generated
301
- * .cuttlefish/openocd.cfg, passed to cortex-debug's configFiles.
124
+ * Build the cortex-debug launch.json config connecting to the west-owned gdb
125
+ * server. `gdbPath` comes from the build's runners.yaml (west's own resolved
126
+ * arch gdb); undefined before the first build (create-time starter).
302
127
  */
303
- function buildLaunchConfig(o, gdbScriptRel, openOcdCfgRel, method) {
304
- // The ELF is at <projectRoot>/build/zephyr/zephyr.elf (Zephyr's standard
305
- // build output). cortex-debug uses `executable` (not `program`).
128
+ function buildLaunchConfig(o, gdbScriptRel, gdbPath) {
306
129
  const executable = `\${workspaceFolder}/${o.appRel}/build/zephyr/zephyr.elf`;
307
- // OpenOCD cfg relative to the workspace root so cortex-debug can pass it
308
- // via the -f flag. Must be a list; cortex-debug prepends -f per entry.
309
- const configFiles = [`\${workspaceFolder}/${openOcdCfgRel}`];
310
- // GDB path resolved from the Zephyr SDK build cache (CMakeCache.txt).
311
- const gdbPath = resolveGdbPath(o.buildDir, o.target);
312
- // OpenOCD binary path — the Espressif fork (openocd-esp32) is required for
313
- // the esp_usb_jtag adapter. cortex-debug's `serverpath` tells it where to
314
- // find the binary (not on PATH by default).
315
- const openocdPath = resolveOpenOcdPath(o.target);
316
- // Post-attach commands executed after GDB connects to the OpenOCD gdbserver.
317
- // set mem inaccessible-by-default off — suppresses "Cannot access memory"
318
- // errors caused by overlapping Xtensa memory regions (flash-mapped
319
- // 0x4200xxxx isn't accessible until the bootloader runs).
320
- // mem 0x42000000 0x44000000 ro cache — tells GDB the app flash region IS
321
- // read-only so -break-insert uses hw breakpoints, not sw breakpoints
322
- // (which would fail with "Cannot access memory at 0x4200xxxx").
323
- // monitor reset init — reset target + halt (bootloader maps flash)
324
- // thb main — temporary HW breakpoint at main()
325
- // c — continue; bootloader maps flash, breaks at main()
326
- //
327
- // The trailing `c` is ESP32-only. On instant-reset ARM targets the
328
- // thb-main stop lands within milliseconds — WHILE cortex-debug is still
329
- // chewing through this command list — and a stop event mid-initialization
330
- // leaves the session half-started (toolbar never enables, user breakpoints
331
- // never bind). The ESP32's bootloader takes hundreds of milliseconds, so
332
- // its stop safely arrives after init completes. ARM keeps the pending
333
- // thb (the first user Continue stops at main()) but hands the run/stop
334
- // transition to cortex-debug.
335
- //
336
- // Paths use forward slashes — ${workspaceFolder} on Windows produces
337
- // backslashes that GDB interprets as escape sequences (\t → tab, etc.).
338
- const ws = o.workspaceRoot.replace(/\\/g, '/');
339
- // The Xtensa flash-mapping commands are ESP32-specific (app flash isn't
340
- // readable until the bootloader maps it); ARM targets drop them.
341
- const isEsp32Target = o.target.split('/')[0].startsWith('esp32');
130
+ // The gdb binary names the architecture (xtensa-espressif_* / arm-zephyr-* /
131
+ // riscv64-*): the Xtensa flash-mapping commands are only correct there —
132
+ // app flash is unreadable until the ESP32 bootloader maps it, and the
133
+ // trailing `c` rides the bootloader's slow boot past cortex-debug's init.
134
+ const isXtensa = (gdbPath ?? '').includes('xtensa');
135
+ // Post-attach commands executed after GDB connects to the west-owned server.
136
+ // set directories . — source lookup root (gdb's cwd is the
137
+ // config's cwd = workspace root)
138
+ // monitor reset init — reset target + halt via the server
139
+ // thb main — temporary HW breakpoint at main()
140
+ // Paths must stay RELATIVE (cortex-debug passes commands verbatim; Windows
141
+ // backslash expansion would corrupt absolute paths).
342
142
  const postAttachCommands = [
343
- `set directories ${ws}`,
143
+ 'set directories .',
344
144
  'set remote hardware-watchpoint-limit 2',
345
145
  'set remote hardware-breakpoint-limit 2',
346
- ...(isEsp32Target ? [
146
+ ...(isXtensa ? [
347
147
  'set mem inaccessible-by-default off',
348
148
  'mem 0x42000000 0x44000000 ro cache',
349
149
  ] : []),
350
150
  'monitor reset init',
351
151
  'thb main',
352
- ...(isEsp32Target ? ['c'] : []),
152
+ ...(isXtensa ? ['c'] : []),
353
153
  ];
354
154
  if (gdbScriptRel) {
355
- postAttachCommands.splice(1, 0, `source ${ws}/${gdbScriptRel}`);
155
+ postAttachCommands.splice(1, 0, `source ${gdbScriptRel}`);
356
156
  }
357
- // Probe-method-driven server shape: jlink-runner methods use cortex-debug's
358
- // jlink server (needs the device name from the board table); openocd-runner
359
- // methods keep the openocd server with the generated cfg file. Without a
360
- // method (ESP32 builtin-JTAG targets), the historical default applies.
361
- const servertype = method?.runner === 'jlink' ? 'jlink' : 'openocd';
362
- const isEsp32 = o.target.split('/')[0].startsWith('esp32');
363
- const cfg = {
157
+ return {
364
158
  name: `TypeCAD Debug (Zephyr, ${o.target.split('/')[0]})`,
365
159
  type: 'cortex-debug',
366
- // Attach mode: no download (the ELF is already flashed). The server
367
- // controller's attachCommands() just halts the target, then our
368
- // postAttachCommands reset it, set a HW breakpoint at main(), and
369
- // continue. HW breakpoints use debug registers and work before the
370
- // bootloader maps the app flash region.
160
+ // Attach mode: no download (the ELF is already flashed by the
161
+ // preLaunchTask's dependency chain). The server is west-owned;
162
+ // cortex-debug only connects.
371
163
  request: 'attach',
372
164
  cwd: '${workspaceFolder}',
373
165
  executable,
374
- servertype,
375
- ...(servertype === 'openocd' ? { configFiles } : {}),
376
- ...(method?.debugDevice ? { device: method.debugDevice } : {}),
377
- interface: method?.debugInterface ?? (isEsp32 ? 'jtag' : 'swd'),
166
+ servertype: 'external',
167
+ gdbTarget: `localhost:${DEBUG_SERVER_PORT}`,
378
168
  ...(gdbPath ? { gdbPath } : {}),
379
- ...(servertype === 'openocd' && openocdPath ? { serverpath: openocdPath } : {}),
380
169
  postAttachCommands,
381
- preLaunchTask: 'cuttlefish: build + flash (debug)',
170
+ preLaunchTask: DEBUG_SERVER_TASK,
171
+ postDebugTask: DEBUG_SERVER_STOP_TASK,
382
172
  };
383
- // openOcdCfgRel is consumed by configFiles above. Referenced here only to
384
- // keep the signature honest.
385
- void openOcdCfgRel;
386
- return cfg;
387
173
  }
388
- /**
389
- * Build the tasks.json entry: rebuild + flash only. cortex-debug starts
390
- * OpenOCD as a child process (servertype: "openocd"), so the preLaunch task
391
- * just needs to build and upload — no isBackground / OpenOCD wrapping.
392
- */
174
+ /** The build+flash task (preLaunchTask) — unchanged shape from the old flow. */
393
175
  function buildTask(o) {
394
176
  return {
395
- label: 'cuttlefish: build + flash (debug)',
177
+ label: DEBUG_BUILD_TASK,
396
178
  type: 'shell',
397
- command: 'npx cuttlefish build --compile --upload --debug',
179
+ command: 'npx typecad-hal build --compile --upload --debug',
398
180
  options: { cwd: `\${workspaceFolder}/${o.appRel}` },
399
181
  group: { kind: 'build', isDefault: false },
400
182
  problemMatcher: [],
401
183
  };
402
184
  }
403
185
  /**
404
- * The adapter speed the S3's built-in USB-Serial-JTAG runs stably at.
405
- *
406
- * The interface cfg (esp_usb_jtag.cfg) defaults to 40000 (40 MHz), the chip
407
- * max. The USB-Serial-JTAG peripheral is a software bitq adapter that bit-bangs
408
- * JTAG over USB bulk transfers; at 40 MHz it can't keep up, drops transfers
409
- * (LIBUSB_ERROR_IO / "missing data from bitq interface"), and the reset/halt
410
- * sequence silently fails — leaving the target running with no breakpoint set
411
- * (the "debugger starts but never stops / buttons don't work" symptom).
412
- *
413
- * 4000 (4 MHz) is the empirically-stable speed for this peripheral.
186
+ * The background task that is the F5 preLaunchTask — ONE task, no dependsOn:
187
+ * `debug-server start --flash` runs the whole build pipeline (transpile →
188
+ * compile → upload, with --debug) and then serves. VS Code releases the
189
+ * debug session to connect gdbTarget when the matcher's endsPattern (the
190
+ * ready marker) fires, while the task keeps serving. (A dependsOn chain was
191
+ * tried: VS Code awaits the whole dependency GROUP, and a background task
192
+ * that never exits never releases the session — F5 hung with no debug UI.)
414
193
  */
415
- const OPENOCD_ADAPTER_SPEED = 4000;
416
- /**
417
- * Build the OpenOCD cfg content. Sources the board's own openocd.cfg (which
418
- * sets ESP_RTOS Zephyr + ESP_ONLYCPU + the esp_usb_jtag driver + the esp32s3
419
- * target) then overrides the adapter speed AFTER the driver loads — the order
420
- * that a bare `-c "adapter speed N"` cannot guarantee (OpenOCD applies -c args
421
- * in command-line order relative to -f, and Cortex-Debug injects its own
422
- * helper/RTOS tcl, so the override can land before the driver exists or be
423
- * re-defaulted). Putting it in the cfg, after the source, is deterministic.
424
- */
425
- /**
426
- * Drop the gdb-attach/gdb-detach target-event blocks from a cfg line list.
427
- * Board cfgs use them for standalone openocd sessions (reset on attach,
428
- * resume on detach), but under VS Code they fire DURING cortex-debug's
429
- * initialization — the unexpected stop event aborts the session setup
430
- * ("Program stopped, probably due to a reset and/or halt issued by
431
- * debugger") and the toolbar never enables. The IDE owns the lifecycle.
432
- */
433
- function stripGdbEventBlocks(lines) {
434
- const out = [];
435
- let skipping = false;
436
- let depth = 0;
437
- for (const line of lines) {
438
- if (!skipping && /configure\s+-event\s+gdb-(attach|detach)/.test(line)) {
439
- skipping = true;
440
- depth = 0;
441
- }
442
- if (skipping) {
443
- depth += (line.match(/\{/g) ?? []).length - (line.match(/\}/g) ?? []).length;
444
- if (depth <= 0 && (line.includes('}') || !line.includes('{')))
445
- skipping = false;
446
- continue;
447
- }
448
- out.push(line);
449
- }
450
- return out;
194
+ function serverTask(o) {
195
+ return {
196
+ label: DEBUG_SERVER_TASK,
197
+ type: 'shell',
198
+ command: 'npx typecad-hal debug-server start --flash',
199
+ // NO_COLOR keeps chalk's ANSI codes out of the output — they break the
200
+ // background patterns below (the banner prints as ESC[36m⇳ Transpiling,
201
+ // and ^-anchored patterns never match past the escape byte). Same remedy
202
+ // as the scaffold's watch task.
203
+ options: { cwd: `\${workspaceFolder}/${o.appRel}`, env: { NO_COLOR: '1' } },
204
+ isBackground: true,
205
+ problemMatcher: {
206
+ owner: 'typecad-hal-debug-server',
207
+ // MUST never match a real line: matched lines become file-less
208
+ // problems (default severity: error), and VS Code then blocks F5 with
209
+ // "errors exist after running preLaunchTask". The sentinel literal
210
+ // cannot occur in pipeline or openocd output. (^$ was tried — it
211
+ // matches the blank lines openocd prints.)
212
+ pattern: { regexp: '__cuttlefish_never_matches__' },
213
+ background: {
214
+ beginsPattern: 'Transpiling',
215
+ endsPattern: `^TYPECAD_HAL: debug server ready on ${DEBUG_SERVER_PORT}`,
216
+ },
217
+ },
218
+ };
451
219
  }
452
- function buildOpenOcdCfg(method, target) {
453
- const header = [
454
- '# Auto-generated by @typecad/framework-zephyr. Do not edit — regenerate',
455
- '# with `cuttlefish build --debug`.',
456
- ];
457
- // Zephyr RTOS awareness (thread names in the call stack) — appended after
458
- // the target source on ARM targets; the ESP32 board cfgs already carry
459
- // ESP_RTOS Zephyr.
460
- const isEsp32 = (target ?? '').split('/')[0].startsWith('esp32');
461
- const rtosLine = isEsp32 ? [] : ['$_TARGETNAME configure -rtos Zephyr'];
462
- if (method?.debugCfgSource && method.debugCfgSource.length > 0) {
463
- // Probe-method-driven config: the board package's verified interface +
464
- // target sources, then the method's quirk lines (e.g. reset_config for an
465
- // unwired SRST) — the cfg-file form of the west runner args.
466
- return [
467
- ...header,
468
- `# Probe method '${method.id}' — from the board package's probeMethods table.`,
469
- ...method.debugCfgSource.map((src) => `source [find ${src}]`),
470
- ...stripGdbEventBlocks(method.debugCfg ?? []),
471
- ...rtosLine,
472
- '',
473
- ].join('\n');
474
- }
475
- // Pack-derived methods (the board's own support/openocd.cfg, extracted by
476
- // the board data pack) carry complete cfg lines — including their
477
- // `source [find ...]` directives — verbatim in file order, minus the
478
- // gdb-attach/detach events (IDE-managed lifecycle; see stripGdbEventBlocks).
479
- if (method?.debugCfg && method.debugCfg.length > 0) {
480
- return [
481
- ...header,
482
- `# Probe method '${method.id}' — the board's own support/openocd.cfg,`,
483
- `# extracted by the board data pack (gdb-attach/detach events removed —`,
484
- `# the IDE owns the session lifecycle).`,
485
- ...stripGdbEventBlocks(method.debugCfg),
486
- ...rtosLine,
487
- '',
488
- ].join('\n');
489
- }
490
- return [
491
- ...header,
492
- '# Sources the board cfg (which loads the esp_usb_jtag adapter driver +',
493
- '# esp32s3 target + ESP_RTOS Zephyr) then overrides the adapter speed to a',
494
- '# USB-JTAG-stable value AFTER the driver is loaded. See debug-config.ts',
495
- '# for the rationale.',
496
- 'source [find board/esp32s3-builtin.cfg]',
497
- `adapter speed ${OPENOCD_ADAPTER_SPEED}`,
498
- '',
499
- ].join('\n');
220
+ /** The postDebugTask — stops the west-owned server when the session ends. */
221
+ function serverStopTask(o) {
222
+ return {
223
+ label: DEBUG_SERVER_STOP_TASK,
224
+ type: 'shell',
225
+ command: 'npx typecad-hal debug-server stop',
226
+ options: { cwd: `\${workspaceFolder}/${o.appRel}` },
227
+ problemMatcher: [],
228
+ };
500
229
  }
501
230
  /**
502
- * Write all gdb-mode debug artifacts for the given target. Called from the
503
- * toolchain compile() after a successful build when debugMode === 'gdb'.
504
- *
505
- * Writes (all idempotent):
506
- * <workspaceRoot>/.vscode/launch.json (cortex-debug config)
507
- * <workspaceRoot>/.vscode/tasks.json (build + flash preLaunch task)
508
- * <projectRoot>/.cuttlefish/openocd.cfg (OpenOCD cfg, adapter speed override)
509
- * <projectRoot>/.cuttlefish/.cuttlefish-gdb.py (lambda frame filter, conditional)
510
- */
511
- /**
512
- * Resolve the debug-side probe method for a project: the board constants the
513
- * transpile persists + the workspace config's zephyr.probe selection.
514
- * Returns the method object (for cfg/servertype data) or undefined — ESP32
515
- * targets and boards without tables fall back to the framework's default
516
- * (esp_usb_jtag openocd) behavior.
231
+ * Write the debug artifacts: the cortex-debug launch entry (merged by name)
232
+ * and the three tasks (merged by label). Returns the workspace-relative
233
+ * paths written, for CLI reporting.
517
234
  */
518
- function resolveDebugProbeMethod(projectRoot, workspaceRoot) {
519
- try {
520
- const bcPath = [
521
- join(projectRoot, 'src', 'board-constants.json'),
522
- join(projectRoot, 'board-constants.json'),
523
- ].find((p) => existsSync(p));
524
- if (!bcPath)
525
- return undefined;
526
- const raw = JSON.parse(readFileSync(bcPath, 'utf8'));
527
- const chip = resolveChipFromBoard(new Map(Object.entries(raw)));
528
- if (!chip)
529
- return undefined;
530
- const zc = loadCuttlefishConfig(workspaceRoot)?.zephyrConfig;
531
- const probe = resolveProbeMethod(zc, chip, 'debug');
532
- if (!probe.ok)
533
- return undefined;
534
- return chip.probeMethods?.find((m) => m.id === zc?.probe);
535
- }
536
- catch {
537
- return undefined;
538
- }
539
- }
540
235
  export function writeDebugConfig(o) {
541
236
  const vscodeDir = join(o.workspaceRoot, '.vscode');
542
- const cuttlefishDir = join(o.projectRoot, '.cuttlefish');
543
- mkdirSync(cuttlefishDir, { recursive: true });
544
- // The selected probe method (if any) drives the debug server shape:
545
- // openocd cfg source/quirks, cortex-debug servertype, wire interface.
546
- const method = resolveDebugProbeMethod(o.projectRoot, o.workspaceRoot);
547
- // openocd.cfg — written first so its relative path can be wired into the
548
- // cortex-debug configFiles. cortex-debug starts OpenOCD as a child process
549
- // and passes this file via -f.
550
- const openOcdCfgPath = join(cuttlefishDir, 'openocd.cfg');
551
- writeFileSync(openOcdCfgPath, buildOpenOcdCfg(method, o.target), 'utf-8');
552
- const openOcdCfgRel = `${o.appRel}/.cuttlefish/openocd.cfg`;
553
- // launch.json — merge the cortex-debug config by name.
237
+ mkdirSync(vscodeDir, { recursive: true });
238
+ // west's resolved facts — present after any successful build. Before the
239
+ // first build the launch entry is written without gdbPath; the next build
240
+ // upgrades it (debugArtifactsNeedRewrite).
241
+ //
242
+ // west records the `-py` (python-enabled) gdb variant; cortex-debug derives
243
+ // objdump/nm paths from the gdb path by name substitution, and the -py
244
+ // variants of those do not exist in the SDK (ENOENT noise, degraded symbol
245
+ // classification). Prefer the plain gdb sibling when it exists.
246
+ let gdbPath = readRunnersFacts(o.buildDir)?.gdb?.replace(/\\/g, '/');
247
+ if (gdbPath && /-py(\.exe)?$/i.test(gdbPath)) {
248
+ const plain = gdbPath.replace(/-py(\.exe)?$/i, '$1');
249
+ if (existsSync(plain))
250
+ gdbPath = plain;
251
+ }
252
+ gdbPath = gdbPath ?? o.starterGdbPath;
253
+ // gdb frame-filter script (lambda frames) — conditional on a source map.
554
254
  const gdbScript = generateGdbScript(o.sourceMapPath);
555
255
  let gdbScriptRel;
556
256
  if (gdbScript) {
557
- const scriptPath = join(cuttlefishDir, '.cuttlefish-gdb.py');
257
+ const scriptPath = join(o.projectRoot, '.typecad-hal', '.typecad-hal-gdb.py');
258
+ mkdirSync(dirname(scriptPath), { recursive: true });
558
259
  writeFileSync(scriptPath, gdbScript, 'utf-8');
559
- gdbScriptRel = `${o.appRel}/.cuttlefish/.cuttlefish-gdb.py`;
260
+ gdbScriptRel = `${o.appRel}/.typecad-hal/.typecad-hal-gdb.py`;
560
261
  }
561
- const launchConfig = buildLaunchConfig(o, gdbScriptRel, openOcdCfgRel, method);
262
+ const launchConfig = buildLaunchConfig(o, gdbScriptRel, gdbPath);
562
263
  mergeJsonArrayEntry(join(vscodeDir, 'launch.json'), 'configurations', 'name', launchConfig);
563
- // tasks.json — merge the build+flash task by label. OpenOCD is managed by
564
- // cortex-debug so the task is a simple synchronous build step.
565
- const task = buildTask(o);
566
- mergeJsonArrayEntry(join(vscodeDir, 'tasks.json'), 'tasks', 'label', task);
264
+ const tasksPath = join(vscodeDir, 'tasks.json');
265
+ for (const task of [buildTask(o), serverTask(o), serverStopTask(o)]) {
266
+ mergeJsonArrayEntry(tasksPath, 'tasks', 'label', task);
267
+ }
268
+ return ['.vscode/launch.json', '.vscode/tasks.json'];
567
269
  }
568
270
  /**
569
- * The Zephyr app dir a `cuttlefish create` scaffold produces, relative to the
570
- * project root: the scaffold fixes entry `./src/main.ts` + outDir `./out`, and
571
- * the CLI resolves output.outDir against the ENTRY's directory (cli.ts), so
572
- * the emitted app root — and therefore the ELF, build dir, and .cuttlefish/
573
- * debug artifacts — always lands at `src/out`. Keep in sync with
574
- * generateProjectConfig in @typecad/cuttlefish create/templates.ts.
271
+ * The Zephyr app dir the standard `typecad-hal create` scaffold produces,
272
+ * relative to the project root: the scaffold fixes entry `./src/main.ts` +
273
+ * outDir `./out`, and the CLI resolves output.outDir against the ENTRY's
274
+ * directory (cli.ts), so the emitted app root lands at `src/out`. The create
275
+ * flow passes its actual resolution (typecad-hal create's starterAppRel) so a
276
+ * non-standard scaffold still gets correct starter paths; this is only the
277
+ * default.
575
278
  */
576
279
  const STARTER_APP_REL = 'src/out';
577
280
  /**
578
- * Create-time starter debug artifacts. Called by the cuttlefish `create` flow
579
- * (via the package's `writeProjectDebugArtifacts` export) so a fresh project
580
- * has a working F5 before any build exists:
581
- *
582
- * The launch.json's preLaunchTask runs `cuttlefish build --compile --upload
583
- * --debug`, which builds + flashes AND rewrites this same launch entry (merged
584
- * by name) with the CMakeCache-resolved gdbPath — so the starter files upgrade
585
- * themselves on the first debug build.
586
- *
587
- * No-ops (returns []) for targets without native GDB support (debugMode() !==
588
- * 'gdb'); the gdb frame-filter script is skipped (no source map exists yet).
281
+ * Create-time starter debug artifacts: the same west-driven launch entry and
282
+ * tasks, minus gdbPath (no build exists yet — runners.yaml is absent). The
283
+ * first build upgrades the entry (debugArtifactsNeedRewrite fires on the
284
+ * missing gdbPath), so F5 after a compile is fully resolved.
589
285
  *
590
- * Returns the workspace-relative paths written, for CLI reporting.
286
+ * No-ops (returns []) for targets without gdb debug facts (no debug-capable
287
+ * probe method in the board's table — printf instrumentation territory).
591
288
  */
592
289
  export function writeProjectDebugArtifacts(o) {
593
290
  if (new ZephyrStrategy().debugMode(o.buildTarget) !== 'gdb')
594
291
  return [];
595
292
  const workspaceRoot = resolve(o.workspaceRoot);
596
- const projectRoot = join(workspaceRoot, STARTER_APP_REL);
597
- writeDebugConfig({
293
+ const appRel = o.appRel ?? STARTER_APP_REL;
294
+ const projectRoot = join(workspaceRoot, appRel);
295
+ return writeDebugConfig({
598
296
  projectRoot,
599
297
  workspaceRoot,
600
- appRel: STARTER_APP_REL,
298
+ appRel,
601
299
  target: o.buildTarget ?? '',
602
- // No build dir exists yet — resolveGdbPath falls back to probing known
603
- // Zephyr SDK locations so gdbPath is still filled in when possible.
604
300
  buildDir: join(projectRoot, 'build'),
301
+ ...(o.gdbPath ? { starterGdbPath: o.gdbPath } : {}),
605
302
  });
303
+ }
304
+ // -- gdb frame-filter script -------------------------------------------------
305
+ export function generateGdbScript(sourceMapPath) {
306
+ if (!sourceMapPath || !existsSync(sourceMapPath))
307
+ return null;
308
+ let mapText = '';
309
+ try {
310
+ mapText = readFileSync(sourceMapPath, 'utf-8');
311
+ }
312
+ catch {
313
+ return null;
314
+ }
315
+ // Only emit when the emitted code contains hoisted-lambda symbols.
316
+ if (!/_isr_\d+/.test(mapText))
317
+ return null;
318
+ // A GDB Python frame-filter. Registered via the launch.json postAttachCommand
319
+ // `source <path>` so GDB auto-loads it on attach.
606
320
  return [
607
- '.vscode/launch.json',
608
- '.vscode/tasks.json',
609
- `${STARTER_APP_REL}/.cuttlefish/openocd.cfg`,
610
- ];
321
+ '# Auto-generated by @typecad/framework-zephyr. GDB frame-filter that',
322
+ '# rewrites typecad-hal hoisted-lambda frame names (*_isr_N) into readable',
323
+ '# <lambda> form so the VS Code call stack is legible.',
324
+ 'import gdb',
325
+ 'import re',
326
+ '',
327
+ 'class CuttlefishLambdaFilter:',
328
+ ' def __init__(self):',
329
+ ' self.name = "cuttlefish_lambda"',
330
+ ' self.priority = 100',
331
+ ' self.enabled = True',
332
+ '',
333
+ ' def filter(self, frame_iter):',
334
+ ' isr_re = re.compile(r"(.*)_isr_(\\d+)")',
335
+ ' return (CuttlefishFrame(f) for f in frame_iter)',
336
+ '',
337
+ 'class CuttlefishFrame:',
338
+ ' def __init__(self, frame):',
339
+ ' self.frame = frame',
340
+ ' def __getattr__(self, name):',
341
+ ' val = getattr(self.frame, name)',
342
+ ' if name == "function":',
343
+ ' m = isr_re.match(val)',
344
+ ' if m: return "<lambda>"',
345
+ ' return val',
346
+ '',
347
+ 'gdb.frame_filters[CuttlefishLambdaFilter().name] = CuttlefishLambdaFilter()',
348
+ '',
349
+ ].join('\n');
611
350
  }