@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,15 +1,27 @@
1
- import yargs from "yargs/yargs";
2
- import contract from "../features/contract/command.js";
3
- import table from "../features/table/command.js";
4
- import tool from "../features/tool/command.js";
5
- import project from "../features/project/command.js";
6
- import probe from "../features/probe/command.js";
7
- import debug from "../features/debug/command.js";
8
- import status from "../features/status/command.js";
9
- import installSkills from "../features/install-skills/command.js";
10
- import installMods from "../features/install-mods/command.js";
11
- const commands = [contract, table, tool, project, probe, debug, status, installSkills, installMods];
12
- const names = commands.map(c => String(c.command).split(" ")[0]);
1
+ import yargs from 'yargs/yargs';
2
+ import contract from '../features/contract/command.js';
3
+ import table from '../features/table/command.js';
4
+ import tool from '../features/tool/command.js';
5
+ import project from '../features/project/command.js';
6
+ import probe from '../features/probe/command.js';
7
+ import debug from '../features/debug/command.js';
8
+ import status from '../features/status/command.js';
9
+ import syntaxCheck from '../features/syntax-check/command.js';
10
+ import installSkills from '../features/install-skills/command.js';
11
+ import installMods from '../features/install-mods/command.js';
12
+ const commands = [
13
+ contract,
14
+ table,
15
+ tool,
16
+ project,
17
+ syntaxCheck,
18
+ probe,
19
+ debug,
20
+ status,
21
+ installSkills,
22
+ installMods,
23
+ ];
24
+ const names = commands.map((c) => String(c.command).split(' ')[0]);
13
25
  /** Exit code of every argument error, as each command's help documents. */
14
26
  const BAD_ARGUMENTS = 2;
15
27
  /**
@@ -22,32 +34,35 @@ const BAD_ARGUMENTS = 2;
22
34
  * `exitCode` 2, so they differ from a failed check or request (1).
23
35
  */
24
36
  export function createCli(args) {
25
- const first = args.find(a => !a.startsWith("-"));
37
+ const first = args.find((a) => !a.startsWith('-'));
26
38
  if (first !== undefined && !names.includes(first)) {
27
- throw Object.assign(new Error(`Unknown command: ${first}`), { exitCode: BAD_ARGUMENTS });
39
+ throw Object.assign(new Error(`Unknown command: ${first}`), {
40
+ exitCode: BAD_ARGUMENTS,
41
+ });
28
42
  }
29
43
  const cli = yargs(args)
30
- .scriptName("turingcode")
44
+ .scriptName('turingcode')
31
45
  .usage("Usage: $0 <command> [options]; $0 <command> --help for each command's usage")
32
46
  .epilogue([
33
- "Turing Code toolkit for AI agents.",
34
- "- Server tools: `tool list` to find a tool, `tool describe <name>` for its arguments,",
35
- " `tool call <name> --args ... > file` to run it and save the result (needs TURINGCODE_TOKEN: $0 tool --help).",
36
- "- Tables: check Markdown or CSV tables against a contract (a JSON file of tables, columns and",
37
- " MongoDB-style checks): `contract describe` shows the tables to write; `table check` until PASS.",
38
- " Contract format: $0 contract --help.",
39
- "- STM32 projects: `project sync -b` to build on the server, `probe program` to flash the board,",
40
- " `probe read` and `probe peripheral` to inspect it, `debug start` ... `debug stop` for a live debug",
41
- " session; `status` shows the project and the installed debug tools.",
42
- "- Agent skills: `install-skills` copies them into ~/.agents/skills (Codex, OpenCode);",
43
- " `install-mods` installs them into Claude Code as the turingcode-skills plugin.",
44
- ].join("\n"))
47
+ 'Turing Code toolkit for AI agents.',
48
+ '- Server tools: `tool list` to find a tool, `tool describe <name>` for its arguments,',
49
+ ' `tool call <name> --args ...` to run it.',
50
+ '- Tables: check Markdown or CSV tables against a contract (a JSON file of tables, columns and',
51
+ ' MongoDB-style checks): `contract describe` shows the tables to write; `table check` until PASS.',
52
+ ' Contract format: $0 contract --help.',
53
+ '- STM32 projects: `project sync -b` to build on the server, `syntax-check [paths..]` for a clang syntax',
54
+ ' check of the project or of loose files, `probe program` to flash the board,',
55
+ ' `probe read` and `probe peripheral` to inspect it, `debug start` ... `debug stop` for a live debug',
56
+ ' session; `status` shows the project and the installed debug tools.',
57
+ '- Agent skills: `install-skills` copies them into ~/.agents/skills (Codex, OpenCode);',
58
+ ' `install-mods` installs them into Claude Code as the turingcode-skills plugin.',
59
+ ].join('\n'))
45
60
  .command(commands)
46
- .demandCommand(1, `Name a command: ${names.slice(0, -1).join(", ")} or ${names.at(-1)}`)
61
+ .demandCommand(1, `Name a command: ${names.slice(0, -1).join(', ')} or ${names.at(-1)}`)
47
62
  .strict()
48
63
  .help()
49
- .hide("help")
50
- .hide("version")
64
+ .hide('help')
65
+ .hide('version')
51
66
  .wrap(null)
52
67
  .exitProcess(false)
53
68
  /**
@@ -60,5 +75,5 @@ export function createCli(args) {
60
75
  throw Object.assign(error ?? new Error(message), { exitCode: BAD_ARGUMENTS });
61
76
  });
62
77
  /** Type tags such as [string] add tokens without information; the typings lack this yargs 17.7 method. */
63
- return cli.usageConfiguration({ "hide-types": true });
78
+ return cli.usageConfiguration({ 'hide-types': true });
64
79
  }
@@ -80,13 +80,3 @@ export declare function getGatewayConfig(): {
80
80
  token: string;
81
81
  url: string;
82
82
  };
83
- /**
84
- * Runs a server command: calls the tool with the gateway token from
85
- * TURINGCODE_TOKEN and prints its text; a tool error sets exit code 1.
86
- *
87
- * @param {string} name - Tool name.
88
- * @param {Record<string, unknown>} args - Tool arguments; undefined entries are dropped.
89
- * @returns {Promise<void>} Resolves once the reply is printed.
90
- * @throws {Error} When TURINGCODE_TOKEN is not set, or the gateway call fails.
91
- */
92
- export declare function runServerTool(name: string, args: Record<string, unknown>): Promise<void>;
package/dist/core/mcp.js CHANGED
@@ -158,21 +158,3 @@ export function getGatewayConfig() {
158
158
  }
159
159
  return { token, url: process.env.TURINGCODE_URL || DEFAULT_URL };
160
160
  }
161
- /**
162
- * Runs a server command: calls the tool with the gateway token from
163
- * TURINGCODE_TOKEN and prints its text; a tool error sets exit code 1.
164
- *
165
- * @param {string} name - Tool name.
166
- * @param {Record<string, unknown>} args - Tool arguments; undefined entries are dropped.
167
- * @returns {Promise<void>} Resolves once the reply is printed.
168
- * @throws {Error} When TURINGCODE_TOKEN is not set, or the gateway call fails.
169
- */
170
- export async function runServerTool(name, args) {
171
- const { token, url } = getGatewayConfig();
172
- const given = Object.fromEntries(Object.entries(args).filter(([, v]) => v !== undefined));
173
- const result = await callTool(name, given, token, url);
174
- (result.isError ? process.stderr : process.stdout).write(result.text + "\n");
175
- if (result.isError) {
176
- process.exitCode = 1;
177
- }
178
- }
@@ -1,19 +1,20 @@
1
1
  import { analyzeProject } from '../../stm32/analysis.js';
2
2
  import { callServer } from '../../stm32/context.js';
3
3
  import { _defineTool } from '../../stm32/tool.js';
4
- import { findStm32Project } from '../../stm32/utils/project_utils.js';
4
+ import { DIR_PROP, requireStm32Project } from '../../stm32/utils/project_utils.js';
5
5
  /** Static analysis of the server copy of the project's own sources (never Drivers/). */
6
6
  export default _defineTool({
7
7
  name: 'analysis_static',
8
8
  description: 'Static analysis of your stm32 project on the TuringCode server (its own sources, never Drivers/HAL/CMSIS; \
9
9
  run `turingcode project sync` first to include local changes). Profiles: quick (cppcheck), full (cppcheck + clang-tidy) \
10
- or misra (cppcheck MISRA C:2012). Returns `file:line:col: severity: message [check id]` lines.',
10
+ or misra (cppcheck MISRA C:2012). Returns `file:line:col: severity: message [check id]` lines. The project is the working directory or --dir; it must hold the .ioc.',
11
11
  properties: {
12
+ dir: DIR_PROP,
12
13
  profile: { type: 'string', enum: ['quick', 'full', 'misra'], description: 'default: quick' },
13
14
  paths: { type: 'string', description: 'Comma-separated files, globs or folders to limit the check to (default: whole project)' },
14
15
  },
15
- run: async (args) => {
16
- const project = await findStm32Project();
16
+ run: async (args, ctx) => {
17
+ const project = await requireStm32Project(args.dir, ctx.cwd);
17
18
  return analyzeProject(callServer, project, args.profile, args.paths);
18
19
  },
19
20
  });
@@ -1,5 +1,7 @@
1
1
  import { CommandModule } from "yargs";
2
- /** How the commands find the project; shown in the help of every STM32 command group. */
2
+ /** How the probe and debug commands find the project; shown in their help. */
3
3
  export declare const PROJECT_HELP: string;
4
+ /** How the project and syntax-check commands pick their folder. */
5
+ export declare const PROJECT_DIR_HELP: string;
4
6
  declare const command: CommandModule;
5
7
  export default command;
@@ -1,31 +1,35 @@
1
1
  import { TOKEN_HELP } from "../../core/mcp.js";
2
2
  import { toolCommand } from "../../stm32/toolCommand.js";
3
3
  import analysisStatic from "./analysis_static.js";
4
- import analysisSyntaxCheck from "./analysis_syntax_check.js";
5
4
  import projectDownloadTemplate from "./project_download_template.js";
6
5
  import projectRegenerate from "./project_regenerate.js";
7
6
  import projectSyncFromServer from "./project_sync_from_server.js";
8
7
  import projectSyncToServer from "./project_sync_to_server.js";
9
8
  import downloadDrivers from "./stm32_cubetools_download_drivers.js";
10
- /** How the commands find the project; shown in the help of every STM32 command group. */
9
+ /** How the probe and debug commands find the project; shown in their help. */
11
10
  export const PROJECT_HELP = [
12
11
  "Project: the nearest folder at or above the working directory that holds .turingcode/ (made by the",
13
12
  "VS Code extension and the debug daemon; not the home folder's) or a .ioc or .mxproject file, else the",
14
13
  "working directory. The STM32 project is that folder or the one subfolder holding a .ioc or .mxproject file.",
15
14
  ].join("\n");
15
+ /** How the project and syntax-check commands pick their folder. */
16
+ export const PROJECT_DIR_HELP = [
17
+ "Project folder: the working directory, or --dir; folders above or below it are never used.",
18
+ "A folder holding a .ioc or .mxproject file is an STM32 project and keeps its name on the server; any other",
19
+ "folder syncs as <name>-<hash of its path>. regen, analyze, drivers and sync -b/-a need the .ioc.",
20
+ ].join("\n");
16
21
  const subcommands = [
17
- toolCommand({ command: "sync", tool: projectSyncToServer, mode: "local", server: true, aliases: { build: "b", analyse: "a" }, examples: [
22
+ toolCommand({ command: "sync", tool: projectSyncToServer, mode: "local", server: true, aliases: { build: "b", analyse: "a", syntax: "s" }, positional: "paths", examples: [
18
23
  ["$0 project sync", "upload the files the server lacks or has a different version of"],
19
24
  ["$0 project sync -b", "sync, then build with the Debug preset"],
20
25
  ["$0 project sync -b Release -a misra", "sync, build Release, then MISRA static analysis"],
26
+ ["$0 project sync -s -b", "sync, syntax-check Core/ and App/, then build"],
27
+ ["$0 project sync -s lib/*.c", "sync only lib/*.c (and the headers next to them) as a temp project and syntax-check them"],
28
+ ["$0 project sync --dir App -s", "sync the App/ folder alone (no .ioc, so it syncs as App-<hash>) and syntax-check it"],
21
29
  ] }),
22
30
  toolCommand({ command: "pull", tool: projectSyncFromServer, mode: "local", server: true, examples: [
23
31
  ["$0 project pull", "download the files that changed on the server, overwriting local copies"],
24
32
  ] }),
25
- toolCommand({ command: "check", tool: analysisSyntaxCheck, mode: "local", server: true, examples: [
26
- ["$0 project check", "syntax-check Core/ and App/ of the synced project"],
27
- ["$0 project check --files Core/Src/main.c", "one file"],
28
- ] }),
29
33
  toolCommand({ command: "analyze", tool: analysisStatic, mode: "local", server: true, examples: [
30
34
  ["$0 project analyze", "quick static analysis (cppcheck) of the synced project"],
31
35
  ["$0 project analyze --profile misra --paths Core/Src", "MISRA C:2012 check of one folder"],
@@ -45,13 +49,13 @@ const command = {
45
49
  command: "project",
46
50
  describe: "Sync, build and edit the local STM32 project with the Turing Code server",
47
51
  builder: cli => subcommands.reduce((c, s) => c.command(s), cli)
48
- .demandCommand(1, "project needs a subcommand: sync, pull, check, analyze, regen, template or drivers")
52
+ .demandCommand(1, "project needs a subcommand: sync, pull, analyze, regen, template or drivers")
49
53
  .epilogue([
50
- "Typical use: edit files, `project sync -b` (add `-a` to also analyse), then `probe program`.",
51
- "`project check` (syntax) and `project analyze` (cppcheck, clang-tidy, MISRA) check the synced code.",
54
+ "Typical use: edit files, `project sync -b` (add `-s` to syntax-check first, `-a` to also analyse), then `probe program`.",
55
+ "`turingcode syntax-check` (syntax) and `project analyze` (cppcheck, clang-tidy, MISRA) check the synced code.",
52
56
  "Other server tools (pins, clocks, .ioc edits) go through `tool call`; after one that",
53
57
  "changes the server copy, `project pull` brings the changes back, and `project regen` regenerates the code.",
54
- PROJECT_HELP,
58
+ PROJECT_DIR_HELP,
55
59
  TOKEN_HELP,
56
60
  ].join("\n")),
57
61
  handler: () => { },
@@ -1,19 +1,20 @@
1
1
  import { callServer } from '../../stm32/context.js';
2
2
  import { regenerateProject } from '../../stm32/regen.js';
3
3
  import { _defineTool } from '../../stm32/tool.js';
4
- import { findStm32Project } from '../../stm32/utils/project_utils.js';
4
+ import { DIR_PROP, requireStm32Project } from '../../stm32/utils/project_utils.js';
5
5
  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
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.',
11
+ 'Local changes are synced to the server first. The project is the working directory or --dir; it must hold the .ioc.',
12
12
  properties: {
13
+ dir: DIR_PROP,
13
14
  force: {
14
15
  type: 'boolean',
15
16
  description: 'Regenerate and pull even when code outside USER CODE sections would be removed',
16
17
  },
17
18
  },
18
- run: async (args) => regenerateProject(callServer, await findStm32Project(), !!args.force),
19
+ run: async (args, ctx) => regenerateProject(callServer, await requireStm32Project(args.dir, ctx.cwd), !!args.force),
19
20
  });
@@ -1,13 +1,14 @@
1
1
  import { callServer } from "../../stm32/context.js";
2
2
  import { syncProjectFromServer } from "../../stm32/sync.js";
3
3
  import { _defineTool } from "../../stm32/tool.js";
4
- import { findStm32Project } from "../../stm32/utils/project_utils.js";
4
+ import { DIR_PROP, resolveProjectDir } from "../../stm32/utils/project_utils.js";
5
5
  export default _defineTool({
6
6
  name: "project_sync_from_server",
7
7
  description: "Download the files of your stm32 project that changed on the TuringCode server (e.g. after project_regenerate " +
8
8
  "or stm32_cubetools_* edits) and overwrite the local copies; local files absent on the server are kept. " +
9
9
  "build/ and git-ignored files (except Drivers/) are skipped. Local edits not yet synced to the server are lost, " +
10
10
  "so run `turingcode project sync` first if you have any. " +
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.",
12
- run: async () => syncProjectFromServer(callServer, await findStm32Project()),
11
+ "The project is the working directory or --dir, never a folder above or below it.",
12
+ properties: { dir: DIR_PROP },
13
+ run: async (args, ctx) => syncProjectFromServer(callServer, await resolveProjectDir(args.dir, ctx.cwd)),
13
14
  });
@@ -1,17 +1,25 @@
1
1
  import analysisStatic from './analysis_static.js';
2
+ import { syncLooseFiles, syntaxCheckFolder, syntaxCheckTempProject } from '../../stm32/analysis.js';
2
3
  import { callServer, runBuild } from '../../stm32/context.js';
3
4
  import { checkBeforeRegen } from '../../stm32/regen.js';
4
5
  import { syncProjectToServer } from '../../stm32/sync.js';
5
6
  import { _defineTool } from '../../stm32/tool.js';
6
- import { findStm32Project } from '../../stm32/utils/project_utils.js';
7
+ import { DIR_PROP, resolveProjectDir } from '../../stm32/utils/project_utils.js';
7
8
  export default _defineTool({
8
9
  name: 'project_sync_to_server',
9
- description: 'Sync your local stm32 project files (except build/ and git-ignored files; Drivers/ and Middlewares/ are always sent) ' +
10
+ description: "Sync a local folder's files (except build/ and git-ignored files; Drivers/ and Middlewares/ are always sent) " +
10
11
  'to the TuringCode server; only files the server lacks or has a different version of are uploaded. \
11
12
  To restore deleted Drivers/ files use `turingcode project drivers`. \
12
13
  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. \
13
- 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.',
14
+ The folder is the working directory or --dir, never one above or below it. A folder holding a .ioc or .mxproject file keeps its name on the server; \
15
+ any other folder is synced as <name>-<hash of its path>, and only --syntax works with it. \
16
+ With paths, only those .c/.h/.cpp/.hpp files (and the headers next to each) are copied into .turingcode/temp/ of the project folder and synced as a temp project with no .ioc or CMakeLists, for `--syntax`.',
14
17
  properties: {
18
+ dir: DIR_PROP,
19
+ paths: {
20
+ type: 'string',
21
+ description: 'Files, folders or globs relative to the working directory to sync as a temp project instead of the folder; only --syntax works with them',
22
+ },
15
23
  force_full_sync: {
16
24
  type: 'boolean',
17
25
  description: 'Upload every file, skipping the check for which files the server already has (server files deleted locally are kept)',
@@ -21,6 +29,10 @@ export default _defineTool({
21
29
  enum: ['', 'Debug', 'Release', 'RelWithDebInfo', 'MinSizeRel'],
22
30
  description: 'After a successful sync, build with this preset; empty = Debug',
23
31
  },
32
+ syntax: {
33
+ type: 'boolean',
34
+ description: 'After a successful sync, syntax-check like `turingcode syntax-check` (before the build)',
35
+ },
24
36
  analyse: {
25
37
  type: 'string',
26
38
  enum: ['', 'quick', 'full', 'misra'],
@@ -32,21 +44,34 @@ export default _defineTool({
32
44
  },
33
45
  },
34
46
  run: async (args, ctx) => {
35
- const project = await findStm32Project();
36
- const { findings, broken } = await checkBeforeRegen(project.root);
47
+ const paths = (args.paths ?? '').split(',').map((p) => p.trim()).filter(Boolean);
48
+ if (paths.length) {
49
+ /** the temp project has no CMakeLists.txt, so a build or static analysis of it always fails */
50
+ if (args.build !== undefined || args.analyse !== undefined)
51
+ throw new Error('--build and --analyse need the stm32 project: sync paths only with --syntax');
52
+ const { temp, synced } = await syncLooseFiles(callServer, paths, ctx.cwd);
53
+ return args.syntax ? `# Sync\n${synced}\n# Syntax check\n${await syntaxCheckTempProject(callServer, temp, ctx.cwd)}` : synced;
54
+ }
55
+ const project = await resolveProjectDir(args.dir, ctx.cwd);
56
+ if (!project.stm32 && (args.build !== undefined || args.analyse !== undefined))
57
+ throw new Error(`--build and --analyse need an STM32 project, and ${project.root} holds no .ioc or .mxproject file`);
58
+ /** only CubeMX projects have USER CODE sections that regen could remove */
59
+ const { findings, broken } = project.stm32 ? await checkBeforeRegen(project.root) : { findings: [], broken: [] };
37
60
  if (broken.length)
38
61
  throw new Error(`Sync stopped, nothing uploaded. Fix the USER CODE markers first:\n\n${broken.join('\n\n')}`);
39
- const synced = await syncProjectToServer(callServer, project, !!args.force_full_sync);
62
+ const synced = `Synced ${project.root} -> projects/${project.name}\n${await syncProjectToServer(callServer, project, !!args.force_full_sync)}`;
40
63
  /** warn, not stop: user-written files with markers are reported too (see recordBaseline) */
41
64
  const outside = findings.length
42
65
  ? `\n\nWarning: code outside USER CODE sections differs from what CubeMX generated; \`project regen\` would stop on it. Move it into a USER CODE section:\n\n${findings.join('\n\n')}`
43
66
  : '';
44
- if (args.build === undefined && args.analyse === undefined)
67
+ if (!args.syntax && args.build === undefined && args.analyse === undefined)
45
68
  return synced + outside;
46
69
  const parts = [];
47
70
  /** the CLI prints each part as soon as it is done, so a long build does not look stuck */
48
71
  const emit = (part) => (ctx.print ? ctx.print(part) : parts.push(part));
49
72
  emit(`# Sync\n${synced}${outside}`);
73
+ if (args.syntax)
74
+ emit(`# Syntax check\n${await syntaxCheckFolder(callServer, project)}`);
50
75
  let built = true;
51
76
  if (args.build !== undefined) {
52
77
  const build = await runBuild(project, args.build || 'Debug', !!args.verbose);
@@ -54,7 +79,7 @@ export default _defineTool({
54
79
  emit(`# Build\n${build.text}`);
55
80
  }
56
81
  if (args.analyse !== undefined) {
57
- emit(`# Static analysis\n${built ? await analysisStatic.run({ profile: args.analyse || 'quick' }, ctx) : 'Skipped: the build failed.'}`);
82
+ emit(`# Static analysis\n${built ? await analysisStatic.run({ dir: args.dir, profile: args.analyse || 'quick' }, ctx) : 'Skipped: the build failed.'}`);
58
83
  }
59
84
  /** a failed build must fail the command, or a script goes on to flash the previous ELF */
60
85
  if (!built)
@@ -1,15 +1,16 @@
1
1
  import { callServer } from '../../stm32/context.js';
2
2
  import { downloadAndUnzip, zipLink } from '../../stm32/utils/downloadzip_utils.js';
3
3
  import { _defineTool } from '../../stm32/tool.js';
4
- import { findStm32Project } from '../../stm32/utils/project_utils.js';
4
+ import { DIR_PROP, requireStm32Project } from '../../stm32/utils/project_utils.js';
5
5
  import { getMcuFromIoc } from '../../stm32/utils/mcu_utils.js';
6
6
  /** Restores the project's Drivers/ files from the server's copy for the .ioc's MCU; existing files are kept. */
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
- run: async () => {
12
- const project = await findStm32Project();
10
+ 'STM32CubeMX makes for the MCU in the .ioc and adds the files the project lacks; existing files are not overwritten. The project is the working directory or --dir; it must hold the .ioc.',
11
+ properties: { dir: DIR_PROP },
12
+ run: async (args, ctx) => {
13
+ const project = await requireStm32Project(args.dir, ctx.cwd);
13
14
  const mcu = await getMcuFromIoc(project.root);
14
15
  const text = await callServer('stm32_cubetools_download_drivers', { mcu }, 125_000);
15
16
  await downloadAndUnzip(zipLink(text), project.root, false); /** throws with the server reply when it has no zip link */
@@ -3,7 +3,7 @@ import { cliVersion } from "../../stm32/context.js";
3
3
  import { _defineTool } from "../../stm32/tool.js";
4
4
  import { findElf } from "../../stm32/utils/findElf.js";
5
5
  import { discover_system_tools } from "../../stm32/utils/discover_tools.js";
6
- import { findProject, findStm32Project } from "../../stm32/utils/project_utils.js";
6
+ import { findIocFolders, findProject, requireStm32Project } from "../../stm32/utils/project_utils.js";
7
7
  import { scanUserSections } from "../../stm32/utils/user_code.js";
8
8
  import { readFile } from "node:fs/promises";
9
9
  import { join } from "node:path";
@@ -13,8 +13,11 @@ export default _defineTool({
13
13
  description: "Check the server token, project and hardware tool setup: current project and STM32 project, its newest .elf in build/, debug session, USER CODE section mismatches in Core/Src/main.c and Core/Inc/main.h, and the installed debug tools (probe-rs, STM32_Programmer_CLI, STM32CubeIDE, STM32CubeMX).",
14
14
  run: async (_args, ctx) => {
15
15
  const p = await findProject(ctx.cwd);
16
- const stm = await findStm32Project(ctx.cwd).catch((e) => e);
17
- const stmText = stm instanceof Error ? `none (${stm.message})` : `${stm.name} (${stm.root})`;
16
+ const stm = await requireStm32Project(undefined, ctx.cwd).catch((e) => e);
17
+ /** the project commands never search below the working directory, so point at the projects found there */
18
+ const below = stm instanceof Error ? await findIocFolders(ctx.cwd) : [];
19
+ const hint = below.length ? `; STM32 projects below it: ${below.join(", ")} (cd into one or pass --dir)` : "";
20
+ const stmText = stm instanceof Error ? `none (${ctx.cwd} holds no .ioc or .mxproject file${hint})` : `${stm.name} (${stm.root})`;
18
21
  const elf = stm instanceof Error ? undefined : await findElf(stm.root);
19
22
  const build = elf ? `${elf.path} (${elf.mtime.toISOString()})` : "none";
20
23
  const tools = await discover_system_tools(true);
@@ -0,0 +1,2 @@
1
+ declare const command: import("yargs").CommandModule<{}, {}>;
2
+ export default command;
@@ -0,0 +1,8 @@
1
+ import { toolCommand } from "../../stm32/toolCommand.js";
2
+ import syntaxCheck from "./syntax_check.js";
3
+ const command = toolCommand({ command: "syntax-check", tool: syntaxCheck, mode: "local", server: true, positional: "paths", examples: [
4
+ ["$0 syntax-check", "syntax-check Core/ and App/ of the synced project"],
5
+ ["$0 syntax-check Core/Src/main.c", "upload one file (and the headers next to it) to a temp project and check it"],
6
+ ["$0 syntax-check 'lib/**/*.c' drivers/", "check every .c under lib/ and every source file under drivers/"],
7
+ ] });
8
+ export default command;
@@ -0,0 +1,3 @@
1
+ /** Syntax-checks the synced project's Core/ and App/, or uploads loose files to a temp project and checks them. */
2
+ declare const _default: import("../../stm32/tool.js").ToolDef;
3
+ export default _default;
@@ -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";