@turingcode/cli 0.3.6 → 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.
@@ -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.
@@ -15,7 +15,7 @@ Before writing code in an area, read its reference file:
15
15
  |---|---|
16
16
  | `references/driver.md` | creating or modifying a driver for an external IC (sensor, part, ...) or Protocol (i2c, spi, ...) |
17
17
  | `references/registers-and-units.md` | datasheet registers, bit fields, signedness, units, conversions, macros |
18
- | `references/tasks-and-interrupts.md` | ISRs, HAL callbacks, RTOS tasks, DMA, mutexes/semaphores, data shared between tasks or with an ISR |
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
19
  | `references/app-startup.md` | `main.c` hook, `extern "C"` entry, initialization order, task creation, re-init, µs time base |
20
20
  | `references/storage.md` | saving settings, calibration or other data to flash/EEPROM |
21
21
  | `references/host-protocol.md` | parsing host frames, command dispatch, register writes from a host, reply/telemetry packets |
@@ -27,6 +27,7 @@ Names in the reference examples (`crc32`, `read_u32`, `flash_*`, `COM_Driver`, .
27
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
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.
30
31
  - Keep `main.c` thin: it only calls into `App/app.cpp`,
31
32
  - when the app is C++ use a thin `extern "C"` interface.
32
33
  - All application code lives in `<Project>/App/`.
@@ -88,4 +89,4 @@ Match the existing style; don't "modernize" it.
88
89
 
89
90
  ## Before you finish
90
91
 
91
- Re-read the diff against these rules 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.
@@ -40,10 +40,3 @@ void app_init(App_Config cfg);
40
40
  - A 32-bit µs counter wraps after about 71.6 min. Extend it with an overflow count, and test the wrap.
41
41
  - A shared timer callback checks `htim` against the timer it owns before acting.
42
42
  - Names match types (`delay_us(time_us_t us)`), and units are converted, not cast.
43
-
44
- ## Checklist
45
- - [ ] `main.c` calls one `extern "C"` entry; every C-callable function is declared in a header
46
- - [ ] Init order is explicit in one place; nothing is used before its `init()`
47
- - [ ] Every task and RTOS object creation is checked
48
- - [ ] Re-init clears the ready flag first and sets it only on success
49
- - [ ] µs counters handle wrap
@@ -95,9 +95,3 @@ Sensor_ABC123 imu(&spi_imu);
95
95
  #define ABC123_ODR_MASK (0x0F << ABC123_ODR_POS)
96
96
  #define ABC123_SPI_READ 0x80
97
97
  ```
98
-
99
- ## Checklist
100
- - [ ] Existing COM driver and IC base are reused
101
- - [ ] IC driver inherits the base, gets its COM driver from the constructor, and makes no HAL calls
102
- - [ ] Every retry and wait is bounded and returns `M_StatusEnum::M_TIMEOUT`
103
- - [ ] Every status is accumulated; no hard-coded `M_StatusEnum::M_OK`
@@ -39,10 +39,3 @@ if (start >= COUNT || len > COUNT - start) return M_StatusEnum::M_OUT_OF_RANGE;
39
39
 
40
40
  - Build into a static buffer, and check the room left before each append.
41
41
  - Clip values to their field width (`CLIP_U16(dt_us)`), and state the unit.
42
-
43
- ## Checklist
44
- - [ ] Frame sizes are `constexpr` and derive from one source
45
- - [ ] Searches and copies are bounded by the received length
46
- - [ ] Unsigned subtraction is guarded; the checksum is checked before acting
47
- - [ ] Range writes check `start + len` without overflow
48
- - [ ] Bad frames are consumed and answered with an error
@@ -28,9 +28,3 @@ reg = (reg & ~ODR_MASK) | ((odr << ODR_POS) & ODR_MASK);
28
28
  - Prefer `constexpr` and `inline` over macros unless you need token pasting.
29
29
  - Fully parenthesize macro bodies and arguments: `#define CLIP_U16(x) ((x) > 0xFFFF ? 0xFFFF : (x))`.
30
30
  - Derive sizes and offsets from one source.
31
-
32
- ## Checklist
33
- - [ ] Bit positions and signedness match the datasheet, with a citation
34
- - [ ] Field writes clear the old value first
35
- - [ ] Every value states its unit; conversions are named
36
- - [ ] Macros are parenthesized; sizes come from one source
@@ -4,137 +4,54 @@
4
4
 
5
5
  ## Register array
6
6
 
7
- - All settings live in one byte array, addressed by offset. RAM is the working copy; flash is the saved copy, saved and loaded as a whole.
8
- - Each offset derives from the previous one and from `sizeof`, so nothing overlaps or is counted twice:
9
-
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`:
10
9
  ```cpp
11
- #define REG_CTRL 0
12
- #define REG_BOOT_COUNT 1 // uint8
13
- #define REG_CALIB_ACC 2 // 3 × float
14
- #define REG_CALIB_MAG (REG_CALIB_ACC + 3 * sizeof(float)) // 3 × float
15
- #define REG_COUNT (REG_CALIB_MAG + 3 * sizeof(float))
16
- ```
17
- - Save only settings. Live status and measurements stay out of the saved array.
18
- - Read and write multi-byte values with `memcpy`, never through a cast pointer. Offsets are not aligned, and an unaligned `float` access faults:
19
- ```cpp
20
- float x;
21
- memcpy(&x, &this->_regs[REG_CALIB_ACC], sizeof(x)); // not *(float*)&this->_regs[...]
22
- ```
23
- - Defaults are one table in code. `load_defaults()` copies it into the array:
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:
24
18
  ```cpp
25
- static constexpr uint8_t REG_DEFAULTS[REG_COUNT] = {
26
- 0x01, // REG_CTRL
27
- 0, // REG_BOOT_COUNT
28
- // the rest is zero-filled: calibration floats = 0.0f
29
- };
30
- ```
31
-
32
- - Setters reject offsets at or past the count, for every byte of a multi-byte write:
33
-
34
- ```cpp
35
- M_Status Register_Store::set_bytes(size_t reg, const uint8_t* src, size_t len) {
36
- if (reg >= REG_COUNT || len > REG_COUNT - reg)
37
- return M_StatusEnum::M_OUT_OF_RANGE;
38
- memcpy(&this->_regs[reg], src, len);
39
- return M_StatusEnum::M_OK;
40
- }
19
+ if (reg >= REG_COUNT || len > REG_COUNT - reg) return M_StatusEnum::M_OUT_OF_RANGE;
41
20
  ```
42
21
 
43
22
  ## Settings page
44
23
 
45
- - Use the last flash page. Take its address and size from the reference manual's flash chapter.
46
- - Shrink the `FLASH` length in the linker script by that page, so code can never be placed on it:
24
+ - Use the last flash page, and shrink `FLASH` in the linker script by it so code can't land there:
47
25
  ```ld
48
- /* last 2 KB page reserved for settings */
49
- FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K - 2K
26
+ FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K - 2K /* last 2 KB page: settings */
50
27
  ```
51
- - Take page size, write unit and erase style from the HAL flash header and API, not from memory: `FLASH_PAGE_SIZE`, the `FLASH_TYPEPROGRAM_*` types (half-word on F1/F3, double-word on G4/L4, flash-word on H7), and whether `FLASH_EraseInitTypeDef` takes a page number (`Page`, plus `Banks` on dual-bank parts) or an address (`PageAddress`). Every programmed block starts on, and is padded to, that write unit. The HAL has no write-unit constant; derive it from the program type, e.g. `#define FLASH_WRITE_UNIT sizeof(uint64_t)` for `FLASH_TYPEPROGRAM_DOUBLEWORD`.
52
- - Check every HAL flash return, and `PageError` after `HAL_FLASHEx_Erase` (`0xFFFFFFFF` means success).
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.
53
31
 
54
32
  ## Header
55
33
 
56
- - The first 16 bytes of the settings flash page are a header; the register array follows. One header covers the whole array, never one per setting.
57
-
58
- ```
59
- settings page: [ magic | version | crc | pad ][ registers ... ]
60
- 0 4 6 10 16
34
+ - Start the page with one 16-byte header for the whole array, then the registers:
61
35
  ```
62
-
63
- - Each field answers one question on load:
64
- - `magic`: does this page hold our settings at all? It's any fixed constant you pick. Blank flash (`0xFFFFFFFF`) or leftover data from other firmware won't match it.
65
- - `version`: was it saved with the current register layout? An old layout would load into the wrong offsets.
66
- - `crc`: are the registers intact? A save cut off by a reset, or a flipped bit, won't match.
67
-
68
- ```cpp
69
- #define FLASH_MAGIC 0x52454753u // "REGS"
70
- #define FLASH_VERSION 3 // bump when an offset moves, a register is added/removed, or a new default must replace saved values
71
- #define HDR_MAGIC 0 // uint32
72
- #define HDR_VERSION 4 // uint16
73
- #define HDR_CRC 6 // uint32, CRC of the registers
74
- #define HDR_LEN 16 // padded to a multiple of the flash write unit
75
- ```
76
-
77
- - On load, a blank flash (0xFF), or a magic, version or CRC mismatch, loads the defaults from code and reports it. The caller logs that `M_ERROR` and keeps running on the defaults; it's expected on first boot, not a fatal error:
78
-
79
- ```cpp
80
- M_Status Register_Store::load() {
81
- uint8_t hdr[HDR_LEN];
82
- M_Status status = this->flash_read(0, hdr, HDR_LEN);
83
- status |= this->flash_read(HDR_LEN, this->_regs, REG_COUNT);
84
- if (status != M_StatusEnum::M_OK
85
- || read_u32(&hdr[HDR_MAGIC]) != FLASH_MAGIC // blank flash reads 0xFFFFFFFF
86
- || read_u16(&hdr[HDR_VERSION]) != FLASH_VERSION
87
- || read_u32(&hdr[HDR_CRC]) != crc32(this->_regs, REG_COUNT)) {
88
- this->load_defaults();
89
- return M_StatusEnum::M_ERROR; // caller reports it
90
- }
91
- return M_StatusEnum::M_OK;
92
- }
36
+ [ magic u32 | version u16 | crc u32 | pad ][ registers ... ]
37
+ 0 4 6 10 16
93
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.
94
43
 
95
44
  ## Writing
96
45
 
97
- - Update the CRC, then erase, program, read back and compare.
98
- - Keep the flash locked except around erase and program, on the failure path too.
99
- - Pad with `0xFF`, the erased value, so padding programs nothing.
100
- - HAL erase and program calls time out internally; check their return. Code that polls the flash busy bit itself needs its own timeout.
101
-
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:
102
48
  ```cpp
103
- M_Status Register_Store::save() {
104
- uint8_t hdr[HDR_LEN];
105
- memset(hdr, 0xFF, HDR_LEN);
106
- write_u32(&hdr[HDR_MAGIC], FLASH_MAGIC);
107
- write_u16(&hdr[HDR_VERSION], FLASH_VERSION);
108
- write_u32(&hdr[HDR_CRC], crc32(this->_regs, REG_COUNT));
109
-
110
- M_Status status = this->flash_unlock();
111
- if (status == M_StatusEnum::M_OK) { // never erase or program a locked flash
112
- status |= this->flash_erase_page(SETTINGS_PAGE); // checks PageError too
113
- if (status == M_StatusEnum::M_OK) status |= this->flash_program(0, hdr, HDR_LEN);
114
- if (status == M_StatusEnum::M_OK) status |= this->flash_program(HDR_LEN, this->_regs, REG_COUNT); // pads the tail with 0xFF
115
- }
116
- status |= this->flash_lock(); // runs even after a failure
117
- if (status != M_StatusEnum::M_OK) return status;
118
- return this->verify(hdr);
119
- }
120
-
121
- M_Status Register_Store::verify(const uint8_t* hdr) { // read back header and registers
122
- uint8_t buf[HDR_LEN + REG_COUNT];
123
- M_Status status = this->flash_read(0, buf, sizeof(buf));
124
- if (status == M_StatusEnum::M_OK
125
- && (memcmp(buf, hdr, HDR_LEN) != 0 || memcmp(&buf[HDR_LEN], this->_regs, REG_COUNT) != 0))
126
- status = M_StatusEnum::M_ERROR;
127
- return status;
128
- }
129
- ```
130
-
131
- ## Checklist
132
- - [ ] Settings page is the last page and is removed from the linker's `FLASH` region
133
- - [ ] Page size, write unit and erase fields come from the HAL; every HAL return and `PageError` is checked
134
- - [ ] Blocks are aligned and `0xFF`-padded to the write unit
135
- - [ ] Multi-byte values are copied with `memcpy`; erase and program run only after a successful unlock
136
- - [ ] One header (magic, version, CRC) covers the whole array
137
- - [ ] Version is bumped on any layout change, or when a new default must replace saved values
138
- - [ ] Blank flash or a bad header falls back to defaults
139
- - [ ] Writes are read back and compared; flash stays locked after
140
- - [ ] Offsets derive from one source; setters are bounded
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.
@@ -1,66 +1,67 @@
1
1
  # Tasks and interrupts
2
2
 
3
- - Use this when writing ISRs, HAL callbacks, RTOS tasks, DMA transfers, or data shared between them.
3
+ - Use this when writing ISRs, HAL callbacks, the main loop, RTOS tasks, DMA, or data shared between them.
4
4
 
5
- ## ISR → task
6
-
7
- - ISRs and HAL callbacks only signal a task. Bus transfers, parsing and math run in the task.
8
- - One notify bit per source, so one task can serve several.
9
- - Null-check every global the callback uses, because it can fire before the object exists.
5
+ ## ISRs
10
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
11
  ```cpp
12
- void HAL_GPIO_EXTI_Callback(uint16_t pin) {
13
- if (reader_task == nullptr) return;
14
- uint32_t bits = 0;
15
- if (pin == IMU_DRDY_Pin) bits |= BIT_IMU_READY;
16
- if (pin == MAG_DRDY_Pin) bits |= BIT_MAG_READY;
17
- if (bits == 0) return;
18
- BaseType_t woken = pdFALSE;
19
- xTaskNotifyFromISR(reader_task, bits, eSetBits, &woken);
20
- portYIELD_FROM_ISR(woken);
21
- }
12
+ while (this->_done != g_isr_count) { handle_event(); this->_done++; } // g_isr_count: volatile, ++ in the ISR
22
13
  ```
14
+ - Null-check globals in callbacks; they can fire before the object exists.
15
+
16
+ ## Without an RTOS
23
17
 
24
- ## Task loop
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
+ ```
25
26
 
26
- - Waits on hardware events have a timeout. On timeout, poll the source (e.g. the DRDY pin level), so a missed edge doesn't stall it.
27
+ ## With FreeRTOS
27
28
 
29
+ - Notify the worker task from the ISR with `...FromISR` APIs, then yield:
28
30
  ```cpp
29
- void task_read_sensors(void*) {
30
- for (;;) {
31
- uint32_t bits = 0;
32
- if (xTaskNotifyWait(0, UINT32_MAX, &bits, pdMS_TO_TICKS(50)) != pdTRUE
33
- && HAL_GPIO_ReadPin(IMU_DRDY_GPIO_Port, IMU_DRDY_Pin)) bits |= BIT_IMU_READY;
34
- if (bits & BIT_IMU_READY) imu->read_into_memory();
35
- }
36
- }
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;
37
40
  ```
38
41
 
39
42
  ## Shared data
40
43
 
41
- - Every buffer used by two contexts has one comment: who writes it, who reads it, what protects it.
42
- - Task ↔ task: a mutex taken with a timeout. On timeout, skip this cycle instead of blocking.
43
- - ISR ↔ task: a single-producer/single-consumer ring, or a critical section around the task's compaction and clearing.
44
- - The writer fills a temporary buffer and copies or swaps it in under the lock. Never write into a buffer that is being parsed.
45
- - A read-and-clear flag is consumed once per cycle, and the result is kept in a local.
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.
46
54
 
47
55
  ## DMA
48
56
 
49
- - DMA buffers are static or class members, never locals.
50
- - Check the length against the DMA buffer size before copying into it.
51
- - Wait for the previous transfer (or take the TX semaphore) before reusing the buffer.
52
- - If starting the transfer fails, release what you took:
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:
53
60
  ```cpp
54
61
  if (HAL_UART_Transmit_DMA(this->_huart, this->_tx_buf, len) != HAL_OK) {
55
- this->_tx_sem.release();
62
+ this->_tx_busy = false; // or this->_tx_sem.release()
56
63
  return M_StatusEnum::M_ERROR;
57
64
  }
58
65
  ```
59
- - An error callback releases only the resources of the transfer that failed.
60
-
61
- ## Checklist
62
- - [ ] ISRs only notify; callbacks null-check globals
63
- - [ ] Every wait on hardware has a timeout and a fallback
64
- - [ ] Every shared buffer documents its writer, reader and lock
65
- - [ ] DMA buffers aren't on the stack; every acquire is released on failure
66
- - [ ] Each read-and-clear flag is consumed once per cycle
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.6",
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": {