validate_desired_state.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. import argparse
  2. import sys
  3. from pathlib import Path, PurePosixPath
  4. import yaml
  5. def safe_relative_path(value):
  6. if not isinstance(value, str) or not value:
  7. return False
  8. path = PurePosixPath(value)
  9. return not path.is_absolute() and ".." not in path.parts
  10. def validate_mod_host_chain(routing, source_by_id):
  11. errors = []
  12. chains = routing.get("mod_host_chains")
  13. if not isinstance(chains, dict):
  14. return ["routing.mod_host_chains must be a mapping"]
  15. if not isinstance(chains, dict) or set(chains) != {"guitar", "voice"}:
  16. errors.append("routing.mod_host_chains must declare exactly the guitar and voice chains")
  17. chain = chains.get("guitar")
  18. if not isinstance(chain, dict):
  19. return errors + ["routing.mod_host_chains.guitar must be a mapping"]
  20. guitar = source_by_id.get("guitar")
  21. physical_input = guitar.get("capture_port") if isinstance(guitar, dict) else None
  22. if chain.get("physical_input_port") != physical_input:
  23. errors.append(
  24. "routing.mod_host_chains.guitar.physical_input_port must match the guitar capture port"
  25. )
  26. if chain.get("source_port") != "rigforge.mod-host-input.capture:capture_AUX0":
  27. errors.append(
  28. "routing.mod_host_chains.guitar.source_port must be the mod-ui-visible input boundary"
  29. )
  30. if chain.get("pipewire_input_port") != "rigforge.mod-host-input:playback_AUX0":
  31. errors.append(
  32. "routing.mod_host_chains.guitar.pipewire_input_port must be the Rigforge input sink"
  33. )
  34. if chain.get("pipewire_output_port") != "rigforge.mod-host-output:capture_AUX0":
  35. errors.append(
  36. "routing.mod_host_chains.guitar.pipewire_output_port must be the Rigforge output source"
  37. )
  38. if chain.get("mod_ui_output_port") != "rigforge.mod-host-output.playback:playback_AUX0":
  39. errors.append(
  40. "routing.mod_host_chains.guitar.mod_ui_output_port must be the mod-ui-visible output boundary"
  41. )
  42. bypass = chain.get("bypass_link")
  43. mix_input = chain.get("mix_input")
  44. if not isinstance(bypass, dict):
  45. errors.append("routing.mod_host_chains.guitar.bypass_link must be a mapping")
  46. elif bypass != {"from": physical_input, "to": mix_input}:
  47. errors.append("routing.mod_host_chains.guitar.bypass_link must identify the direct capture-to-mix edge")
  48. if mix_input != "rigforge.direct-mix.input:playback_AUX0":
  49. errors.append("routing.mod_host_chains.guitar.mix_input must be the guitar mixer's AUX0 input")
  50. processors = chain.get("processors")
  51. if not isinstance(processors, list) or len(processors) != 2:
  52. return errors + ["routing.mod_host_chains.guitar.processors must contain NAM followed by one cabinet IR"]
  53. expected_processors = (
  54. {
  55. "id": "amp-head",
  56. "instance": 0,
  57. "plugin_uri": "http://github.com/mikeoliphant/neural-amp-modeler-lv2",
  58. "mod_ui_instance": "/graph/rigforge_nam",
  59. "bundle_path": ".lv2/neural_amp_modeler.lv2",
  60. "file_property": "http://github.com/mikeoliphant/neural-amp-modeler-lv2#model",
  61. "asset_path": "amp_emul/amphead/VOX_AC15/Vox_AC15CH_Crystal_Clean_TB.nam",
  62. "input_port": "effect_0:input",
  63. "output_port": "effect_0:output",
  64. },
  65. {
  66. "id": "cabinet-ir",
  67. "instance": 1,
  68. "plugin_uri": "http://lsp-plug.in/plugins/lv2/impulse_responses_mono",
  69. "mod_ui_instance": "/graph/rigforge_ir",
  70. "bundle_path": ".lv2/lsp-plugins.lv2",
  71. "file_property": "http://lsp-plug.in/plugins/lv2/impulse_responses_mono/ports#ifn",
  72. "asset_path": "amp_emul/cabinet/VOX_AC30_1964/VOX_AC30_1964_celestion.wav",
  73. "input_port": "effect_1:in",
  74. "output_port": "effect_1:out",
  75. },
  76. )
  77. for index, (processor, expected) in enumerate(zip(processors, expected_processors)):
  78. location = f"routing.mod_host_chains.guitar.processors[{index}]"
  79. if not isinstance(processor, dict):
  80. errors.append(f"{location} must be a mapping")
  81. continue
  82. for key, value in expected.items():
  83. if processor.get(key) != value:
  84. errors.append(f"{location}.{key} must be {value}")
  85. for key in ("bundle_path", "asset_path"):
  86. if not safe_relative_path(processor.get(key)):
  87. errors.append(f"{location}.{key} must be a safe relative path")
  88. if index == 0:
  89. expected_models = {
  90. "crystal_clean_tb": "amp_emul/amphead/VOX_AC15/Vox_AC15CH_Crystal_Clean_TB.nam",
  91. "edge_of_breakup_tb": "amp_emul/amphead/VOX_AC15/Vox_AC15CH_Edge_of_Breakup_TB.nam",
  92. "crunch_tb": "amp_emul/amphead/VOX_AC15/Vox_AC15CH_Crunch_TB.nam",
  93. "overdriven_tb": "amp_emul/amphead/VOX_AC15/Vox_AC15CH_Overdriven_TB.nam",
  94. }
  95. models = processor.get("available_models")
  96. if not isinstance(models, dict) or models != expected_models:
  97. errors.append(f"{location}.available_models must declare the four approved Vox TB models")
  98. elif any(not safe_relative_path(path) for path in models.values()):
  99. errors.append(f"{location}.available_models paths must be safe relative paths")
  100. elif processor.get("asset_path") not in models.values():
  101. errors.append(f"{location}.asset_path must be one of the declared available_models")
  102. if isinstance(processors[0], dict):
  103. parameters = processors[0].get("parameters")
  104. if not isinstance(parameters, dict):
  105. errors.append("routing.mod_host_chains.guitar.processors[0].parameters must be a mapping")
  106. else:
  107. output_level = parameters.get("output_level")
  108. if (
  109. not isinstance(output_level, (int, float))
  110. or isinstance(output_level, bool)
  111. or not -20.0 <= output_level <= 20.0
  112. ):
  113. errors.append("NAM output_level must be between -20 and 20 dB")
  114. links = routing.get("managed_links")
  115. if isinstance(links, list) and len(processors) == 2:
  116. actual_edges = {
  117. (link.get("from"), link.get("to"))
  118. for link in links
  119. if (
  120. isinstance(link, dict)
  121. and isinstance(link.get("from"), str)
  122. and isinstance(link.get("to"), str)
  123. )
  124. }
  125. if isinstance(processors[0], dict) and isinstance(processors[1], dict):
  126. expected_candidates = (
  127. (physical_input, chain.get("pipewire_input_port")),
  128. (chain.get("pipewire_output_port"), mix_input),
  129. (chain.get("pipewire_output_port"), "sooperlooper:loop0_in_1"),
  130. )
  131. for edge in expected_candidates:
  132. if not all(isinstance(endpoint, str) for endpoint in edge):
  133. continue
  134. if edge not in actual_edges:
  135. errors.append(f"mod-host guitar boundary link must be declared: {edge[0]} -> {edge[1]}")
  136. internal_edge = (
  137. processors[0].get("output_port"),
  138. processors[1].get("input_port"),
  139. )
  140. if internal_edge in actual_edges:
  141. errors.append(
  142. "the NAM-to-IR link is owned by mod-ui and must not be a Rigforge managed link"
  143. )
  144. if isinstance(bypass, dict):
  145. bypass_edge = (bypass.get("from"), bypass.get("to"))
  146. if all(isinstance(endpoint, str) for endpoint in bypass_edge) and bypass_edge in actual_edges:
  147. errors.append("the guitar capture-to-mix bypass must not be a managed link")
  148. managed_unlinks = routing.get("managed_unlinks")
  149. unlink_edges = {
  150. (item.get("from"), item.get("to"))
  151. for item in managed_unlinks
  152. if isinstance(item, dict)
  153. } if isinstance(managed_unlinks, list) else set()
  154. if (
  155. all(isinstance(endpoint, str) for endpoint in bypass_edge)
  156. and bypass_edge not in unlink_edges
  157. ):
  158. errors.append("the guitar capture-to-mix bypass must be declared in routing.managed_unlinks")
  159. return errors
  160. def validate_voice_chain(routing, source_by_id):
  161. errors = []
  162. chains = routing.get("mod_host_chains")
  163. chain = chains.get("voice") if isinstance(chains, dict) else None
  164. if not isinstance(chain, dict):
  165. return ["routing.mod_host_chains.voice must declare the microphone effects chain"]
  166. voice = source_by_id.get("voice")
  167. physical_input = voice.get("capture_port") if isinstance(voice, dict) else None
  168. expected = {
  169. "physical_input_port": physical_input,
  170. "source_port": "rigforge.mod-host-input.capture:capture_AUX2",
  171. "pipewire_input_port": "rigforge.mod-host-input:playback_AUX2",
  172. "pipewire_output_port": "rigforge.mod-host-output:capture_AUX2",
  173. "mod_ui_input_port": "capture_3",
  174. "mod_ui_output_port": "playback_3",
  175. }
  176. for key, value in expected.items():
  177. if chain.get(key) != value:
  178. errors.append(f"routing.mod_host_chains.voice.{key} must be {value}")
  179. processors = chain.get("processors")
  180. required = (
  181. ("voice-high-pass", 2, "http://lsp-plug.in/plugins/lv2/filter_mono", "effect_2:in", "effect_2:out"),
  182. ("voice-compressor", 3, "http://lsp-plug.in/plugins/lv2/compressor_mono", "effect_3:in", "effect_3:out"),
  183. ("voice-de-esser", 4, "http://lsp-plug.in/plugins/lv2/deesser_mono", "effect_4:in", "effect_4:out"),
  184. ("voice-reverb", 5, "urn:dragonfly:room", "effect_5:input_l", "effect_5:output_l"),
  185. )
  186. if not isinstance(processors, list) or len(processors) != len(required):
  187. return errors + ["routing.mod_host_chains.voice.processors must declare high-pass, compressor, de-esser, and reverb in order"]
  188. processor_parameters = (
  189. {"mode", "filter_type", "filter_mode", "slope", "frequency_hz", "quality"},
  190. {"compression_mode", "ratio", "attack_time_ms", "release_time_ms"},
  191. {"ratio", "threshold", "attack_time_ms", "release_time_ms", "split_frequency_hz"},
  192. {"dry_level", "early_level", "late_level", "size", "predelay_ms", "decay_seconds", "in_low_cut_hz", "in_high_cut_hz"},
  193. )
  194. for index, (processor, expected_processor) in enumerate(zip(processors, required)):
  195. location = f"routing.mod_host_chains.voice.processors[{index}]"
  196. if not isinstance(processor, dict):
  197. errors.append(f"{location} must be a mapping")
  198. continue
  199. processor_id, instance, plugin_uri, input_port, output_port = expected_processor
  200. expected_instance = f"/graph/rigforge_voice_{processor_id.removeprefix('voice-').replace('-', '_')}"
  201. expected_bundle = ".lv2/DragonflyRoomReverb.lv2" if index == 3 else ".lv2/lsp-plugins.lv2"
  202. for key, value in {
  203. "id": processor_id,
  204. "instance": instance,
  205. "plugin_uri": plugin_uri,
  206. "mod_ui_instance": expected_instance,
  207. "bundle_path": expected_bundle,
  208. "input_port": input_port,
  209. "output_port": output_port,
  210. }.items():
  211. if processor.get(key) != value:
  212. errors.append(f"{location}.{key} must be {value}")
  213. parameters = processor.get("parameters")
  214. if not isinstance(parameters, dict):
  215. errors.append(f"{location}.parameters must be a mapping")
  216. elif set(parameters) != processor_parameters[index]:
  217. errors.append(
  218. f"{location}.parameters must declare exactly "
  219. f"{sorted(processor_parameters[index])}"
  220. )
  221. if isinstance(processors[0], dict):
  222. params = processors[0].get("parameters", {})
  223. for key, value in {"mode": 0, "filter_type": 1, "filter_mode": 2}.items():
  224. if params.get(key) != value:
  225. errors.append(f"voice high-pass parameters.{key} must be {value}")
  226. frequency = params.get("frequency_hz")
  227. if not isinstance(frequency, (int, float)) or isinstance(frequency, bool) or not 50 <= frequency <= 150:
  228. errors.append("voice high-pass frequency_hz must be between 50 and 150")
  229. for index, name in ((1, "compressor"), (2, "de-esser")):
  230. if isinstance(processors[index], dict):
  231. ratio = processors[index].get("parameters", {}).get("ratio")
  232. if not isinstance(ratio, (int, float)) or isinstance(ratio, bool) or not 1 <= ratio <= 10:
  233. errors.append(f"voice {name} ratio must be between 1 and 10")
  234. if isinstance(processors[3], dict):
  235. params = processors[3].get("parameters", {})
  236. dry, late = params.get("dry_level"), params.get("late_level")
  237. if dry != 100.0 or not isinstance(late, (int, float)) or isinstance(late, bool) or not 0 <= late <= 30:
  238. errors.append("voice reverb must retain full dry signal and keep late_level between 0 and 30")
  239. return errors
  240. def validate_mod_host_channel_routes(state, source_by_id):
  241. errors = []
  242. deployment = state.get("deployment")
  243. ports = deployment.get("mod_host_ports") if isinstance(deployment, dict) else None
  244. if not isinstance(ports, dict):
  245. return ["deployment.mod_host_ports must declare four-channel boundaries"]
  246. channel_map = ports.get("channel_map")
  247. if channel_map != ["AUX0", "AUX1", "AUX2", "AUX3"]:
  248. return ["deployment.mod_host_ports.channel_map must contain AUX0 through AUX3"]
  249. required_names = (
  250. "input_sink_name",
  251. "input_source_name",
  252. "output_sink_name",
  253. "output_source_name",
  254. )
  255. if any(not isinstance(ports.get(name), str) or not ports[name] for name in required_names):
  256. return ["deployment.mod_host_ports must declare all four boundary node names"]
  257. routing = state.get("routing")
  258. if not isinstance(routing, dict):
  259. return errors
  260. links = routing.get("managed_links")
  261. if not isinstance(links, list):
  262. return ["routing.managed_links must be a list"]
  263. edges = {
  264. (link.get("from"), link.get("to"))
  265. for link in links
  266. if isinstance(link, dict)
  267. }
  268. for channel, source_id in enumerate(("guitar", "bass", "voice", "synth")):
  269. source = source_by_id.get(source_id)
  270. if not isinstance(source, dict):
  271. continue
  272. position = channel_map[channel]
  273. expected_capture = f"alsa_input.hw_U192k_0:capture_AUX{channel}"
  274. if source.get("physical_input") != channel + 1:
  275. errors.append(
  276. f"{source_id} must use physical input {channel + 1} for mod-ui channel {channel + 1}"
  277. )
  278. if source.get("capture_port") != expected_capture:
  279. errors.append(
  280. f"{source_id} capture_port must be {expected_capture} for mod-ui channel {channel + 1}"
  281. )
  282. expected = (
  283. (
  284. source.get("capture_port"),
  285. f"{ports['input_sink_name']}:playback_{position}",
  286. ),
  287. (
  288. f"{ports['output_source_name']}:capture_{position}",
  289. f"rigforge.direct-mix.input:playback_AUX{channel}",
  290. ),
  291. (
  292. f"{ports['output_source_name']}:capture_{position}",
  293. f"sooperlooper:loop0_in_{channel + 1}",
  294. ),
  295. )
  296. for edge in expected:
  297. if edge not in edges:
  298. errors.append(
  299. f"{source_id} mod-host boundary route must be declared: "
  300. f"{edge[0]} -> {edge[1]}"
  301. )
  302. bypass_edges = {
  303. (source.get("capture_port"), f"rigforge.direct-mix.input:playback_AUX{channel}"),
  304. (source.get("capture_port"), f"sooperlooper:loop0_in_{channel + 1}"),
  305. }
  306. stale = bypass_edges & edges
  307. for source_port, destination_port in sorted(stale):
  308. errors.append(
  309. f"{source_id} capture must not bypass its mod-ui channel: "
  310. f"{source_port} -> {destination_port}"
  311. )
  312. return errors
  313. def validate_additional_looper_routes(routing):
  314. errors = []
  315. links = routing.get("managed_links")
  316. if not isinstance(links, list):
  317. return ["routing.managed_links must be a list"]
  318. second_loop_inputs = {
  319. f"sooperlooper:loop1_in_{channel}" for channel in range(1, 5)
  320. }
  321. input_routes = [
  322. link
  323. for link in links
  324. if (
  325. isinstance(link, dict)
  326. and isinstance(link.get("to"), str)
  327. and link["to"] in second_loop_inputs
  328. )
  329. ]
  330. if input_routes:
  331. errors.append("SooperLooper loop1 inputs must remain unconnected")
  332. second_loop_output_links = [
  333. link
  334. for link in links
  335. if isinstance(link, dict)
  336. and isinstance(link.get("from"), str)
  337. and link["from"].startswith("sooperlooper:loop1_out_")
  338. ]
  339. expected_edge = (
  340. "sooperlooper:loop1_out_1",
  341. "rigforge.direct-mix.input:playback_AUX8",
  342. )
  343. declared_edges = [
  344. (link.get("from"), link.get("to"))
  345. for link in second_loop_output_links
  346. ]
  347. if declared_edges != [expected_edge]:
  348. errors.append(
  349. "SooperLooper loop1 must route only output 1 to direct-mix AUX8"
  350. )
  351. return errors
  352. def validate_state(state):
  353. errors = []
  354. if not isinstance(state, dict):
  355. return ["document root must be a mapping"]
  356. # Establish the declared source map before validating looper references.
  357. sources = state.get("sources")
  358. if not isinstance(sources, list):
  359. return ["sources must be a list"]
  360. source_by_id = {}
  361. physical_inputs = set()
  362. capture_ports = set()
  363. for index, source in enumerate(sources):
  364. location = f"sources[{index}]"
  365. if not isinstance(source, dict):
  366. errors.append(f"{location} must be a mapping")
  367. continue
  368. source_id = source.get("id")
  369. if not isinstance(source_id, str) or not source_id:
  370. errors.append(f"{location}.id must be a non-empty string")
  371. elif source_id in source_by_id:
  372. errors.append(f"duplicate source id: {source_id}")
  373. else:
  374. source_by_id[source_id] = source
  375. physical_input = source.get("physical_input")
  376. if not isinstance(physical_input, int) or isinstance(physical_input, bool):
  377. errors.append(f"{location}.physical_input must be an integer")
  378. elif physical_input in physical_inputs:
  379. errors.append(f"duplicate physical input: {physical_input}")
  380. else:
  381. physical_inputs.add(physical_input)
  382. capture_port = source.get("capture_port")
  383. if not isinstance(capture_port, str) or not capture_port:
  384. errors.append(f"{location}.capture_port must be a non-empty string")
  385. elif capture_port in capture_ports:
  386. errors.append(f"duplicate capture port: {capture_port}")
  387. else:
  388. capture_ports.add(capture_port)
  389. # Keep the first four-channel milestone tied to its four named instruments.
  390. expected_source_ids = {"guitar", "bass", "voice", "synth"}
  391. if set(source_by_id) != expected_source_ids:
  392. errors.append("source ids must be guitar, bass, voice, and synth exactly once")
  393. if len(sources) != 4:
  394. errors.append(f"exactly four sources are required, got {len(sources)}")
  395. if physical_inputs != {1, 2, 3, 4}:
  396. errors.append("physical inputs must cover 1 through 4 exactly once")
  397. # One SooperLooper instance hosts two four-channel loops.
  398. system = state.get("system")
  399. components = system.get("components") if isinstance(system, dict) else None
  400. if not isinstance(components, list):
  401. errors.append("system.components must be a list")
  402. components = []
  403. loopers = [item for item in components if isinstance(item, dict) and item.get("id") == "looper"]
  404. if len(loopers) != 1:
  405. errors.append(f"exactly one looper component is required, got {len(loopers)}")
  406. elif loopers[0].get("instance_count") != 1:
  407. errors.append("looper.instance_count must be 1")
  408. elif loopers[0].get("loop_count") != 2:
  409. errors.append("looper.loop_count must be 2")
  410. elif loopers[0].get("channels_per_loop") != 4:
  411. errors.append("looper.channels_per_loop must be 4")
  412. routing = state.get("routing")
  413. if not isinstance(routing, dict):
  414. errors.append("routing must be a mapping")
  415. return errors
  416. looper_inputs = routing.get("looper_inputs")
  417. if not isinstance(looper_inputs, list):
  418. errors.append("routing.looper_inputs must be a list")
  419. looper_inputs = []
  420. # Check that each source is assigned exactly once across all loop channels.
  421. input_channels = set()
  422. input_sources = set()
  423. for index, loop_input in enumerate(looper_inputs):
  424. location = f"routing.looper_inputs[{index}]"
  425. if not isinstance(loop_input, dict):
  426. errors.append(f"{location} must be a mapping")
  427. continue
  428. source_id = loop_input.get("source")
  429. channel = loop_input.get("channel")
  430. if source_id not in source_by_id:
  431. errors.append(f"{location}.source references unknown source: {source_id}")
  432. if source_id in input_sources:
  433. errors.append(f"source is assigned to multiple looper inputs: {source_id}")
  434. input_sources.add(source_id)
  435. if not isinstance(channel, int) or isinstance(channel, bool) or channel not in range(1, 5):
  436. errors.append(f"{location}.channel must be an integer from 1 through 4")
  437. elif channel in input_channels:
  438. errors.append(f"duplicate looper input channel: {channel}")
  439. else:
  440. input_channels.add(channel)
  441. if len(looper_inputs) != 4 or input_channels != {1, 2, 3, 4}:
  442. errors.append("looper inputs must cover channels 1 through 4 exactly once")
  443. if input_sources != set(source_by_id):
  444. errors.append("each declared source must map to exactly one looper input")
  445. mix = routing.get("mix")
  446. if not isinstance(mix, dict):
  447. errors.append("routing.mix must be a mapping")
  448. else:
  449. output_port = mix.get("output_port")
  450. if not isinstance(output_port, str) or not output_port:
  451. errors.append("routing.mix.output_port must be a non-empty string")
  452. mix_id = mix.get("id")
  453. if not isinstance(mix_id, str) or not mix_id:
  454. errors.append("routing.mix.id must be a non-empty string")
  455. includes = mix.get("includes")
  456. if not isinstance(includes, list) or "looper_returns" not in includes:
  457. errors.append("routing.mix.includes must include looper_returns")
  458. # Loop returns join the output mix but must never feed the loop inputs.
  459. returns = routing.get("looper_returns")
  460. if not isinstance(returns, dict):
  461. errors.append("routing.looper_returns must be a mapping")
  462. elif returns.get("feed_looper_inputs") is not False:
  463. errors.append("routing.looper_returns.feed_looper_inputs must be false")
  464. errors.extend(validate_mod_host_chain(routing, source_by_id))
  465. errors.extend(validate_voice_chain(routing, source_by_id))
  466. errors.extend(validate_mod_host_channel_routes(state, source_by_id))
  467. errors.extend(validate_additional_looper_routes(routing))
  468. parameters = state.get("parameters")
  469. if not isinstance(parameters, dict):
  470. errors.append("parameters must be a mapping")
  471. else:
  472. for key in ("sample_rate_hz", "quantum_frames"):
  473. value = parameters.get(key)
  474. if (
  475. not isinstance(value, int)
  476. or isinstance(value, bool)
  477. or value <= 0
  478. ):
  479. errors.append(f"parameters.{key} must be a positive integer")
  480. controls = state.get("controls")
  481. if not isinstance(controls, dict):
  482. errors.append("controls must be a mapping")
  483. else:
  484. midi_bridge = controls.get("midi_bridge")
  485. if not isinstance(midi_bridge, dict):
  486. errors.append("controls.midi_bridge must be a mapping")
  487. else:
  488. if midi_bridge.get("bindings_file") != "config/midi-bindings.yaml":
  489. errors.append("controls.midi_bridge.bindings_file must be config/midi-bindings.yaml")
  490. if (
  491. not isinstance(midi_bridge.get("input_port_name_contains"), str)
  492. or not midi_bridge["input_port_name_contains"].strip()
  493. ):
  494. errors.append("controls.midi_bridge.input_port_name_contains must be non-empty")
  495. mod_ui = midi_bridge.get("mod_ui")
  496. if not isinstance(mod_ui, dict):
  497. errors.append("controls.midi_bridge.mod_ui must be a mapping")
  498. else:
  499. if mod_ui.get("host") != "127.0.0.1":
  500. errors.append("controls.midi_bridge.mod_ui.host must be 127.0.0.1")
  501. port = mod_ui.get("port")
  502. if (
  503. not isinstance(port, int)
  504. or isinstance(port, bool)
  505. or not 1 <= port <= 65535
  506. ):
  507. errors.append("controls.midi_bridge.mod_ui.port must be a valid TCP port")
  508. elif isinstance(deployment := state.get("deployment"), dict):
  509. ui_deployment = deployment.get("mod_ui")
  510. if (
  511. isinstance(ui_deployment, dict)
  512. and ui_deployment.get("websocket_port") != port
  513. ):
  514. errors.append(
  515. "controls.midi_bridge.mod_ui.port must match deployment.mod_ui.websocket_port"
  516. )
  517. websocket_path = mod_ui.get("websocket_path")
  518. if websocket_path != "/websocket":
  519. errors.append("controls.midi_bridge.mod_ui.websocket_path must be /websocket")
  520. connections = state.get("connections", [])
  521. if not isinstance(connections, list):
  522. errors.append("connections must be a list")
  523. connections = []
  524. # An explicitly-forbidden connection documents policy; any other status is actionable.
  525. for index, connection in enumerate(connections):
  526. if not isinstance(connection, dict):
  527. errors.append(f"connections[{index}] must be a mapping")
  528. continue
  529. if (
  530. connection.get("from") == "looper_returns"
  531. and connection.get("to") in {
  532. "looper_inputs",
  533. "looper_input_1",
  534. "looper_input_2",
  535. "looper_input_3",
  536. "looper_input_4",
  537. }
  538. and connection.get("status") != "explicitly-forbidden"
  539. ):
  540. errors.append(f"connections[{index}] routes looper returns into looper inputs")
  541. deployment = state.get("deployment")
  542. if not isinstance(deployment, dict):
  543. errors.append("deployment must be a mapping")
  544. else:
  545. for component, repository, asset, archive_format, bundle_paths in (
  546. (
  547. "lsp",
  548. "lsp-plugins/lsp-plugins",
  549. "lsp-plugins-{tag}-Linux-aarch64.7z",
  550. "7z",
  551. {"lsp-plugins.lv2": "lsp-plugins-{tag}-Linux-aarch64/LV2/lsp-plugins.lv2"},
  552. ),
  553. (
  554. "dragonfly_reverb",
  555. "michaelwillis/dragonfly-reverb",
  556. "dragonfly-reverb-{tag}-linux-arm64.tar.xz",
  557. "tar.xz",
  558. {
  559. "DragonflyEarlyReflections.lv2": "dragonfly-reverb-{tag}/DragonflyEarlyReflections.lv2",
  560. "DragonflyHallReverb.lv2": "dragonfly-reverb-{tag}/DragonflyHallReverb.lv2",
  561. "DragonflyPlateReverb.lv2": "dragonfly-reverb-{tag}/DragonflyPlateReverb.lv2",
  562. "DragonflyRoomReverb.lv2": "dragonfly-reverb-{tag}/DragonflyRoomReverb.lv2",
  563. },
  564. ),
  565. ):
  566. plugin = deployment.get(component)
  567. if not isinstance(plugin, dict):
  568. errors.append(f"deployment.{component} must be a mapping")
  569. continue
  570. tag = plugin.get("tag")
  571. if not isinstance(tag, str) or not tag or any(
  572. character not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-"
  573. for character in tag
  574. ):
  575. errors.append(f"deployment.{component}.tag must be a simple version tag")
  576. expected_url = f"https://github.com/{repository}/releases/download/{tag}/{asset.format(tag=tag)}"
  577. if plugin.get("archive_url") != expected_url:
  578. errors.append(f"deployment.{component}.archive_url must match its tag and approved release asset")
  579. if plugin.get("archive_format") != archive_format:
  580. errors.append(f"deployment.{component}.archive_format must be {archive_format}")
  581. expected_paths = {
  582. name: path.format(tag=tag) for name, path in bundle_paths.items()
  583. }
  584. if plugin.get("bundle_paths") != expected_paths:
  585. errors.append(f"deployment.{component}.bundle_paths are invalid")
  586. for bundle_name, bundle_path in expected_paths.items():
  587. if bundle_name not in bundle_path:
  588. errors.append(f"deployment.{component}.bundle_paths keys must name their bundle directories")
  589. namlv2 = deployment.get("namlv2")
  590. if not isinstance(namlv2, dict):
  591. errors.append("deployment.namlv2 must be a mapping")
  592. else:
  593. if namlv2.get("source_url") != "https://github.com/mikeoliphant/neural-amp-modeler-lv2":
  594. errors.append(
  595. "deployment.namlv2.source_url must match the approved GitHub repository"
  596. )
  597. tag = namlv2.get("tag")
  598. allowed_tag_characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-"
  599. if not isinstance(tag, str) or not tag or any(
  600. character not in allowed_tag_characters for character in tag
  601. ):
  602. errors.append("deployment.namlv2.tag must be a simple version tag")
  603. archive_url = namlv2.get("archive_url")
  604. expected_url = (
  605. f"https://github.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/{tag}/"
  606. "neural_amp_modeler_lv2_rpi5.tgz"
  607. )
  608. if archive_url != expected_url:
  609. errors.append("deployment.namlv2.archive_url must match its tag and approved RPi 5 release asset")
  610. if namlv2.get("bundle_directory") != "neural_amp_modeler.lv2":
  611. errors.append("deployment.namlv2.bundle_directory must be neural_amp_modeler.lv2")
  612. if namlv2.get("artifact_directory") != "artifacts/nam-lv2/arm64/current":
  613. errors.append(
  614. "deployment.namlv2.artifact_directory must be artifacts/nam-lv2/arm64/current"
  615. )
  616. if namlv2.get("backup_directory") != ".local/state/rigforge/namlv2-backups":
  617. errors.append(
  618. "deployment.namlv2.backup_directory must be "
  619. ".local/state/rigforge/namlv2-backups"
  620. )
  621. sooperlooper = deployment.get("sooperlooper")
  622. if not isinstance(sooperlooper, dict):
  623. errors.append("deployment.sooperlooper must be a mapping")
  624. else:
  625. source_url = sooperlooper.get("source_url")
  626. if source_url != "https://github.com/jojolb/sooperlooper-mods":
  627. errors.append("deployment.sooperlooper.source_url must match the approved GitHub repository")
  628. tag = sooperlooper.get("tag")
  629. if not isinstance(tag, str) or not tag or any(
  630. character not in allowed_tag_characters for character in tag
  631. ):
  632. errors.append("deployment.sooperlooper.tag must be a simple version tag")
  633. for key, expected in (
  634. ("binary_source", "artifacts/sooperlooper/arm64/current/sooperlooper"),
  635. (
  636. "service_source",
  637. "config/systemd/user/rigforge-sooperlooper.service.in",
  638. ),
  639. (
  640. "service_destination",
  641. ".config/systemd/user/rigforge-sooperlooper.service",
  642. ),
  643. ("user_service", "rigforge-sooperlooper.service"),
  644. ("binding_file", "config/sooperlooper/fcb1010.slb"),
  645. ("pw_jack_path", "/usr/bin/pw-jack"),
  646. ("oscsend_path", "/usr/bin/oscsend"),
  647. ):
  648. if sooperlooper.get(key) != expected:
  649. errors.append(f"deployment.sooperlooper.{key} must be {expected}")
  650. timeout_seconds = sooperlooper.get("timeout_seconds")
  651. if (
  652. not isinstance(timeout_seconds, int)
  653. or isinstance(timeout_seconds, bool)
  654. or not 1 <= timeout_seconds <= 300
  655. ):
  656. errors.append("deployment.sooperlooper.timeout_seconds must be between 1 and 300")
  657. osc = sooperlooper.get("osc")
  658. if not isinstance(osc, dict):
  659. errors.append("deployment.sooperlooper.osc must be a mapping")
  660. else:
  661. if osc.get("host") != "127.0.0.1":
  662. errors.append("deployment.sooperlooper.osc.host must be 127.0.0.1")
  663. port = osc.get("port")
  664. if (
  665. not isinstance(port, int)
  666. or isinstance(port, bool)
  667. or not 1 <= port <= 65535
  668. ):
  669. errors.append("deployment.sooperlooper.osc.port must be a valid UDP port")
  670. delay = osc.get("post_start_delay_seconds")
  671. if (
  672. not isinstance(delay, int)
  673. or isinstance(delay, bool)
  674. or not 0 <= delay <= 30
  675. ):
  676. errors.append(
  677. "deployment.sooperlooper.osc.post_start_delay_seconds must be between 0 and 30"
  678. )
  679. prefader = osc.get("discrete_prefader")
  680. if (
  681. not isinstance(prefader, int)
  682. or isinstance(prefader, bool)
  683. or prefader not in (0, 1)
  684. ):
  685. errors.append(
  686. "deployment.sooperlooper.osc.discrete_prefader must be 0 or 1"
  687. )
  688. slweb = deployment.get("slweb")
  689. if not isinstance(slweb, dict):
  690. errors.append("deployment.slweb must be a mapping")
  691. else:
  692. for key, expected in (
  693. ("source_directory", "tools"),
  694. ("install_directory", ".local/share/rigforge/sooperlooper-slweb"),
  695. ("service_source", "config/systemd/user/rigforge-slweb.service.in"),
  696. ("service_destination", ".config/systemd/user/rigforge-slweb.service"),
  697. ("user_service", "rigforge-slweb.service"),
  698. ("python_path", "/usr/bin/python3"),
  699. ("http_port", 8080),
  700. ("files_directory", "/home/jojo/loops"),
  701. ):
  702. if slweb.get(key) != expected:
  703. errors.append(f"deployment.slweb.{key} must be {expected}")
  704. if slweb.get("http_host") not in ("127.0.0.1", "0.0.0.0"):
  705. errors.append(
  706. "deployment.slweb.http_host must be 127.0.0.1 or 0.0.0.0"
  707. )
  708. mod_host = deployment.get("mod_host")
  709. if not isinstance(mod_host, dict):
  710. errors.append("deployment.mod_host must be a mapping")
  711. else:
  712. source_url = mod_host.get("source_url")
  713. if source_url != "https://github.com/mod-audio/mod-host":
  714. errors.append("deployment.mod_host.source_url must match the approved GitHub repository")
  715. tag = mod_host.get("tag")
  716. if not isinstance(tag, str) or not tag or any(
  717. character not in allowed_tag_characters for character in tag
  718. ):
  719. errors.append("deployment.mod_host.tag must be a simple version tag")
  720. for key, expected in (
  721. ("binary_source", "artifacts/mod-host/arm64/current/mod-host"),
  722. ("service_source", "config/systemd/user/rigforge-mod-host.service.in"),
  723. ("service_destination", ".config/systemd/user/rigforge-mod-host.service"),
  724. ("user_service", "rigforge-mod-host.service"),
  725. ("readiness_script", "scripts/wait_mod_host_ports.py"),
  726. ("pw_jack_path", "/usr/bin/pw-jack"),
  727. ("python_path", "/usr/bin/python3"),
  728. ):
  729. if mod_host.get(key) != expected:
  730. errors.append(f"deployment.mod_host.{key} must be {expected}")
  731. socket_port = mod_host.get("socket_port")
  732. if (
  733. not isinstance(socket_port, int)
  734. or isinstance(socket_port, bool)
  735. or not 1 <= socket_port <= 65535
  736. ):
  737. errors.append("deployment.mod_host.socket_port must be a valid TCP port")
  738. feedback_port = mod_host.get("feedback_port")
  739. if (
  740. not isinstance(feedback_port, int)
  741. or isinstance(feedback_port, bool)
  742. or not 1 <= feedback_port <= 65535
  743. ):
  744. errors.append("deployment.mod_host.feedback_port must be a valid TCP port")
  745. elif feedback_port == socket_port:
  746. errors.append("deployment.mod_host.feedback_port must differ from socket_port")
  747. port_wait_timeout = mod_host.get("port_wait_timeout_seconds")
  748. if (
  749. not isinstance(port_wait_timeout, int)
  750. or isinstance(port_wait_timeout, bool)
  751. or not 5 <= port_wait_timeout <= 300
  752. ):
  753. errors.append(
  754. "deployment.mod_host.port_wait_timeout_seconds must be between 5 and 300"
  755. )
  756. mod_ui = deployment.get("mod_ui")
  757. if not isinstance(mod_ui, dict):
  758. errors.append("deployment.mod_ui must be a mapping")
  759. else:
  760. if mod_ui.get("source_url") != "https://github.com/mod-audio/mod-ui":
  761. errors.append("deployment.mod_ui.source_url must match the approved GitHub repository")
  762. tag = mod_ui.get("tag")
  763. if not isinstance(tag, str) or not tag or any(
  764. character not in allowed_tag_characters for character in tag
  765. ):
  766. errors.append("deployment.mod_ui.tag must be a simple version tag")
  767. if mod_ui.get("artifact_directory") != "artifacts/mod-ui/arm64/current":
  768. errors.append(
  769. "deployment.mod_ui.artifact_directory must be artifacts/mod-ui/arm64/current"
  770. )
  771. for key, expected in (
  772. ("launcher", "artifacts/mod-ui/arm64/current/run-mod-ui"),
  773. ("runner_script", "scripts/run_mod_ui_service.py"),
  774. ("service_source", "config/systemd/user/rigforge-mod-ui.service.in"),
  775. ("service_destination", ".config/systemd/user/rigforge-mod-ui.service"),
  776. ("user_service", "rigforge-mod-ui.service"),
  777. ("pw_jack_path", "/usr/bin/pw-jack"),
  778. ("python_path", "/usr/bin/python3"),
  779. ("websocket_host", "127.0.0.1"),
  780. ("reference_directory", ".local/share/rigforge/mod-ui/references"),
  781. ("pedalboards_directory", ".local/share/rigforge/mod-ui/pedalboards"),
  782. ("user_files_directory", ".local/share/rigforge/mod-ui/user-files"),
  783. ("last_state_file", ".local/share/rigforge/mod-ui/last-rigforge.json"),
  784. ):
  785. if mod_ui.get(key) != expected:
  786. errors.append(f"deployment.mod_ui.{key} must be {expected}")
  787. expected_input_ports = [
  788. f"rigforge.mod-host-input.capture:capture_AUX{index}"
  789. for index in range(4)
  790. ]
  791. expected_output_ports = [
  792. f"rigforge.mod-host-output.playback:playback_AUX{index}"
  793. for index in range(4)
  794. ]
  795. if mod_ui.get("hardware_input_ports") != expected_input_ports:
  796. errors.append(
  797. "deployment.mod_ui.hardware_input_ports must declare capture_AUX0 through capture_AUX3"
  798. )
  799. if mod_ui.get("hardware_output_ports") != expected_output_ports:
  800. errors.append(
  801. "deployment.mod_ui.hardware_output_ports must declare playback_AUX0 through playback_AUX3"
  802. )
  803. ui_port = mod_ui.get("websocket_port")
  804. if (
  805. not isinstance(ui_port, int)
  806. or isinstance(ui_port, bool)
  807. or not 1 <= ui_port <= 65535
  808. ):
  809. errors.append("deployment.mod_ui.websocket_port must be a valid TCP port")
  810. elif isinstance(mod_host, dict) and (
  811. ui_port == mod_host.get("socket_port")
  812. or ui_port == mod_host.get("feedback_port")
  813. ):
  814. errors.append("deployment.mod_ui.websocket_port must differ from mod-host TCP ports")
  815. mod_host_ports = deployment.get("mod_host_ports")
  816. if not isinstance(mod_host_ports, dict):
  817. errors.append("deployment.mod_host_ports must be a mapping")
  818. else:
  819. for key, expected in (
  820. ("binary_path", "/usr/bin/pw-loopback"),
  821. ("runner_script", "scripts/run_mod_host_ports.py"),
  822. ("service_source", "config/systemd/user/rigforge-mod-host-ports.service.in"),
  823. ("service_destination", ".config/systemd/user/rigforge-mod-host-ports.service"),
  824. ("user_service", "rigforge-mod-host-ports.service"),
  825. ("python_path", "/usr/bin/python3"),
  826. ("input_sink_name", "rigforge.mod-host-input"),
  827. ("input_source_name", "rigforge.mod-host-input.capture"),
  828. ("output_sink_name", "rigforge.mod-host-output.playback"),
  829. ("output_source_name", "rigforge.mod-host-output"),
  830. ):
  831. if mod_host_ports.get(key) != expected:
  832. errors.append(f"deployment.mod_host_ports.{key} must be {expected}")
  833. if mod_host_ports.get("channel_map") != ["AUX0", "AUX1", "AUX2", "AUX3"]:
  834. errors.append(
  835. "deployment.mod_host_ports.channel_map must contain AUX0 through AUX3"
  836. )
  837. reconcile = deployment.get("reconcile")
  838. if not isinstance(reconcile, dict):
  839. errors.append("deployment.reconcile must be a mapping")
  840. else:
  841. for key, expected in (
  842. ("observer_script", "scripts/observe_pipewire.py"),
  843. (
  844. "service_source",
  845. "config/systemd/user/rigforge-pipewire-reconcile.service.in",
  846. ),
  847. (
  848. "service_destination",
  849. ".config/systemd/user/rigforge-pipewire-reconcile.service",
  850. ),
  851. ("user_service", "rigforge-pipewire-reconcile.service"),
  852. (
  853. "timer_source",
  854. "config/systemd/user/rigforge-pipewire-reconcile.timer.in",
  855. ),
  856. (
  857. "timer_destination",
  858. ".config/systemd/user/rigforge-pipewire-reconcile.timer",
  859. ),
  860. ("user_timer", "rigforge-pipewire-reconcile.timer"),
  861. ("python_path", "/usr/bin/python3"),
  862. ):
  863. if reconcile.get(key) != expected:
  864. errors.append(f"deployment.reconcile.{key} must be {expected}")
  865. interval = reconcile.get("interval_seconds")
  866. if (
  867. not isinstance(interval, int)
  868. or isinstance(interval, bool)
  869. or not 5 <= interval <= 300
  870. ):
  871. errors.append(
  872. "deployment.reconcile.interval_seconds must be between 5 and 300"
  873. )
  874. midi_bridge = deployment.get("midi_bridge")
  875. if not isinstance(midi_bridge, dict):
  876. errors.append("deployment.midi_bridge must be a mapping")
  877. else:
  878. for key, expected in (
  879. ("bridge_script", "scripts/midi_action_bridge.py"),
  880. (
  881. "service_source",
  882. "config/systemd/user/rigforge-midi-bridge.service.in",
  883. ),
  884. (
  885. "service_destination",
  886. ".config/systemd/user/rigforge-midi-bridge.service",
  887. ),
  888. ("user_service", "rigforge-midi-bridge.service"),
  889. ("python_path", "/usr/bin/python3"),
  890. ):
  891. if midi_bridge.get(key) != expected:
  892. errors.append(f"deployment.midi_bridge.{key} must be {expected}")
  893. pipewire = deployment.get("pipewire")
  894. if not isinstance(pipewire, dict):
  895. errors.append("deployment.pipewire must be a mapping")
  896. else:
  897. expected_fragment_source = "config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf"
  898. if pipewire.get("fragment_source") != expected_fragment_source:
  899. errors.append("deployment.pipewire.fragment_source must name the managed repository fragment")
  900. expected_fragment_destination = ".config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf"
  901. if pipewire.get("fragment_destination") != expected_fragment_destination:
  902. errors.append("deployment.pipewire.fragment_destination must be the user filter-chain fragment path")
  903. if pipewire.get("user_service") != "filter-chain.service":
  904. errors.append("deployment.pipewire.user_service must be filter-chain.service")
  905. return errors
  906. def main(argv=None):
  907. parser = argparse.ArgumentParser()
  908. parser.add_argument(
  909. "state_file",
  910. nargs="?",
  911. type=Path,
  912. default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
  913. )
  914. args = parser.parse_args(argv)
  915. try:
  916. with args.state_file.open(encoding="utf-8") as state_stream:
  917. state = yaml.safe_load(state_stream)
  918. except (OSError, yaml.YAMLError) as error:
  919. print(f"Unable to load {args.state_file}: {error}", file=sys.stderr)
  920. return 2
  921. errors = validate_state(state)
  922. if errors:
  923. for error in errors:
  924. print(f"ERROR: {error}", file=sys.stderr)
  925. return 1
  926. print(f"Valid desired state: {args.state_file}")
  927. return 0
  928. if __name__ == "__main__":
  929. raise SystemExit(main())