From 2254fd545b8cc2826249c6eb049deead9f03dd3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jannik=20A=C3=9Ffalg?= <67785539+repeat98@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:58:41 +0100 Subject: [PATCH] The SDK checks now fail on an Octatrack hook nobody subscribes, raises or contributes to unless unused-hooks.json says why, and on a stale line there. Co-Authored-By: Claude Opus 5.5 --- changelog/2026-11-16-hook-coverage.md | 1 + docs/module-guides/README.md | 2 +- sdk/machines/octatrack/hook_coverage.py | 145 +++++++++++++++++++++++ sdk/machines/octatrack/unused-hooks.json | 20 ++++ sdk/tests/test_hook_coverage.py | 76 ++++++++++++ 5 files changed, 243 insertions(+), 1 deletion(-) create mode 100644 changelog/2026-11-16-hook-coverage.md create mode 100644 sdk/machines/octatrack/hook_coverage.py create mode 100644 sdk/machines/octatrack/unused-hooks.json create mode 100644 sdk/tests/test_hook_coverage.py diff --git a/changelog/2026-11-16-hook-coverage.md b/changelog/2026-11-16-hook-coverage.md new file mode 100644 index 0000000000..e3efd67823 --- /dev/null +++ b/changelog/2026-11-16-hook-coverage.md @@ -0,0 +1 @@ +Octatrack SDK: a check that every hook and table in `events.json` has a user (a module, draft, module adapter, the base's build or a test that subscribes, raises or contributes to it) or a one-line reason in `sdk/machines/octatrack/unused-hooks.json`; a reason whose hook is now used, or gone, fails too. It starts with 15 hooks that wait for their first module: the project, bank and Part hooks and `ev_modules_ready` from 14 November, and the MIDI generator table. diff --git a/docs/module-guides/README.md b/docs/module-guides/README.md index 2ee6d4e0c6..af6cbbd1e4 100644 --- a/docs/module-guides/README.md +++ b/docs/module-guides/README.md @@ -145,7 +145,7 @@ Machine modules whose native source predates these hooks declare the same subscr Propose a hook, or a table, when the gate says two module hooks meet, when you need a site that another module or the base already patches, or when many modules will need it. A site only your module uses needs no shared hook ([choose how a module hooks in](#choose-how-a-module-hooks-in)): -1. Open a pull request that adds one entry at the end of `sdk/machines/octatrack/events.json`, then regenerate its outputs with `python3 -B sdk/machines/octatrack/events.py --write`. A hook needs its name (`ev_` and what happens), its kind, its stock site (address, length in whole instructions and a SHA-256 guard), or none for a raised hook, when it runs, its C prototype and its order rule. A table needs an `ot_` name, its record size and C declaration, its room and the sites its reader owns. Addresses, lengths and hashes only: no stock bytes. A [take hook](../../sdk/machines/octatrack/elekloader/README.md#take-hooks) needs a stock tail, not a prototype. CI has no firmware: rebuild the base with your OS. `pr:ready` claims its index on the [agent board](../AGENT_BOARD.md). +1. Open a pull request that adds one entry at the end of `sdk/machines/octatrack/events.json`, then regenerate its outputs with `python3 -B sdk/machines/octatrack/events.py --write`. A hook needs its name (`ev_` and what happens), its kind, its stock site (address, length in whole instructions and a SHA-256 guard), or none for a raised hook, when it runs, its C prototype and its order rule. A table needs an `ot_` name, its record size and C declaration, its room and the sites its reader owns. Addresses, lengths and hashes only: no stock bytes. A [take hook](../../sdk/machines/octatrack/elekloader/README.md#take-hooks) needs a stock tail, not a prototype. CI has no firmware: rebuild the base with your OS. `pr:ready` claims its index on the [agent board](../AGENT_BOARD.md). A new hook needs a user that subscribes, raises or contributes (a module, draft, adapter or test), or a line in `sdk/machines/octatrack/unused-hooks.json` saying why it waits; `sdk/tests/test_hook_coverage.py` fails otherwise, and on a line whose hook has found its user. 2. Say which modules patch that site today. Until they subscribe, list each such pair in `compatibility.json` as `pending-migration`, with the hook and `until`. 3. The owner reviews the entry. Every later module subscribes or contributes instead of patching. diff --git a/sdk/machines/octatrack/hook_coverage.py b/sdk/machines/octatrack/hook_coverage.py new file mode 100644 index 0000000000..bbf29b99a4 --- /dev/null +++ b/sdk/machines/octatrack/hook_coverage.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-or-later +"""Every hook and table in events.json has a user, or a line in unused-hooks.json saying why it has none yet. + + python3 -B sdk/machines/octatrack/hook_coverage.py # the problems; exit 1 if any + python3 -B sdk/machines/octatrack/hook_coverage.py --list # each hook's users + +A user is a declaration the loader or a build binds by: a `subscribe` ({"event", "fn"} or "HOOK:FN:ORDER"), +`contribute` ({"to", "data"}) or `raise` entry in a module's or draft's runtime.json, a machine port +(module-adapters/machine-ports.json), a package row (src/engine/assets/octatrack-module-packages.json), or the same +entries written in Python (dict(event=..., fn=...), build.py's --subscribe HOOK:... and --raise HOOK) by the base's +build, an adapter, a module's tools or a test. A hook named only in prose, a comment, a C or assembly symbol, or the +base's own raise has no user: nothing binds a handler to it. A line in unused-hooks.json whose hook is used now, or +that names no hook, fails too, so the list stays exact. dsp-sites.json needs no such list: each of its sites names +the module whose manifest declares it, and dsp_sites.py --check refuses a site no manifest declares. +""" +import argparse +import ast +import json +from pathlib import Path +import subprocess +import sys + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +REGISTRY = 'sdk/machines/octatrack/events.json' +ALLOW = 'sdk/machines/octatrack/unused-hooks.json' +SCANNED = ('sdk/octatrack/modules', 'sdk/drafts', 'sdk/machines/octatrack', 'sdk/tests', + 'src/engine/assets/octatrack-module-packages.json') +# The registry, its generated outputs, the generator and this check (and its test's fixtures) are not users. +SKIPPED = {REGISTRY, ALLOW, 'sdk/machines/octatrack/site-events.json', 'sdk/machines/octatrack/events.py', + 'sdk/machines/octatrack/hook_coverage.py', 'sdk/tests/test_hook_coverage.py'} + + +def tracked(root=ROOT): + """The checked-in files the check reads, relative to root.""" + out = subprocess.run(['git', '-C', str(root), 'ls-files', '-z', '--', *SCANNED], capture_output=True, check=True).stdout + return [p for p in out.decode().split('\0') if p.endswith(('.json', '.py')) and p not in SKIPPED] + + +def _hook(text): + return text.split(':', 1)[0] if isinstance(text, str) else None + + +def _json_uses(doc): + """(hook, how) for each subscribe, contribute and raise entry anywhere in a JSON document.""" + if isinstance(doc, list): + for x in doc: + yield from _json_uses(x) + if not isinstance(doc, dict): + return + for key, field in (('subscribe', 'event'), ('contribute', 'to'), ('raise', None)): + for x in doc.get(key) if isinstance(doc.get(key), list) else (): + hook = x.get(field) if isinstance(x, dict) and field else _hook(x) + if isinstance(hook, str): + yield hook, key + for x in doc.values(): + yield from _json_uses(x) + + +def _str(node): + return node.value if isinstance(node, ast.Constant) and isinstance(node.value, str) else None + + +def _python_uses(tree): + """(hook, how) for each subscribe, contribute and raise entry written in Python, and build.py's arguments.""" + for node in ast.walk(tree): + fields = None + if isinstance(node, ast.Dict): + fields = {_str(k): v for k, v in zip(node.keys, node.values) if k is not None and _str(k)} + elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == 'dict': + fields = {k.arg: k.value for k in node.keywords if k.arg} + if fields: + if 'fn' in fields and _str(fields.get('event')): + yield _str(fields['event']), 'subscribe' + if 'data' in fields and _str(fields.get('to')): + yield _str(fields['to']), 'contribute' + for key in ('subscribe', 'raise'): + if isinstance(fields.get(key), (ast.List, ast.Tuple)): + yield from ((_hook(_str(x)), key) for x in fields[key].elts if _str(x)) + items = node.elts if isinstance(node, (ast.List, ast.Tuple)) else node.args if isinstance(node, ast.Call) else () + for flag, value in zip(items, items[1:]): + if _str(flag) in ('--subscribe', '--raise') and _str(value): + yield _hook(_str(value)), _str(flag)[2:] + + +def users(root=ROOT, paths=None): + """{hook: ['path (how)', ...]} over the given files (default: the checked-in ones the check reads).""" + found = {} + for path in tracked(root) if paths is None else paths: + try: + text = (Path(root) / path).read_text(encoding='utf-8') + uses = _json_uses(json.loads(text)) if path.endswith('.json') else _python_uses(ast.parse(text)) + for hook, how in list(uses): + found.setdefault(hook, set()).add('%s (%s)' % (path, how)) + except (OSError, UnicodeDecodeError, ValueError, SyntaxError): + continue # not this check's to judge: the file's own checks read it + return {h: sorted(u) for h, u in found.items()} + + +def _unique(pairs): + keys = [k for k, _ in pairs] + if len(keys) != len(set(keys)): + raise ValueError('%s lists a hook twice' % ALLOW) + return dict(pairs) + + +def problems(root=ROOT, paths=None): + """What to fix, one line each: a hook nothing uses and no line explains, and a line that is stale.""" + root = Path(root) + hooks = [e['event'] for e in json.loads((root / REGISTRY).read_text(encoding='utf-8'))['events']] + try: + allowed = json.loads((root / ALLOW).read_text(encoding='utf-8'), object_pairs_hook=_unique)['unused'] + except (OSError, KeyError, ValueError) as error: + return ['%s: %s' % (ALLOW, error)] + used, out = users(root, paths), [] + for hook in hooks: + if hook not in used and hook not in allowed: + out.append('%s: no module, draft, adapter, base build or test subscribes, raises or contributes to it. Give it ' + 'its first user in the same pull request, or add a line to %s saying why it waits' % (hook, ALLOW)) + for hook, reason in allowed.items(): + if hook not in hooks: + out.append('%s: %s names a hook events.json does not have: remove the line' % (hook, ALLOW)) + elif hook in used: + out.append('%s: %s says nothing uses it, but %s does: remove the line' % (hook, ALLOW, used[hook][0])) + if not isinstance(reason, str) or not reason.strip() or '\n' in reason or len(reason) > 200: + out.append('%s: its line in %s needs a reason of one line (200 characters at most)' % (hook, ALLOW)) + return out + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.split('\n')[0]) + parser.add_argument('--list', action='store_true', help="print each hook's users") + args = parser.parse_args(argv) + if args.list: + used = users() + for e in json.loads((ROOT / REGISTRY).read_text(encoding='utf-8'))['events']: + print('%s: %s' % (e['event'], ', '.join(used.get(e['event'], ['none'])))) + found = problems() + print('\n'.join(found) or 'Every hook in events.json has a user or a reason in ' + ALLOW) + return 1 if found else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/sdk/machines/octatrack/unused-hooks.json b/sdk/machines/octatrack/unused-hooks.json new file mode 100644 index 0000000000..00d26ada23 --- /dev/null +++ b/sdk/machines/octatrack/unused-hooks.json @@ -0,0 +1,20 @@ +{ + "about": "The hooks and tables in events.json that no module, draft, module adapter, base build or test subscribes, raises or contributes to yet, each with one line saying why (hook_coverage.py, run by sdk/tests/test_hook_coverage.py). A hook here is base code no module exercises: the first place to look when the base needs room. Remove a line in the pull request that gives its hook a user; the check fails on a line whose hook is used or gone.", + "unused": { + "ot_midi_generators": "base table since #775, its reader host-tested; VECTOR MIDI contributed in VECTOR 0.3.0 (#1339) and left with 0.3.1 (#1342), its own module pending", + "ev_banks_load": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending", + "ev_banks_loaded": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending", + "ev_bank_load": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending", + "ev_bank_loaded": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending", + "ev_project_new": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending", + "ev_bank_write": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending", + "ev_bank_written": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending", + "ev_project_store": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending", + "ev_project_stored": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending", + "ev_project_reload": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending", + "ev_project_reloaded": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending", + "ev_part_saved": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending", + "ev_part_clear": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending; not yet reached on a unit", + "ev_modules_ready": "added in #1564: the base raises it when the installed modules change, so a module may read its file from the card; first module pending" + } +} diff --git a/sdk/tests/test_hook_coverage.py b/sdk/tests/test_hook_coverage.py new file mode 100644 index 0000000000..5622e654ba --- /dev/null +++ b/sdk/tests/test_hook_coverage.py @@ -0,0 +1,76 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Every Octatrack hook has a user or a reason (sdk/machines/octatrack/hook_coverage.py, unused-hooks.json).""" +import json +from pathlib import Path +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / 'sdk/machines/octatrack')) +import hook_coverage # noqa: E402 + +FILES = { + 'sdk/octatrack/modules/a/runtime.json': {'schema': 1, 'subscribe': [{'event': 'ev_call', 'fn': 'f', 'order': 50}], + 'raise': ['ev_raised']}, + 'sdk/machines/octatrack/module-adapters/machine-ports.json': {'ports': {'b': {'contribute': [ + {'to': 'ot_table', 'order': 10, 'data': 'rec'}]}}}, + 'src/engine/assets/octatrack-module-packages.json': {'packages': [{'id': 'c', 'subscribe': ['ev_take:mw_take:40']}]}, + 'sdk/tests/test_x.py': "run('--raise', 'ev_tested')\nhooks = [dict(event='ev_built', fn='g', order=1)]\n", + 'sdk/drafts/d/notes.py': "# ev_prose is named here, looked up and half declared: none of it binds a handler\n" + "index = events.index('ev_prose')\nx = {'event': 'ev_prose'}\n", + 'sdk/drafts/d/README.json': {'about': 'ev_prose'}, +} +HOOKS = ['ev_call', 'ev_raised', 'ot_table', 'ev_take', 'ev_tested', 'ev_built', 'ev_prose'] + + +class HookCoverage(unittest.TestCase): + def test_every_hook_has_a_user_or_a_reason(self): + self.assertEqual(hook_coverage.problems(), []) + + def tree(self, allowed, files=FILES): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + root = Path(temp.name) + docs = {hook_coverage.REGISTRY: {'events': [{'event': h} for h in HOOKS]}, **files} + for path, doc in docs.items(): + (root / path).parent.mkdir(parents=True, exist_ok=True) + (root / path).write_text(doc if isinstance(doc, str) else json.dumps(doc)) + (root / hook_coverage.ALLOW).write_text(allowed if isinstance(allowed, str) else json.dumps({'unused': allowed})) + return root, [p for p in files] + + def test_declarations_count_and_prose_does_not(self): + root, paths = self.tree({}) + used = hook_coverage.users(root, paths) + self.assertEqual(sorted(h for h in used if h in HOOKS), sorted(set(HOOKS) - {'ev_prose'})) + self.assertEqual(used['ev_take'], ['src/engine/assets/octatrack-module-packages.json (subscribe)']) + self.assertEqual(used['ev_tested'], ['sdk/tests/test_x.py (raise)']) + problems = hook_coverage.problems(root, paths) + self.assertEqual(len(problems), 1) + self.assertTrue(problems[0].startswith('ev_prose: no module'), problems) + + def test_a_reason_clears_an_unused_hook(self): + root, paths = self.tree({'ev_prose': 'waiting for its first module'}) + self.assertEqual(hook_coverage.problems(root, paths), []) + + def test_a_stale_or_unknown_line_fails(self): + root, paths = self.tree({'ev_prose': 'waiting', 'ev_call': 'unused, it said', 'ev_gone': 'renamed'}) + problems = hook_coverage.problems(root, paths) + self.assertEqual(len(problems), 2, problems) + self.assertIn('ev_call: %s says nothing uses it, but sdk/octatrack/modules/a/runtime.json (subscribe) does' + % hook_coverage.ALLOW, problems[0]) + self.assertTrue(problems[1].startswith('ev_gone: ') and 'does not have' in problems[1]) + + def test_a_reason_is_one_line(self): + for reason in ('', ' ', 'two\nlines', 'x' * 201, None): + with self.subTest(reason=reason): + root, paths = self.tree({'ev_prose': reason}) + self.assertEqual(len(hook_coverage.problems(root, paths)), 1) + + def test_a_hook_listed_twice_fails(self): + root, paths = self.tree('{"unused": {"ev_prose": "a", "ev_prose": "b"}}') + self.assertEqual(hook_coverage.problems(root, paths), ['%s: %s lists a hook twice' % ((hook_coverage.ALLOW,) * 2)]) + + +if __name__ == '__main__': + unittest.main()