@turingcode/cli 0.2.12 → 0.3.4

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 (186) hide show
  1. package/README.md +2 -0
  2. package/dist/cli/create-cli.d.ts +10 -0
  3. package/dist/cli/create-cli.js +12 -2
  4. package/dist/cli/index.d.ts +9 -0
  5. package/dist/cli/index.js +5 -1
  6. package/dist/core/bound-error.d.ts +10 -0
  7. package/dist/core/date.d.ts +12 -0
  8. package/dist/core/exact/expression.d.ts +49 -0
  9. package/dist/core/exact/fraction.d.ts +85 -0
  10. package/dist/core/files.d.ts +44 -0
  11. package/dist/core/files.js +46 -1
  12. package/dist/core/json-shape.d.ts +45 -0
  13. package/dist/core/json-shape.js +0 -43
  14. package/dist/core/mcp.d.ts +92 -0
  15. package/dist/core/mcp.js +57 -30
  16. package/dist/core/query.d.ts +69 -0
  17. package/dist/core/query.js +11 -0
  18. package/dist/core/report.d.ts +11 -0
  19. package/dist/core/tables/csv.d.ts +18 -0
  20. package/dist/core/tables/markdown.d.ts +22 -0
  21. package/dist/core/tables/types.d.ts +25 -0
  22. package/dist/features/contract/check.d.ts +30 -0
  23. package/dist/features/contract/check.js +2 -3
  24. package/dist/features/contract/command.d.ts +12 -0
  25. package/dist/features/contract/command.js +64 -64
  26. package/dist/features/contract/describe.d.ts +22 -0
  27. package/dist/features/contract/diagnostics.d.ts +108 -0
  28. package/dist/features/contract/load.d.ts +58 -0
  29. package/dist/features/contract/load.js +24 -17
  30. package/dist/features/contract/model.d.ts +67 -0
  31. package/dist/features/contract/rules.d.ts +137 -0
  32. package/dist/features/contract/rules.js +11 -12
  33. package/dist/features/debug/clear_breakpoint.d.ts +2 -0
  34. package/dist/features/debug/clear_breakpoint.js +24 -0
  35. package/dist/features/debug/command.d.ts +5 -0
  36. package/dist/features/debug/command.js +66 -0
  37. package/dist/features/debug/continue.d.ts +2 -0
  38. package/dist/features/debug/continue.js +22 -0
  39. package/dist/features/debug/debug_start.d.ts +2 -0
  40. package/dist/features/debug/debug_start.js +22 -0
  41. package/dist/features/debug/debug_stop.d.ts +2 -0
  42. package/dist/features/debug/debug_stop.js +11 -0
  43. package/dist/features/debug/evaluate.d.ts +2 -0
  44. package/dist/features/debug/evaluate.js +48 -0
  45. package/dist/features/debug/get_stack.d.ts +2 -0
  46. package/dist/features/debug/get_stack.js +14 -0
  47. package/dist/features/debug/get_variables.d.ts +2 -0
  48. package/dist/features/debug/get_variables.js +26 -0
  49. package/dist/features/debug/halt.d.ts +2 -0
  50. package/dist/features/debug/halt.js +16 -0
  51. package/dist/features/debug/set_breakpoint.d.ts +2 -0
  52. package/dist/features/debug/set_breakpoint.js +30 -0
  53. package/dist/features/debug/step.d.ts +2 -0
  54. package/dist/features/debug/step.js +23 -0
  55. package/dist/features/install-mods/command.d.ts +6 -0
  56. package/dist/features/install-mods/command.js +18 -0
  57. package/dist/features/install-mods/install.d.ts +23 -0
  58. package/dist/features/install-mods/install.js +48 -0
  59. package/dist/features/install-skills/command.d.ts +7 -0
  60. package/dist/features/install-skills/command.js +22 -0
  61. package/dist/features/install-skills/install.d.ts +13 -0
  62. package/dist/features/install-skills/install.js +29 -0
  63. package/dist/features/probe/command.d.ts +5 -0
  64. package/dist/features/probe/command.js +44 -0
  65. package/dist/features/probe/kill_all_debuggers.d.ts +2 -0
  66. package/dist/features/probe/kill_all_debuggers.js +50 -0
  67. package/dist/features/probe/list_probes.d.ts +2 -0
  68. package/dist/features/probe/list_probes.js +8 -0
  69. package/dist/features/probe/program_project.d.ts +2 -0
  70. package/dist/features/probe/program_project.js +29 -0
  71. package/dist/features/probe/read_fault_status.d.ts +2 -0
  72. package/dist/features/probe/read_fault_status.js +19 -0
  73. package/dist/features/probe/read_memory.d.ts +2 -0
  74. package/dist/features/probe/read_memory.js +36 -0
  75. package/dist/features/probe/read_peripheral.d.ts +2 -0
  76. package/dist/features/probe/read_peripheral.js +58 -0
  77. package/dist/features/probe/reset_probe_usb.d.ts +2 -0
  78. package/dist/features/probe/reset_probe_usb.js +17 -0
  79. package/dist/features/probe/reset_target.d.ts +2 -0
  80. package/dist/features/probe/reset_target.js +16 -0
  81. package/dist/features/probe/target_info.d.ts +2 -0
  82. package/dist/features/probe/target_info.js +34 -0
  83. package/dist/features/project/analysis_static.d.ts +2 -0
  84. package/dist/features/project/analysis_static.js +19 -0
  85. package/dist/features/project/analysis_syntax_check.d.ts +2 -0
  86. package/dist/features/project/analysis_syntax_check.js +21 -0
  87. package/dist/features/project/command.d.ts +5 -0
  88. package/dist/features/project/command.js +64 -0
  89. package/dist/features/project/project_build.d.ts +2 -0
  90. package/dist/features/project/project_build.js +22 -0
  91. package/dist/features/project/project_download_template.d.ts +2 -0
  92. package/dist/features/project/project_download_template.js +34 -0
  93. package/dist/features/project/project_regenerate.d.ts +2 -0
  94. package/dist/features/project/project_regenerate.js +20 -0
  95. package/dist/features/project/project_sync_from_server.d.ts +2 -0
  96. package/dist/features/project/project_sync_from_server.js +13 -0
  97. package/dist/features/project/project_sync_to_server.d.ts +2 -0
  98. package/dist/features/project/project_sync_to_server.js +51 -0
  99. package/dist/features/project/stm32_cubetools_download_drivers.d.ts +2 -0
  100. package/dist/features/project/stm32_cubetools_download_drivers.js +19 -0
  101. package/dist/features/status/command.d.ts +2 -0
  102. package/dist/features/status/command.js +6 -0
  103. package/dist/features/status/get_status.d.ts +2 -0
  104. package/dist/features/status/get_status.js +44 -0
  105. package/dist/features/table/check.d.ts +38 -0
  106. package/dist/features/table/check.js +16 -23
  107. package/dist/features/table/command.d.ts +3 -0
  108. package/dist/features/table/command.js +4 -5
  109. package/dist/features/table/read.d.ts +28 -0
  110. package/dist/features/table/read.js +23 -3
  111. package/dist/features/tool/command.d.ts +35 -0
  112. package/dist/lib.d.ts +11 -0
  113. package/dist/lib.js +9 -0
  114. package/dist/stm32/actions/DebugAction.d.ts +63 -0
  115. package/dist/stm32/actions/DebugAction.js +105 -0
  116. package/dist/stm32/actions/DebugActionInfo.d.ts +7 -0
  117. package/dist/stm32/actions/DebugActionInfo.js +9 -0
  118. package/dist/stm32/actions/DebugActionListProbes.d.ts +9 -0
  119. package/dist/stm32/actions/DebugActionListProbes.js +10 -0
  120. package/dist/stm32/actions/DebugActionProgram.d.ts +28 -0
  121. package/dist/stm32/actions/DebugActionProgram.js +79 -0
  122. package/dist/stm32/actions/DebugActionRead.d.ts +38 -0
  123. package/dist/stm32/actions/DebugActionRead.js +59 -0
  124. package/dist/stm32/actions/DebugActionReset.d.ts +11 -0
  125. package/dist/stm32/actions/DebugActionReset.js +9 -0
  126. package/dist/stm32/actions/DebugActionServer.d.ts +7 -0
  127. package/dist/stm32/actions/DebugActionServer.js +9 -0
  128. package/dist/stm32/analysis.d.ts +19 -0
  129. package/dist/stm32/analysis.js +21 -0
  130. package/dist/stm32/build.d.ts +34 -0
  131. package/dist/stm32/build.js +79 -0
  132. package/dist/stm32/context.d.ts +23 -0
  133. package/dist/stm32/context.js +42 -0
  134. package/dist/stm32/daemon.d.ts +63 -0
  135. package/dist/stm32/daemon.js +202 -0
  136. package/dist/stm32/regen.d.ts +68 -0
  137. package/dist/stm32/regen.js +225 -0
  138. package/dist/stm32/session.d.ts +134 -0
  139. package/dist/stm32/session.js +374 -0
  140. package/dist/stm32/sync.d.ts +24 -0
  141. package/dist/stm32/sync.js +72 -0
  142. package/dist/stm32/tool.d.ts +43 -0
  143. package/dist/stm32/tool.js +20 -0
  144. package/dist/stm32/toolCommand.d.ts +50 -0
  145. package/dist/stm32/toolCommand.js +102 -0
  146. package/dist/stm32/utils/discover_tools.d.ts +24 -0
  147. package/dist/stm32/utils/discover_tools.js +121 -0
  148. package/dist/stm32/utils/downloadzip_utils.d.ts +57 -0
  149. package/dist/stm32/utils/downloadzip_utils.js +180 -0
  150. package/dist/stm32/utils/faultUtils.d.ts +14 -0
  151. package/dist/stm32/utils/faultUtils.js +69 -0
  152. package/dist/stm32/utils/findElf.d.ts +9 -0
  153. package/dist/stm32/utils/findElf.js +19 -0
  154. package/dist/stm32/utils/hash_utils.d.ts +19 -0
  155. package/dist/stm32/utils/hash_utils.js +28 -0
  156. package/dist/stm32/utils/listSyncFiles.d.ts +9 -0
  157. package/dist/stm32/utils/listSyncFiles.js +98 -0
  158. package/dist/stm32/utils/mcu_utils.d.ts +59 -0
  159. package/dist/stm32/utils/mcu_utils.js +99 -0
  160. package/dist/stm32/utils/project_utils.d.ts +54 -0
  161. package/dist/stm32/utils/project_utils.js +102 -0
  162. package/dist/stm32/utils/svdUtils.d.ts +31 -0
  163. package/dist/stm32/utils/svdUtils.js +30 -0
  164. package/dist/stm32/utils/truncate.d.ts +7 -0
  165. package/dist/stm32/utils/truncate.js +9 -0
  166. package/dist/stm32/utils/usb_utils.d.ts +5 -0
  167. package/dist/stm32/utils/usb_utils.js +23 -0
  168. package/dist/stm32/utils/user_code.d.ts +14 -0
  169. package/dist/stm32/utils/user_code.js +43 -0
  170. package/dist/stm32/utils/utils_mutex.d.ts +15 -0
  171. package/dist/stm32/utils/utils_mutex.js +93 -0
  172. package/dist/stm32/validate.d.ts +16 -0
  173. package/dist/stm32/validate.js +46 -0
  174. package/mods/claude/.claude-plugin/marketplace.json +8 -0
  175. package/mods/claude/turingcode-skills/.claude-plugin/plugin.json +5 -0
  176. package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +50 -0
  177. package/mods/claude/turingcode-skills/skills/turingcode-cli/references/board-and-debug.md +22 -0
  178. package/mods/claude/turingcode-skills/skills/turingcode-cli/references/build-and-check.md +19 -0
  179. package/mods/claude/turingcode-skills/skills/turingcode-cli/references/new-project.md +9 -0
  180. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/SKILL.md +43 -0
  181. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/concurrency.md +42 -0
  182. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/init-and-timing.md +35 -0
  183. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/input-and-bounds.md +34 -0
  184. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/registers-and-units.md +35 -0
  185. package/package.json +11 -3
  186. package/dist/features/clock/command.js +0 -63
@@ -0,0 +1,58 @@
1
+ import { Diagnostic } from "./diagnostics.js";
2
+ import { Contract } from "./model.js";
3
+ /** A contract file that was read, with its dependencies. */
4
+ export interface LoadedContract {
5
+ path: string;
6
+ /** `name@version`, `name`, or the file name: how findings refer to this contract. */
7
+ label: string;
8
+ /** The contract when it and all its dependencies are valid, else null. */
9
+ contract: Contract | null;
10
+ /** Dependencies by alias (each loaded, valid or not). */
11
+ deps: Map<string, LoadedContract>;
12
+ }
13
+ /**
14
+ * Parses a table reference (a rule's `on`).
15
+ *
16
+ * @param {string} ref - `Table` or `alias:Table`.
17
+ * @returns {{alias: string|null, table: string}} Its parts.
18
+ */
19
+ export declare function parseTableRef(ref: string): {
20
+ alias: string | null;
21
+ table: string;
22
+ };
23
+ /**
24
+ * Parses a column reference.
25
+ *
26
+ * @param {string} ref - `Column`, `Table.Column` or `alias:Table.Column`.
27
+ * @returns {{alias: string|null, table: string|null, column: string}} Its parts.
28
+ */
29
+ export declare function parseRef(ref: string): {
30
+ alias: string | null;
31
+ table: string | null;
32
+ column: string;
33
+ };
34
+ /**
35
+ * The status of a check whose contract did not load: MISSING_DATA when a contract file
36
+ * could not be read, else INVALID_CONTRACT.
37
+ *
38
+ * @param {Diagnostic[]} diags - The loading diagnostics.
39
+ * @returns {"MISSING_DATA" | "INVALID_CONTRACT"} The status.
40
+ */
41
+ export declare const failedLoadStatus: (diags: Diagnostic[]) => "MISSING_DATA" | "INVALID_CONTRACT";
42
+ /**
43
+ * Validates one contract whose dependencies are already loaded.
44
+ *
45
+ * @param {unknown} data - Parsed contract JSON.
46
+ * @param {Map<string, LoadedContract>} deps - Its dependencies by alias.
47
+ * @returns {Diagnostic[]} Every problem; empty when valid.
48
+ */
49
+ export declare function validateContract(data: unknown, deps: Map<string, LoadedContract>): Diagnostic[];
50
+ /**
51
+ * Reads and validates a contract and, recursively, the contracts it depends on.
52
+ *
53
+ * @param {string} path - Contract file.
54
+ * @param {Diagnostic[]} out - Receives every problem; a dependency's are prefixed with its label.
55
+ * @param {string[]} [stack=[]] - Files being loaded above this one (cycle detection).
56
+ * @returns {LoadedContract} The contract (null when it or a dependency is invalid).
57
+ */
58
+ export declare function loadContract(path: string, out: Diagnostic[], stack?: string[]): LoadedContract;
@@ -4,6 +4,16 @@ import { checkShape, show } from "../../core/json-shape.js";
4
4
  import { diag } from "./diagnostics.js";
5
5
  import { CONTRACT_SHAPE, keyColumns } from "./model.js";
6
6
  import { checkQuery } from "./rules.js";
7
+ /**
8
+ * Parses a table reference (a rule's `on`).
9
+ *
10
+ * @param {string} ref - `Table` or `alias:Table`.
11
+ * @returns {{alias: string|null, table: string}} Its parts.
12
+ */
13
+ export function parseTableRef(ref) {
14
+ const colon = ref.indexOf(":");
15
+ return colon > 0 ? { alias: ref.slice(0, colon), table: ref.slice(colon + 1) } : { alias: null, table: ref };
16
+ }
7
17
  /**
8
18
  * Parses a column reference.
9
19
  *
@@ -11,22 +21,18 @@ import { checkQuery } from "./rules.js";
11
21
  * @returns {{alias: string|null, table: string|null, column: string}} Its parts.
12
22
  */
13
23
  export function parseRef(ref) {
14
- const colon = ref.indexOf(":");
15
- const alias = colon > 0 ? ref.slice(0, colon) : null;
16
- const rest = colon > 0 ? ref.slice(colon + 1) : ref;
24
+ const { alias, table: rest } = parseTableRef(ref);
17
25
  const dot = rest.indexOf(".");
18
26
  return dot > 0 ? { alias, table: rest.slice(0, dot), column: rest.slice(dot + 1) } : { alias, table: null, column: rest };
19
27
  }
20
28
  /**
21
- * Parses a table reference (a rule's `on`).
29
+ * The status of a check whose contract did not load: MISSING_DATA when a contract file
30
+ * could not be read, else INVALID_CONTRACT.
22
31
  *
23
- * @param {string} ref - `Table` or `alias:Table`.
24
- * @returns {{alias: string|null, table: string}} Its parts.
32
+ * @param {Diagnostic[]} diags - The loading diagnostics.
33
+ * @returns {"MISSING_DATA" | "INVALID_CONTRACT"} The status.
25
34
  */
26
- export function parseTableRef(ref) {
27
- const colon = ref.indexOf(":");
28
- return colon > 0 ? { alias: ref.slice(0, colon), table: ref.slice(colon + 1) } : { alias: null, table: ref };
29
- }
35
+ export const failedLoadStatus = (diags) => (diags.some(d => d.code === "CONTRACT.MISSING_FILE") ? "MISSING_DATA" : "INVALID_CONTRACT");
30
36
  /** A shape message without its leading JSON path, which the diagnostic already shows as its column. */
31
37
  const stripPath = (message, path) => message.replace(/^[^:]*: /, "") || path;
32
38
  /** Pushes CONTRACT.DUPLICATE for repeated names. */
@@ -49,12 +55,12 @@ export function validateContract(data, deps) {
49
55
  const out = [];
50
56
  const shapeIssues = checkShape(data, CONTRACT_SHAPE, "$");
51
57
  for (const i of shapeIssues) {
52
- out.push(diag(i.kind === "regex" ? "CONTRACT.BAD_REGEX" : "CONTRACT.BAD_FIELD", stripPath(i.message, i.path), { column: i.path }, i.found, i.expected));
58
+ out.push(diag("CONTRACT.BAD_FIELD", stripPath(i.message, i.path), { column: i.path }, i.found, i.expected));
53
59
  }
54
- // A bad regex leaves the structure intact, so the other checks still run and report everything at once.
55
- if (shapeIssues.some(i => i.kind !== "regex"))
60
+ if (shapeIssues.length)
56
61
  return out;
57
62
  const c = data;
63
+ // Checked here, not by the shape: the "string" shape rejects "", the most common missing value.
58
64
  for (const v of c.missing_values ?? []) {
59
65
  if (typeof v !== "string")
60
66
  out.push(diag("CONTRACT.BAD_FIELD", "missing_values must be strings", { column: "missing_values" }, show(v), "a string"));
@@ -172,12 +178,14 @@ export function loadContract(path, out, stack = []) {
172
178
  const full = resolve(path);
173
179
  const loaded = { path, label: basename(path), contract: null, deps: new Map() };
174
180
  const own = [];
181
+ // Findings in a dependency name it; findings in the checked contract need no prefix.
182
+ const publish = () => out.push(...(stack.length ? own.map(d => ({ ...d, message: `${loaded.label}: ${d.message}` })) : own));
175
183
  const file = readJsonFile(path);
176
184
  if (!file.ok) {
177
185
  own.push(file.error === "unreadable"
178
186
  ? diag("CONTRACT.MISSING_FILE", `cannot read ${path}: ${file.message}`, {}, path, "a readable file")
179
187
  : diag("CONTRACT.BAD_JSON", `${path}: ${file.message}`, {}, path, "valid JSON"));
180
- out.push(...(stack.length ? own.map(d => ({ ...d, message: `${loaded.label}: ${d.message}` })) : own));
188
+ publish();
181
189
  return loaded;
182
190
  }
183
191
  const data = file.data;
@@ -190,7 +198,7 @@ export function loadContract(path, out, stack = []) {
190
198
  if (typeof rel !== "string")
191
199
  continue; // reported by the shape check
192
200
  const depPath = resolve(dirname(path), rel);
193
- if ([...stack, full].includes(resolve(depPath))) {
201
+ if ([...stack, full].includes(depPath)) {
194
202
  own.push(diag("CONTRACT.CYCLE", `depends_on '${alias}' leads back to ${rel}`, { column: `depends_on.${alias}` }, rel, "no cycle"));
195
203
  depsOk = false;
196
204
  continue;
@@ -200,8 +208,7 @@ export function loadContract(path, out, stack = []) {
200
208
  depsOk &&= dep.contract !== null;
201
209
  }
202
210
  own.push(...validateContract(data, loaded.deps));
203
- // Findings in a dependency name it; findings in the checked contract need no prefix.
204
- out.push(...(stack.length ? own.map(d => ({ ...d, message: `${loaded.label}: ${d.message}` })) : own));
211
+ publish();
205
212
  loaded.contract = depsOk && !own.some(d => d.severity === "FAIL") ? data : null;
206
213
  return loaded;
207
214
  }
@@ -0,0 +1,67 @@
1
+ import type { Shape } from "../../core/json-shape.js";
2
+ import type { Query } from "../../core/query.js";
3
+ export declare const COLUMN_TYPES: readonly ["string", "integer", "number", "boolean", "date", "list"];
4
+ export type ColumnType = (typeof COLUMN_TYPES)[number];
5
+ /** One declared column. Only `name` is required; every value constraint is in `match`. */
6
+ export interface Column {
7
+ name: string;
8
+ /** Default `string`. */
9
+ type?: ColumnType;
10
+ description?: string;
11
+ /** The cell must not be a missing value. Default false. */
12
+ required?: boolean;
13
+ /** Item separator for `list`. Default ",". */
14
+ separator?: string;
15
+ /** A MongoDB-style condition every filled cell must meet, e.g. `{"$in": ["a", "b"]}`. */
16
+ match?: Record<string, unknown>;
17
+ }
18
+ /** A rule: rows (of `on`, default this table) matching `when` must match `require`, or their number must match `count`. */
19
+ export interface Rule {
20
+ id?: string;
21
+ description?: string;
22
+ /** `Table` or `alias:Table` whose rows the rule tests. Default: the table the rule is in. */
23
+ on?: string;
24
+ /** Rows the rule applies to: a row query. */
25
+ when?: Query;
26
+ /** A row query every applicable row must match. */
27
+ require?: Query;
28
+ /** A condition on the number of applicable rows, e.g. `{"$gte": 1}`. */
29
+ count?: Record<string, unknown>;
30
+ /** `error` (default) fails the check, `warning` only reports. */
31
+ severity?: "error" | "warning";
32
+ }
33
+ export interface Table {
34
+ name: string;
35
+ description?: string;
36
+ /** The table must be present. Default true. */
37
+ required?: boolean;
38
+ /** Columns must appear in the declared order. Default false. */
39
+ ordered?: boolean;
40
+ /** Columns not declared are allowed. Default false. */
41
+ allow_extra_columns?: boolean;
42
+ /** Column (or columns) whose values identify a row: required and unique. */
43
+ primary_key?: string | string[];
44
+ columns: Column[];
45
+ rules?: Rule[];
46
+ }
47
+ /** A table contract. Only `tables` is required. */
48
+ export interface Contract {
49
+ name?: string;
50
+ version?: string;
51
+ description?: string;
52
+ /** `markdown` (default): one `## <Table>` section per table; `csv`: one `<Table>.csv` per table. */
53
+ format?: "markdown" | "csv";
54
+ /** Cell texts that count as missing. Default [""]. */
55
+ missing_values?: string[];
56
+ /** Tables not declared are allowed. Default false. */
57
+ allow_extra_tables?: boolean;
58
+ /** Other contracts this one references: alias -> contract file (relative to this one). */
59
+ depends_on?: Record<string, string>;
60
+ tables: Table[];
61
+ }
62
+ export declare const COLUMN_SHAPE: Shape;
63
+ /** A rule. */
64
+ export declare const RULE_SHAPE: Shape;
65
+ export declare const CONTRACT_SHAPE: Shape;
66
+ /** The primary key columns of a table (empty when none). */
67
+ export declare const keyColumns: (t: Table) => string[];
@@ -0,0 +1,137 @@
1
+ import type { Node } from "../../core/exact/expression.js";
2
+ import { Fraction } from "../../core/exact/fraction.js";
3
+ import { Doc, Query, QueryHooks, Value } from "../../core/query.js";
4
+ import type { Alternative, Code } from "./diagnostics.js";
5
+ import type { Column, Contract, Table } from "./model.js";
6
+ declare const CALC_OPS: readonly ["<=", ">=", "==", "!=", "<", ">"];
7
+ type CalcOp = (typeof CALC_OPS)[number];
8
+ /** One table row: its label (primary key or `#n`), its cells by column name, and the cells as a query sees them. */
9
+ export interface Row {
10
+ label: string;
11
+ cells: Record<string, string>;
12
+ doc: Doc;
13
+ /** The row has the wrong number of cells (ROW_SHAPE): it counts and can be referenced, but its own cells are not checked. */
14
+ shapeError: boolean;
15
+ }
16
+ /** A resolved `Table.Column` or `alias:Table.Column` reference. */
17
+ export interface Ref {
18
+ alias: string | null;
19
+ table: Table;
20
+ column: Column;
21
+ }
22
+ /** What `contract check` gives a query to validate it. */
23
+ export interface ValidateContext {
24
+ contract: Contract;
25
+ /** The table whose rows the query tests. */
26
+ table: Table;
27
+ /** Reports a contract problem (`field` names the contract field). */
28
+ problem(code: Code, message: string, field: string, found: string, expected: string): void;
29
+ /** Reports UNKNOWN_COLUMN for names the table does not declare; returns whether all exist. */
30
+ requireColumns(names: string[], field: string): boolean;
31
+ /** Resolves `Table.Column` or `alias:Table.Column`, reporting what is unknown. */
32
+ resolve(ref: string, field: string): Ref | null;
33
+ }
34
+ /** A query's hooks plus `$calc`'s values, which explaining a COMPARE failure needs. */
35
+ export interface CheckHooks extends QueryHooks {
36
+ calcValues(param: unknown, doc: Doc): {
37
+ left: Fraction;
38
+ right: Fraction;
39
+ } | null;
40
+ }
41
+ /** A failing part of a query, ready to report. */
42
+ export interface Failure {
43
+ code: Code;
44
+ message: string;
45
+ column: string;
46
+ found: string;
47
+ expected: string;
48
+ /** For NONE_OF: why each `$or` branch failed. */
49
+ alternatives?: Alternative[];
50
+ }
51
+ /** Splits a list cell into trimmed, non-empty items. */
52
+ export declare const listItems: (cell: string, separator?: string) => string[];
53
+ /** A value as text: list items joined, missing as empty. */
54
+ export declare const valueText: (v: Value | undefined) => string;
55
+ /**
56
+ * Whether `word` occurs in `text` as a whole token (not inside a longer word or ID).
57
+ *
58
+ * @param {string} text - Text to search.
59
+ * @param {string} word - The value.
60
+ * @returns {boolean} True when mentioned.
61
+ */
62
+ export declare function mentions(text: string, word: string): boolean;
63
+ /** Number columns of a table: the names a `$calc` expression may use. */
64
+ export declare const numberColumns: (t: Table) => Set<string>;
65
+ /** A parsed `$calc`: `"Qty * Price == Total"` or `{"expr": "...", "tolerance": 0.01}`. */
66
+ interface Calc {
67
+ text: string;
68
+ left: Node;
69
+ op: CalcOp;
70
+ right: Node;
71
+ tolerance: Fraction;
72
+ }
73
+ /**
74
+ * Parses a `$calc` parameter over the given number columns.
75
+ *
76
+ * @param {unknown} param - The parameter.
77
+ * @param {Set<string>} allowed - Number columns the expression may use.
78
+ * @returns {Calc | string} The parsed comparison, or what is wrong with it.
79
+ */
80
+ export declare function parseCalc(param: unknown, allowed: Set<string>): Calc | string;
81
+ /**
82
+ * Evaluates a `$calc` on a row.
83
+ *
84
+ * @param {Calc} c - The parsed comparison.
85
+ * @param {Doc} doc - The row.
86
+ * @param {Set<string>} numbers - The table's number columns.
87
+ * @returns {{left: Fraction, right: Fraction, holds: boolean} | null} The sides and the result; null when a
88
+ * value is missing or not a number, or the arithmetic fails (the column check reports those).
89
+ */
90
+ export declare function evaluateCalc(c: Calc, doc: Doc, numbers: Set<string>): {
91
+ left: Fraction;
92
+ right: Fraction;
93
+ holds: boolean;
94
+ } | null;
95
+ /**
96
+ * Validates a query of the contract (`match`, `when`, `require`, `count`):
97
+ * operators, values, columns, `$ref`/`$mentioned` targets, `$calc` and `$regex`.
98
+ *
99
+ * @param {unknown} q - The query, as a row query.
100
+ * @param {string} field - Contract field, for the report.
101
+ * @param {ValidateContext} v - Validation context.
102
+ * @returns {void}
103
+ */
104
+ export declare function checkQuery(q: unknown, field: string, v: ValidateContext): void;
105
+ /**
106
+ * Splits a row query into parts that are checked (and reported) one by one.
107
+ *
108
+ * @param {Query} q - The query.
109
+ * @returns {Query[]} One row query per column operator, logical operator, `$calc` or `$unique`.
110
+ */
111
+ export declare function splitQuery(q: Query): Query[];
112
+ /**
113
+ * Explains why a row fails one part of a query.
114
+ *
115
+ * @param {Query} part - A part from `splitQuery`.
116
+ * @param {Doc} doc - The row.
117
+ * @param {CheckHooks} hooks - The hooks the query ran with.
118
+ * @returns {Failure} Code, message, column, found and expected.
119
+ */
120
+ export declare function explain(part: Query, doc: Doc, hooks: CheckHooks): Failure;
121
+ /**
122
+ * One column condition in words, e.g. "one of `a`, `b`".
123
+ *
124
+ * @param {unknown} cond - The condition.
125
+ * @param {(v: unknown) => string} c - Formats a value (backticks for describe, String for diagnostics).
126
+ * @returns {string} The text.
127
+ */
128
+ export declare function renderCondition(cond: unknown, c?: (v: unknown) => string): string;
129
+ /**
130
+ * A row query in words, e.g. "`Status` = `shipped` and `Tracking` filled".
131
+ *
132
+ * @param {unknown} q - The query.
133
+ * @param {(v: unknown) => string} c - Formats a value.
134
+ * @returns {string} The text.
135
+ */
136
+ export declare function renderQuery(q: unknown, c?: (v: unknown) => string): string;
137
+ export {};
@@ -1,12 +1,11 @@
1
1
  import { BoundError } from "../../core/bound-error.js";
2
2
  import { AstError, evaluate, namesIn, parseExpression } from "../../core/exact/expression.js";
3
3
  import { Fraction } from "../../core/exact/fraction.js";
4
- import { compileQuery, prepareQuery } from "../../core/query.js";
4
+ import { compileQuery, prepareQuery, queryTester } from "../../core/query.js";
5
5
  /** Largest expression a `$calc` may use. */
6
6
  const MAX_EXPRESSION_NODES = 256;
7
7
  const CALC_OPS = ["<=", ">=", "==", "!=", "<", ">"];
8
8
  const code = (v) => `\`${String(v)}\``;
9
- const plain = (v) => String(v);
10
9
  const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
11
10
  const NUMERIC_TEXT = { $gt: ">", $gte: ">=", $lt: "<", $lte: "<=" };
12
11
  /** Splits a list cell into trimmed, non-empty items. */
@@ -154,7 +153,7 @@ export function splitQuery(q) {
154
153
  */
155
154
  export function explain(part, doc, hooks) {
156
155
  const [key, arg] = Object.entries(part)[0];
157
- const match = { code: "MATCH", message: "row does not match", column: "-", found: "-", expected: renderQuery(part, plain) };
156
+ const match = { code: "MATCH", message: "row does not match", column: "-", found: "-", expected: renderQuery(part, String) };
158
157
  if (key === "$calc") {
159
158
  const values = hooks.calcValues(arg, doc);
160
159
  const text = isObject(arg) ? String(arg.expr) : String(arg);
@@ -169,7 +168,7 @@ export function explain(part, doc, hooks) {
169
168
  if (key === "$or" || key === "$and") {
170
169
  // The first failing part of each branch: all of them for $or, the first failing branch for $and.
171
170
  const failures = arg.flatMap(branch => {
172
- const failing = splitQuery(branch).find(p => !compileQuery(prepareQuery(p).query, hooks)(doc));
171
+ const failing = splitQuery(branch).find(p => !queryTester(p, hooks)(doc));
173
172
  return failing ? [explain(failing, doc, hooks)] : [];
174
173
  });
175
174
  if (key === "$and")
@@ -191,7 +190,7 @@ export function explain(part, doc, hooks) {
191
190
  */
192
191
  function explainFirst(column, cond, value, hooks) {
193
192
  const parts = splitCondition("_", cond);
194
- const failing = parts.find(p => !compileQuery(prepareQuery(p).query, hooks)({ _: value })) ?? parts[0];
193
+ const failing = parts.find(p => !queryTester(p, hooks)({ _: value })) ?? parts[0];
195
194
  return explainCondition(column, failing._, value, hooks);
196
195
  }
197
196
  /**
@@ -212,13 +211,13 @@ function explainFirst(column, cond, value, hooks) {
212
211
  */
213
212
  function explainOr(column, alternatives, value, hooks) {
214
213
  const text = valueText(value);
215
- const expected = renderCondition({ $or: alternatives }, plain);
214
+ const expected = renderCondition({ $or: alternatives }, String);
216
215
  const failures = alternatives.map(alt => explainFirst(column, alt, value, hooks));
217
216
  const narrowed = failures.filter(f => f.code !== "MATCH" && f.found !== text && f.found !== "");
218
217
  if (narrowed.length === 1)
219
218
  return { ...narrowed[0], expected };
220
219
  const shared = failures.every(f => f.code === failures[0].code) ? failures[0].code : null;
221
- const names = alternatives.map((alt, i) => `(${renderCondition(alt, plain)})${shared ? "" : ` [${failures[i].code}]`}`);
220
+ const names = alternatives.map((alt, i) => `(${renderCondition(alt, String)})${shared ? "" : ` [${failures[i].code}]`}`);
222
221
  const none = names.length === 2 ? `neither ${names[0]} nor ${names[1]}` : `none of ${names.join(", ")}`;
223
222
  const failure = { code: shared ?? "NONE_OF", message: `'${text}' is ${none}`, column, found: text, expected };
224
223
  return shared ? failure : { ...failure, alternatives: failures.map(f => ({ code: f.code, message: f.message })) };
@@ -227,14 +226,14 @@ function explainOr(column, alternatives, value, hooks) {
227
226
  * Explains why one column's value fails a single-operator condition.
228
227
  *
229
228
  * @param {string} column - The column.
230
- * @param {unknown} cond - The condition (one operator, or a plain value).
229
+ * @param {unknown} cond - The condition (one operator, or a String value).
231
230
  * @param {Value} value - The value.
232
231
  * @param {CheckHooks} hooks - The hooks the query ran with.
233
232
  * @returns {Failure} The explanation.
234
233
  */
235
234
  function explainCondition(column, cond, value, hooks) {
236
235
  const text = valueText(value);
237
- const expected = renderCondition(cond, plain);
236
+ const expected = renderCondition(cond, String);
238
237
  const fail = (c, message, found = text, exp = expected) => ({ code: c, message, column, found, expected: exp });
239
238
  if (cond === null || (isObject(cond) && "$eq" in cond && cond.$eq === null))
240
239
  return fail("EMPTY_IF", `${column} must be empty`, text, "empty");
@@ -273,7 +272,7 @@ function explainCondition(column, cond, value, hooks) {
273
272
  case "$or":
274
273
  return explainOr(column, arg, value, hooks);
275
274
  case "$and": {
276
- const sub = arg.find(c => !compileQuery(prepareQuery({ _: c }).query, hooks)({ _: value }));
275
+ const sub = arg.find(c => !queryTester({ _: c }, hooks)({ _: value }));
277
276
  if (sub !== undefined)
278
277
  return explainFirst(column, sub, value, hooks);
279
278
  break;
@@ -283,7 +282,7 @@ function explainCondition(column, cond, value, hooks) {
283
282
  const inner = isObject(arg) && Object.keys(arg).length === 1 ? arg : null;
284
283
  if (!inner)
285
284
  break;
286
- const test = compileQuery(prepareQuery({ _: arg }).query, hooks);
285
+ const test = queryTester({ _: arg }, hooks);
287
286
  const badItems = items.filter(x => !test({ _: x }));
288
287
  const f = explainCondition(column, inner, badItems.length === 1 ? badItems[0] : badItems, hooks);
289
288
  return { ...f, expected: `every item ${f.expected}` };
@@ -295,7 +294,7 @@ function explainCondition(column, cond, value, hooks) {
295
294
  * One column condition in words, e.g. "one of `a`, `b`".
296
295
  *
297
296
  * @param {unknown} cond - The condition.
298
- * @param {(v: unknown) => string} c - Formats a value (backticks for describe, plain for diagnostics).
297
+ * @param {(v: unknown) => string} c - Formats a value (backticks for describe, String for diagnostics).
299
298
  * @returns {string} The text.
300
299
  */
301
300
  export function renderCondition(cond, c = code) {
@@ -0,0 +1,2 @@
1
+ declare const _default: import("../../stm32/tool.js").ToolDef;
2
+ export default _default;
@@ -0,0 +1,24 @@
1
+ import { _defineTool } from '../../stm32/tool.js';
2
+ import { getSession, projectFile, syncBreakpoints } from '../../stm32/session.js';
3
+ // Removes source breakpoints from the debug session.
4
+ export default _defineTool({
5
+ name: 'clear_breakpoint',
6
+ description: 'Remove a source breakpoint from the debug session. Without line, removes every breakpoint in the file; without file, removes all breakpoints.',
7
+ properties: {
8
+ file: { type: 'string', maxLength: 512, description: 'Project-relative path' },
9
+ line: { type: 'integer', minimum: 1 },
10
+ },
11
+ run: async (args) => {
12
+ const s = getSession();
13
+ const files = args.file ? [projectFile(s.opts.root, args.file)] : [...s.breakpoints.keys()];
14
+ for (const rel of files) {
15
+ const keep = args.line ? (s.breakpoints.get(rel) ?? []).filter((b) => b.line !== args.line) : [];
16
+ s.breakpoints.set(rel, keep);
17
+ await syncBreakpoints(s, rel);
18
+ if (!keep.length)
19
+ s.breakpoints.delete(rel);
20
+ }
21
+ const left = [...s.breakpoints].flatMap(([rel, list]) => list.map((b) => `${rel}:${b.line}`));
22
+ return `Breakpoints left: ${left.length ? left.join(', ') : 'none'}`;
23
+ },
24
+ });
@@ -0,0 +1,5 @@
1
+ import { CommandModule } from "yargs";
2
+ /** The session tools, served by the debug daemon. */
3
+ export declare const DEBUG_TOOLS: import("../../stm32/tool.js").ToolDef[];
4
+ declare const command: CommandModule;
5
+ export default command;
@@ -0,0 +1,66 @@
1
+ import { runDaemon } from "../../stm32/daemon.js";
2
+ import { toolCommand } from "../../stm32/toolCommand.js";
3
+ import { findProject } from "../../stm32/utils/project_utils.js";
4
+ import { PROBE_TOOLS } from "../probe/command.js";
5
+ import { PROJECT_HELP } from "../project/command.js";
6
+ import clearBreakpoint from "./clear_breakpoint.js";
7
+ import continueTarget from "./continue.js";
8
+ import debugStart from "./debug_start.js";
9
+ import debugStop from "./debug_stop.js";
10
+ import evaluate from "./evaluate.js";
11
+ import getStack from "./get_stack.js";
12
+ import getVariables from "./get_variables.js";
13
+ import halt from "./halt.js";
14
+ import setBreakpoint from "./set_breakpoint.js";
15
+ import step from "./step.js";
16
+ /** The session tools, served by the debug daemon. */
17
+ export const DEBUG_TOOLS = [debugStart, debugStop, halt, continueTarget, step, setBreakpoint, clearBreakpoint, getStack, getVariables, evaluate];
18
+ const subcommands = [
19
+ toolCommand({ command: "start", tool: debugStart, mode: "start", examples: [
20
+ ["$0 debug start", "attach to the running firmware (it must match the newest .elf in build/)"],
21
+ ["$0 debug start --flash", "flash the .elf and halt after reset"],
22
+ ] }),
23
+ toolCommand({ command: "stop", tool: debugStop, mode: "session", examples: [["$0 debug stop", "end the session; the target keeps running"]] }),
24
+ toolCommand({ command: "halt", tool: halt, mode: "session", examples: [["$0 debug halt", "pause and show where"]] }),
25
+ toolCommand({ command: "continue", tool: continueTarget, mode: "session", examples: [
26
+ ["$0 debug continue", "resume"],
27
+ ["$0 debug continue --wait 10", "resume and wait up to 10 s for a breakpoint"],
28
+ ] }),
29
+ toolCommand({ command: "step", tool: step, mode: "session", examples: [
30
+ ["$0 debug step", "step over one source line"],
31
+ ["$0 debug step --kind into", "step into a call"],
32
+ ] }),
33
+ toolCommand({ command: "break", tool: setBreakpoint, mode: "session", examples: [
34
+ ["$0 debug break --file Core/Src/main.c --line 120", "breakpoint at a line"],
35
+ ["$0 debug break --file Core/Src/main.c --line 120 --condition 'count > 3'", "conditional breakpoint"],
36
+ ] }),
37
+ toolCommand({ command: "clear", tool: clearBreakpoint, mode: "session", examples: [
38
+ ["$0 debug clear --file Core/Src/main.c --line 120", "remove one breakpoint"],
39
+ ["$0 debug clear", "remove every breakpoint"],
40
+ ] }),
41
+ toolCommand({ command: "stack", tool: getStack, mode: "session", examples: [["$0 debug stack", "call stack of the halted target"]] }),
42
+ toolCommand({ command: "vars", tool: getVariables, mode: "session", examples: [["$0 debug vars --frame 1", "locals of the caller's frame"]] }),
43
+ toolCommand({ command: "eval", tool: evaluate, mode: "session", examples: [["$0 debug eval --expr 'count, cfg.mode, buf[2]'", "several expressions"]] }),
44
+ ];
45
+ // Hidden: the background process `debug start` launches in the project folder.
46
+ const daemon = {
47
+ command: "daemon",
48
+ describe: false,
49
+ builder: cli => cli.options({ root: { type: "string", describe: "Project root, as the CLI that launched it found it" } }),
50
+ handler: async (argv) => runDaemon(argv.root ?? (await findProject()).root, [...DEBUG_TOOLS, ...PROBE_TOOLS]),
51
+ };
52
+ const command = {
53
+ command: "debug",
54
+ describe: "Debug the firmware on the board: breakpoints, stepping, stack, variables (probe-rs)",
55
+ builder: cli => [...subcommands, daemon].reduce((c, s) => c.command(s), cli)
56
+ .demandCommand(1, "debug needs a subcommand: start, stop, halt, continue, step, break, clear, stack, vars or eval")
57
+ .epilogue([
58
+ "`debug start` launches a background daemon for the project that holds the probe-rs session; the other",
59
+ "debug commands talk to it, so the session lives across runs until `debug stop` (the daemon then exits).",
60
+ "Its files are in .turingcode/ (daemon.token, daemon.log, probe.lock). Needs probe-rs and a .elf in build/",
61
+ "(`project build`). Breakpoint files are project-relative paths, e.g. Core/Src/main.c.",
62
+ PROJECT_HELP,
63
+ ].join("\n")),
64
+ handler: () => { },
65
+ };
66
+ export default command;
@@ -0,0 +1,2 @@
1
+ declare const _default: import("../../stm32/tool.js").ToolDef;
2
+ export default _default;
@@ -0,0 +1,22 @@
1
+ import { _defineTool } from '../../stm32/tool.js';
2
+ import { getSession } from '../../stm32/session.js';
3
+ // Resumes the target, optionally waiting for it to stop again.
4
+ export default _defineTool({
5
+ name: 'continue',
6
+ description: 'Resume the target in the debug session. With wait > 0, waits up to that many seconds for it to stop (e.g. at a breakpoint) and reports where.',
7
+ properties: { wait: { type: 'integer', minimum: 0, maximum: 60, description: 'Seconds to wait for a stop (default 0)' } },
8
+ run: async (args) => {
9
+ const s = getSession();
10
+ s.requireHalted();
11
+ const stopped = s.waitEvent('stopped', (args.wait ?? 0) * 1000);
12
+ // Set before the request: the stopped event of a short run can arrive before its response
13
+ s.state = 'running';
14
+ await s.request('continue', { threadId: s.threadId }).catch((e) => {
15
+ s.state = 'halted';
16
+ throw e;
17
+ });
18
+ if (!args.wait)
19
+ return 'Running';
20
+ return (await stopped) ? s.location() : `Still running after ${args.wait} s`;
21
+ },
22
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("../../stm32/tool.js").ToolDef;
2
+ export default _default;
@@ -0,0 +1,22 @@
1
+ import { _defineTool } from '../../stm32/tool.js';
2
+ import { findStm32Project } from '../../stm32/utils/project_utils.js';
3
+ import { startSession } from '../../stm32/session.js';
4
+ import { findElf } from '../../stm32/utils/findElf.js';
5
+ import { getMcuFromIoc } from '../../stm32/utils/mcu_utils.js';
6
+ // Starts a probe-rs debug session on the project's board.
7
+ export default _defineTool({
8
+ name: 'debug_start',
9
+ description: "Start a probe-rs debug session on the project's board using the newest .elf in build/. By default it attaches to the running firmware (which must match that .elf); with flash=true it flashes the .elf first and halts after reset, so breakpoints can be set before continue. Takes ownership of the probe until `turingcode debug stop`.",
10
+ properties: { flash: { type: 'boolean', description: 'Flash the .elf and halt after reset (default false: attach)' } },
11
+ needsProbe: true,
12
+ run: async (args, ctx) => {
13
+ const project = await findStm32Project();
14
+ const elf = await findElf(project.root);
15
+ if (!elf)
16
+ throw new Error("No .elf in the project's build/ folder: run `turingcode project build` first");
17
+ const chip = await getMcuFromIoc(project.root);
18
+ const flash = args.flash === true;
19
+ const s = await startSession({ root: project.root, chip, elf: elf.path, flash });
20
+ return `Debug session started (${flash ? 'flashed' : 'attached'}, ${chip}, ${elf.path})\n${await s.location()}`;
21
+ },
22
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("../../stm32/tool.js").ToolDef;
2
+ export default _default;
@@ -0,0 +1,11 @@
1
+ import { _defineTool } from '../../stm32/tool.js';
2
+ import { getSession } from '../../stm32/session.js';
3
+ // Ends the probe-rs debug session; the target keeps running.
4
+ export default _defineTool({
5
+ name: 'debug_stop',
6
+ description: 'Stop the debug session and release the probe. Breakpoints are removed and the target keeps running.',
7
+ run: async () => {
8
+ await getSession().stop();
9
+ return 'Debug session stopped, probe released';
10
+ },
11
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("../../stm32/tool.js").ToolDef;
2
+ export default _default;