@turingcode/cli 0.3.14 → 0.3.16

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 (46) hide show
  1. package/dist/cli/create-cli.js +46 -31
  2. package/dist/core/mcp.d.ts +0 -10
  3. package/dist/core/mcp.js +0 -18
  4. package/dist/features/project/analysis_static.js +5 -4
  5. package/dist/features/project/command.d.ts +3 -1
  6. package/dist/features/project/command.js +15 -11
  7. package/dist/features/project/project_regenerate.js +4 -3
  8. package/dist/features/project/project_sync_from_server.js +4 -3
  9. package/dist/features/project/project_sync_to_server.js +33 -8
  10. package/dist/features/project/stm32_cubetools_download_drivers.js +5 -4
  11. package/dist/features/status/get_status.js +6 -3
  12. package/dist/features/syntax-check/command.d.ts +2 -0
  13. package/dist/features/syntax-check/command.js +8 -0
  14. package/dist/features/syntax-check/syntax_check.d.ts +3 -0
  15. package/dist/features/syntax-check/syntax_check.js +27 -0
  16. package/dist/features/tool/command.d.ts +2 -0
  17. package/dist/features/tool/command.js +58 -7
  18. package/dist/lib.d.ts +1 -1
  19. package/dist/lib.js +1 -1
  20. package/dist/stm32/analysis.d.ts +40 -4
  21. package/dist/stm32/analysis.js +61 -5
  22. package/dist/stm32/toolCommand.d.ts +1 -0
  23. package/dist/stm32/toolCommand.js +7 -2
  24. package/dist/stm32/utils/makeTempProject.d.ts +16 -0
  25. package/dist/stm32/utils/makeTempProject.js +79 -0
  26. package/dist/stm32/utils/project_utils.d.ts +36 -1
  27. package/dist/stm32/utils/project_utils.js +48 -2
  28. package/mods/claude/turingcode-skills/skills/AGENTS.md +0 -5
  29. package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +2 -1
  30. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/SKILL.md +50 -42
  31. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/M_StatusEnum.md +30 -9
  32. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/code/BusMutexRegistry.hpp +138 -0
  33. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/code/COM_Driver.hpp +97 -0
  34. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/code/COM_I2C.hpp +83 -0
  35. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/code/COM_SPI.hpp +69 -0
  36. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/code/COM_USART.hpp +58 -0
  37. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/code/Util_MutexManager.hpp +212 -0
  38. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver.md +81 -0
  39. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_ic.md +123 -0
  40. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_protocol.md +16 -0
  41. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_rtos.md +129 -0
  42. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_test.md +17 -0
  43. package/package.json +1 -1
  44. package/dist/features/project/analysis_syntax_check.d.ts +0 -3
  45. package/dist/features/project/analysis_syntax_check.js +0 -21
  46. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver.md +0 -97
@@ -1,20 +1,56 @@
1
- /** Server syntax check and static analysis of the STM32 project. Used by the project commands and the VS Code extension. */
2
1
  import { ServerCall } from './sync.js';
3
2
  import { Project } from './tool.js';
3
+ import { TempProject } from './utils/makeTempProject.js';
4
4
  /**
5
- * Syntax-checks files of the project's server copy.
5
+ * Syntax-checks files of the project's server copy with the server's analysis tool.
6
6
  * @param call server tool caller
7
7
  * @param project project root and name
8
8
  * @param files project-relative files, globs or folders (default: Core and App)
9
- * @returns `file:line:col: severity: message` lines
9
+ * @returns one report per file, with `file:line:col: severity: message` lines for errors
10
10
  */
11
11
  export declare function syntaxCheckProject(call: ServerCall, project: Project, files?: string[]): Promise<string>;
12
+ /**
13
+ * Syntax-checks a synced folder: Core/ and App/ of an STM32 project, or every synced .c/.h/.cpp/.hpp file of any other folder.
14
+ * @param call server tool caller
15
+ * @param project folder, server name and whether it holds a .ioc, as resolveProjectDir returns them
16
+ * @returns one report per file, with `file:line:col: severity: message` lines for errors
17
+ */
18
+ export declare function syntaxCheckFolder(call: ServerCall, project: Project & {
19
+ stm32: boolean;
20
+ }): Promise<string>;
12
21
  /**
13
22
  * Runs static analysis on the project's server copy (its own sources, never Drivers/).
14
23
  * @param call server tool caller
15
24
  * @param project project root and name
16
25
  * @param profile quick, full or misra
17
- * @param paths comma-separated files, globs or folders to limit the check to; empty for the whole project
26
+ * @param paths comma-separated project-relative files, globs or folders to limit the check to; empty for the whole project
18
27
  * @returns `file:line:col: severity: message [check id]` lines
19
28
  */
20
29
  export declare function analyzeProject(call: ServerCall, project: Project, profile?: string, paths?: string): Promise<string>;
30
+ /**
31
+ * Rewrites the temp project's paths in a server report to the local files they were copied from.
32
+ * @param text server report
33
+ * @param temp the temp project
34
+ * @param cwd folder the shown paths are relative to
35
+ * @returns the report with local paths
36
+ */
37
+ export declare function toLocalPaths(text: string, temp: TempProject, cwd: string): string;
38
+ /**
39
+ * Copies loose files into a temp project (see makeTempProject) and syncs it to the server.
40
+ * @param call server tool caller
41
+ * @param paths files, folders or globs, relative to cwd
42
+ * @param cwd caller's working directory
43
+ * @returns the temp project and the sync summary
44
+ */
45
+ export declare function syncLooseFiles(call: ServerCall, paths: string[], cwd: string): Promise<{
46
+ temp: TempProject;
47
+ synced: string;
48
+ }>;
49
+ /**
50
+ * Syntax-checks an already synced temp project's requested files.
51
+ * @param call server tool caller
52
+ * @param temp the temp project
53
+ * @param cwd caller's working directory, for the shown paths
54
+ * @returns the server report with local paths
55
+ */
56
+ export declare function syntaxCheckTempProject(call: ServerCall, temp: TempProject, cwd: string): Promise<string>;
@@ -1,21 +1,77 @@
1
+ /** Server syntax check and static analysis of the STM32 project. Used by the project commands and the VS Code extension. */
2
+ import { relative } from 'node:path';
3
+ import { syncProjectToServer } from './sync.js';
4
+ import { listSyncFiles } from './utils/listSyncFiles.js';
5
+ import { makeTempProject } from './utils/makeTempProject.js';
1
6
  /**
2
- * Syntax-checks files of the project's server copy.
7
+ * Syntax-checks files of the project's server copy with the server's analysis tool.
3
8
  * @param call server tool caller
4
9
  * @param project project root and name
5
10
  * @param files project-relative files, globs or folders (default: Core and App)
6
- * @returns `file:line:col: severity: message` lines
11
+ * @returns one report per file, with `file:line:col: severity: message` lines for errors
7
12
  */
8
13
  export function syntaxCheckProject(call, project, files = ['Core', 'App']) {
9
- return call('analysis_syntax_check', { files: files.map((f) => `projects/${project.name}/${f}`) }, 125_000);
14
+ return call('analysis', { project_name: project.name, syntax: true, analysis_mode: 'none', paths: files }, 125_000);
15
+ }
16
+ /**
17
+ * Syntax-checks a synced folder: Core/ and App/ of an STM32 project, or every synced .c/.h/.cpp/.hpp file of any other folder.
18
+ * @param call server tool caller
19
+ * @param project folder, server name and whether it holds a .ioc, as resolveProjectDir returns them
20
+ * @returns one report per file, with `file:line:col: severity: message` lines for errors
21
+ */
22
+ export async function syntaxCheckFolder(call, project) {
23
+ if (project.stm32)
24
+ return syntaxCheckProject(call, project);
25
+ /** a plain folder has no Core/ or App/ layout, so check its own sources */
26
+ const files = (await listSyncFiles(project.root)).filter((f) => /\.(c|h|cpp|hpp)$/.test(f) && !f.startsWith('Drivers/'));
27
+ if (!files.length)
28
+ throw new Error(`No .c/.h/.cpp/.hpp files to check in ${project.root}`);
29
+ return syntaxCheckProject(call, project, files);
10
30
  }
11
31
  /**
12
32
  * Runs static analysis on the project's server copy (its own sources, never Drivers/).
13
33
  * @param call server tool caller
14
34
  * @param project project root and name
15
35
  * @param profile quick, full or misra
16
- * @param paths comma-separated files, globs or folders to limit the check to; empty for the whole project
36
+ * @param paths comma-separated project-relative files, globs or folders to limit the check to; empty for the whole project
17
37
  * @returns `file:line:col: severity: message [check id]` lines
18
38
  */
19
39
  export function analyzeProject(call, project, profile = 'quick', paths = '') {
20
- return call('analysis_static', { project_name: project.name, profile, paths }, 125_000);
40
+ return call('analysis', { project_name: project.name, analysis_mode: profile, paths }, 125_000);
41
+ }
42
+ /**
43
+ * Rewrites the temp project's paths in a server report to the local files they were copied from.
44
+ * @param text server report
45
+ * @param temp the temp project
46
+ * @param cwd folder the shown paths are relative to
47
+ * @returns the report with local paths
48
+ */
49
+ export function toLocalPaths(text, temp, cwd) {
50
+ const prefix = relative(cwd, temp.source).split('\\').join('/');
51
+ const local = (rel) => (prefix ? `${prefix}/${rel}` : rel);
52
+ let out = text.split(`/work/projects/${temp.name}/`).join(prefix ? `${prefix}/` : '');
53
+ for (const rel of temp.files)
54
+ out = out.split(`'${rel}'`).join(`'${local(rel)}'`);
55
+ return out;
56
+ }
57
+ /**
58
+ * Copies loose files into a temp project (see makeTempProject) and syncs it to the server.
59
+ * @param call server tool caller
60
+ * @param paths files, folders or globs, relative to cwd
61
+ * @param cwd caller's working directory
62
+ * @returns the temp project and the sync summary
63
+ */
64
+ export async function syncLooseFiles(call, paths, cwd) {
65
+ const temp = await makeTempProject(paths, cwd);
66
+ return { temp, synced: await syncProjectToServer(call, temp) };
67
+ }
68
+ /**
69
+ * Syntax-checks an already synced temp project's requested files.
70
+ * @param call server tool caller
71
+ * @param temp the temp project
72
+ * @param cwd caller's working directory, for the shown paths
73
+ * @returns the server report with local paths
74
+ */
75
+ export async function syntaxCheckTempProject(call, temp, cwd) {
76
+ return toLocalPaths(await syntaxCheckProject(call, temp, temp.files), temp, cwd);
21
77
  }
@@ -15,6 +15,7 @@ export interface ToolCommandSpec {
15
15
  server?: boolean; /** calls the Turing Code server, so its help shows the token help */
16
16
  examples: [string, string][]; /** [command line, what it does] */
17
17
  aliases?: Record<string, string>; /** flag -> short alias, e.g. { build: "b" } */
18
+ positional?: string; /** string argument taken as trailing words (`<command> [name..]`), passed to the tool comma-joined */
18
19
  }
19
20
  /**
20
21
  * Converts a tool argument name to its flag: `force_full_sync` -> `force-full-sync`.
@@ -22,6 +22,8 @@ export const flagName = (name) => name.replace(/_/g, "-");
22
22
  export function toolArgs(tool, argv) {
23
23
  return Object.fromEntries(Object.keys(tool.inputSchema.properties)
24
24
  .map(name => [name, argv[flagName(name)]])
25
+ /** a positional argument arrives as an array of words, empty when none is given */
26
+ .map(([name, value]) => [name, Array.isArray(value) ? (value.length ? value.join(",") : undefined) : value])
25
27
  .filter(([, value]) => value !== undefined));
26
28
  }
27
29
  /**
@@ -72,7 +74,8 @@ export async function runToolCommand(tool, args, mode) {
72
74
  */
73
75
  export function toolCommand(spec) {
74
76
  const { properties, required = [] } = spec.tool.inputSchema;
75
- const options = Object.fromEntries(Object.entries(properties).map(([name, p]) => [flagName(name), {
77
+ const positional = spec.positional && flagName(spec.positional);
78
+ const options = Object.fromEntries(Object.entries(properties).filter(([name]) => name !== spec.positional).map(([name, p]) => [flagName(name), {
76
79
  type: p.type === "integer" || p.type === "number" ? "number" : p.type,
77
80
  /** the CLI hides yargs' type and choices tags, so the allowed values go in the text */
78
81
  describe: [p.description, p.enum && `one of ${p.enum.filter(Boolean).join(", ")}`, required.includes(name) ? "required" : undefined]
@@ -82,10 +85,12 @@ export function toolCommand(spec) {
82
85
  }]));
83
86
  const description = spec.tool.description.replace(/\s+/g, " ").trim();
84
87
  return {
85
- command: spec.command,
88
+ command: positional ? `${spec.command} [${positional}..]` : spec.command,
86
89
  describe: description.split(/(?<!\be\.g)(?<=\.)\s(?=[A-Z])/)[0],
87
90
  builder: cli => {
88
91
  let c = cli.options(options);
92
+ if (positional)
93
+ c = c.positional(positional, { type: "string", array: true, describe: properties[spec.positional].description });
89
94
  for (const [line, what] of spec.examples)
90
95
  c = c.example(line, what);
91
96
  return c.epilogue([
@@ -0,0 +1,16 @@
1
+ import { Project } from "../tool.js";
2
+ export interface TempProject extends Project {
3
+ files: string[]; /** the requested files, posix paths relative to root */
4
+ source: string; /** the folder root mirrors: the common ancestor of every copied file */
5
+ }
6
+ /**
7
+ * Copies loose source files into <project folder>/.turingcode/temp/tmp-<hash> so they sync and check like a project
8
+ * (with no .ioc and no CMakeLists.txt): the matched .c/.h/.cpp/.hpp files plus the headers next to each, at their
9
+ * paths relative to their common ancestor. The folder is wiped first; the hash of that ancestor names it, so repeated
10
+ * runs on the same folder reuse one server project.
11
+ * @param paths files, folders or globs, relative to cwd
12
+ * @param cwd folder the paths are relative to; its project folder (see findProject) holds .turingcode/temp
13
+ * @returns the temp project, the requested files in it and the folder it mirrors
14
+ * @throws when no source file matches
15
+ */
16
+ export declare function makeTempProject(paths: string[], cwd: string): Promise<TempProject>;
@@ -0,0 +1,79 @@
1
+ import { copyFile, glob, mkdir, readdir, rm, stat } from "node:fs/promises";
2
+ import { dirname, extname, join, relative, resolve, sep } from "node:path";
3
+ import { sha256 } from "./hash_utils.js";
4
+ import { findProject } from "./project_utils.js";
5
+ /** What the server's syntax check takes; headers are also copied as include targets. */
6
+ const SOURCE_EXTS = new Set([".c", ".h", ".cpp", ".hpp"]);
7
+ const HEADER_EXTS = new Set([".h", ".hpp"]);
8
+ const GLOB_MAGIC = /[*?[\]{}]/;
9
+ /**
10
+ * Lists the files a path, folder or glob names, skipping build/ and dot folders inside a folder.
11
+ * @param cwd folder the path is relative to
12
+ * @param p file, folder or glob
13
+ * @returns absolute file paths
14
+ */
15
+ async function expandPath(cwd, p) {
16
+ if (GLOB_MAGIC.test(p)) {
17
+ const found = [];
18
+ /** the pattern stays relative: fs.glob reads backslashes of an absolute Windows path as escapes */
19
+ for await (const f of glob(p, { cwd })) {
20
+ const abs = resolve(cwd, f);
21
+ if ((await stat(abs).catch(() => undefined))?.isFile())
22
+ found.push(abs);
23
+ }
24
+ return found;
25
+ }
26
+ const abs = resolve(cwd, p);
27
+ const st = await stat(abs).catch(() => undefined);
28
+ if (st?.isFile())
29
+ return [abs];
30
+ if (!st?.isDirectory())
31
+ return [];
32
+ const ents = await readdir(abs, { recursive: true, withFileTypes: true });
33
+ return ents
34
+ .filter((e) => e.isFile())
35
+ .map((e) => join(e.parentPath, e.name))
36
+ .filter((f) => !relative(abs, f).split(sep).slice(0, -1).some((d) => d.startsWith(".") || d === "build"));
37
+ }
38
+ /**
39
+ * Returns the deepest folder holding every given file.
40
+ * @param files absolute file paths (at least one)
41
+ * @returns the common ancestor folder
42
+ */
43
+ function commonFolder(files) {
44
+ let common = dirname(files[0]);
45
+ for (const f of files)
46
+ while (relative(common, f).startsWith(".."))
47
+ common = dirname(common);
48
+ return common;
49
+ }
50
+ /**
51
+ * Copies loose source files into <project folder>/.turingcode/temp/tmp-<hash> so they sync and check like a project
52
+ * (with no .ioc and no CMakeLists.txt): the matched .c/.h/.cpp/.hpp files plus the headers next to each, at their
53
+ * paths relative to their common ancestor. The folder is wiped first; the hash of that ancestor names it, so repeated
54
+ * runs on the same folder reuse one server project.
55
+ * @param paths files, folders or globs, relative to cwd
56
+ * @param cwd folder the paths are relative to; its project folder (see findProject) holds .turingcode/temp
57
+ * @returns the temp project, the requested files in it and the folder it mirrors
58
+ * @throws when no source file matches
59
+ */
60
+ export async function makeTempProject(paths, cwd) {
61
+ const base = join((await findProject(cwd)).root, ".turingcode", "temp");
62
+ const inBase = (f) => !relative(base, f).startsWith("..");
63
+ const matched = (await Promise.all(paths.map((p) => expandPath(cwd, p)))).flat();
64
+ const requested = [...new Set(matched)].filter((f) => SOURCE_EXTS.has(extname(f).toLowerCase()) && !inBase(f)).sort();
65
+ if (!requested.length)
66
+ throw new Error(`No .c/.h/.cpp/.hpp files match ${paths.join(", ")}`);
67
+ const headers = await Promise.all([...new Set(requested.map(dirname))].map(async (dir) => (await readdir(dir, { withFileTypes: true })).filter((e) => e.isFile() && HEADER_EXTS.has(extname(e.name).toLowerCase())).map((e) => join(dir, e.name))));
68
+ const copied = [...new Set([...requested, ...headers.flat()])];
69
+ const source = commonFolder(copied);
70
+ const name = `tmp-${sha256(source).slice(0, 12)}`;
71
+ const root = join(base, name);
72
+ await rm(root, { recursive: true, force: true });
73
+ for (const f of copied) {
74
+ const to = join(root, relative(source, f));
75
+ await mkdir(dirname(to), { recursive: true });
76
+ await copyFile(f, to);
77
+ }
78
+ return { root, name, source, files: requested.map((f) => relative(source, f).split(sep).join("/")) };
79
+ }
@@ -1,3 +1,4 @@
1
+ import type { Prop } from "../tool.js";
1
2
  export interface ProjectSettings {
2
3
  included_files: string[]; /** posix paths relative to the project root; files or folders synced even when otherwise excluded */
3
4
  }
@@ -27,7 +28,7 @@ export declare function findProject(start?: string): Promise<{
27
28
  name: string;
28
29
  }>;
29
30
  /**
30
- * Finds the STM32 project inside the project folder: the folder itself or a subfolder holding a .ioc or .mxproject file.
31
+ * Finds the STM32 project for the probe and debug commands: findProject's folder or the one subfolder holding a .ioc or .mxproject file.
31
32
  * @param start folder to start from, see findProject
32
33
  * @returns the STM32 project root and name (its folder name)
33
34
  * @throws when no STM32 project or more than one is found
@@ -36,6 +37,38 @@ export declare function findStm32Project(start?: string): Promise<{
36
37
  root: string;
37
38
  name: string;
38
39
  }>;
40
+ /**
41
+ * Says whether a folder itself holds a .ioc or .mxproject file, without looking above or below it.
42
+ * @param dir folder to check
43
+ * @returns true when dir is an STM32 project folder
44
+ */
45
+ export declare function isStm32Folder(dir: string): Promise<boolean>;
46
+ /**
47
+ * Resolves the folder the project commands work on: exactly the given folder, never one above or below it.
48
+ * An STM32 project folder keeps its folder name on the server; any other folder gets a short hash of its path
49
+ * appended, so two such folders with the same name do not overwrite each other on the server.
50
+ * @param dir folder given with --dir, relative to cwd; default cwd
51
+ * @param cwd working directory
52
+ * @returns the folder, its server project name and whether it holds a .ioc or .mxproject file
53
+ * @example
54
+ * await resolveProjectDir("App", "C:/work"); // { root: "C:\\work\\App", name: "App-3f9a1c", stm32: false }
55
+ */
56
+ export declare function resolveProjectDir(dir?: string, cwd?: string): Promise<{
57
+ root: string;
58
+ name: string;
59
+ stm32: boolean;
60
+ }>;
61
+ /**
62
+ * Resolves the folder like resolveProjectDir and requires it to be an STM32 project, for the commands that need its .ioc.
63
+ * @param dir folder given with --dir, relative to cwd; default cwd
64
+ * @param cwd working directory
65
+ * @returns the STM32 project root and name (its folder name)
66
+ * @throws when the folder holds no .ioc or .mxproject file
67
+ */
68
+ export declare function requireStm32Project(dir?: string, cwd?: string): Promise<{
69
+ root: string;
70
+ name: string;
71
+ }>;
39
72
  /**
40
73
  * Finds the STM32 project in a given folder without looking above it: the folder itself or a subfolder holding a .ioc or .mxproject file.
41
74
  * @param root folder to search, e.g. the folder open in VS Code
@@ -52,3 +85,5 @@ export declare function findStm32ProjectIn(root: string): Promise<{
52
85
  * @returns the matching folders, absolute
53
86
  */
54
87
  export declare function findIocFolders(dir: string): Promise<string[]>;
88
+ /** The --dir argument of the project commands. */
89
+ export declare const DIR_PROP: Prop;
@@ -1,6 +1,7 @@
1
- import { readdir, readFile } from "node:fs/promises";
1
+ import { readdir, readFile, stat } from "node:fs/promises";
2
2
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
3
3
  import { homedir } from "node:os";
4
+ import { sha256 } from "./hash_utils.js";
4
5
  /** Middlewares/ (FreeRTOS, USB, FatFs) is CubeMX output the build needs, yet projects often git-ignore it. */
5
6
  const DEFAULT_INCLUDED = ["Middlewares"];
6
7
  /**
@@ -65,7 +66,7 @@ export async function findProject(start = process.cwd()) {
65
66
  return { root: resolve(start), name: basename(resolve(start)) };
66
67
  }
67
68
  /**
68
- * Finds the STM32 project inside the project folder: the folder itself or a subfolder holding a .ioc or .mxproject file.
69
+ * Finds the STM32 project for the probe and debug commands: findProject's folder or the one subfolder holding a .ioc or .mxproject file.
69
70
  * @param start folder to start from, see findProject
70
71
  * @returns the STM32 project root and name (its folder name)
71
72
  * @throws when no STM32 project or more than one is found
@@ -73,6 +74,46 @@ export async function findProject(start = process.cwd()) {
73
74
  export async function findStm32Project(start) {
74
75
  return findStm32ProjectIn((await findProject(start)).root);
75
76
  }
77
+ /**
78
+ * Says whether a folder itself holds a .ioc or .mxproject file, without looking above or below it.
79
+ * @param dir folder to check
80
+ * @returns true when dir is an STM32 project folder
81
+ */
82
+ export async function isStm32Folder(dir) {
83
+ return (await readdir(dir, { withFileTypes: true }).catch(() => [])).some((e) => e.isFile() && /^(\.mxproject|.+\.ioc)$/.test(e.name));
84
+ }
85
+ /**
86
+ * Resolves the folder the project commands work on: exactly the given folder, never one above or below it.
87
+ * An STM32 project folder keeps its folder name on the server; any other folder gets a short hash of its path
88
+ * appended, so two such folders with the same name do not overwrite each other on the server.
89
+ * @param dir folder given with --dir, relative to cwd; default cwd
90
+ * @param cwd working directory
91
+ * @returns the folder, its server project name and whether it holds a .ioc or .mxproject file
92
+ * @example
93
+ * await resolveProjectDir("App", "C:/work"); // { root: "C:\\work\\App", name: "App-3f9a1c", stm32: false }
94
+ */
95
+ export async function resolveProjectDir(dir, cwd = process.cwd()) {
96
+ const root = resolve(cwd, dir ?? ".");
97
+ if (!(await stat(root).catch(() => undefined))?.isDirectory())
98
+ throw new Error(`${root} is not a folder`);
99
+ const stm32 = await isStm32Folder(root);
100
+ /** Windows paths are case-insensitive, so C:\x and c:\x must give the same name */
101
+ const key = process.platform === "win32" ? root.toLowerCase() : root;
102
+ return { root, name: stm32 ? basename(root) : `${basename(root)}-${sha256(key).slice(0, 6)}`, stm32 };
103
+ }
104
+ /**
105
+ * Resolves the folder like resolveProjectDir and requires it to be an STM32 project, for the commands that need its .ioc.
106
+ * @param dir folder given with --dir, relative to cwd; default cwd
107
+ * @param cwd working directory
108
+ * @returns the STM32 project root and name (its folder name)
109
+ * @throws when the folder holds no .ioc or .mxproject file
110
+ */
111
+ export async function requireStm32Project(dir, cwd) {
112
+ const { root, name, stm32 } = await resolveProjectDir(dir, cwd);
113
+ if (!stm32)
114
+ throw new Error(`${root} is not an STM32 project: it holds no .ioc or .mxproject file. Run the command in the project folder or pass --dir <folder>.`);
115
+ return { root, name };
116
+ }
76
117
  /**
77
118
  * Finds the STM32 project in a given folder without looking above it: the folder itself or a subfolder holding a .ioc or .mxproject file.
78
119
  * @param root folder to search, e.g. the folder open in VS Code
@@ -103,3 +144,8 @@ export async function findIocFolders(dir) {
103
144
  const below = await Promise.all(ents.filter((e) => e.isDirectory() && !SKIPPED_DIRS.test(e.name)).map((e) => findIocFolders(join(dir, e.name))));
104
145
  return [...here, ...below.flat()];
105
146
  }
147
+ /** The --dir argument of the project commands. */
148
+ export const DIR_PROP = {
149
+ type: "string",
150
+ description: "Project folder, relative to the working directory (default: the working directory; folders above or below it are never used)",
151
+ };
@@ -1,8 +1,3 @@
1
1
  # Writing these skills
2
2
 
3
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,8 @@ description: use for creating, build, debug, program, flash or analyze any STM32
15
15
 
16
16
  Each command group has its own `--help` with flags and examples. Read it before using commands in that area.
17
17
 
18
- - `turingcode project --help`: sync, build, pull, regen, syntax check and static analysis.
18
+ - `turingcode project --help`: sync, build, pull, regen and static analysis.
19
+ - `turingcode syntax-check --help`: clang syntax check of the project, or of loose files, folders or globs.
19
20
  - `turingcode probe --help`: flash, reset, read memory or registers, decode faults, recover a stuck probe.
20
21
  - `turingcode debug --help`: breakpoints, stepping, stack, variables.
21
22
 
@@ -5,15 +5,17 @@ description: Coding rules for embedded C/C++ firmware on STM32. Use whenever wri
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 it.
8
+ - These rules outrank speed: when a rule conflicts with a faster solution, follow the rule and report it.
9
+ - A project's `AGENTS.md` overrides this skill wherever it is more specific (layout, shared helpers, generator markers, tests).
9
10
 
10
- A project's `AGENTS.md` overrides this skill wherever it is more specific (layout, shared helpers, generator markers, tests). Read it first.
11
+ - some names in the references (`crc32`, `flash_*`, `COM_Driver`, ...) are placeholders for the project's own functions and helpers. Use the existing ones.
12
+ - add a missing helper once to the project's shared helper location (or `Utils/` if it has none), never inline.
11
13
 
12
- ## Read the matching reference first
14
+ ## Read the matching references
13
15
 
14
- | Read | When the change touches |
16
+ | Read | When changing or making |
15
17
  |---|---|
16
- | `references/driver.md` | a driver for an external IC or bus protocol |
18
+ | `references/driver/driver.md` | a driver for an external IC or bus protocol |
17
19
  | `references/registers-and-units.md` | datasheet registers, bit fields, signedness, units, conversions |
18
20
  | `references/tasks-and-interrupts.md` | ISRs, HAL callbacks, the main loop, RTOS tasks and their wakeups, DMA, shared data |
19
21
  | `references/app-startup.md` | `main.c` hook, `extern "C"` entry, init order, tasks, µs time base |
@@ -21,12 +23,7 @@ A project's `AGENTS.md` overrides this skill wherever it is more specific (layou
21
23
  | `references/host-protocol.md` | host frames, command dispatch, register writes, replies/telemetry |
22
24
  | `references/M_StatusEnum.md` | no `M_Status.hpp`, or how to return and combine statuses |
23
25
 
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.
26
-
27
- ## Generated and vendor code
28
-
29
- ## CubeMX-generated code
26
+ ## Generated code
30
27
 
31
28
  - In generated files (`main.c`, peripheral init, ...), write only inside
32
29
  `/* USER CODE BEGIN/END */` blocks and leave the markers alone. CubeMX
@@ -35,19 +32,25 @@ A project's `AGENTS.md` overrides this skill wherever it is more specific (layou
35
32
  - HAL callbacks can only be defined once. If generated code already defines
36
33
  one (often in `main.c` or `stm32xxxx_it.c`), call your handler from its
37
34
  USER CODE block.
35
+
36
+ ## Application Code Location
37
+
38
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/`.
39
+ which needs `extern "C"` guards.
40
+ - All application code lives in `<Project>/App/`, generic code lives in the project's shared helper location (or `App/Utils/`/`App/Math/`).
41
+ - A shared library or SDK inside `App/` is not a Code Area: use it, don't restructure it, ask before changing it.
40
42
 
41
43
  ## File layout
42
44
 
43
- Each Code Area you create gets one folder in `App/`:
45
+ - put source (c,cpp) and header (h,hpp) files in the same folder with the same base name.
46
+ - Include project headers by file name only (`#include "com_spi.hpp"`), never with a folder or `../` path.
47
+
44
48
 
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:
49
+ - Below is a list of folders for each code area in `App/` folder, these are a guide for you to know where to put things that you must create, not a rule to what to create. only create files and folders that are asked in your task:
47
50
 
48
51
  | Folder | Content |
49
- |---|---|
50
- | `Platform/` | HAL↔App adapters: bus arbitration, peripheral access |
52
+ |---|---|
53
+ | `Drivers/` | IC and Protocol Drivers |
51
54
  | `Algorithms/` | conversion, calibration, filtering, estimation, fusion |
52
55
  | `Control/` | regulation that commands actuators |
53
56
  | `Comms/` | host/device protocols: framing, parsing, telemetry |
@@ -56,39 +59,44 @@ Each Code Area you create gets one folder in `App/`:
56
59
  | `System/` | startup order, main cycle/tasks, modes, faults |
57
60
  | `Update/` | firmware update |
58
61
  | `Math/` | numeric types and linear algebra |
59
- | `Utils/` | domain-free helpers used by 2+ Code Areas |
60
-
61
-
62
-
63
- A shared library or SDK inside `App/` is not a Code Area: use it, don't restructure it, ask before changing it.
64
-
65
- Each Code Area is one module: source + header with the same base name.
66
-
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.
62
+ | `Utils/` | domain-free helpers |
72
63
 
73
64
  ## House style
74
65
 
75
- Match the existing style; don't "modernize" it.
66
+ - **Methods**: lowerCamelCase
67
+ - **Members**:
68
+ - Public members: lowerCamelCase
69
+ - Private members: lowerCamelCase with trailing _
70
+ - Internal Helpers: lowerCamelCase with trailing __
71
+ access members via `this->`.
76
72
 
77
73
  - **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.
74
+
75
+ - **Errors**: prefer `M_Status` (`M_StatusEnum::M_OK`, ...), never `bool` or raw ints; accumulate with `status |= ...`.
76
+
82
77
  - **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.
78
+
79
+ - **Comments**: use structured documentation comments
80
+ - use `/* ---- Title ---- */` banners
81
+ - `////` marks disabled code.
82
+ - for functions write proper comments with `@brief`, `@param`, `@return`, `@throws` and `@note` tags, e.g.:
83
+ ```cpp
84
+ /**
85
+ * @brief …
86
+ *
87
+ * …
88
+ *
89
+ * @tparam …
90
+ * @param A …
91
+ * @param B …
92
+ * @return …
93
+ * @throws …
94
+ * @note …
95
+ */
96
+ ```
84
97
 
85
98
  ## Safety rules
86
99
 
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.
100
+ 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, write in comments why.
88
101
  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
102
  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.
91
-
92
- ## Before you finish
93
-
94
- Re-read the diff against these rules and the references you loaded.
@@ -1,11 +1,7 @@
1
1
  # M_Status
2
2
 
3
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
-
4
+
9
5
  ## Usage
10
6
 
11
7
  ```cpp
@@ -20,14 +16,39 @@ return status; // the worst result win
20
16
  - Add `Utils/M_Status.hpp`. Include the family HAL header (`stm32g4xx_hal.h`, `stm32f3xx_hal.h`, ...) for `HAL_StatusTypeDef`.
21
17
 
22
18
  ```cpp
23
- enum M_StatusEnum { M_OK = 0, M_ERROR, M_BUSY, M_TIMEOUT, M_OUT_OF_RANGE, M_DISABLED, M_NOT_SUPPORTED };
19
+ #pragma once
20
+ /**
21
+ * Status type shared by all drivers
22
+ * Values are ordered best to worst so `|=` keeps the worst result.
23
+ */
24
+ enum M_StatusEnum {
25
+ M_OK = 0,
26
+ M_BUSY,
27
+ M_TIMEOUT,
28
+ M_OUT_OF_RANGE,
29
+ M_DISABLED,
30
+ M_NOT_SUPPORTED,
31
+ M_NOT_FOUND,
32
+ M_MISMATCH,
33
+ M_ERROR
34
+ };
24
35
 
25
36
  class M_Status {
26
37
  public:
27
38
  M_StatusEnum value;
28
39
  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; }
40
+ M_Status(HAL_StatusTypeDef h) {
41
+ switch (h) {
42
+ case HAL_OK: this->value = M_OK; break;
43
+ case HAL_BUSY: this->value = M_BUSY; break;
44
+ case HAL_TIMEOUT: this->value = M_TIMEOUT; break;
45
+ default: this->value = M_ERROR; break;
46
+ }
47
+ }
48
+ M_Status& operator|=(M_Status o) {
49
+ if (o.value > this->value) this->value = o.value;
50
+ return *this;
51
+ }
31
52
  operator M_StatusEnum() const { return this->value; }
32
53
  };
33
- ```
54
+ ```