tan-cli 0.7.0__py3-none-any.whl

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 (330) hide show
  1. tan/__init__.py +0 -0
  2. tan/__main__.py +120 -0
  3. tan/cli.py +939 -0
  4. tan/command_table.py +265 -0
  5. tan/commands/__init__.py +8 -0
  6. tan/commands/bootstrap_cmd.py +4856 -0
  7. tan/commands/bootstrap_patches.py +164 -0
  8. tan/commands/bootstrap_toolchain_fetch.py +155 -0
  9. tan/commands/bootstrap_toolchain_pin.py +36 -0
  10. tan/commands/build/__init__.py +1 -0
  11. tan/commands/build/configure_inputs.py +277 -0
  12. tan/commands/build/execute.py +1852 -0
  13. tan/commands/build/host_python.py +59 -0
  14. tan/commands/build/link_stale.py +78 -0
  15. tan/commands/build/manifest.py +428 -0
  16. tan/commands/build/materialise.py +81 -0
  17. tan/commands/build/token_substitution.py +381 -0
  18. tan/commands/build/toolchain.py +482 -0
  19. tan/commands/build/user_defines_wipe.py +115 -0
  20. tan/commands/build/workspace_patches.py +65 -0
  21. tan/commands/build_cmd.py +2236 -0
  22. tan/commands/build_output.py +331 -0
  23. tan/commands/clean_cmd.py +1183 -0
  24. tan/commands/completion_cmd.py +786 -0
  25. tan/commands/debug_config_cmd.py +2425 -0
  26. tan/commands/diff_cmd.py +940 -0
  27. tan/commands/doctor_cmd.py +4767 -0
  28. tan/commands/examples_cmd.py +644 -0
  29. tan/commands/explain_cmd.py +1319 -0
  30. tan/commands/faultdecode_cmd.py +931 -0
  31. tan/commands/flash_atoc_guard.py +240 -0
  32. tan/commands/flash_cmd.py +5731 -0
  33. tan/commands/flash_mram_guard.py +150 -0
  34. tan/commands/flash_ram.py +578 -0
  35. tan/commands/flash_raw.py +583 -0
  36. tan/commands/generate_cmd.py +1456 -0
  37. tan/commands/image_cmd.py +753 -0
  38. tan/commands/init_cmd.py +1740 -0
  39. tan/commands/inspect_cmd.py +377 -0
  40. tan/commands/kconfig_cmd.py +734 -0
  41. tan/commands/model_cmd.py +1514 -0
  42. tan/commands/model_device_cmd.py +351 -0
  43. tan/commands/model_device_live.py +234 -0
  44. tan/commands/model_host_cmd.py +430 -0
  45. tan/commands/model_zoo_cmd.py +363 -0
  46. tan/commands/monitor_actions.py +125 -0
  47. tan/commands/monitor_cmd.py +626 -0
  48. tan/commands/monitor_session.py +505 -0
  49. tan/commands/new_som_cmd.py +1522 -0
  50. tan/commands/pinmux_cmd.py +568 -0
  51. tan/commands/presets_cmd.py +1123 -0
  52. tan/commands/probe_cmd.py +421 -0
  53. tan/commands/reset_cmd.py +354 -0
  54. tan/commands/reset_confirm.py +168 -0
  55. tan/commands/run_cmd.py +637 -0
  56. tan/commands/scaffold_cmd.py +490 -0
  57. tan/commands/sdk_cmd.py +1723 -0
  58. tan/commands/size_cmd.py +1020 -0
  59. tan/commands/support_bundle_cmd.py +1073 -0
  60. tan/commands/trace_cmd.py +341 -0
  61. tan/commands/validate_cmd.py +2009 -0
  62. tan/commands/west_forward_cmd.py +736 -0
  63. tan/commands/workspace_patch_check.py +296 -0
  64. tan/core/__init__.py +1 -0
  65. tan/core/alp_conf_pregen.py +100 -0
  66. tan/core/artifact_provenance.py +240 -0
  67. tan/core/atoc_guard.py +276 -0
  68. tan/core/atoc_guard_messages.py +232 -0
  69. tan/core/atoc_replacement.py +118 -0
  70. tan/core/atomic_write.py +178 -0
  71. tan/core/board_context.py +351 -0
  72. tan/core/board_diagnostic.py +111 -0
  73. tan/core/board_files.py +221 -0
  74. tan/core/board_validator.py +542 -0
  75. tan/core/board_validator_compat.py +196 -0
  76. tan/core/board_validator_run.py +129 -0
  77. tan/core/board_validator_schema.py +186 -0
  78. tan/core/board_validator_skew.py +46 -0
  79. tan/core/board_yaml_edit.py +295 -0
  80. tan/core/board_yaml_pos.py +118 -0
  81. tan/core/bootstrap.py +2572 -0
  82. tan/core/build_plan.py +625 -0
  83. tan/core/consent.py +104 -0
  84. tan/core/console_filter.py +245 -0
  85. tan/core/debug_launch.py +1803 -0
  86. tan/core/devicetree_lint.py +168 -0
  87. tan/core/dir_removal.py +229 -0
  88. tan/core/doctor_git.py +172 -0
  89. tan/core/doctor_libraries.py +253 -0
  90. tan/core/doctor_render.py +185 -0
  91. tan/core/doctor_scope.py +66 -0
  92. tan/core/doctor_setools.py +237 -0
  93. tan/core/doctor_stale.py +180 -0
  94. tan/core/document_guards.py +723 -0
  95. tan/core/dp_id.py +97 -0
  96. tan/core/elf_load.py +63 -0
  97. tan/core/error_catalog.py +171 -0
  98. tan/core/example_catalog.py +499 -0
  99. tan/core/example_facets.py +151 -0
  100. tan/core/faultdecode.py +521 -0
  101. tan/core/flash_plan.py +2501 -0
  102. tan/core/flow_d_report.py +381 -0
  103. tan/core/flow_d_uptime.py +164 -0
  104. tan/core/fs_confine.py +130 -0
  105. tan/core/global_flags.py +230 -0
  106. tan/core/host_python.py +210 -0
  107. tan/core/image_bundle.py +247 -0
  108. tan/core/inert.py +147 -0
  109. tan/core/jlink_binary.py +128 -0
  110. tan/core/jlink_probe.py +481 -0
  111. tan/core/jsonc_splice.py +404 -0
  112. tan/core/launch_provenance.py +257 -0
  113. tan/core/link_refusal.py +76 -0
  114. tan/core/metadata_schema.py +376 -0
  115. tan/core/model_check.py +227 -0
  116. tan/core/model_device.py +449 -0
  117. tan/core/model_doctor.py +198 -0
  118. tan/core/model_host.py +48 -0
  119. tan/core/model_list.py +112 -0
  120. tan/core/model_zoo.py +353 -0
  121. tan/core/module_template.py +340 -0
  122. tan/core/mram_link.py +87 -0
  123. tan/core/new_som_ospi.py +94 -0
  124. tan/core/os_class.py +159 -0
  125. tan/core/patch_paths.py +87 -0
  126. tan/core/pending.py +40 -0
  127. tan/core/plain_zephyr_plan.py +138 -0
  128. tan/core/plan_exec.py +373 -0
  129. tan/core/plan_tokens.py +600 -0
  130. tan/core/probe.py +155 -0
  131. tan/core/probe_plan.py +237 -0
  132. tan/core/proxy.py +168 -0
  133. tan/core/publish.py +31 -0
  134. tan/core/python_floor.py +178 -0
  135. tan/core/ram_run.py +694 -0
  136. tan/core/ram_watch.py +231 -0
  137. tan/core/raw_write.py +160 -0
  138. tan/core/reset_plan.py +56 -0
  139. tan/core/run.py +161 -0
  140. tan/core/scaffold.py +2203 -0
  141. tan/core/scaffold_selftest_identity.py +225 -0
  142. tan/core/sdk_default_registry.py +565 -0
  143. tan/core/sdk_discovery.py +996 -0
  144. tan/core/sdk_removal.py +465 -0
  145. tan/core/serial_actions.py +175 -0
  146. tan/core/serial_capture.py +185 -0
  147. tan/core/serial_url.py +45 -0
  148. tan/core/setools.py +608 -0
  149. tan/core/setools_scratch.py +243 -0
  150. tan/core/shapes.py +194 -0
  151. tan/core/size.py +610 -0
  152. tan/core/som_buildability.py +204 -0
  153. tan/core/som_schema_version.py +62 -0
  154. tan/core/subprocess_env.py +201 -0
  155. tan/core/sysbuild_image.py +94 -0
  156. tan/core/system_manifest.py +827 -0
  157. tan/core/text_layout.py +73 -0
  158. tan/core/timestamp.py +182 -0
  159. tan/core/tool_lookup.py +383 -0
  160. tan/core/toolchain_pin.py +117 -0
  161. tan/core/toolchain_provision.py +1224 -0
  162. tan/core/trusted_path.py +134 -0
  163. tan/core/uboot_breakin.py +154 -0
  164. tan/core/uri_reference.py +415 -0
  165. tan/core/user_defines.py +152 -0
  166. tan/core/venv.py +332 -0
  167. tan/core/west_patches.py +143 -0
  168. tan/core/west_workspace_refusal.py +159 -0
  169. tan/core/zephyr_env.py +124 -0
  170. tan/env.py +185 -0
  171. tan/envelope.py +647 -0
  172. tan/exit_codes.py +12 -0
  173. tan/lazy_typer.py +185 -0
  174. tan/model/__init__.py +2 -0
  175. tan/model/_gen_fixture.py +132 -0
  176. tan/model/adapters/__init__.py +116 -0
  177. tan/model/adapters/cpu.py +26 -0
  178. tan/model/adapters/deepx.py +94 -0
  179. tan/model/adapters/drpai.py +242 -0
  180. tan/model/adapters/ethos_u.py +951 -0
  181. tan/model/adapters/executorch.py +55 -0
  182. tan/model/analyze.py +694 -0
  183. tan/model/build.py +304 -0
  184. tan/model/check.py +682 -0
  185. tan/model/manifest.py +625 -0
  186. tan/model/measure.py +216 -0
  187. tan/model/npu_ops_validate.py +130 -0
  188. tan/model/package.py +125 -0
  189. tan/model/perf.py +635 -0
  190. tan/model/perf_apply.py +721 -0
  191. tan/model/prep.py +193 -0
  192. tan/model/sram_fit.py +502 -0
  193. tan/model/targets.py +374 -0
  194. tan/model/tensorio.py +287 -0
  195. tan/net.py +73 -0
  196. tan/output_format.py +213 -0
  197. tan/planner/__init__.py +219 -0
  198. tan/planner/aperture.py +202 -0
  199. tan/planner/buildplan.py +1092 -0
  200. tan/planner/camera_owner.py +192 -0
  201. tan/planner/cameras.py +132 -0
  202. tan/planner/carveout.py +755 -0
  203. tan/planner/cli.py +274 -0
  204. tan/planner/headers.py +315 -0
  205. tan/planner/kconfig.py +2435 -0
  206. tan/planner/kconfig_symbols.py +473 -0
  207. tan/planner/libraries.py +677 -0
  208. tan/planner/link_target.py +237 -0
  209. tan/planner/linux_ownership.py +216 -0
  210. tan/planner/loader.py +1525 -0
  211. tan/planner/manifest.py +116 -0
  212. tan/planner/memory.py +161 -0
  213. tan/planner/memregion.py +56 -0
  214. tan/planner/models.py +533 -0
  215. tan/planner/orchestrator.py +874 -0
  216. tan/planner/ownership.py +203 -0
  217. tan/planner/partition.py +1160 -0
  218. tan/planner/paths.py +32 -0
  219. tan/planner/plain_slice.py +139 -0
  220. tan/planner/project_emit/__init__.py +60 -0
  221. tan/planner/project_emit/bom_netlist.py +375 -0
  222. tan/planner/project_emit/dts.py +580 -0
  223. tan/planner/project_emit/hw_info.py +221 -0
  224. tan/planner/project_emit/native_sim.py +136 -0
  225. tan/planner/project_emit/west_libs.py +213 -0
  226. tan/planner/project_loader.py +264 -0
  227. tan/planner/sdk_capability.py +203 -0
  228. tan/planner/sdk_compat.py +395 -0
  229. tan/planner/secure.py +350 -0
  230. tan/planner/slugs.py +394 -0
  231. tan/planner/som_metadata.py +325 -0
  232. tan/planner/strict_loaders.py +131 -0
  233. tan/planner/template.py +1037 -0
  234. tan/planner/template_pins.py +535 -0
  235. tan/planner/template_rewrite.py +714 -0
  236. tan/planner/topology.py +208 -0
  237. tan/planner/validate.py +365 -0
  238. tan/planner/whole_device_alias.py +67 -0
  239. tan/planner/zephyr_board.py +3510 -0
  240. tan/planner_cli.py +97 -0
  241. tan/planner_emit.py +617 -0
  242. tan/planner_root.py +119 -0
  243. tan/soc_ref.py +58 -0
  244. tan/templates/__init__.py +34 -0
  245. tan/templates/vendored/MANIFEST.md +1862 -0
  246. tan/templates/vendored/diagnostics/E1M-AEN801/CMakeLists.txt +8 -0
  247. tan/templates/vendored/diagnostics/E1M-AEN801/README.md +112 -0
  248. tan/templates/vendored/diagnostics/E1M-AEN801/board.yaml +38 -0
  249. tan/templates/vendored/diagnostics/E1M-AEN801/boards/native_sim_native_64.conf +11 -0
  250. tan/templates/vendored/diagnostics/E1M-AEN801/boards/native_sim_native_64.overlay +29 -0
  251. tan/templates/vendored/diagnostics/E1M-AEN801/prj.conf +5 -0
  252. tan/templates/vendored/diagnostics/E1M-AEN801/src/main.c +266 -0
  253. tan/templates/vendored/diagnostics/E1M-AEN801/testcase.yaml +53 -0
  254. tan/templates/vendored/diagnostics/E1M-V2N101/CMakeLists.txt +8 -0
  255. tan/templates/vendored/diagnostics/E1M-V2N101/README.md +112 -0
  256. tan/templates/vendored/diagnostics/E1M-V2N101/board.yaml +38 -0
  257. tan/templates/vendored/diagnostics/E1M-V2N101/boards/native_sim_native_64.conf +11 -0
  258. tan/templates/vendored/diagnostics/E1M-V2N101/boards/native_sim_native_64.overlay +29 -0
  259. tan/templates/vendored/diagnostics/E1M-V2N101/prj.conf +5 -0
  260. tan/templates/vendored/diagnostics/E1M-V2N101/src/main.c +266 -0
  261. tan/templates/vendored/diagnostics/E1M-V2N101/testcase.yaml +53 -0
  262. tan/templates/vendored/edge-ai/E1M-AEN801/CMakeLists.txt +10 -0
  263. tan/templates/vendored/edge-ai/E1M-AEN801/README.md +75 -0
  264. tan/templates/vendored/edge-ai/E1M-AEN801/board.yaml +38 -0
  265. tan/templates/vendored/edge-ai/E1M-AEN801/prj.conf +8 -0
  266. tan/templates/vendored/edge-ai/E1M-AEN801/src/cold_chain.c +371 -0
  267. tan/templates/vendored/edge-ai/E1M-AEN801/src/cold_chain.h +178 -0
  268. tan/templates/vendored/edge-ai/E1M-AEN801/src/main.c +373 -0
  269. tan/templates/vendored/edge-ai/E1M-AEN801/testcase.yaml +62 -0
  270. tan/templates/vendored/edge-ai/E1M-V2N101/CMakeLists.txt +10 -0
  271. tan/templates/vendored/edge-ai/E1M-V2N101/README.md +75 -0
  272. tan/templates/vendored/edge-ai/E1M-V2N101/board.yaml +37 -0
  273. tan/templates/vendored/edge-ai/E1M-V2N101/prj.conf +8 -0
  274. tan/templates/vendored/edge-ai/E1M-V2N101/src/cold_chain.c +371 -0
  275. tan/templates/vendored/edge-ai/E1M-V2N101/src/cold_chain.h +178 -0
  276. tan/templates/vendored/edge-ai/E1M-V2N101/src/main.c +373 -0
  277. tan/templates/vendored/edge-ai/E1M-V2N101/testcase.yaml +62 -0
  278. tan/templates/vendored/iot/E1M-AEN801/CMakeLists.txt +14 -0
  279. tan/templates/vendored/iot/E1M-AEN801/README.md +103 -0
  280. tan/templates/vendored/iot/E1M-AEN801/board.yaml +69 -0
  281. tan/templates/vendored/iot/E1M-AEN801/prj.conf +15 -0
  282. tan/templates/vendored/iot/E1M-AEN801/src/cc3501e_bridge.c +196 -0
  283. tan/templates/vendored/iot/E1M-AEN801/src/cc3501e_bridge.h +173 -0
  284. tan/templates/vendored/iot/E1M-AEN801/src/main.c +262 -0
  285. tan/templates/vendored/iot/E1M-AEN801/testcase.yaml +68 -0
  286. tan/templates/vendored/minimal/E1M-AEN801/CMakeLists.txt +8 -0
  287. tan/templates/vendored/minimal/E1M-AEN801/README.md +108 -0
  288. tan/templates/vendored/minimal/E1M-AEN801/board.yaml +32 -0
  289. tan/templates/vendored/minimal/E1M-AEN801/prj.conf +8 -0
  290. tan/templates/vendored/minimal/E1M-AEN801/src/main.c +111 -0
  291. tan/templates/vendored/minimal/E1M-AEN801/testcase.yaml +49 -0
  292. tan/templates/vendored/minimal/E1M-V2N101/CMakeLists.txt +8 -0
  293. tan/templates/vendored/minimal/E1M-V2N101/README.md +108 -0
  294. tan/templates/vendored/minimal/E1M-V2N101/board.yaml +32 -0
  295. tan/templates/vendored/minimal/E1M-V2N101/prj.conf +8 -0
  296. tan/templates/vendored/minimal/E1M-V2N101/src/main.c +111 -0
  297. tan/templates/vendored/minimal/E1M-V2N101/testcase.yaml +49 -0
  298. tan/templates/vendored/multicore-mailbox/E1M-AEN801/CMakeLists.txt +8 -0
  299. tan/templates/vendored/multicore-mailbox/E1M-AEN801/README.md +120 -0
  300. tan/templates/vendored/multicore-mailbox/E1M-AEN801/board.yaml +57 -0
  301. tan/templates/vendored/multicore-mailbox/E1M-AEN801/boards/native_sim_native_64.overlay +40 -0
  302. tan/templates/vendored/multicore-mailbox/E1M-AEN801/peer/CMakeLists.txt +13 -0
  303. tan/templates/vendored/multicore-mailbox/E1M-AEN801/peer/main.c +171 -0
  304. tan/templates/vendored/multicore-mailbox/E1M-AEN801/peer/prj.conf +17 -0
  305. tan/templates/vendored/multicore-mailbox/E1M-AEN801/peer/testcase.yaml +23 -0
  306. tan/templates/vendored/multicore-mailbox/E1M-AEN801/prj.conf +22 -0
  307. tan/templates/vendored/multicore-mailbox/E1M-AEN801/src/main.c +185 -0
  308. tan/templates/vendored/multicore-mailbox/E1M-AEN801/testcase.yaml +26 -0
  309. tan/templates/vendored/sensor/E1M-AEN801/CMakeLists.txt +8 -0
  310. tan/templates/vendored/sensor/E1M-AEN801/README.md +112 -0
  311. tan/templates/vendored/sensor/E1M-AEN801/board.yaml +57 -0
  312. tan/templates/vendored/sensor/E1M-AEN801/boards/native_sim_native_64.conf +10 -0
  313. tan/templates/vendored/sensor/E1M-AEN801/boards/native_sim_native_64.overlay +28 -0
  314. tan/templates/vendored/sensor/E1M-AEN801/prj.conf +5 -0
  315. tan/templates/vendored/sensor/E1M-AEN801/src/main.c +186 -0
  316. tan/templates/vendored/sensor/E1M-AEN801/testcase.yaml +52 -0
  317. tan/templates/vendored/sensor/E1M-V2N101/CMakeLists.txt +8 -0
  318. tan/templates/vendored/sensor/E1M-V2N101/README.md +112 -0
  319. tan/templates/vendored/sensor/E1M-V2N101/board.yaml +57 -0
  320. tan/templates/vendored/sensor/E1M-V2N101/boards/native_sim_native_64.conf +10 -0
  321. tan/templates/vendored/sensor/E1M-V2N101/boards/native_sim_native_64.overlay +28 -0
  322. tan/templates/vendored/sensor/E1M-V2N101/prj.conf +5 -0
  323. tan/templates/vendored/sensor/E1M-V2N101/src/main.c +186 -0
  324. tan/templates/vendored/sensor/E1M-V2N101/testcase.yaml +52 -0
  325. tan/version.py +102 -0
  326. tan_cli-0.7.0.dist-info/METADATA +125 -0
  327. tan_cli-0.7.0.dist-info/RECORD +330 -0
  328. tan_cli-0.7.0.dist-info/WHEEL +5 -0
  329. tan_cli-0.7.0.dist-info/entry_points.txt +2 -0
  330. tan_cli-0.7.0.dist-info/top_level.txt +1 -0
tan/core/atoc_guard.py ADDED
@@ -0,0 +1,276 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Flow A's half of the whole-ATOC guard (tan-cli#1267). Pure -- no IO.
3
+
4
+ A `zephyr_west_flash` slice that stays on Flow A runs `west flash`, which on
5
+ an Alif Ensemble board picks the board.cmake default runner `alif_flash` and
6
+ burns over the SE-UART. That write REPLACES the whole ATOC, the same as Flow
7
+ D's -- but unlike Flow D, the runner can ask the part what is resident first.
8
+ alp-sdk#2262 (PR alp-sdk#2275, in tan's pin since #1301) made it do exactly
9
+ that: before burning, `alif_flash` reads the resident ATOC back over the
10
+ SE-UART and refuses when a foreign entry would be delisted or the read could
11
+ not be verified, unless `--replace-atoc` is passed. Every attempt leaves a
12
+ machine-readable verdict, `<build_dir>/alif_flash/atoc-guard.json`, whose
13
+ shape alp-sdk freezes as `alp-sdk.alif-flash-atoc-guard.v1`
14
+ (`docs/aen-provisioning.md` section 0.6). tan's half, all decided here:
15
+
16
+ * pass `--replace-atoc` through to `west flash` -- and only to a slice whose
17
+ runner is `alif_flash`, from a module whose runner has the guard
18
+ ([`decide_replace_atoc`]), and only to ONE such slice per run
19
+ ([`ambiguous_replace_message`]);
20
+ * read the verdict when `west flash` exits ([`parse_verdict`]);
21
+ * turn a refusal into its own message ([`refusal_message`]), which the CLI
22
+ reports under its own issue code. The message texts live in
23
+ `tan.core.atoc_guard_messages`.
24
+
25
+ `--replace-atoc` is NOT `--atoc-unqueryable` and the two are never merged or
26
+ aliased (alp-sdk#2025's header, repeated by the runner's own help). Flow D's
27
+ flag acknowledges a write that cannot be checked; this one overrides a check
28
+ that ran. An operator on a no-SE-UART bench passes the Flow D flag on every
29
+ run, so a flag that answered both would silence the one guard that can look
30
+ first.
31
+
32
+ **No manifest spelling, unlike Flow D's `flash_args.atoc_unqueryable`.** That
33
+ key exists because Flow D can never query, so a manifest that knows its own
34
+ boot layout can record the acknowledgement once. Flow A's guard does query:
35
+ a persisted override would turn off a working check for every later run,
36
+ including the one where the board carries something new. The override is a
37
+ statement about what is resident on the board right now, so it is re-stated
38
+ per invocation. `tan run --flash` regenerates the manifest anyway, so a key
39
+ would not survive there either.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import json
45
+ import re
46
+ from dataclasses import dataclass
47
+
48
+ from tan.core.atoc_guard_messages import (
49
+ FLOW_D_ACK_FLAG,
50
+ REPLACE_ATOC_FLAG,
51
+ not_applicable_message,
52
+ unguarded_message,
53
+ )
54
+
55
+ #: The west runner that carries the guard. A runner NAME, not a part number:
56
+ #: tan decides applicability from the build's own `runners.yaml` (or an
57
+ #: explicit `flash_args.runner`), never from silicon knowledge (ADR-0017).
58
+ ALIF_FLASH_RUNNER = "alif_flash"
59
+
60
+ #: The Zephyr module name alp-sdk declares in its `zephyr/module.yml`
61
+ #: (`name: alp-sdk`) -- the key `zephyr_modules.txt` lists it under.
62
+ SDK_MODULE_NAME = "alp-sdk"
63
+
64
+ VERDICT_SCHEMA = "alp-sdk.alif-flash-atoc-guard.v1"
65
+ VERDICT_DIR = "alif_flash"
66
+ VERDICT_FILE = "atoc-guard.json"
67
+
68
+ REFUSED_FOREIGN = "refused-foreign"
69
+ REFUSED_UNVERIFIED = "refused-unverified"
70
+ REPLACED = "replaced"
71
+ #: Every `status` the v1 contract defines. Anything else is a verdict tan
72
+ #: cannot read, never a guess.
73
+ VERDICT_STATUSES = ("clear", "empty", REFUSED_FOREIGN, REFUSED_UNVERIFIED, REPLACED)
74
+ QUERY_STATUSES = ("unverified", "empty", "ok")
75
+
76
+ #: The module-relative path of the runner whose source tan reads to learn
77
+ #: whether it has the guard -- the `runners: - file:` alp-sdk's
78
+ #: `zephyr/module.yml` declares. Path segments, joined by the caller.
79
+ RUNNER_SOURCE_PARTS = ("scripts", "west_commands", "runners", "alif_flash.py")
80
+
81
+ _FLASH_RUNNER_RE = re.compile(r"^flash-runner:[ \t]*['\"]?([^'\"\s#]+)", re.MULTILINE)
82
+ _MODULE_LINE_RE = re.compile(r'^"([^"]*)":"([^"]*)":')
83
+
84
+
85
+ def parse_flash_runner(runners_yaml: str) -> str | None:
86
+ """The build's default flash runner out of Zephyr's
87
+ `<build_dir>/zephyr/runners.yaml` -- the top-level `flash-runner:` line
88
+ `west flash` itself falls back to when no `--runner` is given. `None`
89
+ when absent."""
90
+ match = _FLASH_RUNNER_RE.search(runners_yaml)
91
+ return match.group(1) if match else None
92
+
93
+
94
+ def parse_module_dir(zephyr_modules_txt: str, name: str = SDK_MODULE_NAME) -> str | None:
95
+ """The module root `name` was built from, out of Zephyr's
96
+ `<build_dir>/zephyr_modules.txt` (one `"<name>":"<path>":"<cmake>"` line
97
+ per module, written by `zephyr_module.py --cmake-out` at configure time).
98
+ This is the checkout `west flash` imports the module's runners from,
99
+ which need not be the SDK tan is bound to. `None` when not listed."""
100
+ for line in zephyr_modules_txt.splitlines():
101
+ match = _MODULE_LINE_RE.match(line.strip())
102
+ if match and match.group(1) == name:
103
+ return match.group(2)
104
+ return None
105
+
106
+
107
+ def parse_domain_build_dirs(domains_yaml: str) -> list[str] | None:
108
+ """Every domain's build dir out of a sysbuild's top-level `domains.yaml`
109
+ (Zephyr's `domains:` list of `{name, build_dir}`), in file order. `None`
110
+ when the text is not that shape. `west flash` with no `--domain` runs
111
+ the board's runner once per domain, each with that domain's own
112
+ `build_dir` -- which is where the verdict lands. PyYAML is imported
113
+ here, not at module scope: `import tan.cli` must not pay for it
114
+ (tan-cli#810, `tests/gates/test_cli_import_is_lean.py`)."""
115
+ import yaml # noqa: PLC0415
116
+
117
+ try:
118
+ doc = yaml.safe_load(domains_yaml)
119
+ except yaml.YAMLError:
120
+ return None
121
+ domains = doc.get("domains") if isinstance(doc, dict) else None
122
+ if not isinstance(domains, list) or not domains:
123
+ return None
124
+ dirs = [d.get("build_dir") for d in domains if isinstance(d, dict)]
125
+ if len(dirs) != len(domains) or not all(isinstance(d, str) and d for d in dirs):
126
+ return None
127
+ return dirs
128
+
129
+
130
+ def runner_has_guard(runner_source: str) -> bool:
131
+ """Does this `alif_flash.py` source carry the #2262 guard? Both halves
132
+ are required: the `--replace-atoc` argument (west rejects an unknown one,
133
+ so tan must never pass it blind) and the v1 verdict schema (what tan reads
134
+ back). They landed together in alp-sdk PR #2275."""
135
+ return f"'{REPLACE_ATOC_FLAG}'" in runner_source and VERDICT_SCHEMA in runner_source
136
+
137
+
138
+ # ── which slices the flag applies to ─────────────────────────────────────────
139
+
140
+ #: `ReplaceAtocDecision.warning_kind` values. The CLI maps each to its own
141
+ #: issue code.
142
+ NOT_APPLICABLE = "not-applicable"
143
+ UNGUARDED = "unguarded"
144
+
145
+
146
+ @dataclass(frozen=True)
147
+ class RunnerFacts:
148
+ """What tan learnt about the runner one west entry will reach.
149
+
150
+ `runner`: the effective west runner, `None` when unknown, with
151
+ `unknown_reason` saying why. `source`: the `alif_flash.py` tan checked,
152
+ `origin` where that path came from (the build's module list, or the
153
+ bound SDK as a fallback). `has_guard`: whether that source has the guard
154
+ (`None` when not checked). `verdict_dir`: the dir the runner's verdict
155
+ lands under (the single sysbuild domain's, or `--build-dir` itself)."""
156
+
157
+ runner: str | None = None
158
+ unknown_reason: str | None = None
159
+ source: str = ""
160
+ origin: str = ""
161
+ has_guard: bool | None = None
162
+ verdict_dir: str = ""
163
+
164
+
165
+ @dataclass(frozen=True)
166
+ class ReplaceAtocDecision:
167
+ """What tan does about the guard for one entry.
168
+
169
+ `append`: put `--replace-atoc` on the `west flash` argv. `guarded`: this
170
+ entry runs a runner that writes a verdict, so the outcome is checked
171
+ against it. `warning`/`warning_kind`: a disclosure, or `None`.
172
+ `source`: the runner file checked, for later messages."""
173
+
174
+ append: bool = False
175
+ guarded: bool = False
176
+ warning: str | None = None
177
+ warning_kind: str | None = None
178
+ source: str = ""
179
+
180
+
181
+ def decide_replace_atoc(
182
+ method: str, entry_id: str, facts: RunnerFacts, replace_atoc: bool
183
+ ) -> ReplaceAtocDecision:
184
+ """Pure. `method` is the DISPATCHED method (Flow D already selected)."""
185
+ if method != "zephyr_west_flash" or facts.runner != ALIF_FLASH_RUNNER:
186
+ if not replace_atoc:
187
+ return ReplaceAtocDecision()
188
+ return ReplaceAtocDecision(
189
+ warning=not_applicable_message(
190
+ method, entry_id, facts.runner, facts.unknown_reason, ALIF_FLASH_RUNNER
191
+ ),
192
+ warning_kind=NOT_APPLICABLE,
193
+ )
194
+ if not facts.has_guard:
195
+ return ReplaceAtocDecision(
196
+ warning=unguarded_message(entry_id, facts.source, facts.origin, replace_atoc),
197
+ warning_kind=UNGUARDED,
198
+ source=facts.source,
199
+ )
200
+ return ReplaceAtocDecision(append=replace_atoc, guarded=True, source=facts.source)
201
+
202
+
203
+ # ── reading the verdict ──────────────────────────────────────────────────────
204
+
205
+
206
+ @dataclass(frozen=True)
207
+ class GuardVerdict:
208
+ """A verdict that matched the v1 contract."""
209
+
210
+ status: str
211
+ foreign: tuple[str, ...]
212
+ transcript: str
213
+ query_status: str
214
+ allowed: tuple[str, ...] = ()
215
+
216
+ @property
217
+ def refused(self) -> bool:
218
+ return self.status in (REFUSED_FOREIGN, REFUSED_UNVERIFIED)
219
+
220
+
221
+ def _str_list(value: object) -> bool:
222
+ return isinstance(value, list) and all(isinstance(n, str) for n in value)
223
+
224
+
225
+ def parse_verdict(text: str) -> GuardVerdict | str:
226
+ """The verdict, or a one-line reason it cannot be read. Strict: an
227
+ unknown schema, status or query_status, a field of the wrong type, or a
228
+ combination the runner cannot produce ([`_inconsistency`]) is unreadable
229
+ -- tan never reports a refusal the runner did not state."""
230
+ try:
231
+ raw = json.loads(text)
232
+ except ValueError as err:
233
+ return f"it is not valid JSON ({err})"
234
+ if not isinstance(raw, dict):
235
+ return "it is not a JSON object"
236
+ if raw.get("schema") != VERDICT_SCHEMA:
237
+ return f"its schema is {raw.get('schema')!r}, not {VERDICT_SCHEMA!r}"
238
+ status, query = raw.get("status"), raw.get("query_status")
239
+ if status not in VERDICT_STATUSES:
240
+ return f"its status {status!r} is not one {VERDICT_SCHEMA} defines"
241
+ if query not in QUERY_STATUSES:
242
+ return f"its query_status {query!r} is not one {VERDICT_SCHEMA} defines"
243
+ for field in ("foreign", "allowed"):
244
+ if not _str_list(raw.get(field)):
245
+ return f"its {field} field is not a list of strings"
246
+ if not isinstance(raw.get("transcript"), str):
247
+ return "its transcript field is not a string"
248
+ verdict = GuardVerdict(
249
+ status, tuple(raw["foreign"]), raw["transcript"], query, tuple(raw["allowed"])
250
+ )
251
+ problem = _inconsistency(verdict)
252
+ return verdict if problem is None else problem
253
+
254
+
255
+ def _inconsistency(v: GuardVerdict) -> str | None:
256
+ """A status/query_status/foreign combination alp-sdk's `decide_atoc_guard`
257
+ (`scripts/aen_atoc.py`, which the runner writes the verdict from) cannot
258
+ produce. Its rules, and the contract's own reading of `replaced`
259
+ (`query_status == "unverified"` with `foreign == []`, or any other
260
+ query_status with a non-empty `foreign`): an unverified query is decided
261
+ before the foreign check, so its `foreign` is always `[]`; `empty` means
262
+ no ATOC was found, so nothing can be foreign."""
263
+ expected = {
264
+ REFUSED_FOREIGN: v.query_status == "ok" and bool(v.foreign),
265
+ REFUSED_UNVERIFIED: v.query_status == "unverified" and not v.foreign,
266
+ REPLACED: (v.query_status == "unverified" and not v.foreign)
267
+ or (v.query_status == "ok" and bool(v.foreign)),
268
+ "clear": v.query_status == "ok" and not v.foreign,
269
+ "empty": v.query_status == "empty" and not v.foreign,
270
+ }[v.status]
271
+ if expected:
272
+ return None
273
+ return (
274
+ f"its status {v.status!r} with query_status {v.query_status!r} and foreign "
275
+ f"{list(v.foreign)!r} is a combination {VERDICT_SCHEMA} does not produce"
276
+ )
@@ -0,0 +1,232 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Every operator-facing sentence of Flow A's whole-ATOC guard (tan-cli#1267).
3
+ Pure. The decisions live in `tan.core.atoc_guard`; these functions only word
4
+ them, so a message can be read (and pinned by a test) in one place.
5
+
6
+ Verdict-taking functions accept any object with the `GuardVerdict` fields
7
+ (`status`, `foreign`, `transcript`, `query_status`, `allowed`) -- typed
8
+ loosely so this module need not import the one that imports it.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from typing import Any, Iterable, Mapping
15
+
16
+ #: Spelled exactly as alp-sdk's runner `do_add_parser` registers it.
17
+ REPLACE_ATOC_FLAG = "--replace-atoc"
18
+
19
+ #: The Flow D acknowledgement -- named here only so messages can say it does
20
+ #: NOT answer this guard. `test_atoc_guard` pins it equal to
21
+ #: `flash_plan.ATOC_ACK_FLAG`.
22
+ FLOW_D_ACK_FLAG = "--atoc-unqueryable"
23
+
24
+ #: The runner's own name for a factory-provisioned module's MCUboot ATOC
25
+ #: entry (`_FACTORY_MCUBOOT_ATOC_NAME` in alp-sdk's
26
+ #: `scripts/west_commands/runners/alif_flash.py`, itself marked TBD there).
27
+ #: The runner steers AWAY from `--replace-atoc` when it is among the foreign
28
+ #: entries, because deleting it leaves the module unable to boot; tan's
29
+ #: message follows it rather than inviting the override.
30
+ FACTORY_MCUBOOT_ATOC_NAME = "MCUBOOT-"
31
+
32
+ #: alp-sdk's documented way to put BOTH M55 cores into one ATOC over the
33
+ #: SE-UART (`docs/aen-bench-bringup.md`, "Flow A -- Dual-core deferred-TOC
34
+ #: boot", at tan's pin): one burn carrying both entries, HP-master shape.
35
+ DUAL_CORE_PATH = (
36
+ "alp-sdk's scripts/bench/aen/flash-run-dualcore.sh <hp-build-dir> <he-build-dir>, "
37
+ "which burns one ATOC carrying both cores' entries (docs/aen-bench-bringup.md, "
38
+ "\"Flow A -- Dual-core deferred-TOC boot\"; it emits the HP-master shape, and an "
39
+ "HE-master ATOC is not scripted)"
40
+ )
41
+
42
+
43
+ def not_applicable_message(
44
+ method: str, entry_id: str, runner: str | None, unknown_reason: str | None, alif: str
45
+ ) -> str:
46
+ head = f"{method}[{entry_id}]: {REPLACE_ATOC_FLAG} was not passed to this entry"
47
+ if method == "alif_mram_jlink":
48
+ why = (
49
+ "it dispatches Flow D (alif_mram_jlink), which has no SE-UART query to "
50
+ f"override. Flow D's whole-ATOC acknowledgement is {FLOW_D_ACK_FLAG}, a "
51
+ f"different flag on purpose; {REPLACE_ATOC_FLAG} does not stand in for it"
52
+ )
53
+ elif method != "zephyr_west_flash":
54
+ why = f"{REPLACE_ATOC_FLAG} applies only to the {alif} west runner"
55
+ elif runner is None:
56
+ why = f"tan could not learn which west runner it uses: {unknown_reason}"
57
+ else:
58
+ why = f"its west runner is {runner}, not {alif}, and only {alif} has the pre-burn ATOC guard"
59
+ return f"{head}: {why}."
60
+
61
+
62
+ def unguarded_message(entry_id: str, source: str, origin: str, replace_atoc: bool) -> str:
63
+ """An `alif_flash` slice whose runner has no guard. Said plainly, so a
64
+ green run is never read as a checked one."""
65
+ passed = (
66
+ f" {REPLACE_ATOC_FLAG} was NOT passed: that runner does not accept it, "
67
+ "and west would reject the whole command."
68
+ if replace_atoc
69
+ else ""
70
+ )
71
+ return (
72
+ f"zephyr_west_flash[{entry_id}]: this write goes through the alif_flash west "
73
+ f"runner, and the runner tan checked -- {source} ({origin}) -- has no pre-burn "
74
+ "ATOC guard (alp-sdk#2262), or could not be read. The write REPLACES the whole "
75
+ "ATOC: any resident entry it does not name (an A32 boot chain, the other core's "
76
+ f"app, a factory MCUboot) is silently delisted, and nothing checks first.{passed} "
77
+ "Build against an alp-sdk whose runner has the guard (tan-cli#1267)."
78
+ )
79
+
80
+
81
+ def no_verdict_after_success(entry_id: str, reason: str, source: str) -> str:
82
+ """`west flash` succeeded on an entry tan treated as guarded, but there is
83
+ no usable verdict: the guard did not run for this write."""
84
+ return (
85
+ f"zephyr_west_flash[{entry_id}]: west flash succeeded, but the alif_flash "
86
+ f"runner's ATOC guard verdict is unusable ({reason}). tan checked {source} and "
87
+ "found the guard there, so west most likely loaded a different alif_flash "
88
+ "runner, one without it. Treat this write as UNGUARDED: it replaced the whole "
89
+ "ATOC, and any resident entry it did not name may now be delisted (tan-cli#1267)."
90
+ )
91
+
92
+
93
+ def ambiguous_replace_message(entry_ids: list[str]) -> str:
94
+ """`--replace-atoc` would reach more than one alif_flash write in one run."""
95
+ names = ", ".join(entry_ids)
96
+ return (
97
+ f"flash: {REPLACE_ATOC_FLAG} would reach {len(entry_ids)} alif_flash writes in "
98
+ f"this run ({names}). Each one REPLACES the whole ATOC with only its own entry, "
99
+ "so the flag given to accept losing what is on the board now would also "
100
+ "override the next write's guard into delisting what the previous write in "
101
+ "this same run had just put there. Nothing was flashed. Narrow the run to one "
102
+ f"entry with --core CORE_ID (or --helper NAME) and pass {REPLACE_ATOC_FLAG} only "
103
+ "there. Flashing several cores this way leaves only the last one listed; to "
104
+ f"put both M55 cores in the ATOC use {DUAL_CORE_PATH} (tan-cli#1267)."
105
+ )
106
+
107
+
108
+ def refusal_message(entry_id: str, verdict: Any, earlier: Mapping[str, str]) -> str:
109
+ """A refused verdict. `earlier` maps each ATOC section an EARLIER entry of
110
+ this run wrote to that entry's id."""
111
+ head = (
112
+ f"zephyr_west_flash[{entry_id}]: the alif_flash runner's pre-burn ATOC guard "
113
+ f"refused this write before anything was burned (status: {verdict.status}; "
114
+ f"transcript: {verdict.transcript})."
115
+ )
116
+ if verdict.status == "refused-unverified":
117
+ return f"{head} {_unverified_body()}"
118
+ own = [name for name in verdict.foreign if name in earlier]
119
+ if own:
120
+ return f"{head} {_sequential_body(own, earlier)}"
121
+ return f"{head} {_foreign_body(verdict.foreign)}"
122
+
123
+
124
+ def _unverified_body() -> str:
125
+ return (
126
+ "It could not verify what is resident in the ATOC over the SE-UART "
127
+ "(maintenance getbanner/gettoc). The write REPLACES every app entry not "
128
+ "in it, so writing blind could silently delist anything already on the "
129
+ "board -- on a factory-provisioned Alp Lab module that includes its "
130
+ f"MCUboot bootloader, which {REPLACE_ATOC_FLAG} would then delete without ever "
131
+ "naming it. Check the SE-UART wiring and SE_UART, read the transcript, "
132
+ f"confirm by hand what is resident, and re-run with {REPLACE_ATOC_FLAG} only "
133
+ "once you know it is safe to lose. If the runner's own message says the "
134
+ "read succeeded but its table format was not recognised, file the "
135
+ f"transcript instead: {REPLACE_ATOC_FLAG} is not the answer there. "
136
+ f"{FLOW_D_ACK_FLAG} does not answer this guard."
137
+ )
138
+
139
+
140
+ def _sequential_body(own: list[str], earlier: Mapping[str, str]) -> str:
141
+ written = ", ".join(f"{name} (written by {earlier[name]})" for name in own)
142
+ return (
143
+ f"The resident entry it would delist is {written}, written earlier in this same "
144
+ "run. This manifest cannot be Flow A-flashed one core after another: every "
145
+ "alif_flash write REPLACES the whole ATOC with only its own entry, so each core "
146
+ f"delists the one flashed before it. {REPLACE_ATOC_FLAG} is NOT the fix here -- "
147
+ "it would delist that entry again. To put both cores in the ATOC use "
148
+ f"{DUAL_CORE_PATH}."
149
+ )
150
+
151
+
152
+ def _foreign_body(foreign: tuple[str, ...]) -> str:
153
+ names = ", ".join(foreign)
154
+ lead = (
155
+ "The write REPLACES the whole ATOC -- it does not merge -- and the board "
156
+ f"also carries: {names}."
157
+ )
158
+ if FACTORY_MCUBOOT_ATOC_NAME in foreign:
159
+ return (
160
+ f"{lead} That includes the factory-provisioned "
161
+ f"{FACTORY_MCUBOOT_ATOC_NAME!r} MCUboot bootloader: burning would delist "
162
+ "it and leave the module unable to boot until MCUboot is "
163
+ "reprovisioned. Load your app without disturbing it instead -- a "
164
+ "J-Link loadbin of your imgtool-signed image straight to slot0 "
165
+ "(alp-sdk docs/aen-provisioning.md section 0.5, Option B). "
166
+ f"{REPLACE_ATOC_FLAG} still overrides this refusal, but it deletes "
167
+ f"{FACTORY_MCUBOOT_ATOC_NAME!r}."
168
+ )
169
+ return (
170
+ f"{lead} Burning would have silently delisted {names}. Capture or restore "
171
+ f"{names} first (alp-sdk docs/aen-provisioning.md), then re-run with "
172
+ f"{REPLACE_ATOC_FLAG} -- or pass it now only if losing them is intended. "
173
+ f"{FLOW_D_ACK_FLAG} does not answer this guard."
174
+ )
175
+
176
+
177
+ def unreadable_note(reason: str) -> str:
178
+ """Appended to a failure (or success) on a guarded runner whose verdict
179
+ tan could not use. Says what is not known, invents nothing."""
180
+ return (
181
+ f" The alif_flash ATOC guard verdict could not be read ({reason}), so tan "
182
+ "cannot say what the guard decided for this write; see west's own output."
183
+ )
184
+
185
+
186
+ def passed_note(verdict: Any, *, failed: bool = False) -> str:
187
+ """The guard's outcome for a verdict that did NOT refuse. On a failed
188
+ write, an override is reported as an override, not as a done deletion."""
189
+ if verdict.status != "replaced":
190
+ return f"ATOC guard: {verdict.status}"
191
+ if verdict.query_status == "unverified":
192
+ return f"ATOC guard: {REPLACE_ATOC_FLAG} overrode an UNVERIFIED read of the resident ATOC"
193
+ names = ", ".join(verdict.foreign)
194
+ if failed:
195
+ return (
196
+ f"ATOC guard: {REPLACE_ATOC_FLAG} overrode {names}; the write then failed, so "
197
+ f"whether {names} is still listed is unknown"
198
+ )
199
+ return f"ATOC guard: {REPLACE_ATOC_FLAG} overrode resident entries, now delisted: {names}"
200
+
201
+
202
+ #: Two host-setup notices west prints whatever the write's outcome
203
+ #: (tan-cli#1426), each matched by its WORDING, never by its logger: zephyr's
204
+ #: runner loader failing to import a runner module (`runners/__init__.py`,
205
+ #: `_import_runner_module`), and a runner saying an optional Python package is
206
+ #: missing (alif_flash's `fdt` hint for app-gen-toc, logged from `do_run`).
207
+ #: Keying on the `WARNING: runners.<name>:` prefix alone would also take a
208
+ #: warning the runner's own ATOC guard might log, and label it unrelated.
209
+ _RUNNER_SETUP_NOISE = (
210
+ re.compile(r'^(?:WARNING: )?The module for runner "[^"]+" could not be imported\b'),
211
+ re.compile(r"^WARNING: runners\.[\w.]+: the '[^']+' Python package\b[^.]*\bwas not found\b"),
212
+ )
213
+
214
+
215
+ def split_runner_setup_noise(lines: Iterable[str]) -> tuple[list[str], list[str]]:
216
+ """`(kept, noise)`: `lines` with west's runner-loading warnings moved out,
217
+ order preserved on both sides."""
218
+ kept: list[str] = []
219
+ noise: list[str] = []
220
+ for line in lines:
221
+ is_noise = any(p.match(line.strip()) for p in _RUNNER_SETUP_NOISE)
222
+ (noise if is_noise else kept).append(line)
223
+ return kept, noise
224
+
225
+
226
+ def runner_setup_note(entry_id: str, noise: Iterable[str]) -> str:
227
+ """The warning that carries what a refusal's message no longer does."""
228
+ return (
229
+ f"zephyr_west_flash[{entry_id}]: west also printed runner setup warnings, "
230
+ "unrelated to the ATOC guard's refusal (a west runner or a Python package it "
231
+ f"imports is missing from this environment): {' | '.join(n.strip() for n in noise)}"
232
+ )
@@ -0,0 +1,118 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """What a Flow D write does to the boot table, spelled out (tan-cli#1322).
3
+
4
+ A Flow D `loadbin` of the ATOC REPLACES the whole table (tan-cli#1252). The
5
+ generic acknowledgement text says so, but an operator reading it cannot tell
6
+ WHICH entries survive. This module adds the specifics tan can honestly know:
7
+
8
+ * the entries the new ATOC will carry -- `DEVICE` (unless `--no-device-config`)
9
+ and the entry being written -- known BEFORE anything is signed, so the refusal
10
+ can name them, and known exactly from the signed report once it exists, so a
11
+ preview can name those instead;
12
+ * the resident entries that will NOT be rewritten -- known only when the
13
+ operator supplies them (`flash_args.resident_atoc_entries`, e.g. read off the
14
+ SE-UART `maintenance -opt gettoc` output), because Flow D itself has no
15
+ SE-UART channel to enumerate the resident table. When they are not supplied
16
+ the text says they are unknown rather than implying there are none.
17
+
18
+ Pure: no IO.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import re
23
+ from collections.abc import Sequence
24
+ from typing import Any
25
+
26
+ from tan.core.flash_plan import FlashPlanError, _fa_has_key
27
+
28
+ #: The optional manifest key listing the entries resident on the board.
29
+ RESIDENT_KEY = "resident_atoc_entries"
30
+
31
+ _RESIDENT_ITEM = re.compile(r"^([^@\s]+)(?:@(0[xX][0-9A-Fa-f]+)(?:\+(0[xX][0-9A-Fa-f]+))?)?$")
32
+
33
+ #: The `DEVICE` entry name (`app-gen-toc`'s own spelling).
34
+ DEVICE_ENTRY = "DEVICE"
35
+
36
+
37
+ def written_entries(
38
+ entry_id: str, *more: str, device_config: bool
39
+ ) -> tuple[str, ...]:
40
+ """The entry names the new ATOC will carry, in table order, as known
41
+ without signing: `DEVICE` (when a device config is included) then the
42
+ entry itself, then any further slices signed into the same ATOC (`more`,
43
+ tan-cli#1509)."""
44
+ return ((DEVICE_ENTRY,) if device_config else ()) + (entry_id, *more)
45
+
46
+
47
+ def resident_regions(flash_args: Any) -> tuple[tuple[str, int | None, int | None], ...] | None:
48
+ """`flash_args.resident_atoc_entries` as `(name, address, size)` tuples, or
49
+ `None` when the key is absent (the resident table is unknown). Each item is
50
+ `NAME`, `NAME@0xADDR` or `NAME@0xADDR+0xSIZE`; the address (and size) are what
51
+ let tan refuse a write whose sectors would erase that entry
52
+ (`flash.write-sector-overlap`). A present but malformed value raises
53
+ `FlashPlanError`: guessing here would understate what a write deletes."""
54
+ if not _fa_has_key(flash_args, RESIDENT_KEY):
55
+ return None
56
+ raw = flash_args[RESIDENT_KEY]
57
+ bad = FlashPlanError(
58
+ f"alif_mram_jlink: flash_args.{RESIDENT_KEY} must be a list of ATOC entry names, "
59
+ f"each NAME, NAME@0xADDR or NAME@0xADDR+0xSIZE (e.g. [DEVICE, ALP-HE@0x80010000+0x4000]); "
60
+ f"got {raw!r}"
61
+ )
62
+ if not isinstance(raw, list):
63
+ raise bad
64
+ out: list[tuple[str, int | None, int | None]] = []
65
+ for item in raw:
66
+ if not isinstance(item, str) or not item.strip():
67
+ raise bad
68
+ match = _RESIDENT_ITEM.match(item.strip())
69
+ if match is None:
70
+ raise bad
71
+ name, addr, size = match.groups()
72
+ out.append((name, int(addr, 16) if addr else None, int(size, 16) if size else None))
73
+ return tuple(out)
74
+
75
+
76
+ def resident_entries(flash_args: Any) -> tuple[str, ...] | None:
77
+ """The NAMES in `flash_args.resident_atoc_entries`, or `None` when absent."""
78
+ regions = resident_regions(flash_args)
79
+ return None if regions is None else tuple(name for name, _a, _s in regions)
80
+
81
+
82
+ def replacement_detail(
83
+ writes: Sequence[str],
84
+ resident: Sequence[str] | None,
85
+ *,
86
+ device_config: bool,
87
+ left_out: Sequence[str] = (),
88
+ ) -> str:
89
+ """The sentence appended to the whole-ATOC refusal and preview note.
90
+ `left_out` (tan-cli#1509) names the manifest's other `alif_mram_jlink` slices
91
+ this run does not flash: they are in the manifest, so tan KNOWS they are
92
+ delisted whatever `resident_atoc_entries` says."""
93
+ parts = [f"This ATOC names: {', '.join(writes)}."]
94
+ if left_out:
95
+ parts.append(
96
+ f"The manifest's other alif_mram_jlink slice(s) ({', '.join(left_out)}) are NOT "
97
+ "named, so they will be delisted too -- drop --core to flash them in the same ATOC."
98
+ )
99
+ if not device_config:
100
+ parts.append(
101
+ "It carries NO DEVICE entry (--no-device-config), so the resident DEVICE "
102
+ "entry -- firewall regions, HFXO trims, SE_BOOT_INFO -- is deleted."
103
+ )
104
+ if resident is None:
105
+ parts.append(
106
+ "The resident table is UNKNOWN (Flow D cannot enumerate it): every entry "
107
+ "not named above will be delisted. Read it first over the SE-UART "
108
+ f"(`maintenance -opt gettoc`) and list it in flash_args.{RESIDENT_KEY} to "
109
+ "have tan name them."
110
+ )
111
+ else:
112
+ lost = [n for n in resident if n not in set(writes)]
113
+ parts.append(
114
+ "Resident entries that will NOT be rewritten (delisted): "
115
+ + (", ".join(lost) if lost else "none")
116
+ + "."
117
+ )
118
+ return " ".join(parts)