@turingcode/cli 0.3.14 → 0.3.15

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/contract/command.js +64 -64
  5. package/dist/features/probe/program_project.js +3 -3
  6. package/dist/features/project/analysis_static.js +7 -6
  7. package/dist/features/project/command.d.ts +3 -1
  8. package/dist/features/project/command.js +15 -11
  9. package/dist/features/project/project_regenerate.js +4 -3
  10. package/dist/features/project/project_sync_from_server.js +4 -3
  11. package/dist/features/project/project_sync_to_server.js +36 -11
  12. package/dist/features/project/stm32_cubetools_download_drivers.js +5 -4
  13. package/dist/features/status/get_status.js +6 -3
  14. package/dist/features/syntax-check/command.d.ts +2 -0
  15. package/dist/features/syntax-check/command.js +8 -0
  16. package/dist/features/syntax-check/syntax_check.d.ts +3 -0
  17. package/dist/features/syntax-check/syntax_check.js +27 -0
  18. package/dist/features/tool/command.d.ts +2 -0
  19. package/dist/features/tool/command.js +58 -7
  20. package/dist/lib.d.ts +1 -1
  21. package/dist/lib.js +1 -1
  22. package/dist/stm32/analysis.d.ts +40 -4
  23. package/dist/stm32/analysis.js +61 -5
  24. package/dist/stm32/toolCommand.d.ts +1 -0
  25. package/dist/stm32/toolCommand.js +7 -2
  26. package/dist/stm32/utils/makeTempProject.d.ts +16 -0
  27. package/dist/stm32/utils/makeTempProject.js +79 -0
  28. package/dist/stm32/utils/project_utils.d.ts +36 -1
  29. package/dist/stm32/utils/project_utils.js +48 -2
  30. package/mods/claude/turingcode-skills/skills/AGENTS.md +0 -5
  31. package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +48 -47
  32. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/SKILL.md +50 -42
  33. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/M_StatusEnum.md +24 -6
  34. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/code/BusMutexRegistry.hpp +138 -0
  35. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/code/Util_MutexManager.hpp +212 -0
  36. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver.md +72 -0
  37. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_ic.md +125 -0
  38. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_protocol.md +116 -0
  39. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_rtos.md +130 -0
  40. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_test.md +14 -0
  41. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/storage.md +57 -57
  42. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/tasks-and-interrupts.md +70 -70
  43. package/package.json +2 -2
  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
@@ -0,0 +1,27 @@
1
+ import { syncLooseFiles, syntaxCheckFolder, syntaxCheckTempProject } from '../../stm32/analysis.js';
2
+ import { callServer } from '../../stm32/context.js';
3
+ import { _defineTool } from '../../stm32/tool.js';
4
+ import { DIR_PROP, resolveProjectDir } from '../../stm32/utils/project_utils.js';
5
+ /** Syntax-checks the synced project's Core/ and App/, or uploads loose files to a temp project and checks them. */
6
+ export default _defineTool({
7
+ name: 'syntax_check',
8
+ description: 'Check .c/.h/.cpp/.hpp files for syntax errors with clang on the TuringCode server. \
9
+ Without paths it checks the synced project, the working directory or --dir: Core/ and App/ of an STM32 project, else all its source files (run `turingcode project sync` first to include local changes). \
10
+ With files, folders or globs it copies them, with the headers next to each, into .turingcode/temp/ of the project folder, \
11
+ syncs that copy as a temp project with no .ioc or CMakeLists (so quoted includes only find headers next to the file) and checks them. \
12
+ Returns `file:line:col: severity: message` lines.',
13
+ properties: {
14
+ dir: DIR_PROP,
15
+ paths: {
16
+ type: 'string',
17
+ description: 'Files, folders or globs relative to the working directory, e.g. src/*.c (default: the synced project)',
18
+ },
19
+ },
20
+ run: async (args, ctx) => {
21
+ const paths = (args.paths ?? '').split(',').map((p) => p.trim()).filter(Boolean);
22
+ if (!paths.length)
23
+ return syntaxCheckFolder(callServer, await resolveProjectDir(args.dir, ctx.cwd));
24
+ const { temp } = await syncLooseFiles(callServer, paths, ctx.cwd);
25
+ return syntaxCheckTempProject(callServer, temp, ctx.cwd);
26
+ },
27
+ });
@@ -1,5 +1,7 @@
1
1
  import { CommandModule } from 'yargs';
2
2
  import { ToolInfo } from '../../core/mcp.js';
3
+ /** A tool result larger than this many bytes is saved to a file instead of printed. */
4
+ export declare const SAVE_ABOVE_BYTES = 4096;
3
5
  /**
4
6
  * Formats tools as one line each: name, then the first line of its description.
5
7
  *
@@ -1,6 +1,11 @@
1
+ import { mkdir, readdir, writeFile } from 'node:fs/promises';
2
+ import { join, relative } from 'node:path';
1
3
  import { readJsonArg } from '../../core/files.js';
2
- import { getGatewayConfig, listTools, runServerTool, TOKEN_HELP, } from '../../core/mcp.js';
4
+ import { callTool, getGatewayConfig, listTools, TOKEN_HELP, } from '../../core/mcp.js';
5
+ import { findProject } from '../../stm32/utils/project_utils.js';
3
6
  import { JSON_FLAG } from '../contract/command.js';
7
+ /** A tool result larger than this many bytes is saved to a file instead of printed. */
8
+ export const SAVE_ABOVE_BYTES = 4096;
4
9
  /**
5
10
  * Names a JSON schema's type compactly: `string`, `integer | null`, `list of string`, `"a" | "b"`, ...
6
11
  *
@@ -87,6 +92,47 @@ export function pickTools(tools, names) {
87
92
  }
88
93
  return names.map((name) => tools.find((t) => t.name === name));
89
94
  }
95
+ /**
96
+ * Saves a tool result as the next free `<project>/.turingcode/results/<tool>-<n>.txt`.
97
+ *
98
+ * @param {string} tool - Tool name, used in the file name.
99
+ * @param {string} text - The tool result.
100
+ * @returns {Promise<string>} The saved file's path.
101
+ */
102
+ async function saveToolResult(tool, text) {
103
+ const dir = join((await findProject()).root, '.turingcode', 'results');
104
+ await mkdir(dir, { recursive: true });
105
+ const pattern = new RegExp(`^${tool.replace(/[^\w-]/g, '_')}-(\\d+)\\.txt$`);
106
+ const taken = (await readdir(dir)).map((name) => Number(name.match(pattern)?.[1] ?? 0));
107
+ const file = join(dir, `${tool.replace(/[^\w-]/g, '_')}-${Math.max(0, ...taken) + 1}.txt`);
108
+ await writeFile(file, text);
109
+ return file;
110
+ }
111
+ /**
112
+ * Calls one server tool and prints its result; unless `full`, one over SAVE_ABOVE_BYTES is saved to a file
113
+ * and only its size and path are printed. A tool error goes to stderr with exit code 1.
114
+ *
115
+ * @param {string} name - Tool name.
116
+ * @param {Record<string, unknown>} args - Tool arguments.
117
+ * @param {boolean} full - Print the result whatever its size.
118
+ * @returns {Promise<void>} Resolves once the result is printed.
119
+ */
120
+ async function runToolCall(name, args, full) {
121
+ const { token, url } = getGatewayConfig();
122
+ const result = await callTool(name, args, token, url);
123
+ if (result.isError) {
124
+ process.stderr.write(result.text + '\n');
125
+ process.exitCode = 1;
126
+ return;
127
+ }
128
+ const bytes = Buffer.byteLength(result.text);
129
+ if (full || bytes <= SAVE_ABOVE_BYTES) {
130
+ process.stdout.write(result.text + '\n');
131
+ return;
132
+ }
133
+ const file = relative(process.cwd(), await saveToolResult(name, result.text)).replace(/\\/g, '/');
134
+ process.stdout.write(`Result was too long (${(bytes / 1024).toFixed(1)} KB), saved to ${file}. Don't read all of it, grep what you need.\n`);
135
+ }
90
136
  const list = {
91
137
  command: 'list',
92
138
  describe: 'List the server tools your gateway token can call, one line each',
@@ -130,7 +176,7 @@ const describe = {
130
176
  };
131
177
  const call = {
132
178
  command: 'call <name>',
133
- describe: 'Call a server tool and print its text result (redirect it to save it in a file)',
179
+ describe: 'Call a server tool and print its text result (a large one is saved to a file)',
134
180
  builder: (cli) => cli
135
181
  .positional('name', { type: 'string', describe: 'Tool name, from `tool list`' })
136
182
  .options({
@@ -139,6 +185,10 @@ const call = {
139
185
  coerce: readJsonArg,
140
186
  describe: 'Tool arguments: inline JSON object or .json path',
141
187
  },
188
+ full: {
189
+ type: 'boolean',
190
+ describe: 'Print the whole result, even one over 4 KB',
191
+ },
142
192
  })
143
193
  .check((argv) => {
144
194
  const value = argv.args;
@@ -149,18 +199,19 @@ const call = {
149
199
  return true;
150
200
  })
151
201
  .example(`$0 tool call <name> --args '{"<arg>":"<value>"}'`, 'inline arguments, result printed')
152
- .example('$0 tool call <name> --args args.json > result.md', 'arguments from a file, result saved to a file')
202
+ .example('$0 tool call <name> --args args.json', 'arguments from a file')
153
203
  .epilogue([
154
204
  'Calls one tool of the Turing Code server. <name> comes from `tool list`, its arguments from',
155
205
  '`tool describe <name>`.',
156
206
  '--args is a JSON object, inline or a path to a .json file;',
157
207
  'leave it out for a tool without arguments.',
158
208
  'Windows PowerShell 5.1 and cmd strip the quotes of inline JSON: use a .json file there.',
159
- "The tool's text result goes to stdout: redirect it (`> file`) to save a large result without",
160
- 'reading it. A tool error is printed to stderr.',
209
+ "The tool's text result goes to stdout. A result over 4 KB is saved to",
210
+ '.turingcode/results/<tool>-<n>.txt of the project folder instead, and only its size and path are',
211
+ 'printed; --full prints it anyway. A tool error is printed to stderr.',
161
212
  TOKEN_HELP,
162
213
  ].join('\n')),
163
- handler: (args) => runServerTool(args.name, (args.args ?? {})),
214
+ handler: (args) => runToolCall(args.name, (args.args ?? {}), Boolean(args.full)),
164
215
  };
165
216
  const command = {
166
217
  command: 'tool',
@@ -172,7 +223,7 @@ const command = {
172
223
  .demandCommand(1, 'tool needs a subcommand: list, describe or call')
173
224
  .epilogue([
174
225
  'Typical use: `tool list` to find a tool, `tool describe <name>` for its arguments, then',
175
- '`tool call <name> --args ... > file` to save its result.',
226
+ '`tool call <name> --args ...` (a result over 4 KB is saved to .turingcode/results/).',
176
227
  TOKEN_HELP,
177
228
  ].join('\n')),
178
229
  handler: () => { },
package/dist/lib.d.ts CHANGED
@@ -11,5 +11,5 @@ export { buildProject, BUILD_PRESETS } from "./stm32/build.js";
11
11
  export { analyzeProject, syntaxCheckProject } from "./stm32/analysis.js";
12
12
  export type { BuildResult } from "./stm32/build.js";
13
13
  export { downloadAndUnzip, zipLink } from "./stm32/utils/downloadzip_utils.js";
14
- export { findStm32Project, findStm32ProjectIn } from "./stm32/utils/project_utils.js";
14
+ export { findStm32Project, findStm32ProjectIn, requireStm32Project, resolveProjectDir } from "./stm32/utils/project_utils.js";
15
15
  export type { Project } from "./stm32/tool.js";
package/dist/lib.js CHANGED
@@ -8,4 +8,4 @@ export { recordBaseline, regenerateProject } from "./stm32/regen.js";
8
8
  export { buildProject, BUILD_PRESETS } from "./stm32/build.js";
9
9
  export { analyzeProject, syntaxCheckProject } from "./stm32/analysis.js";
10
10
  export { downloadAndUnzip, zipLink } from "./stm32/utils/downloadzip_utils.js";
11
- export { findStm32Project, findStm32ProjectIn } from "./stm32/utils/project_utils.js";
11
+ export { findStm32Project, findStm32ProjectIn, requireStm32Project, resolveProjectDir } from "./stm32/utils/project_utils.js";
@@ -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.