@turingcode/cli 0.3.12 → 0.3.14

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.
@@ -4,70 +4,70 @@ import { describeContract } from "./describe.js";
4
4
  export const CONTRACT = { type: "string", demandOption: true, describe: "Contract JSON (required)" };
5
5
  export const JSON_FLAG = { type: "boolean", describe: "Full result as one-line JSON" };
6
6
  /** The contract format in brief, for `contract --help`. Only tables, and each table's and column's name, are required. */
7
- const FORMAT = `Contract JSON. Only "tables" and each table's and column's "name" are required; every other
8
- field is optional. "(default)" marks the value used when a field is left out; other values are examples.
9
- {
10
- "name": "shop.orders", "version": "1.0.0", "description": "...", // shown in output
11
- "format": "markdown", // (default), or "format": "csv": one <table>.csv per table. The tables
12
- // given with --tables / --dep must be in their own contract's format
13
- "missing_values": [""], // (default) cell texts that count as empty (null in queries), e.g. ["", "-"].
14
- // Keep a marker like "-" out of it when "-" is a real value: "-" allowed
15
- // but an empty cell forbidden is "required": true plus
16
- // "match": {"$or": [{"$eq": "-"}, {"$every": {"$ref": "Tests.ID"}}]}
17
- "allow_extra_tables": false, // (default) true: tables not declared here are allowed
18
- "depends_on": { "customers": "customers.contract.json" }, // path absolute or relative to this contract;
19
- // its tables passed with --dep customers=<file>, referenced as "customers:Table.Column"
20
- "tables": [{
21
- "name": "Orders",
22
- "required": true, // (default) the table must be in the document
23
- "primary_key": "Order_ID", // or ["A", "B"]; always filled and unique, no "required" needed
24
- "ordered": false, // (default) true: columns must be in the declared order
25
- "allow_extra_columns": false, // (default) true: columns not declared here are allowed
26
- "columns": [{
27
- "name": "Total",
28
- "type": "number", // string (default) | integer | number | boolean | date (YYYY-MM-DD) | list
29
- "required": false, // (default) true: every cell must be filled (an empty cell fails
30
- // MISSING_VALUE); the column itself must always be in the header
31
- "separator": ",", // (default) list item separator
32
- "match": { "$gte": 0, "$lte": 100 } // condition every filled cell meets (MongoDB query);
33
- // empty cells are skipped: use "required" to forbid them
34
- }],
35
- "rules": [{ // exactly one of require, count
36
- "id": "...", "description": "...", // shown in findings; description replaces the "expected" text
37
- "severity": "error", // (default) or "warning": reported as WARN, does not fail the check
38
- "on": "Table", // or "alias:Table"; default: the table the rule is in
39
- "when": { "Status": "shipped" }, // rows the rule applies to; default: all rows
40
- "require": { "Tracking": { "$ne": null } }, // row query each of them matches
41
- "count": { "$gte": 1 } // or: condition on how many there are
42
- }]
43
- }]
44
- }
45
- Queries are MongoDB syntax: cells are text, an empty cell is null, a list is an array of its items
46
- (split on "separator", trimmed; an operator matches if any item does, so {"$eq": "x"} means "has item x"
47
- and {"$ne": "x"} means "no item is x"). Operators:
48
- $eq $ne $in $nin $not $regex $options $or $and $nor (also inside a column's condition)
49
- $gt $gte $lt $lte exact number comparison, or date comparison with a "YYYY-MM-DD" bound
50
- $ref "Table.Column" value exists there (or "alias:Table.Column" of a dependency)
51
- $every {...} every list item meets the condition
52
- $length {...} length (chars, or list items) meets the condition
53
- $unique true no two rows share the value; in a row query ["A", "B"]: the combination
54
- $mentioned "Table.Column" | [...] | "*" value appears there as a word; "*": anywhere in the
55
- document outside the value's own table (prose and other tables both count)
56
- $calc "Qty * Price == Total" | {"expr": ..., "tolerance": 0.01} row query only; exact arithmetic
57
- Codes: each failing operator reports its own: $eq $in → BAD_VALUE, $regex → PATTERN, $gt.. → OUT_OF_RANGE,
58
- $length → BAD_LENGTH, $ref → UNKNOWN_REF, $unique → DUPLICATE_KEY, $mentioned → NOT_MENTIONED,
59
- {"$ne": null} in a rule → REQUIRED_IF, a wrong type → BAD_TYPE, a rule's other queries → MATCH.
60
- A value failing every branch of an $or reports the branches' code when they agree, else NONE_OF
61
- (each branch's code in the message, and in --json "alternatives").
62
- Examples:
63
- "match": { "$regex": "^O-[0-9]+$" }
64
- "match": { "$in": ["open", "paid", "shipped"] }
65
- "match": { "$length": { "$gte": 1 }, "$every": { "$ref": "Lines.Line_ID" } }
66
- "match": { "$or": [{ "$eq": "always" }, { "$ref": "Scenarios.ID" }] }
67
- "match": { "$ref": "customers:Customers.ID" } // a column of the dependency "customers"
68
- { "when": { "Kind": { "$in": ["resistor", "capacitor"] } }, "require": { "Value": { "$ne": null } } }
69
- { "require": { "$calc": { "expr": "Qty * Price == Total", "tolerance": "0.005" } } }
70
- { "on": "bom:Parts", "require": { "Ref": { "$ref": "Stock.Ref" } } }
7
+ const FORMAT = `Contract JSON. Only "tables" and each table's and column's "name" are required; every other
8
+ field is optional. "(default)" marks the value used when a field is left out; other values are examples.
9
+ {
10
+ "name": "shop.orders", "version": "1.0.0", "description": "...", // shown in output
11
+ "format": "markdown", // (default), or "format": "csv": one <table>.csv per table. The tables
12
+ // given with --tables / --dep must be in their own contract's format
13
+ "missing_values": [""], // (default) cell texts that count as empty (null in queries), e.g. ["", "-"].
14
+ // Keep a marker like "-" out of it when "-" is a real value: "-" allowed
15
+ // but an empty cell forbidden is "required": true plus
16
+ // "match": {"$or": [{"$eq": "-"}, {"$every": {"$ref": "Tests.ID"}}]}
17
+ "allow_extra_tables": false, // (default) true: tables not declared here are allowed
18
+ "depends_on": { "customers": "customers.contract.json" }, // path absolute or relative to this contract;
19
+ // its tables passed with --dep customers=<file>, referenced as "customers:Table.Column"
20
+ "tables": [{
21
+ "name": "Orders",
22
+ "required": true, // (default) the table must be in the document
23
+ "primary_key": "Order_ID", // or ["A", "B"]; always filled and unique, no "required" needed
24
+ "ordered": false, // (default) true: columns must be in the declared order
25
+ "allow_extra_columns": false, // (default) true: columns not declared here are allowed
26
+ "columns": [{
27
+ "name": "Total",
28
+ "type": "number", // string (default) | integer | number | boolean | date (YYYY-MM-DD) | list
29
+ "required": false, // (default) true: every cell must be filled (an empty cell fails
30
+ // MISSING_VALUE); the column itself must always be in the header
31
+ "separator": ",", // (default) list item separator
32
+ "match": { "$gte": 0, "$lte": 100 } // condition every filled cell meets (MongoDB query);
33
+ // empty cells are skipped: use "required" to forbid them
34
+ }],
35
+ "rules": [{ // exactly one of require, count
36
+ "id": "...", "description": "...", // shown in findings; description replaces the "expected" text
37
+ "severity": "error", // (default) or "warning": reported as WARN, does not fail the check
38
+ "on": "Table", // or "alias:Table"; default: the table the rule is in
39
+ "when": { "Status": "shipped" }, // rows the rule applies to; default: all rows
40
+ "require": { "Tracking": { "$ne": null } }, // row query each of them matches
41
+ "count": { "$gte": 1 } // or: condition on how many there are
42
+ }]
43
+ }]
44
+ }
45
+ Queries are MongoDB syntax: cells are text, an empty cell is null, a list is an array of its items
46
+ (split on "separator", trimmed; an operator matches if any item does, so {"$eq": "x"} means "has item x"
47
+ and {"$ne": "x"} means "no item is x"). Operators:
48
+ $eq $ne $in $nin $not $regex $options $or $and $nor (also inside a column's condition)
49
+ $gt $gte $lt $lte exact number comparison, or date comparison with a "YYYY-MM-DD" bound
50
+ $ref "Table.Column" value exists there (or "alias:Table.Column" of a dependency)
51
+ $every {...} every list item meets the condition
52
+ $length {...} length (chars, or list items) meets the condition
53
+ $unique true no two rows share the value; in a row query ["A", "B"]: the combination
54
+ $mentioned "Table.Column" | [...] | "*" value appears there as a word; "*": anywhere in the
55
+ document outside the value's own table (prose and other tables both count)
56
+ $calc "Qty * Price == Total" | {"expr": ..., "tolerance": 0.01} row query only; exact arithmetic
57
+ Codes: each failing operator reports its own: $eq $in → BAD_VALUE, $regex → PATTERN, $gt.. → OUT_OF_RANGE,
58
+ $length → BAD_LENGTH, $ref → UNKNOWN_REF, $unique → DUPLICATE_KEY, $mentioned → NOT_MENTIONED,
59
+ {"$ne": null} in a rule → REQUIRED_IF, a wrong type → BAD_TYPE, a rule's other queries → MATCH.
60
+ A value failing every branch of an $or reports the branches' code when they agree, else NONE_OF
61
+ (each branch's code in the message, and in --json "alternatives").
62
+ Examples:
63
+ "match": { "$regex": "^O-[0-9]+$" }
64
+ "match": { "$in": ["open", "paid", "shipped"] }
65
+ "match": { "$length": { "$gte": 1 }, "$every": { "$ref": "Lines.Line_ID" } }
66
+ "match": { "$or": [{ "$eq": "always" }, { "$ref": "Scenarios.ID" }] }
67
+ "match": { "$ref": "customers:Customers.ID" } // a column of the dependency "customers"
68
+ { "when": { "Kind": { "$in": ["resistor", "capacitor"] } }, "require": { "Value": { "$ne": null } } }
69
+ { "require": { "$calc": { "expr": "Qty * Price == Total", "tolerance": "0.005" } } }
70
+ { "on": "bom:Parts", "require": { "Ref": { "$ref": "Stock.Ref" } } }
71
71
  { "severity": "warning", "require": { "ID": { "$mentioned": "*" } } }`;
72
72
  const check = {
73
73
  command: "check",
@@ -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
  });
@@ -7,10 +7,8 @@ import { SWD_SPEED_PROP } from '../../stm32/actions/DebugAction.js';
7
7
  /** Flashes the newest ELF in the project's build/ folder. */
8
8
  export default _defineTool({
9
9
  name: 'program_project',
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).",
10
+ description: "Flash the newest .elf in the project's build/ folder \
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) => {
@@ -24,8 +22,8 @@ export default _defineTool({
24
22
  chip,
25
23
  speed: args.speed,
26
24
  }).catch((e) => {
27
- throw new Error(`${e?.message ?? e}\n\nIf the probe does not answer \
28
- (USB sleep, DEV_USB_COMM_ERR, probe not found), \
25
+ throw new Error(`${e?.message ?? e}\n\nIf the probe does not answer \
26
+ (USB sleep, DEV_USB_COMM_ERR, probe not found), \
29
27
  run \`turingcode probe reset-usb\` and try again once.`);
30
28
  });
31
29
  return `Programmed ${elf.path} (${chip})\n\n${program_result}`;
@@ -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);
@@ -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
  */
@@ -14,7 +14,7 @@ const ALWAYS_SKIPPED = /\.(zip|gz|gzip|rar)$/i; /** archives, even when listed i
14
14
  * @returns true if the path passes the rules
15
15
  */
16
16
  function isSyncablePre(rel) {
17
- return (!rel.startsWith("build/") &&
17
+ return (!/(^|\/)build\//.test(rel) && /** build output at any depth, as the server skips it */
18
18
  !/(^|\/)\.[^/]*\//.test(rel) && /** dot folders at any depth: .git, .turingcode, .codex, .vscode, ... */
19
19
  !/(^|\/)\.env(\.[^/]*)?$/.test(rel) && /** .env, .env.local, ... */
20
20
  !/\.csv$/i.test(rel) && /** data dumps */
@@ -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,45 +1,48 @@
1
- ---
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.
4
- ---
5
-
6
- # turingcode CLI for STM32
7
-
8
- `turingcode` handles the whole STM32 workflow: project setup, building, configuration, flashing and debugging. Use it instead of calling probe-rs or STM32_Programmer_CLI directly.
9
-
10
- ## Start here
11
-
12
- Run `turingcode status` first. It shows the project, token, last build, debug session and installed probe tools.
13
-
14
- ## Commands
15
-
16
- Each command group has its own `--help` with flags and examples. Read it before using commands in that area.
17
-
18
- - `turingcode project --help`: sync (`-b` to also build), pull, regen, drivers, syntax check, static analysis.
19
- - `turingcode probe --help`: flash, reset, read memory or registers, decode faults, recover a stuck probe.
20
- - `turingcode debug --help`: breakpoints, stepping, stack, variables.
21
-
22
- ## Server tools
23
-
24
- Pins, clocks, `.ioc` edits, register lookup and the datasheet knowledge base (MCUs and components) run as server tools:
25
-
26
- - `turingcode tool list` shows the available tools.
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`.
29
-
30
-
31
- ## New project
32
-
33
- Only when the user asks for a new project: follow [references/newproject.md](references/newproject.md).
34
-
35
- ## Typical loop
36
-
37
- 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.
38
- 2. Flash with `turingcode probe program`.
39
- 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.
40
- 4. On a crash, run `turingcode probe faults`, or `turingcode debug start` with breakpoints to find the cause.
41
-
42
- ## CRITICAL Safety rules
43
-
44
- - 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.
45
- - Don't touch RDP without a reason. Level 1 → 0 mass-erases the flash, and Level 2 is permanent.
1
+ ---
2
+ name: turingcode-cli
3
+ description: use for creating, build, debug, program, flash or analyze any STM32 project
4
+ ---
5
+
6
+ # turingcode CLI for STM32
7
+
8
+ `turingcode` handles the whole STM32 workflow: project setup, building, configuration, flashing and debugging. Use it instead of calling probe-rs or STM32_Programmer_CLI directly.
9
+
10
+ ## Start here
11
+
12
+ - Run `turingcode status` first. It shows the project, token, last build, debug session and installed probe tools.
13
+
14
+ ## Commands
15
+
16
+ Each command group has its own `--help` with flags and examples. Read it before using commands in that area.
17
+
18
+ - `turingcode project --help`: sync, build, pull, regen, syntax check and static analysis.
19
+ - `turingcode probe --help`: flash, reset, read memory or registers, decode faults, recover a stuck probe.
20
+ - `turingcode debug --help`: breakpoints, stepping, stack, variables.
21
+
22
+ ## Server tools
23
+
24
+ Pins, clocks, `.ioc` edits, register lookup and the datasheet knowledge base (MCUs and components) run as server tools:
25
+
26
+ - `turingcode tool list` shows the available tools.
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`.
29
+
30
+
31
+ ## New project
32
+
33
+ Only when the user asks for a new project: follow [references/newproject.md](references/newproject.md).
34
+
35
+ ## Typical loop
36
+
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.
39
+ 2. Flash with `turingcode probe program`.
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.
41
+ 4. On a crash, run `turingcode probe faults`, or `turingcode debug start` with breakpoints to find the cause.
42
+
43
+ ## CRITICAL Safety rules
44
+
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.
@@ -1,7 +1,48 @@
1
1
  # New project
2
2
 
3
- Only when the user asks for one.
3
+ Only when the user asks for a new project.
4
4
 
5
- 1. Run `turingcode probe info` to identify the connected chip and list its matching CubeMX names.
6
- 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.
7
- 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.
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 and their wakeups, 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.
@@ -1,57 +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.
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.
@@ -1,67 +1,70 @@
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.
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
+ - When an interrupt marks new data (UART RX event, data-ready pin, DMA complete), notify the task from it; don't make the task poll with `osDelay`. Poll only when no interrupt source exists, and say so in a comment.
36
+ - One notification can stand for several events: on each wake, handle everything pending (loop until no complete item is left).
37
+ - Set the task handle before enabling the IRQ, and reset it to `nullptr` if task creation fails.
38
+ - Give ISRs that call FreeRTOS an NVIC priority ≥ `configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY` (numerically).
39
+ - Wait with a timeout as a safety net; on timeout poll the source, so a missed edge (or data a parse step left behind) can't stall the task:
40
+ ```cpp
41
+ if (xTaskNotifyWait(0, UINT32_MAX, &bits, pdMS_TO_TICKS(50)) != pdTRUE
42
+ && HAL_GPIO_ReadPin(IMU_DRDY_GPIO_Port, IMU_DRDY_Pin)) bits |= EVT_IMU_READY;
43
+ ```
44
+
45
+ ## Shared data
46
+
47
+ - ISR ↔ loop or task: copy and clear under a critical section, then work on the copy. Use `taskENTER_CRITICAL()` with FreeRTOS, `__disable_irq()` without:
48
+ ```cpp
49
+ taskENTER_CRITICAL();
50
+ size_t n = rx_len;
51
+ memcpy(local, rx_buf, n);
52
+ rx_len = 0;
53
+ taskEXIT_CRITICAL();
54
+ parse(local, n); // never parse rx_buf in place
55
+ ```
56
+ - Task ↔ task: take a mutex with a timeout, never `portMAX_DELAY`. On timeout, skip this cycle.
57
+
58
+ ## DMA
59
+
60
+ - Use static or member buffers, never locals; DMA keeps running after the call returns.
61
+ - Check the length against the buffer size before copying in.
62
+ - 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:
63
+ ```cpp
64
+ if (HAL_UART_Transmit_DMA(this->_huart, this->_tx_buf, len) != HAL_OK) {
65
+ this->_tx_busy = false; // or this->_tx_sem.release()
66
+ return M_StatusEnum::M_ERROR;
67
+ }
68
+ ```
69
+ - Enable both the DMA and the peripheral interrupt in the `.ioc`; UART TX completion comes from the USART IRQ.
70
+ - 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.12",
3
+ "version": "0.3.14",
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": {