@turingcode/cli 0.3.8 → 0.3.13

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.
@@ -95,6 +95,10 @@ export function readJsonArg(value) {
95
95
  return JSON.parse(text);
96
96
  }
97
97
  catch (e) {
98
- throw new Error(`invalid JSON (${e.message})`);
98
+ /** Windows PowerShell 5.1 and cmd drop the inner quotes of inline JSON, leaving `{key:` behind. */
99
+ const hint = /^\s*[{[]\s*[\w$-]+\s*:/.test(text)
100
+ ? "; the shell removed its double quotes (Windows PowerShell 5.1 and cmd do), put the JSON in a .json file and pass its path"
101
+ : "";
102
+ throw new Error(`invalid JSON (${e.message})${hint}`);
99
103
  }
100
104
  }
@@ -7,7 +7,7 @@ import { SWD_SPEED_PROP } from '../../stm32/actions/DebugAction.js';
7
7
  /** Starts a probe-rs debug session on the project's board. */
8
8
  export default _defineTool({
9
9
  name: 'debug_start',
10
- description: "Start a probe-rs debug session on the project's board using the newest .elf in build/. By default it attaches to the running firmware (which must match that .elf); with flash=true it flashes the .elf first and halts after reset, so breakpoints can be set before continue. Takes ownership of the probe until `turingcode debug stop`.",
10
+ description: "Start a debug session on the project's board using the newest .elf in build/. By default it attaches to the running firmware (which must match that .elf); with flash=true it flashes the .elf first and halts after reset, so breakpoints can be set before continue. Takes ownership of the probe until `turingcode debug stop`.",
11
11
  properties: {
12
12
  flash: { type: 'boolean', description: 'Flash the .elf and halt after reset (default false: attach)' },
13
13
  speed: SWD_SPEED_PROP,
@@ -3,6 +3,6 @@ import { DebugActionListProbes } from '../../stm32/actions/DebugActionListProbes
3
3
  /** Lists the connected debug probes with the installed debug tool. */
4
4
  export default _defineTool({
5
5
  name: 'list_probes',
6
- description: 'List the debug probes (ST-LINK, J-Link, CMSIS-DAP, ...) connected to this machine (probe-rs list, or STM32_Programmer_CLI --list).',
6
+ description: 'List the debug probes (ST-LINK, J-Link, CMSIS-DAP, ...) connected to this machine.',
7
7
  run: async () => DebugActionListProbes.run_action_get_tail({}),
8
8
  });
@@ -8,9 +8,7 @@ import { SWD_SPEED_PROP } from '../../stm32/actions/DebugAction.js';
8
8
  export default _defineTool({
9
9
  name: 'program_project',
10
10
  description: "Flash the newest .elf in the project's build/ folder \
11
- (downloaded by `turingcode project sync -b`) to the board over SWD with the installed programmer (probe-rs or STM32_Programmer_CLI), \
12
- verify it and reset the target. If probe-rs fails and STM32_Programmer_CLI is installed, retries once with it \
13
- (hot-plug: attaches and halts the running core without a reset).",
11
+ (downloaded by `turingcode project sync -b`) to the board over SWD, verify it and reset the target.",
14
12
  properties: { speed: SWD_SPEED_PROP },
15
13
  needsProbe: true,
16
14
  run: async (args, ctx) => {
@@ -7,7 +7,7 @@ import { getMcuFromIoc, isArmv6m } from '../../stm32/utils/mcu_utils.js';
7
7
  /** Reads and decodes the SCB fault status registers. */
8
8
  export default _defineTool({
9
9
  name: 'read_fault_status',
10
- description: 'Read and decode the Cortex-M fault status registers (CFSR, HFSR, DFSR, MMFAR, BFAR, AFSR) over SWD (probe-rs or STM32_Programmer_CLI), without halting the core. Use it after the board hangs in HardFault_Handler.',
10
+ description: 'Read and decode the Cortex-M fault status registers (CFSR, HFSR, DFSR, MMFAR, BFAR, AFSR) over SWD, without halting the core. Use it after the board hangs in HardFault_Handler.',
11
11
  properties: { speed: SWD_SPEED_PROP },
12
12
  needsProbe: true,
13
13
  run: async (args, ctx) => {
@@ -7,7 +7,7 @@ import { SWD_SPEED_PROP } from '../../stm32/actions/DebugAction.js';
7
7
  /** Reads target memory while the core keeps running. */
8
8
  export default _defineTool({
9
9
  name: 'read_memory',
10
- description: "Read target memory over SWD (probe-rs or STM32_Programmer_CLI) without halting the core, at most 4096 bytes per call. Width defaults to the widest one the address and length allow; use 32 for peripheral registers.",
10
+ description: "Read target memory over SWD without halting the core, at most 4096 bytes per call. Width defaults to the widest one the address and length allow; use 32 for peripheral registers.",
11
11
  properties: {
12
12
  address: { type: 'string', pattern: '^0x[0-9A-Fa-f]{1,8}$' },
13
13
  length: { type: 'integer', minimum: 1, maximum: 4096, description: 'Bytes to read' },
@@ -9,7 +9,7 @@ import { loadPeripheral } from '../../stm32/utils/svdUtils.js';
9
9
  /** Reads a peripheral's registers and decodes them with the MCU's SVD data from the TuringCode server. */
10
10
  export default _defineTool({
11
11
  name: 'read_peripheral',
12
- description: "Read and decode a peripheral's registers (e.g. GPIOA, USART2, TIM1, RCC) over SWD (probe-rs or STM32_Programmer_CLI), using the MCU's SVD data from the TuringCode server (needs TURINGCODE_TOKEN the first time per peripheral, then cached in .turingcode/svd/ and works offline). Does not halt the core. Data/FIFO registers whose read has side effects are skipped. Lists non-zero fields only.",
12
+ description: "Read and decode a peripheral's registers (e.g. GPIOA, USART2, TIM1, RCC) over SWD (needs TURINGCODE_TOKEN the first time per peripheral, then works offline). Does not halt the core. Data/FIFO registers whose read has side effects are skipped. Lists non-zero fields only.",
13
13
  properties: { name: { type: 'string', pattern: '^[A-Za-z0-9_]{1,32}$' }, speed: SWD_SPEED_PROP },
14
14
  required: ['name'],
15
15
  needsProbe: true,
@@ -4,7 +4,7 @@ import { resetStlinkUsb } from '../../stm32/utils/usb_utils.js';
4
4
  /** Wakes an ST-LINK whose USB link went to sleep, which makes programming fail. */
5
5
  export default _defineTool({
6
6
  name: 'reset_probe_usb',
7
- description: 'Restart the USB connection of every connected ST-LINK probe (Windows, pnputil). Use when programming or debugging fails \
7
+ description: 'Restart the USB connection of every connected ST-LINK probe (Windows only). Use when programming or debugging fails \
8
8
  because the probe does not answer (e.g. it is in USB sleep, DEV_USB_COMM_ERR, "probe not found"). Needs administrator rights.',
9
9
  needsProbe: true,
10
10
  run: async () => {
@@ -6,7 +6,7 @@ import { SWD_SPEED_PROP } from '../../stm32/actions/DebugAction.js';
6
6
  /** Resets the board over SWD; the chip comes from the project's .ioc. */
7
7
  export default _defineTool({
8
8
  name: 'reset_target',
9
- description: "Hardware reset of the project's target board over SWD (probe-rs or STM32_Programmer_CLI).",
9
+ description: "Hardware reset of the project's target board over SWD.",
10
10
  properties: { speed: SWD_SPEED_PROP },
11
11
  needsProbe: true,
12
12
  run: async (args, ctx) => {
@@ -2,12 +2,11 @@ import { DebugActionInfo } from '../../stm32/actions/DebugActionInfo.js';
2
2
  import { SWD_SPEED_PROP } from '../../stm32/actions/DebugAction.js';
3
3
  import { callServer } from '../../stm32/context.js';
4
4
  import { _defineTool } from '../../stm32/tool.js';
5
- import { deviceLines, lineFamily, matchMcuNames, parseTargetInfo } from '../../stm32/utils/mcu_utils.js';
5
+ import { deviceLines, lineFamily, matchMcuNames, parseTargetInfo, } from '../../stm32/utils/mcu_utils.js';
6
6
  /** Identifies the connected chip and lists the CubeMX names that fit it, for `project template --mcu`. */
7
7
  export default _defineTool({
8
8
  name: 'target_info',
9
- description: 'Identify the chip connected to the debug probe (STM32_Programmer_CLI, without resetting it): device ID, name, flash size, core and voltage, ' +
10
- 'and the CubeMX MCU names that match it for `turingcode project template --mcu` (needs TURINGCODE_TOKEN; the package and pin count cannot be read over SWD). Needs no project.',
9
+ description: 'Identify the chip connected to the debug probe: device ID, name, flash size, core and voltage',
11
10
  properties: { speed: SWD_SPEED_PROP },
12
11
  needsProbe: true,
13
12
  run: async (args) => {
@@ -21,8 +20,10 @@ export default _defineTool({
21
20
  ];
22
21
  const families = [...new Set(deviceLines(info.name).map(lineFamily))];
23
22
  try {
24
- const names = (await Promise.all(families.map((family) => callServer('list_mcu_names', { family }))))
25
- .flatMap((text) => text.split('\n').map((l) => l.trim()).filter((l) => /^STM32\w+$/.test(l)));
23
+ const names = (await Promise.all(families.map((family) => callServer('list_mcu_names', { family })))).flatMap((text) => text
24
+ .split('\n')
25
+ .map((l) => l.trim())
26
+ .filter((l) => /^STM32\w+$/.test(l)));
26
27
  const matches = matchMcuNames(names, info);
27
28
  lines.push(matches.length
28
29
  ? `MCU names for \`project template --mcu\` (pick the package; it can't be read over SWD): ${matches.join(', ')}`
@@ -6,10 +6,9 @@ export default _defineTool({
6
6
  name: 'project_regenerate',
7
7
  description: 'Regenerate the project code from its .ioc file with CubeMX on the TuringCode server, then pull the result ' +
8
8
  '(run after pin, clock or peripheral edits). CubeMX keeps only the code inside USER CODE sections, so it first ' +
9
- 'compares each file with USER CODE markers with the code CubeMX generated last time (.turingcode/generated/) and ' +
9
+ 'compares each file with USER CODE markers with the code CubeMX generated last time and ' +
10
10
  'stops with a diff of the code that would be removed; force regenerates anyway and still shows that diff. ' +
11
- 'Local changes are synced to the server first. ' +
12
- 'The project is the folder with a .ioc or .mxproject file inside the project folder (the nearest folder holding .turingcode/ or a .ioc file, else the working directory); fails if there are several.',
11
+ 'Local changes are synced to the server first.',
13
12
  properties: {
14
13
  force: {
15
14
  type: 'boolean',
@@ -6,7 +6,7 @@ import { _defineTool } from '../../stm32/tool.js';
6
6
  import { findStm32Project } from '../../stm32/utils/project_utils.js';
7
7
  export default _defineTool({
8
8
  name: 'project_sync_to_server',
9
- description: 'Sync your local stm32 project files (except build/ and git-ignored files; Drivers/ is always sent) ' +
9
+ description: 'Sync your local stm32 project files (except build/ and git-ignored files; Drivers/ and Middlewares/ are always sent) ' +
10
10
  'to the TuringCode server; only files the server lacks or has a different version of are uploaded. \
11
11
  To restore deleted Drivers/ files use `turingcode project drivers`. \
12
12
  Stops before uploading when a USER CODE BEGIN/END marker is unmatched, and warns about code outside USER CODE sections that `project regen` would remove. \
@@ -56,6 +56,9 @@ export default _defineTool({
56
56
  if (args.analyse !== undefined) {
57
57
  emit(`# Static analysis\n${built ? await analysisStatic.run({ profile: args.analyse || 'quick' }, ctx) : 'Skipped: the build failed.'}`);
58
58
  }
59
+ /** a failed build must fail the command, or a script goes on to flash the previous ELF */
60
+ if (!built)
61
+ process.exitCode = 1;
59
62
  return parts.join('\n');
60
63
  },
61
64
  });
@@ -7,8 +7,7 @@ import { getMcuFromIoc } from '../../stm32/utils/mcu_utils.js';
7
7
  export default _defineTool({
8
8
  name: 'stm32_cubetools_download_drivers',
9
9
  description: 'Restore missing Drivers/ files (CMSIS, HAL) of your local stm32 project: downloads the complete Drivers/ folder ' +
10
- 'STM32CubeMX makes for the MCU in the .ioc and adds the files the project lacks; existing files are not overwritten. ' +
11
- 'The project is the folder with a .ioc or .mxproject file inside the project folder (the nearest folder holding .turingcode/ or a .ioc file, else the working directory); fails if there are several.',
10
+ 'STM32CubeMX makes for the MCU in the .ioc and adds the files the project lacks; existing files are not overwritten.',
12
11
  run: async () => {
13
12
  const project = await findStm32Project();
14
13
  const mcu = await getMcuFromIoc(project.root);
@@ -155,6 +155,7 @@ const call = {
155
155
  '`tool describe <name>`.',
156
156
  '--args is a JSON object, inline or a path to a .json file;',
157
157
  'leave it out for a tool without arguments.',
158
+ 'Windows PowerShell 5.1 and cmd strip the quotes of inline JSON: use a .json file there.',
158
159
  "The tool's text result goes to stdout: redirect it (`> file`) to save a large result without",
159
160
  'reading it. A tool error is printed to stderr.',
160
161
  TOKEN_HELP,
@@ -2,7 +2,7 @@
2
2
  * Lists the project files to push (posix relative paths): everything except build/, folders starting with a dot,
3
3
  * .env files, .zip/.csv/.gz/.gzip/.rar files, .md files other than README.md, files over 10 MB and git-ignored files. Drivers/ is always listed, even when git-ignored.
4
4
  * Only the files whose hash differs from the server's copy are uploaded, so the unchanged Drivers/ costs only its manifest entries.
5
- * Files and folders in included_files of .turingcode/settings.json are synced despite these rules, except archives and files over 10 MB.
5
+ * Files and folders in included_files of .turingcode/settings.json (always including Middlewares/) are synced despite these rules, except archives and files over 10 MB.
6
6
  * Logs a warning when git is unavailable, as .gitignore is then not applied.
7
7
  * ponytail: without git installed, .gitignore is not applied (only the fixed excludes); parse it here if that matters.
8
8
  */
@@ -75,7 +75,7 @@ async function walkFiles(root, dir = "") {
75
75
  * Lists the project files to push (posix relative paths): everything except build/, folders starting with a dot,
76
76
  * .env files, .zip/.csv/.gz/.gzip/.rar files, .md files other than README.md, files over 10 MB and git-ignored files. Drivers/ is always listed, even when git-ignored.
77
77
  * Only the files whose hash differs from the server's copy are uploaded, so the unchanged Drivers/ costs only its manifest entries.
78
- * Files and folders in included_files of .turingcode/settings.json are synced despite these rules, except archives and files over 10 MB.
78
+ * Files and folders in included_files of .turingcode/settings.json (always including Middlewares/) are synced despite these rules, except archives and files over 10 MB.
79
79
  * Logs a warning when git is unavailable, as .gitignore is then not applied.
80
80
  * ponytail: without git installed, .gitignore is not applied (only the fixed excludes); parse it here if that matters.
81
81
  */
@@ -2,7 +2,7 @@ export interface ProjectSettings {
2
2
  included_files: string[]; /** posix paths relative to the project root; files or folders synced even when otherwise excluded */
3
3
  }
4
4
  /**
5
- * Loads <root>/.turingcode/settings.json, filling missing keys with defaults.
5
+ * Loads <root>/.turingcode/settings.json; included_files always holds DEFAULT_INCLUDED plus the file's own entries.
6
6
  * @param root project root folder
7
7
  * @returns the project settings; defaults when the file does not exist
8
8
  * @throws when the file is not valid JSON, a key has the wrong type, or a path points outside the project
@@ -1,9 +1,10 @@
1
1
  import { readdir, readFile } from "node:fs/promises";
2
2
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
3
3
  import { homedir } from "node:os";
4
- const DEFAULTS = { included_files: [] };
4
+ /** Middlewares/ (FreeRTOS, USB, FatFs) is CubeMX output the build needs, yet projects often git-ignore it. */
5
+ const DEFAULT_INCLUDED = ["Middlewares"];
5
6
  /**
6
- * Loads <root>/.turingcode/settings.json, filling missing keys with defaults.
7
+ * Loads <root>/.turingcode/settings.json; included_files always holds DEFAULT_INCLUDED plus the file's own entries.
7
8
  * @param root project root folder
8
9
  * @returns the project settings; defaults when the file does not exist
9
10
  * @throws when the file is not valid JSON, a key has the wrong type, or a path points outside the project
@@ -12,7 +13,7 @@ export async function loadProjectSettings(root) {
12
13
  const file = join(root, ".turingcode", "settings.json");
13
14
  const text = await readFile(file, "utf8").catch((e) => (e?.code === "ENOENT" ? undefined : Promise.reject(e)));
14
15
  if (text === undefined)
15
- return { ...DEFAULTS };
16
+ return { included_files: [...DEFAULT_INCLUDED] };
16
17
  let raw;
17
18
  try {
18
19
  raw = JSON.parse(text);
@@ -25,7 +26,7 @@ export async function loadProjectSettings(root) {
25
26
  const included = raw.included_files ?? [];
26
27
  if (!Array.isArray(included) || !included.every((p) => typeof p === "string"))
27
28
  throw new Error(`${file}: included_files must be an array of strings`);
28
- return { included_files: included.map((p) => toProjectPath(root, p, file)).filter(Boolean) };
29
+ return { included_files: [...new Set([...DEFAULT_INCLUDED, ...included.map((p) => toProjectPath(root, p, file)).filter(Boolean)])] };
29
30
  }
30
31
  /**
31
32
  * Turns a settings path into a posix path relative to root, refusing paths outside the project.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: turingcode-cli
3
- description: Use the turingcode CLI for any STM32 project work - create, sync, build or analyze a project; regenerate from the .ioc; change pins, clocks or peripherals; flash, read registers or debug the board; look up MCU and component datasheets.
3
+ description: use for creating, build, debug, program, flash or analyze any STM32 project
4
4
  ---
5
5
 
6
6
  # turingcode CLI for STM32
@@ -9,13 +9,13 @@ description: Use the turingcode CLI for any STM32 project work - create, sync, b
9
9
 
10
10
  ## Start here
11
11
 
12
- Run `turingcode status` first. It shows the project, token, last build, debug session and installed probe tools.
12
+ - Run `turingcode status` first. It shows the project, token, last build, debug session and installed probe tools.
13
13
 
14
14
  ## Commands
15
15
 
16
16
  Each command group has its own `--help` with flags and examples. Read it before using commands in that area.
17
17
 
18
- - `turingcode project --help`: sync (`-b` to also build), pull, regen, drivers, syntax check, static analysis.
18
+ - `turingcode project --help`: sync, build, pull, regen, syntax check and static analysis.
19
19
  - `turingcode probe --help`: flash, reset, read memory or registers, decode faults, recover a stuck probe.
20
20
  - `turingcode debug --help`: breakpoints, stepping, stack, variables.
21
21
 
@@ -25,25 +25,24 @@ Pins, clocks, `.ioc` edits, register lookup and the datasheet knowledge base (MC
25
25
 
26
26
  - `turingcode tool list` shows the available tools.
27
27
  - `turingcode tool call <name> --args '<json>' > result.md` runs one.
28
+ - On Windows PowerShell or cmd, inline JSON loses its quotes: write the JSON to a `.json` file and pass `--args args.json`.
28
29
 
29
- After a tool changes the server copy of the project, run `turingcode project pull` (or `project regen`) to bring the changes local.
30
30
 
31
31
  ## New project
32
32
 
33
- Only when the user asks for one.
34
-
35
- 1. Run `turingcode probe info` to identify the connected chip and list its matching CubeMX names.
36
- 2. Pick one name. The package (pin count) can't be read over SWD, so ask the user or pick a package with the pins they need. Names that differ only in package build the same code for their shared pins.
37
- 3. Run `turingcode project template --mcu <name>` to download it into `./<name>/`, then `cd` into that folder. All project commands run from the project folder; copy your `.env` there if you use one.
33
+ Only when the user asks for a new project: follow [references/newproject.md](references/newproject.md).
38
34
 
39
35
  ## Typical loop
40
36
 
41
- 1. Edit the code, run `turingcode project sync -b` and fix the reported errors. Before finishing a change, run `turingcode project sync -b -a` to add static analysis.
37
+ 1. Edit the code, run `turingcode project sync -b` and fix the reported errors.
38
+ - Before finishing a change, run `turingcode project sync -b -a` for static analysis.
42
39
  2. Flash with `turingcode probe program`.
43
40
  3. Verify it runs without looking at the board: read a register the program changes a few times with `turingcode probe read` and check that it changes as expected.
44
41
  4. On a crash, run `turingcode probe faults`, or `turingcode debug start` with breakpoints to find the cause.
45
42
 
46
43
  ## CRITICAL Safety rules
47
44
 
48
- - Don't ever write debug registers by hand (DHCSR, DEMCR, DCRSR, DCRDR, FPB). doing so may brick the mcu. Halt, step and breakpoints go through `turingcode debug`, which releases the debug state on exit.
49
- - Don't touch RDP without a reason. Level 1 → 0 mass-erases the flash, and Level 2 is permanent.
45
+ - Don't ever write debug registers by hand (DHCSR, DEMCR, DCRSR, DCRDR, FPB). doing so may brick the mcu.
46
+ - Halt, step and breakpoints go through `turingcode debug`, which releases the debug state on exit.
47
+ - NEVER touch RDP without asking first.
48
+ - Level 1 → 0 mass-erases the flash, and Level 2 is permanent.
@@ -0,0 +1,48 @@
1
+ # New project
2
+
3
+ Only when the user asks for a new project.
4
+
5
+ 1. Run `turingcode probe info` to identify the connected chip.
6
+ 2. The package (pin count) can't be read over SWD, so ask the user
7
+
8
+ 3. Run `turingcode project template --mcu <name>` to download it into `./<name>/`, if project root is the current working directory you can copy the project files to `./` afterwards
9
+
10
+ 4. Add `.vscode/c_cpp_properties.json` so VS Code IntelliSense resolves the ARM GCC headers. the build gets its include paths and defines from CMake, IntelliSense does not. Two things matter:
11
+ - `compilerPath`: makes the extension ask GCC for its system include folders, where `stdint.h` lives.
12
+ - `defines`: `USE_HAL_DRIVER` and the device symbol (`STM32G474xx`, ...) are required by the HAL headers; without them the HAL fails to parse.
13
+
14
+ Take the include paths and defines from `cmake/stm32cubemx/CMakeLists.txt` (`MX_Include_Dirs`, `MX_Defines_Syms`) and the top-level `CMakeLists.txt`, and adjust the toolchain version to the installed one:
15
+
16
+ ```json
17
+ {
18
+ "version": 4,
19
+ "configurations": [
20
+ {
21
+ "name": "STM32",
22
+ "compilerPath": "C:/ST/STM32CubeCLT_1.18.0/GNU-tools-for-STM32/bin/arm-none-eabi-g++.exe",
23
+ "intelliSenseMode": "gcc-arm",
24
+ "cStandard": "c11",
25
+ "cppStandard": "c++17",
26
+ "includePath": [
27
+ "${workspaceFolder}/Core/Inc",
28
+ "${workspaceFolder}/Drivers/STM32G4xx_HAL_Driver/Inc",
29
+ "${workspaceFolder}/Drivers/STM32G4xx_HAL_Driver/Inc/Legacy",
30
+ "${workspaceFolder}/Drivers/CMSIS/Device/ST/STM32G4xx/Include",
31
+ "${workspaceFolder}/Drivers/CMSIS/Include",
32
+ "${workspaceFolder}/App/**"
33
+ ],
34
+ "defines": ["USE_HAL_DRIVER", "STM32G474xx", "DEBUG"]
35
+ }
36
+ ]
37
+ }
38
+ ```
39
+
40
+
41
+ 5. Make sure to these to `.gitignore`
42
+ ```gitignore
43
+ /Drivers/
44
+ /Middlewares/
45
+ /build/
46
+ .env
47
+ .turingcode/
48
+ ```
@@ -1,92 +1,94 @@
1
1
  ---
2
2
  name: turingcode-firmware-code
3
- description: Coding rules for embedded C/C++ firmware on STM32 (HAL, FreeRTOS, CMSIS-RTOS2) — file layout under App/, house style, and safety rules. Use whenever writing, editing, reviewing or organizing .c, .cpp, .h or .hpp files for a microcontroller, sensor drivers, ISRs and HAL callbacks, DMA, UART/SPI protocols, RTOS tasks, flash storage, filters, register maps and more.
3
+ description: Coding rules for embedded C/C++ firmware on STM32. Use whenever writing, editing, reviewing or organizing .c, .cpp, .h or .hpp files for a microcontroller or sensor driver.
4
4
  ---
5
5
 
6
6
  # Embedded C/C++ rules
7
7
 
8
- These rules outrank speed: when a rule conflicts with a faster solution, follow the rule and report to the user.
8
+ These rules outrank speed: when a rule conflicts with a faster solution, follow the rule and report it.
9
9
 
10
- ## Read the matching reference first
10
+ A project's `AGENTS.md` overrides this skill wherever it is more specific (layout, shared helpers, generator markers, tests). Read it first.
11
11
 
12
- Before writing code in an area, read its reference file:
12
+ ## Read the matching reference first
13
13
 
14
14
  | Read | When the change touches |
15
15
  |---|---|
16
- | `references/driver.md` | creating or modifying a driver for an external IC (sensor, part, ...) or Protocol (i2c, spi, ...) |
17
- | `references/registers-and-units.md` | datasheet registers, bit fields, signedness, units, conversions, macros |
18
- | `references/tasks-and-interrupts.md` | ISRs, HAL callbacks, the main loop, RTOS tasks, DMA, mutexes/semaphores, data shared between tasks or with an ISR |
19
- | `references/app-startup.md` | `main.c` hook, `extern "C"` entry, initialization order, task creation, re-init, µs time base |
20
- | `references/storage.md` | saving settings, calibration or other data to flash/EEPROM |
21
- | `references/host-protocol.md` | parsing host frames, command dispatch, register writes from a host, reply/telemetry packets |
22
- | `references/M_StatusEnum.md` | the project has no `M_Status.hpp`, or how to return and combine statuses |
16
+ | `references/driver.md` | a driver for an external IC or bus protocol |
17
+ | `references/registers-and-units.md` | datasheet registers, bit fields, signedness, units, conversions |
18
+ | `references/tasks-and-interrupts.md` | ISRs, HAL callbacks, the main loop, RTOS tasks, DMA, shared data |
19
+ | `references/app-startup.md` | `main.c` hook, `extern "C"` entry, init order, tasks, µs time base |
20
+ | `references/storage.md` | saving settings, calibration or data to flash/EEPROM |
21
+ | `references/host-protocol.md` | host frames, command dispatch, register writes, replies/telemetry |
22
+ | `references/M_StatusEnum.md` | no `M_Status.hpp`, or how to return and combine statuses |
23
23
 
24
- Names in the reference examples (`crc32`, `read_u32`, `flash_*`, `COM_Driver`, ...) are placeholders for the project's own helpers and base classes. Use the existing ones. Add a missing helper once, to `Utils/` (CRC, byte packing) or `Platform/` (flash, bus access), never inline in the module that needs it.
24
+ - some names in the references (`crc32`, `flash_*`, `COM_Driver`, ...) are placeholders for the project's own functions and helpers. Use the existing ones.
25
+ - add a missing helper once to the project's shared helper location (or `Utils/`/`Platform/` if it has none), never inline.
25
26
 
26
27
  ## Generated and vendor code
27
28
 
28
- - CubeMX regenerates generated files (`main.c`, `stm32*_it.c`, …) and deletes everything outside `/* USER CODE BEGIN <name> */` … `/* USER CODE END <name> */`. Write only inside these blocks, keep what they already hold, and never change, move or delete the markers.
29
- - Never edit vendor code (HAL, CMSIS).
30
- - If the generated code already defines a HAL callback (e.g. `HAL_TIM_PeriodElapsedCallback` for the HAL time base), don't define it again. Call your handler from its USER CODE block.
31
- - Keep `main.c` thin: it only calls into `App/app.cpp`,
32
- - when the app is C++ use a thin `extern "C"` interface.
33
- - All application code lives in `<Project>/App/`.
34
-
29
+ ## CubeMX-generated code
30
+
31
+ - In generated files (`main.c`, peripheral init, ...), write only inside
32
+ `/* USER CODE BEGIN/END */` blocks and leave the markers alone. CubeMX
33
+ deletes everything outside them when it regenerates.
34
+ - Don't edit HAL/CMSIS. Updates overwrite them.
35
+ - HAL callbacks can only be defined once. If generated code already defines
36
+ one (often in `main.c` or `stm32xxxx_it.c`), call your handler from its
37
+ USER CODE block.
38
+ - Keep `main.c` thin: it only calls `App/app.h` (`app_init()`, `app_loop()`),
39
+ which needs `extern "C"` guards. All application code lives in `<Project>/App/`.
40
+
35
41
  ## File layout
36
42
 
37
- The architecture plan splits the project into Code Areas, each with a Structural_Role, and lists the ICs used. Map them to files as follows.
43
+ Each Code Area you create gets one folder in `App/`:
38
44
 
39
- ### Folders
45
+ - External IC (registers, config, readout, commands) → `Drivers/<IC>/`, `<IC>` uppercase part number without ordering/package/reel suffixes. All Code Areas of one IC share it.
46
+ - Everything else → one category folder:
40
47
 
41
- Each Code Area gets exactly one folder in `<Project>/App/`:
42
-
43
- - Code that talks to an external IC (register access, configuration, readout, commands) → `Drivers/<IC>/`. `<IC>` is the part number from the IC list, uppercase, without ordering, package or reel suffixes. All Code Areas of one IC share that folder.
44
- - Everything else → one top-level category folder. Prefer these names; use another concise PascalCase name only when none fits:
45
-
46
- | Folder | Typical content |
48
+ | Folder | Content |
47
49
  |---|---|
48
- | `Platform/` | Adapters between HAL and App/: shared-bus arbitration, MCU peripheral access |
49
- | `Algorithms/` | Data transformation: conversion, calibration, filtering, estimation, fusion |
50
- | `Control/` | Regulation that commands actuators |
51
- | `Comms/` | Protocols with external hosts/devices: framing, parsing, telemetry |
52
- | `Storage/` | Persistent data: logs, saved settings |
53
- | `UI/` | Local user interaction: screens, menus, buttons, status LEDs |
54
- | `System/` | Orchestration: startup order, main cycle or tasks, modes, fault supervision |
55
- | `Update/` | Firmware update |
56
- | `Math/` | Shared numeric types and linear algebra |
57
- | `Utils/` | Generic, domain-free helpers used by two or more Code Areas |
50
+ | `Platform/` | HAL↔App adapters: bus arbitration, peripheral access |
51
+ | `Algorithms/` | conversion, calibration, filtering, estimation, fusion |
52
+ | `Control/` | regulation that commands actuators |
53
+ | `Comms/` | host/device protocols: framing, parsing, telemetry |
54
+ | `Storage/` | persistent data: logs, settings |
55
+ | `UI/` | screens, menus, buttons, LEDs |
56
+ | `System/` | startup order, main cycle/tasks, modes, faults |
57
+ | `Update/` | firmware update |
58
+ | `Math/` | numeric types and linear algebra |
59
+ | `Utils/` | domain-free helpers used by 2+ Code Areas |
60
+
58
61
 
59
- Create a folder only when something goes in it. No subfolders other than `Drivers/<IC>/`.
60
62
 
61
- ### Files
63
+ A shared library or SDK inside `App/` is not a Code Area: use it, don't restructure it, ask before changing it.
62
64
 
63
- Each Code Area is one module: a source file and a header with the same base name (`.c`/`.h` for C, `.cpp`/`.hpp` for C++).
65
+ Each Code Area is one module: source + header with the same base name.
64
66
 
65
- - **Driver modules**: the base name is the IC part number in lowercase (`test_ic_1.c` / `test_ic_1.h`), however the Code Area is worded. Add `<ic>_regs.h` when it does register access. A second Code Area for the same IC gets its own base name in the same folder.
66
- - **Other modules**: the base name is the snake_case of the Code Area's purpose, without the category word (`attitude_estimation`, `output_protocol`).
67
- - Header only, with no source file, when the module holds just constants, macros or inline/template helpers.
68
- - Base names are unique across `App/`; on a collision, prefix the lowercase category name.
69
- - Create no other files: no tests, docs, build files, README, configuration headers or placeholders.
67
+ - **Driver**: base name is the lowercase IC part (`test_ic_1.c/.h`); add `<ic>_regs.h` for register access. A second Code Area for the same IC gets its own base name in the same folder.
68
+ - **Other**: snake_case purpose without the category word (`attitude_estimation`).
69
+ - Header only when the module holds just constants, macros or inline/template helpers.
70
+ - Base names are unique across Code Area folders; on collision, prefix the lowercase category.
71
+ - Create no other files for a Code Area (tests, docs, build files, README, config headers) unless the project requires them.
70
72
 
71
73
  ## House style
72
74
 
73
75
  Match the existing style; don't "modernize" it.
74
76
 
75
- - **Classes**: PascalCase words joined by underscores, prefixed by layer or role: `Sensor_Driver`, `Util_Mutex`, `Filter_MovingAvg`.
76
- - **Members**: private fields start with `_`, internal helpers with `__`. Always access members through `this->`.
77
- - **Methods**: snake_case in new code. Leave existing names in other cases as they are.
78
- - **Errors**: return the project's `M_Status` (`M_StatusEnum::M_OK`, ...), never `bool` or raw ints. Accumulate with `status |= ...` so the worst result wins.
79
- - **Comments**: `/* ---- Title ---- */` for section banners; `/** */` blocks explain why, physics and units, and cite the datasheet; `////` marks code disabled temporarily.
80
- - **Variants**: templates and `if constexpr` for compile-time sizes and variants; runtime feature switches as register or config bits. Use concrete class names directly (`Sensor_ICM42688 imu;`), with no typedef selection layer.
81
- - **Layering**: all code lives in `App/`. Generic, reusable code goes in `Utils/` or `Math/`; chip- or product-specific code stays in its own module.
77
+ - **Classes**: PascalCase joined by underscores, prefixed by layer/role: `Sensor_Driver`, `Util_Mutex`, `Filter_MovingAvg`.
78
+ - **Members**: `_` private fields, `__` internal helpers, always via `this->`.
79
+ - **Methods**: snake_case in new code; leave existing names.
80
+ - **Errors**: return `M_Status` (`M_StatusEnum::M_OK`, ...), never `bool` or raw ints; accumulate with `status |= ...`.
81
+ - **Comments**: `/* ---- Title ---- */` banners; `/** */` explains why, physics, units, datasheet; `////` marks disabled code.
82
+ - **Variants**: templates/`if constexpr` for compile-time sizes; register/config bits for runtime switches; concrete class names, no typedef selection layer.
83
+ - **Layering**: all code in `App/`; generic code in the project's shared helper location (or `Utils/`/`Math/`), chip/product code in its own module.
82
84
 
83
85
  ## Safety rules
84
86
 
85
- 1. **Never drop a status.** Check or accumulate every status, `HAL_StatusTypeDef` and RTOS return (`xTaskCreate`, semaphore acquire, queue send). Never return a hard-coded `M_StatusEnum::M_OK` after fallible steps. If ignoring one is genuinely safe, say why in a comment.
86
- 2. **Every wait has a timeout and an error path.** No unbounded loops on hardware (ID checks, status bits, ready flags), and no retry count where 0 means "forever". Return an error so a missing peripheral fails visibly instead of hanging boot.
87
- 3. **Budget memory.** No `new`/`delete` in periodic or per-transaction paths; preallocate buffers and matrices as members or statics. Keep KB-sized objects (filter windows, matrices, arrays) off task stacks, and size each stack for what it holds.
88
- 4. **Test speed tweaks.** Before committing a performance change to a read or parse path, test it on hardware and confirm the success branch still runs on success.
87
+ 1. **Never drop a status.** Check or accumulate every status, `HAL_StatusTypeDef` and RTOS return. Never return `M_OK` after fallible steps; if ignoring one is safe, say why.
88
+ 2. **Every wait has a timeout and an error path.** No unbounded hardware loops, no retry count where 0 means "forever"; fail visibly instead of hanging boot.
89
+ 3. **Budget memory.** No `new`/`delete` in periodic/per-transaction paths; preallocate as members or statics; keep KB-sized objects off task stacks and size each stack.
90
+ 4. **Test speed tweaks** on hardware before committing, and confirm the success branch still runs.
89
91
 
90
92
  ## Before you finish
91
93
 
92
- Re-read the diff against these rules and the reference files you loaded.
94
+ Re-read the diff against these rules and the references you loaded.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turingcode/cli",
3
- "version": "0.3.8",
3
+ "version": "0.3.13",
4
4
  "description": "Turing Code toolkit for AI agents: check Markdown/CSV tables against table contracts, e.g. `turingcode table check`.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -42,4 +42,4 @@
42
42
  "@types/yargs": "17.0.35",
43
43
  "typescript": "7.0.2"
44
44
  }
45
- }
45
+ }