@turingcode/cli 0.3.5 → 0.3.7

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 (25) hide show
  1. package/dist/cli/create-cli.js +1 -1
  2. package/dist/features/debug/command.js +1 -1
  3. package/dist/features/debug/debug_start.js +1 -1
  4. package/dist/features/probe/program_project.js +2 -2
  5. package/dist/features/project/command.js +3 -8
  6. package/dist/features/project/project_sync_to_server.js +1 -1
  7. package/dist/stm32/build.js +1 -1
  8. package/dist/stm32/utils/findElf.d.ts +1 -1
  9. package/dist/stm32/utils/findElf.js +1 -1
  10. package/mods/claude/turingcode-skills/skills/AGENTS.md +8 -0
  11. package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +5 -3
  12. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/SKILL.md +70 -25
  13. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/M_StatusEnum.md +33 -0
  14. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/app-startup.md +42 -0
  15. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver.md +97 -0
  16. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/host-protocol.md +41 -0
  17. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/registers-and-units.md +21 -26
  18. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/storage.md +57 -0
  19. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/tasks-and-interrupts.md +67 -0
  20. package/package.json +4 -1
  21. package/dist/features/project/project_build.d.ts +0 -3
  22. package/dist/features/project/project_build.js +0 -22
  23. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/concurrency.md +0 -42
  24. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/init-and-timing.md +0 -35
  25. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/input-and-bounds.md +0 -21
@@ -36,7 +36,7 @@ export function createCli(args) {
36
36
  "- Tables: check Markdown or CSV tables against a contract (a JSON file of tables, columns and",
37
37
  " MongoDB-style checks): `contract describe` shows the tables to write; `table check` until PASS.",
38
38
  " Contract format: $0 contract --help.",
39
- "- STM32 projects: `project sync`, `project build` on the server, `probe program` to flash the board,",
39
+ "- STM32 projects: `project sync -b` to build on the server, `probe program` to flash the board,",
40
40
  " `probe read` and `probe peripheral` to inspect it, `debug start` ... `debug stop` for a live debug",
41
41
  " session; `status` shows the project and the installed debug tools.",
42
42
  "- Agent skills: `install-skills` copies them into ~/.agents/skills (Codex, OpenCode);",
@@ -58,7 +58,7 @@ const command = {
58
58
  "`debug start` launches a background daemon for the project that holds the probe-rs session; the other",
59
59
  "debug commands talk to it, so the session lives across runs until `debug stop` (the daemon then exits).",
60
60
  "Its files are in .turingcode/ (daemon.token, daemon.log, probe.lock). Needs probe-rs and a .elf in build/",
61
- "(`project build`). Breakpoint files are project-relative paths, e.g. Core/Src/main.c.",
61
+ "(`project sync -b`). Breakpoint files are project-relative paths, e.g. Core/Src/main.c.",
62
62
  PROJECT_HELP,
63
63
  ].join("\n")),
64
64
  handler: () => { },
@@ -13,7 +13,7 @@ export default _defineTool({
13
13
  const project = await findStm32Project();
14
14
  const elf = await findElf(project.root);
15
15
  if (!elf)
16
- throw new Error("No .elf in the project's build/ folder: run `turingcode project build` first");
16
+ throw new Error("No .elf in the project's build/ folder: run `turingcode project sync -b` first");
17
17
  const chip = await getMcuFromIoc(project.root);
18
18
  const flash = args.flash === true;
19
19
  const s = await startSession({ root: project.root, chip, elf: elf.path, flash });
@@ -7,14 +7,14 @@ import { DebugActionProgram } from '../../stm32/actions/DebugActionProgram.js';
7
7
  export default _defineTool({
8
8
  name: 'program_project',
9
9
  description: "Flash the newest .elf in the project's build/ folder \
10
- (downloaded by `turingcode project build`) to the board over SWD with the installed programmer (probe-rs or STM32_Programmer_CLI), \
10
+ (downloaded by `turingcode project sync -b`) to the board over SWD with the installed programmer (probe-rs or STM32_Programmer_CLI), \
11
11
  verify it and reset the target.",
12
12
  needsProbe: true,
13
13
  run: async (_args, ctx) => {
14
14
  const project = await findStm32Project();
15
15
  const elf = await findElf(project.root);
16
16
  if (!elf)
17
- throw new Error("No .elf in the project's build/ folder: run `turingcode project build` first");
17
+ throw new Error("No .elf in the project's build/ folder: run `turingcode project sync -b` first");
18
18
  const chip = await getMcuFromIoc(project.root);
19
19
  const program_result = await DebugActionProgram.run_action_get_tail({
20
20
  elf: elf.path,
@@ -2,7 +2,6 @@ import { TOKEN_HELP } from "../../core/mcp.js";
2
2
  import { toolCommand } from "../../stm32/toolCommand.js";
3
3
  import analysisStatic from "./analysis_static.js";
4
4
  import analysisSyntaxCheck from "./analysis_syntax_check.js";
5
- import projectBuild from "./project_build.js";
6
5
  import projectDownloadTemplate from "./project_download_template.js";
7
6
  import projectRegenerate from "./project_regenerate.js";
8
7
  import projectSyncFromServer from "./project_sync_from_server.js";
@@ -23,10 +22,6 @@ const subcommands = [
23
22
  toolCommand({ command: "pull", tool: projectSyncFromServer, mode: "local", server: true, examples: [
24
23
  ["$0 project pull", "download the files that changed on the server, overwriting local copies"],
25
24
  ] }),
26
- toolCommand({ command: "build", tool: projectBuild, mode: "local", server: true, examples: [
27
- ["$0 project build", "build the Debug preset and download the .elf into build/Debug/"],
28
- ["$0 project build --preset Release", "build another preset"],
29
- ] }),
30
25
  toolCommand({ command: "check", tool: analysisSyntaxCheck, mode: "local", server: true, examples: [
31
26
  ["$0 project check", "syntax-check Core/ and App/ of the synced project"],
32
27
  ["$0 project check --files Core/Src/main.c", "one file"],
@@ -50,10 +45,10 @@ const command = {
50
45
  command: "project",
51
46
  describe: "Sync, build and edit the local STM32 project with the Turing Code server",
52
47
  builder: cli => subcommands.reduce((c, s) => c.command(s), cli)
53
- .demandCommand(1, "project needs a subcommand: sync, pull, build, check, analyze, regen, template or drivers")
48
+ .demandCommand(1, "project needs a subcommand: sync, pull, check, analyze, regen, template or drivers")
54
49
  .epilogue([
55
- "Typical use: edit files, `project sync` (or `project sync -b -a` to also build and analyse), `project build`,",
56
- "then `probe program`. `project check` (syntax) and `project analyze` (cppcheck, clang-tidy, MISRA) check the synced code.",
50
+ "Typical use: edit files, `project sync -b` (add `-a` to also analyse), then `probe program`.",
51
+ "`project check` (syntax) and `project analyze` (cppcheck, clang-tidy, MISRA) check the synced code.",
57
52
  "Other server tools (pins, clocks, .ioc edits) go through `tool call`; after one that",
58
53
  "changes the server copy, `project pull` brings the changes back, and `project regen` regenerates the code.",
59
54
  PROJECT_HELP,
@@ -19,7 +19,7 @@ export default _defineTool({
19
19
  build: {
20
20
  type: 'string',
21
21
  enum: ['', 'Debug', 'Release', 'RelWithDebInfo', 'MinSizeRel'],
22
- description: 'After a successful sync, build with this preset like `turingcode project build`; empty = Debug',
22
+ description: 'After a successful sync, build with this preset; empty = Debug',
23
23
  },
24
24
  analyse: {
25
25
  type: 'string',
@@ -1,4 +1,4 @@
1
- /** Server build of the STM32 project and download of its ELF. Used by the project commands and the VS Code extension. */
1
+ /** Server build of the STM32 project and download of its ELF. Used by `project sync -b` and the VS Code extension. */
2
2
  import { join } from 'node:path';
3
3
  import { replyBody } from '../core/mcp.js';
4
4
  import { downloadFile } from './utils/downloadzip_utils.js';
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Finds the most recently built .elf under the project's build/ folder (project_build downloads it to build/<preset>/).
2
+ * Finds the most recently built .elf under the project's build/ folder (project sync -b downloads it to build/<preset>/).
3
3
  * @param root project root folder
4
4
  * @returns the .elf path and its modification time, or undefined when there is none
5
5
  */
@@ -1,7 +1,7 @@
1
1
  import { readdir, stat } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  /**
4
- * Finds the most recently built .elf under the project's build/ folder (project_build downloads it to build/<preset>/).
4
+ * Finds the most recently built .elf under the project's build/ folder (project sync -b downloads it to build/<preset>/).
5
5
  * @param root project root folder
6
6
  * @returns the .elf path and its modification time, or undefined when there is none
7
7
  */
@@ -0,0 +1,8 @@
1
+ # Writing these skills
2
+
3
+ - Generic only: rules and house style that hold in any project. Never copy one project's architecture (boot order, register layout, frame format) into a skill.
4
+ - Save context: `SKILL.md` holds short rules and a reference table; details go in `references/*.md`, read only when needed.
5
+ - Short bullets, no prose. Small code examples that show the structure, not full implementations.
6
+ - Examples use the house names: `M_Status` / `M_StatusEnum::M_OK`, `this->`, `_member`, snake_case methods.
7
+ - Don't repeat what a tool already reports (e.g. `turingcode status` reports a missing token).
8
+ - Test a change with a subagent that follows only the skill, on real hardware when possible.
@@ -6,14 +6,16 @@ description: Use when running the turingcode CLI on an STM32 project - creating
6
6
  # turingcode for STM32
7
7
 
8
8
  - `turingcode` is a set of tools for working with stm32 projects.
9
- - Start with `turingcode status`: it shows the project, token, last build, debug session and the installed probe tools.
10
- - Server commands need `TURINGCODE_TOKEN`: set it in the environment, or put `TURINGCODE_TOKEN=<token>` in `.env` in the project folder.
9
+
10
+ ## Before you start
11
+
12
+ - Run `turingcode status` first: it shows the project, token, last build, debug session and the installed probe tools.
11
13
 
12
14
  ## Commands
13
15
 
14
16
  Read the help before you run commands in an area; every subcommand has its own `--help` with flags and examples.
15
17
 
16
- - `turingcode project --help`: sync, build, pull, regen, drivers, syntax check, static analysis.
18
+ - `turingcode project --help`: sync (with `-b` to build), pull, regen, drivers, syntax check, static analysis.
17
19
  - `turingcode probe --help`: flash, reset, read memory or registers, decode faults, recover a stuck probe.
18
20
  - `turingcode debug --help`: breakpoints, stepping, stack, variables.
19
21
 
@@ -1,47 +1,92 @@
1
1
  ---
2
2
  name: turingcode-firmware-code
3
- description: Coding rules for embedded C/C++ firmware (STM32, HAL, FreeRTOS/CMSIS-RTOS2). Use whenever writing, editing or reviewing .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.
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.
4
4
  ---
5
5
 
6
6
  # Embedded C/C++ rules
7
7
 
8
- When a rule and speed conflict, the rule wins.
8
+ These rules outrank speed: when a rule conflicts with a faster solution, follow the rule and report to the user.
9
9
 
10
- ## Load the reference that matches the task
10
+ ## Read the matching reference first
11
11
 
12
- Read the file before you write code in that area, not after.
12
+ Before writing code in an area, read its reference file:
13
13
 
14
14
  | Read | When the change touches |
15
15
  |---|---|
16
- | `references/input-and-bounds.md` | parsing UART/SPI/host frames, lengths, indices, register writes from a host, array or page bounds |
17
- | `references/concurrency.md` | ISRs, HAL callbacks, DMA, semaphores/mutexes, buffers shared between tasks or with an ISR, read-and-clear flags |
18
- | `references/init-and-timing.md` | boot order, flash-backed config, driver (re)init, timer callbacks, µs time, `extern "C"` interfaces |
19
- | `references/registers-and-units.md` | sensor drivers, datasheet registers, bit fields, units, signedness, macros |
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 |
20
23
 
21
- ## General code editing rules
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.
22
25
 
23
- - In generated files (main.c, stm32*_it.c, ...) write code only between `/* USER CODE BEGIN <name> */` and `/* USER CODE END <name> */`; CubeMX deletes everything else on project regeneration. Never change, move or delete the markers, and keep code the section already holds.
26
+ ## Generated and vendor code
27
+
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
+
35
+ ## File layout
36
+
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.
38
+
39
+ ### Folders
40
+
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 |
47
+ |---|---|
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 |
58
+
59
+ Create a folder only when something goes in it. No subfolders other than `Drivers/<IC>/`.
60
+
61
+ ### Files
62
+
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++).
64
+
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.
24
70
 
25
71
  ## House style
26
72
 
27
- Match this; don't "modernize" it.
73
+ Match the existing style; don't "modernize" it.
28
74
 
29
- - **Classes**: PascalCase joined with underscores, prefixed by layer or role: `Sensor_Driver`, `Util_Mutex`, `Filter_MovingAvg`.
30
- - **Members**: private fields start with `_`; internal helpers start with `__`. Always access members with `this->`.
31
- - **Methods**: snake_case for new code. Existing names in another case stay as they are; don't rename them on the side.
32
- - **Errors**: return a status enum, not `bool` or raw ints. Accumulate with `status |= ...` so the worst result wins.
33
- - **Comments**: `/* ---- Title ---- */` section banners. `/** */` blocks explain why, physics and units, and cite the datasheet. `////` marks code switched off for a short time.
34
- - **Compile-time choices**: templates and `if constexpr` for sizes and variants. Project selection goes through typedefs in a config header. Runtime feature switches are register or config bits.
35
- - **Layering**: reusable code goes in a shared library; project code only adds what's chip- or product-specific. C code (`main.c`) reaches C++ only through a thin `extern "C"` interface.
36
- - Never edit vendor code (HAL, CMSIS, generated code outside `USER CODE` blocks).
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.
37
82
 
38
- ## Rules for all code
83
+ ## Safety rules
39
84
 
40
- 1. **Never drop a status.** Check or accumulate every status, `HAL_StatusTypeDef` and RTOS return (`xTaskCreate`, semaphore acquire, queue send). Don't return a hard-coded OK after fallible steps. If ignoring one is truly fine, say why in one comment.
41
- 2. **Every wait has a timeout and an error path.** No bare `while(1)` on hardware (ID checks, waiting on a bit, ready flags), and no retry count where 0 means "forever". Return an error and make the failure visible; a missing peripheral must not hang boot silently.
42
- 3. **Memory budget.** No `new`/`delete` in periodic or per-transaction paths; preallocate buffers and matrices as members or statics. Keep KB-sized objects (large filter windows, matrices, arrays) off task stacks, and size each stack from what it holds.
43
- 4. **Speed tweaks get tested.** Before committing a performance change to a read or parse path, test it on hardware and check that the success branch still runs on success.
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.
44
89
 
45
90
  ## Before you finish
46
91
 
47
- Re-read the diff against the rules above and against the checklist at the end of each reference file you loaded.
92
+ Re-read the diff against these rules and the reference files you loaded.
@@ -0,0 +1,33 @@
1
+ # M_Status
2
+
3
+ - Use this when the project has no `M_Status.hpp` yet, or when unsure how to return or combine statuses.
4
+
5
+ ## Values
6
+
7
+ - Only these, ordered best to worst: `M_OK`, `M_ERROR`, `M_BUSY`, `M_TIMEOUT`, `M_OUT_OF_RANGE`, `M_DISABLED`, `M_NOT_SUPPORTED`. Never add one without asking.
8
+
9
+ ## Usage
10
+
11
+ ```cpp
12
+ M_Status status = M_StatusEnum::M_OK;
13
+ status |= this->com()->write(REG, &val, 1);
14
+ status |= HAL_SPI_Transmit(this->_hspi, buf, len, 10); // HAL statuses too
15
+ return status; // the worst result wins
16
+ ```
17
+
18
+ ## If the project has none
19
+
20
+ - Add `Utils/M_Status.hpp`. Include the family HAL header (`stm32g4xx_hal.h`, `stm32f3xx_hal.h`, ...) for `HAL_StatusTypeDef`.
21
+
22
+ ```cpp
23
+ enum M_StatusEnum { M_OK = 0, M_ERROR, M_BUSY, M_TIMEOUT, M_OUT_OF_RANGE, M_DISABLED, M_NOT_SUPPORTED };
24
+
25
+ class M_Status {
26
+ public:
27
+ M_StatusEnum value;
28
+ M_Status(M_StatusEnum v = M_OK) : value(v) {}
29
+ M_Status(HAL_StatusTypeDef h); // HAL_OK→M_OK, HAL_ERROR→M_ERROR, HAL_BUSY→M_BUSY, HAL_TIMEOUT→M_TIMEOUT
30
+ M_Status& operator|=(M_Status o) { if (o.value > this->value) this->value = o.value; return *this; }
31
+ operator M_StatusEnum() const { return this->value; }
32
+ };
33
+ ```
@@ -0,0 +1,42 @@
1
+ # App startup
2
+
3
+ - Use this when writing the `main.c` hook, the app entry, initialization order, task creation, re-init of drivers, or a µs time base.
4
+
5
+ ## Entry from main.c
6
+
7
+ - `main.c` passes the HAL handles in one C struct to one `extern "C"` function. The rest of the app is invisible to C.
8
+ - Declare every C-callable function in a header. Without one, C compiles an implicit declaration and passes garbage arguments.
9
+
10
+ ```c
11
+ #ifdef __cplusplus
12
+ extern "C" {
13
+ #endif
14
+ typedef struct {
15
+ SPI_HandleTypeDef* spi_1;
16
+ TIM_HandleTypeDef* tim_micros;
17
+ } App_Config;
18
+
19
+ void app_init(App_Config cfg);
20
+ #ifdef __cplusplus
21
+ }
22
+ #endif
23
+ ```
24
+
25
+ ## Initialization
26
+
27
+ - The order lives in one function, written out step by step. Don't spread it over constructors or static initializers.
28
+ - Construct before `init()`, and `init()` before first use. Nothing reads a store before it's loaded.
29
+ - If `init()` needs the scheduler (RTOS delays, mutexes), run it in a task, and make the tasks that depend on it wait for it.
30
+ - Check every `xTaskCreate`, `osThreadNew`, queue and event-group creation.
31
+
32
+ ## Re-init
33
+
34
+ - One owner handles re-init requests.
35
+ - Clear the module's ready flag first; its users skip their work while it's clear.
36
+ - Set it again only when `init()` returns `M_StatusEnum::M_OK`.
37
+
38
+ ## Time base
39
+
40
+ - A 32-bit µs counter wraps after about 71.6 min. Extend it with an overflow count, and test the wrap.
41
+ - A shared timer callback checks `htim` against the timer it owns before acting.
42
+ - Names match types (`delay_us(time_us_t us)`), and units are converted, not cast.
@@ -0,0 +1,97 @@
1
+ # Writing and Editing an IC driver
2
+
3
+ - Use this when you want to create or edit driver for ICs or Protocols.
4
+ - If the project already has a COM driver or an IC base with similar names, inherit from it. Don't write a second one.
5
+
6
+ ## Layers
7
+
8
+ - `COM_Driver` is the base for protocol drivers (`COM_SPI`, `COM_I2C`). Only these call HAL.
9
+ - `IC_Driver` is the base for IC drivers in `Drivers/<IC>/`. It talks to the chip only through a `COM_Driver*`.
10
+
11
+ ## COM driver
12
+
13
+ - Used as a base class for communication protocols (I2C, SPI, ...)
14
+ - Subclasses implement transfers (read and write) using HAL or LL methods.
15
+
16
+ ```cpp
17
+ class COM_Driver {
18
+ public:
19
+ virtual M_Status read(uint8_t reg, uint8_t* data, size_t len = 1) = 0;
20
+ virtual M_Status write(uint8_t reg, const uint8_t* data, size_t len) = 0;
21
+
22
+ M_Status write_bit(uint8_t reg, uint8_t bit, uint8_t value); // read-modify-write
23
+ M_Status write_verify(uint8_t reg, uint8_t value, size_t tries); // write, read back, compare
24
+ M_Status wait_for_register(uint8_t reg, uint8_t expected, size_t tries);
25
+ void set_address_mask(uint8_t write_or, uint8_t read_or); // e.g. SPI read bit 0x80
26
+ };
27
+ ```
28
+
29
+ ### Protocol driver
30
+
31
+ - Owns the HAL handle and chip select; the IC driver never sees them.
32
+ - Holds the bus mutex for the whole transfer, chip select included, so ICs sharing the bus don't interleave.
33
+
34
+ ```cpp
35
+ class COM_SPI : public COM_Driver {
36
+ public:
37
+ COM_SPI(SPI_HandleTypeDef* hspi, GPIO_TypeDef* cs_port, uint16_t cs_pin);
38
+ M_Status read(uint8_t reg, uint8_t* data, size_t len = 1) override; // CS low, TX reg|read mask, RX data, CS high
39
+ M_Status write(uint8_t reg, const uint8_t* data, size_t len) override;
40
+ private:
41
+ SPI_HandleTypeDef* _hspi;
42
+ GPIO_TypeDef* _cs_port;
43
+ uint16_t _cs_pin;
44
+ };
45
+ ```
46
+
47
+ ## IC_Driver Class
48
+
49
+ - Base class used for all ICs
50
+ - Subclasses implement the virtual methods.
51
+ - A feature the IC lacks (eg: write into a temperature sensor) returns `M_StatusEnum::M_NOT_SUPPORTED`, never `M_StatusEnum::M_OK`.
52
+ - ICs of one family can share a templated base between the two for compile-time sample sizes, (eg: `template <size_t AXES, size_t BYTES_PER_AXIS> class IC_Sensor : public IC_Driver`).
53
+
54
+ ```cpp
55
+ class IC_Driver {
56
+ public:
57
+ explicit IC_Driver(COM_Driver* com) : _com(com) {}
58
+ virtual M_Status init() = 0;
59
+ virtual M_Status reset() = 0;
60
+ virtual M_Status read(uint8_t* buf, size_t* index) = 0; // appends at buf[*index]
61
+ protected:
62
+ COM_Driver* com() { return this->_com; }
63
+ private:
64
+ COM_Driver* _com;
65
+ };
66
+ ```
67
+
68
+ ### IC Sensor Driver
69
+
70
+ ```cpp
71
+ class Sensor_ABC123 : public IC_Driver {
72
+ public:
73
+ using IC_Driver::IC_Driver;
74
+ M_Status init() override;
75
+ M_Status reset() override;
76
+ M_Status read(uint8_t* buf, size_t* index) override;
77
+ M_Status verify_id() { return this->com()->wait_for_register(ABC123_WHO_AM_I, ABC123_ID, 5); }
78
+ };
79
+ ```
80
+
81
+ - It never calls HAL and never creates its COM driver. The owner wires the two together:
82
+ ```cpp
83
+ COM_SPI spi_imu(&hspi1, IMU_CS_GPIO_Port, IMU_CS_Pin);
84
+ Sensor_ABC123 imu(&spi_imu);
85
+ ```
86
+
87
+ ## Register header
88
+
89
+ `abc123_regs.h`, plain C, in datasheet order:
90
+ ```c
91
+ #define ABC123_WHO_AM_I 0x0F
92
+ #define ABC123_ID 0x6B
93
+ #define ABC123_CTRL1 0x10
94
+ #define ABC123_ODR_POS 4
95
+ #define ABC123_ODR_MASK (0x0F << ABC123_ODR_POS)
96
+ #define ABC123_SPI_READ 0x80
97
+ ```
@@ -0,0 +1,41 @@
1
+ # Host protocol
2
+
3
+ - Use this when parsing frames from a host (UART, USB, SPI slave, CAN), dispatching commands, or building reply and telemetry packets.
4
+ - Every received byte is untrusted: one bad length can make the host write anywhere in memory.
5
+
6
+ ## Frame sizes
7
+
8
+ - Every size and offset of the frame is a `constexpr` derived from the others. No length is written as a literal in the parser.
9
+ - Use a template for compile-time size variants, per the house style.
10
+
11
+ ## Receiving
12
+
13
+ - Find the start of a frame, and drop the bytes before it. If the frame isn't complete yet, wait for more bytes.
14
+ - Remove the frame from the buffer whether or not it parsed, so a bad frame can't block the queue.
15
+ - Bound every search and copy by the bytes actually received, not by the maximum frame size.
16
+
17
+ ## Parse checks, in order
18
+
19
+ 1. The received length covers the header before any header byte is read.
20
+ 2. The length field matches the bytes received and is at most the maximum.
21
+ 3. Unsigned subtraction is guarded:
22
+ ```cpp
23
+ if (len < OVERHEAD) return M_StatusEnum::M_OUT_OF_RANGE;
24
+ size_t data_len = len - OVERHEAD;
25
+ ```
26
+ 4. The checksum or CRC matches before anything acts on the frame.
27
+
28
+ ## Dispatch
29
+
30
+ - A write to an indexed range checks the whole range, without overflow:
31
+ ```cpp
32
+ if (start >= COUNT || len > COUNT - start) return M_StatusEnum::M_OUT_OF_RANGE;
33
+ ```
34
+ - Writes to read-only data are rejected.
35
+ - Reply with the result, so the host sees a rejection.
36
+ - Keep these checks compiled in; never put them behind a debug-only macro.
37
+
38
+ ## Outgoing packets
39
+
40
+ - Build into a static buffer, and check the room left before each append.
41
+ - Clip values to their field width (`CLIP_U16(dt_us)`), and state the unit.
@@ -1,35 +1,30 @@
1
- # Registers, units and macros
1
+ # Registers and units
2
2
 
3
- ## Read the datasheet, then copy it exactly
3
+ - Use this when turning datasheet registers into code, or writing bit fields, units, conversions, constants or macros.
4
4
 
5
- - Check every bit position against the datasheet. A reset bit isn't bit 0 just because it's listed first.
6
- - Read two's-complement registers (trim values, temperature) into signed types (`int8_t`), as the datasheet says.
7
- - Keep the datasheet formula and section in a `/** */` comment next to the code that uses it.
5
+ ## Datasheet registers
8
6
 
9
- ## Bit edits clear before they set
10
-
11
- To change a field, clear it and then set it:
7
+ - Copy bit positions, widths and reset values from the datasheet, and cite it: `/** DS §8.3, table 21 */`.
8
+ - Read two's-complement registers into signed types. Sign-extend non-native widths explicitly:
12
9
  ```cpp
13
- reg = (reg & ~ODR_MASK) | (odr << ODR_POS);
10
+ int32_t v = ((int32_t)b[0] << 16) | (b[1] << 8) | b[2];
11
+ if (v & 0x800000) v -= 0x1000000; // 24-bit two's complement
12
+ ```
13
+ - Read multi-byte values out of byte buffers with `memcpy` or byte shifts, never through a cast pointer (`*(float*)&buf[i]`): the offset may be unaligned.
14
+ - Clear a field before setting it:
15
+ ```cpp
16
+ reg = (reg & ~ODR_MASK) | ((odr << ODR_POS) & ODR_MASK);
14
17
  ```
15
- Don't just OR a new value into a register that already holds the old one.
16
-
17
- ## Units are part of the name
18
18
 
19
- - Put the unit in the name or in the comment next to every constant: `ref_uT`, `dt_us`, `heading_rad`.
20
- - A fallback or reference constant uses the sensor's real output unit (a reference in gauss is wrong for a sensor that outputs µT).
21
- - Noise and scale conversions keep their units consistent: rad vs deg, magnitude vs magnitude squared.
19
+ ## Units
22
20
 
23
- ## Macros are fully parenthesized
21
+ - Put the unit in every name, or in a comment beside it: `dt_us`, `ref_uT`, `scale_mg_per_lsb`.
22
+ - Convert between units with a named conversion (`us_to_ns()`), never a cast.
23
+ - Write constants in the sensor's output unit.
24
+ - Name noise as `_std` or `_var`; the two differ by a square.
24
25
 
25
- ```cpp
26
- #define BUF_SIZE (3 * sizeof(float))
27
- #define CLIP_U16(x) ((x) > 0xFFFF ? 0xFFFF : (x))
28
- ```
29
- Prefer `constexpr` constants and `inline` functions over macros when no token pasting is needed. Derive layout constants (group lengths, offsets) from one source, so nothing is counted twice.
26
+ ## Constants and macros
30
27
 
31
- ## Checklist
32
- - [ ] Bit positions and signedness match the datasheet
33
- - [ ] Field writes clear the old value first
34
- - [ ] Every constant states its unit, and the unit matches the sensor
35
- - [ ] Macro bodies and arguments are parenthesized
28
+ - Prefer `constexpr` and `inline` over macros unless you need token pasting.
29
+ - Fully parenthesize macro bodies and arguments: `#define CLIP_U16(x) ((x) > 0xFFFF ? 0xFFFF : (x))`.
30
+ - Derive sizes and offsets from one source.
@@ -0,0 +1,57 @@
1
+ # Storage
2
+
3
+ - Use this when saving settings, calibration or other data to flash or EEPROM.
4
+
5
+ ## Register array
6
+
7
+ - Keep all settings in one byte array addressed by offset. RAM is the working copy; save and load it as a whole.
8
+ - Derive each offset from the previous one with `sizeof`:
9
+ ```cpp
10
+ #define REG_CTRL 0 // uint8
11
+ #define REG_CALIB_ACC 1 // 3 × float
12
+ #define REG_COUNT (REG_CALIB_ACC + 3 * sizeof(float))
13
+ ```
14
+ - Save only settings, never live status or measurements.
15
+ - Copy multi-byte values with `memcpy`, never through a cast pointer; offsets are unaligned and an unaligned `float` access faults.
16
+ - Keep defaults in one `static constexpr uint8_t REG_DEFAULTS[REG_COUNT]` table; `load_defaults()` copies it in.
17
+ - Bound every setter over the whole write:
18
+ ```cpp
19
+ if (reg >= REG_COUNT || len > REG_COUNT - reg) return M_StatusEnum::M_OUT_OF_RANGE;
20
+ ```
21
+
22
+ ## Settings page
23
+
24
+ - Use the last flash page, and shrink `FLASH` in the linker script by it so code can't land there:
25
+ ```ld
26
+ FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K - 2K /* last 2 KB page: settings */
27
+ ```
28
+ - Take the page size, program type and erase fields from the HAL, not from memory: `FLASH_PAGE_SIZE`, `FLASH_TYPEPROGRAM_*`, and `Page` or `PageAddress` in `FLASH_EraseInitTypeDef`.
29
+ - Derive the write unit from the program type (`sizeof(uint64_t)` for `DOUBLEWORD`). Align every block to it and pad with `0xFF`.
30
+ - Check every HAL flash return, and `PageError == 0xFFFFFFFF` after erase.
31
+
32
+ ## Header
33
+
34
+ - Start the page with one 16-byte header for the whole array, then the registers:
35
+ ```
36
+ [ magic u32 | version u16 | crc u32 | pad ][ registers ... ]
37
+ 0 4 6 10 16
38
+ ```
39
+ - `magic`: a fixed constant; blank or foreign flash won't match.
40
+ - `version`: bump it when an offset moves, a register is added or removed, or a new default must replace saved values.
41
+ - `crc`: over the registers; catches a cut-off save or a flipped bit.
42
+ - On load, if the read fails or any field mismatches, load the defaults and return `M_ERROR`. The caller logs it and keeps running; it's expected on first boot.
43
+
44
+ ## Writing
45
+
46
+ - Write in this order: build the header with the new CRC, unlock, erase, program the header, program the registers, lock, then read back and compare header and registers.
47
+ - Erase or program only after a successful unlock, and stop at the first failure. Always lock, even after a failure:
48
+ ```cpp
49
+ M_Status status = this->flash_unlock();
50
+ if (status == M_StatusEnum::M_OK) status |= this->flash_erase_page(SETTINGS_PAGE);
51
+ if (status == M_StatusEnum::M_OK) status |= this->flash_program(0, hdr, HDR_LEN);
52
+ if (status == M_StatusEnum::M_OK) status |= this->flash_program(HDR_LEN, this->_regs, REG_COUNT);
53
+ status |= this->flash_lock();
54
+ if (status == M_StatusEnum::M_OK) status = this->verify(hdr);
55
+ ```
56
+ - Give your own busy-bit polling a timeout; the HAL calls already have one.
57
+ - Save from a task or the main loop, never from an ISR.
@@ -0,0 +1,67 @@
1
+ # Tasks and interrupts
2
+
3
+ - Use this when writing ISRs, HAL callbacks, the main loop, RTOS tasks, DMA, or data shared between them.
4
+
5
+ ## ISRs
6
+
7
+ - Only signal from an ISR: set an event bit, notify a task, or bump a counter. Do bus transfers, parsing and math in the loop or a task; in an ISR they block every lower-priority interrupt.
8
+ - Never call blocking HAL (`HAL_SPI_Transmit`, `HAL_Delay`, ...) or `printf` in an ISR.
9
+ - Use one event bit per source.
10
+ - Count events that must not be lost; bits merge when an event repeats before it's handled:
11
+ ```cpp
12
+ while (this->_done != g_isr_count) { handle_event(); this->_done++; } // g_isr_count: volatile, ++ in the ISR
13
+ ```
14
+ - Null-check globals in callbacks; they can fire before the object exists.
15
+
16
+ ## Without an RTOS
17
+
18
+ - Set bits in a `volatile` event word in the ISR. In the loop, take and clear it with interrupts off, then work with them on:
19
+ ```cpp
20
+ __disable_irq();
21
+ uint32_t events = g_events;
22
+ g_events = 0;
23
+ __enable_irq();
24
+ if (events & EVT_IMU_READY) imu->read_into_memory();
25
+ ```
26
+
27
+ ## With FreeRTOS
28
+
29
+ - Notify the worker task from the ISR with `...FromISR` APIs, then yield:
30
+ ```cpp
31
+ BaseType_t woken = pdFALSE;
32
+ xTaskNotifyFromISR(reader_task, EVT_IMU_READY, eSetBits, &woken);
33
+ portYIELD_FROM_ISR(woken);
34
+ ```
35
+ - Give ISRs that call FreeRTOS an NVIC priority ≥ `configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY` (numerically).
36
+ - Wait with a timeout; on timeout poll the source, so a missed edge can't stall the task:
37
+ ```cpp
38
+ if (xTaskNotifyWait(0, UINT32_MAX, &bits, pdMS_TO_TICKS(50)) != pdTRUE
39
+ && HAL_GPIO_ReadPin(IMU_DRDY_GPIO_Port, IMU_DRDY_Pin)) bits |= EVT_IMU_READY;
40
+ ```
41
+
42
+ ## Shared data
43
+
44
+ - ISR ↔ loop or task: copy and clear under a critical section, then work on the copy. Use `taskENTER_CRITICAL()` with FreeRTOS, `__disable_irq()` without:
45
+ ```cpp
46
+ taskENTER_CRITICAL();
47
+ size_t n = rx_len;
48
+ memcpy(local, rx_buf, n);
49
+ rx_len = 0;
50
+ taskEXIT_CRITICAL();
51
+ parse(local, n); // never parse rx_buf in place
52
+ ```
53
+ - Task ↔ task: take a mutex with a timeout, never `portMAX_DELAY`. On timeout, skip this cycle.
54
+
55
+ ## DMA
56
+
57
+ - Use static or member buffers, never locals; DMA keeps running after the call returns.
58
+ - Check the length against the buffer size before copying in.
59
+ - Take a semaphore (RTOS) or test-and-set a busy flag with interrupts off (bare-metal) before writing the buffer. Release it in the complete callback, and yourself if the start fails:
60
+ ```cpp
61
+ if (HAL_UART_Transmit_DMA(this->_huart, this->_tx_buf, len) != HAL_OK) {
62
+ this->_tx_busy = false; // or this->_tx_sem.release()
63
+ return M_StatusEnum::M_ERROR;
64
+ }
65
+ ```
66
+ - Enable both the DMA and the peripheral interrupt in the `.ioc`; UART TX completion comes from the USART IRQ.
67
+ - Check the generated `*_IRQHandler` calls `HAL_DMA_IRQHandler` / `HAL_UART_IRQHandler`. If empty, add it in USER CODE; otherwise the IRQ re-enters forever.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turingcode/cli",
3
- "version": "0.3.5",
3
+ "version": "0.3.7",
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": {
@@ -23,7 +23,10 @@
23
23
  "build": "node scripts/build.cjs",
24
24
  "typecheck": "tsc --noEmit && tsc --project tsconfig.test.json --noEmit",
25
25
  "test": "node scripts/test.cjs",
26
+ "install-skills": "node scripts/build.cjs && node dist/cli/index.js install-skills",
27
+ "install-mods": "node scripts/build.cjs && node dist/cli/index.js install-mods",
26
28
  "default_publish": "npm publish --access public --tag latest",
29
+ "after_publish": "npm i -g @azrico/azcli",
27
30
  "prepublishOnly": "npm test && npm run build"
28
31
  },
29
32
  "publishConfig": {
@@ -1,3 +0,0 @@
1
- /** Builds the server copy and downloads the resulting ELF into the local build/<preset>/ folder. */
2
- declare const _default: import("../../stm32/tool.js").ToolDef;
3
- export default _default;
@@ -1,22 +0,0 @@
1
- import { runBuild } from '../../stm32/context.js';
2
- import { _defineTool } from '../../stm32/tool.js';
3
- import { findStm32Project } from '../../stm32/utils/project_utils.js';
4
- /** Builds the server copy and downloads the resulting ELF into the local build/<preset>/ folder. */
5
- export default _defineTool({
6
- name: 'project_build',
7
- description: 'Build the project on the TuringCode server \
8
- (run `turingcode project sync` first to include local changes), then download the .elf ' +
9
- 'into the local build/<preset>/ folder for `turingcode probe program`. \
10
- Prints the result, warnings in the project code, sizes and the clock audit summary (`--verbose` for the full reply).',
11
- properties: {
12
- preset: {
13
- type: 'string',
14
- enum: ['Debug', 'Release', 'RelWithDebInfo', 'MinSizeRel'],
15
- },
16
- verbose: {
17
- type: 'boolean',
18
- description: 'Print the full build reply (compiler, Drivers/ warnings, map file, stack usage, build log, clock tables); a failed build always prints it',
19
- },
20
- },
21
- run: async (args) => runBuild(await findStm32Project(), args.preset ?? 'Debug', !!args.verbose),
22
- });
@@ -1,42 +0,0 @@
1
- # Concurrency: ISRs, DMA, tasks
2
-
3
- ## Release on every path
4
-
5
- If a function takes a semaphore or mutex and then starts a transfer, release it when the start fails too. Otherwise the next wait blocks forever:
6
- ```cpp
7
- if (HAL_UART_Transmit_DMA(...) != HAL_OK) {
8
- this->_tx_sem.release();
9
- return Status::ERROR;
10
- }
11
- ```
12
- Error callbacks only release what belongs to that error. An RX overrun must not release the TX semaphore while TX DMA is still running.
13
-
14
- ## DMA buffers outlive the transfer
15
-
16
- - A buffer handed to DMA is static, a class member, or from a pool, never a local array. The stack frame is gone while DMA is still reading it.
17
- - Check the length against the DMA buffer size before copying into it.
18
- - Outgoing bytes (command, address) go in the TX buffer, not the RX one.
19
-
20
- ## Shared data has one owner and one protection
21
-
22
- For every buffer touched by an ISR and a task, or by two tasks, write a comment saying who writes it, who reads it and what protects it. Then pick one of these:
23
-
24
- - **ISR-filled queue:** the task wraps compaction and clearing in a critical section (or disables that IRQ), or the queue is a lock-free single-producer/single-consumer ring.
25
- - **Sample written by one task while another parses it:** read into a temp buffer, then copy or swap under the lock. Never write straight into the buffer being parsed, or you get torn samples.
26
- - **Driver used by a running task:** don't re-init or calibrate it while that task is still using it (see `init-and-timing.md`).
27
-
28
- ## Read-and-clear flags are consumed once
29
-
30
- A "consume" call returns a flag and clears it. Call it once per flag per cycle and keep the result:
31
- ```cpp
32
- const bool acc_changed = this->acc->consume_changed();
33
- const bool gyro_changed = this->gyro->consume_changed(); // its own flag
34
- ```
35
- A second call on the same flag always returns false.
36
-
37
- ## Checklist
38
- - [ ] Every acquire has a release on the failure path
39
- - [ ] Error callbacks only release their own resources
40
- - [ ] No DMA buffer on the stack; lengths checked against the DMA buffer
41
- - [ ] Every shared buffer has a documented owner and lock
42
- - [ ] Each read-and-clear flag is consumed exactly once per cycle
@@ -1,35 +0,0 @@
1
- # Initialization and timing
2
-
3
- ## Order is explicit
4
-
5
- - Nothing reads a store before it's initialized: init the flash driver before loading config from it. If the load fails, use defaults, not whatever `new` left in memory (it isn't zeroed).
6
- - Erased flash reads 0xFF, and that isn't a valid config: every bit on, every scale at its maximum. Detect it with a magic number, version or CRC, and fall back to safe defaults.
7
- - Leave the flash locked after init. Unlock only around an erase or program.
8
-
9
- ## Callbacks may fire before your objects exist
10
-
11
- HAL and ISR callbacks (EXTI, UART error, timer) can run before the task that creates the global object, for example when the interrupt is enabled in generated init code. Null-check every global pointer they use:
12
- ```cpp
13
- if (driver == nullptr) return;
14
- ```
15
-
16
- ## Re-init
17
-
18
- Before re-initializing or calibrating a driver:
19
- 1. Stop or pause the tasks that use it.
20
- 2. Clear its ready flag first.
21
- 3. Set the flag again only when init succeeds.
22
-
23
- ## Timers
24
-
25
- - Pass the correct handle to every timer helper. Helpers that compare handles return early on a mismatch, and the event is lost.
26
- - Declare every C-callable function in its header. Otherwise C compiles an implicit declaration, and the function gets garbage arguments without any error.
27
- - A 32-bit µs counter wraps after about 71.6 min. Extend it with overflow counting, and test the wrap.
28
- - Names match types: `delay_us(time_us_t us)`. Don't cast ns into a µs type without converting.
29
-
30
- ## Checklist
31
- - [ ] Stores are initialized before they're read; failed loads fall back to defaults
32
- - [ ] Blank flash is detected
33
- - [ ] Callbacks null-check globals
34
- - [ ] Re-init stops users and clears the ready flag first
35
- - [ ] Timer callbacks pass the right handle; C interfaces are declared in headers
@@ -1,21 +0,0 @@
1
- # Input and bounds
2
-
3
- Bytes from UART, SPI, flash or a host are untrusted. One bad length byte can let the host write anywhere in memory.
4
-
5
- ## Check before you use
6
-
7
- Before using a received value as a length, index or offset:
8
-
9
- - Check it against the **real** buffer size, not a "max expected" constant. A `memcpy` or search over the max length reads past a shorter buffer.
10
- - Guard unsigned subtraction:
11
- ```cpp
12
- if (recv_len < HEADER_LEN) return Status::OUT_OF_RANGE;
13
- size_t data_len = recv_len - HEADER_LEN;
14
- ```
15
- - Bound every write into a table (registers, config) against its count, for every element (`start + i < count`), not only the first.
16
- - Keep these checks compiled in. Don't put them behind a debug-only macro.
17
-
18
-
19
- ## Checklist
20
- - [ ] Every external length, index and offset is checked against the real size
21
- - [ ] No unsigned subtraction without a guard