diff --git a/.agents/skills/modwerk-diagnostics/SKILL.md b/.agents/skills/modwerk-diagnostics/SKILL.md index 832667edde..496ab94b61 100644 --- a/.agents/skills/modwerk-diagnostics/SKILL.md +++ b/.agents/skills/modwerk-diagnostics/SKILL.md @@ -9,7 +9,7 @@ If the developer is not the owner, say that shared diagnostics are private to th The records are private. Tester names and anything quoted from a record stay in chat and in `~/.cache/modwerk-local/`: never in a commit, pull request, issue, changelog or document. There, write "a tester" and only the technical fact. -1. **Pull.** `git fetch`, then `npm run diagnostics:pull` on Node 24. The summary is long, so write it to `~/.cache/modwerk-local/diagnostics/pull-.txt` and read its Problems section first; every record is in `~/.cache/modwerk-local/diagnostics/latest.json` (UTC). What the summary means, its known noise and an HTTP 403 are in `docs/MAINTENANCE.md#beta-worker`; the record schema is `src/community/octatrack-diagnostics-contract.ts`. With an argument, read only that member's, module's or symptom's records. +1. **Pull.** `git fetch`, then `npm run diagnostics:pull` on Node 24. The summary is long, so write it to `~/.cache/modwerk-local/diagnostics/pull-.txt` and read its Problems section first; every record is in `~/.cache/modwerk-local/diagnostics/latest.json` (UTC). What the summary means, its known noise and an HTTP 403 are in `docs/MAINTENANCE.md#beta-worker`; the record schema is `src/community/octatrack-diagnostics-contract.ts`. With an argument, read only that member's, module's or symptom's records. A member who does not share can hand over the same records themselves: Copy details or a saved `modwerk-support-*.txt` after a USB error, or the USB events block of a report they posted; read their JSON lines with `parseSupportFile` (`src/community/support-report.ts`). 2. **Sort the failures into causes**, not records: sync and link failures, build failures, browser errors, unresponsive units, stalls and crashes in device logs, restores that were not `RESTORED`, CPU or DSP near the limit. One cause is one line: what happens, on which base, set, browser and OS, how many units, first and last seen. 3. **Drop what is not open.** For each cause check, in this order: the unit's base and module versions against what is live (an old build's bug that `changelog/` or the module's changelog already fixed is done), the open issues and pull requests (`gh issue list`, `gh pr list`), the findings in `docs/OCTATRACK_BETA_TEST_PLAN.md`, and the stock OS's own behaviour. Say which it was. 4. **Prove the rest before fixing it.** Find the code the record points at and reproduce the failure in a test, over HTTP, or with the developer MCP. On the owner's computer, take a turn through the [unit queue](../../../docs/OCTATRACK_DRIVING.md#taking-turns-on-the-unit) for hardware reproduction (`/modwerk-test-on-unit`). Confirm the shared emulator is free before starting it. A cause you cannot reproduce is a hypothesis: say what would confirm it, and add the missing diagnostic field or log line as the fix if that is what stands in the way. Never ask a tester to run tests. diff --git a/.agents/skills/modwerk-new-module/SKILL.md b/.agents/skills/modwerk-new-module/SKILL.md index e5901018ef..c35cad4ca7 100644 --- a/.agents/skills/modwerk-new-module/SKILL.md +++ b/.agents/skills/modwerk-new-module/SKILL.md @@ -32,7 +32,7 @@ Follow `docs/ADD_A_MODULE.md` and the rules in `AGENTS.md`, in this order. 7. **Test** with `/modwerk-test-on-unit`, which runs `docs/TEST_PROCEDURE.md` (`npm run test:procedure -- `) and the module's own edge cases: your own tests on their unit first, then theirs; without a unit, in the emulator. Record only what was observed, on the named build. 8. **Finish,** once the developer says testing is done (until then, the pull request stays a draft): - docs, credits, and a thumbnail in the shared style (`docs/ADD_A_MODULE.md#module-thumbnail-style`); - - release notes in `src/community/module-changelogs/`; + - release notes in `src/community/module-changelogs/` (an Octatrack DSP effect: `npm run module:list -- ` moves the draft and its notes into place and writes its listing); - review it as the owner will, against the pull request worker's checklist and the rules contributions most often break (`docs/MAINTENANCE.md#pull-request-worker`), and have a fresh agent session that never saw the work review the diff (in Claude Code, `/code-review`); fix what applies; - then `/modwerk-pr-ready`, and mark the draft ready. diff --git a/.agents/skills/modwerk-pr-ready/SKILL.md b/.agents/skills/modwerk-pr-ready/SKILL.md index 5ee9ed995c..225654432d 100644 --- a/.agents/skills/modwerk-pr-ready/SKILL.md +++ b/.agents/skills/modwerk-pr-ready/SKILL.md @@ -12,7 +12,7 @@ Follow `docs/DEVELOPER_WORKFLOW.md#make-it-mergeable`. 3. **Check once.** For a new commit, stage the intended files and run `npm run pr:ready -- --commit "Message"`. For an existing commit, run `npm run pr:ready`. For a registered author, use `npm run pr:ready -- --author ` and include the same `--author` option when committing. Let each command manage its own machine slot so other worktrees can run while you push or watch GitHub. Not before draft pushes: between fixes, run the tests you touched or `npm run check -- --base origin/main --rerun-failed`. - On a replay assignment, read the printed TASK.md, attempt it in its snapshot and repeat the same command with `--eval-agent ""`. Do this yourself on the first attempt, including when you could only partly solve it. The score stays on this computer ([agent evals](../../../docs/AGENT_EVALS.md)). - It also claims on the agent board what the branch adds (a new module, hook or table index, migration) and stops when someone else holds one. Never work around a claim: renumber, rename or ask its holder yourself. Signed out, it asks for `npm run board -- login` first. When it notes questions or replies in the developer's board inbox, read them (`npm run board -- inbox`), answer them yourself from what you can check, close your settled ones, and tell the developer what you said; only a decision about their own work goes to them first. When it offers a finding, post it yourself. -4. **Push.** For base work, find the draft from `base/-next`, push the commits directly to its branch and update its description. A contributor working from a fork links their commits there for a maintainer. Start the machine’s cumulative draft only when none exists. The owner marks it ready after extensive unit testing ([Change a base](../../../docs/DEVELOPER_WORKFLOW.md#change-a-base)). For other work, update the existing PR. If the work and required testing are done and a one-sitting fix has no PR yet, open it ready with `gh pr create`. For work with testing or review preparation still pending, [open a draft early](../../../docs/DEVELOPER_WORKFLOW.md#open-a-draft-early) with `gh pr create --draft`. If it changes what runs on an instrument (a `.mwrm` package or `.elemod` base), mark it ready only after the developer has tested that exact build on a unit. Give the result its own line ("Tested on a unit: base 8d1db124, MKII, what ran", or "Not tested on a unit: "). Draft or ready, list the change's edge cases under "Edge cases", using the table `npm run test:procedure` writes or "Edge cases: none, because …" (`docs/TEST_PROCEDURE.md`). CI checks both. Write the title and description using the PR template. Answer what the guides lacked ("Guides: nothing" is fine). +4. **Push.** For base work, find the draft from `base/-next`, push the commits directly to its branch and update its description. A contributor working from a fork links their commits there for a maintainer. Start the machine’s cumulative draft only when none exists. The owner marks it ready after extensive unit testing ([Change a base](../../../docs/DEVELOPER_WORKFLOW.md#change-a-base)). For other work, update the existing PR. If the work and required testing are done and a one-sitting fix has no PR yet, open it ready with `gh pr create`. For work with testing or review preparation still pending, [open a draft early](../../../docs/DEVELOPER_WORKFLOW.md#open-a-draft-early) with `gh pr create --draft`. If it changes what runs on an instrument (a `.mwrm` package or `.elemod` base), mark it ready only after the developer has tested that exact build on a unit. Give the result its own line ("Tested on a unit: base 8d1db124, MKII, what ran", or "Not tested on a unit: "). Draft or ready, list the change's edge cases under "Edge cases", using the table `npm run test:procedure` writes or "Edge cases: none, because …" (`docs/TEST_PROCEDURE.md`). CI checks both. Write the title and description using the PR template, save the description to a file and run `npm run pr:body -- FILE.md` (`--draft` for a draft) before you open the PR or save an edit; it applies CI's describe check. Answer what the guides lacked ("Guides: nothing" is fine). - **Finish the GitHub handoff yourself.** After pushing a finished contribution and passing full `pr:ready`, read `gh pr view --json state,headRefOid,isDraft`. Check that the open PR has the tested head. With the required testing recorded, run `gh pr ready ` if it is a draft. Read the PR again and confirm the same head shows `isDraft: false`. If the head changed, check the new commit first. If it stays a draft, name the remaining task and its owner. This also applies to a contributor PR targeting `base/-next`. The owner promotes the cumulative PR from that branch into `main` after extensive unit testing. - Watch `gh pr checks --watch` until green. For a red job, read `gh run view --log-failed`. - If `main` moves before the merge, start again at 1. diff --git a/.claude/skills/modwerk-diagnostics/SKILL.md b/.claude/skills/modwerk-diagnostics/SKILL.md index 832667edde..496ab94b61 100644 --- a/.claude/skills/modwerk-diagnostics/SKILL.md +++ b/.claude/skills/modwerk-diagnostics/SKILL.md @@ -9,7 +9,7 @@ If the developer is not the owner, say that shared diagnostics are private to th The records are private. Tester names and anything quoted from a record stay in chat and in `~/.cache/modwerk-local/`: never in a commit, pull request, issue, changelog or document. There, write "a tester" and only the technical fact. -1. **Pull.** `git fetch`, then `npm run diagnostics:pull` on Node 24. The summary is long, so write it to `~/.cache/modwerk-local/diagnostics/pull-.txt` and read its Problems section first; every record is in `~/.cache/modwerk-local/diagnostics/latest.json` (UTC). What the summary means, its known noise and an HTTP 403 are in `docs/MAINTENANCE.md#beta-worker`; the record schema is `src/community/octatrack-diagnostics-contract.ts`. With an argument, read only that member's, module's or symptom's records. +1. **Pull.** `git fetch`, then `npm run diagnostics:pull` on Node 24. The summary is long, so write it to `~/.cache/modwerk-local/diagnostics/pull-.txt` and read its Problems section first; every record is in `~/.cache/modwerk-local/diagnostics/latest.json` (UTC). What the summary means, its known noise and an HTTP 403 are in `docs/MAINTENANCE.md#beta-worker`; the record schema is `src/community/octatrack-diagnostics-contract.ts`. With an argument, read only that member's, module's or symptom's records. A member who does not share can hand over the same records themselves: Copy details or a saved `modwerk-support-*.txt` after a USB error, or the USB events block of a report they posted; read their JSON lines with `parseSupportFile` (`src/community/support-report.ts`). 2. **Sort the failures into causes**, not records: sync and link failures, build failures, browser errors, unresponsive units, stalls and crashes in device logs, restores that were not `RESTORED`, CPU or DSP near the limit. One cause is one line: what happens, on which base, set, browser and OS, how many units, first and last seen. 3. **Drop what is not open.** For each cause check, in this order: the unit's base and module versions against what is live (an old build's bug that `changelog/` or the module's changelog already fixed is done), the open issues and pull requests (`gh issue list`, `gh pr list`), the findings in `docs/OCTATRACK_BETA_TEST_PLAN.md`, and the stock OS's own behaviour. Say which it was. 4. **Prove the rest before fixing it.** Find the code the record points at and reproduce the failure in a test, over HTTP, or with the developer MCP. On the owner's computer, take a turn through the [unit queue](../../../docs/OCTATRACK_DRIVING.md#taking-turns-on-the-unit) for hardware reproduction (`/modwerk-test-on-unit`). Confirm the shared emulator is free before starting it. A cause you cannot reproduce is a hypothesis: say what would confirm it, and add the missing diagnostic field or log line as the fix if that is what stands in the way. Never ask a tester to run tests. diff --git a/.claude/skills/modwerk-new-module/SKILL.md b/.claude/skills/modwerk-new-module/SKILL.md index e5901018ef..c35cad4ca7 100644 --- a/.claude/skills/modwerk-new-module/SKILL.md +++ b/.claude/skills/modwerk-new-module/SKILL.md @@ -32,7 +32,7 @@ Follow `docs/ADD_A_MODULE.md` and the rules in `AGENTS.md`, in this order. 7. **Test** with `/modwerk-test-on-unit`, which runs `docs/TEST_PROCEDURE.md` (`npm run test:procedure -- `) and the module's own edge cases: your own tests on their unit first, then theirs; without a unit, in the emulator. Record only what was observed, on the named build. 8. **Finish,** once the developer says testing is done (until then, the pull request stays a draft): - docs, credits, and a thumbnail in the shared style (`docs/ADD_A_MODULE.md#module-thumbnail-style`); - - release notes in `src/community/module-changelogs/`; + - release notes in `src/community/module-changelogs/` (an Octatrack DSP effect: `npm run module:list -- ` moves the draft and its notes into place and writes its listing); - review it as the owner will, against the pull request worker's checklist and the rules contributions most often break (`docs/MAINTENANCE.md#pull-request-worker`), and have a fresh agent session that never saw the work review the diff (in Claude Code, `/code-review`); fix what applies; - then `/modwerk-pr-ready`, and mark the draft ready. diff --git a/.claude/skills/modwerk-pr-ready/SKILL.md b/.claude/skills/modwerk-pr-ready/SKILL.md index 5ee9ed995c..225654432d 100644 --- a/.claude/skills/modwerk-pr-ready/SKILL.md +++ b/.claude/skills/modwerk-pr-ready/SKILL.md @@ -12,7 +12,7 @@ Follow `docs/DEVELOPER_WORKFLOW.md#make-it-mergeable`. 3. **Check once.** For a new commit, stage the intended files and run `npm run pr:ready -- --commit "Message"`. For an existing commit, run `npm run pr:ready`. For a registered author, use `npm run pr:ready -- --author ` and include the same `--author` option when committing. Let each command manage its own machine slot so other worktrees can run while you push or watch GitHub. Not before draft pushes: between fixes, run the tests you touched or `npm run check -- --base origin/main --rerun-failed`. - On a replay assignment, read the printed TASK.md, attempt it in its snapshot and repeat the same command with `--eval-agent ""`. Do this yourself on the first attempt, including when you could only partly solve it. The score stays on this computer ([agent evals](../../../docs/AGENT_EVALS.md)). - It also claims on the agent board what the branch adds (a new module, hook or table index, migration) and stops when someone else holds one. Never work around a claim: renumber, rename or ask its holder yourself. Signed out, it asks for `npm run board -- login` first. When it notes questions or replies in the developer's board inbox, read them (`npm run board -- inbox`), answer them yourself from what you can check, close your settled ones, and tell the developer what you said; only a decision about their own work goes to them first. When it offers a finding, post it yourself. -4. **Push.** For base work, find the draft from `base/-next`, push the commits directly to its branch and update its description. A contributor working from a fork links their commits there for a maintainer. Start the machine’s cumulative draft only when none exists. The owner marks it ready after extensive unit testing ([Change a base](../../../docs/DEVELOPER_WORKFLOW.md#change-a-base)). For other work, update the existing PR. If the work and required testing are done and a one-sitting fix has no PR yet, open it ready with `gh pr create`. For work with testing or review preparation still pending, [open a draft early](../../../docs/DEVELOPER_WORKFLOW.md#open-a-draft-early) with `gh pr create --draft`. If it changes what runs on an instrument (a `.mwrm` package or `.elemod` base), mark it ready only after the developer has tested that exact build on a unit. Give the result its own line ("Tested on a unit: base 8d1db124, MKII, what ran", or "Not tested on a unit: "). Draft or ready, list the change's edge cases under "Edge cases", using the table `npm run test:procedure` writes or "Edge cases: none, because …" (`docs/TEST_PROCEDURE.md`). CI checks both. Write the title and description using the PR template. Answer what the guides lacked ("Guides: nothing" is fine). +4. **Push.** For base work, find the draft from `base/-next`, push the commits directly to its branch and update its description. A contributor working from a fork links their commits there for a maintainer. Start the machine’s cumulative draft only when none exists. The owner marks it ready after extensive unit testing ([Change a base](../../../docs/DEVELOPER_WORKFLOW.md#change-a-base)). For other work, update the existing PR. If the work and required testing are done and a one-sitting fix has no PR yet, open it ready with `gh pr create`. For work with testing or review preparation still pending, [open a draft early](../../../docs/DEVELOPER_WORKFLOW.md#open-a-draft-early) with `gh pr create --draft`. If it changes what runs on an instrument (a `.mwrm` package or `.elemod` base), mark it ready only after the developer has tested that exact build on a unit. Give the result its own line ("Tested on a unit: base 8d1db124, MKII, what ran", or "Not tested on a unit: "). Draft or ready, list the change's edge cases under "Edge cases", using the table `npm run test:procedure` writes or "Edge cases: none, because …" (`docs/TEST_PROCEDURE.md`). CI checks both. Write the title and description using the PR template, save the description to a file and run `npm run pr:body -- FILE.md` (`--draft` for a draft) before you open the PR or save an edit; it applies CI's describe check. Answer what the guides lacked ("Guides: nothing" is fine). - **Finish the GitHub handoff yourself.** After pushing a finished contribution and passing full `pr:ready`, read `gh pr view --json state,headRefOid,isDraft`. Check that the open PR has the tested head. With the required testing recorded, run `gh pr ready ` if it is a draft. Read the PR again and confirm the same head shows `isDraft: false`. If the head changed, check the new commit first. If it stays a draft, name the remaining task and its owner. This also applies to a contributor PR targeting `base/-next`. The owner promotes the cumulative PR from that branch into `main` after extensive unit testing. - Watch `gh pr checks --watch` until green. For a red job, read `gh run view --log-failed`. - If `main` moves before the merge, start again at 1. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 88fbabf801..adf058c3cd 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -9,6 +9,8 @@ **A module or module update:** describe the change in behaviour, module version(s), compatibility and source/media attribution. Run it through [the test procedure](../docs/TEST_PROCEDURE.md) and give its "Tested on a unit" line and its edge-case table under a line "Edge cases". Then say what the guides lacked or got wrong while you built it and link the `Docs:` pull request that fixes it, or write "nothing"; the module release itself stays free of guide edits. +Before you save this description, `npm run pr:body -- FILE.md` (add `--draft` for a draft) checks it as CI's describe check will. + The checks do the rest. `npm run pr:ready` (a registered author: `npm run pr:ready -- --author `) runs what CI runs: the module contract, version and release notes, compatibility and UI claims, resource and qualification records, documentation and licences. A pull request with a red check is labelled `needs-work` and leaves the review queue until it is green; after 14 days without a new commit it is closed, and you can reopen it once it is green. Until your first module is published, one module pull request is reviewed at a time. No check can prove these, so you vouch for them: diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 90482cdca2..ddc2f09b9e 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -15,6 +15,8 @@ concurrency: cancel-in-progress: false jobs: approval: + # Only Modwerk publishes; every later job needs this one, so a fork that syncs main skips them all and mails no one. + if: github.repository == 'repeat98/modwerk' runs-on: ubuntu-24.04 timeout-minutes: 5 permissions: diff --git a/.github/workflows/worker.yml b/.github/workflows/worker.yml index a0851eb0e1..8a82787317 100644 --- a/.github/workflows/worker.yml +++ b/.github/workflows/worker.yml @@ -15,6 +15,8 @@ concurrency: cancel-in-progress: false jobs: scope: + # Only Modwerk deploys. A fork that syncs main would run this, fail without the secrets and mail its owner. + if: github.repository == 'repeat98/modwerk' runs-on: ubuntu-24.04 timeout-minutes: 5 permissions: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7a9790f5af..c4d271dc19 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,6 +4,8 @@ Existing published module authors may use the [automatic author-update workflow] Contribute modules, fixes, documentation, screenshots and audio as pull requests to this repository. The owner approves first releases and changes beyond registered-author scope; later scoped author updates can publish automatically after evidence verification and required checks; the website has no second approval step. Guest comments and author issue reports on the site need no registration. +New here, or sitting on a fork? [Make your own mod](https://modwerk.app/submit/?utm_source=github-contributing) walks you through it: agree the plan with your agent, build, test on your unit or in the emulator, open the pull request, get it reviewed and check it live. Work that stays in a fork never reaches Modwerk; only a pull request here does. + ## Modules Follow [Add or port a module](docs/ADD_A_MODULE.md). It covers porting from octabam or elekloader and writing your own, for every machine, with the commands to run. Read [the guide for your module's category](docs/module-guides/README.md) before you write it: it says how a module must behave beside parameter locks, LFOs, scenes, saved projects and other modules, and a module that acts in time uses the instrument's own tempo, track speed and swing. `npm run module:doctor -- ` must be green. diff --git a/LICENSES/platform.json b/LICENSES/platform.json index 50842fca41..4393ed618b 100644 --- a/LICENSES/platform.json +++ b/LICENSES/platform.json @@ -42,6 +42,7 @@ "src/community/profile-links.ts", "src/community/remote-session-contract.ts", "src/community/report-closure.ts", + "src/community/support-report.ts", "src/community/usage-contract.ts", "src/community/usage-pages.ts", "src/config/beta-invitation.ts", diff --git a/MODDING_GUIDELINES.md b/MODDING_GUIDELINES.md index 8c5e788ab8..d2e3f74dfd 100644 --- a/MODDING_GUIDELINES.md +++ b/MODDING_GUIDELINES.md @@ -23,6 +23,14 @@ These rules protect the makers' copyright and the goodwill that lets modding exi - **Keep firmware on its instrument.** No plugin, app or emulator that lets people use a maker's firmware without the instrument. Developer emulators that run your own OS on your own computer to test modules are fine. - **Don't pass as official.** A modified build shows that it is modified wherever the instrument allows, for example on its start-up screen. Makers' names appear only to say what something works with ("modules for the Elektron Octatrack"), never as the name of a module or a build. Modwerk is independent: it is not affiliated with, endorsed by or supported by any maker. +## Respect the instrument + +An instrument that does exactly what it was built for is a joy to play and easy to understand. Mods add to it the way plugins add to a studio. They don't turn it into something else. + +- **Build for this panel.** A feature follows the instrument's own labels, button layout and way of working, so every control still does what it says. +- **No one-to-one copies of another instrument.** A feature or workflow taken from another instrument is redesigned for this one, not carried over screen for screen. Copied unchanged, its controls stop matching their labels. +- **Keep it focused.** Make the instrument better at what it is. Don't turn it into a general-purpose machine where nobody can tell what does what. + ## Keep a way back - An instrument gets public downloads only once its official OS restores it, with the steps written down. diff --git a/README.md b/README.md index 926433ed60..37823606b4 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@

Independent and unofficial. Not affiliated with, endorsed by or supported by Elektron.

Get started · + Make your own mod · SDK guide · Add or port a module · Contribute diff --git a/changelog/2026-11-24-cycle-scan-like-cases.md b/changelog/2026-11-24-cycle-scan-like-cases.md new file mode 100644 index 0000000000..68b2d81591 --- /dev/null +++ b/changelog/2026-11-24-cycle-scan-like-cases.md @@ -0,0 +1 @@ +Development: `node scripts/cycle-scan.mjs unit` compares a unit reading with the scan's model only when both are the same case (package, setting, transport, what the key bus carried for a key-bus effect, and the base a base charge was timed on), and prints "not comparable" with the reason otherwise; it compares a reading's DSP peak, where it kept one, with the dearest setting. The table in `sdk/cycle-scan/README.md` is now written by `unit --write`, and `cycle-scan check` fails when it differs (it still charged the key bus 51 after the charge became 43). diff --git a/changelog/2026-11-24-device-price-peaks.md b/changelog/2026-11-24-device-price-peaks.md new file mode 100644 index 0000000000..66e6ceb9f8 --- /dev/null +++ b/changelog/2026-11-24-device-price-peaks.md @@ -0,0 +1 @@ +Development: `npm run device:price` now keeps each DSP core's peak beside its mean and takes three readings of every state by default (`--readings`), so `evidence/cpu-price.json` records the worst block each core saw and how far the readings agreed (`spread`); `--key-bus live|silent` records what the key bus carried. Older records load unchanged, and `module:doctor` names the spread of a record that has one. diff --git a/changelog/2026-11-24-usb-support-details.md b/changelog/2026-11-24-usb-support-details.md new file mode 100644 index 0000000000..15d5153cea --- /dev/null +++ b/changelog/2026-11-24-usb-support-details.md @@ -0,0 +1 @@ +Your Octatrack: after a failed sync, connection, self-test or base update, **Copy details** and **Save report** next to the error give you what went wrong, the base with its USB Audio layout and the last USB events, to paste in a message or keep as a file. The page keeps its last 100 USB events in memory whether or not you share diagnostics, and sends none of them by itself. **Report a problem** now fills in what the Octatrack runs and the last error, and offers to attach those events; you see what is attached and can remove it before posting. A failed base update that changes only the USB Audio layout now names the layout ("came back on base 0.8.1 (USB Audio off)") instead of reading like the same base. diff --git a/changelog/2026-11-24-zoom-printed-model.md b/changelog/2026-11-24-zoom-printed-model.md new file mode 100644 index 0000000000..0557609970 --- /dev/null +++ b/changelog/2026-11-24-zoom-printed-model.md @@ -0,0 +1 @@ +Zoom pedal page: before flashing the base, and before the first effect install, removal or sync on a connection, the page asks you to confirm the model printed on your pedal. An MS-50G running MIDISTOMP answers over USB exactly like an MS-70CDR, so the page could not tell them apart. diff --git a/changelog/2026-11-25-board-wait.md b/changelog/2026-11-25-board-wait.md new file mode 100755 index 0000000000..e05e550b9c --- /dev/null +++ b/changelog/2026-11-25-board-wait.md @@ -0,0 +1 @@ +Agent board: `npm run board -- wait ` ends as soon as someone else answers that thread, and without an id when anything new reaches your inbox. It checks once a minute, prints the thread, and gives up after `--minutes` (default 60) with exit code 3, so an agent can run it in the background after asking instead of the developer telling it to check. In a contributor session shared on 24 November, 19 of 99 prompts were "check the messages". diff --git a/changelog/2026-11-25-dsp-gate-library.md b/changelog/2026-11-25-dsp-gate-library.md new file mode 100644 index 0000000000..829d33bb3a --- /dev/null +++ b/changelog/2026-11-25-dsp-gate-library.md @@ -0,0 +1 @@ +SDK: Octatrack DSP effects get a shared host-test harness, `sdk/octatrack/tools/dsp_gate.py`. It finds dsp_asm, dsp_host and the disassembler, assembles a module, writes the synthetic image, runs one to eight instances (knobs, automation, splits, both cores, garbage state, the guard), checks the assembler traps and renders `npm run fx:audit`'s signals. A module's `verify.py` imports it instead of copying another module's gate, as Resonator's was copied into five modules before Mackity. Porting an Airwindows plugin starts with `npm run module:new -- --kind dsp --port airwindows --upstream `. It copies upstream's files at the checked-out commit with their import record and adds a reference model, its host test, `verify.py` and `perf.py` on the harness. diff --git a/changelog/2026-11-25-evidence-hashes-as-git-stores.md b/changelog/2026-11-25-evidence-hashes-as-git-stores.md new file mode 100644 index 0000000000..7e357834c3 --- /dev/null +++ b/changelog/2026-11-25-evidence-hashes-as-git-stores.md @@ -0,0 +1 @@ +Development: a module's evidence hashes (its qualification source, folder and performance stamp) read each text file with the LF line endings Git stores, so a file saved with CRLF on Windows no longer passes `modules:check` and `module:doctor` locally and fails in CI (Mackity's thumbnail, #2148). The performance stamp leaves the library card's art (`presentation/`) out, as the package fingerprint does, so new art needs no new stamp; a stamp written before keeps holding until the source changes. `module:doctor` names a module's CRLF files and fails those the compiler reads, whose package fingerprint would still differ from CI's. diff --git a/changelog/2026-11-25-fork-ci-guard.md b/changelog/2026-11-25-fork-ci-guard.md new file mode 100644 index 0000000000..af4be2079a --- /dev/null +++ b/changelog/2026-11-25-fork-ci-guard.md @@ -0,0 +1 @@ +Forks: syncing a fork's `main` no longer runs the Worker deploy or the site publish there. Both workflows ran on every push to `main` in any repository, failed in a fork for want of the secrets, and mailed the fork's owner a failure for something they never started (seen by a contributor on 23 November). The first job of `worker.yml` and `pages.yml` now runs only in `repeat98/modwerk`, and the jobs after it are skipped with it. diff --git a/changelog/2026-11-25-kofi-webhook.md b/changelog/2026-11-25-kofi-webhook.md new file mode 100644 index 0000000000..a3af7acad9 --- /dev/null +++ b/changelog/2026-11-25-kofi-webhook.md @@ -0,0 +1 @@ +Support: the bar for how much of the running costs Ko-fi tips cover now fills itself. Ko-fi reports each payment to the Worker, which keeps only the amount, currency, month and Ko-fi’s message ID; names, email addresses and messages are not stored. Ko-fi’s test payments are not counted. The bar appears once the owner connects the webhook (docs/KOFI_WEBHOOK.md). diff --git a/changelog/2026-11-25-mcp-follows-checkout.md b/changelog/2026-11-25-mcp-follows-checkout.md new file mode 100644 index 0000000000..def93970a0 --- /dev/null +++ b/changelog/2026-11-25-mcp-follows-checkout.md @@ -0,0 +1 @@ +The developer MCP rebuilds its copy of the site when the checkout changes (a branch switch or a base regeneration), so device tools know the new base without reconnecting the server. diff --git a/changelog/2026-11-25-module-list.md b/changelog/2026-11-25-module-list.md new file mode 100644 index 0000000000..851e5c1df5 --- /dev/null +++ b/changelog/2026-11-25-module-list.md @@ -0,0 +1 @@ +Development: `npm run module:list -- ` lists an Octatrack DSP-effect draft in one step: it moves the folder and its release notes into place and writes the catalogue entry, build order, descriptor guard, package row and, for a port, the import record and licence entry, all done by hand for Mackity on 25 November 2026. `--dry-run` shows the changes first, and it prints the steps that still need Docker, the OS file or the unit. diff --git a/changelog/2026-11-25-module-qualify.md b/changelog/2026-11-25-module-qualify.md new file mode 100644 index 0000000000..283f482620 --- /dev/null +++ b/changelog/2026-11-25-module-qualify.md @@ -0,0 +1 @@ +Development: `npm run module:qualify -- --procedure DIR --base TEXT` writes a module's release record from its evidence. It reads the test procedure's record and `price.json`, the tested package, the perf:audit record and the screen captures. From them it writes `tests.qualification`, the measured gauges and the CPU price and instance curve, and computes `sourceSha256` last. Words a person has to stand behind are kept as written, or drafted and marked for the author to edit. `--check` and `module:doctor` report a stale `sourceSha256` with the command that refreshes it. `device:price --write` and the test procedure (`--price-base TEXT`) now write a draft's price and curve into `sdk/drafts/` too. diff --git a/changelog/2026-11-25-octatrack-part-read-sram.md b/changelog/2026-11-25-octatrack-part-read-sram.md new file mode 100644 index 0000000000..0155d705e3 --- /dev/null +++ b/changelog/2026-11-25-octatrack-part-read-sram.md @@ -0,0 +1 @@ +Octatrack base 0.8.2: every frame costs about one point of CPU less. Sixteen times every audio frame the Octatrack looks up which Part is playing, and it read that from a slow part of its memory although the same value sits in its fast on-chip memory, written there at the same moments. The base now reads the fast copy. On an MKII the frame interrupt fell from 37.0 to 36.0 % on a busy pattern and from 29.8 to 28.8 % stopped; the sound and every value the DSPs receive stay the same. diff --git a/changelog/2026-11-25-pr-body-local.md b/changelog/2026-11-25-pr-body-local.md new file mode 100644 index 0000000000..e40a334b37 --- /dev/null +++ b/changelog/2026-11-25-pr-body-local.md @@ -0,0 +1 @@ +Development: `npm run pr:body -- FILE.md` checks a pull request description before you open or edit the pull request, with the rules of CI's describe check and this branch's changed files (`--draft` for a draft, `--changed-since ` for another base, `-` for stdin); `npm run pr:ready -- --body FILE.md` runs the same check. A failing edge-case table now names each unfinished row and what it lacks, for example a result that says "not run" without why. diff --git a/changelog/2026-11-25-price-curve-cost-table.md b/changelog/2026-11-25-price-curve-cost-table.md new file mode 100644 index 0000000000..22dec7b6ec --- /dev/null +++ b/changelog/2026-11-25-price-curve-cost-table.md @@ -0,0 +1 @@ +Development: `npm run device:price -- --curve` installs the module with this checkout's frame cost table and the module's `each` booked at 0, so a stale booking no longer refuses or hushes the second instance the curve is there to measure (Grain 0.1.3 on 24 November 2026: each booked at its first, 33.3). Its first instance and the admission runs are still judged as booked, and afterwards it sends this checkout's own table back, which the unit keeps. `npm run device -- set` takes `--costs FILE` for that. diff --git a/changelog/2026-11-25-ram-boot-pending-update.md b/changelog/2026-11-25-ram-boot-pending-update.md new file mode 100644 index 0000000000..8ff1550581 --- /dev/null +++ b/changelog/2026-11-25-ram-boot-pending-update.md @@ -0,0 +1 @@ +Developer tools: `npm run device -- boot` no longer RAM-boots over a base update that is flashed but not yet confirmed. Each restart, a RAM boot included, spends one of the update's two starts, and with both spent the Octatrack went back to its previous base. The command now waits for the update to confirm itself when the unit is running it, and otherwise refuses with the steps to confirm it first (`--spend-tries` boots anyway). diff --git a/changelog/2026-11-25-respect-the-instrument.md b/changelog/2026-11-25-respect-the-instrument.md new file mode 100644 index 0000000000..8ed3dd3128 --- /dev/null +++ b/changelog/2026-11-25-respect-the-instrument.md @@ -0,0 +1 @@ +Modding guidelines: a new section, Respect the instrument. Mods are built for the instrument's own panel and way of working, features from another instrument are redesigned rather than copied one to one, and no mod turns an instrument into a general-purpose machine where nobody can tell what does what. diff --git a/changelog/2026-11-25-rytm-retired-modules-in-saved-sets.md b/changelog/2026-11-25-rytm-retired-modules-in-saved-sets.md new file mode 100644 index 0000000000..6b431c7faa --- /dev/null +++ b/changelog/2026-11-25-rytm-retired-modules-in-saved-sets.md @@ -0,0 +1 @@ +Analog Rytm MKII: a saved set that still names Ping-Pong Loop or Improved Performance opens again, without that module, instead of being listed as unreadable. The other modules in it stay. diff --git a/changelog/2026-11-25-session-share-new.md b/changelog/2026-11-25-session-share-new.md new file mode 100644 index 0000000000..f20701fe64 --- /dev/null +++ b/changelog/2026-11-25-session-share-new.md @@ -0,0 +1 @@ +Session sharing: `npm run session -- share --new` shares only what came after an earlier share of the same session. Sharing the rest of a long session meant fetching the last share, finding where it ended and listing every earlier entry with `--skip` by hand (seen in a contributor session shared in five parts, 24 November). `--new` reads your own shares made since the session started and leaves out each entry one of them already holds; `preview --new` shows the result first. diff --git a/changelog/2026-11-25-support-thank-you.md b/changelog/2026-11-25-support-thank-you.md new file mode 100644 index 0000000000..f33585d8fd --- /dev/null +++ b/changelog/2026-11-25-support-thank-you.md @@ -0,0 +1 @@ +Support: the screens that end an install (a kept USB sync, a saved card file, a downloaded .syx) carry one quiet line with the Ko-fi link. People who use Modwerk a lot get a short thank-you on a later visit, at most once in 60 days: after their 5th, 25th and 100th install, on their 10th and 30th day, or after installing the base. It explains the hosting and AI token costs, closes at once, and a Ko-fi click or Don't show again ends it. The support dialogs show the running costs, about €145 a month for hosting and AI tokens. The module check-in after an Octatrack sync no longer says "Inside your .bin". diff --git a/changelog/2026-11-25-test-procedure-put-back.md b/changelog/2026-11-25-test-procedure-put-back.md new file mode 100644 index 0000000000..9651492e93 --- /dev/null +++ b/changelog/2026-11-25-test-procedure-put-back.md @@ -0,0 +1 @@ +Development: `npm run test:procedure` leaves the test bank as it found it. Step 6 notes the bank, pattern and Part and whether the Part equals its saved copy (and SAVEs a clean one once, so RELOAD works after a RAM boot); after the soak and at put-back the runner goes back there and RELOADs that Part, then checks both copies. Put back runs after a failed unit step too, and fails with the fix when it cannot. The soak's program changes now stay in the bank the run started on. On 25 November every bank with trigs on the owner's unit had a Part left edited, and the next run refused to start. docs/TEST_PROCEDURE.md describes the test bank to run on. diff --git a/changelog/2026-11-25-unit-preflight.md b/changelog/2026-11-25-unit-preflight.md new file mode 100755 index 0000000000..917bd1fdb0 --- /dev/null +++ b/changelog/2026-11-25-unit-preflight.md @@ -0,0 +1 @@ +Development: `npm run test:procedure` reads the Octatrack before step 1, and again when its unit turn starts, and fails in seconds, before anything is built or installed, when the base does not answer development requests, the transport plays, the current Part differs from its saved copy, a module would be picked on a pattern with trigs on more than six tracks, or the MIDI bridge the soak needs does not answer or cannot send (`scripts/octatrack-preflight.py`). The MIDI bridge opens the unit's port again after a RAM boot instead of refusing every later message. diff --git a/docs/ADD_A_MODULE.md b/docs/ADD_A_MODULE.md index ac98d75472..6c1fb13c6b 100644 --- a/docs/ADD_A_MODULE.md +++ b/docs/ADD_A_MODULE.md @@ -15,7 +15,7 @@ Every module follows [the guide for its category](module-guides/README.md): effe | You want to | Go to | Start with | | --- | --- | --- | | Port an octabam module | [Octatrack](#octatrack) | the module's folder in octabam at an exact commit | -| Write a new Octatrack module | [Octatrack](#octatrack) | `npm run module:new -- my-filter --kind dsp --author ` (`--kind coldfire` for a CPU module), then `npm run module:dev -- my-filter` to hear it ([the fast loop](#the-fast-loop)) | +| Write a new Octatrack module | [Octatrack](#octatrack) | `npm run module:new -- my-filter --kind dsp --author ` (`--kind coldfire` for a CPU module), then `npm run module:dev -- my-filter` to hear it ([the fast loop](#the-fast-loop)); DSP gates import `sdk/octatrack/tools/dsp_gate.py`; an Airwindows port adds `--port airwindows --upstream ` ([how](../sdk/templates/dsp-port/README.md)) | | Bring an elekloader mod to Digitakt or Digitone | [Digitakt and Digitone](#digitakt-and-digitone) | the author's released `.elemod` files | | Write a new Digitakt or Digitone mod | [Digitakt and Digitone](#digitakt-and-digitone) | `npm run module:new -- my-mod --machine digitakt --author ` | | Write or port an Analog Rytm MKII mod | [the Rytm guide](../sdk/machines/analog-rytm-mkii/README.md) | `npm run module:new -- my-mod --machine analog-rytm-mkii --author ` | @@ -65,7 +65,7 @@ Keep unqualified Octatrack work under `sdk/drafts//`, with its draft release notes in `CHANGELOG.json`; `npm run module:new` starts it there. Every folder in `sdk/octatrack/modules/` is validated for publication even when absent from `sdk/catalog.json`, so a draft there blocks catalogue generation for -everyone. Move it there, and its notes into `src/community/module-changelogs/`, +everyone. List it there with `npm run module:list` ([step 4](#octatrack)) only when the publication requirements are met. A listed module's update waits as a draft PR, where CI and `pr:ready -- --draft` warn about its missing evidence; marking it ready requires it. @@ -83,10 +83,10 @@ a Modwerk base with the USB bridge ([driving the Octatrack](OCTATRACK_DRIVING.md `m68k-elf` binutils for ColdFire code and Octabam's `dsp_asm` for DSP code (`npm run upstream:tools`, then `make setup` in that octabam checkout), and no firmware. Hooks, entry points and state: [OCTATRACK_API.md](OCTATRACK_API.md). -Each trial ends with a verdict from the unit's own log: a crash, DSP stall, -frozen UI or skipped track during it fails the trial (exit 1), and it is -rolled back even with `--accept`; `npm run device -- do diaglog` shows the log. -Each incident names its boot and the seconds since that boot. +A crash, DSP stall, frozen UI or skipped track in the unit's log fails the +trial (exit 1) and rolls it back even with `--accept`; +`npm run device -- do diaglog` shows it, each incident with its boot and +seconds since. **Two tiers.** `module:doctor -- --draft ` judges a draft as experimental: the lines a trial and a tester need (category, DSP sources, cross-compatibility, @@ -103,7 +103,6 @@ A test that needs no firmware, unit or emulator goes in the module's folder as `module:doctor -- ` runs them (a draft's as a release line), and `npm run sdk:check` runs every listed module's on each pull request. Name an emulator or hardware script otherwise, such as `emulator_test.py`. - Run this after every edit: about 15 seconds, no firmware, no module code run. ```sh @@ -117,7 +116,7 @@ npm run modules:compat -- # Octatrack: installs beside every ## What CI runs -- **Documentation-only pull requests:** licence, generated catalogue, release-note coverage, module contract, tutorial and screenshot-provenance validation, plus the catalogue tests (`src/catalog`, about 15 seconds), because some of them check that the guides link to files that exist. No full application test suite, bundle, Windows runner or native compiler. +- **Documentation-only pull requests:** licence, generated catalogue, release-note coverage, module contract, tutorial and screenshot-provenance validation, plus the catalogue tests (`src/catalog`), which check the guides' links. No full application test suite, bundle, Windows runner or native compiler. - **Application or behaviour changes:** the full `npm run check` (lint, tests, types, build). - **Only a pull request that changes module source, the module build or the committed packages:** the Docker compile that must reproduce the committed packages. Changes to module folders or their path handling also run the Windows check. These are the same inputs the release uses to decide whether to rebuild the modules. - **After the merge:** the release verifies the merge approval, re-verifies the generated files, licences and module records, then type-checks and bundles what the pull request already tested. It rebuilds the modules only if module inputs changed. @@ -160,7 +159,7 @@ Documentation/media-only fixes add a clearly marked documentation-only or media- ## Documentation-only updates -Local module `README.md`, `TESTING.md` and `CPU.md` can be edited without updating import checksums. Their recorded hashes remain import history. Code, licences, archived snapshots and preserved `upstream/` documentation retain exact checksums. The lightweight `npm run sdk:imports:check` uses Node alone and runs on documentation PRs; the full SDK check at publication uses the same policy. +Local module `README.md`, `TESTING.md` and `CPU.md` can be edited without updating import checksums. Their recorded hashes remain import history. Code, licences, archived snapshots and preserved `upstream/` documentation retain exact checksums. `npm run sdk:imports:check` applies this on documentation PRs, as the SDK check does at publication. Fixing the README, tutorial, captions or screenshots of a module that has its qualification record needs none of the heavy steps: no version bump, rebuilt packages, fresh approval or Docker compile in CI when only README, Markdown, `media/`, `presentation/` or `evidence/` files change. Compiled packages bind to the module’s code fingerprint (`moduleSourceFingerprint` in `scripts/module-source.mjs`), which ignores those files and the manifest’s prose (`presentation`, `access`, `controls`, `tests`, `media`, and on Digitakt, Digitone, Rytm and Four the credited names and `compatibility.conflicts`). Any other manifest field, the `evidence` block included, still needs a greater version, so record a new hardware run in `TESTING.md`, `evidence/*.json` and `tests.summary`; older native evidence can also bind the thumbnail, so replace it through the [shared preview artwork path](#module-thumbnail-style). Open a normal pull request and run `npm run check -- --base origin/main`. In PR checks and deployment, prose and media skip native compilation; source, build inputs and compiler changes keep it. The frozen baseline modules, `cc-map` and `previewvol` keep their older exact-folder rules (see [retained evidence](MODULE_QUALIFICATION.md#risk-based-update-checks--3-october-2026)). @@ -200,13 +199,12 @@ SVG thumbnails consistent with the displayed illustration. - Keep diagrams conceptual. They must not imply measured audio, processor load, hardware verification or instrument-screen authenticity. -Older native qualification fingerprints and every owner-approved update's -`sourceSha256` include the original `presentation/thumbnail.svg`, even though -the compiled-package fingerprint excludes presentation files; changing it makes -`modules:generate` fail with "does not cover this exact native source". For -these modules, replace the displayed artwork -through an `ART` entry in `ModulePreview.tsx` and preserve the bound -asset; do not rewrite evidence hashes for an illustration change. +Native qualification fingerprints and owner-approved updates' `sourceSha256` +include `presentation/thumbnail.svg`; the package fingerprint and performance +stamp do not. Changing it makes `modules:generate` fail with "does not cover +this exact native source": replace the displayed art through an `ART` entry +in `ModulePreview.tsx` and keep the bound file; never rewrite evidence hashes +for art. They read text with Git's LF endings, so CRLF on Windows matches CI. ## Screenshot walkthroughs @@ -255,9 +253,7 @@ it needs no `--keeps-ok`. It also reads the self-test with the package installed and checks that the inventory at the end equals the one before; it has no crash test. Its entry lists what it leaves for the developer at the unit. It is the agent's own test before a developer gets a build -(`/modwerk-test-on-unit`); a release still needs `device:qualify`. Added on -12 November 2026 and not yet run on a unit: record what it does the first -time. +(`/modwerk-test-on-unit`); a release still needs `device:qualify`. **A private USB package of a draft.** `npm run module:dev -- --build-only` builds it ([the fast loop](#the-fast-loop)); it refuses a machine module, whose @@ -325,15 +321,15 @@ the [loader compatibility guide](../sdk/machines/octatrack/elekloader/README.md# - *Porting:* copy the module's folder from octabam at an exact commit into `sdk/octatrack/modules//`, and put the author's original files it depends on under `upstream/`. Record every copied file with its source path and SHA-256 in `sdk/imports/-.json`; `sidechain-compressor-f80ecfe.json` is an example. Add the licence to `sdk/octabam/licenses/manifest.json`, then run `npm run licenses:generate`. - *New:* `npm run module:new` creates the draft in `sdk/drafts//`. Pick a free effect ID, and replace `verify.py`, which fails on purpose until you do. - Either way, read the traps in [octabam's AGENTS.md](../sdk/octabam/AGENTS.md) before writing DSP or ColdFire code. The DSP assembler silently mis-encodes some instructions, and several of these traps assemble cleanly into the wrong machine code. -2. **Fill in the manifest** from [the template](../public/module-repository.example.json): every control, the access steps, compatibility and conflicts. Add the resource gauges (`resources.impact`, see [gauges](MODULE_RESOURCE_GAUGES.md)) and the qualification record (`tests.qualification`, see [fields](MODULE_QUALIFICATION.md)). +2. **Fill in the manifest** from [the template](../public/module-repository.example.json): every control, the access steps, compatibility and conflicts. The [gauges](MODULE_RESOURCE_GAUGES.md) and [`tests.qualification`](MODULE_QUALIFICATION.md) come from the evidence (step 3). 3. **Measure and test.** - - Record the worst-case cycles for each processor and the exact memory regions and totals. New FX should aim for DSP cost in the same ballpark as worst-case stock SPRING REV. Plan around that reference before implementation and compare expensive types/settings, moving controls and trigger splits under matched conditions on both cores. This is a design target without a fixed ratio or hard per-effect ceiling; substantially higher cost needs optimization and review of the remaining headroom. + - Record the worst-case cycles for each processor and the exact memory regions and totals. New FX should aim for DSP cost in the same ballpark as worst-case stock SPRING REV, measured under matched conditions on both cores ([the design target](MODULE_QUALIFICATION.md#worst-case-cycle-counts)). - For an effect, also check how it sounds: aliasing, clipping, DC and idle behaviour (`npm run fx:audit`, [effects guide](module-guides/effects.md#sound-quality)). Paste the table into TESTING.md, or write "not tested". No gate in CI runs it. - Name its CPU price in `resources.cpuPrice`, measured on a unit: what one playing track of a machine adds (`npm run device -- do`, `guard`), also its descriptor's `reserved[0]`; any other module's frame-interrupt share with `npm run device:price`. `modules:check` refuses a module without one ([format](MODULE_PERFORMANCE.md)). Every release proves its cost on a unit too ([what](TEST_PROCEDURE.md#what-a-release-measures)). - - Add a hardware report from a real unit, stating its model, how long it ran, what was tested and the limitations. There is no minimum duration or track count. + - Run [the test procedure](TEST_PROCEDURE.md) on a real unit, then write the record from its evidence, never by hand: `npm run module:qualify -- --procedure DIR --base TEXT --write` ([how](MODULE_QUALIFICATION.md#write-the-record-from-the-evidence)). The hardware report states the model, what was tested and the limitations; there is no minimum duration or track count. - A fix for a stock bug can be regressed in the emulator: `ot_emu`'s `call

[args]` runs a stock routine on a booted image, after `poke` has set up the state (Direct Jump Kyoti's `verify.py`, part 6, runs the MIDI Plays-Free stall on the original OS and on the module image). - If you could not test on hardware, say so in the pull request. Only the owner can waive this, for one exact version. -4. **List it and compile the packages without firmware.** The build compiles every module in `sdk/catalog.json`, so add an entry for yours first: `id`, `version` and `addedAt`, the UTC time it was first added (for example `2026-10-05T12:00:00Z`). From then on, `modules:check` also requires the complete qualification record, documentation and screenshots. Commit, then run this from the clean checkout. The output folder must not exist yet. +4. **List it and compile the packages without firmware.** The build compiles every module in `sdk/catalog.json`, so list yours first: for a DSP effect, `npm run module:list -- ` moves the draft into place and writes its listing (`--dry-run` shows what; it prints what stays by hand); for any other, add `id`, `version` and `addedAt` (UTC) to the catalogue. From then on, `modules:check` also requires the complete qualification record, documentation and screenshots. Commit, then run this from the clean checkout. The output folder must not exist yet. ```sh image=$(docker image inspect modwerk-source-tools --format '{{.Id}}') bash scripts/build-modules-isolated.sh . ../module-packages "$image" diff --git a/docs/AGENT_BOARD.md b/docs/AGENT_BOARD.md index a8ea131f32..d868534210 100644 --- a/docs/AGENT_BOARD.md +++ b/docs/AGENT_BOARD.md @@ -9,7 +9,7 @@ A claim has a kind and a key, and each key has one holder at a time: | Kind | Key | Example | | --- | --- | --- | | `module` | machine and module id | `octatrack/tape-echo`, `digitone/swarm` | -| `hook` | machine and hook or table index: its `index` in `sdk/machines/octatrack/events.json`, or its place in the core's `interface.json` on the elemod machines. Consecutive new indices are one claim on a run, which `pr:ready` makes and which takes the place of your own claims inside it | `octatrack/39`, `octatrack/38-51`, `digitakt/events/7`, `digitakt/tables/1` | +| `hook` | machine and hook or table index: its `index` in `sdk/machines/octatrack/events.json`, or its place in the core's `interface.json` on the elemod machines. Consecutive new indices are one claim on a run, which `pr:ready` makes and which takes the place of your own claims inside it. A run claimed ahead of the work also covers a branch that adds only part of it | `octatrack/39`, `octatrack/38-51`, `digitakt/events/7`, `digitakt/tables/1` | | `migration` | D1 migration number | `0085` | | `dsp-region` | machine and DSP memory claim name; no file declares these yet, so they are claimed by hand | `octatrack/fx2-delay-line` | | `machine-id` | machine and the id a manifest takes in `platform.claims` (`machine:`); kits store it, so like a hook index it is never renumbered | `digitakt/10` | @@ -31,7 +31,7 @@ A thread is a question, a finding or a wanted task about a **topic**: a claim's - **Findings** are for everyone: a trap, a measured limit, something a guide lacks, which another developer working now would hit before your pull request merges. The guide edit still rides on your pull request ([Share what you learn](DEVELOPER_WORKFLOW.md#share-what-you-learn)); give its number with `--pr ` (or `link --pr ` later; `fold` is the same) and the finding ends when that pull request merges, since the guide carries it. Otherwise it lapses after 90 days. - **Wanted tasks** are small, scoped jobs any signed-in developer posts for any agent to take: `npm run board -- wanted site configurator "…"`, with `--priority high` or `low` when it is not normal. Its author changes the priority with `priority `, and an administrator on Start developing, where the tasks stand as a board: to do, taken, in review and done, each with who took it. `npm run board -- messages --kind wanted` lists the open ones, most urgent first (`--machine ` for an instrument, `site` for the site). `take ` names you as its one holder, `--pr ` on `take` or `link` links your pull request, and the task ends when that merges. It lapses 90 days after it was posted, and its author closes it. - **Pull requests.** The hourly run checks each linked pull request: merged ends the thread, closed without merging only unlinks it. -- **Inbox.** `npm run board -- inbox` lists the questions waiting for your answer (to you, or to nobody about something you hold, and the last word is not yours) and the replies to what you wrote. +- **Inbox.** `npm run board -- inbox` lists the questions waiting for your answer (to you, or to nobody about something you hold, and the last word is not yours) and the replies to what you wrote. `npm run board -- wait` without an id ends when anything new arrives there. - **Limits.** At most 20 open threads per person, 50 replies per thread, and the 30 board writes an hour claims share. Authors delete their own posts (`delete `); administrators close or delete any on Start developing. ### When a question needs a GitHub follow-up @@ -52,6 +52,7 @@ The board is the agents' channel. Each agent runs its developer's side of it its - **says what it holds**: right after `module:new`, a one-line note of what the module does (`npm run board -- claim module --note "…"`); `pr:ready` fills an empty note from the manifest's summary; - **asks** as soon as its plan meets someone else's work: a claim on the same idea under another id, a hook, number or stock site it needs, a module it would touch; +- **waits for the answer itself**: after asking, it runs `npm run board -- wait ` in the background and reads the reply when that ends (exit 0 with the thread, 3 after `--minutes`, default 60), so the developer never has to tell it to check the board; - **shows** the open wanted tasks for the instrument or area it is about to work on (`/modwerk-start`, `/modwerk-contribute`), and takes one when the developer picks it; - **answers** the questions in its inbox as soon as a command names them, from what it can check in the code, the branch and the claims, and closes its own once settled; - **posts a finding** when it hits a trap another developer working now would hit; diff --git a/docs/AGENT_SESSIONS.md b/docs/AGENT_SESSIONS.md index 935bdb01b4..275347f3ea 100644 --- a/docs/AGENT_SESSIONS.md +++ b/docs/AGENT_SESSIONS.md @@ -26,6 +26,8 @@ When a task is done (`npm run pr:ready` says Ready, or the developer stops) and - **always**: the developer said to share every session. Share it and say so in a line. - **never**: the developer said not to be asked. Don't offer it. +A session that goes on after it was shared is shared again with `--new`: what the developer's earlier shares of it already hold stays out, so the owner gets only the rest, without working out `--skip` by hand. + When the developer answers "always" or "never", save it with `npm run session -- prefer always|never` (in `~/.config/modwerk/session-sharing.json`). Never share without a yes or a standing "always". Ask once per session, never twice. ## What leaves the computer diff --git a/docs/APP_DEVELOPMENT.md b/docs/APP_DEVELOPMENT.md index 7131c4d672..de5b1450a3 100644 --- a/docs/APP_DEVELOPMENT.md +++ b/docs/APP_DEVELOPMENT.md @@ -156,9 +156,7 @@ WaveSurfer's full BSD notice is included by `npm run licenses:generate`. ## Optional site support -The Ko-fi page is configured in `src/config/support.ts`. Set it to an empty string to hide the support entry. - -“Support Modwerk” appears under Resources in the desktop sidebar and in the mobile menu. Its “Contribute to Modwerk” dialog credits octabam and module authors, and links to Discord, the testing and bug-report forum, the code contribution guide and Ko-fi. Ko-fi opens in a new tab and handles the payment. Modwerk counts dialog opens and Ko-fi link clicks, including clicks from bell notifications, as site statistics. See [site statistics](STATISTICS.md). +`src/config/support.ts` holds the Ko-fi page (empty hides it) and `SUPPORT_COSTS`; a [webhook](KOFI_WEBHOOK.md) fills the bar. “Support Modwerk” in the sidebar opens “Contribute to Modwerk”: credits to octabam and module authors, and links to Discord, the forum, the contribution guide and Ko-fi. Install screens carry a Ko-fi line; frequent users get a thank-you on a later visit (triggers in `src/community/support-prompt.ts`, preview `?preview=support-thanks`). Ko-fi opens in a new tab and takes payment. Clicks count by place ([statistics](STATISTICS.md)). ## Module creator support diff --git a/docs/DEVELOPER_WORKFLOW.md b/docs/DEVELOPER_WORKFLOW.md index 6ee79f68f3..1d69dcff9e 100644 --- a/docs/DEVELOPER_WORKFLOW.md +++ b/docs/DEVELOPER_WORKFLOW.md @@ -52,12 +52,12 @@ npm run pr:ready -- --author # a registered author's update: also the The command fetches `main` and runs CI’s scoped checks. With `--commit`, stage the whole change. Success commits it with your hooks, verifies tree and parent, and checks scope and board claims. Failure leaves it staged. The default checks a clean commit and regenerates stale catalogues or notices after a failure. Files that fail the full test run and pass alone are listed as flaky. -Once **Ready**, push and run `gh pr view --json state,headRefOid,isDraft`. When the open PR points to the checked commit and required testing is recorded, run `gh pr ready ` yourself if it is a draft. Confirm the same head has `isDraft: false` before reporting completion, then watch `gh pr checks --watch` until green. If it stays a draft, name the blocker and who owns it. This includes contributor PRs into `base/-next`. The owner promotes the cumulative PR from that branch into `main`. +Once **Ready**, push and run `gh pr view --json state,headRefOid,isDraft`. When the open PR points to the checked commit and required testing is recorded, run `gh pr ready ` yourself if it is a draft. Confirm the same head has `isDraft: false` before reporting completion, then watch `gh pr checks --watch` until green. If it stays a draft, name the blocker and who owns it. This includes contributor PRs into `base/-next`, whose cumulative PR the owner promotes into `main`. Common checks and failures follow. - **main moved.** An author update merges automatically only when its CI ran against the current `main`; the scope job's name records both commits. When `main` moves first, run `pr:ready` again and push. -- **A narrow clone kept a stale ref.** `pr:ready` updates the remote's `main` tracking ref even in a single-branch clone. A manual `git fetch origin main` can update only `FETCH_HEAD` under a narrow fetch refspec; fetch `refs/heads/main:refs/remotes/origin/main` before following a `git merge origin/main` instruction in that setup. +- **A narrow clone kept a stale ref.** `pr:ready` updates the remote's `main` tracking ref even in a single-branch clone; by hand, `git fetch origin main` may update only `FETCH_HEAD`, so fetch `refs/heads/main:refs/remotes/origin/main` before `git merge origin/main`. - **Stale generated files.** `src/catalog/module-documents.json` and the compatibility files go stale whenever `main` moves under your branch. `pr:ready` regenerates them; commit what it names. Never edit them by hand. - **Letter case.** macOS and Windows find `Foo.s` when you wrote `foo.s`; Linux CI does not. `modules:check` refuses a manifest path in the wrong case, but not an `.include` line inside an assembly source, so check those yourself. - **Conflicts in Octatrack base and package assets.** Take `main`'s base files and rebuild them; never take one side's module asset JSONs (`dsp-packages.json`, `coldfire-packages.json`, `octatrack-module-packages.json` and the like) whole, since each side carries its own modules' rows. Merge them row by row, keep one row per module, then rebuild as a base change does: the beta base, `octatrack:module-packages -- --base-only`, the isolated build and import (it rewrites `module-build.json`, the one file holding build provenance, so on a conflict there take `main`'s copy), the standalone recipe pins and Analog BD's proofs. After a base rebuild, `octatrack:module-packages -- --base-only --stock OS.bin` holds back a base-bound package that lags its catalogue version (`lagsBehind`): set that row's `requiredBase` to the new identity by hand; `sdk/tests/test_base_bound.py` rebuilds it and fails unless its published bytes still match. @@ -84,7 +84,7 @@ Common checks and failures follow. The Octatrack compiler job rebuilds every base-bound package with the pinned Elekloader sources and compares its bytes with the published package. To repeat that check from the repository root, run `bash scripts/test-base-bound.sh [local-elekloader-checkout]`. It uses the committed tree. The SDK summary lists other skipped checks and their prerequisites. -The required PR check includes the description and hardware-evidence verdict. Editing the description or changing draft status runs it again. When changing how the checker reads form fields, [exercise inline labels and standalone questions](../scripts/agent-eval/markdown-fields.md). The branch must be current with main to merge. +The required PR check includes the description and hardware-evidence verdict. A description edit or draft change reruns it. Check it early: `npm run pr:body -- pr.md` (`--draft`, `--changed-since `, `-` for stdin). When changing how the checker reads form fields, [exercise inline labels and standalone questions](../scripts/agent-eval/markdown-fields.md). The branch must be current with main to merge. ### Who reviews a first release diff --git a/docs/FRONTEND_MCP.md b/docs/FRONTEND_MCP.md index 262795e539..c43fb65e23 100644 --- a/docs/FRONTEND_MCP.md +++ b/docs/FRONTEND_MCP.md @@ -35,7 +35,11 @@ Node must resolve to version 24. No HTTP listener, browser extension, cloud MCP endpoint or administrator key is installed. The transport implements the [MCP stdio protocol](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports). -The frontend is imported through an in-memory Vite bundle. Route +The frontend is imported through an in-memory Vite bundle. Before each site or +device tool call the server compares the files that bundle and the package +manifest were built from, and rebuilds them when a branch switch or a base +regeneration changed one, so the new base is known without reconnecting (/mcp). +An open trial keeps its bundle until Keep or Undo. Route `console.error`, `warn`, `info` and `debug` through `formatMcpLog(...args)` and keep protocol output on stdout. Sanitizing only exceptions leaves warnings able to print large data-URL stacks; bounded messages must omit stacks, diff --git a/docs/KOFI_WEBHOOK.md b/docs/KOFI_WEBHOOK.md new file mode 100644 index 0000000000..c9103453ad --- /dev/null +++ b/docs/KOFI_WEBHOOK.md @@ -0,0 +1,20 @@ +# Ko-fi webhook + +The support dialogs show the running costs (`SUPPORT_COSTS` in `src/config/support.ts`) and a bar for how much of them Ko-fi tips covered this month. Ko-fi has no API for reading a goal or a total, so the Worker counts the payments Ko-fi reports to it. + +## How it works + +- Ko-fi posts each payment to `/kofi/webhook` as a form field `data` holding JSON with the account's verification token (`server/kofi.ts`). +- The Worker keeps Ko-fi's message ID (a repeated delivery counts once), the UTC month, the amount in cents, the currency and whether it counts (`kofi_payments`, migration 0105). The payer's name, email address, message and links are never stored. +- Donations and subscriptions count; shop orders and commissions do not. A payer at `example.com` is Ko-fi's **Send test** and never counts. +- `GET /support/coverage` returns `{ month, euros }`: this UTC month's counted payments in euros, or `euros: null` while the token is not set. Payments in another currency are kept but not added. +- The dialogs add `SUPPORT_COSTS.covered` when `SUPPORT_COSTS.month` (`YYYY-MM`) is the current month, for tips from before the webhook was set up. + +## Setup (owner) + +1. On Ko-fi, open the webhooks page (`https://ko-fi.com/manage/webhooks`) and set the webhook URL to `https://octamod-community.octamod.workers.dev/api/kofi/webhook`. +2. Copy the verification token shown there and store it as a Worker secret: `npx wrangler secret put KOFI_VERIFICATION_TOKEN --config wrangler.worker.jsonc`. +3. Press **Send test** on Ko-fi. The test is stored but not counted; `npx wrangler d1 execute octamod-community --remote --config wrangler.worker.jsonc --command "SELECT month,amount_cents,currency,counted FROM kofi_payments"` shows it with `counted` 0. +4. Tips received earlier this month: set `month` and `covered` in `SUPPORT_COSTS` once. + +Until the secret is set, the webhook answers 503 and the dialogs show the costs without a bar. diff --git a/docs/MODULE_PERFORMANCE.md b/docs/MODULE_PERFORMANCE.md index 11fc79b758..34e7dd5027 100644 --- a/docs/MODULE_PERFORMANCE.md +++ b/docs/MODULE_PERFORMANCE.md @@ -51,7 +51,7 @@ New FX should aim for DSP cost in the **same ballpark as stock SPRING REV at its 2. **A benchmark against stock.** A DSP module is compared with the stock effect closest in function, from `benchmark_stock_dsp.py` (`out/stock_dsp_bench/results.json`, made from your own OS file, so never committed; the record copies only the comparator's figure, the dearest stock figure and the stock image's SHA-256). Up to 1.5x its cost is fine, up to 3x needs a sentence on what the extra cost buys, and above that, or dearer than every stock effect, fails unless `stock.justification` explains it and the owner accepts. A ColdFire module is compared with the stock image under the same flood: `cfmeter.py` reports the longest frame interrupt and the idle time, and the module may add at most 10% of a 362.8 us frame to the interrupt and 10 points of idle time. A track machine whose `resources.cpuPrice` is a `machine-render` price is judged against that price instead, since the base books that share of the frame for each track playing it. For a machine, measure the available render time separately in the busiest pattern it supports. [Machine render checklist](module-guides/machines.md#track-machines) 3. **A stress run.** A DSP module: the most instances you claim per core, eight tracks, three active LFOs per track and a dozen locked slots per step (`stress_project.py`), rendered for at least 2 s through `dsp_host -guard -dirty` (`pressure.py render`), with no clobber and no hang. Two seconds take about a minute or two in `dsp_host`; keep test runs that short (owner, 15 October 2026). DSP code reached only through stock-code hooks, with no effect id, has no instance for `dsp_host` to render: its record sets `stress.harness` to `ot_emu` and runs the same stress project on the whole built image under the ColdFire port, every track routed through the hooked path, for at least 30 s, with no hang and no late DSP read-back (`guard` and `dirty` stay null). `module:doctor` accepts that only for a module without an effect id. A MIDI module: a flood of notes, CC and clock at the wire rate (about 1040 three-byte messages a second) at 240 BPM or more for at least 10 s, stopping mid-note and changing Part while it runs, with no stuck note, no hang and every dropped message counted and explained. -**Stamp the record when you measure.** `npm run perf:audit -- check /evidence/performance.json --stamp`, run right after the measurements, writes `sourceSha256`: the hash of the module's source the numbers were taken on (everything but its documents, media, manifest and `evidence/`). `module:doctor` fails a stamp for other source, so changed code needs new numbers, and a record without one for a module listed from 18 November 2026 or a draft judged as a release; earlier records are asked to stamp at their next measurement. Measure, then stamp: a stamp on numbers you did not take again is a false record. An owner's exact-source approval (`sdk/approvals/-build-approval.json`) binds the whole module, its record included, so it stands in for the stamp. With `current-build-hardware` waived, it also excuses a MIDI flood that ran at the audit's rate without a hang but did not count stuck notes or lost messages. It never excuses a measured failure. +**Stamp the record when you measure.** `npm run perf:audit -- check /evidence/performance.json --stamp`, run right after the measurements, writes `sourceSha256`: the hash of the module's source the numbers were taken on (all but its documents, media, art (`presentation/`), manifest and `evidence/`; text read with Git's LF endings). `module:doctor` fails a stamp for other source, so changed code needs new numbers, and a record without one for a module listed from 18 November 2026 or a draft judged as a release; earlier records are asked to stamp at their next measurement. Measure, then stamp: a stamp on numbers you did not take again is a false record. An owner's exact-source approval (`sdk/approvals/-build-approval.json`) binds the whole module, its record included, so it stands in for the stamp. With `current-build-hardware` waived, it also excuses a MIDI flood that ran at the audit's rate without a hang but did not count stuck notes or lost messages. It never excuses a measured failure. **The cycle scan checks what you record.** Instructions are not cycles: a DSP56300 instruction takes 1 to 6 cycles and the core idles on some sequences (pipeline stalls), so a module's instructions a sample understate what it costs beside stock diff --git a/docs/MODULE_QUALIFICATION.md b/docs/MODULE_QUALIFICATION.md index 251027e999..1401d30fc8 100644 --- a/docs/MODULE_QUALIFICATION.md +++ b/docs/MODULE_QUALIFICATION.md @@ -113,27 +113,35 @@ A module that changes stock behaviour and draws nothing of its own (no controls, ## Record in the module manifest -Complete [the qualification template](../public/module-qualification.example.json) using actual results and place its object under `tests.qualification` in `octamod.module.json`. The downloadable file and scaffold copy are deliberately incomplete: null numbers, placeholder identities and pending/failed statuses fail validation. Leave a draft without `tests.qualification` while developing; it cannot pass submission/publication checks. Never replace unknown quantities with zero, averages or invented measurements. +`npm run module:qualify` writes `tests.qualification` from the evidence ([below](#write-the-record-from-the-evidence)). [The qualification template](../public/module-qualification.example.json) shows its shape. The downloadable file and scaffold copy are deliberately incomplete: null numbers, placeholder identities and pending/failed statuses fail validation. Leave a draft without `tests.qualification` while developing; it cannot pass submission/publication checks. Never replace unknown quantities with zero, averages or invented measurements. Keep `tests.report`, `tests.evidenceRevision`, README, native declarations and the qualification reports synchronized. `tests.evidenceRevision` identifies the exact tested source commit; `qualification.moduleVersion` must match the submitted version. `qualification.sourceSha256` binds the evidence to the current native source inventory and `qualification.imageSha256` identifies the exact local image tested on hardware (a reviewer may reproduce it from the unchanged DSP source). Commit only the hashes, never the firmware bytes. Source changes invalidate the qualification hash. Each qualification `report` must reference `TESTING.md` or a `.md`, `.json` or `.txt` report under `evidence/`. Reports must be regular, nonempty local files. The manifest and draft template are not evidence reports. Keep executable source and runtime inputs outside `evidence/`. -Compute the source identity from the repository root with Node 24, after source and local text report paths are final: +### Write the record from the evidence + +Do not write the record by hand. After [the test procedure](TEST_PROCEDURE.md) has run, draft it from what was measured, for a draft in `sdk/drafts/` or a listed module: ```sh -node --input-type=module - <<'JS' -import { readFile } from 'node:fs/promises' -import { resolve } from 'node:path' -import { parseModuleDocument } from './src/catalog/module-contract.ts' -import { moduleNativeSourceSha256 } from './scripts/module-qualification.mjs' -const folder = resolve('sdk/octatrack/modules/my-module') -const document = parseModuleDocument(JSON.parse(await readFile(resolve(folder, 'octamod.module.json'), 'utf8'))) -console.log(await moduleNativeSourceSha256(folder, document)) -JS +npm run module:qualify -- --procedure DIR --base "development twin 8fd6d456 of base 0.8.1, MKII, OS 1.40C" # prints what changes +npm run module:qualify -- --procedure DIR --base "…" --write # writes it +npm run module:qualify -- --check ``` -For this command, fill all fields with actual results first, including a valid temporary source hash, then replace that hash with the output. The fingerprint is SHA-256 of a sorted JSON object mapping relative source paths to file SHA-256 values. It excludes the website manifest, Markdown documentation, licence files, `media/`, the incomplete `qualification.example.json` template, declared text evidence reports and OS/Python cache files. All other regular files, including native manifests, native verification code and text runtime data, contribute: a change to the module's own probe (`qualification/probe.cpp`, its runner) alone moves the fingerprint and needs the evidence re-pinned like any source change. The complete-folder legacy fingerprint includes documentation, reports, metadata and media too. Symlinks and special files are rejected. +`DIR` is the procedure's `--out` folder. The command reads its `procedure.json` and `price.json`, the package it tested, `evidence/performance.json` and `media/capture.json`. From these it writes: + +- the CPU price, `evidence/cpu-price.json` and `evidence/frame-cost.json`, as `device:price --write` would have (`--base` names the base the unit ran); +- the storage and processing gauges, `tests.qualification` with the hardware record (model, date, tester, tested commit and package); +- the cycles from the perf:audit record and the memory regions from the package header. + +It computes `sourceSha256` last, over the folder as it will be written. Numbers and identities come from the evidence. Words a person must stand behind are kept as written: rationales, conditions, the hardware summary and limitations, and the tutorial. Where none exist, they are drafted from the data and start with `[module:qualify draft]`. `--check` and `module:doctor` fail until you have read and edited each one. A value with no source stays out, and the command says what would supply it. `--image SHA`, `--tester LOGIN` and `--model` name what the record cannot know. + +The drafted cycle bound is the performance record's static floor. Add any per-call setup and trigger-split cost that floor leaves out (Mackity charges both per 16-frame block). The drafted memory regions are what the package header shows. Add the stock blocks the effect reuses, the stack and any scratch. + +When only files that are not code changed after the test (evidence, presentation), `npm run module:qualify -- --rehash --write` recomputes `sourceSha256`. `--check` lists every file changed since the tested commit. If one of them is code, run the procedure again instead. + +The fingerprint is SHA-256 of a sorted JSON object mapping relative source paths to file SHA-256 values, each file read as Git stores it (text with LF line endings, `.gitattributes`), so a CRLF working tree on Windows gives CI's hash. It excludes the website manifest, Markdown documentation, licence files, `media/`, the incomplete `qualification.example.json` template, declared text evidence reports and OS/Python cache files. All other regular files, including native manifests, native verification code and text runtime data, contribute: a change to the module's own probe (`qualification/probe.cpp`, its runner) alone moves the fingerprint and needs the evidence re-pinned like any source change. The complete-folder legacy fingerprint includes documentation, reports, metadata and media too. Symlinks and special files are rejected. ## Worst-case cycle counts diff --git a/docs/OCTATRACK_DRIVING.md b/docs/OCTATRACK_DRIVING.md index d83dd49655..325138e8ed 100644 --- a/docs/OCTATRACK_DRIVING.md +++ b/docs/OCTATRACK_DRIVING.md @@ -15,10 +15,9 @@ On Windows keep the default chunk size, so a transfer fits WinUSB. The `serve` l ## The rules - Never SAVE, SAVE ALL or SYNC TO CARD the owner's project, unless the owner asks to recover something. -- Do not change the owner's Parts. Test on a bank whose working Part equals its saved Part (bank B in - LIVE/Dev12: every Part FILTER/DELAY). Check that with `mem` (below) first, and put it back with `reload` - afterwards; then both copies must equal the saved copy read before. (Until 11 October 2026 this said - PART+FUNC+PLAY, which clears: Dev12's bank B Part 1 is named `PART 1` from it.) +- Do not change the owner's Parts. Test on [a test bank](TEST_PROCEDURE.md#a-test-bank), first checking that its working + Part equals its saved one (`mem` below, or `scripts/octatrack-preflight.py`); `reload` it afterwards, then both + copies must equal the saved copy read before. - Read the state before you change it, and after you put it back. - RELOAD needs a Part that was saved at least once. On one that never was, it shows SAVE PART FIRST! and changes nothing, even when its working and saved copies matched before the test. Picking the original effects @@ -210,7 +209,7 @@ error and moves on. macOS `nc -U` hangs up before the reply, so use the script. | one-shot `npm run device:price -- [--out FILE.json] [ID or FILE.mwrm …]` | what a module costs, measured beside the running session (`serve --share /tmp/modwerk-share.sock`, a development twin): for each USB package, or each `.mwrm` file of an unpublished build, a timed trial, then the frame interrupt's share, the CPU meter and both DSPs while the selected pattern plays, before it, with it installed and used nowhere, and for an effect on one slot of `--slot` (T1) at its defaults (a `.mwrm` file of a published effect, named after its id, takes the effect's slots and name from its catalogue row; one of a new effect gets only the at-rest reading, 17 November 2026); `--socket` is the session's socket and `--share` the shared one; the trial is rolled back and the slot's effect picked back. It presses PLAY and STOP itself, so set the scene up first and leave the transport stopped. A machine in use and other settings are not measured. It waits for an upload however long it takes: cutting one short left MODWERK SYNC / RECEIVING MODULES at 57 % on the unit until `npm run device -- recover --socket /tmp/modwerk-share.sock` (14 November 2026). On that day, with four FLEX tracks sounding on an MKII, FM Synth 0.1.2 cost 19.1 points of the frame installed on no track, POLY8 0.3.1 13.5, Repitch 0.2.0 7.9, Euclid 3.0 and every other module under 1 | | one-shot `npm run device -- lifecycle` | not a read-out: the single-slot loader test. It stages and accepts test modules, and on a base with module sets it stops at "removal empties the slot" and leaves an unnamed module 0 kept on the card, which a power cycle keeps (26 October 2026, MKII, flashed `92a13ff0`). `npm run device -- remove --seconds 3 --accept` takes it out. For the module list: `npm run device -- do inventory` | | `flash DIR` | after `boot DIR`: that base writes its own container (`DIR/NOT_FLASH_CANDIDATE.bin` deciphered) to NOR with stock's routines, verifies it and restarts on it; refuses any other base's. Not yet run on a unit; the owner's call ([traps](OCTATRACK_HARDWARE_TRAPS.md#writing-nor-over-usb)) | -| `boot DIR`, `boot DIR 4096` | RAM boot a `build_core.py` output; the session restarts on the new base. `node scripts/octatrack-bootsoak.mjs DIR --socket PATH` repeats it in batches of 15 (about four minutes), logs each boot and stops at the first that does not come back: how often a restart loses USB is known from 20 boots only, which still allows one in seven. From the flashed `usbtest9` on macOS add 4096 (bytes a frame): it times out on the default 4,095-byte frames ([traps](OCTATRACK_HARDWARE_TRAPS.md#usb-and-ep0)) | +| `boot DIR`, `boot DIR 4096` | RAM boot a `build_core.py` output; the session restarts on the new base. Refused over a flashed update not yet confirmed: each restart spends one of its two starts (`--spend-tries` overrides). `node scripts/octatrack-bootsoak.mjs DIR --socket PATH` repeats it in batches of 15 until one does not come back (20 boots so far: up to one loss in seven). From the flashed `usbtest9` on macOS add 4096: it times out on the default 4,095-byte frames ([traps](OCTATRACK_HARDWARE_TRAPS.md#usb-and-ep0)) | STATE's `recording` bit reports sampler recorders. Check live-sequencer recording separately when qualifying an edit's recording refusal; that bit alone does not @@ -236,7 +235,7 @@ stall. Each CC was checked on its own against the Part's bytes and the screen: l - MIDI goes through `scripts/octatrack-midi-bridge.py` on the computer the unit is plugged into (on Windows the device venv's Python, through winmm; port 50124, beside the USB bridge's: on a Windows host with WSL's mirrored networking 47812 refused the bind, 19 November 2026). Start it before the run and stop it after: while it runs it holds the - unit's MIDI port. Restart it after a RAM boot: its port goes dead. + unit's MIDI port. After a RAM boot it reopens the port on a failed send (copies before 25 November 2026 must restart). - The project: track channels 1-8, and TRANSP RECV and PROG CH RECV on in PROJECT > MIDI > SYNC. A project with them off ignores START and program changes without an error: the summary then shows no pattern changes and the stopped CPU. Program changes arrive on the channel PROG CH RECV names; set to CH AUTO, that is MIDI > CHANNELS' @@ -288,10 +287,10 @@ not isolated: verify each held-row transition and stock modifier release, and st stops at RENAME, so UP three times, DOWN, YES (`savepart`: DOWN twice). Do not use SAVE or SAVE ALL on a Part you changed. **An MKI has no PART key** (#2099): FUNC + MIDI opens the Part window, an arrow moves its cursor, YES selects; FUNC + BANK there opens the menu. Steps choose by the MKII flag (`0x46c8d18c`); `device:emulator -- --mki`. After a RAM boot - every Part counts as never saved and RELOAD shows SAVE PART FIRST! (MKII, 20 November 2026), so `device:test` and - `device:qualify` SAVE the Part once before they change anything, while its working copy equals its saved one: the - same bytes, and their closing RELOAD then works. `reload` reports no failure: compare - the Part with its saved copy afterwards (SAVE PART FIRST! above). + every Part counts as never saved and RELOAD shows SAVE PART FIRST! (MKII, 20 November 2026), so `device:test`, + `device:qualify` and `test:procedure` (`octatrack-part-state.mjs`) SAVE the Part once before they change anything, + while its working copy equals its saved one: the same bytes, and their closing RELOAD then works (`test:procedure`'s + also after its soak). `reload` reports no failure: compare the Part with its saved copy afterwards. - **Patterns.** PATTERN+TRIG n selects pattern n of this bank. Another bank: BANK, then TRIG b (bank b), then TRIG n (pattern n) within four seconds (the manual's "CHOOSE BANK", "CHOOSE PATTERN"). Stopped, it applies at once; playing, it waits for the pattern's end. diff --git a/docs/OCTATRACK_TWO_SLOT_BASE.md b/docs/OCTATRACK_TWO_SLOT_BASE.md index 273c5c9bc1..d335d2b7fa 100644 --- a/docs/OCTATRACK_TWO_SLOT_BASE.md +++ b/docs/OCTATRACK_TWO_SLOT_BASE.md @@ -51,7 +51,9 @@ section at `0x4012`, ours a 6-byte jump, to `0x40000400` and calls it; the stub 1. reads both records: a slot counts when its record checks and the container's own section sum matches; 2. picks the newest counting slot. If it is not confirmed, it clears one *tries* bit first (a single-word program run from SRAM, since NOR answers status while it programs); after two tries without a confirmation it - starts the other counting slot, clearing one more bit so the base can tell it went back; + starts the other counting slot, clearing one more bit so the base can tell it went back. A RAM boot's soft + reset is a start too, so `npm run device -- boot` refuses while the newest slot is unconfirmed (an update + lost to RAM boots, 20 November 2026) and waits when that update is the base running; 3. unpacks that slot with the bootloader's own unpacker and enters it exactly as the bootloader would: its cache settings, its stack (return address and boot word), every register as it left them; 4. invalidates the instruction cache before that jump (CACR bit 8, as `runtime.c` does on the unit). The diff --git a/docs/README.md b/docs/README.md index 2b3eb0b58d..992084c429 100644 --- a/docs/README.md +++ b/docs/README.md @@ -90,6 +90,7 @@ Every document in `docs/`, one line each. [AGENTS.md](../AGENTS.md) says which t - [SOCIAL-PREVIEW.md](SOCIAL-PREVIEW.md): sharing preview artwork. - [COMMUNITY_OPERATIONS.md](COMMUNITY_OPERATIONS.md): running the community: registrations, moderation, [email sendouts](COMMUNITY_OPERATIONS.md#preparing-an-email-sendout). - [DOMAIN_AND_MAIL.md](DOMAIN_AND_MAIL.md): the modwerk.app domain, hosting and mail setup. +- [KOFI_WEBHOOK.md](KOFI_WEBHOOK.md): the Ko-fi webhook that fills the support dialogs' cost bar, and its setup. - [PLATFORM_LICENSING.md](PLATFORM_LICENSING.md): the backend's and frontend's licences. - [LEGAL_COMPLIANCE.md](LEGAL_COMPLIANCE.md): German and EU compliance preparation. diff --git a/docs/STATISTICS.md b/docs/STATISTICS.md index e94dbfce7d..1c6c982142 100644 --- a/docs/STATISTICS.md +++ b/docs/STATISTICS.md @@ -43,6 +43,7 @@ The existing opt-out, DNT/GPC, origin checks, omitted credentials/referrer and a - `visit_source`: where a page load came from. `visit-source.ts` maps the link's `utm_source`, or else the referring site's domain, to a fixed category in the browser. The address never leaves the browser. A page reached from the site itself, a reload and back/forward count nothing; an empty referrer counts as `direct`. To credit a campaign, tag its links with `utm_source` set to a listed source (or an alias such as `newsletter` → `mail`); the site drops `utm_…` from the address once read. Modwerk's own mails (news, activity, welcome, beta) tag every site link `mail-` when sent, TARS's Discord replies tag theirs `discord-bot` (`server/site-link-tags.ts`), the forum feed's links `forum-feed`, the thread Share button `forum-share`, push notifications (`public/push-sw.js`) `push` and the repository README `github-readme`; account mail is never tagged. - `sign_in_prompt`: how `LoginPromptDialog` was answered, `gate-…` before a firmware build (it can be skipped) and `other-…` before a member action. +- `support_prompt`: the support thank-you by what earned it (`installs-`, `days-`, `base-`) and its answer (`shown`, `kofi`, `later`, `closed` for Escape, `never`), and every other Modwerk Ko-fi click by place (`line-`, `dialog-`, `bell-`, `announcement-`, `welcome-kofi`). All Ko-fi clicks also count in `support_clicks`. The counts that earn the dialog stay in the browser. The admin statistics show both under "Where visits come from". The consent version is unchanged: nothing joins the consented payload, and the privacy page names both counts. diff --git a/docs/TEST_PROCEDURE.md b/docs/TEST_PROCEDURE.md index f93fc7ec9f..3e67f5984a 100644 --- a/docs/TEST_PROCEDURE.md +++ b/docs/TEST_PROCEDURE.md @@ -20,6 +20,8 @@ npm run test:procedure -- analog-rytm-mkii:temp-save # machine:id where two ma It runs the steps below with the tools that already do them and stops at the first failure. Without a unit session it records the unit steps as not run, with the command each would have run. It ends with a record for the build: `procedure.md`, a `TESTING.md` entry with an empty edge-case table, and `procedure.json` for programs. A module's automated part takes under a minute without a unit (temp-save, 20 November 2026: 9 to 18 s for steps 1 to 4, 32 s with the emulator) and a few minutes with one. +**The preflight.** With an Octatrack session it first runs `python3 -B scripts/octatrack-preflight.py`, before step 1 and again when its unit turn starts (before step 1 only while no other session holds the unit). In a few seconds of reads it fails step 6, nothing built or installed, with one line a problem and its fix: a base that does not answer development requests (a flashed release base), the transport playing, a current Part that differs from its saved copy, for a module a current pattern with trigs on more than six tracks unless it is `--pick-pattern` (`device:test` picks on the pattern the unit is on: on C01 with all eight tracks playing admission refused Mackity, CPU FULL), and when the soak runs a MIDI bridge that does not answer or cannot send one tune request (F6). On 25 November 2026 each of these cost a 5 to 15 minute run. Run it alone to check the unit before you start. + Options: `--package FILE` tests that package instead of building one, `--published` the catalogue's, `--share SOCKET` names the unit session, `--no-unit` leaves the unit alone, `--emulator-socket SOCK` adds the emulator rehearsal, `--target emulator` runs steps 6 to 10 on an emulator session ([below](#one-set-of-cases-two-targets)), `--out DIR` puts the record there (default: the system's temporary folder), `--soak-seconds` and `--scene` go to the soak and the price. On another machine: `--stock STOCK.syx --elemod BASE.elemod --label XX01` link the test image, `--link` drives the unit over the machine's own link, `--cases DIR` and `--emu DTBOOT` ([every machine](#every-machine)). ## The steps @@ -35,11 +37,11 @@ For a ColdFire track machine, leave grid and live recording off. Step 7 records | 3 | Name the build | host | `npm run module:dev -- --build-only`; a base: its `.elemod` | a package exists | revision and SHA-256 | | 4 | DSP cost model | contract | `node scripts/cycle-scan.mjs check` | every record current | its log | | 5 | Emulator rehearsal | emulator | `node scripts/device.mjs try PKG --emulator --socket SOCK`; a base: `set` with every package | the trial rolls back with no fault logged | its log, labelled emulator | -| 6 | Read the unit | unit or emulator | `node scripts/device.mjs status` and `do inventory` on the session | it answers | the starting inventory | +| 6 | Read the unit | unit or emulator | `node scripts/device.mjs status` and `do inventory` on the session; `node scripts/octatrack-part-state.mjs read` | it answers | the starting inventory; the bank, pattern and Part, and whether the Part equals its saved copy | | 7 | Scripted unit pass | unit or emulator | `npm run device:test -- --testing-entry FILE PKG`; a base: `node scripts/device.mjs set A,B,… --seconds 30 --split`, every USB package but one of each declared conflict, halved while the unit has no room | no crash, stall, freeze or skipped track; the set rolls back | `device-test.md`, its log | -| 8 | Soak | unit or emulator | `node scripts/octatrack-soak.mjs`, a module inside a trial of its own | no new crash, stall or frozen frame | `soak.json` | +| 8 | Soak | unit or emulator | `node scripts/octatrack-soak.mjs`, a module inside a trial of its own; then `octatrack-part-state.mjs restore` | no new crash, stall or frozen frame; the Part put back | `soak.json` | | 9 | Cost on the unit | unit | `npm run device:price -- --out price.json --curve T1,T3,T6,T7 PKG`; a base: every USB package | at rest at most 0.2 points of the frame interrupt, or the module rests (a machine, or it answers `ev_in_use`); an effect or a machine: its first instance read under 100 % of a frame, and alone on the empty and the medium pattern it is admitted and plays with no dropped render and no stall | `price.json`: frame interrupt, CPU meter, both DSPs, at rest and in use; the curve and the admission run | -| 10 | Put back | unit or emulator | `do inventory` again | equal to step 6 | its log | +| 10 | Put back | unit or emulator | `do inventory` again; `octatrack-part-state.mjs restore` | the inventory equal to step 6; the unit back on step 6's bank, pattern and Part, that Part's working copy equal to its saved one | its log; what it put back | | 11 | Agent by hand | unit or emulator | inside a trial (`npm run module:dev -- ` or the MCP) | what you saw matches the README | screenshots, captures | | 12 | Submitter's own stage | unit | their hands and ears | what they report | their words, as they said them | @@ -50,14 +52,30 @@ Each step proves only what it ran. Steps 1 to 5 prove the code paths they exerci - **3. A rebuild starts again at step 1.** The record names the source revision (and says when the tree had uncommitted changes) and the package's SHA-256. Every later result is about this build only. A draft DSP module with no published figures is built with the builder's placeholders (600 modeled cycles, buffer 0), which the loader refuses at verify with refusal 6, `RUNTIME_CYCLES` (Ghost Cut, 21 November 2026), and the runner takes no figures. Build it yourself with the measured ones and hand it over: `npm run module:dev -- --build-only --cycles N --cycles-kind modeled --state N --buffer N --out PKG`, then `--package PKG`. `--buffer` is the Y words of the slot buffer the effect reads. - **4.** The check fails a cycle-scan record whose module source changed since its scan. After changing a module's DSP code, scan it again on a computer with the scan's tools: `node scripts/cycle-scan.mjs record ` ([sdk/cycle-scan](../sdk/cycle-scan/README.md), [MODULE_PERFORMANCE.md](MODULE_PERFORMANCE.md)). - **5.** Start `ot_emu` with `--usb-host SOCK` on a development twin of the base, from [the adapted emulator builder](../scripts/octatrack-emulator/build.py) (the plain port refused the trial with loader refusal 5, 20 November 2026). A ColdFire module needs no `--dsp`, which runs about ten times faster; give the base 20 s after the socket appears. Or run steps 6 to 10 there instead, through `npm run device:emulator` ([below](#one-set-of-cases-two-targets)). What passes here can still fail on the unit: read [what `ot_emu` does not show](OCTATRACK_HARDWARE_TRAPS.md#the-emulator-and-the-tools). Build the twin with `build_core.py --dev` and the beta flags; on main it links only with `--resident-stock-hooks --resident-on-demand` among them, and without them stops at "Core has unexpected unresolved imports" (the arena, bss and run symbols and the `ev_` hooks). This set linked on 21 November 2026: `--dsp-loader --dev --usb-midi --packaged-usb-audio --site-events --table-owners sdk/machines/octatrack/module-adapters/table-owners.json --resident-stock-hooks --resident-on-demand --cached-modules --module-sets --sample-editor --module-ui-roots --part-menu`, with `ELEKLOADER_DSP_ASM` naming `dsp_asm` in the `dsp56300` build tree and `dsp56kDisassemble` built beside it. -- **6-10.** The unit steps go through the device commands and keep [the driving rules](OCTATRACK_DRIVING.md): a development base, transport stopped, a bank and Part whose working copy equals its saved one. Nothing is kept: every install is a trial that rolls back. The runner takes the unit for steps 6 to 10 as one turn of [the unit queue](OCTATRACK_DRIVING.md#taking-turns-on-the-unit) (`npm run unit -- run`), and the device commands inside it do not queue again; an emulator target takes no turn. -- **8.** The fast seeded soak needs the MIDI bridge on the computer the unit is plugged into (`scripts/octatrack-midi-bridge.py`; outside Windows its Python needs `pip install mido python-rtmidi`, or the soak fails with no MIDI bridge on its port) and the project's MIDI receive settings ([A fast soak](OCTATRACK_DRIVING.md)). Its program changes select patterns: by default programs 0-3 (bank A) on channel 1, and the unit stays where the last one put it, so step 9 then prices that scene. Point them at the test scene and the project's channels with `--soak-programs 32-35 --soak-pc-channel 11` (`--soak-auto-channel` for the crossfader and scenes). A failure prints the seed and a log that replays it (`--replay FILE`). In a checkout without `scripts/octatrack-soak.mjs`, a module soaks inside step 7 (`device:test --soak 120`) instead. -- **9.** "At rest" is the module installed and used nowhere: what every player pays for having it. The figure is `device:price`'s at-rest reading: the share of the frame interrupt (`guard`, 8 s) the module adds while the selected pattern plays with sounding sample tracks, installed and used nowhere, against the same scene without it, on a development twin of the base it is released for. It is the one measure the limit is judged on: a machine's render price or a figure from another tool is not compared with it, and the record (`evidence/cpu-price.json`) names its base and scene. Above 0.2 points the module must rest: a machine does by itself, any other module answers `ev_in_use` and marks its frame detours `"rests"`, and `module:doctor` fails a release from 20 November 2026 that does neither (`AT_REST_LIMIT` and `AT_REST_FROM` in `scripts/module-cpu-price.mjs`, both the owner's to change). Judge both figures against [MODULE_PERFORMANCE.md](MODULE_PERFORMANCE.md); a base-bound package is left out, since a development twin does not trust it. An effect or a machine is then placed on one to four empty tracks for its instance curve, and picked alone on the empty pattern (`--pick-pattern`, 2) and the medium one (`--measure-pattern`, 1) after each has played: a refusal, a dropped render, a stall, or a first reading past 100 % of a frame fails the step, and a release from 24 November 2026 needs the same in its `evidence/frame-cost.json` ([what a release measures](MODULE_PERFORMANCE.md#measure-a-module)). The test bank therefore needs an empty pattern and a medium one (a trig every four steps on six tracks, two playing samples) with T1, T3, T6 and T7 free. The medium pattern is for admission, a pattern with room for the curve: a bank's medium pattern can read past 80 % with stock alone (Dev17 C04: 81 %), and a machine whose first instance costs 20 to 30 points then reads the overload (Amiga 0.3.1, SYNTIZ 0.1.0 and FM Synth 0.1.5 there). The tool does not start the curve when the pattern with the module at rest plus its booked first instance reaches 100 %, and says so: read the curve on a lighter pattern with `--measure-pattern` (one sample track, or none) and keep admission on the medium one with `--admission-pattern`. Each reading presses STOP before PLAY, and one the transport did not play through is refused and ends the run. +- **6-10.** The unit steps go through the device commands and keep [the driving rules](OCTATRACK_DRIVING.md): a development base, transport stopped, a bank and Part whose working copy equals its saved one ([a test bank](#a-test-bank), never the owner's music; [the preflight](#who-runs-it) checks each first). Nothing is kept: every install is a trial that rolls back. The runner takes the unit for steps 6 to 10 as one turn of [the unit queue](OCTATRACK_DRIVING.md#taking-turns-on-the-unit) (`npm run unit -- run`), and the device commands inside it do not queue again; an emulator target takes no turn. +- **8.** The fast seeded soak needs the MIDI bridge on the computer the unit is plugged into (`scripts/octatrack-midi-bridge.py`; outside Windows its Python needs `pip install mido python-rtmidi`, or the soak fails with no MIDI bridge on its port; the preflight checks it first) and the project's MIDI receive settings ([A fast soak](OCTATRACK_DRIVING.md)). After a RAM boot the bridge opens the unit's port again by itself; a copy from before 25 November 2026 refused every message then (`midiOutShortMsg refused`) until restarted. Its program changes select patterns 1 to 4 of the bank step 6 found the unit on (bank C: programs 32-35), on channel 1; `--soak-programs 32-35 --soak-pc-channel 11` name others and the project's channel (`--soak-auto-channel` for the crossfader and scenes), and step 6 then reads those banks' Parts too. Afterwards the runner puts step 6's bank, pattern and Part back (step 10's `restore`), so step 9 prices that scene. A failure prints the seed and a log that replays it (`--replay FILE`). In a checkout without `scripts/octatrack-soak.mjs`, a module soaks inside step 7 (`device:test --soak 120`) instead. +- **9.** "At rest" is the module installed and used nowhere: what every player pays for having it. The figure is `device:price`'s at-rest reading: the share of the frame interrupt (`guard`, three 8-s readings a state, `--readings`) the module adds while the selected pattern plays with sounding sample tracks, installed and used nowhere, against the same scene without it, on a development twin of the base it is released for. It is the one measure the limit is judged on: a machine's render price or a figure from another tool is not compared with it, and the record (`evidence/cpu-price.json`) names its base and scene. Above 0.2 points the module must rest: a machine does by itself, any other module answers `ev_in_use` and marks its frame detours `"rests"`, and `module:doctor` fails a release from 20 November 2026 that does neither (`AT_REST_LIMIT` and `AT_REST_FROM` in `scripts/module-cpu-price.mjs`, both the owner's to change). Judge both figures against [MODULE_PERFORMANCE.md](MODULE_PERFORMANCE.md); a base-bound package is left out, since a development twin does not trust it. An effect or a machine is then placed on one to four empty tracks for its instance curve, and picked alone on the empty pattern (`--pick-pattern`, 2) and the medium one (`--measure-pattern`, 1) after each has played: a refusal, a dropped render, a stall, or a first reading past 100 % of a frame fails the step, and a release from 24 November 2026 needs the same in its `evidence/frame-cost.json` ([what a release measures](MODULE_PERFORMANCE.md#measure-a-module)). [The test bank](#a-test-bank) therefore needs an empty pattern and a medium one (a trig every four steps on six tracks, two playing samples) with T1, T3, T6 and T7 free. The medium pattern is for admission, a pattern with room for the curve: a bank's medium pattern can read past 80 % with stock alone (Dev17 C04: 81 %), and a machine whose first instance costs 20 to 30 points then reads the overload (Amiga 0.3.1, SYNTIZ 0.1.0 and FM Synth 0.1.5 there). The tool does not start the curve when the pattern with the module at rest plus its booked first instance reaches 100 %, and says so: read the curve on a lighter pattern with `--measure-pattern` (one sample track, or none) and keep admission on the medium one with `--admission-pattern`. The unit judges picks by the cost table the last set sent, kept through rollbacks and power cycles, so the curve installs its module with this checkout's table and the module's `each` booked at 0 (a booked guess must not refuse the instances that measure it), then sends this checkout's own table back. Each reading presses STOP before PLAY, and one the transport did not play through is refused and ends the run. Step 9 keeps its readings in the record's `price.json`. With `--price-base TEXT` (the base the unit runs), it also writes the price and the curve into the module's folder, a draft's included. Without it, `npm run module:qualify -- --procedure DIR --base TEXT --write` brings them in afterwards, with the rest of the release record ([write the record from the evidence](MODULE_QUALIFICATION.md#write-the-record-from-the-evidence)). +- **10.** The soak's CCs edit the Part it plays (on 25 November 2026 every bank with trigs on the owner's unit had a Part 1 whose working copy differed from its saved one, and the next run's `device:test` refused to start). So step 6 notes the bank, pattern and Part and whether the Part equals its saved copy, and SAVEs a clean one once, stopped: the same bytes, but after a RAM boot RELOAD refuses a Part not saved since. After the soak and here, `octatrack-part-state.mjs restore` stops the transport, goes back to that bank, pattern and Part, RELOADs the Part when it was clean at the start and differs now, and checks both copies against the saved copy read first. A Part that differed at the start is left as found: those edits are not the run's to discard. Put back also runs after a later unit step failed, and fails with the fix when a RELOAD is refused (SAVE PART FIRST!), the saved copy changed, or another Part step 6 read as saved changed; the record says what it put back. - **11.** Reach every control and screen by the README's button steps and take a `png:` screenshot of each. Record MAIN and CUE over USB with a sustained sound and look for runs of exact zeros or a block played twice. Then Undo and check the inventory again ([/modwerk-test-on-unit](../.claude/skills/modwerk-test-on-unit/SKILL.md)). - **12.** The developer here is the submitter: the person whose agent ran steps 1 to 11, at their own unit, not a reviewer. Only after 1 to 11 passed on this build. Give the developer the button steps and what they should see or hear for each item the record lists: the sound, timing by ear, MIDI and scenes, two instances, Part and project reload, the Keep and the power cycle. On a contributor's unit the Keep, the power cycle, a flash and listening are theirs, and the agent asks for each run; on the owner's computer agents need no OK for trials, RAM boots of development builds or a Keep a test needs, and never ask him for a card, while flashing and power cycles stay his ([owner operations](OWNER_OPERATIONS.md)). A fault they find is fixed, and the procedure starts again on the new build. A machine without a USB link runs the steps its tools reach, and the record lists the rest as not run with what is missing; step 12 then carries all the hardware evidence ([every machine](#every-machine)). +## A test bank + +Unit runs edit the Part they play and switch patterns, so they run on one bank kept for them, never on the owner's music. Set it up once by hand in the project the unit runs (no tool creates or changes a project), and select it, stopped, before a run: the procedure works on the bank, pattern and Part it finds, and puts them back at the end. + +| Pattern | What it holds | Used by | +|---|---|---| +| 1, medium | a trig every four steps on T1, T2, T3, T5, T6 and T7, samples on T2 and T5 only: T1, T3, T6 and T7 trig with no sample | step 9's `--measure-pattern 1`: the curve and admission ([module performance](MODULE_PERFORMANCE.md)) | +| 2, empty | no trigs | `--pick-pattern 2`: picks judged with room | +| 3, busy | samples on all eight tracks, a trig on every step | listening and the soak, never the curve: near the line the guard drops renders | +| 4, short | four steps, trigs on two tracks | the soak: a program change lands at a pattern's end | + +- Every pattern on Part 1, with stock effects. SAVE the Part once after setting it up (FUNC+PART, SAVE), so its working copy equals its saved one: step 6 checks that, and step 10 reloads it. A run that finds it changed leaves it alone, and `device:test` refuses it. +- The soak's program changes go to patterns 1 to 4 of the bank the run starts on (program 16 × (bank − 1) + pattern − 1: bank C pattern 1 is 32), so the project needs PROG CH RECEIVE and the channels [the soak](OCTATRACK_DRIVING.md#a-fast-soak) names. +- Name the bank in `--scene` ("C01, Part 1, stopped"); `--pick-pattern 2 --measure-pattern 1` are the defaults. + ## What a release measures Every release of an Octatrack module proves these on a unit, on the version it ships (owner, 23 November 2026). `module:doctor` and `modules:check` refuse a release dated from 24 November 2026 without them, whenever its module was first listed; step 9 runs the unit part. Only the owner can excuse a curve's first reading or admission run, for one exact version: `release-cost` in the module's approval (`sdk/approvals/-build-approval.json`). The curve itself is still read on that version. @@ -66,7 +84,7 @@ Every release of an Octatrack module proves these on a unit, on the version it s | --- | --- | --- | --- | | Idle | what it adds installed and used nowhere | `device:price --write` | `evidence/cpu-price.json` (`atRest`) | | Mean | its CPU price: the frame interrupt's share in use | `device:price --write`; a machine with `guard` (below) | `resources.cpuPrice` | -| DSP | both cores' load in use, for a module with DSP code | `device:price --write` | `evidence/cpu-price.json` (`inUse.dsp1to4`, `dsp5to8`) | +| DSP | both cores' load in use, for a module with DSP code | `device:price --write` | `evidence/cpu-price.json` (`inUse.dsp1to4`, `dsp5to8`, each core's peak `dsp1to4Peak`, `dsp5to8Peak`, and the readings' `spread`) | | Curve | the longest frame with 1 to 4 instances: `first`, `each`, `rest` | `device:price --write --curve` | `evidence/frame-cost.json` | | Admission | alone on an empty and on a medium pattern: admitted, then played with no dropped render and no stall | the same run | `evidence/frame-cost.json` (`admission`) | | Worst case | worst-case cycles, a stock benchmark and a stress run | `perf:audit` | `evidence/performance.json` | @@ -180,6 +198,6 @@ When the change cannot behave differently on an instrument (a package rebuilt to - **A module:** `procedure.md` with the edge-case table filled in, as an entry in the module's `TESTING.md`, followed by the submitter's own results apart from their agent's. - **A base:** a dated record in `docs/verification/`, linked from the cumulative draft's description. -- **The pull request:** the record's last lines, "Tested on a unit: …" (or "Not tested on a unit: why") and the edge-case table under a line "Edge cases". A ready pull request that changes a `.mwrm`, `.elemod` or `.ZDL` file fails its description check without both ([the check](../scripts/pr-body.mjs)). A draft may still be in test, so it needs no unit line yet, but it lists its edge cases from the start, each "not run: why" until it ran. For base work, keep this table on the machine’s cumulative draft. +- **The pull request:** the record's last lines, "Tested on a unit: …" (or "Not tested on a unit: why") and the edge-case table under a line "Edge cases". A ready pull request that changes a `.mwrm`, `.elemod` or `.ZDL` file fails its description check without both ([the check](../scripts/pr-body.mjs); `npm run pr:body -- FILE.md`, with `--draft` for a draft, runs it before you save the description). A draft may still be in test, so it needs no unit line yet, but it lists its edge cases from the start, each "not run: why" until it ran. For base work, keep this table on the machine’s cumulative draft. "Not tested" is a valid result, and it stays visible. An emulator result never counts as hardware evidence. A tester's report stays labelled as reported. diff --git a/docs/ZOOM_MULTISTOMP.md b/docs/ZOOM_MULTISTOMP.md index 2bea705ebd..547261cf42 100644 --- a/docs/ZOOM_MULTISTOMP.md +++ b/docs/ZOOM_MULTISTOMP.md @@ -359,7 +359,10 @@ finds where they are tied to it. releases are built from the MS-70CDR's 2.10 for all three pedals and answer as an MS-70CDR; on an MS-50G or MS-60B that runs one model's firmware on another, which the [modding guidelines](../MODDING_GUIDELINES.md) refuse, so - the page never flashes that build onto another pedal. Their base is + the page never offers that build for another pedal. It can't tell over USB: + a pedal running that build answers as an MS-70CDR whatever it is (the model + byte is in its flash, #2076), so the page asks for the model printed on the + pedal before the base flash and the first effect write. Their base is MIDISTOMP's patches on the pedal's own OS from its own updater (MIDISTOMP's `models/ms50g.yaml` and `ms60b.yaml` name them): a build per pedal agreed with Luca, imported like `ms70cdr-2.10` (`BUILD` in diff --git a/docs/verification/2026-11-23-octatrack-base-0-8-2.md b/docs/verification/2026-11-23-octatrack-base-0-8-2.md index e62c16924a..ba6e601d80 100644 --- a/docs/verification/2026-11-23-octatrack-base-0-8-2.md +++ b/docs/verification/2026-11-23-octatrack-base-0-8-2.md @@ -166,3 +166,44 @@ saved copy (6,322 bytes) before each case and after it, and its saved copy never (832,656 bytes). Base-bound packages relinked to it; Recorder Loop Fix 0.1.0's bytes change with the base's addresses (`6b568782…`, written under `public/octatrack-base-packages/`). - Not run on a unit: any of this. Next: the per-module `profile:3` pass on a twin of this source, and the price at rest. + +## 25 November 2026: the frame interrupt reads the current Part from SRAM (Laslo, lasl00) + +- **Why:** the frame interrupt calls `0x400068e4` twice a track, 16 times a frame (`0x4000d340`, `0x4000d36c`), and it + begins with `mvzb 0x100b14cf,%d0`, the current Part from CS1. Stock keeps the same byte in on-chip SRAM at `0x80000003` + and writes both wherever it writes either: SRAM, then CS1 in the next instruction (`0x40062142`/`8`, `0x400621e2`/`8`, + `0x40087ea6`/`ac`); the boot (`0x4001fa76`) and the reset (`0x40025aaa`) set CS1 and memcpy copies it to SRAM + (`0x400208ae`). The pairs are not masked, so in the one instruction between them stock's other 94 readers of + `0x80000003` already see a new Part and this one sees it a frame later: with the change it sees it with them. +- **Change:** `build_core.py` `PART_READ`: the six bytes at `0x400068f0` become `mvzb 0x80000003,%d0` (`op: bytes`, guard + on the stock instruction): the same flags, one CS1 read fewer per call. The ISR's other read (`0x4000d212`) is a rare + branch and stays. +- **Found with** `ot_emu` (stock 1.40C, project CPUCURVE: Part 1, 120 BPM, A01 a trig every four steps on T1-T4, T6, T7 + with T2 and T4 playing a 2 s loop, Dev17 C04 style) and a local counter of data accesses outside cached SDRAM by PC + (not in this tree): over 11,025 frames A01 made 28.1 CS1 accesses a frame, 16.0 of them this read, besides 12 of the + renderer's per-voice CS1 record. Most of the 9,000 accesses outside SDRAM go to SRAM, which is as cheap as a cache hit. +- **Emulator A/B:** development twins of this source without (`f8c3f344…`, MAIN `7a306ec6…`) and with the change + (`30592832…`, MAIN `ceb6f9a2…`), the beta flags without controller rows plus `--dev`, the same 11,025 frames of A01: + the same instructions over the frames (350,396,946); all 353,406 writes to the DSP host port equal (address, value, + PC); SRAM and `0x46c80000..0x46cbffff` equal; CS1 equal but the eight bytes of the base identity. CS1 accesses 46.3 → + 30.3 a frame. At `0x400068f0` the two bytes were equal at all 176,400 calls, also on a project saved on Part 3 (the + load writes 2 through the `0x40087ea6` pair). Not checked in the emulator: a Part switch while playing. +- **On Laslo's MKII** (OS 1.40C, the flashed base 0.8 `e1152583`, RAM boots of the two twins A, B, A; CPUCURVE3 on the + card; `guard` 8 s readings): + + | Frame interrupt mean (longest frame) | A | B | A again | + | --- | --- | --- | --- | + | A01, six tracks trigging, two samples (6 readings) | 37.0-37.1 % (77.6-79.8) | 36.0 % (76.4-79.1) | 37.0-37.1 % (76.9-80.3) | + | A03, four trigging, no sample (3) | 29.8 % (63.3-63.7) | 28.8 % (62.3-62.5) | 29.8 % (62.9-64.6) | + | A02, empty, playing (2) | 29.8 % (40.2-40.7) | 28.8 % (39.3) | 29.8 % (40.2-40.6) | + | stopped (2) | 29.8 % (40.1-40.3) | 28.7 % (39.1-39.3) | 29.7-29.8 % (40.1-40.4) | + + One point of the frame interrupt in every state (about 3.6 µs, 0.23 µs a CS1 byte read); the longest frame about a + point lower where the pattern does not set it. Nothing skipped. CPU meter: 49.4-50.2 → 48.3-49.1 % on A01. +- Release 0.8.2 rebuilt: base `880c0a34538757dd…` (was `fad2c729`); browser = native `.bin` `a4ecb83fcea5f609…` + (832,628 bytes). Base-bound packages relinked. +- **Part switches while playing** (twin B, A01 playing, Laslo at the unit through the PART menu): Parts 1, 2, 3, 2, 1, + 2, 3, 4, 1 over about two minutes, the current Part read from SRAM every 4 s. Nothing skipped, no stall, no error in + 1,003,642 frames; back on Part 1 the frame interrupt read 36.0 % again (the longest frame up to 87.3 % in the readings + that held a Part load). By ear: Part 1's sound came back cleanly each time (Parts 2-4 of the project hold no sample). +- Not run: the release image on a unit. diff --git a/migrations/0105_kofi_payments.sql b/migrations/0105_kofi_payments.sql new file mode 100644 index 0000000000..b3955cd3c7 --- /dev/null +++ b/migrations/0105_kofi_payments.sql @@ -0,0 +1,12 @@ +-- Ko-fi payments from the webhook (server/kofi.ts), for the share of the running costs that tips cover. Only Ko-fi's +-- message ID (a repeated delivery counts once), the UTC month, the amount in cents, the currency and whether it counts +-- (a donation or subscription that is not Ko-fi's test) are kept. No name, email address, message or link is stored. +CREATE TABLE kofi_payments ( + message_id TEXT PRIMARY KEY, + month TEXT NOT NULL, + amount_cents INTEGER NOT NULL, + currency TEXT NOT NULL, + counted INTEGER NOT NULL, + received_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX kofi_payments_month ON kofi_payments(month, counted); diff --git a/package.json b/package.json index 6e7586a998..24f9acb618 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "todo": "node scripts/maintenance-bot/todo.mjs", "check": "node scripts/check.mjs", "agent:eval": "node scripts/agent-eval/run.mjs", + "pr:body": "node scripts/pr-body.mjs", "pr:ready": "node scripts/pr-ready.mjs", "preinstall": "node scripts/require-node.mjs", "prepare": "node scripts/require-node.mjs && node scripts/mirror-octatrack-modules.mjs && node scripts/machine-modules.mjs && node scripts/module-changelogs.mjs --write && node scripts/elekloader-vendor.ts --write", @@ -62,6 +63,8 @@ "module:new": "node scripts/scaffold-module.mjs", "module:dev": "node scripts/module-dev.mjs", "module:doctor": "node scripts/module-doctor.mjs", + "module:list": "node scripts/module-list.mjs", + "module:qualify": "node scripts/module-qualify.mjs", "fx:audit": "node scripts/fx-audit.mjs", "perf:audit": "node scripts/perf-audit.mjs", "stock:branches": "node scripts/stock-branches.mjs", diff --git a/public/licenses/THIRD_PARTY_NOTICES.html b/public/licenses/THIRD_PARTY_NOTICES.html index 77e00d348a..38ff2fd1ed 100644 --- a/public/licenses/THIRD_PARTY_NOTICES.html +++ b/public/licenses/THIRD_PARTY_NOTICES.html @@ -89,6 +89,7 @@ src/community/profile-links.ts src/community/remote-session-contract.ts src/community/report-closure.ts +src/community/support-report.ts src/community/usage-contract.ts src/community/usage-pages.ts src/config/beta-invitation.ts @@ -913,9 +914,9 @@ ======================================================================== -Airwindows Chorus +Airwindows Chorus and Mackity SPDX: MIT -Used in: modules/airwindows-chorus: Chorus +Used in: modules/airwindows-chorus: Chorus; modules/mackity: Mackity Notice source: https://raw.githubusercontent.com/airwindows/airwindows/e718c9bcfcdd736deeddb08bffe6bce2aa8e0eea/LICENSE MIT License diff --git a/public/licenses/THIRD_PARTY_NOTICES.txt b/public/licenses/THIRD_PARTY_NOTICES.txt index 10ac7f8491..60b8c3920e 100644 --- a/public/licenses/THIRD_PARTY_NOTICES.txt +++ b/public/licenses/THIRD_PARTY_NOTICES.txt @@ -88,6 +88,7 @@ src/community/ot-log.ts src/community/profile-links.ts src/community/remote-session-contract.ts src/community/report-closure.ts +src/community/support-report.ts src/community/usage-contract.ts src/community/usage-pages.ts src/config/beta-invitation.ts @@ -912,9 +913,9 @@ SOFTWARE. ======================================================================== -Airwindows Chorus +Airwindows Chorus and Mackity SPDX: MIT -Used in: modules/airwindows-chorus: Chorus +Used in: modules/airwindows-chorus: Chorus; modules/mackity: Mackity Notice source: https://raw.githubusercontent.com/airwindows/airwindows/e718c9bcfcdd736deeddb08bffe6bce2aa8e0eea/LICENSE MIT License diff --git a/public/octatrack-modules/mackity/0.1.0-experimental.mwrm b/public/octatrack-modules/mackity/0.1.0-experimental.mwrm new file mode 100644 index 0000000000..0dcfda908c Binary files /dev/null and b/public/octatrack-modules/mackity/0.1.0-experimental.mwrm differ diff --git a/scripts/agent-board.mjs b/scripts/agent-board.mjs index 90b438fd27..e60855b986 100644 --- a/scripts/agent-board.mjs +++ b/scripts/agent-board.mjs @@ -20,6 +20,8 @@ // npm run board -- reply "answer" [--pr ] | link --pr | close | delete // # --pr / link: the thread ends when that pull request merges (fold = link) // npm run board -- inbox # questions, replies and your expiring claims +// npm run board -- wait [] [--minutes 60] # ends when someone else answers thread , or anything new reaches your inbox; +// # run it in the background after asking: exit 0 with the thread, 3 at the deadline // npm run board -- activity # how many developers use the board // // Kinds: module (machine/id), hook (octatrack/39, digitakt/events/7, a run octatrack/38-51), migration (0085), dsp-region (machine/name), @@ -202,6 +204,7 @@ export function neededClaims({ root, base, head = 'HEAD' }) { const hookSpan = key => { const [, list, first, last] = /^(.+)\/(\d+)(?:-(\d+))?$/.exec(key); return { list, first: Number(first), last: Number(last ?? first) } } const overlaps = (a, b) => { const x = hookSpan(a), y = hookSpan(b); return x.list === y.list && x.first <= y.last && y.first <= x.last } +const covers = (a, b) => { const x = hookSpan(a), y = hookSpan(b); return x.list === y.list && x.first <= y.first && y.last <= x.last } /** Consecutive new hook indices of one list become one claim (octatrack/38-51): a base change may add more hooks than * one person may hold claims. */ function hookRuns(items) { @@ -224,13 +227,14 @@ export async function compareClaims(needed, login, { pullRequest, ...options } = const claims = await listClaims({}, options), byKey = new Map(claims.map(item => [item.kind + ' ' + item.key, item])) const result = { mine: [], others: [], free: [], unknown: [] } for (const item of needed) { - // Hook claims overlap by index; the holder's own inside a run give way to it when the run is claimed. + // Hook claims overlap by index; the holder's own inside a run give way to it when the run is claimed. A run claimed + // ahead of the work (tables/4-6 while the branch adds 4-5 so far) covers the part a branch adds. const near = item.kind === 'hook' ? claims.filter(claim => claim.kind === 'hook' && overlaps(claim.key, item.key)) : [byKey.get(item.kind + ' ' + item.key)].filter(Boolean) - const theirs = login && near.find(claim => claim.holder !== login.toLowerCase() && !(pullRequest && claim.pullRequest === pullRequest)), exact = near.find(claim => claim.key === item.key) + const theirs = login && near.find(claim => claim.holder !== login.toLowerCase() && !(pullRequest && claim.pullRequest === pullRequest)), held = near.find(claim => claim.key === item.key) ?? (item.kind === 'hook' ? near.find(claim => covers(claim.key, item.key)) : undefined) if (!near.length) result.free.push(item) else if (!login) result.unknown.push({ ...item, claim: near[0] }) else if (theirs) result.others.push({ ...item, claim: theirs }) - else if (exact) result.mine.push({ ...item, claim: exact }) + else if (held) result.mine.push({ ...item, claim: held }) else result.free.push(item) } return result @@ -306,6 +310,28 @@ export async function inboxNotes(options = {}) { if (expiring) notes.push(`You have ${expiring} board claim${expiring === 1 ? '' : 's'} expiring within three days. Run npm run board -- inbox to see which claims to review.`) return notes } +/** Waits until someone other than `me` has the newest word in a thread `read` returns, a thread is new, or one ends. + * Returns the threads that changed, or null at the deadline. A board that does not answer for a moment is read again + * at the next turn, so a long wait survives a deploy. */ +export async function waitForReply({ read, me, minutes = 60, every = 60000, sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), now = Date.now }) { + const state = thread => ({ word: thread.replies?.at(-1)?.id ?? thread.id, by: thread.replies?.at(-1)?.author ?? thread.author, ended: Boolean(thread.endedAt) }) + const seen = new Map((await read()).map(thread => [thread.id, state(thread)])) + const deadline = now() + minutes * 60000 + while (now() < deadline) { + await sleep(Math.min(every, deadline - now())) + let threads + try { threads = await read() } catch (error) { if (error instanceof BoardUnavailable) continue; throw error } + const changed = threads.filter(thread => { + const before = seen.get(thread.id), after = state(thread) + if (!before) return after.by !== me + return (before.word !== after.word && after.by !== me) || before.ended !== after.ended + }) + for (const thread of threads) seen.set(thread.id, state(thread)) + if (changed.length) return changed + } + return null +} + /** One thread as the terminal shows it. Quoted text is another developer's words. */ export function describeThread(thread) { const to = thread.to ? (thread.kind === 'wanted' ? ' taken by @' : ' → @') + thread.to : '', when = thread.endedAt ? 'ended ' + thread.endedAt.slice(0, 10) + ' (' + thread.endedReason + ')' : 'open until ' + thread.endsAt.slice(0, 10) @@ -375,7 +401,7 @@ export function branchVerdict(compared, { requireClaims = false } = {}) { const lines = [] for (const item of compared.others) lines.push(`✗ ${item.kind} ${item.key} (${item.why}) is claimed by ${describeClaim(item.claim)}. Ask them, or renumber / rename.`) for (const item of compared.unknown) lines.push(`· ${item.kind} ${item.key} is claimed by ${describeClaim(item.claim)}; sign in (npm run board -- login) so the check can tell whether that is you.`) - for (const item of compared.mine) lines.push(`✓ ${item.kind} ${item.key}: yours.`) + for (const item of compared.mine) lines.push(`✓ ${item.kind} ${item.key}: yours${item.claim && item.claim.key !== item.key ? ' (claim ' + item.claim.key + ')' : ''}.`) for (const item of compared.free) lines.push(requireClaims ? `✗ ${item.kind} ${item.key} (${item.why}) is unclaimed. Claim it so nobody else starts the same work: npm run board -- login once, then npm run pr:ready (it claims what the branch adds) or npm run board -- claim ${item.kind} ${item.key}. Then rerun this check.` : `· ${item.kind} ${item.key} (${item.why}) is unclaimed: npm run board -- claim ${item.kind} ${item.key}`) @@ -438,6 +464,21 @@ async function main(argv) { } return 0 } + if (command === 'wait') { + const minutes = flag('--minutes') ? Number(option('--minutes')) : 60 + if (!Number.isInteger(minutes) || minutes < 1 || minutes > 720) throw new Error('Give --minutes as a whole number from 1 to 720.') + const token = await readToken(), me = token && await whoami({ token }) + if (!me) throw new BoardError('Sign in for the board first: npm run board -- login', 401) + const id = rest[0] + const read = id ? async () => [(await boardRequest('/agent-board/messages/' + encodeURIComponent(id), { token })).message] + : async () => { const box = await inbox({ token }); if (!box) throw new BoardError('The board sign-in ended: npm run board -- login', 401); return [...box.waiting, ...box.replies] } + console.log(`Waiting up to ${minutes} minutes for ${id ? 'an answer in ' + id : 'something new in your inbox'}.`) + const changed = await waitForReply({ read, me, minutes }) + if (!changed) { console.log(`No answer within ${minutes} minutes. Run it again to keep waiting.`); return 3 } + console.log(UNTRUSTED) + for (const thread of changed) console.log(describeThread(thread).join('\n')) + return 0 + } if (command === 'activity') { const weeks = option('--weeks') if (flag('--weeks') && weeks === undefined) throw new BoardError('Give the number of weeks after --weeks.', 400) diff --git a/scripts/agent-board.test.mjs b/scripts/agent-board.test.mjs index 9d6d7a1052..7703671563 100644 --- a/scripts/agent-board.test.mjs +++ b/scripts/agent-board.test.mjs @@ -91,6 +91,17 @@ describe('the board client', () => { expect((await compare(claimRow('hook', 'octatrack/38-51', 'ada'))).mine).toHaveLength(1) expect((await compare(claimRow('hook', 'octatrack/events/40', 'bo'), claimRow('hook', 'octatrack/52', 'bo'))).free).toHaveLength(1) }) + it('counts a run claimed ahead of the work as covering the part a branch adds', async () => { + const needed = [{ kind: 'hook', key: 'digitakt-ii/tables/4-5' }] + const compare = (claims, pullRequest) => board.compareClaims(needed, 'Ada', { fetch: answer(200, { claims }), pullRequest }) + expect((await compare([claimRow('hook', 'digitakt-ii/tables/4-6', 'ada')])).mine[0].claim.key).toBe('digitakt-ii/tables/4-6') + expect((await compare([{ ...claimRow('hook', 'digitakt-ii/tables/4-6', 'claptom'), pullRequest: 1999 }], 1999)).mine).toHaveLength(1) + expect((await compare([claimRow('hook', 'digitakt-ii/tables/4-6', 'bo')])).others).toHaveLength(1) + expect((await compare([claimRow('hook', 'digitakt-ii/tables/4', 'ada')])).free).toHaveLength(1) + expect((await compare([claimRow('hook', 'digitakt-ii/tables/5-6', 'ada')])).free).toHaveLength(1) + expect((await compare([claimRow('hook', 'digitakt-ii/events/4-6', 'ada')])).free).toHaveLength(1) + expect(board.branchVerdict(await compare([claimRow('hook', 'digitakt-ii/tables/4-6', 'ada')]), { requireClaims: true })).toEqual({ ok: true, lines: ['✓ hook digitakt-ii/tables/4-5: yours (claim digitakt-ii/tables/4-6).'] }) + }) it('fails an unclaimed item only in a pull request run, and someone else\'s claim always', () => { const free = { mine: [], others: [], unknown: [], free: [{ kind: 'module', key: 'octatrack/drummap', why: 'new module' }] } expect(board.branchVerdict(free).ok).toBe(true) @@ -227,8 +238,44 @@ describe('pr:ready and the board', () => { expect(await run({ claims: [handWritten] })).toEqual([{ kind: 'module', key: 'octatrack/slicer', branch: 'work', note: 'Slices a loop.' }, { kind: 'module', key: 'octatrack/echo', branch: 'work' }]) expect((await run({ refuseNotes: true })).map(item => item.key + (item.note ? ' + note' : ''))).toEqual(['octatrack/slicer + note', 'octatrack/slicer', 'octatrack/echo + note', 'octatrack/echo']) }) + it('renews a covering run whole instead of claiming only the part the branch adds', async () => { + const { taken, module } = fake({ claims: [claimRow('hook', 'octatrack/36-38', 'ada')] }) + const result = await boardClaims('.', 'main', module) + expect(taken.map(item => item.key)).toEqual(['0084', 'octatrack/36-38']) + expect(result.notes).toContain('Board: claimed hook octatrack/36-38 for @ada.') + }) it('only notes an unreachable board', async () => { const result = await boardClaims('.', 'main', fake({ fail: true }).module) expect(readiness({ board: result })).toMatchObject({ ok: true, notes: expect.arrayContaining([expect.stringContaining('claims not checked')]) }) }) }) + +describe('npm run board -- wait', () => { + const thread = (replies, extra = {}) => ({ id: 't1', author: 'asker', replies: replies.map(([id, author]) => ({ id, author })), ...extra }) + const clock = () => { let t = 0; return { now: () => t, sleep: async ms => { t += ms } } } + + it('ends when someone else has the newest word, not on the waiting developer\'s own reply', async () => { + const reads = [[thread([])], [thread([['r1', 'asker']])], [thread([['r1', 'asker'], ['r2', 'owner']])]] + const changed = await board.waitForReply({ read: async () => reads.shift() ?? [], me: 'asker', ...clock() }) + expect(changed.map(item => item.replies.at(-1).id)).toEqual(['r2']) + }) + + it('ends on a thread new to the inbox or one that ended, and reads again after the board was briefly away', async () => { + let n = 0 + const read = async () => { + n++ + if (n === 2) throw new board.BoardUnavailable('deploying') + return n < 3 ? [thread([])] : [thread([]), { id: 't2', author: 'reviewer', replies: [] }] + } + expect((await board.waitForReply({ read, me: 'asker', ...clock() })).map(item => item.id)).toEqual(['t2']) + const ends = [[thread([['r1', 'asker']])], [thread([['r1', 'asker']], { endedAt: '2026-11-25T10:00:00Z' })]] + expect((await board.waitForReply({ read: async () => ends.shift(), me: 'asker', ...clock() })).map(item => item.id)).toEqual(['t1']) + }) + + it('gives up at the deadline', async () => { + const reads = [] + const result = await board.waitForReply({ read: async () => { reads.push(1); return [thread([])] }, me: 'asker', minutes: 3, ...clock() }) + expect(result).toBeNull() + expect(reads.length).toBe(4) + }) +}) diff --git a/scripts/agent-session.mjs b/scripts/agent-session.mjs index e385847378..4f12600aca 100644 --- a/scripts/agent-session.mjs +++ b/scripts/agent-session.mjs @@ -5,7 +5,8 @@ // npm run session -- status # whether to ask the developer: ask (the default), always or never // npm run session -- prefer ask|always|never // npm run session -- preview [--skip 3,7] # what would be sent, written to ~/.cache/modwerk/session-preview.json -// npm run session -- share --note "…" [--skip 3,7] [--file ] [--agent claude-code|codex] +// npm run session -- share --note "…" [--skip 3,7] [--new] [--file ] [--agent claude-code|codex] +// # --new: leave out what your earlier shares of this session already hold // npm run session -- list | get | delete // npm run session -- review [--file ] # where this session spent its time; printed here, nothing is sent // npm run session -- pull # the owner: every shared session into ~/.cache/modwerk-local/sessions/, @@ -103,11 +104,33 @@ export async function findTranscript({ file, agent } = {}) { return pick } -export async function buildSession({ file, agent, note = '', skip = [] }) { +/** The entries the developer's own earlier shares already hold, as "who at" keys. Only shares made since `since` (when + * this transcript started) can hold any of it, so older ones are not fetched. */ +export async function sharedMoments(get, since = '') { + const { sessions } = await get('/agent-sessions'), keys = new Set(), ids = [] + for (const item of sessions) { + if (since && item.createdAt < since) continue + const shared = await get('/agent-sessions/' + encodeURIComponent(item.id)) + for (const entry of shared.session?.entries ?? []) if (entry.at) keys.add(entry.who + ' ' + entry.at) + ids.push(item.id.slice(0, 8)) + } + return { keys, ids } +} +/** Indexes of the transcript entries an earlier share already sent. */ +export const alreadyShared = (entries, keys) => entries.flatMap((entry, index) => entry.at && keys.has(entry.who + ' ' + entry.at) ? [index] : []) + +export async function buildSession({ file, agent, note = '', skip = [], shared }) { const info = await lstat(file) if (!info.isFile()) throw new Error(file + ' is not a transcript file.') const lines = (await readFile(file, 'utf8')).split('\n').filter(Boolean) const read = agent === 'codex' ? readCodexRollout(lines) : readClaudeTranscript(lines) + // --new: what an earlier share of this session sent stays out, the way --skip leaves entries out. + if (shared) { + const { keys, ids } = await shared(read.startedAt ?? '') + const left = alreadyShared(read.entries, keys) + if (ids.length) console.log(`Leaving out ${left.length} entries already in your earlier shares (${ids.join(', ')}).`) + skip = [...skip, ...left] + } let user = '' try { user = userInfo().username } catch { /* none */ } return prepareSession(read, note, { user, host: hostname().split('.')[0], home: homedir(), names: developerNames() }, skip) @@ -204,7 +227,7 @@ export async function pullSessions(folder, get) { } export async function main(argv = process.argv.slice(2)) { - const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: { note: { type: 'string' }, skip: { type: 'string' }, file: { type: 'string' }, agent: { type: 'string' } } }) + const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: { note: { type: 'string' }, skip: { type: 'string' }, file: { type: 'string' }, agent: { type: 'string' }, new: { type: 'boolean' } } }) const [command = 'help', arg] = positionals const skip = (values.skip ?? '').split(',').filter(Boolean).map(Number).filter(Number.isInteger) if (command === 'status') { console.log(sharingLine(await readPreference())); return 0 } @@ -223,7 +246,8 @@ export async function main(argv = process.argv.slice(2)) { // The note is what the owner reads first; an agent once sent the instructions' "…" placeholder as it was. if (command === 'share' && placeholderNote(values.note)) { console.error('Write the note: a few sentences on what got in the way in this session (--note "The board refused … until …").'); return 2 } const found = await findTranscript({ file: values.file, agent: values.agent }) - const session = await buildSession({ ...found, note: values.note ?? '', skip }) + const shared = values.new ? async since => sharedMoments(async path => boardRequest(path, { token: await token() }), since) : undefined + const session = await buildSession({ ...found, note: values.note ?? '', skip, shared }) await writePrivate(previewFile(), JSON.stringify(session, null, 2) + '\n') console.log(summary(session, found.file)) console.log(`What would be sent: ${previewFile()}`) @@ -233,7 +257,7 @@ export async function main(argv = process.argv.slice(2)) { return 1 } if (command === 'preview') return 0 - if (!session.entries.length) { console.error('This session has no conversation to share yet.'); return 1 } + if (!session.entries.length) { console.error(values.new ? 'Your earlier shares already hold all of this session.' : 'This session has no conversation to share yet.'); return 1 } const data = gzipSync(JSON.stringify(session)) if (data.length > SESSION_GZIP_LIMIT) { console.error('The session is too large to share even trimmed. Leave entries out with --skip.'); return 1 } const result = await boardRequest('/agent-sessions', { method: 'POST', token: await token(), body: { consent: SESSION_CONSENT_VERSION, data: data.toString('base64') } }) @@ -266,7 +290,7 @@ export async function main(argv = process.argv.slice(2)) { console.log(`${count} shared sessions in ${folder} (INDEX.md lists them).`) return 0 } - console.log('npm run session -- review | status | prefer ask|always|never | preview | share --note "…" [--skip 3,7] [--file ] | list | get | delete | pull') + console.log('npm run session -- review | status | prefer ask|always|never | preview | share --note "…" [--skip 3,7] [--new] [--file ] | list | get | delete | pull') return command === 'help' ? 0 : 2 } diff --git a/scripts/agent-session.test.mjs b/scripts/agent-session.test.mjs index c19979f555..a7df7e158d 100644 --- a/scripts/agent-session.test.mjs +++ b/scripts/agent-session.test.mjs @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { mkdtemp, readFile, readdir, rm } from 'node:fs/promises' +import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { gzipSync } from 'node:zlib' @@ -7,7 +7,7 @@ import { testServer } from '../src/community/test-server.ts' import { handleCommunity } from '../server/transport.ts' import { SESSION_CONSENT_VERSION } from '../src/community/agent-sessions.ts' import { COMMUNITY_RULES_VERSION } from '../src/legal/policy.ts' -import { accountRequest, asAccount, pullSessions } from './agent-session.mjs' +import { accountRequest, alreadyShared, asAccount, buildSession, pullSessions, sharedMoments } from './agent-session.mjs' import { BoardError } from './agent-board.mjs' const password = 'private session pull test passphrase' @@ -62,3 +62,29 @@ describe('npm run session -- pull', () => { await expect(asAccount({ email: plain, password }, session => pullSessions(folder, async path => (await accountRequest(path, { ...options, session })).value), options)).rejects.toMatchObject({ status: 401 }) }) }) + +describe('npm run session -- share --new', () => { + it('leaves out what an earlier share of the same session already sent, and fetches only shares made since it started', async () => { + const folder = await mkdtemp(join(tmpdir(), 'session-new-')) + cleanup.push(() => rm(folder, { recursive: true, force: true })) + const line = (type, text, timestamp) => JSON.stringify({ type, timestamp, message: { role: type, content: type === 'user' ? text : [{ type: 'text', text }] } }) + const file = join(folder, 'transcript.jsonl') + await writeFile(file, [ + line('user', 'Measure the rest peaks.', '2026-11-20T12:00:00.000Z'), + line('assistant', 'POLY8 is the one.', '2026-11-20T12:05:00.000Z'), + line('user', 'Now the curves.', '2026-11-24T10:00:00.000Z'), + line('assistant', 'FM Synth first is 17.3.', '2026-11-24T10:20:00.000Z'), + ].join('\n') + '\n') + const fetched = [] + const get = async path => { + fetched.push(path) + if (path === '/agent-sessions') return { sessions: [{ id: 'aaaaaaaa-0000-4000-8000-000000000001', createdAt: '2026-11-20T12:10:00.000Z' }, { id: 'bbbbbbbb-0000-4000-8000-000000000002', createdAt: '2026-11-01T09:00:00.000Z' }] } + return { session: { entries: [{ who: 'developer', text: 'Measure the rest peaks.', at: '2026-11-20T12:00:00.000Z' }, { who: 'agent', text: 'POLY8 is the one.', at: '2026-11-20T12:05:00.000Z' }] } } + } + const session = await buildSession({ file, agent: 'claude-code', note: 'rest', shared: since => sharedMoments(get, since) }) + expect(session.entries.map(entry => entry.text)).toEqual(['Now the curves.', 'FM Synth first is 17.3.']) + // The share from before this transcript started cannot hold any of it and is not fetched. + expect(fetched).toEqual(['/agent-sessions', '/agent-sessions/aaaaaaaa-0000-4000-8000-000000000001']) + expect(alreadyShared([{ who: 'agent', at: '2026-11-20T12:05:00.000Z' }, { who: 'developer', at: '2026-11-20T12:05:00.000Z' }, { who: 'tool' }], new Set(['agent 2026-11-20T12:05:00.000Z']))).toEqual([0]) + }) +}) diff --git a/scripts/build-module-packages.py b/scripts/build-module-packages.py index f2f196f8ba..691c1241d4 100644 --- a/scripts/build-module-packages.py +++ b/scripts/build-module-packages.py @@ -8,7 +8,7 @@ import argparse, hashlib, importlib.util, json, os, re, shutil, struct, subprocess, sys, tempfile APP = Path(__file__).resolve().parents[1] -ORDER = ['miniverb', 'tapeecho', 'euclid', 'repitch', 'tapehead', 'airwindows-chorus', 'everb', 'bbd', 'lofi2', 'ring-sc', 'vibrato', 'resonator'] +ORDER = ['miniverb', 'tapeecho', 'euclid', 'repitch', 'tapehead', 'airwindows-chorus', 'everb', 'bbd', 'lofi2', 'ring-sc', 'vibrato', 'resonator', 'mackity'] # DSP code that stock code reaches through hooks. Output Matrix has no FX menu entry and is also a requested ColdFire module. HOOKED = ['sidechain-compressor', 'output-matrix'] REQUESTED = ['analog-bassdrum', 'usb-audio-out-tracks-main-cue', 'quantizer', 'synth', 'vector', 'playmodes', 'mute-modes', 'recorder-loop-fix', 'poly8', 'output-matrix', 'quantize-live-rec-toggle', 'apply-scene', 'direct-jump-kyoti', 'dejavu', 'arp-key-locks', 'temp-save', 'tuner', 'slow-lfo', 'bar-led', 'stem-rec', 'songbook'] @@ -581,6 +581,14 @@ def at(base): donorSha256='3b3f9b15f2f6addfea9fc281f5b9fdf054bf305778059b8d43db41d390f0401f', fx2Slot=0x400d5ff8, slotSha256='79bc740214b4d029e385d06d21e224d04e8f91b53fb26ea08ffa4e5d70964b7a')) + if not any(row['id'] == 'mackity' for row in descriptor_guards): + # The same DARK REV donor and stock NONE at unused FX2 id 0x1a, as the effects above; + # the build checks both hashes against the private OS 1.40C. Never retain stock bytes. + descriptor_guards.append(dict(id='mackity', key='MACKITY', author='repeat98', + fxId=0x1a, donorAddress=0x400d58f0, + donorSha256='3b3f9b15f2f6addfea9fc281f5b9fdf054bf305778059b8d43db41d390f0401f', + fx2Slot=0x400d6044, + slotSha256='79bc740214b4d029e385d06d21e224d04e8f91b53fb26ea08ffa4e5d70964b7a')) for old in descriptor_guards: module = byid[old['id']] if module.menu.donor_desc + 0x38 != old['donorAddress'] or module.menu.fx2_id != old['fxId']: diff --git a/scripts/cycle-scan.mjs b/scripts/cycle-scan.mjs index 8666900e06..29dcebbde6 100644 --- a/scripts/cycle-scan.mjs +++ b/scripts/cycle-scan.mjs @@ -4,7 +4,8 @@ // // node scripts/cycle-scan.mjs record [ ...] # on your computer: scan each Octatrack module, write its record // node scripts/cycle-scan.mjs check # anywhere, CI included: judge every committed record -// node scripts/cycle-scan.mjs unit [--markdown] # anywhere: the records against the unit's in-use readings (report only) +// node scripts/cycle-scan.mjs unit [--markdown|--write] # anywhere: the records against the unit's in-use readings (report only; +// # --write puts the table into sdk/cycle-scan/README.md, which check holds to it) // // `record` runs sdk/cycle-scan/interlock_scan.py --sweep on the module and on the stock effect its performance.json compares // it with, and writes sdk/cycle-scan/records/.json: the dearest setting's instructions, cycles and stalls a sample, @@ -20,7 +21,7 @@ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSy import { tmpdir } from 'node:os' import { dirname, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' -import { modulePerformanceSourceSha256 } from './module-qualification.mjs' +import { moduleEarlierPerformanceSourceSha256, modulePerformanceSourceSha256 } from './module-qualification.mjs' import { parseModuleDocument } from '../src/catalog/module-contract.ts' const root = resolve(dirname(fileURLToPath(import.meta.url)), '..') @@ -62,60 +63,133 @@ export function atSetting(report, setting) { return { setting, instructions: round(run.instr), cycles: round(run.cycles), stalls: round(run.stall) } } -/** The meter points an in-use reading added on the core of the slot it was taken on (T1-T4 core 1, T5-T8 core 0). */ +/** The meter points an in-use reading added on the core of the slot it was taken on (T1-T4 core 1, T5-T8 core 0): the mean, + * and the peak, the core's busiest block, which device:price keeps from 24 November 2026 (null in an older record). */ export function inUsePoints(result) { const track = Number(/^T(\d)/.exec(result?.inUseOn ?? '')?.[1]) if (!result?.inUseAdds || !track) return null - return { on: result.inUseOn, points: track <= 4 ? result.inUseAdds.dsp1to4 : result.inUseAdds.dsp5to8 } + const core = track <= 4 ? 'dsp1to4' : 'dsp5to8', peak = result.inUseAdds[core + 'Peak'] + return { on: result.inUseOn, points: result.inUseAdds[core], peak: typeof peak === 'number' ? peak : null } } -/** One module's line of the unit report: its cpu-price.json in-use reading against the record's model at the same - * setting (the defaults, where a fresh pick starts), plus what the base charges for features its package requires, - * which run outside the effect's proc and so outside the scan. `price` is evidence/cpu-price.json or null; `extra` - * [{name, cycles}]. */ -export function unitLine({ id, record, price, extra = [] }) { +/** The base identities a text names: each hex run of eight or more digits, cut to eight ("development twin d3d71297 of base + * 0.7.8 (main 02dfa20ca)" names d3d71297 and 02dfa20c). */ +export const identities = text => (String(text ?? '').match(/\b[0-9a-f]{8,}\b/g) ?? []).map(id => id.slice(0, 8)) + +/** The case a cycle-scan record models: the version and the published package it covers (the package row of that version), + * the setting, and what plays. dsp_host runs the proc block after block, as a playing unit does, and feeds no key bus, so a + * key-bus effect is scanned with its key bus silent. `keyBus` says whether the module reads the key bus at all. */ +export function scanCase({ record, row, keyBus = false }) { + return { version: record.version, package: row?.version === record.version ? row.sha256 ?? null : null, setting: record.defaults?.setting ?? null, + transport: 'playing', keyBus: keyBus ? record.inputs?.keyBus ?? 'silent' : null } +} + +/** The case a device:price reading measured (evidence/cpu-price.json): the version and package, the setting (a fresh pick + * starts at the defaults), what played (`inputs`, recorded from 24 November 2026: the transport always, the key bus when the + * caller named it; device:price always reads playing) and the base it ran on. */ +export function unitCase({ price, record, keyBus = false }) { + return { version: price.version, package: price.result?.packageSha256 ?? null, setting: price.result?.setting ?? record.defaults?.setting ?? null, + transport: price.inputs?.transport ?? 'playing', keyBus: keyBus ? price.inputs?.keyBus ?? 'not stated' : null, base: price.base ?? null } +} + +/** Why a reading and a model are not the same case: [] when they are. `extra` is the base charges added to the model, each + * with the base identities it was timed on (`bases`): a reading on another base ran another build of that base code. */ +export function notComparable(scan, unit, extra = []) { + const why = [] + if (scan.package && unit.package && scan.package !== unit.package) + why.push(`the unit measured package ${unit.package.slice(0, 8)}, not the published ${scan.version} (${scan.package.slice(0, 8)})`) + if (scan.setting !== unit.setting) why.push(`the unit read it at ${unit.setting}, the model is at ${scan.setting}`) + if (scan.transport !== unit.transport) why.push(`the unit read with the sequencer ${unit.transport}, the scan runs every block`) + if (scan.keyBus !== unit.keyBus) why.push(unit.keyBus === 'not stated' + ? `the reading does not say what its key bus carried, the scan's was ${scan.keyBus}` + : `its key bus was ${unit.keyBus} on the unit and ${scan.keyBus} in the scan`) + const seen = identities(unit.base) + for (const charge of extra) if (charge.bases?.length && !charge.bases.some(id => seen.includes(id))) + why.push(`the unit read on ${seen[0] ?? (unit.base || 'an unnamed base')}, the ${charge.name} charge (${charge.cycles}) was timed on ${charge.bases[0]}`) + return why +} + +/** One module's line of the unit report: its cpu-price.json in-use reading against the record's model, only where both are + * the same case (notComparable); else the line says why not and gives no ratio. The mean is compared with the model at the + * defaults (where a fresh pick starts), the peak, where the reading kept one, with the dearest setting, which bounds every + * setting. Both add what the base charges for features the package requires, which run outside the effect's proc and so + * outside the scan. `price` is evidence/cpu-price.json or null; `extra` [{name, cycles, bases?}]; `row` the USB package row. */ +export function unitLine({ id, record, price, extra = [], row, keyBus = false }) { const line = { id, version: record.version, modelDefaults: record.defaults?.cycles ?? null, modelDearest: record.dearest.cycles, - setting: record.defaults?.setting ?? null, outside: extra, notes: [] } + setting: record.defaults?.setting ?? null, outside: extra.map(({ name, cycles }) => ({ name, cycles })), notes: [] } const reading = inUsePoints(price?.result) if (!reading) { line.notes.push('no in-use reading on the unit'); return line } if (price.version !== record.version) { line.notes.push(`the unit reading is for ${price.version}, the record for ${record.version}`); return line } Object.assign(line, { on: reading.on, points: reading.points, unit: round(reading.points * POINT), base: price.base, measuredAt: price.measuredAt }) + if (reading.peak != null) Object.assign(line, { peak: reading.peak, unitPeak: round(reading.peak * POINT) }) if (line.modelDefaults == null) { line.notes.push('the record keeps no defaults run: record it again'); return line } - line.model = round(line.modelDefaults + extra.reduce((sum, e) => sum + e.cycles, 0)) + const charges = extra.reduce((sum, e) => sum + e.cycles, 0) + line.model = round(line.modelDefaults + charges) + const why = notComparable(scanCase({ record, row, keyBus }), unitCase({ price, record, keyBus }), extra) + if (why.length) { line.notComparable = why; return line } line.ratio = round(line.unit / line.model) if (Math.abs(line.unit / line.model - 1) > OUTLIER) line.outlier = true + if (line.unitPeak != null) { + line.modelPeak = round(line.modelDearest + charges) + line.peakRatio = round(line.unitPeak / line.modelPeak) + if (line.unitPeak > line.modelPeak * (1 + OUTLIER)) line.peakAbove = true + } return line } /** Every record against the unit's in-use readings, and the scanned modules that lack one. */ export function unitReport(base = root) { const dir = join(base, RECORDS), packages = readJson(join(base, 'src/engine/assets/octatrack-module-packages.json')).packages - const features = readJson(join(base, 'sdk/machines/octatrack/dsp-sites.json')).features + const sites = readJson(join(base, 'sdk/machines/octatrack/dsp-sites.json')), features = sites.features + const keyBusBits = features.filter(f => f.name === 'keybus').map(f => f.bit) + // A base charge's evidence names the base it was timed on (keybus-tap-timing-*.json's `base`). + const timedOn = f => { const path = f.evidence && join(base, 'sdk/machines/octatrack', f.evidence); return path && existsSync(path) ? identities(JSON.stringify(readJson(path).base)) : [] } const lines = readdirSync(dir).filter(name => name.endsWith('.json')).sort().map(name => { const record = readJson(join(dir, name)), id = record.module, pricePath = join(base, MODULES, id, 'evidence/cpu-price.json') - const requires = packages.find(row => row.id === id)?.requires ?? 0 - const extra = features.filter(f => requires & f.bit && typeof f.hardware === 'number').map(f => ({ name: f.name, cycles: f.hardware })) - return unitLine({ id, record, price: existsSync(pricePath) ? readJson(pricePath) : null, extra }) + const row = packages.find(item => item.id === id), requires = row?.requires ?? 0 + const extra = features.filter(f => requires & f.bit && typeof f.hardware === 'number').map(f => ({ name: f.name, cycles: f.hardware, bases: timedOn(f) })) + // A key-bus reader: its package requires the key bus, or the module owns a key-bus site (Sidechain Compressor's tap). + const keyBus = keyBusBits.some(bit => requires & bit) || sites.sites.some(site => site.module === id && keyBusBits.includes(site.feature)) + return unitLine({ id, record, price: existsSync(pricePath) ? readJson(pricePath) : null, extra, row, keyBus }) }) return { lines, missing: lines.filter(line => line.unit == null).map(line => line.id) } } /** The unit report as the Markdown table in sdk/cycle-scan/README.md. */ export function unitMarkdown({ lines }) { - const f = n => n == null ? '–' : String(Math.round(n)) + const f = n => n == null ? '–' : String(Math.round(n)), base = l => l.outside.length ? ' + ' + l.outside.map(e => `${e.cycles} ${e.name}`).join(' + ') : '' + const verdict = l => l.notComparable ? 'not comparable: ' + l.notComparable.join('; ') + : l.ratio == null ? l.notes.join('; ') : (l.outlier ? '**outlier**' : 'within ' + OUTLIER * 100 + ' %') + (l.peakAbove ? '; **peak above the dearest model**' : '') const rows = lines.map(l => `| ${l.id} ${l.version.replace(/-experimental$/, '')} | ${l.points == null ? '–' : `${l.points} = ${f(l.unit)} (${l.on})`} | ` + - `${l.setting ?? '–'} | ${f(l.modelDefaults)}${l.outside.length ? ' + ' + l.outside.map(e => `${e.cycles} ${e.name}`).join(' + ') : ''} | ${f(l.modelDearest)} | ` + - `${l.ratio == null ? '–' : l.ratio.toFixed(2)} | ${l.outlier ? '**outlier**' : l.notes.join('; ') || 'within ' + OUTLIER * 100 + ' %'} |`) - return ['| Module | Unit, in use (points = cycles a sample) | Defaults run | Model at defaults (+ base features) | Model, dearest | Unit ÷ model | Verdict |', - '|---|---|---|---|---|---|---|', ...rows].join('\n') + `${l.peak == null ? '–' : `${l.peak} = ${f(l.unitPeak)}`} | ${l.setting ?? '–'} | ${f(l.modelDefaults)}${base(l)} | ${f(l.modelDearest)}${base(l)} | ` + + `${l.ratio == null ? '–' : l.ratio.toFixed(2)} | ${l.peakRatio == null ? '–' : l.peakRatio.toFixed(2)} | ${verdict(l)} |`) + return ['| Module | Unit, in use (points = cycles a sample) | Unit, peak | Defaults run | Model at defaults (+ base features) | Model, dearest (+ base features) | Unit ÷ model | Peak ÷ dearest | Verdict |', + '|---|---|---|---|---|---|---|---|---|', ...rows].join('\n') +} + +export const README = 'sdk/cycle-scan/README.md' +const TABLE_START = '', TABLE_END = '' +/** The README's text with the table between its markers replaced. */ +export function withTable(text, table) { + const start = text.indexOf(TABLE_START), end = text.indexOf(TABLE_END) + if (start < 0 || end < start) throw new Error(`${README} has lost the generated table's markers`) + return text.slice(0, start + TABLE_START.length) + '\n' + table + '\n' + text.slice(end) +} +/** A failure when the README's committed table is not what the records and readings generate now, else null. */ +export function tableDrift(base = root) { + const path = join(base, README) + if (!existsSync(path)) return null + const text = readFileSync(path, 'utf8') + return withTable(text, unitMarkdown(unitReport(base))) === text ? null + : `${README}: the table under "Checked against the unit" is not what the records and the unit readings give now: run node scripts/cycle-scan.mjs unit --write` } -/** One record's verdict: {fail: [...], info: [...]}. `sourceSha256` is the module's source now; `performance` its - * evidence/performance.json, or null. */ -export function judge({ id, record, sourceSha256, performance }) { +/** One record's verdict: {fail: [...], info: [...]}. `sourceSha256` is the module's source now; `earlierSha256` the same + * source with presentation/, which records scanned before 25 November 2026 name; `performance` its evidence/performance.json, or null. */ +export function judge({ id, record, sourceSha256, earlierSha256, performance }) { const fail = [], info = [] if (record.schema !== 1 || record.module !== id) fail.push(`${id}: not a cycle-scan record for this module`) - if (record.sourceSha256 !== sourceSha256) + if (record.sourceSha256 !== sourceSha256 && !(earlierSha256 && record.sourceSha256 === earlierSha256)) fail.push(`${id}: the module's source changed since its cycle scan: run node scripts/cycle-scan.mjs record ${id} on your computer`) const scan = record.dearest const measured = performance?.cycles?.unit === 'instructions/sample' ? performance.cycles.measured : undefined @@ -169,12 +243,16 @@ export async function check(base = root) { const folder = join(base, MODULES, id) if (!existsSync(join(folder, 'octamod.module.json'))) { fail.push(`${id}: a cycle-scan record for a module that is not in ${MODULES}`); continue } const record = readJson(join(dir, id + '.json')) - const verdict = judge({ id, record, sourceSha256: await modulePerformanceSourceSha256(folder, documentOf(folder)), performance: performanceOf(folder) }) + const document = documentOf(folder) + const verdict = judge({ id, record, sourceSha256: await modulePerformanceSourceSha256(folder, document), earlierSha256: await moduleEarlierPerformanceSourceSha256(folder, document), performance: performanceOf(folder) }) const charge = judgeCharge({ id, record, row: packages.find(row => row.id === id), listed: catalog.find(entry => entry.id === id)?.addedAt }) fail.push(...verdict.fail, ...charge.fail); info.push(...verdict.info, ...charge.info) } const unscanned = readdirSync(join(base, MODULES)).filter(id => !ids.includes(id) && performanceOf(join(base, MODULES, id))?.kind === 'dsp') if (unscanned.length) info.push(`no cycle scan yet: ${unscanned.sort().join(', ')}`) + // The README's unit table is generated: it fell behind the key-bus charge once (51 there, 43 in dsp-sites.json). + const drift = ids.length ? tableDrift(base) : null + if (drift) fail.push(drift) return { fail, info, records: ids.length } } @@ -220,15 +298,21 @@ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.ur const { fail, info, records } = await check() for (const line of info) console.log(' · ' + line) for (const line of fail) console.error(' ✗ ' + line) - console.log(fail.length ? `Cycle scan: ${fail.length} of ${records} records fail.` : `Cycle scan: ${records} records current, none under-reported.`) + console.log(fail.length ? `Cycle scan: ${fail.length} failure${fail.length === 1 ? '' : 's'} over ${records} records.` : `Cycle scan: ${records} records current, none under-reported.`) if (fail.length) process.exitCode = 1 } else if (command === 'unit') { const report = unitReport() if (ids.includes('--markdown')) console.log(unitMarkdown(report)) - else for (const l of report.lines) console.log(` ${l.outlier ? '!' : '·'} ${l.id}: ` + (l.unit == null ? l.notes.join('; ') : - `unit ${l.unit} cycles a sample (${l.points} points on ${l.on}), model ${l.model} at ${l.setting}` + - (l.outside.length ? ` with ${l.outside.map(e => e.name + ' ' + e.cycles).join(', ')}` : '') + `, ${l.ratio}x` + (l.outlier ? ': an outlier' : ''))) - if (report.missing.length && !ids.includes('--markdown')) console.log(`No in-use reading to compare: ${report.missing.join(', ')}. A report only; nothing fails.`) - } else { console.error('Usage: node scripts/cycle-scan.mjs record [ ...] | check | unit [--markdown]'); process.exitCode = 2 } + else if (ids.includes('--write')) { + const path = join(root, README), text = readFileSync(path, 'utf8'), next = withTable(text, unitMarkdown(report)) + if (next !== text) writeFileSync(path, next) + console.log(next === text ? `${README}: the table is current.` : `${README}: wrote the table.`) + } else for (const l of report.lines) console.log(` ${l.notComparable ? '×' : l.outlier || l.peakAbove ? '!' : '·'} ${l.id}: ` + (l.unit == null ? l.notes.join('; ') : + `unit ${l.unit} cycles a sample (${l.points} points on ${l.on}${l.peak == null ? '' : `, peak ${l.peak}`}), model ${l.model} at ${l.setting}` + + (l.outside.length ? ` with ${l.outside.map(e => e.name + ' ' + e.cycles).join(', ')}` : '') + + (l.notComparable ? `: not comparable: ${l.notComparable.join('; ')}` : `, ${l.ratio}x` + (l.outlier ? ': an outlier' : '') + + (l.peakRatio == null ? '' : `; peak ${l.unitPeak} against ${l.modelPeak} at the dearest, ${l.peakRatio}x` + (l.peakAbove ? ': above the model' : ''))))) + if (report.missing.length && !ids.includes('--markdown') && !ids.includes('--write')) console.log(`No in-use reading to compare: ${report.missing.join(', ')}. A report only; nothing fails.`) + } else { console.error('Usage: node scripts/cycle-scan.mjs record [ ...] | check | unit [--markdown | --write]'); process.exitCode = 2 } } catch (error) { console.error(error.message); process.exitCode = 1 } } diff --git a/scripts/cycle-scan.test.mjs b/scripts/cycle-scan.test.mjs index ab1400332a..f7770489b9 100644 --- a/scripts/cycle-scan.test.mjs +++ b/scripts/cycle-scan.test.mjs @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' -import { CHARGE_COVERS_MODEL_FROM, POINT, UNDER_REPORT, atSetting, charged, check, dearest, inUsePoints, judge, judgeCharge, unitLine, unitMarkdown, unitReport } from './cycle-scan.mjs' +import { CHARGE_COVERS_MODEL_FROM, POINT, UNDER_REPORT, atSetting, charged, check, dearest, identities, inUsePoints, judge, judgeCharge, notComparable, scanCase, + tableDrift, unitCase, unitLine, unitMarkdown, unitReport, withTable } from './cycle-scan.mjs' const record = (more = {}) => ({ schema: 1, module: 'fx', version: '0.1.0', sourceSha256: 'a'.repeat(64), dearest: { setting: 'MODE=B/max', settings: 4, instructions: 400, cycles: 650, stalls: 90, stallsByKind: { arith: 60 } }, @@ -67,10 +68,19 @@ describe('the unit report', () => { const withDefaults = record({ defaults: { setting: 'MODE=A/def', instructions: 380, cycles: 600, stalls: 80 } }) it('reads the meter of the core the slot is on, at 45.32 cycles a point', () => { expect(POINT).toBe(45.32) - expect(inUsePoints({ inUseOn: 'T1 FX2', inUseAdds: { dsp1to4: 7.5, dsp5to8: 0.9 } })).toEqual({ on: 'T1 FX2', points: 7.5 }) - expect(inUsePoints({ inUseOn: 'T5 FX1', inUseAdds: { dsp1to4: 6.3, dsp5to8: 5.5 } })).toEqual({ on: 'T5 FX1', points: 5.5 }) + expect(inUsePoints({ inUseOn: 'T1 FX2', inUseAdds: { dsp1to4: 7.5, dsp5to8: 0.9 } })).toEqual({ on: 'T1 FX2', points: 7.5, peak: null }) + expect(inUsePoints({ inUseOn: 'T5 FX1', inUseAdds: { dsp1to4: 6.3, dsp5to8: 5.5, dsp1to4Peak: 9, dsp5to8Peak: 8.1 } })).toEqual({ on: 'T5 FX1', points: 5.5, peak: 8.1 }) expect(inUsePoints({ atRestAdds: {} })).toBeNull() }) + it('compares the peak with the dearest run, which bounds every setting, and flags one above it', () => { + const peaked = peak => price({ result: { inUseOn: 'T1 FX2', inUseAdds: { dsp1to4: 14.3, dsp5to8: 0.6, dsp1to4Peak: peak, dsp5to8Peak: 1 } } }) + expect(unitLine({ id: 'fx', record: withDefaults, price: peaked(15) })).toMatchObject({ peak: 15, unitPeak: 679.8, modelPeak: 650, peakRatio: 1.05 }) + const above = unitLine({ id: 'fx', record: withDefaults, price: peaked(16), extra: [{ name: 'keybus', cycles: 43 }] }) + expect(above).toMatchObject({ unitPeak: 725.12, modelPeak: 693, peakRatio: 1.05 }) + expect(above.peakAbove).toBeUndefined() + expect(unitLine({ id: 'fx', record: withDefaults, price: peaked(16) }).peakAbove).toBe(true) + expect(unitMarkdown({ lines: [unitLine({ id: 'fx', record: withDefaults, price: peaked(16) })] })).toContain('| 16 = 725 | MODE=A/def | 600 | 650 | 1.08 | 1.12 | within 10 %; **peak above the dearest model** |') + }) it('compares the reading with the model at the defaults and lists an outlier', () => { const near = unitLine({ id: 'fx', record: withDefaults, price: price() }) expect(near).toMatchObject({ unit: 648.08, model: 600, ratio: 1.08, setting: 'MODE=A/def' }) @@ -94,6 +104,59 @@ describe('the unit report', () => { }) }) +describe('only like cases are compared', () => { + const price = (more = {}) => ({ version: '0.1.0', base: 'development twin d3d71297 of base 0.7.8 (main 02dfa20ca)', measuredAt: '2026-11-18', + result: { inUseOn: 'T1 FX2', inUseAdds: { dsp1to4: 7.5, dsp5to8: 0.9 } }, ...more }) + const ring = record({ defaults: { setting: 'DUCK/def', instructions: 2.5, cycles: 5, stalls: 0 } }) + const tap = [{ name: 'keybus', cycles: 43, bases: ['856cbbcf', '9ac83b23', '1c937ed6'] }] + it('reads the base identities a base names, eight hex digits each', () => { + expect(identities('development twin d3d71297 of base 0.7.8 (main 02dfa20ca)')).toEqual(['d3d71297', '02dfa20c']) + expect(identities('8850f5399c453b9c (development twin, ef6099b0a)')).toEqual(['8850f539', 'ef6099b0']) + expect(identities(undefined)).toEqual([]) + }) + it('keeps a key-bus effect read with an unstated or live key bus, on another base than its charge, out of the ratio', () => { + const line = unitLine({ id: 'ring-sc', record: ring, price: price(), extra: tap, keyBus: true }) + expect(line.ratio).toBeUndefined() + expect(line.outlier).toBeUndefined() + expect(line.notComparable).toEqual([ + 'the reading does not say what its key bus carried, the scan\'s was silent', + 'the unit read on d3d71297, the keybus charge (43) was timed on 856cbbcf', + ]) + expect(unitMarkdown({ lines: [line] })).toMatch(/\| – \| – \| not comparable: the reading does not say what its key bus carried/) + const live = unitLine({ id: 'ring-sc', record: ring, price: price({ base: 'twin 856cbbcf', inputs: { transport: 'playing', keyBus: 'live' } }), extra: tap, keyBus: true }) + expect(live.notComparable).toEqual(['its key bus was live on the unit and silent in the scan']) + }) + it('pairs a key-bus effect read with a silent key bus on the base its charge was timed on', () => { + const silent = price({ base: 'development twin 1c937ed6', inputs: { transport: 'playing', keyBus: 'silent' } }) + expect(unitLine({ id: 'ring-sc', record: ring, price: silent, extra: tap, keyBus: true })).toMatchObject({ model: 48, ratio: 7.08, outlier: true }) + }) + it('refuses a reading of another package, another setting or a stopped sequencer', () => { + const row = { id: 'fx', version: '0.1.0', sha256: 'c'.repeat(64) }, scan = scanCase({ record: ring, row }) + expect(scan).toEqual({ version: '0.1.0', package: 'c'.repeat(64), setting: 'DUCK/def', transport: 'playing', keyBus: null }) + const unit = more => unitCase({ price: price(more), record: ring }) + expect(notComparable(scan, unit())).toEqual([]) // an older reading names no package: its version stands for it + expect(notComparable(scan, unit({ result: { packageSha256: 'c'.repeat(64) } }))).toEqual([]) + expect(notComparable(scan, unit({ result: { packageSha256: '9f22861f'.padEnd(64, '0') } }))).toEqual(['the unit measured package 9f22861f, not the published 0.1.0 (cccccccc)']) + expect(notComparable(scan, unit({ result: { setting: 'DUCK/max' } }))).toEqual(['the unit read it at DUCK/max, the model is at DUCK/def']) + expect(notComparable(scan, unit({ inputs: { transport: 'stopped' } }))).toEqual(['the unit read with the sequencer stopped, the scan runs every block']) + expect(scanCase({ record: ring, row: { ...row, version: '0.1.1' } }).package).toBeNull() // the row is another version's package + }) +}) + +describe('the README\'s unit table', () => { + // Generated from sdk/cycle-scan/records/, each module's evidence/cpu-price.json, sdk/machines/octatrack/dsp-sites.json and + // src/engine/assets/octatrack-module-packages.json; a change to any of them that moves a row must regenerate it. + it('is what node scripts/cycle-scan.mjs unit --markdown generates now', () => { + expect(tableDrift()).toBeNull() + }) + it('replaces only what lies between its markers, and fails without them', () => { + const start = '' + const text = `# x\n${start}\n| old |\n\nafter\n` + expect(withTable(text, '| new |')).toBe(`# x\n${start}\n| new |\n\nafter\n`) + expect(() => withTable('# no table', '| new |')).toThrow(/sdk\/cycle-scan\/README.md has lost the generated table's markers/) + }) +}) + describe('the committed records', () => { it('finds every committed record current and none under-reported', async () => { const result = await check() diff --git a/scripts/device.mjs b/scripts/device.mjs index f11eebea5f..bf493387e8 100644 --- a/scripts/device.mjs +++ b/scripts/device.mjs @@ -13,7 +13,8 @@ // npm run device -- remove [MODULE.mwrm] [--accept] # that file's module, else module 0 // npm run device -- set A.mwrm,B.mwrm,-C.mwrm [--accept] # one whole-set offer, as the site's Sync sends it: files to install, -FILE // to remove that file's module, +refuse for two test modules of which the base refuses the second (so the set rolls back); -// --split runs a set the module pool or a DSP window cannot hold (RUNTIME_MEMORY) in halves, each its own trial +// --split runs a set the module pool or a DSP window cannot hold (RUNTIME_MEMORY) in halves, each its own trial; +// --costs FILE sends that frame cost table (frame-costs.json's shape) instead of this checkout's; the unit keeps it either way // npm run device -- recover # a trial or staged set another run left behind: roll it back, leave upload mode // npm run device -- lifecycle // npm run device -- boot BUILD_DIR [--chunk 4096] # RAM boot: build_core.py's output, no flashing; serve: 'boot DIR 4096' @@ -60,7 +61,7 @@ import { crashNames, keepSymbols, namesFor } from '../src/dev/address-names.ts' import { trialVerdict } from '../src/dev/trial-verdict.ts' import { Bench, benchEndpoint, device, enumerate, shareBench } from './usb-bench.mjs' import { sequenceDrives, takeUnitTurn } from './unit-queue.mjs' -import { stageRefusal } from './octatrack-step-base.mjs' +import { bootOverPendingUpdate, stageRefusal } from './octatrack-step-base.mjs' const { values, positionals: [command, file] } = parseArgs({ allowPositionals: true, options: { help: { type: 'boolean', short: 'h' }, @@ -68,11 +69,13 @@ const { values, positionals: [command, file] } = parseArgs({ allowPositionals: t seconds: { type: 'string', default: '5' }, accept: { type: 'boolean', default: false }, split: { type: 'boolean', default: false }, + costs: { type: 'string' }, // set: the frame cost table to send, in frame-costs.json's shape (device:price's measuring table) emulator: { type: 'boolean', default: false }, png: { type: 'string' }, scale: { type: 'string', default: '2' }, share: { type: 'string' }, // serve: a second bench socket for the frontend MCP (shareBench) chunk: { type: 'string' }, // boot: bytes a frame (4096 for the flashed usbtest9 on macOS; docs/OCTATRACK_HARDWARE_TRAPS.md) + 'spend-tries': { type: 'boolean', default: false }, // boot: even over a base update not yet confirmed (bootOverPendingUpdate) } }) const usage = `Usage: npm run device -- COMMAND [--socket PATH] [--emulator] @@ -81,7 +84,7 @@ const usage = `Usage: npm run device -- COMMAND [--socket PATH] [--emulator] screen [--png FILE] [--scale 1-4] try MODULE.mwrm | set FILE,-FILE,… | remove [MODULE.mwrm] [--seconds 1-3600] [--accept] recover | lifecycle - boot BUILD_DIR [--chunk 1-4096] | flash BUILD_DIR + boot BUILD_DIR [--chunk 1-4096] [--spend-tries] | flash BUILD_DIR key NAME[+NAME] | enc A+3 | fader 0-255 | do SEQUENCE mem ADDR LENGTH | probe 0|1 | meter 0|1 @@ -788,7 +791,10 @@ if (command === 'serve') { : name.startsWith('-') ? [removal(identity.base, id(new Uint8Array(readFileSync(name.slice(1))))).data] : [new Uint8Array(readFileSync(name))]) // The unit refuses the set's identity while an install is open, which read as "busy" (22 November 2026: a killed `set` left its trial) if (session.status.phase !== 'normal') throw new Error(`The unit is in ${state(session.status)}: an install or trial is still open. If nothing else is running one, npm run device -- recover rolls it back.`) - const costs = ((await transport.capabilities())?.features ?? 0) & RuntimeFeature.frameCosts ? frameCostTable() : undefined + // A v2 set's table is kept in battery RAM whether or not the set is kept (loader.c): this checkout's, or --costs. + const own = values.costs ? JSON.parse(readFileSync(values.costs, 'utf8')) : undefined + const costs = ((await transport.capabilities())?.features ?? 0) & RuntimeFeature.frameCosts ? (own ? frameCostTable(own.costs, own.stock ?? null) : frameCostTable()) : undefined + if (own && !costs) throw new Error('--costs: this base keeps no frame cost table (no frame costs capability), so it would not be sent.') const offer = async packages => { const data = encodeModuleSet(identity.base, await transport.setIdentity(), packages, costs) console.log(`set: ${packages.length} changes, ${data.length} bytes${costs ? `, ${costs.length} frame costs` : ''}`) @@ -837,6 +843,15 @@ if (command === 'serve') { const expected = JSON.parse(readFileSync(join(file, 'proofs.json'), 'utf8')).configurationHash if (image.length < 4 || new DataView(image.buffer, image.byteOffset).getUint32(0) !== 0x4fefffe4) throw new Error(join(file, 'MAIN.raw') + ' is not an OS image.') + // A base update flashed and not yet confirmed loses one of its starts to each restart, a RAM boot's too (20 November 2026) + const slotsNow = () => transport.slots().catch(() => undefined) + let pending = values.emulator || values['spend-tries'] ? undefined : bootOverPendingUpdate(await slotsNow()) + if (pending?.wait) { + console.log('waiting up to 20 s for the base update the unit runs to confirm itself…') + for (let second = 0; second < 20 && pending?.wait; second++) { await wait(1000); pending = bootOverPendingUpdate(await slotsNow()) } + } + if (pending?.refusal) throw new Error(pending.refusal) + if (pending?.warning) console.log(pending.warning) const arm = async (s, base, flashed = false) => { const tooBig = stageRefusal(join(file, 'MAIN.raw'), image.length, s.status.capacity, flashed) if (tooBig) throw new Error(tooBig) diff --git a/scripts/fixtures/module-qualify/mackity/capture.json b/scripts/fixtures/module-qualify/mackity/capture.json new file mode 100644 index 0000000000..f3b8512e34 --- /dev/null +++ b/scripts/fixtures/module-qualify/mackity/capture.json @@ -0,0 +1,41 @@ +{ + "firmware": "1.40C", + "moduleVersion": "0.1.0-experimental", + "hardware": true, + "model": "MKII", + "capturedOn": "2026-11-25", + "capturedBy": "repeat98", + "imageSha256": "af4934ce5cdbc9816bc49864bd8848a6bad0af9af692b6752f330749b5f1b5c6", + "baseIdentity": "8fd6d456abf3865b36ac024d19324290dc36cb04a7efe29be4838ce6e825afb3", + "packageSha256": "5a58d4cc9ce2e5c2878ddafab9fa4437d4ded051066e1d0788307693330b39ac", + "sourceRevision": "ccbb96b6c06ae074159be45d66f69812d450793f", + "setup": "The owner's Octatrack MKII, OS 1.40C, RAM-booted on development twin 8fd6d456 of Modwerk base 0.8.1 (imageSha256 is that twin's MAIN image; baseIdentity is the identity the unit reported). The module ran as a RAM trial of the package named here, built by npm run module:dev -- mackity --build-only --cycles 226 --cycles-kind executed --state 32 from the source revision named here. Each picture is the unit's own LCD, read over USB by the development session's png step: 128x64 at integer scale 2 (256x128), two grey levels in an 8-bit greyscale PNG, not edited. Hardware captures, not emulator ones. The panel steps were sent by the session (bank F pattern 1; pick:T2:FX1:MACKITY; T2; FX1; FUNC+FX1).", + "palette": { + "on": [ + 24, + 24, + 24 + ], + "off": [ + 255, + 255, + 255 + ] + }, + "images": [ + { + "path": "mackity-chooser.png", + "sha256": "20bfc4bfed6244b16bf5c3bb7885caaa2f1a69020b2752c81908dc842d5a7b3c", + "scale": 2, + "page": "FX1 SETUP (effect chooser)", + "state": "Track 2 with Mackity on FX1: FUNC+FX1 opens the chooser on the current effect, Mackity." + }, + { + "path": "mackity-main.png", + "sha256": "6e303c4880734a17813ae318bde25906fd3e272de72ba73cac25ac1300c67bd6", + "scale": 2, + "page": "FX1", + "state": "Track 2 with Mackity on FX1 at the defaults (TRIM 13, PAD 127), stopped." + } + ] +} diff --git a/scripts/fixtures/module-qualify/mackity/cpu-price.json b/scripts/fixtures/module-qualify/mackity/cpu-price.json new file mode 100644 index 0000000000..5a466a167b --- /dev/null +++ b/scripts/fixtures/module-qualify/mackity/cpu-price.json @@ -0,0 +1,146 @@ +{ + "module": "mackity", + "version": "0.1.0-experimental", + "base": "development twin 8fd6d456 of base 0.8.1 (eb6679620d0c9ed7), the owner's MKII, OS 1.40C", + "scene": "Project on the owner's development unit, bank C, Part 1 reloaded in RAM to its saved copy; picks on the empty C02, readings on C04 (trigs on steps 1/5/9/13 of T1-T4, T6, T7) at the project tempo; transport played by the tool", + "inputs": { + "transport": "playing" + }, + "seconds": 8, + "readings": 3, + "measuredAt": "2026-11-25T09:20:07.215Z", + "result": { + "id": "mackity", + "version": "file", + "packageSha256": "5a58d4cc9ce2e5c2878ddafab9fa4437d4ded051066e1d0788307693330b39ac", + "before": { + "frame": 32.2, + "frameMax": 87.3, + "frames": 67404, + "skipped": 0, + "cpu": 55.7, + "dsp1to4": 32.7, + "dsp5to8": 43.7, + "dsp1to4Peak": 35.7, + "dsp5to8Peak": 44.6, + "readings": 3, + "spread": { + "frame": 0, + "cpu": 0.3, + "dsp1to4": 0, + "dsp5to8": 0, + "frameMax": 1.9, + "dsp1to4Peak": 1.9, + "dsp5to8Peak": 0.7 + } + }, + "atRest": { + "frame": 32.2, + "frameMax": 87.1, + "frames": 69517, + "skipped": 0, + "cpu": 55.7, + "dsp1to4": 32.7, + "dsp5to8": 43.7, + "dsp1to4Peak": 33.7, + "dsp5to8Peak": 44.8, + "readings": 3, + "spread": { + "frame": 0, + "cpu": 0.1, + "dsp1to4": 0, + "dsp5to8": 0, + "frameMax": 1.5, + "dsp1to4Peak": 0, + "dsp5to8Peak": 0.9 + } + }, + "atRestAdds": { + "frame": 0, + "cpu": 0, + "dsp1to4": 0, + "dsp5to8": 0, + "dsp1to4Peak": -2, + "dsp5to8Peak": 0.2 + }, + "inUse": { + "frame": 32.3, + "frameMax": 86.2, + "frames": 69919, + "skipped": 0, + "cpu": 55.7, + "dsp1to4": 40.8, + "dsp5to8": 43.7, + "dsp1to4Peak": 41.8, + "dsp5to8Peak": 44.8, + "readings": 3, + "spread": { + "frame": 0.1, + "cpu": 0.7, + "dsp1to4": 0, + "dsp5to8": 0, + "frameMax": 1.2, + "dsp1to4Peak": 0, + "dsp5to8Peak": 0.9 + } + }, + "inUseAdds": { + "frame": 0.1, + "cpu": 0, + "dsp1to4": 8.1, + "dsp5to8": 0, + "dsp1to4Peak": 6.1, + "dsp5to8Peak": 0.2 + }, + "inUseOn": "T1 FX2", + "curve": { + "tracks": [ + "T1", + "T3", + "T6", + "T7" + ], + "points": [ + 87.1, + 85.3, + 84.9, + 88, + 84.2 + ], + "adds": [ + -1.8, + -2.2, + 0.9, + -2.9 + ], + "first": 0.9, + "each": 0.9, + "notes": [], + "admission": [ + { + "pattern": "empty", + "number": 2, + "track": "T1", + "seconds": 8, + "admitted": true, + "frameMax": 36.4, + "frame": 27.7, + "dropped": 0, + "stalls": 0 + }, + { + "pattern": "medium", + "number": 4, + "track": "T1", + "seconds": 8, + "admitted": true, + "frameMax": 83, + "frame": 32.3, + "dropped": 0, + "stalls": 0 + } + ] + }, + "rolledBack": true + } +} diff --git a/scripts/fixtures/module-qualify/mackity/frame-cost.json b/scripts/fixtures/module-qualify/mackity/frame-cost.json new file mode 100644 index 0000000000..bb2049383c --- /dev/null +++ b/scripts/fixtures/module-qualify/mackity/frame-cost.json @@ -0,0 +1,55 @@ +{ + "module": "mackity", + "version": "0.1.0-experimental", + "base": "development twin 8fd6d456 of base 0.8.1 (eb6679620d0c9ed7), the owner's MKII, OS 1.40C", + "scene": "Project on the owner's development unit, bank C, Part 1 reloaded in RAM to its saved copy; picks on the empty C02, readings on C04 (trigs on steps 1/5/9/13 of T1-T4, T6, T7) at the project tempo; transport played by the tool", + "seconds": 8, + "measuredAt": "2026-11-25T09:20:07.215Z", + "tracks": [ + "T1", + "T3", + "T6", + "T7" + ], + "rest": 0, + "first": 0.9, + "each": 0.9, + "points": [ + 87.1, + 85.3, + 84.9, + 88, + 84.2 + ], + "adds": [ + -1.8, + -2.2, + 0.9, + -2.9 + ], + "admission": [ + { + "pattern": "empty", + "number": 2, + "track": "T1", + "seconds": 8, + "admitted": true, + "frameMax": 36.4, + "frame": 27.7, + "dropped": 0, + "stalls": 0 + }, + { + "pattern": "medium", + "number": 4, + "track": "T1", + "seconds": 8, + "admitted": true, + "frameMax": 83, + "frame": 32.3, + "dropped": 0, + "stalls": 0 + } + ], + "notes": [] +} diff --git a/scripts/fixtures/module-qualify/mackity/module.json b/scripts/fixtures/module-qualify/mackity/module.json new file mode 100644 index 0000000000..d35dfd6cb5 --- /dev/null +++ b/scripts/fixtures/module-qualify/mackity/module.json @@ -0,0 +1,281 @@ +{ + "schemaVersion": 2, + "id": "mackity", + "key": "MACKITY", + "name": "Mackity", + "version": "0.1.0-experimental", + "category": "effects", + "author": { + "github": "repeat98", + "credits": [ + "Chris Johnson / Airwindows: original Mackity algorithm and MIT-licensed source" + ] + }, + "nativeManifest": "manifest.py", + "presentation": { + "label": "MACKITY", + "family": "Saturation", + "summary": "Chris Johnson's Airwindows Mackity: the input stage of a Mackie-style mixing desk, driven by IN TRIM, on FX1 or FX2 of any track.", + "overview": "Mackity is Airwindows' model of a Mackie-style desk's input stage. The track's audio passes a gentle low cut, the desk's high-frequency rolloff, the IN TRIM gain and the console's clip, rounded by its curve, then a second rolloff and a DC blocker. At TRIM 13 it adds only the desk's colour; turning TRIM up drives the channel into the clip, from warm thickening to hard, square distortion. PAD sets the output level. The algorithm is upstream's, unchanged, in 24-bit fixed point at the Octatrack's 44.1 kHz.", + "highlights": [ + "Upstream's complete Mackity algorithm, credited to Chris Johnson", + "TRIM from silence through 0 dB (13) to +39.6 dB into the console's clip", + "Stereo and buffer-free: FX1 or FX2 on any track" + ], + "usage": [ + "Put MACKITY on FX1 of a drum or bass track. At TRIM 13 and PAD 127 it adds the desk's colour without a change in level.", + "Turn TRIM up for drive: at 26 (+12 dB) a track peaking at -12 dBFS reaches the clip, and above that it clips harder.", + "Turn PAD down to set the output level after heavy drive." + ] + }, + "controls": [ + { + "name": "TRIM", + "default": 13, + "count": 128, + "labels": null, + "doc": "In Trim: the gain into the desk, (TRIM/13)^2 as in the original. 13 is 0 dB, 26 is +12 dB, 52 is +24 dB, 127 is +39.6 dB; 0 is silence. More gain drives the signal into the console's clip." + }, + { + "name": "PAD", + "default": 127, + "count": 128, + "labels": null, + "doc": "Out Pad: the output level, PAD/128; 127 is exactly 0 dB, 64 is -6 dB, 0 is silence. With heavy drive the desk's rolloff peaks up to about 0.6 dB over full scale, which the Octatrack's output limits; PAD 120 or lower keeps every peak." + } + ], + "compatibility": { + "firmware": "1.40C", + "location": "FX1 / FX2", + "conflicts": [], + "uiClaims": [], + "limitations": [ + "At high TRIM the clip makes harmonics above 22 kHz that fold back below it, as the original does at 44.1 kHz.", + "With heavy drive, peaks up to about 0.6 dB over full scale are limited by the Octatrack's output; PAD 120 or lower keeps them.", + "On a pattern that already fills the CPU, a pick can be refused with CPU FULL (it asks +3 % on a busy eight-track pattern).", + "Tested on one MKII by the test procedure; the MKI, a Part or project reload with it saved and a power cycle were not tested by hand.", + "The original's 32-bit float dither is left out: the Octatrack's path is 24-bit fixed point." + ], + "effectId": 26 + }, + "resources": { + "recorded": "2026-11-25", + "storage": { + "label": "DSP program / state", + "display": "208 words / 32-word state", + "value": null, + "unit": "see display", + "method": "static", + "conditions": "The USB package's DSP effect: 208 program words on each DSP core it runs on; 32 words of the 256-word X block per instance (31 used); no buffer, no Y memory, no ColdFire code per frame.", + "source": "TESTING.md" + }, + "processing": { + "label": "DSP instruction peak", + "display": "228 instructions/sample per instance", + "value": null, + "unit": "see display", + "method": "emulator", + "conditions": "perf.py in dsp_host, 48 cases (defaults, TRIM 127, moving knobs, each unsplit and with a trig split at 1-15): worst 228.2 with a 1-frame split, 225.3 unsplit at every setting, against 290.1 for LO-FI and 330.9 for DJ EQ, the dearest stock effect. On the unit the DSP meter on T1-T4 rose 8.1 points with it on T1 FX2. Executed instructions, not chip cycles.", + "source": "TESTING.md" + }, + "cpuPrice": { + "value": 0.1, + "unit": "percent-of-frame", + "measure": "frame-interrupt", + "tool": "npm run device:price -- --write", + "date": "2026-11-25", + "conditions": "Project on the owner's development unit, bank C, Part 1 reloaded in RAM to its saved copy; picks on the empty C02, readings on C04 (trigs on steps 1/5/9/13 of T1-T4, T6, T7) at the project tempo; transport played by the tool; base development twin 8fd6d456 of base 0.8.1 (eb6679620d0c9ed7), the owner's MKII, OS 1.40C; 3 readings of 8 s a state. Frame interrupt 32.2 % before, 32.2 % installed and used nowhere, 32.3 % on T1 FX2; CPU meter 55.7 % before, 55.7 % at rest, 55.7 % in use.", + "source": "evidence/cpu-price.json" + }, + "impact": { + "conditions": "One active instance at the dearest setting (TRIM 127) with moving knobs and trig splits; no buffer; on the unit, the frame-interrupt price on a medium pattern.", + "cpu": { + "level": "minimal", + "basis": "measured-comparison", + "rationale": "No ColdFire audio code: the stock FX page publishes the knobs. On the owner's MKII the frame interrupt rose 0.1 points with it on T1 FX2 and 0 installed and unused; the instance curve read first 0.9, each 0.9.", + "source": "TESTING.md" + }, + "dsp": { + "level": "moderate", + "basis": "measured-comparison", + "rationale": "228.2 executed instructions/sample worst case with trig splits, 0.79 of LO-FI (290.1) and 0.69 of DJ EQ (330.9), the dearest stock effect, under matching cases; the static bound for four per core is 1,004 of 3,120 cycles a sample. Chip timing is unmeasured.", + "source": "TESTING.md" + }, + "memory": { + "level": "low", + "basis": "source-estimate", + "rationale": "208 program words per core, 32 words of the 256-word X block per instance, no buffer.", + "source": "TESTING.md" + } + } + }, + "tests": { + "report": "TESTING.md", + "summary": "verify.py matches the bit-exact model in dsp_host in every case; test_reference.py holds the model to upstream's algorithm; perf:audit passes at 0.79 of LO-FI's worst; npm run test:procedure steps 1-10 passed on the owner's MKII (25 Nov 2026), with the soak, the CPU price and the instance curve, and the screens captured on the unit.", + "hardwareStatus": "reported", + "evidenceRevision": "ccbb96b6c06ae074159be45d66f69812d450793f", + "gates": [ + "Worst-case cycles under parameter modulation and maximum load", + "Exact memory region and maximum-instance totals", + "Owner-reviewed real-hardware evidence with actual coverage and limitations" + ], + "qualification": { + "moduleVersion": "0.1.0-experimental", + "sourceSha256": "7271f6d9bb015b103e2048bf65912cd8b78bdcbe6205c37cb58f7434f22af846", + "cycles": [ + { + "processor": "dsp", + "worstCase": 4078, + "maxConfiguration": 16312, + "maxInstances": 8, + "budget": 49920, + "unit": "cycles/block", + "method": "static", + "conditions": { + "parameterExtremes": "Static bound per 16-frame block from the assembled words (perf.py): the per-sample loop's 21 words plus twice the 115-word channel routine, 251 cycles a sample (x16 = 4,016), plus the 62-word per-call setup (knob decode, seeding, the glides' snap) charged once per call. The loop and the routine have no conditional branch, so every knob value runs the same words.", + "parameterModulation": "Two calls per block cover a trig split: 16 x 251 + 2 x 31 = 4,078 (the setup's words split between its two halves, each charged on every call). LFOs, locks, scenes and CC reach the same two knob words, decoded every call and glided per sample. The dsp_host measurement with moving knobs and splits at 1-15 read at most 228.2 executed instructions a sample (3,651 a block), inside the bound.", + "modeSwitching": "Mackity has no modes: TRIM and PAD are continuous and run the same code at every value. Part changes reach it as knob changes.", + "maxLoad": "Eight instances, four per DSP core (FX2 of four tracks, or FX1 and FX2 of two): 4 x 4,078 = 16,312 per core within the SDK's 49,920 module allowance (3,120 a sample x 16). On the unit, eight at once while playing ran with CPU 458 and DSP peaks 663 and 743 per mille (device:test). The 2 s eight-instance dsp_host stress run peaked at 913.0 executed instructions a sample per core (evidence/performance.json). Real-chip contention and stalls are not modelled.", + "inputConditions": "The bound does not depend on sample values: silence, impulses, full-scale and clipping input run the same straight-line code. The stress stems include full-scale squares, impulses, DC steps, noise and a 20 Hz-20 kHz sweep." + }, + "report": "evidence/performance.json" + } + ], + "memory": { + "regions": [ + { + "name": "DSP program, the package's effect on each core it runs on", + "space": "dsp-p", + "words": 208, + "wordBits": 24, + "bytes": 624, + "scope": "shared" + }, + { + "name": "Used and initialized stock X state, r7+0..0x1f", + "space": "dsp-x", + "words": 32, + "wordBits": 24, + "bytes": 96, + "scope": "instance" + }, + { + "name": "Reserved remainder of the 256-word stock X block", + "space": "dsp-x", + "words": 224, + "wordBits": 24, + "bytes": 672, + "scope": "instance" + }, + { + "name": "System stack, one bsr inside the sample loop's do, on both cores", + "space": "dsp-x", + "words": 8, + "wordBits": 24, + "bytes": 24, + "scope": "shared" + } + ], + "perInstanceBytes": 768, + "sharedBytes": 648, + "maxInstances": 8, + "totalBytes": 6792, + "conditions": "The USB package (472 bytes of code and data, no bss, one DSP effect of 208 words) as the Modwerk base loads it into each core's DSP arena; per instance the stock 256-word r7 block an FX instance gets, of which Mackity initializes $00-$1f and uses $00-$1e; no allocator buffer, no Y memory (ybase NEVER), no scratch outside r7. The system stack holds the do loop and one bsr. Logical 24-bit DSP words.", + "report": "TESTING.md" + }, + "imageSha256": "af4934ce5cdbc9816bc49864bd8848a6bad0af9af692b6752f330749b5f1b5c6", + "hardware": { + "kind": "functional", + "status": "reported", + "model": "MKII", + "testedOn": "2026-11-25", + "tester": "repeat98", + "sourceRevision": "ccbb96b6c06ae074159be45d66f69812d450793f", + "imageSha256": "af4934ce5cdbc9816bc49864bd8848a6bad0af9af692b6752f330749b5f1b5c6", + "summary": "On the owner's Octatrack MKII (OS 1.40C), RAM-booted on development twin 8fd6d456 of base 0.8.1 (imageSha256 is that twin's MAIN image), the agent in the owner's session ran npm run test:procedure on the package of this source (5a58d4cc): software checks, the cost model, device:test (alone on FX2 of T1 and T5, eight at once while playing, 12 Part switches), a 2-minute soak, device:price with the instance curve and admission on the empty C02 and the medium C04, and the inventory put back; all passed. Earlier the same day, a 30-second RAM trial on the release base 0.8.1 and device:test on an empty bank passed too. The screens were read off the unit's LCD during a trial. The owner asked for it to be released without the hands-on stage (25 Nov 2026: \"you can merge and get it live yourself\").", + "limitations": [ + "One unit and its owner's session, not an independent reviewer; the MKI was not tested.", + "The owner's listening, a Part and project save and reload, and the Keep with a power cycle were not run by hand.", + "MAIN and CUE were not recorded over USB.", + "Single 8-s readings of the DSP load scatter by about a point; the DSP cost stands on dsp_host's count.", + "A card build beside Analog BD was not built or placed." + ], + "report": "TESTING.md" + }, + "documentation": { + "tutorial": { + "title": "Quick tutorial", + "steps": [ + "Put MACKITY on FX1 of a drum loop's track: hold FUNC, press FX1, turn LEVEL to Mackity and press YES. At TRIM 13 and PAD 127 the loop keeps its level and gains the desk's colour.", + "Turn TRIM to 40 on the FX1 page. The loop thickens and its peaks flatten into the clip; turn PAD to about 90 to bring the level back down.", + "Set TRIM 13 and PAD 127 to return to the clean desk, or select NONE in the FX1 chooser to remove it." + ] + }, + "screenshots": [ + "media/mackity-chooser.png", + "media/mackity-main.png" + ], + "screenshotStyle": "black-and-white" + } + } + }, + "source": { + "repository": "https://github.com/airwindows/airwindows", + "revision": "e718c9bcfcdd736deeddb08bffe6bce2aa8e0eea", + "path": "plugins/LinuxVST/src/Mackity" + }, + "license": { + "spdx": "MIT", + "file": "LICENSE", + "declaration": "Chris Johnson's published Mackity source and his full MIT copyright and permission notice are retained in upstream/ and LICENSE; the Octatrack adaptation is distributed under the same terms. No desktop binary, firmware, extracted stock routine or table, or memory dump is included." + }, + "media": [ + { + "path": "media/mackity-chooser.png", + "captureType": "hardware", + "caption": "Select an audio track, hold FUNC and press FX1. Turn LEVEL down the list to Mackity and press YES to put it on FX1 (FX2 works the same).", + "alt": "Octatrack FX1 SETUP: the effect list from FLANGER to LO-FI with the cursor on Mackity.", + "credit": "Modwerk documentation capture; underlying Octatrack UI by Elektron", + "license": "LicenseRef-OT-UI-Documentation", + "source": "original", + "otUi": { + "page": "FX1 SETUP (effect chooser)", + "shows": "location", + "firmware": "1.40C", + "moduleVersion": "0.1.0-experimental", + "imageSha256": "af4934ce5cdbc9816bc49864bd8848a6bad0af9af692b6752f330749b5f1b5c6", + "setup": "Captured over USB from the LCD of the owner's Octatrack MKII (OS 1.40C, development twin 8fd6d456 of Modwerk base 0.8.1, RAM-booted; imageSha256 is that twin's MAIN image) with the development session's png step on 25 November 2026, during a RAM trial of this version's package 5a58d4cc, built by module:dev from source ccbb96b6c. 256x128, the 128x64 LCD at integer scale 2, two grey levels, not edited." + } + }, + { + "path": "media/mackity-main.png", + "captureType": "hardware", + "caption": "Press FX1 for its page: TRIM (knob A) drives the desk, 13 is 0 dB; PAD (knob B) sets the output level, 127 is 0 dB.", + "alt": "Octatrack FX1 page of track 2 running Mackity: knobs TRIM and PAD, FX1 Mackity in the bottom line.", + "credit": "Modwerk documentation capture; underlying Octatrack UI by Elektron", + "license": "LicenseRef-OT-UI-Documentation", + "source": "original", + "otUi": { + "page": "FX1", + "shows": "controls", + "firmware": "1.40C", + "moduleVersion": "0.1.0-experimental", + "imageSha256": "af4934ce5cdbc9816bc49864bd8848a6bad0af9af692b6752f330749b5f1b5c6", + "setup": "Captured over USB from the LCD of the owner's Octatrack MKII (OS 1.40C, development twin 8fd6d456 of Modwerk base 0.8.1, RAM-booted; imageSha256 is that twin's MAIN image) with the development session's png step on 25 November 2026, during a RAM trial of this version's package 5a58d4cc, built by module:dev from source ccbb96b6c. 256x128, the 128x64 LCD at integer scale 2, two grey levels, not edited." + } + } + ], + "access": { + "location": "FUNC + FX1 or FUNC + FX2 SETUP on an audio track: the effect chooser. TRIM and PAD are on the FX page (knobs A and B).", + "steps": [ + "Select an audio track that plays a sample.", + "Hold FUNC and press FX1 (or FX2) to open its SETUP. Turn LEVEL to Mackity and press YES.", + "Press FX1 (or FX2) for its page: TRIM on knob A, PAD on knob B.", + "Set TRIM 13 and PAD 127 for the desk's colour at unchanged level, or select NONE to remove it." + ], + "screenshots": [ + "media/mackity-chooser.png", + "media/mackity-main.png" + ] + } +} diff --git a/scripts/fixtures/module-qualify/mackity/performance.json b/scripts/fixtures/module-qualify/mackity/performance.json new file mode 100644 index 0000000000..3caf887c25 --- /dev/null +++ b/scripts/fixtures/module-qualify/mackity/performance.json @@ -0,0 +1,34 @@ +{ + "schema": 1, + "module": "mackity", + "version": "0.1.0-experimental", + "sourceSha256": "617cb4e6beee171d3ba2be4883e9553dfa29aac13739768327a6af6aadfe0974", + "kind": "dsp", + "cycles": { + "unit": "instructions/sample", + "static": 251, + "measured": 228.2, + "instancesPerCore": 4, + "method": "static: perf.py, by the rule tools/build/cycle_count.py prices a straight-line loop with (one cycle a word): the per-sample loop's 21 words plus twice the 115-word channel routine it calls, 251 cycles/sample; the routine has no branch and the loop no nested do or rep. The per-call setup (62 words: knob decode, seeding, the glides' snap) runs once a call and is not in this floor; bsr/rts pipeline cost is not modelled. measured: perf.py, executed instructions from dsp_host's meter, one instance on verify.py's synthetic image (no null-stub subtraction), 4,096 blocks of 16 frames of stereo noise each: fixed knobs at the defaults (TRIM 13, PAD 127) and the dearest setting (TRIM 127), and a moving pattern (both knobs swept by triangles and jumped at random every 37 blocks), each unsplit and with a trig split at every position 1-15: 48 cases. Unsplit 225.30 in every case (the sample loop has no conditional branch); worst 228.20 with a split of 1 frame, where the setup runs twice a block. Executed instructions in dsp_host, not chip cycles; no stalls modelled." + }, + "stock": { + "comparator": "LO-FI", + "comparatorWorst": 290.06, + "dearestWorst": 330.94, + "baseline": "LOFI2's record (perf.py bench on the original image, the same stock image): LO-FI through fixed, moving and trig-split-1-15 cases, worst 290.06, unsplit 275.44; DJ EQ, the dearest stock effect, 330.94 with splits, 293.38 unsplit, as benchmark_stock_dsp.py's results.json. Not re-run for Mackity; its own cases match those (fixed, moving, a split at every position 1-15).", + "stockSha256": "164f31224bf61181e3f50e7dec40df9afcae5b16dbf6e4c0d0cc5e986af0a84e", + "justification": "LO-FI is the stock effect closest in function (its distortion stage). Mackity's worst, 228.20, is 0.79x LO-FI's 290.06 and 0.69x DJ EQ's 330.94; unsplit 225.30 against 275.44 and 293.38. It does upstream's whole algorithm: two 48-bit one-pole high-passes, two direct-form biquads, the clip and the fifth-order curve, per channel." + }, + "stress": { + "instancesPerCore": 4, + "tracks": 8, + "lfosPerTrack": 3, + "lockedSlots": 12, + "seconds": 2, + "guard": true, + "dirty": true, + "clobbers": 0, + "hangs": 0, + "method": "perf.py --stress: stress_project.py needs an Octatrack template project, so the load is driven straight into dsp_host on verify.py's synthetic image with both cores (-memB, -ctxB): eight Mackity instances, four a core, each on its own stem (decaying noise bursts, a full-scale square, a 20 Hz-20 kHz sweep, full-scale noise, impulses, full-scale DC steps, silence, a three-note chord) for 2 s plus a 2 s tail; all twelve parameter words given a new value every block through -paramfile: three LFOs (triangles on TRIM and PAD with a random jump every 37 blocks, a square on slot 2) and random values on slots 3-11. Mackity has two knobs and reads only slots 0 and 1; the other ten change to show that traffic on slots it does not read leaves it alone; trig splits of 1, 3, 7, 8, 12 and 15 frames on six instances; -guard (window 14,336 words an instance) and -dirty 0x5a. Result: host exit 0, no hang; every instance 0 stray write regions and 0 clobbers, guard clean; per-core peak 913.0 and 907.1 executed instructions/sample with four instances each (4 x 228.2). The instance at core 1 position 2 fed silence still put out non-zero samples: the harness writes one word a block into that audio block, as a do-nothing init/proc module in the same layout shows (1,000 non-zero samples in 1,000 blocks), so it is not Mackity's. It exercises the DSP side only: the firmware's LFO and lock delivery, Part switches and the ColdFire side are not in it." + } +} diff --git a/scripts/fixtures/module-qualify/mackity/price.json b/scripts/fixtures/module-qualify/mackity/price.json new file mode 100644 index 0000000000..a36d29d892 --- /dev/null +++ b/scripts/fixtures/module-qualify/mackity/price.json @@ -0,0 +1,146 @@ +{ + "scene": "bank C of the project on the owner's development unit, Part 1 reloaded in RAM, pattern 2 (empty) to pick, pattern 4 (trigs every four steps on T1-T4, T6, T7) to measure, transport stopped", + "inputs": { + "transport": "playing" + }, + "seconds": 8, + "readings": 3, + "slot": "T1", + "measuredAt": "2026-11-25T09:20:07.215Z", + "results": [ + { + "id": "mackity", + "version": "file", + "packageSha256": "5a58d4cc9ce2e5c2878ddafab9fa4437d4ded051066e1d0788307693330b39ac", + "before": { + "frame": 32.2, + "frameMax": 87.3, + "frames": 67404, + "skipped": 0, + "cpu": 55.7, + "dsp1to4": 32.7, + "dsp5to8": 43.7, + "dsp1to4Peak": 35.7, + "dsp5to8Peak": 44.6, + "readings": 3, + "spread": { + "frame": 0, + "cpu": 0.3, + "dsp1to4": 0, + "dsp5to8": 0, + "frameMax": 1.9, + "dsp1to4Peak": 1.9, + "dsp5to8Peak": 0.7 + } + }, + "atRest": { + "frame": 32.2, + "frameMax": 87.1, + "frames": 69517, + "skipped": 0, + "cpu": 55.7, + "dsp1to4": 32.7, + "dsp5to8": 43.7, + "dsp1to4Peak": 33.7, + "dsp5to8Peak": 44.8, + "readings": 3, + "spread": { + "frame": 0, + "cpu": 0.1, + "dsp1to4": 0, + "dsp5to8": 0, + "frameMax": 1.5, + "dsp1to4Peak": 0, + "dsp5to8Peak": 0.9 + } + }, + "atRestAdds": { + "frame": 0, + "cpu": 0, + "dsp1to4": 0, + "dsp5to8": 0, + "dsp1to4Peak": -2, + "dsp5to8Peak": 0.2 + }, + "inUse": { + "frame": 32.3, + "frameMax": 86.2, + "frames": 69919, + "skipped": 0, + "cpu": 55.7, + "dsp1to4": 40.8, + "dsp5to8": 43.7, + "dsp1to4Peak": 41.8, + "dsp5to8Peak": 44.8, + "readings": 3, + "spread": { + "frame": 0.1, + "cpu": 0.7, + "dsp1to4": 0, + "dsp5to8": 0, + "frameMax": 1.2, + "dsp1to4Peak": 0, + "dsp5to8Peak": 0.9 + } + }, + "inUseAdds": { + "frame": 0.1, + "cpu": 0, + "dsp1to4": 8.1, + "dsp5to8": 0, + "dsp1to4Peak": 6.1, + "dsp5to8Peak": 0.2 + }, + "inUseOn": "T1 FX2", + "curve": { + "tracks": [ + "T1", + "T3", + "T6", + "T7" + ], + "points": [ + 87.1, + 85.3, + 84.9, + 88, + 84.2 + ], + "adds": [ + -1.8, + -2.2, + 0.9, + -2.9 + ], + "first": 0.9, + "each": 0.9, + "notes": [], + "admission": [ + { + "pattern": "empty", + "number": 2, + "track": "T1", + "seconds": 8, + "admitted": true, + "frameMax": 36.4, + "frame": 27.7, + "dropped": 0, + "stalls": 0 + }, + { + "pattern": "medium", + "number": 4, + "track": "T1", + "seconds": 8, + "admitted": true, + "frameMax": 83, + "frame": 32.3, + "dropped": 0, + "stalls": 0 + } + ] + }, + "rolledBack": true + } + ] +} diff --git a/scripts/fixtures/module-qualify/mackity/procedure.json b/scripts/fixtures/module-qualify/mackity/procedure.json new file mode 100644 index 0000000000..58d64f4702 --- /dev/null +++ b/scripts/fixtures/module-qualify/mackity/procedure.json @@ -0,0 +1,210 @@ +{ + "procedure": 1, + "command": "npm run test:procedure -- mackity --package /tmp/mackity-q/mackity.mwrm --share /tmp/mackity-q/share.sock --dev-socket /tmp/mackity-q/dev.sock --out /tmp/mackity-q/proc --soak-seconds 120 --pick-pattern 2 --measure-pattern 4 --scene 'bank C of the project on the owner'\\''s development unit, Part 1 reloaded in RAM, pattern 2 (empty) to pick, pattern 4 (trigs every four steps on T1-T4, T6, T7) to measure, transport stopped'", + "date": "2026-11-25", + "started": "2026-11-25T09:16:02.394Z", + "finished": "2026-11-25T09:24:29.384Z", + "seconds": 507, + "target": { + "kind": "module", + "id": "mackity", + "version": "0.1.0-experimental", + "machine": "octatrack", + "draft": true + }, + "build": { + "revision": "ccbb96b6c06ae074159be45d66f69812d450793f", + "dirty": false, + "package": { + "path": "/tmp/mackity-q/mackity.mwrm", + "sha256": "5a58d4cc9ce2e5c2878ddafab9fa4437d4ded051066e1d0788307693330b39ac" + } + }, + "unit": { + "available": true, + "share": "/tmp/mackity-q/share.sock", + "target": "unit" + }, + "steps": [ + { + "id": "software", + "title": "Software checks", + "layer": "host", + "unit": false, + "status": "passed", + "commands": [ + "npm run module:doctor -- --draft mackity" + ], + "seconds": 9.9, + "log": "logs/01-software.log" + }, + { + "id": "compat", + "title": "Beside every other module", + "layer": "contract", + "unit": false, + "status": "not run", + "commands": [], + "seconds": 0, + "reason": "a draft is judged beside every other module by module:doctor --draft (its compatibility line, step 1)" + }, + { + "id": "build", + "title": "Name the build", + "layer": "host", + "unit": false, + "status": "passed", + "commands": [], + "seconds": 0, + "log": "logs/03-build.log" + }, + { + "id": "cost-model", + "title": "DSP cost model", + "layer": "contract", + "unit": false, + "status": "passed", + "commands": [ + "node scripts/cycle-scan.mjs check" + ], + "seconds": 0.2, + "log": "logs/04-cost-model.log" + }, + { + "id": "emulator", + "title": "Emulator rehearsal", + "layer": "emulator", + "unit": false, + "status": "not run", + "commands": [], + "seconds": 0, + "reason": "no emulator session (--emulator-socket SOCK, an ot_emu with --usb-host on a development base)" + }, + { + "id": "unit-read", + "title": "Read the unit", + "layer": "target", + "unit": true, + "status": "passed", + "commands": [ + "node scripts/device.mjs status --socket /tmp/mackity-q/share.sock", + "node scripts/device.mjs do inventory --socket /tmp/mackity-q/share.sock" + ], + "seconds": 0.3, + "log": "logs/06-unit-read.log" + }, + { + "id": "unit-pass", + "title": "Scripted unit pass", + "layer": "target", + "unit": true, + "status": "passed", + "commands": [ + "npm run device:test -- --share /tmp/mackity-q/share.sock --testing-entry /tmp/mackity-q/proc/device-test.md /tmp/mackity-q/mackity.mwrm" + ], + "seconds": 111.2, + "log": "logs/07-unit-pass.log" + }, + { + "id": "soak", + "title": "Soak", + "layer": "target", + "unit": true, + "status": "passed", + "commands": [ + "node scripts/device.mjs try /tmp/mackity-q/mackity.mwrm --seconds 420 --socket /tmp/mackity-q/share.sock", + "node scripts/octatrack-soak.mjs --seconds 120 --log /tmp/mackity-q/proc/soak.json" + ], + "seconds": 122.8, + "log": "logs/08-soak.log" + }, + { + "id": "cost-unit", + "title": "Cost on the unit", + "layer": "unit", + "unit": true, + "status": "passed", + "commands": [ + "npm run device:price -- --share /tmp/mackity-q/share.sock --out /tmp/mackity-q/proc/price.json --scene 'bank C of the project on the owner'\\''s development unit, Part 1 reloaded in RAM, pattern 2 (empty) to pick, pattern 4 (trigs every four steps on T1-T4, T6, T7) to measure, transport stopped' --curve T1,T3,T6,T7 --pick-pattern 2 --measure-pattern 4 /tmp/mackity-q/mackity.mwrm" + ], + "seconds": 261.8, + "log": "logs/09-cost-unit.log" + }, + { + "id": "restore", + "title": "Put back", + "layer": "target", + "unit": true, + "status": "passed", + "commands": [ + "node scripts/device.mjs do inventory --socket /tmp/mackity-q/share.sock" + ], + "seconds": 0.3, + "log": "logs/10-restore.log" + }, + { + "id": "by-hand", + "title": "Agent by hand", + "layer": "target", + "unit": false, + "status": "to do", + "commands": [], + "seconds": 0, + "todo": [ + "every control and screen by the README's button steps, a png: screenshot of each, compared with the README and its UI claims", + "MAIN and CUE recorded over USB (rec) with a sustained sound, checked for dropouts (runs of exact zeros, a block played twice)" + ] + }, + { + "id": "developer", + "title": "Submitter's own stage", + "layer": "unit", + "unit": false, + "status": "to do", + "commands": [], + "seconds": 0, + "todo": [ + "how it sounds and plays, and timing by ear", + "MIDI, scenes and recording with it", + "it beside the other modules installed on their unit", + "two instances with different settings, on both FX slots and both DSP cores where it can (docs/MODULE_QUALIFICATION.md)", + "Part reload, project save and reload, and a power cycle with it saved: what survives (the Keep and the power cycle are theirs)" + ] + } + ], + "edgeCases": { + "suggested": [ + { + "touches": "an effect slot", + "ask": "FX1 and FX2, both DSP cores, eight instances at once; one edited while another plays", + "see": "MODULE_QUALIFICATION.md#essential-persistence-and-instance-checks--8-october-2026" + }, + { + "touches": "memory", + "ask": "the module pool nearly full; a delay buffer next to it; the largest set it can join", + "see": "OCTATRACK_HARDWARE_TRAPS.md#dsp-loader-dynamic-dsp-code" + }, + { + "touches": "persistence", + "ask": "saved in a Part, then a Part reload, a project reload and a power cycle; removed while a saved Part still names it", + "see": "OCTATRACK_MODULE_EDGE_CASES.md#copying-and-saving" + }, + { + "touches": "DSP code", + "ask": "DSP FULL; both cores; the receiver window; pipeline stalls the instruction count hides", + "see": "OCTATRACK_HARDWARE_TRAPS.md#coldfire-and-dsp-load" + } + ], + "cases": [] + }, + "developer": { + "status": "to do", + "items": [ + "how it sounds and plays, and timing by ear", + "MIDI, scenes and recording with it", + "it beside the other modules installed on their unit", + "two instances with different settings, on both FX slots and both DSP cores where it can (docs/MODULE_QUALIFICATION.md)", + "Part reload, project save and reload, and a power cycle with it saved: what survives (the Keep and the power cycle are theirs)" + ] + } +} diff --git a/scripts/frontend-mcp-refresh.test.mjs b/scripts/frontend-mcp-refresh.test.mjs new file mode 100755 index 0000000000..df1e211c86 --- /dev/null +++ b/scripts/frontend-mcp-refresh.test.mjs @@ -0,0 +1,74 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { mkdtemp, rm, writeFile, chmod, utimes } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createFrontendTools } from './frontend-mcp.mjs' + +// The MCP bundles the site at start. After a branch switch or a base regeneration it kept that bundle and refused the +// new base until the developer reconnected; now each tool call compares the files the bundle came from and rebuilds. +let folder, watched, service +const at = seconds => new Date(Date.UTC(2026, 10, 1, 0, 0, seconds)) +beforeEach(async () => { + folder = await mkdtemp(join(tmpdir(), 'modwerk-mcp-refresh-')); await chmod(folder, 0o700) + watched = join(folder, 'base-versions.json') + await writeFile(watched, '{"latest":"0.8.1"}'); await utimes(watched, at(1), at(1)) +}) +afterEach(async () => { await service?.close(); service = undefined; await rm(folder, { recursive: true, force: true }) }) + +/** A bundler that builds the site from `watched`: its documents carry the build number. */ +function counting({ fail = () => false, during = async () => {} } = {}) { + const builds = { site: 0, publication: 0 } + const bundle = async entry => { + if (entry.endsWith('octatrack-publication.ts')) { builds.publication++; return { module: { publishedPackages: { packages: [] } }, files: [] } } + builds.site++ + await during(builds.site) + if (fail(builds.site)) throw new Error('Could not resolve ../catalog/machine-modules.json') + const build = builds.site + return { files: [watched], module: { validateConfiguration: value => value, createRuntimeCatalogue: () => ({ ids: [] }), resolveSelection: () => {}, documents: { everb: { build } } } } + } + return { builds, bundle } +} +const tools = (bundle, now) => createFrontendTools({ dataDir: join(folder, 'workspace') }, undefined, { bundle, ...now ? { now } : {} }) + +describe('the developer MCP follows the checkout', () => { + it('keeps its bundle while nothing it was built from changed', async () => { + const { builds, bundle } = counting() + service = await tools(bundle) + expect(await service.call('site_module', { id: 'everb' })).toEqual({ build: 1 }) + expect(await service.call('site_module', { id: 'everb' })).toEqual({ build: 1 }) + expect(builds).toEqual({ site: 1, publication: 1 }) + }) + + it('rebuilds the site and the package manifest after a bundled file changed (a branch switch or base regeneration)', async () => { + const { builds, bundle } = counting() + service = await tools(bundle) + await writeFile(watched, '{"latest":"0.8.2"}'); await utimes(watched, at(2), at(2)) + expect(await service.call('site_module', { id: 'everb' })).toEqual({ build: 2 }) + expect(builds).toEqual({ site: 2, publication: 2 }) + // Board tools do not use the site bundle, so they never wait for a rebuild. + await utimes(watched, at(3), at(3)) + await service.call('board_claims', {}).catch(() => {}) + expect(builds.site).toBe(2) + }) + + it('says why when the changed checkout does not build, and builds again on the next call', async () => { + const { builds, bundle } = counting({ fail: build => build === 2 }) + service = await tools(bundle) + await utimes(watched, at(2), at(2)) + await expect(service.call('site_module', { id: 'everb' })).rejects.toThrow(/checkout changed since this server bundled the site.*rebuilding failed: Could not resolve/) + expect(await service.call('site_module', { id: 'everb' })).toEqual({ build: 3 }) + expect(builds.site).toBe(3) + }) + + it('builds again when a file was written while the bundle was being built', async () => { + // A regeneration still writing its files: the first bundle may hold half of them. The clock is the test's, since file + // times are coarser than Date.now() and the server counts a build from 2 s before it began. + let now = at(10).getTime() + const { builds, bundle } = counting({ during: async build => { if (build === 1) await utimes(watched, at(9), at(9)) } }) + service = await tools(bundle, () => now) + now = at(30).getTime() + expect(await service.call('site_module', { id: 'everb' })).toEqual({ build: 2 }) + expect(await service.call('site_module', { id: 'everb' })).toEqual({ build: 2 }) + expect(builds.site).toBe(2) + }) +}) diff --git a/scripts/frontend-mcp.mjs b/scripts/frontend-mcp.mjs index 0165668bd2..09db1145f6 100644 --- a/scripts/frontend-mcp.mjs +++ b/scripts/frontend-mcp.mjs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later import { existsSync } from 'node:fs' -import { readFile, writeFile, mkdir, rename, lstat, rm } from 'node:fs/promises' -import { resolve, join } from 'node:path' +import { readFile, writeFile, mkdir, rename, lstat, rm, stat } from 'node:fs/promises' +import { resolve, join, isAbsolute } from 'node:path' import { pathToFileURL, fileURLToPath } from 'node:url' import { randomUUID, createHash } from 'node:crypto' import { createInterface } from 'node:readline' @@ -144,14 +144,38 @@ export async function createFrontendTools(options, injected, dependencies = {}) try { await takeLease(lease, dependencies.lease) } catch (error) { activeWorkspace = false; throw error } try { await writeFile(join(lease, 'owner.json'), JSON.stringify({ pid: process.pid, started: new Date().toISOString() }), { mode: 0o600, flag: 'wx' }) - let frontend = injected - if (!frontend) { - const bridge = join(ROOT, 'scripts/frontend-mcp-bridge.ts') - const bundled = await build({ root, configFile: false, logLevel: 'silent', plugins: [{ name: 'mcp-candidate-source', resolveId(id, importer) { if (importer === bridge && id.startsWith('../src/')) return resolve(root, id.slice(3)) } }], define: { 'import.meta.env.VITE_COMMUNITY_API_URL': JSON.stringify(api.href), 'import.meta.env.DEV': 'false', 'import.meta.env.BASE_URL': JSON.stringify('/') }, build: { ssr: bridge, write: false, minify: false, sourcemap: false } }) - const source = bundled.output.find(entry => entry.type === 'chunk' && entry.isEntry)?.code + // The site bundle and the package manifest, with the files they were built from. A branch switch or a base regeneration + // changes those files, and a server that kept its first bundle refused the new base until the developer reconnected + // (/mcp). So each tool call compares them first and rebuilds what changed (refreshFrontend below). + const bridge = join(ROOT, 'scripts/frontend-mcp-bridge.ts') + const bundle = dependencies.bundle ?? (async entry => { + const bundled = await build({ root, configFile: false, logLevel: 'silent', plugins: [{ name: 'mcp-candidate-source', resolveId(id, importer) { if (importer === bridge && id.startsWith('../src/')) return resolve(root, id.slice(3)) } }], define: { 'import.meta.env.VITE_COMMUNITY_API_URL': JSON.stringify(api.href), 'import.meta.env.DEV': 'false', 'import.meta.env.BASE_URL': JSON.stringify('/') }, build: { ssr: entry, write: false, minify: false, sourcemap: false } }) + const chunks = bundled.output.filter(item => item.type === 'chunk'), source = chunks.find(item => item.isEntry)?.code if (!source) throw new Error('Could not load the frontend testing bridge.') - frontend = await import('data:text/javascript;base64,' + Buffer.from(source).toString('base64')) + return { module: await import('data:text/javascript;base64,' + Buffer.from(source).toString('base64')), files: chunks.flatMap(item => item.moduleIds).filter(id => isAbsolute(id) && existsSync(id)) } + }) + const publication = join(root, 'src/engine/elekloader/octatrack-publication.ts'), packagesFile = join(root, 'src/engine/assets/octatrack-module-packages.json') + // Size and modification time of each file. A file written while the bundle was being built (a regeneration still running) + // leaves the stamp empty, so the next call builds again instead of keeping a bundle of half-written inputs. File times + // run on a coarser clock than Date.now() (and some file systems keep 2 s), so the build counts from 2 s before it began. + const stamp = async (files, since = Infinity) => { + const seen = await Promise.all(files.map(file => stat(file).then(info => ({ line: file + ' ' + info.size + ' ' + info.mtimeMs, late: info.mtimeMs >= since }), () => ({ line: file + ' gone', late: true })))) + return seen.some(item => item.late) ? '' : seen.map(item => item.line).join('\n') + } + let frontend, preparedModules, catalogue, built = { files: [], stamp: '' } + async function loadFrontend() { + const started = (dependencies.now ?? Date.now)() - 2000 + const site = injected ? { module: injected, files: [] } : await bundle(bridge) + // Private preparation receipts name the native SDK's paths. A normal site session uses its served files. + const published = !options.preparedModules && !injected && existsSync(publication) ? await bundle(publication) : null + const nextManifest = published ? published.module.publishedPackages : JSON.parse(await readFile(packagesFile, 'utf8')) + const prepared = options.preparedModules && await loadPreparedModules(options.preparedModules, nextManifest, site.module) + const files = injected ? [] : [...new Set([...site.files, ...published ? published.files : [packagesFile], ...options.preparedModules ? [options.preparedModules] : []])] + const nextCatalogue = prepared?.catalogue ?? site.module.createRuntimeCatalogue(nextManifest) + frontend = site.module; preparedModules = prepared; catalogue = nextCatalogue + built = { files, stamp: await stamp(files, started) } } + await loadFrontend() if (!Array.isArray(sets) || sets.length > 100) throw new Error('The local set file is invalid.') sets = sets.map(frontend.validateConfiguration) const save = async values => { @@ -159,20 +183,14 @@ export async function createFrontendTools(options, injected, dependencies = {}) try { await writeFile(temporary, JSON.stringify(values, null, 2), { mode: 0o600, flag: 'wx' }); await rename(temporary, file); sets = values } finally { await rm(temporary, { force: true }) } } - const publication = join(root, 'src/engine/elekloader/octatrack-publication.ts') - // Private preparation receipts name the native SDK's paths. A normal site session uses its served files. - const manifest = !options.preparedModules && !injected && existsSync(publication) - ? (await import(pathToFileURL(publication).href)).publishedPackages - : JSON.parse(await readFile(join(root, 'src/engine/assets/octatrack-module-packages.json'), 'utf8')) - const preparedModules = options.preparedModules && await loadPreparedModules(options.preparedModules, manifest, frontend) - const catalogue = preparedModules?.catalogue ?? frontend.createRuntimeCatalogue(manifest) - const load = preparedModules?.load ?? (async entry => { + const load = entry => preparedModules?.load ? preparedModules.load(entry) : loadSitePackage(entry) + const loadSitePackage = async entry => { if (!/^octatrack-modules\/[a-z0-9-]+\/[a-zA-Z0-9.-]+\.mwrm$/.test(entry.path) && !(/^[a-f0-9]{64}$/.test(entry.sha256) && entry.path === 'octatrack-base-packages/' + entry.sha256 + '.mwrm')) throw new Error('Unexpected module asset path.') const bytes = new Uint8Array(await readFile(join(root, 'public', entry.path))) if (bytes.length !== entry.bytes || hash(bytes) !== entry.sha256) throw new Error('The local site package differs from its manifest.') return bytes - }) + } const storage = () => { const map = new Map(); return { getItem: key => map.get(key) ?? null, setItem: (key, value) => map.set(key, value), removeItem: key => map.delete(key) } } globalThis.localStorage = storage(); globalThis.sessionStorage = storage() if (credentials) { @@ -533,6 +551,15 @@ export async function createFrontendTools(options, injected, dependencies = {}) if (!keep && !frontend.sameModules(result.inventory.moduleIds, completed.before.inventory.moduleIds)) throw new Error('Undo did not restore the reviewed inventory.') return { kept: keep, completed: true, ...result } } + // Before each tool call: rebuild the bundle when a file it was built from changed. An open trial keeps the bundle it + // started with until Keep or Undo; the link and reviews belong to the old bundle, so they are dropped. + async function refreshFrontend() { + if (trial || await stamp(built.files) === built.stamp) return + dropLink(); closeZoom() + try { await loadFrontend() } + catch (error) { throw new Error('The checkout changed since this server bundled the site (a branch switch or base regeneration), and rebuilding failed: ' + error.message + ' Once the checkout builds again, call the tool again; nothing was sent.', { cause: error }) } + console.error('Rebuilt the site bundle: the checkout changed since the last tool call.') + } let running = false return { tools: TOOLS, @@ -548,7 +575,7 @@ export async function createFrontendTools(options, injected, dependencies = {}) if (closed) throw new Error('The MCP workspace is closed.') if (running) throw new Error('Another frontend/device operation is running.') running = true - try { return await handlers[name](args) } finally { running = false; releaseIdleLink() } + try { if (!name.startsWith('board_')) await refreshFrontend(); return await handlers[name](args) } finally { running = false; releaseIdleLink() } }, // Every caller gets the same promise: on SIGTERM both the closed input and the signal handler close, and the handler // exits only after the lock is removed (an early return here once let the process exit with the lock still there). diff --git a/scripts/module-cpu-price.mjs b/scripts/module-cpu-price.mjs index 4cd045d07c..75484fadea 100644 --- a/scripts/module-cpu-price.mjs +++ b/scripts/module-cpu-price.mjs @@ -34,6 +34,17 @@ export function manifestWithoutPrice(text) { /** The price a device:price reading gives: the larger of what the module added at rest and in use, never below 0. */ export const measuredPrice = result => Math.max(0, result.atRestAdds.frame, result.inUseAdds?.frame ?? 0) +/** How far a device:price record's own readings agreed, for module:doctor: '' for a record of one reading a state (every record + * before 24 November 2026), else the count and the widest spread of the frame interrupt's share and of the slot core's DSP peak. */ +export function readingsNote(record) { + if (!(record?.readings > 1)) return '' + const states = ['before', 'atRest', 'inUse'].map(key => record.result?.[key]?.spread).filter(Boolean) + const widest = key => { const values = states.map(spread => spread[key]).filter(value => typeof value === 'number'); return values.length ? Math.max(...values) : null } + const frame = widest('frame'), track = Number(/^T(\d)/.exec(record.result?.inUseOn ?? '')?.[1]) + const peak = track ? widest(track <= 4 ? 'dsp1to4Peak' : 'dsp5to8Peak') : null + return '; ' + record.readings + ' readings a state' + (frame === null ? '' : ', the frame interrupt within ' + frame + ' points') + + (peak === null ? '' : ', the ' + (track <= 4 ? 'T1-4' : 'T5-8') + ' DSP peak within ' + peak) +} /** How to measure the price of a machine (true) or of any other module (false), for the messages. */ export function cpuPriceHowTo(id, machine) { @@ -147,8 +158,10 @@ export function cpuPriceStatus({ root, document, pending, glue = null }) { if (!declared) return { state: 'fail', detail: 'it names no CPU price (resources.cpuPrice)', fix: howTo } if (machine && declared.measure !== 'machine-render') return { state: 'fail', detail: 'it is a machine, so its price is what one playing track adds ("measure": "machine-render"), not ' + declared.measure, fix: howTo } if (!machine && declared.measure !== 'frame-interrupt') return { state: 'fail', detail: 'it is not a machine, so its price is the frame interrupt\'s share ("measure": "frame-interrupt"); only a machine\'s descriptor carries a render price', fix: howTo } + let repeat = '' if (declared.source.endsWith('.json')) { // a price device:price wrote: recomputed from its readings, never taken on trust const record = readJson(resolve(root, 'sdk/octatrack/modules', id, declared.source)) + repeat = readingsNote(record) if (record?.module !== id || !record.result?.atRestAdds) return { state: 'fail', detail: 'its price names ' + declared.source + ' as its source, which holds no device:price reading of ' + id, fix: howTo } // Tape Echo 0.1.9 carried the price read on 0.1.6: a release from RELEASE_COST_FROM measures its own. const date = releaseDate({ root, document }), logged = existsSync(resolve(root, 'src/community/module-changelogs', id + '.json')) @@ -168,7 +181,7 @@ export function cpuPriceStatus({ root, document, pending, glue = null }) { if (meter) return { state: 'fail', ...meter } const what = declared.value + ' % of a frame (' + declared.measure + ', ' + declared.tool + ', ' + declared.date + ')' const adds = document.resources.cpuMeter ? '; adds ' + document.resources.cpuMeter.value + ' meter points (reserved[1], ' + document.resources.cpuMeter.date + ')' : '' - return { state: 'ok', detail: what + (descriptors.length ? '; ' + descriptors.map(item => item.symbol).join(', ') + ' carries the same in reserved[0]' : '') + adds } + return { state: 'ok', detail: what + repeat + (descriptors.length ? '; ' + descriptors.map(item => item.symbol).join(', ') + ' carries the same in reserved[0]' : '') + adds } } /** The meter points a machine adds, recomputed from its paired readings: { added } or { problem }. */ diff --git a/scripts/module-cpu-price.test.mjs b/scripts/module-cpu-price.test.mjs index 45a6832fb3..acb25b4540 100644 --- a/scripts/module-cpu-price.test.mjs +++ b/scripts/module-cpu-price.test.mjs @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { parseModuleCpuMeter, parseModuleCpuPrice, parseModuleDocument } from '../src/catalog/module-contract.ts' -import { AT_REST_FROM, AT_REST_LIMIT, CPU_PRICE_PENDING_REASON, RELEASE_COST_FROM, curveProblem, FRAME_COST_FROM, FRAME_COST_RECORD, FRAME_COSTS_BASE_PATH, atRestStatus, frameCostStatus, generateFrameCosts, cReserved0, cpuPriceProblems, cpuPriceStatus, glueReserved0, machineDescriptors, parseCpuPricePending, portGlue, readCpuPricePending } from './module-cpu-price.mjs' +import { AT_REST_FROM, AT_REST_LIMIT, CPU_PRICE_PENDING_REASON, RELEASE_COST_FROM, curveProblem, FRAME_COST_FROM, FRAME_COST_RECORD, FRAME_COSTS_BASE_PATH, atRestStatus, frameCostStatus, generateFrameCosts, cReserved0, cpuPriceProblems, cpuPriceStatus, glueReserved0, machineDescriptors, parseCpuPricePending, portGlue, readCpuPricePending, readingsNote } from './module-cpu-price.mjs' const repo = fileURLToPath(new URL('../', import.meta.url)) const roots = [] @@ -67,6 +67,17 @@ describe('every Octatrack module names its CPU price', () => { expect(missing).toMatchObject({ state: 'fail', detail: expect.stringContaining('holds no device:price reading of other') }) }) + it('says how far a record of several readings a state agreed, and nothing for a record of one', () => { + const spread = (frame, dsp1to4Peak) => ({ spread: { frame, frameMax: 3, dsp1to4: 0.4, dsp1to4Peak, dsp5to8Peak: 9 } }) + const record = { module: 'echo', readings: 3, result: { atRestAdds: { frame: 0.2 }, inUseAdds: { frame: 1.3 }, inUseOn: 'T2 FX2', before: spread(0.3, 2.1), atRest: spread(0.6, 1.2), inUse: spread(0.4, 4.4) } } + expect(readingsNote(record)).toBe('; 3 readings a state, the frame interrupt within 0.6 points, the T1-4 DSP peak within 4.4') + expect(readingsNote({ ...record, result: { ...record.result, inUseOn: 'T6 FX1' } })).toMatch(/T5-8 DSP peak within 9$/) + expect(readingsNote({ module: 'echo', seconds: 8, result: { atRestAdds: { frame: 0 } } })).toBe('') + const root = fixture({ 'sdk/octatrack/modules/echo/evidence/cpu-price.json': record }) + expect(cpuPriceStatus({ root, document: module('echo', 'FX2', { ...share(1.3), source: 'evidence/cpu-price.json' }), pending: new Map(), glue: {} })) + .toMatchObject({ state: 'ok', detail: expect.stringContaining('3 readings a state, the frame interrupt within 0.6 points') }) + }) + it('takes a machine whose descriptor carries the price it names, literal or #define', () => { expect(cpuPriceStatus({ root: fixture(machineFolder('\n .reserved = {7},')), document: module('wave', 'Track machine', render(7)), pending: new Map(), glue: {} })).toMatchObject({ state: 'ok' }) expect(cpuPriceStatus({ root: fixture(machineFolder('\n .reserved = { WAVE_PRICE },')), document: module('wave', 'Track machine', render(9)), pending: new Map(), glue: {} })).toMatchObject({ state: 'ok' }) diff --git a/scripts/module-doctor.mjs b/scripts/module-doctor.mjs index 7320848f1e..ac62c43068 100644 --- a/scripts/module-doctor.mjs +++ b/scripts/module-doctor.mjs @@ -17,9 +17,9 @@ import { fileURLToPath } from 'node:url' import { availableModules, PAUSED_MODULE_IDS, isBetaModule } from '../src/catalog/availability.ts' import { MODULE_V3_CATEGORIES } from '../src/catalog/module-contract-v3.ts' import { parseModuleDocument } from '../src/catalog/module-contract.ts' -import { moduleSourceFingerprint } from './module-source.mjs' +import { isDocumentationPath, moduleSourceFingerprint } from './module-source.mjs' import { ANALOG_BD_DSP_COMPANIONS } from '../src/engine/analog-bd-layout.ts' -import { moduleNativeSourceSha256, modulePerformanceSourceSha256 } from './module-qualification.mjs' +import { crlfModuleFiles, moduleEarlierPerformanceSourceSha256, moduleNativeSourceSha256, modulePerformanceSourceSha256 } from './module-qualification.mjs' import { judgeRecord, ownerWaivedPerformanceRow, priceLimits, approvalCoversSource, stampVerdict } from './perf-audit-analysis.mjs' import { LINK_DEVICES } from '../src/engine/elektron/elemod.ts' import { stageDraft } from './draft-stage.mjs' @@ -30,6 +30,7 @@ import { mirrorOctatrackModules } from './mirror-octatrack-modules.mjs' import { BASES, PACKAGES, formatRetestQueue, packageHistory, retestQueue } from './retest-queue.mjs' import { RELEASE_COST_FROM, atRestStatus, cpuPriceStatus, frameCostStatus, readCpuPricePending, releaseDate } from './module-cpu-price.mjs' import { moduleTestFiles, runModuleTests } from './module-tests.mjs' +import { qualifyProblems } from './module-qualify.mjs' // Modules first listed on or after this day carry a measured performance record (docs/MODULE_PERFORMANCE.md); earlier ones keep their qualification evidence. const PERFORMANCE_REQUIRED_FROM = '2026-10-07' @@ -80,7 +81,7 @@ const nativeParams = compatResult?.nativeParams // The modules listed before every module had to name its CPU price, which wait for a measurement. const cpuPending = readCpuPricePending(root) // The qualification source hash is async; compute it once per module before the checks run. -const nativeHashes = new Map(), performanceHashes = new Map() +const nativeHashes = new Map(), performanceHashes = new Map(), earlierPerformanceHashes = new Map(), crlfFiles = new Map(), qualifyChecks = new Map() // The USB package file's Git history, read once and only when a hardware record and the shipped package differ. let packageRows = null const retest = documents => retestQueue({ documents, packages: json(PACKAGES).packages, history: (packageRows ??= packageHistory(root)), bases: json(BASES).bases }) @@ -157,7 +158,7 @@ function octatrack(id) { } if (!lines.some(line => line.name === 'performance')) ok('performance', rows.filter(item => item.name !== 'record' && !ownerWaivedPerformanceRow(record, item, hardwareApproval, nativeHashes.get(id))).map(item => item.name + ' ' + item.state).join(', ') + ' (npm run perf:audit)') // Were these numbers taken on this code? The stamp names the source they were measured on. - const stamped = stampVerdict(record, performanceHashes.get(id), draft || !entry || (entry.addedAt ?? '').slice(0, 10) >= PERFORMANCE_STAMP_REQUIRED_FROM, (draft ? 'sdk/drafts/' + id : folder) + '/evidence/performance.json') + const stamped = stampVerdict(record, performanceHashes.get(id), draft || !entry || (entry.addedAt ?? '').slice(0, 10) >= PERFORMANCE_STAMP_REQUIRED_FROM, (draft ? 'sdk/drafts/' + id : folder) + '/evidence/performance.json', earlierPerformanceHashes.get(id)) if (stamped.state === 'fail' && !record.sourceSha256 && approvalCoversSource(hardwareApproval, id, document.version, nativeHashes.get(id))) info('performance stamp', 'not stamped: the owner\'s approval binds this exact source, record included (' + approvalPath + ')') else if (stamped.state === 'fail') fail('performance stamp', stamped.detail, stamped.fix) @@ -170,6 +171,13 @@ function octatrack(id) { if (exists(folder + '/presentation/thumbnail.svg') || new RegExp("^\\s+'?" + id + "'?: \\(\\) =>", 'm').test(art)) ok('thumbnail', 'the library card has art') else fail('thumbnail', 'no presentation/thumbnail.svg and no hand-drawn art', 'add a 320x192 presentation/thumbnail.svg that shows what the module does') + // Git stores text with LF (.gitattributes). The evidence hashes read files as Git stores them; the compiled-package fingerprint, here + // and in the compiler, reads them as they are, so a CRLF file the compiler reads is a different package fingerprint here than in CI. + const crlf = crlfFiles.get(id) ?? [], compiled = moduleCardless(id) ? [] : crlf.filter(path => !isDocumentationPath('modules/' + id + '/' + path)) + const crlfFix = "sed -i 's/\\r$//' " + crlf.slice(0, 3).map(path => (draft ? 'sdk/drafts/' + id : folder) + '/' + path).join(' ') + (crlf.length > 3 ? ' … (' + crlf.length + ' files)' : '') + if (compiled.length) fail('line endings', compiled.slice(0, 3).join(', ') + (compiled.length > 3 ? ' and ' + (compiled.length - 3) + ' more' : '') + ' ha' + (compiled.length === 1 ? 's' : 've') + ' CRLF line endings here, Git stores LF, so the package fingerprint here differs from CI\'s', crlfFix) + else if (crlf.length) info('line endings', crlf.slice(0, 3).join(', ') + (crlf.length > 3 ? ' and ' + (crlf.length - 3) + ' more' : '') + ': CRLF here, LF in Git; the evidence hashes read them as Git stores them. To match: ' + crlfFix) + // A page descriptor written by hand is where a short list ends up as a knob: the widget word (desc+0x132) beside the count (desc+0xd2). const sources = readdirSync(resolve(root, folder), { recursive: true, encoding: 'utf8' }).filter(name => /\.(c|h|py)$/.test(name)).map(name => [name, readFileSync(resolve(root, folder, name), 'utf8')]) const byHand = sources.filter(([, text]) => !text.includes('modwerk_page.h') && /0x132\b/i.test(text) && /0xd2\b/i.test(text)).map(([name]) => name) @@ -212,6 +220,11 @@ function octatrack(id) { else if (curve.state === 'ok') ok('frame cost', curve.detail) else info('frame cost', curve.detail + (curve.fix ? '. Fix: ' + curve.fix : '')) + // The release record against the source it was tested on, and drafted words nobody has read yet (npm run module:qualify). + const qualified = qualifyChecks.get(id) ?? [] + if (qualified.length) fail('qualification', qualified.map(problem => problem.detail).join('; '), qualified[0].fix) + else if (document.tests.qualification) ok('qualification', 'bound to this source, nothing left drafted (npm run module:qualify -- ' + id + ' --check)') + if (rulesProblem) fail('module rules', 'npm run modules:check fails: ' + rulesProblem.slice(0, 220), 'fix what it names, then run npm run modules:check -- --base origin/main') else ok('module rules', 'versions, documentation, tutorial, screenshots, qualification, resource gauges (npm run modules:check)') @@ -340,6 +353,9 @@ for (const id of octatrackIds) { const document = parseModuleDocument(json('sdk/octatrack/modules/' + id + '/octamod.module.json')) nativeHashes.set(id, await moduleNativeSourceSha256(resolve(root, 'sdk/octatrack/modules', id), document)) performanceHashes.set(id, await modulePerformanceSourceSha256(resolve(root, 'sdk/octatrack/modules', id), document)) + earlierPerformanceHashes.set(id, await moduleEarlierPerformanceSourceSha256(resolve(root, 'sdk/octatrack/modules', id), document)) + crlfFiles.set(id, await crlfModuleFiles(resolve(root, 'sdk/octatrack/modules', id))) + qualifyChecks.set(id, await qualifyProblems({ root, folder: resolve(root, 'sdk/octatrack/modules', id), document, nativeSha: nativeHashes.get(id), evidence: false })) } // The fingerprint of the compiled packages must match the code too: documentation edits never change it. const fingerprintOk = !octatrackIds.length || (await moduleSourceFingerprint(root)) === json('src/engine/assets/module-build.json').sourceTreeSha256 diff --git a/scripts/module-doctor.test.mjs b/scripts/module-doctor.test.mjs index 26477eb44e..90470a9278 100644 --- a/scripts/module-doctor.test.mjs +++ b/scripts/module-doctor.test.mjs @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { spawnSync } from 'node:child_process' -import { existsSync, mkdtempSync, readdirSync, rmSync } from 'node:fs' +import { execFileSync, spawnSync } from 'node:child_process' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' import { homedir, tmpdir } from 'node:os' import { delimiter, join } from 'node:path' import { fileURLToPath } from 'node:url' @@ -70,6 +70,44 @@ describe('module doctor', () => { } rmSync(out, { recursive: true, force: true }) }, 2 * moduleCheckTimeout + 2 * 120_000) + // A port starts from upstream's files at the commit checked out, a reference model, its host test and gates on the shared harness + // (sdk/octatrack/tools/dsp_gate.py). As written it must pass the experimental lines; its own host test fails until it is ported. + it.skipIf(process.env.MODWERK_DEFER_DRAFT_DOCTOR === '1')('checks a draft where every gate looks: a module:new port of an Airwindows plugin', () => { + const clone = mkdtempSync(join(tmpdir(), 'modwerk-airwindows.')), plugin = join(clone, 'plugins/LinuxVST/src/Fakeity') + const git = (...args) => execFileSync('git', ['-C', clone, '-c', 'user.name=t', '-c', 'user.email=t@example.invalid', ...args], { encoding: 'utf8' }) + mkdirSync(plugin, { recursive: true }) + writeFileSync(join(clone, 'LICENSE'), 'MIT License\n\nCopyright (c) 2018 Example Author\n') + writeFileSync(join(plugin, 'FakeityProc.cpp'), 'void processReplacing() {}\n') + git('init', '-q'); git('add', '-A'); git('commit', '-qm', 'one') + const revision = git('rev-parse', 'HEAD').trim() + writeFileSync(join(plugin, 'FakeityProc.cpp'), 'an edit not committed\n') + const id = 'zz-port-' + process.pid, draft = join(root, 'sdk/drafts', id) + const scaffold = (...args) => spawnSync(process.execPath, ['scripts/scaffold-module.mjs', ...args, '--author', 'example-author'], { cwd: root, encoding: 'utf8', env: { ...process.env, MODWERK_BOARD: 'off' } }) + try { + expect(scaffold(id, '--kind', 'coldfire', '--port', 'airwindows', '--upstream', plugin).stderr).toContain('--kind dsp --port airwindows') + expect(scaffold(id, '--kind', 'dsp', '--port', 'airwindows', '--upstream', clone).stderr).toContain('name the plugin\'s folder') + expect(existsSync(draft)).toBe(false) + const made = scaffold(id, '--kind', 'dsp', '--port', 'airwindows', '--upstream', plugin) + expect(made.status, made.stderr).toBe(0) + // Upstream's bytes at HEAD, not the working tree, each recorded for sdk/imports/. + expect(readFileSync(join(draft, 'upstream/FakeityProc.cpp'), 'utf8')).toBe('void processReplacing() {}\n') + const record = JSON.parse(readFileSync(join(draft, 'import-record.json'), 'utf8')) + expect(record.revision).toBe(revision) + expect(record.files.map(file => file.path)).toEqual(['upstream/FakeityProc.cpp', 'upstream/LICENSE']) + expect(readFileSync(join(draft, 'LICENSE'), 'utf8')).toContain('Example Author') + const manifest = JSON.parse(readFileSync(join(draft, 'octamod.module.json'), 'utf8')) + expect(manifest.source).toEqual({ repository: 'https://github.com/airwindows/airwindows', revision, path: 'plugins/LinuxVST/src/Fakeity' }) + for (const file of ['reference.py', 'test_reference.py', 'verify.py', 'perf.py', 'engine.asm']) expect(existsSync(join(draft, file)), file).toBe(true) + expect(readFileSync(join(draft, 'verify.py'), 'utf8')).toContain('import dsp_gate as G') + const host = spawnSync('python3', ['-B', join(draft, 'test_reference.py')], { encoding: 'utf8' }) + expect(host.status).not.toBe(0) + expect(host.stderr).toContain('set PORTED = True') + const result = doctor('--draft', id) + expect(result.stdout).toContain('The experimental lines are green') + expect(result.status, result.stdout).toBe(0) + } finally { rmSync(draft, { recursive: true, force: true }); rmSync(clone, { recursive: true, force: true }) } + expect(existsSync(join(root, 'sdk/octatrack/modules', id))).toBe(false) + }, moduleCheckTimeout + 30_000) // Two tiers: a draft is judged on what trying and sharing it needs; what listing it needs reads as still to do until --release. it.skipIf(process.env.MODWERK_DEFER_DRAFT_DOCTOR === '1')('judges a draft as experimental, and as a release with --release', () => { const draft = readdirSync(join(root, 'sdk/drafts')).find(name => existsSync(join(root, 'sdk/drafts', name, 'octamod.module.json')) && !existsSync(join(root, 'sdk/octatrack/modules', name))) diff --git a/scripts/module-list.mjs b/scripts/module-list.mjs new file mode 100755 index 0000000000..512cbdbf4f --- /dev/null +++ b/scripts/module-list.mjs @@ -0,0 +1,386 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// List an Octatrack DSP effect: the mechanical steps of moving a draft from sdk/drafts// into the library, in one command. +// +// npm run module:list -- [ ...] moves each draft to sdk/octatrack/modules// and its CHANGELOG.json to +// src/community/module-changelogs/.json, deletes the scaffold's examples, and +// writes the catalogue entry, the build order, the descriptor guard, the package row +// and, for a port with upstream/ files, the import record and the licence entry; +// then npm run licenses:generate and modules:generate +// --dry-run prints what it would change and changes nothing +// --cycles N --cycles-kind executed|modeled|hardware --state N [--slots fx1|fx2|both] [--buffer N] +// the DSP figures the unit tests used (module:dev's options). Default: the last +// `npm run module:dev -- ... --cycles` command in the module's TESTING.md +// --added-at 2026-11-25T08:23:53Z the catalogue entry's addedAt (default: now, UTC) +// --upstream-dir DIR a clone of the port's upstream repository: the import record's source hashes are +// read there at the recorded revision instead of from the vendored copies +// --source-path upstream/FILE=PATH where an upstream/ file sits in that repository (default: the manifest's +// source.path/FILE, and a licence file at the repository root) +// +// Every check runs before anything is written, and the doctor's experimental lines must be green (module:doctor -- --draft). +// Running it again changes nothing. The steps that need Docker, the stock OS or the unit stay by hand; it prints them at the end +// (docs/ADD_A_MODULE.md, Octatrack). The descriptor guard's hashes are never made up: they are the ones the effects already listed +// recorded for the same stock donor and the same kind of FX2 slot, and a donor or slot without one is refused. +import { createHash } from 'node:crypto' +import { spawnSync } from 'node:child_process' +import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs' +import { basename, dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { parseArgs } from 'node:util' + +const ID = /^[a-z0-9]+(-[a-z0-9]+)*$/ +const CYCLE_KINDS = ['executed', 'modeled', 'hardware'], SLOTS = ['fx1', 'fx2', 'both'] +const SCAFFOLD_EXAMPLES = ['qualification.example.json', 'resource-impact.example.json'] +// The ColdFire's FX2 id table (sdk/octabam/tools/remix/rig.py): an id's slot is the word at FX2_IDS + 4 * id. The build guards the +// donor descriptor from donor_desc + 0x38 (scripts/build-module-packages.py checks both against the manifest). +const FX2_IDS = 0x400d5fdc, DONOR_GUARD = 0x38 +const BUILD = 'scripts/build-module-packages.py', CATALOG = 'sdk/catalog.json', RECIPES = 'src/engine/assets/descriptor-recipes.json' +const PACKAGES = 'src/engine/assets/octatrack-module-packages.json', LICENCES = 'sdk/octabam/licenses/manifest.json' +const SCHEMA = 'sdk/octabam/tools/remix/schema.py', STOCK = 'sdk/octabam/tools/remix/stock.py' +const GUARD_ANCHOR = ' for old in descriptor_guards:\n' +const LICENCE_FILE = /^(licen[cs]e|copying|notice)([.-].*)?$/i + +export class Refusal extends Error {} +const refuse = message => { throw new Refusal(message) } +const hex = (value, width) => '0x' + value.toString(16).padStart(width, '0') +const sha256 = bytes => createHash('sha256').update(bytes).digest('hex') +/** What `git hash-object` prints for these bytes. */ +export const gitBlob = bytes => createHash('sha1').update(Buffer.concat([Buffer.from('blob ' + bytes.length + '\0'), bytes])).digest('hex') +const json = value => JSON.stringify(value, null, 2) + '\n' +const python = text => "'" + text.replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'" + +/** The checkout as this run will leave it: reads see the planned writes, and nothing touches the disk until flush(). */ +function tree(root) { + const files = new Map(), moves = [], at = path => resolve(root, path) + const read = path => { + if (files.has(path)) { if (files.get(path) === null) throw new Error(path + ' is deleted by this run'); return files.get(path) } + return readFileSync(at(path)) + } + return { + exists: path => files.has(path) ? files.get(path) !== null : existsSync(at(path)), + read, text: path => read(path).toString('utf8'), + list(folder) { + const out = [], walk = path => { + for (const entry of readdirSync(at(path), { withFileTypes: true })) { + if (entry.isDirectory()) walk(path + '/' + entry.name) + else out.push(path + '/' + entry.name) + } + } + if (existsSync(at(folder))) walk(folder) + return out.sort() + }, + write: (path, data) => files.set(path, Buffer.from(data)), + remove: path => files.set(path, null), + move: (from, to) => moves.push([from, to]), + flush() { + for (const [from, to] of moves) { mkdirSync(dirname(at(to)), { recursive: true }); renameSync(at(from), at(to)) } + for (const [path, data] of files) { + if (data === null) rmSync(at(path), { force: true }) + else { mkdirSync(dirname(at(path)), { recursive: true }); writeFileSync(at(path), data) } + } + }, + } +} + +/** The literal fields module:list needs from a manifest.py, comments and docstrings left out. */ +export function manifestFacts(source) { + const code = source.replace(/"""[\s\S]*?"""|'''[\s\S]*?'''/g, '').replace(/(^|\s)#.*$/gm, '$1') + const field = (name, pattern) => code.match(new RegExp('\\b' + name + '\\s*=\\s*' + pattern))?.[1] + const number = name => { const value = field(name, '(0x[0-9a-fA-F]+|\\d+)\\b'); return value === undefined ? undefined : Number(value) } + return { kind: field('kind', 'Kind\\.(\\w+)'), key: field('key', '"([^"]*)"'), author: field('author', '"([^"]*)"'), + fxId: number('fx2_id'), donor: number('donor_desc'), replaces: field('replaces', '"([^"]*)"') } +} + +/** Every descriptor guard already recorded: the generated recipes and the dicts the build script appends. */ +function recordedGuards(t) { + const rows = JSON.parse(t.text(RECIPES)).recipes.map(({ id, fxId, donorAddress, donorSha256, fx2Slot, slotSha256 }) => ({ id, fxId, donorAddress, donorSha256, fx2Slot, slotSha256 })) + const number = '(0x[0-9a-fA-F]+|\\d+)', hash = "'([0-9a-f]{64})'" + const dict = new RegExp(`dict\\(id='([^']+)'[^)]*?fxId=${number},\\s*donorAddress=${number},\\s*donorSha256=${hash},\\s*fx2Slot=${number},\\s*slotSha256=${hash}`, 'g') + for (const m of t.text(BUILD).matchAll(dict)) rows.push({ id: m[1], fxId: Number(m[2]), donorAddress: Number(m[3]), donorSha256: m[4], fx2Slot: Number(m[5]), slotSha256: m[6] }) + return rows +} + +function stockFacts(t) { + const ids = t.text(SCHEMA).match(/STOCK_FX2_IDS\s*=\s*frozenset\(\{([^}]*)\}\)/) + if (!ids) refuse(`${SCHEMA} no longer has STOCK_FX2_IDS; module:list cannot tell stock FX2 ids from free ones.`) + const names = new Map() + if (t.exists(STOCK)) for (const m of t.text(STOCK).matchAll(/_stock\("([^"]+)",\s*"[^"]*",\s*(0x[0-9a-fA-F]+),\s*(0x[0-9a-fA-F]+)/g)) names.set(Number(m[3]), m[1]) + return { ids: new Set(ids[1].split(',').map(item => item.trim()).filter(Boolean).map(Number)), names } +} + +/** The guard's addresses from the manifest, and its hashes from guards already verified on the same donor and kind of slot. */ +export function deriveGuard(t, id, facts) { + if (facts.fxId === undefined || facts.donor === undefined) refuse(`${id}: manifest.py's MenuEntry gives no fx2_id or donor_desc as a number; module:list reads both from it.`) + const stock = stockFacts(t), rows = recordedGuards(t).filter(row => row.id !== id) + const fxId = facts.fxId, donorAddress = facts.donor + DONOR_GUARD, fx2Slot = FX2_IDS + 4 * fxId + const free = Array.from({ length: 0x1c }, (_, i) => i + 4).filter(i => !stock.ids.has(i) && !rows.some(row => row.fxId === i)).map(i => hex(i, 2)) + if (fxId < 0x04 || fxId > 0x1f) refuse(`${id}: FX2 id ${hex(fxId, 2)} is outside 0x04-0x1f.`) + const taken = rows.find(row => row.fxId === fxId) + if (taken) refuse(`${id}: FX2 id ${hex(fxId, 2)} is already ${taken.id}'s. Pick a free one in manifest.py (${free.join(', ') || 'none is left'}).`) + const replacing = stock.ids.has(fxId) + if (replacing && !facts.replaces) refuse(`${id}: FX2 id ${hex(fxId, 2)} belongs to a stock effect. Pick a free one (${free.join(', ') || 'none is left'}) or declare MenuEntry(replaces=...).`) + const one = (values, what) => { + const found = [...new Set(values)] + if (found.length > 1) refuse(`${id}: the recorded guards disagree on ${what} (${found.join(', ')}); settle that before listing anything on it.`) + return found[0] + } + const donorName = address => stock.names.get(address - DONOR_GUARD) + const donors = [...new Set(rows.map(row => row.donorAddress))].map(address => `${donorName(address) ?? 'the descriptor'} ${hex(address - DONOR_GUARD, 8)}`) + const donorSha256 = one(rows.filter(row => row.donorAddress === donorAddress).map(row => row.donorSha256), 'the donor at ' + hex(donorAddress, 8)) + if (!donorSha256) refuse(`${id}: no listed effect clones the donor descriptor at ${hex(facts.donor, 8)}, so its guard (${hex(donorAddress, 8)}) has no verified hash. Clone a donor one does (${donors.join(', ')}), or hash it on your own OS 1.40C and add the guard to ${BUILD} by hand.`) + const slotSha256 = replacing + ? one(rows.filter(row => row.fx2Slot === fx2Slot).map(row => row.slotSha256), 'the FX2 slot at ' + hex(fx2Slot, 8)) + : one(rows.filter(row => !stock.ids.has(row.fxId)).map(row => row.slotSha256), 'the stock NONE slot of unused ids') + if (!slotSha256) refuse(replacing + ? `${id}: no listed module replaces ${facts.replaces} yet, so its FX2 slot (${hex(fx2Slot, 8)}) has no verified hash. Hash it on your own OS 1.40C and add the guard to ${BUILD} by hand.` + : `${id}: no listed effect sits on an unused FX2 id, so the stock NONE slot has no verified hash. Hash it on your own OS 1.40C and add the guard to ${BUILD} by hand.`) + const slot = replacing ? `${facts.replaces}'s stock FX2 slot at id ${hex(fxId, 2)}` : `stock NONE at unused FX2 id ${hex(fxId, 2)}` + return { fxId, donorAddress, donorSha256, fx2Slot, slotSha256, donor: donorName(donorAddress) ?? 'stock descriptor ' + hex(facts.donor, 8), slot } +} + +export function guardBlock(id, facts, guard) { + return [ + ` if not any(row['id'] == ${python(id)} for row in descriptor_guards):`, + ` # The ${guard.donor} donor and ${guard.slot}, with the hashes the effects above recorded for`, + ` # them (npm run module:list); the build checks both against the private OS 1.40C. Never retain stock bytes.`, + ` descriptor_guards.append(dict(id=${python(id)}, key=${python(facts.key)}, author=${python(facts.author)},`, + ` fxId=${hex(guard.fxId, 2)}, donorAddress=${hex(guard.donorAddress, 8)},`, + ` donorSha256='${guard.donorSha256}',`, + ` fx2Slot=${hex(guard.fx2Slot, 8)},`, + ` slotSha256='${guard.slotSha256}'))`, + ].join('\n') + '\n' +} + +const ORDER_LINE = /^ORDER = \[([^\]\n]*)\]$/m +function buildOrder(t) { + const m = t.text(BUILD).match(ORDER_LINE) + if (!m) refuse(`${BUILD} has no one-line ORDER = [...]; add the id by hand.`) + return [...m[1].matchAll(/'([^']+)'/g)].map(item => item[1]) +} + +/** The DSP figures the unit tests used: the options, else the last module:dev command with --cycles in TESTING.md. */ +export function dspFigures(testing, id, given = {}) { + let from = null, found = {} + const text = testing.replace(/\s+/g, ' '), start = `npm run module:dev -- ${id} ` + for (let at = text.indexOf(start); at >= 0; at = text.indexOf(start, at + 1)) { + const tokens = text.slice(at + start.length).split(/[`)]/)[0].trim().split(' '), options = {} + for (let i = 0; i < tokens.length && tokens[i].startsWith('--'); i++) { + const name = tokens[i].slice(2) + if (['cycles', 'cycles-kind', 'state', 'slots', 'buffer'].includes(name) && tokens[i + 1] !== undefined && !tokens[i + 1].startsWith('--')) options[name] = tokens[++i].replace(/[.,;:]+$/, '') + } + if (options.cycles !== undefined) { found = options; from = (start + tokens.join(' ')).trim() } + } + const pick = name => given[name] ?? found[name] + const figures = { slots: pick('slots') ?? 'both', cycles: pick('cycles'), cyclesKind: pick('cycles-kind'), state: pick('state'), buffer: pick('buffer') ?? '0' } + const missing = [['cycles', 'cycles'], ['cycles-kind', 'cyclesKind'], ['state', 'state']].filter(([, key]) => figures[key] === undefined).map(([name]) => '--' + name) + if (missing.length) refuse(`${id}: give ${missing.join(', ')} as the unit tests used them (npm run module:dev -- ${id} --cycles N --cycles-kind KIND --state N), or record that command in TESTING.md.`) + const integer = (name, value, least) => { if (!/^\d+$/.test(String(value)) || Number(value) < least) refuse(`${id}: --${name} must be a whole number of at least ${least}, not ${value}.`); return Number(value) } + if (!CYCLE_KINDS.includes(figures.cyclesKind)) refuse(`${id}: --cycles-kind must be ${CYCLE_KINDS.join(', ')}, not ${figures.cyclesKind}.`) + if (!SLOTS.includes(figures.slots)) refuse(`${id}: --slots must be ${SLOTS.join(', ')}, not ${figures.slots}.`) + return { slots: figures.slots, cycles: integer('cycles', figures.cycles, 1), cyclesKind: figures.cyclesKind, state: integer('state', figures.state, 1), buffer: integer('buffer', figures.buffer, 0), from } +} + +const ownerRepo = url => { const m = /github(?:usercontent)?\.com\/([^/]+)\/([^/#?]+)/i.exec(url ?? ''); return m ? (m[1] + '/' + m[2].replace(/\.git$/, '')).toLowerCase() : null } + +function upstreamBytes(dir, revision, path) { + const result = spawnSync('git', ['-C', dir, 'cat-file', 'blob', revision + ':' + path], { maxBuffer: 1 << 28 }) + if (result.status !== 0) refuse(`${path} is not in ${dir} at ${revision}: ${String(result.stderr).trim()}`) + return result.stdout +} + +/** Plan one module: every change it needs, refused before anything is written. */ +function plan(t, id, settings) { + const draft = `sdk/drafts/${id}`, listed = `sdk/octatrack/modules/${id}` + const entry = JSON.parse(t.text(CATALOG)).modules.find(item => item.id === id) + const hasDraft = t.exists(draft), hasListed = t.exists(listed) + if (hasDraft && (hasListed || entry)) refuse(`${id} is listed already (${entry ? CATALOG : listed}). Its next version is an update, not a listing: docs/MODULE_AUTHOR_UPDATES.md.`) + if (!hasDraft && !(hasListed && entry)) refuse(`No draft named ${id} under sdk/drafts${hasListed ? ` (${listed} exists, but ${CATALOG} does not list it: move it back to ${draft} and run this again)` : ''}. Start one with npm run module:new.`) + const folder = hasDraft ? draft : listed, changes = [], notes = [] + if (!t.exists(folder + '/manifest.py') || !t.exists(folder + '/octamod.module.json')) refuse(`${id} is not an Octatrack DSP module: ${folder} needs manifest.py and octamod.module.json.`) + const facts = manifestFacts(t.text(folder + '/manifest.py')), doc = JSON.parse(t.text(folder + '/octamod.module.json')) + if (facts.kind !== 'DSP_EFFECT') refuse(`${id} is a ${facts.kind ?? 'unknown'} module (manifest.py kind=Kind.${facts.kind ?? '?'}); module:list lists DSP effects only. List it by hand: docs/ADD_A_MODULE.md, Octatrack, step 4.`) + if (doc.id !== id) refuse(`${folder}/octamod.module.json names ${doc.id}, not ${id}.`) + if (doc.key !== facts.key || doc.author?.github !== facts.author) refuse(`${id}: octamod.module.json's key and author (${doc.key}, ${doc.author?.github}) differ from manifest.py's (${facts.key}, ${facts.author}); the build refuses that.`) + const version = doc.version + + // 1. The folder, the release notes and the scaffold's examples. + const notesFile = `src/community/module-changelogs/${id}.json` + if (hasDraft) { + changes.push(`move ${draft}/ to ${listed}/`); t.move(draft, listed) + for (const name of SCAFFOLD_EXAMPLES) if (t.exists(`${draft}/${name}`)) { changes.push(`delete the scaffold's ${name}`); t.remove(`${listed}/${name}`) } + } else for (const name of SCAFFOLD_EXAMPLES) if (t.exists(`${listed}/${name}`)) changes.push(`delete the scaffold's ${name}`) + const draftNotes = `${folder}/CHANGELOG.json` + if (t.exists(draftNotes)) { + const bytes = t.read(draftNotes) + if (t.exists(notesFile) && !t.read(notesFile).equals(bytes)) refuse(`${id}: both ${draftNotes} and ${notesFile} exist and differ; keep one.`) + changes.push(`move ${draftNotes} to ${notesFile}`) + if (hasDraft) { t.write(notesFile, bytes); t.remove(`${listed}/CHANGELOG.json`) } + } + if (hasDraft) { + let releases = null + try { releases = JSON.parse(t.text(t.exists(draftNotes) ? draftNotes : notesFile)) } catch { /* refused below */ } + if (!Array.isArray(releases) || !releases.some(item => item?.version === version)) refuse(`${id}: no release notes for ${version}. Write them in ${draftNotes} first (docs/ADD_A_MODULE.md, Release notes).`) + } else if (!t.exists(notesFile)) changes.push(`release notes ${notesFile}`) + + // 2. The catalogue entry, after the last DSP effect. + const order = buildOrder(t) + if (!entry) { + const catalog = JSON.parse(t.text(CATALOG)) + const after = catalog.modules.findLastIndex(item => order.includes(item.id)) + catalog.modules.splice(after < 0 ? catalog.modules.length : after + 1, 0, { id, version, addedAt: settings.addedAt }) + changes.push(`${CATALOG}: ${id} ${version}, added ${settings.addedAt}`); t.write(CATALOG, json(catalog)) + } + + // 3. The build order and the descriptor guard. + if (!order.includes(id)) { + changes.push(`${BUILD}: ${id} at the end of ORDER`) + t.write(BUILD, t.text(BUILD).replace(ORDER_LINE, `ORDER = [${[...order, id].map(item => `'${item}'`).join(', ')}]`)) + } + if (!t.text(BUILD).includes(`if not any(row['id'] == ${python(id)} for row in descriptor_guards):`) && !recordedGuards(t).some(row => row.id === id)) { + const guard = deriveGuard(t, id, facts), source = t.text(BUILD) + if (!source.includes(GUARD_ANCHOR)) refuse(`${BUILD} changed shape (no "${GUARD_ANCHOR.trim()}"); add ${id}'s descriptor guard by hand.`) + t.write(BUILD, source.replace(GUARD_ANCHOR, guardBlock(id, facts, guard) + GUARD_ANCHOR)) + changes.push(`${BUILD}: descriptor guard fxId ${hex(guard.fxId, 2)}, donor ${hex(guard.donorAddress, 8)} (${guard.donor}), FX2 slot ${hex(guard.fx2Slot, 8)}`) + } + + // 4. The package row, after the last DSP effect's; octatrack:module-packages completes it. + const packages = JSON.parse(t.text(PACKAGES)) + if (!packages.packages.some(row => row.id === id)) { + const figures = dspFigures(t.exists(folder + '/TESTING.md') ? t.text(folder + '/TESTING.md') : '', id, settings.figures) + const { from, ...dsp } = figures + const row = { id, slots: dsp.slots, cycles: dsp.cycles, cyclesKind: dsp.cyclesKind, state: dsp.state, buffer: dsp.buffer, version, path: `octatrack-modules/${id}/${version}.mwrm` } + const after = packages.packages.findLastIndex(item => order.includes(item.id)) + packages.packages.splice(after < 0 ? packages.packages.length : after + 1, 0, row) + t.write(PACKAGES, json(packages)) + changes.push(`${PACKAGES}: ${dsp.slots}, ${dsp.cycles} ${dsp.cyclesKind} cycles, ${dsp.state} state words, buffer ${dsp.buffer}` + (from ? ` (from TESTING.md: ${from})` : '')) + } + + // 5. A port: the import record of its upstream/ files and its licence entry. + const upstream = t.list(folder + '/upstream') + let licences = false + if (upstream.length) { + const source = doc.source ?? {}, repository = source.repository, revision = source.revision + if (!repository || !/^[0-9a-f]{40}$/.test(revision ?? '')) refuse(`${id} has upstream/ files, so its octamod.module.json needs source.repository and the full 40-character source.revision.`) + const recordPath = `sdk/imports/${id}-${revision.slice(0, 7)}.json` + if (!hasListed || !t.exists(recordPath)) { + const paths = upstream.map(path => path.slice(folder.length + 1)) + const unknown = Object.keys(settings.sourcePaths).filter(path => !paths.includes(path)) + if (unknown.length) refuse(`${id}: --source-path names ${unknown.join(', ')}, which ${folder} does not have.`) + const licence = path => LICENCE_FILE.test(basename(path)) && path.split('/').length === 2 + const files = [...paths.filter(path => !licence(path)), ...paths.filter(licence)].map(path => { + const vendored = t.read(folder + '/' + path), rest = path.slice('upstream/'.length) + const sourcePath = settings.sourcePaths[path] ?? (licence(path) ? rest : source.path ? `${source.path}/${rest}` : refuse(`${id}: the manifest's source block has no path; give --source-path ${path}=PATH.`)) + const original = settings.upstreamDir ? upstreamBytes(settings.upstreamDir, revision, sourcePath) : vendored + return { path, sourcePath, sourceBytes: original.length, sourceGitBlob: gitBlob(original), sourceSha256: sha256(original), vendoredSha256: sha256(vendored) } + }) + const record = json({ schemaVersion: 1, repository, revision, moduleVersion: version, root: `sdk/octabam/modules/${id}`, modules: [id], files }) + if (t.exists(recordPath) && t.text(recordPath) !== record) refuse(`${id}: ${recordPath} exists and differs from what module:list would write; remove it or finish it by hand.`) + if (!t.exists(recordPath)) { + t.write(recordPath, record) + changes.push(`${recordPath}: ${files.map(file => `${file.path} from ${file.sourcePath}`).join(', ')}`) + const edited = files.filter(file => file.sourceSha256 !== file.vendoredSha256).map(file => file.path) + notes.push(settings.upstreamDir + ? `The source hashes were read in ${settings.upstreamDir} at ${revision.slice(0, 7)}${edited.length ? `; ${edited.join(', ')} differ from upstream` : ''}.` + : `The import record takes the upstream/ files as unchanged copies of ${repository} at ${revision.slice(0, 7)}; give --upstream-dir with a clone of it to hash upstream's own files.`) + } + } + const manifest = JSON.parse(t.text(LICENCES)), repo = ownerRepo(repository) + const components = manifest.components.filter(component => (component.sources ?? []).some(item => ownerRepo(item.url) === repo)) + const usedIn = `modules/${id}: ${doc.name}` + if (components.length !== 1) notes.push(components.length + ? `${LICENCES}: ${components.map(c => c.id).join(' and ')} all name ${repository}; add ${id} to the right one's usedIn and to moduleComponents by hand, then npm run licenses:generate.` + : `${LICENCES} has no component for ${repository}: add one (its notice file in sdk/octabam/licenses/, sources, usedIn "${usedIn}") and moduleComponents.${id}, then npm run licenses:generate.`) + else { + const component = components[0] + if (!component.usedIn.some(line => line === usedIn || line.startsWith(`modules/${id}:`) || line === `modules/${id}`)) { component.usedIn.push(usedIn); licences = true } + if (!(manifest.moduleComponents[id] ?? []).includes(component.id)) { + const entries = Object.entries(manifest.moduleComponents).filter(([key]) => key !== id) + const after = entries.findLastIndex(([, ids]) => ids.includes(component.id)) + entries.splice(after < 0 ? entries.length : after + 1, 0, [id, [...(manifest.moduleComponents[id] ?? []), component.id]]) + manifest.moduleComponents = Object.fromEntries(entries); licences = true + } + if (licences) { + t.write(LICENCES, json(manifest)) + changes.push(`${LICENCES}: ${id} under ${component.id} ("${usedIn}")`) + notes.push(`The licence component's name reads "${component.name}"; rename it if it should name ${doc.name} too, then npm run licenses:generate.`) + } + } + } + return { id, name: doc.name, draft: hasDraft, changes, notes, licences } +} + +function runDoctor(root, id) { + const result = spawnSync(process.execPath, ['scripts/module-doctor.mjs', '--draft', id], { cwd: root, encoding: 'utf8', maxBuffer: 1 << 26 }) + return { ok: result.status === 0, output: (result.stdout ?? '') + (result.stderr ?? '') } +} +function runScript(root, script) { + return spawnSync(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['run', '-s', script], { cwd: root, stdio: 'inherit' }).status ?? 1 +} + +const NEXT_STEPS = ids => [ + 'Still by hand (docs/ADD_A_MODULE.md, Octatrack, steps 4-8):', + '1. Commit, then compile the packages from the clean checkout (the output folder must not exist yet) and commit what the import changes:', + ' image=$(docker image inspect modwerk-source-tools --format \'{{.Id}}\')', + ' bash scripts/build-modules-isolated.sh . ../module-packages "$image"', + ' npm run modules:import -- ../module-packages/packages --development', + '2. npm run octatrack:module-packages: builds the USB package and completes the package row (abi, module, bytes, sha256).', + '3. Re-pin Tape Echo\'s and Euclid\'s standalone recipes to the new asset files; npm run check fails until they are.', + '4. The qualification record (tests.qualification, docs/MODULE_QUALIFICATION.md) and the unit evidence, then npm run modules:generate.', + '5. A port whose author has no GitHub login here: the display author in DISPLAY_AUTHORS, src/catalog/module-authors.ts.', + `6. ${ids.map(id => `npm run module:doctor -- ${id}`).join(', ')}, then npm run pr:ready.`, +] + +/** List the drafts `ids`. Refuses (Refusal) before writing anything; returns the plans. */ +export async function listModules(root, ids, options = {}) { + const { dryRun = false, figures = {}, upstreamDir = null, sourcePaths = {}, log = console.log, doctor = runDoctor, run = runScript } = options + const addedAt = options.addedAt ?? new Date().toISOString().replace(/\.\d+Z$/, 'Z') + if (!ids.length || ids.some(id => !ID.test(id))) refuse('Usage: npm run module:list -- [ ...] [--dry-run] [--cycles N --cycles-kind executed|modeled|hardware --state N] [--slots fx1|fx2|both] [--buffer N] [--added-at ISO] [--upstream-dir DIR] [--source-path upstream/FILE=PATH]') + if (new Set(ids).size !== ids.length) refuse('Name each module once.') + const single = [...Object.values(figures).filter(value => value !== undefined), upstreamDir, ...Object.keys(sourcePaths)].some(Boolean) + if (single && ids.length > 1) refuse('--cycles, --cycles-kind, --state, --slots, --buffer, --upstream-dir and --source-path describe one module: list one id at a time with them.') + if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(addedAt)) refuse(`--added-at must be a UTC time like 2026-11-25T08:23:53Z, not ${addedAt}.`) + const t = tree(root), plans = ids.map(id => plan(t, id, { addedAt, figures, upstreamDir, sourcePaths })) + for (const p of plans) if (!p.draft && p.changes.length) refuse(`${p.id} is listed already, and module:list lists drafts only. Not done for it: ${p.changes.join('; ')}.`) + const drafts = plans.filter(p => p.draft) + if (!drafts.length) { log(`${ids.join(', ')}: listed already; nothing to change.`); return plans } + for (const p of drafts) { + const result = doctor(root, p.id) + if (!result.ok) refuse(`${p.id}: npm run module:doctor -- --draft ${p.id} has red experimental lines; fix them first.\n${result.output.trim().split('\n').slice(-40).join('\n')}`) + } + for (const p of plans) { + log(p.draft ? `${p.name} (${p.id})${dryRun ? ', would change' : ''}:` : `${p.id}: listed already; nothing to change.`) + for (const line of p.changes) log(' ' + line) + for (const line of p.notes) log(' Note: ' + line) + } + const generators = [...(plans.some(p => p.licences) ? ['licenses:generate'] : []), 'modules:generate'] + if (dryRun) log(`\nDry run: nothing changed. A real run then runs npm run ${generators.join(' and npm run ')}.`) + else { + t.flush() + for (const script of generators) if (run(root, script) !== 0) refuse(`npm run ${script} failed (above). The listing is written; fix what it names and run npm run ${script} again.`) + } + log('\n' + NEXT_STEPS(drafts.map(p => p.id)).join('\n')) + return plans +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const root = resolve(dirname(fileURLToPath(import.meta.url)), '..') + let parsed + try { + parsed = parseArgs({ allowPositionals: true, options: { + 'dry-run': { type: 'boolean', default: false }, cycles: { type: 'string' }, 'cycles-kind': { type: 'string' }, state: { type: 'string' }, + slots: { type: 'string' }, buffer: { type: 'string' }, 'added-at': { type: 'string' }, 'upstream-dir': { type: 'string' }, + 'source-path': { type: 'string', multiple: true, default: [] }, + } }) + } catch (error) { console.error(error.message); process.exit(2) } + const { values, positionals } = parsed + const sourcePaths = Object.fromEntries(values['source-path'].map(item => { const at = item.indexOf('='); return at > 0 ? [item.slice(0, at), item.slice(at + 1)] : [item, ''] })) + try { + if (Object.values(sourcePaths).some(value => !value)) refuse('--source-path takes upstream/FILE=PATH.') + await listModules(root, positionals, { + dryRun: values['dry-run'], addedAt: values['added-at'], upstreamDir: values['upstream-dir'] ? resolve(values['upstream-dir']) : null, sourcePaths, + figures: { cycles: values.cycles, 'cycles-kind': values['cycles-kind'], state: values.state, slots: values.slots, buffer: values.buffer }, + }) + } catch (error) { + if (!(error instanceof Refusal)) throw error + console.error(error.message); process.exitCode = 1 + } +} diff --git a/scripts/module-list.test.mjs b/scripts/module-list.test.mjs new file mode 100755 index 0000000000..3591695c6b --- /dev/null +++ b/scripts/module-list.test.mjs @@ -0,0 +1,216 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { createHash } from 'node:crypto' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { Refusal, dspFigures, gitBlob, listModules } from './module-list.mjs' + +// A minimal checkout: two listed DSP effects (one on the DARK REV donor, one on SPRING REV), a stock-id replacement in the +// recipes, a ColdFire module, and the draft "desk", a port with upstream/ files, shaped as Mackity was on 25 November 2026. +const A = 'a'.repeat(64), B = 'b'.repeat(64), C = 'c'.repeat(64), E = 'e'.repeat(64), F = 'f'.repeat(64) +const REV = 'e718c9bcfcdd736deeddb08bffe6bce2aa8e0eea' +const BUILD = `ORDER = ['dark', 'tape'] +REQUESTED = ['cf-thing'] + +def main(): + descriptor_guards = list(baseline['descriptor-recipes.json']['recipes']) + if not any(row['id'] == 'tape' for row in descriptor_guards): + descriptor_guards.append(dict(id='tape', key='TAPE ECHO', author='someone', + fxId=0x0f, donorAddress=0x400d575e, + donorSha256='${B}', + fx2Slot=0x400d6018, + slotSha256='${F}')) + for old in descriptor_guards: + module = byid[old['id']] +` +const MANIFEST = kind => `"""DESK -- a desk input stage. + +An old note said fx2_id=0x04 and donor_desc=0x400d0000; neither counts. +""" +from remix.schema import Kind, MenuEntry, Module + +MODULE = Module( + name="desk", + key="DESK", + kind=Kind.${kind}, + category=Category.TRACK, author="someone", author_url="https://github.com/someone", + menu=MenuEntry( + fx2_id=0x1a, # a free non-stock id; fx2_id=0x05 in a comment does not count + donor_desc=0x400d58b8, # DARK REV + abbr=b"DESK", + fullname=b"Desk", + ), +) +` +const TESTING = 'Built with `npm run module:dev -- desk --build-only --cycles 600` first, then from this\nfolder with `npm run module:dev -- desk --build-only --cycles 226\n--cycles-kind executed --state 32` (208 DSP words).\n' +const NOTES = '[\n {\n "version": "0.1.0-experimental",\n "date": "2026-11-25",\n "changes": ["First release."]\n }\n]\n' +const CPP = 'int desk(int x) { return x; }\n', LICENSE = 'hello\n' + +let root +const write = (path, text) => { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), text) } +const read = path => readFileSync(join(root, path), 'utf8') +const json = path => JSON.parse(read(path)) +const out = value => JSON.stringify(value, null, 2) + '\n' +function snapshot() { + const files = {} + const walk = folder => { + for (const entry of readdirSync(join(root, folder), { withFileTypes: true })) { + const path = folder ? folder + '/' + entry.name : entry.name + if (entry.isDirectory()) walk(path) + else files[path] = readFileSync(join(root, path), 'base64') + } + } + walk('') + return files +} +function draft({ kind = 'DSP_EFFECT', manifest = MANIFEST(kind), testing = TESTING, id = 'desk' } = {}) { + write(`sdk/drafts/${id}/manifest.py`, manifest) + write(`sdk/drafts/${id}/octamod.module.json`, out({ id, key: 'DESK', name: 'Desk', version: '0.1.0-experimental', author: { github: 'someone' }, + source: { repository: 'https://github.com/airwindows/airwindows', revision: REV, path: 'plugins/LinuxVST/src/Desk' } })) + write(`sdk/drafts/${id}/CHANGELOG.json`, NOTES) + write(`sdk/drafts/${id}/TESTING.md`, testing) + write(`sdk/drafts/${id}/desk.asm`, '; code\n') + write(`sdk/drafts/${id}/upstream/Desk.cpp`, CPP) + write(`sdk/drafts/${id}/upstream/LICENSE`, LICENSE) + for (const name of ['qualification.example.json', 'resource-impact.example.json']) write(`sdk/drafts/${id}/${name}`, '{}\n') +} +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'modwerk-module-list-')) + write('sdk/catalog.json', out({ schemaVersion: 1, modules: [ + { id: 'dark', version: '0.2.0', addedAt: '2026-10-01T00:00:00Z' }, { id: 'tape', version: '0.1.0', addedAt: '2026-10-02T00:00:00Z' }, + { id: 'cf-thing', version: '0.1.0', addedAt: '2026-10-03T00:00:00Z' }] })) + write('scripts/build-module-packages.py', BUILD) + write('src/engine/assets/descriptor-recipes.json', out({ schema: 1, recipes: [ + { id: 'dark', key: 'DARK', fxId: 0x17, donorAddress: 0x400d58f0, donorSha256: A, fx2Slot: 0x400d6038, slotSha256: F }, + { id: 'comp', key: 'COMP', fxId: 0x18, donorAddress: 0x400d5a82, donorSha256: C, fx2Slot: 0x400d603c, slotSha256: E }] })) + write('sdk/octabam/tools/remix/schema.py', 'STOCK_FX2_IDS = frozenset({0x04, 0x05, 0x08, 0x0c, 0x0d, 0x10, 0x11, 0x12,\n 0x13, 0x14, 0x15, 0x16, 0x18, 0x19, 0x1c})\n') + write('sdk/octabam/tools/remix/stock.py', ' _stock("SPRING REV", "spring", 0x15, 0x400d5726, b"SPRG", b"SPRING REV",\n _stock("DARK REV", "dark", 0x16, 0x400d58b8, b"DARK", b"DARK REV", 1067,\n') + write('src/engine/assets/octatrack-module-packages.json', out({ packages: [ + { id: 'dark', slots: 'fx2', cycles: 300, cyclesKind: 'executed', state: 64, buffer: 100, version: '0.2.0', path: 'octatrack-modules/dark/0.2.0.mwrm' }, + { id: 'cf-thing', octabam: true, version: '0.1.0', path: 'octatrack-modules/cf-thing/0.1.0.mwrm' }], usbAudio: {} })) + write('sdk/octabam/licenses/manifest.json', out({ schemaVersion: 1, components: [{ id: 'airwindows', name: 'Airwindows Chorus', spdx: 'MIT', noticeFile: 'airwindows.txt', + sources: [{ url: `https://raw.githubusercontent.com/airwindows/airwindows/${REV}/LICENSE`, revision: REV, path: 'LICENSE' }], usedIn: ['modules/chorus: Chorus'] }], + moduleComponents: { chorus: ['airwindows'], other: ['elsewhere'] } })) + write('src/community/module-changelogs/dark.json', '[]\n') + draft() +}) +afterEach(() => rmSync(root, { recursive: true, force: true })) + +function list(ids = ['desk'], options = {}) { + const lines = [], ran = [], doctored = [] + const promise = listModules(root, ids, { addedAt: '2026-11-25T08:23:53Z', log: line => lines.push(line), run: (_, script) => { ran.push(script); return 0 }, + doctor: (_, id) => { doctored.push(id); return { ok: true, output: '' } }, ...options }) + return { promise, lines, ran, doctored } +} + +describe('module:list', () => { + it('does the listing steps Mackity took by hand', async () => { + const { promise, ran, doctored } = list() + await promise + expect(doctored).toEqual(['desk']) + // The folder, its release notes and the scaffold's examples. + expect(existsSync(join(root, 'sdk/drafts/desk'))).toBe(false) + expect(read('sdk/octatrack/modules/desk/desk.asm')).toBe('; code\n') + for (const name of ['qualification.example.json', 'resource-impact.example.json', 'CHANGELOG.json']) expect(existsSync(join(root, 'sdk/octatrack/modules/desk', name))).toBe(false) + expect(read('src/community/module-changelogs/desk.json')).toBe(NOTES) + // The catalogue entry after the last DSP effect. + expect(json('sdk/catalog.json').modules.map(item => item.id)).toEqual(['dark', 'tape', 'desk', 'cf-thing']) + expect(json('sdk/catalog.json').modules[2]).toEqual({ id: 'desk', version: '0.1.0-experimental', addedAt: '2026-11-25T08:23:53Z' }) + // ORDER and the guard: DARK REV's descriptor + 0x38, the FX2 table + 4 * 0x1a, and the hashes recorded for both. + const build = read('scripts/build-module-packages.py') + expect(build.split('\n')[0]).toBe("ORDER = ['dark', 'tape', 'desk']") + expect(build).toContain(` if not any(row['id'] == 'desk' for row in descriptor_guards): + # The DARK REV donor and stock NONE at unused FX2 id 0x1a, with the hashes the effects above recorded for + # them (npm run module:list); the build checks both against the private OS 1.40C. Never retain stock bytes. + descriptor_guards.append(dict(id='desk', key='DESK', author='someone', + fxId=0x1a, donorAddress=0x400d58f0, + donorSha256='${A}', + fx2Slot=0x400d6044, + slotSha256='${F}')) + for old in descriptor_guards: +`) + // The package row after the last DSP effect's, with the figures of the last module:dev command in TESTING.md. + const packages = json('src/engine/assets/octatrack-module-packages.json').packages + expect(packages.map(row => row.id)).toEqual(['dark', 'desk', 'cf-thing']) + expect(packages[1]).toEqual({ id: 'desk', slots: 'both', cycles: 226, cyclesKind: 'executed', state: 32, buffer: 0, version: '0.1.0-experimental', path: 'octatrack-modules/desk/0.1.0-experimental.mwrm' }) + // The import record: licence last, at the repository root; git's blob id of "hello\n" is ce013625. + const digest = text => createHash('sha256').update(text).digest('hex') + expect(json(`sdk/imports/desk-${REV.slice(0, 7)}.json`)).toEqual({ schemaVersion: 1, repository: 'https://github.com/airwindows/airwindows', revision: REV, + moduleVersion: '0.1.0-experimental', root: 'sdk/octabam/modules/desk', modules: ['desk'], files: [ + { path: 'upstream/Desk.cpp', sourcePath: 'plugins/LinuxVST/src/Desk/Desk.cpp', sourceBytes: CPP.length, sourceGitBlob: gitBlob(Buffer.from(CPP)), sourceSha256: digest(CPP), vendoredSha256: digest(CPP) }, + { path: 'upstream/LICENSE', sourcePath: 'LICENSE', sourceBytes: 6, sourceGitBlob: 'ce013625030ba8dba906f756967f9e9ca394464a', sourceSha256: digest(LICENSE), vendoredSha256: digest(LICENSE) }] }) + // The licence entry under the component that names the same repository. + const licences = json('sdk/octabam/licenses/manifest.json') + expect(licences.components[0].usedIn).toEqual(['modules/chorus: Chorus', 'modules/desk: Desk']) + expect(Object.entries(licences.moduleComponents)).toEqual([['chorus', ['airwindows']], ['desk', ['airwindows']], ['other', ['elsewhere']]]) + expect(ran).toEqual(['licenses:generate', 'modules:generate']) + }) + + it('changes nothing when run again', async () => { + await list().promise + const before = snapshot(), again = list() + await again.promise + expect(snapshot()).toEqual(before) + expect(again.lines[0]).toBe('desk: listed already; nothing to change.') + expect(again.ran).toEqual([]) + expect(again.doctored).toEqual([]) + }) + + it('prints what it would change on a dry run and changes nothing', async () => { + const before = snapshot(), run = list(['desk'], { dryRun: true }) + await run.promise + expect(snapshot()).toEqual(before) + expect(run.ran).toEqual([]) + const text = run.lines.join('\n') + expect(text).toContain('Desk (desk), would change:') + expect(text).toContain('move sdk/drafts/desk/ to sdk/octatrack/modules/desk/') + expect(text).toContain('sdk/catalog.json: desk 0.1.0-experimental, added 2026-11-25T08:23:53Z') + expect(text).toContain('descriptor guard fxId 0x1a, donor 0x400d58f0 (DARK REV), FX2 slot 0x400d6044') + expect(text).toContain('226 executed cycles, 32 state words, buffer 0 (from TESTING.md: npm run module:dev -- desk --build-only --cycles 226 --cycles-kind executed --state 32)') + expect(text).toContain('Dry run: nothing changed.') + expect(text).toContain('npm run octatrack:module-packages') + }) + + it('takes the DSP figures from the options over TESTING.md', async () => { + await list(['desk'], { figures: { cycles: '250', 'cycles-kind': 'hardware', state: '40', slots: 'fx2', buffer: '2048' } }).promise + const row = json('src/engine/assets/octatrack-module-packages.json').packages.find(item => item.id === 'desk') + expect(row).toMatchObject({ slots: 'fx2', cycles: 250, cyclesKind: 'hardware', state: 40, buffer: 2048 }) + }) + + it('reads the last module:dev command that gives --cycles', () => { + expect(dspFigures(TESTING, 'desk')).toMatchObject({ cycles: 226, cyclesKind: 'executed', state: 32, slots: 'both', buffer: 0 }) + expect(() => dspFigures('Not measured.', 'desk')).toThrow(/give --cycles, --cycles-kind, --state/) + }) + + const refused = async (pattern, options, ids) => { + const before = snapshot() + await expect(list(ids, options).promise).rejects.toThrow(pattern) + await expect(list(ids, options).promise).rejects.toBeInstanceOf(Refusal) + expect(snapshot()).toEqual(before) + } + it('refuses a ColdFire module', async () => { + rmSync(join(root, 'sdk/drafts/desk'), { recursive: true }); draft({ kind: 'CF_PATCH' }) + await refused(/CF_PATCH module .*lists DSP effects only/) + }) + it('refuses a missing draft', () => refused(/No draft named nope under sdk\/drafts/, {}, ['nope'])) + it('refuses a draft of a listed id', async () => { + draft({ id: 'dark', manifest: MANIFEST('DSP_EFFECT').replace('name="desk"', 'name="dark"') }) + await refused(/dark is listed already \(sdk\/catalog.json\)/, {}, ['dark']) + }) + it('refuses a draft whose experimental doctor lines are red', () => + refused(/has red experimental lines[\s\S]*✗ ui claims/, { doctor: () => ({ ok: false, output: ' ✗ ui claims none declared\n' }) })) + it('refuses a donor without a verified hash', async () => { + rmSync(join(root, 'sdk/drafts/desk'), { recursive: true }); draft({ manifest: MANIFEST('DSP_EFFECT').replace('donor_desc=0x400d58b8', 'donor_desc=0x400d5000') }) + await refused(/donor descriptor at 0x400d5000, so its guard \(0x400d5038\) has no verified hash. Clone a donor one does \(DARK REV 0x400d58b8, the descriptor 0x400d5a4a, SPRING REV 0x400d5726\)/) + }) + it('refuses an FX2 id another module holds or a stock one', async () => { + rmSync(join(root, 'sdk/drafts/desk'), { recursive: true }); draft({ manifest: MANIFEST('DSP_EFFECT').replace('fx2_id=0x1a,', 'fx2_id=0x17,') }) + await refused(/FX2 id 0x17 is already dark's/) + rmSync(join(root, 'sdk/drafts/desk'), { recursive: true }); draft({ manifest: MANIFEST('DSP_EFFECT').replace('fx2_id=0x1a,', 'fx2_id=0x15,') }) + await refused(/FX2 id 0x15 belongs to a stock effect/) + }) + it('refuses DSP figures it cannot find', async () => { + rmSync(join(root, 'sdk/drafts/desk'), { recursive: true }); draft({ testing: 'Not measured.\n' }) + await refused(/desk: give --cycles, --cycles-kind, --state/) + }) +}) diff --git a/scripts/module-qualification.d.mts b/scripts/module-qualification.d.mts index 7386f389c5..c97fda9cca 100644 --- a/scripts/module-qualification.d.mts +++ b/scripts/module-qualification.d.mts @@ -4,5 +4,9 @@ export const BASELINE_PATH: string export function moduleFolderSha256(folder: string): Promise export function qualificationReports(document: ModuleDocument): string[] export function moduleNativeSourceSha256(folder: string, document: ModuleDocument): Promise +export function modulePerformanceSourceSha256(folder: string, document: ModuleDocument): Promise +export function moduleEarlierPerformanceSourceSha256(folder: string, document: ModuleDocument): Promise +export function gitStoredBytes(bytes: Uint8Array): Uint8Array +export function crlfModuleFiles(folder: string): Promise export function parseQualificationBaseline(value: unknown): Map export function requireFolderQualification(folder: string, document: ModuleDocument, baseline: Map, waivers?: Map, options?: { root?: string; approvedRef?: string }): Promise<'retained-evidence' | 'retained' | 'qualified' | 'owner-waived'> diff --git a/scripts/module-qualification.mjs b/scripts/module-qualification.mjs index 5fb0932373..dd9391efcc 100644 --- a/scripts/module-qualification.mjs +++ b/scripts/module-qualification.mjs @@ -15,6 +15,29 @@ import { CPU_PRICE_RECORD, manifestWithoutPrice } from './module-cpu-price.mjs' export const BASELINE_PATH = 'sdk/approvals/module-qualification-baseline.json' export const WAIVERS_PATH = 'sdk/approvals/module-release-waivers.json' const sha = bytes => createHash('sha256').update(bytes).digest('hex') +/** The bytes Git stores for a file under this repository's `* text=auto eol=lf` (.gitattributes): a file Git takes for text keeps + * its CRLF line endings as LF, anything else is stored as it is. Every hash here reads these, so a working tree with CRLF (a file + * written on Windows) hashes as CI's LF checkout does (Mackity, #2148: a CRLF thumbnail.svg passed locally and failed in CI). + * Git's own test (convert.c: gather_stats, convert_is_binary): binary if the file has a NUL, a CR not followed by LF, or more + * than one non-printable byte in 128 printable ones. A file committed with CRLF before the attribute stays CRLF in Git; no + * module file is (25 November 2026). */ +export function gitStoredBytes(bytes) { + let crlf=0, lonecr=0, nul=0, printable=0, nonprintable=0 + for(let i=0;i>7)path!==CPU_PRICE_RECORD)) { - const bytes=await readFile(resolve(folder,path)) + const bytes=gitStoredBytes(await readFile(resolve(folder,path))) hashes[path]=sha(path==='octamod.module.json'?manifestWithoutPrice(bytes.toString('utf8'))??bytes:bytes) } return sha(JSON.stringify(hashes)) @@ -56,8 +85,15 @@ export async function moduleNativeSourceSha256(folder, document) { return fingerprint(folder,await nativePaths(folder,document)) } // The source a performance record was measured on: the native source without evidence/, so the stamp written into -// evidence/performance.json (npm run perf:audit -- check FILE --stamp) does not change what it stamps. +// evidence/performance.json (npm run perf:audit -- check FILE --stamp) does not change what it stamps, and without +// presentation/ (the library card's art; media/ is never native source), which no compiler reads, as the compiled-package +// fingerprint leaves it out (module-source.mjs): new art needs no new numbers. export async function modulePerformanceSourceSha256(folder, document) { + return fingerprint(folder,(await nativePaths(folder,document)).filter(path=>!path.startsWith('evidence/')&&!path.startsWith('presentation/'))) +} +// What a stamp written before 25 November 2026 names: the same source with presentation/. A record stamped then still +// holds while that source is unchanged; the next --stamp writes the hash above. +export async function moduleEarlierPerformanceSourceSha256(folder, document) { return fingerprint(folder,(await nativePaths(folder,document)).filter(path=>!path.startsWith('evidence/'))) } // An owner-approved update publishes a new version without fresh evidence for diff --git a/scripts/module-qualification.test.mjs b/scripts/module-qualification.test.mjs index 4359f3e67c..7e1be462a5 100644 --- a/scripts/module-qualification.test.mjs +++ b/scripts/module-qualification.test.mjs @@ -1,13 +1,73 @@ import { afterEach, expect, it } from 'vitest' import { execFileSync } from 'node:child_process' -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' -import { evidenceOnBaseProblem, moduleFolderSha256, moduleNativeSourceSha256, modulePricelessFolderSha256, testingVersionProblem } from './module-qualification.mjs' +import { crlfModuleFiles, evidenceOnBaseProblem, gitStoredBytes, moduleEarlierPerformanceSourceSha256, moduleFolderSha256, moduleNativeSourceSha256, modulePerformanceSourceSha256, modulePricelessFolderSha256, testingVersionProblem } from './module-qualification.mjs' const roots = [] afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) }) +it('reads each file as Git stores it under the repository\'s .gitattributes', () => { + const root = mkdtempSync(join(tmpdir(), 'git-bytes-')); roots.push(root) + const git = (...args) => execFileSync('git', args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] }) + git('init', '-q') + writeFileSync(join(root, '.gitattributes'), readFileSync(new URL('../.gitattributes', import.meta.url))) + const files = { + 'crlf.svg': '\r\n \r\n\r\n', + 'mixed.c': 'int a;\r\nint b;\nint c;\r\n', + 'lf.py': 'x = 1\ny = 2\n', + 'lone-cr.txt': 'one\rtwo\r\n', + 'nul.bin': 'a\r\n\0b\r\n', + 'controls.bin': '\x01\x02\x03\r\nabc\r\n', + 'ctrl-z.txt': 'end\r\n\x1a', + 'utf8.md': 'Grüße — é\r\n', + } + for (const [name, text] of Object.entries(files)) writeFileSync(join(root, name), text) + git('add', '.') + for (const name of Object.keys(files)) { + const stored = git('cat-file', 'blob', ':' + name), here = readFileSync(join(root, name)) + expect(Buffer.from(gitStoredBytes(here)).equals(stored), name).toBe(true) + } + expect(gitStoredBytes(readFileSync(join(root, 'crlf.svg'))).includes(13)).toBe(false) +}) + +it('hashes a module with CRLF text as the LF checkout CI has, and names the CRLF files', async () => { + const folder = mkdtempSync(join(tmpdir(), 'crlf-')); roots.push(folder) + const document = { id: 'echo', version: '0.1.0-experimental', tests: {} } + writeFileSync(join(folder, 'octamod.module.json'), JSON.stringify(document, null, 2) + '\n') + writeFileSync(join(folder, 'native.c'), 'int echo;\nint gain;\n') + mkdirSync(join(folder, 'presentation')); writeFileSync(join(folder, 'presentation/thumbnail.svg'), '\n \n\n') + const hashes = async () => [await moduleFolderSha256(folder), await modulePricelessFolderSha256(folder), await moduleNativeSourceSha256(folder, document), await modulePerformanceSourceSha256(folder, document)] + const lf = await hashes() + expect(await crlfModuleFiles(folder)).toEqual([]) + // Mackity (#2148): the thumbnail written on Windows with CRLF, the source too. + writeFileSync(join(folder, 'presentation/thumbnail.svg'), '\r\n \r\n\r\n') + writeFileSync(join(folder, 'native.c'), 'int echo;\r\nint gain;\r\n') + expect(await hashes()).toEqual(lf) + expect(await crlfModuleFiles(folder)).toEqual(['native.c', 'presentation/thumbnail.svg']) + // A change Git would store is still a change. + writeFileSync(join(folder, 'native.c'), 'int echo;\r\nint gain = 1;\r\n') + expect((await hashes()).some((hash, i) => hash === lf[i])).toBe(false) +}) + +it('leaves the art out of the performance source, and keeps the earlier hash for older stamps', async () => { + const folder = mkdtempSync(join(tmpdir(), 'art-')); roots.push(folder) + const document = { id: 'echo', version: '0.1.0-experimental', tests: {} } + writeFileSync(join(folder, 'octamod.module.json'), JSON.stringify(document) + '\n') + writeFileSync(join(folder, 'native.c'), 'int echo;\n') + mkdirSync(join(folder, 'presentation')); writeFileSync(join(folder, 'presentation/thumbnail.svg'), '\n') + const performance = await modulePerformanceSourceSha256(folder, document), earlier = await moduleEarlierPerformanceSourceSha256(folder, document), native = await moduleNativeSourceSha256(folder, document) + expect(earlier).not.toBe(performance) + writeFileSync(join(folder, 'presentation/thumbnail.svg'), '\n') + expect(await modulePerformanceSourceSha256(folder, document)).toBe(performance) + // The earlier stamp and the qualification source still cover the art, as recorded hashes on main expect. + expect(await moduleEarlierPerformanceSourceSha256(folder, document)).not.toBe(earlier) + expect(await moduleNativeSourceSha256(folder, document)).not.toBe(native) + writeFileSync(join(folder, 'native.c'), 'int echo = 1;\n') + expect(await modulePerformanceSourceSha256(folder, document)).not.toBe(performance) +}) + it('refuses a new module whose tested commit is already on main, and judges no other commit', () => { const root = mkdtempSync(join(tmpdir(), 'evidence-')); roots.push(root) const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8' }).trim() diff --git a/scripts/module-qualify.mjs b/scripts/module-qualify.mjs new file mode 100644 index 0000000000..e3f015f561 --- /dev/null +++ b/scripts/module-qualify.mjs @@ -0,0 +1,410 @@ +#!/usr/bin/env node +// SPDX-License-Identifier: Elastic-2.0 +// Copyright (c) 2026 Jannik Aßfalg (repeat98) +// The release record of an Octatrack module, written from its evidence instead of by hand (docs/MODULE_QUALIFICATION.md). +// +// npm run module:qualify -- --procedure DIR [--package FILE.mwrm] [--base TEXT] [--write] +// Drafts tests.qualification and the measured resource gauges from what is already measured: the test procedure's record +// (DIR/procedure.json, its device:price readings DIR/price.json), the package it tested (DIR/procedure.json names it; or +// --package), evidence/performance.json (perf:audit), evidence/cpu-price.json and frame-cost.json, media/capture.json. +// price.json's reading becomes evidence/cpu-price.json, resources.cpuPrice and evidence/frame-cost.json, as device:price +// --write would have written them; --base names the base the unit ran, which the record needs (device:price --base). +// It prints what changes; --write writes it. sourceSha256 is computed last, over the folder as it will be written. +// npm run module:qualify -- --check # a stale sourceSha256, fields still marked as drafts, evidence for another version +// npm run module:qualify -- --rehash [--write] # only sourceSha256, after a change to files that are not code +// Options: --draft (sdk/drafts/ when both it and the listed folder exist), --image SHA (the tested image when it is +// not the procedure's package), --tester LOGIN, --model MKI|MKII. +// +// A listed module (sdk/octatrack/modules/) or a draft (sdk/drafts/). Numbers and identities come from the evidence and +// replace what the manifest says; words a person has to stand behind (rationales, conditions, the hardware summary and its +// limitations, the tutorial) are kept as written. Where the manifest has none, they are drafted from the data and start with +// DRAFT, which --check and module:doctor refuse until the author has read and edited them. A value with no source stays out, +// with a note saying what would supply it. Nothing here runs module code or touches a unit. +import { execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { basename, dirname, join, relative, resolve } from 'node:path' +import { parseArgs } from 'node:util' +import { parseModuleDocument, requireModuleQualificationForPublication } from '../src/catalog/module-contract.ts' +import { BASELINE_PATH, moduleNativeSourceSha256, parseQualificationBaseline } from './module-qualification.mjs' +import { CPU_PRICE_RECORD, FRAME_COST_RECORD, curveProblem, manifestJson } from './module-cpu-price.mjs' +import { curveRecord, moduleFolder, priceRecord } from './octatrack-price.mjs' +import { LIMITS } from './perf-audit-analysis.mjs' + +/** The mark a drafted text starts with until its author has read it. */ +export const DRAFT = '[module:qualify draft] ' +const PERFORMANCE_RECORD = 'evidence/performance.json', CAPTURE_RECORD = 'media/capture.json' +const GATES = ['Worst-case cycles under parameter modulation and maximum load', 'Exact memory region and maximum-instance totals', + 'Owner-reviewed real-hardware evidence with actual coverage and limitations'] +const UNIT_STEPS = ['unit-read', 'unit-pass', 'soak', 'cost-unit', 'restore'] +const json2 = value => JSON.stringify(value, null, 2) + '\n' +const readJson = path => existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : null +const short = sha => String(sha).slice(0, 8) + +/** What a runtime package's header says (sdk/runtime/loader/README.md): code and data bytes, and from ABI 5 its DSP effect. */ +export function packageFacts(data) { + if (data.length < 32 || data.toString('ascii', 0, 4) !== 'MWRM') throw new Error('not an Octatrack runtime package (no MWRM header)') + const abi = data.readUInt16BE(4), dsp = abi >= 5 && data.length >= 50 + return { abi, sha256: createHash('sha256').update(data).digest('hex'), imageBytes: data.readUInt32BE(8), bssBytes: data.readUInt32BE(12), + dspWords: dsp ? data.readUInt32BE(32) : 0, slots: dsp ? data[39] : 0, cycles: dsp ? data.readUInt16BE(44) : 0, cyclesKind: dsp ? data[46] : 0, + stateWords: dsp ? data[47] : 0, bufferWords: dsp ? data.readUInt16BE(48) : 0 } +} + +/** The tiers a measurement suggests (docs/MODULE_RESOURCE_GAUGES.md). Suggestions: the author keeps or changes the level. */ +export const suggestCpuLevel = price => price < 0.5 ? 'minimal' : price < 2 ? 'low' : price < 10 ? 'moderate' : 'high' +export const suggestDspLevel = share => share < 0.25 ? 'minimal' : share < 0.5 ? 'low' : share < 1 ? 'moderate' : 'high' +export const suggestMemoryLevel = bytes => bytes < 512 ? 'minimal' : bytes < 16384 ? 'low' : bytes < 65536 ? 'moderate' : 'high' + +/** The module's folder: the listed one, or the draft (`draft`: the draft even when both exist). */ +export function qualifyFolder(root, id, draft = false) { + if (draft) return existsSync(resolve(root, 'sdk/drafts', id, 'octamod.module.json')) ? resolve(root, 'sdk/drafts', id) : null + return moduleFolder(root, id) +} + +/** Everything the record is drafted from. `procedure`: a test:procedure --out folder; `packagePath`: the tested .mwrm. */ +export function readEvidence({ folder, procedure, packagePath }) { + const evidence = { performance: readJson(join(folder, PERFORMANCE_RECORD)), cpuPrice: readJson(join(folder, CPU_PRICE_RECORD)), + frameCost: readJson(join(folder, FRAME_COST_RECORD)), capture: readJson(join(folder, CAPTURE_RECORD)), procedure: null, price: null, package: null } + if (procedure) { + evidence.procedure = readJson(join(procedure, 'procedure.json')) + if (!evidence.procedure) throw new Error(join(procedure, 'procedure.json') + ' is missing: name the folder npm run test:procedure -- --out wrote') + evidence.price = readJson(join(procedure, 'price.json')) + } + const named = packagePath ?? evidence.procedure?.build?.package?.path + if (named && existsSync(named)) evidence.package = packageFacts(readFileSync(named)) + else if (packagePath) throw new Error('No package at ' + packagePath) + const tested = evidence.procedure?.build?.package?.sha256 + if (evidence.package && tested && evidence.package.sha256 !== tested) throw new Error('The package ' + short(evidence.package.sha256) + ' is not the one the procedure tested (' + short(tested) + ')') + return evidence +} + +/** Keep what a person wrote; draft it from the data only where nothing is written. */ +function wording(old, drafted, path, reads) { + if (typeof old === 'string' && old.trim()) return old + reads.push(path) + return DRAFT + drafted +} + +/** The drafted manifest and evidence files: { document, files: { path: text }, notes, reads, changedLevels }. Pure: reads only `evidence`. + * sourceSha256 is left as it was; sourceHashOf computes it over the result. */ +export function draftRecord({ document: original, evidence, options = {} }) { + const document = structuredClone(original), notes = [], reads = [], files = {}, id = document.id, version = document.version + const { performance: perfAny, procedure, price, capture } = evidence + const pkg = evidence.package + let { cpuPrice: priceRec, frameCost: curveRec } = evidence + + // 1. The procedure: this module, this version. + if (procedure && (procedure.target?.id !== id || procedure.target?.version !== version)) + throw new Error('The procedure tested ' + procedure.target?.id + ' ' + procedure.target?.version + ', not ' + id + ' ' + version) + + // 2. The price and the curve from the procedure's device:price run, as device:price --write writes them. + const result = price?.results?.find(item => item.id === id) + if (price && !result) notes.push('price.json holds no reading of ' + id + ': the CPU price and the curve stay as they are') + if (result) { + const base = options.base ?? price.base + if (priceRec?.measuredAt === price.measuredAt && priceRec?.version === version) notes.push(CPU_PRICE_RECORD + ' already holds this run (' + price.measuredAt + '): kept as it is') + else if (!base) notes.push('the CPU price and the curve in price.json are not written: name the base the unit ran with --base TEXT (as device:price --base takes it: "development twin 8fd6d456 of base 0.8.1, the owner\'s MKII, OS 1.40C")') + else { + const made = priceRecord({ document, result, base, scene: price.scene, seconds: price.seconds, measuredAt: price.measuredAt, readings: price.readings ?? 1, inputs: price.inputs }) + if (made.problem) notes.push('the CPU price is not written: ' + made.problem) + else { files[CPU_PRICE_RECORD] = json2(made.record); document.resources.cpuPrice = made.cpuPrice; priceRec = made.record } + if (result.curve && !result.curve.error) { + const curve = curveRecord({ result, version, base, scene: price.scene, seconds: price.seconds, measuredAt: price.measuredAt }) + if (curve.problem) notes.push('the curve is not written: ' + curve.problem) + else { + files[FRAME_COST_RECORD] = json2(curve.record); curveRec = curve.record + const problem = curveProblem(curve.record) + if (problem) notes.push('NOT RELEASABLE on this curve: ' + problem) + } + } + } + } + + // 3. The performance record, when it is this version's. + const perf = perfAny?.module === id && perfAny?.version === version ? perfAny : null + if (perfAny && !perf) notes.push(PERFORMANCE_RECORD + ' is for ' + perfAny.module + ' ' + perfAny.version + ': its numbers stay out until it is measured for ' + version) + if (!perfAny) notes.push('no ' + PERFORMANCE_RECORD + ': cycles and the DSP gauge stay as they are (npm run perf:audit -- template dsp|coldfire)') + if (!pkg) notes.push('no package: storage and memory are kept as written (name it with --package FILE.mwrm, or a procedure that built one)') + const dsp = perf?.kind === 'dsp' + const resources = document.resources + if (procedure?.date) resources.recorded = procedure.date + + // 4. The measured gauges: storage from the package, processing from the performance record. + if (pkg) { + const old = resources.storage?.method === 'unmeasured' ? {} : resources.storage ?? {} + const program = pkg.dspWords ? pkg.dspWords + ' program words on each DSP core it runs on; ' + pkg.stateWords + ' words of state per instance; ' + (pkg.bufferWords ? pkg.bufferWords + ' delay-buffer words' : 'no delay buffer') + '; ' : '' + resources.storage = { ...(pkg.dspWords ? { label: 'DSP program / state', display: pkg.dspWords + ' words / ' + pkg.stateWords + '-word state' } : { label: 'ColdFire code', display: (pkg.imageBytes + pkg.bssBytes) + ' bytes' }), + value: null, unit: 'see display', method: 'static', + conditions: wording(old.conditions, 'The USB package ' + short(pkg.sha256) + ': ' + program + pkg.imageBytes + ' bytes of ColdFire code and data, ' + (pkg.bssBytes ? pkg.bssBytes + ' bytes of bss' : 'no bss') + '.', 'resources.storage.conditions', reads), + source: old.source ?? 'TESTING.md' } + } + if (perf) { + const old = resources.processing?.method === 'unmeasured' ? {} : resources.processing ?? {}, c = perf.cycles ?? {} + const unit = resources.cpuPrice && priceRec?.result?.inUseAdds && priceRec.result.inUseOn ? ' On the unit the DSP load of ' + (/^T[1-4]/.test(priceRec.result.inUseOn) ? 'T1-T4' : 'T5-T8') + ' rose ' + (/^T[1-4]/.test(priceRec.result.inUseOn) ? priceRec.result.inUseAdds.dsp1to4 : priceRec.result.inUseAdds.dsp5to8) + ' points with it on ' + priceRec.result.inUseOn + '.' : '' + resources.processing = dsp + ? { label: 'DSP instruction peak', display: Math.round(c.measured) + ' instructions/sample per instance', value: null, unit: 'see display', method: 'emulator', + conditions: wording(old.conditions, 'perf:audit record: worst ' + c.measured + ' executed instructions a sample (static floor ' + c.static + '), against ' + perf.stock?.comparator + ' ' + perf.stock?.comparatorWorst + ' and ' + perf.stock?.dearestWorst + ' for the dearest stock effect. Executed instructions, not chip cycles.' + unit, 'resources.processing.conditions', reads), + source: old.source ?? PERFORMANCE_RECORD } + : { label: 'ColdFire worst event', display: c.measured + ' cycles/event', value: null, unit: 'see display', method: old.method && old.method !== 'unmeasured' ? old.method : 'emulator', + conditions: wording(old.conditions, 'perf:audit record: worst event ' + c.measured + ' cycles' + (c.static ? ' (static bound ' + c.static + ')' : '') + ' of a ' + c.budget + '-cycle deadline.' + unit, 'resources.processing.conditions', reads), + source: old.source ?? PERFORMANCE_RECORD } + } + + // 5. The qualification record: kept for this version's tested build, drafted where the evidence supplies it. + const oldQ = document.tests.qualification?.moduleVersion === version ? document.tests.qualification : null + const steps = procedure?.steps ?? [], unitSteps = steps.filter(step => UNIT_STEPS.includes(step.id)) + const failed = steps.filter(step => step.status === 'failed'), unitPassed = unitSteps.filter(step => step.status === 'passed') + const revision = procedure?.build?.revision + let q = oldQ ? structuredClone(oldQ) : null + if (procedure && failed.length) notes.push('the procedure failed at ' + failed.map(step => step.title).join(', ') + ': no hardware record is drafted from it') + else if (procedure && !unitPassed.length) notes.push('no unit step passed in the procedure (' + (unitSteps[0]?.reason ?? 'not run') + '): no hardware record is drafted from it') + else if (procedure && !/^[a-f0-9]{40}$/.test(revision ?? '')) notes.push('the procedure names no source commit (' + revision + '): no hardware record is drafted from it') + else if (procedure) { + if (procedure.build.dirty) notes.push('the procedure ran on a checkout with uncommitted changes, so ' + short(revision) + ' is not exactly the tested source: commit, rebuild and run it again before release') + const oldH = oldQ?.hardware, sameBuild = oldH?.sourceRevision === revision + const tested = procedure.build.package?.sha256 + const image = options.image ?? (sameBuild ? oldQ.imageSha256 : null) ?? tested + if (!image) notes.push('no tested image: the procedure names no package; give it with --image SHA') + const shot = capture && capture.packageSha256 === tested ? capture : null + q = { moduleVersion: version, sourceSha256: oldQ?.sourceSha256 ?? '0'.repeat(64), cycles: oldQ?.cycles, memory: oldQ?.memory, imageSha256: image, hardware: null, documentation: oldQ?.documentation ?? document.tests.documentation } + if (oldH && sameBuild && oldH.kind !== 'functional') q.hardware = oldH + else { + const model = options.model ?? (sameBuild ? oldH.model : undefined) ?? shot?.model ?? null + if (!model) notes.push('the model is not recorded (null): give it with --model MKI|MKII') + let tester = options.tester ?? (sameBuild ? oldH.tester : undefined) ?? shot?.capturedBy + if (!tester) { tester = document.author.github; reads.push('tests.qualification.hardware.tester (the author, ' + tester + '; --tester LOGIN when someone else ran it)') } + const passed = steps.filter(step => step.status === 'passed' && step.id !== 'build').map(step => step.title) + const notRun = steps.filter(step => step.status === 'not run').map(step => 'Not run: ' + step.title.toLowerCase() + (step.reason ? ' (' + step.reason + ')' : '') + '.') + const toDo = steps.filter(step => step.status === 'to do').flatMap(step => step.todo ?? []).map(item => 'Not done yet: ' + item + '.') + const summary = 'On ' + (model ? 'an Octatrack ' + model : 'an Octatrack (model not recorded)') + ', ' + procedure.date + ', npm run test:procedure ran on package ' + short(tested) + ' built from ' + short(revision) + + ': ' + passed.join(', ') + ' passed' + (curveRec?.version === version ? '; the CPU price ' + (resources.cpuPrice?.value ?? '?') + ' % of a frame, the instance curve first ' + curveRec.first + ', each ' + curveRec.each + ', admitted alone on the empty and the medium pattern' : '') + '.' + const limitations = sameBuild && oldH.limitations?.length ? oldH.limitations : [...notRun, ...toDo].slice(0, 16).map(item => DRAFT + item) + if (!(sameBuild && oldH.limitations?.length)) reads.push('tests.qualification.hardware.limitations') + q.hardware = { kind: 'functional', status: 'reported', model, testedOn: procedure.date, tester, sourceRevision: revision, imageSha256: image, + summary: wording(sameBuild ? oldH.summary : undefined, summary, 'tests.qualification.hardware.summary', reads), limitations, report: oldH?.report ?? 'TESTING.md' } + } + document.tests.evidenceRevision = revision + if (q.hardware.kind === 'functional') document.tests.hardwareStatus = 'reported' // a detailed record keeps its own status + document.tests.summary = wording(original.tests.hardwareStatus !== 'untested' && original.tests.qualification ? original.tests.summary : undefined, + 'npm run test:procedure on ' + (q.hardware.model ?? 'an Octatrack') + ' (' + procedure.date + '): ' + unitPassed.length + ' of ' + unitSteps.length + ' unit steps passed' + (perf ? '; perf:audit ' + (dsp ? 'worst ' + perf.cycles.measured + ' instructions a sample' : 'worst event ' + perf.cycles.measured + ' cycles') : '') + '.', 'tests.summary', reads) + if (!document.tests.gates?.length) document.tests.gates = GATES + } + if (q) { + // Cycles: one record a processor, from the perf:audit record when the manifest has none for this version. + if (!q.cycles && perf) { + const c = perf.cycles, s = perf.stress ?? {} + if (dsp && c.static > 0 && Number.isInteger(c.instancesPerCore)) { + const worst = Math.ceil(c.static), n = c.instancesPerCore + q.cycles = [{ processor: 'dsp', worstCase: worst, maxConfiguration: worst * n, maxInstances: Math.min(16, 2 * n), budget: LIMITS.usableCycles, unit: 'cycles/sample', method: 'static', + conditions: { + parameterExtremes: DRAFT + 'Static floor ' + c.static + ' a sample from the perf:audit record; measured ' + c.measured + ' at the dearest case. Add any per-call setup, initialization and trigger-split cost the floor leaves out. ' + String(c.method ?? '').slice(0, 3000), + parameterModulation: DRAFT + 'Stress run: ' + s.lfosPerTrack + ' LFOs a track, ' + s.lockedSlots + ' locked slots, ' + s.seconds + ' s, ' + s.clobbers + ' clobbers, ' + s.hangs + ' hangs. Say how LFOs, locks, scenes and CC reach the code.', + modeSwitching: DRAFT + 'Not in the evidence: say how mode, bypass and Part changes were covered, or why the module has none.', + maxLoad: DRAFT + n + ' instances a core, ' + Math.min(16, 2 * n) + ' on both: ' + n + ' x ' + worst + ' = ' + worst * n + ' of the ' + LIMITS.usableCycles + ' cycles a core can spend a sample. Stress: ' + s.instancesPerCore + ' a core on ' + s.tracks + ' tracks.', + inputConditions: DRAFT + 'Not in the evidence: say which inputs (silence, full scale, impulses, feedback) the bound and the stress run cover.' }, + report: PERFORMANCE_RECORD }] + reads.push('tests.qualification.cycles[0] (worstCase is the static floor: it must also cover setup and trigger splits; and its five conditions)') + } else if (!dsp && (c.static > 0 || c.measured > 0) && c.budget > 0) { + const worst = Math.ceil(c.static > 0 ? c.static : c.measured) + q.cycles = [{ processor: 'coldfire', worstCase: worst, maxConfiguration: worst, maxInstances: 1, budget: Math.round(c.budget), unit: 'cycles/event', method: c.static > 0 ? 'static' : 'emulator', + conditions: Object.fromEntries(['parameterExtremes', 'parameterModulation', 'modeSwitching', 'maxLoad', 'inputConditions'].map(key => [key, DRAFT + 'Not in the evidence: ' + key + ' (docs/MODULE_QUALIFICATION.md#worst-case-cycle-counts). ' + (key === 'parameterExtremes' ? String(c.method ?? '').slice(0, 3000) : '')])), + report: PERFORMANCE_RECORD }] + reads.push('tests.qualification.cycles[0] (its five conditions, and maxInstances)') + } else notes.push('the performance record gives no cycle bound to draft from: write tests.qualification.cycles by hand') + } else if (q.cycles && perf && dsp) { + const record = q.cycles.find(item => item.processor === 'dsp'), perSample = record && (record.unit === 'cycles/block' ? record.worstCase / 16 : record.worstCase) + if (record && record.unit !== 'cycles/event' && perSample < perf.cycles.static) reads.push('tests.qualification.cycles: worstCase ' + record.worstCase + ' ' + record.unit + ' is under the static floor ' + perf.cycles.static + ' a sample in ' + PERFORMANCE_RECORD) + } + // Memory: the package's own allocations when the manifest has none for this version; else checked against the package. + if (!q.memory && pkg) { + const regions = [], maxInstances = q.cycles?.[0]?.maxInstances ?? 1 + if (pkg.dspWords) regions.push({ name: 'DSP program, the package\'s effect on each core it runs on', space: 'dsp-p', words: pkg.dspWords, wordBits: 24, bytes: pkg.dspWords * 3, scope: 'shared' }) + if (pkg.stateWords) regions.push({ name: 'DSP state per instance, the package\'s state words', space: 'dsp-x', words: pkg.stateWords, wordBits: 24, bytes: pkg.stateWords * 3, scope: 'instance' }) + if (pkg.imageBytes) regions.push({ name: 'ColdFire code and data of the USB package', space: 'cpu-ram', words: pkg.imageBytes, wordBits: 8, bytes: pkg.imageBytes, scope: 'shared' }) + if (pkg.bssBytes) regions.push({ name: 'ColdFire bss of the USB package', space: 'cpu-ram', words: pkg.bssBytes, wordBits: 8, bytes: pkg.bssBytes, scope: 'shared' }) + if (pkg.bufferWords) notes.push('the package reads ' + pkg.bufferWords + ' delay-buffer words: add that region to tests.qualification.memory.regions with its space and scope') + const perInstanceBytes = regions.filter(r => r.scope === 'instance').reduce((sum, r) => sum + r.bytes, 0), sharedBytes = regions.filter(r => r.scope === 'shared').reduce((sum, r) => sum + r.bytes, 0) + if (regions.length) { + q.memory = { regions, perInstanceBytes, sharedBytes, maxInstances, totalBytes: perInstanceBytes * maxInstances + sharedBytes, + conditions: DRAFT + 'From the header of the USB package ' + short(pkg.sha256) + ' (ABI ' + pkg.abi + '). Add what the header cannot show: stock blocks the effect reuses, the stack, Y memory, scratch, and why none are left out.', report: 'TESTING.md' } + reads.push('tests.qualification.memory (the regions are the package header\'s; add what it cannot show)') + } + } else if (q.memory && pkg?.dspWords) { + const program = q.memory.regions.filter(r => r.space === 'dsp-p') + if (program.length && !program.some(r => r.words === pkg.dspWords)) reads.push('tests.qualification.memory: no dsp-p region holds the package\'s ' + pkg.dspWords + ' program words') + if (pkg.stateWords && !q.memory.regions.some(r => r.space === 'dsp-x' && r.scope === 'instance' && r.words >= pkg.stateWords)) reads.push('tests.qualification.memory: no per-instance dsp-x region covers the package\'s ' + pkg.stateWords + ' state words') + } + // Documentation: the tutorial is the author's; drafted from the access steps when there is none. + if (!q.documentation) { + const steps = (document.access?.steps?.length >= 3 ? document.access.steps : document.presentation?.usage ?? []).slice(0, 12) + if (steps.length >= 3) { + q.documentation = { tutorial: { title: 'Quick tutorial', steps: steps.map(step => DRAFT + step) }, screenshots: (document.access?.screenshots ?? []).length ? document.access.screenshots : document.media.filter(item => item.otUi).map(item => item.path), screenshotStyle: 'black-and-white' } + reads.push('tests.qualification.documentation.tutorial (from the access steps: setup, a control example, the result and how to stop)') + } else notes.push('no tutorial: write tests.qualification.documentation.tutorial (three steps or more) by hand') + } + const missing = ['cycles', 'memory', 'hardware', 'documentation', 'imageSha256'].filter(key => !q[key]) + if (missing.length) { notes.push('tests.qualification is not written: it lacks ' + missing.join(', ')); q = null } + else document.tests.qualification = { moduleVersion: q.moduleVersion, sourceSha256: q.sourceSha256, cycles: q.cycles, memory: q.memory, imageSha256: q.imageSha256, hardware: q.hardware, documentation: q.documentation } + } else if (!procedure && !oldQ) notes.push('no procedure and no qualification record for ' + version + ': name the test procedure\'s folder with --procedure DIR') + + // 6. The gauges: levels suggested from the measurements, rationales drafted where none is written. + const share = perf && dsp && perf.stock?.dearestWorst > 0 ? perf.cycles.measured / perf.stock.dearestWorst : null + const memoryBytes = document.tests.qualification?.memory?.totalBytes + const estimates = { + cpu: typeof resources.cpuPrice?.value === 'number' && resources.cpuPrice.measure === 'frame-interrupt' && priceRec?.result ? { level: suggestCpuLevel(resources.cpuPrice.value), source: CPU_PRICE_RECORD, + rationale: 'On the unit the frame interrupt rose ' + priceRec.result.inUseAdds?.frame + ' points with it on ' + priceRec.result.inUseOn + ' and ' + priceRec.result.atRestAdds?.frame + ' installed and unused' + (curveRec?.version === version ? '; the instance curve read first ' + curveRec.first + ', each ' + curveRec.each : '') + '.' } : null, + dsp: share !== null ? { level: suggestDspLevel(share), source: PERFORMANCE_RECORD, + rationale: perf.cycles.measured + ' executed instructions a sample worst case, ' + (perf.cycles.measured / perf.stock.comparatorWorst).toFixed(2) + ' of ' + perf.stock.comparator + ' (' + perf.stock.comparatorWorst + ') and ' + share.toFixed(2) + ' of the dearest stock effect (' + perf.stock.dearestWorst + '). Chip timing is unmeasured.' } + : perf && !dsp && pkg && !pkg.dspWords ? { level: 'minimal', source: PERFORMANCE_RECORD, rationale: 'No DSP code: the package carries no DSP words.' } : null, + memory: typeof memoryBytes === 'number' ? { level: suggestMemoryLevel(memoryBytes), source: 'TESTING.md', rationale: memoryBytes + ' bytes at ' + document.tests.qualification.memory.maxInstances + ' instances (tests.qualification.memory).' } : null, + } + const impact = resources.impact ? structuredClone(resources.impact) : {}, changedLevels = [] + for (const [key, estimate] of Object.entries(estimates)) { + const old = impact[key] + if (old) { if (estimate && old.level !== estimate.level) changedLevels.push('resources.impact.' + key + '.level is ' + old.level + '; the measurements suggest ' + estimate.level + ' (' + estimate.rationale + ')'); continue } + if (!estimate) continue + // Memory is counted from the build (the package header, the inventory), not compared with a measurement. + impact[key] = { level: estimate.level, basis: key === 'memory' ? 'source-estimate' : 'measured-comparison', rationale: DRAFT + estimate.rationale, source: estimate.source } + reads.push('resources.impact.' + key + ' (level ' + estimate.level + ' suggested from the measurement)') + } + if (['cpu', 'dsp', 'memory'].every(key => impact[key])) { + impact.conditions = wording(impact.conditions, 'One active instance at the dearest setting measured' + (resources.cpuPrice ? '; on the unit, the frame-interrupt price on ' + (priceRec?.scene ?? 'the procedure\'s scene') : '') + '.', 'resources.impact.conditions', reads) + resources.impact = { conditions: impact.conditions, cpu: impact.cpu, dsp: impact.dsp, memory: impact.memory } + } else if (!resources.impact) notes.push('resources.impact is not written: ' + ['cpu', 'dsp', 'memory'].filter(key => !impact[key]).join(', ') + ' has no measurement here (a CPU price, a DSP performance record, a memory inventory)') + return { document, files, notes, reads, changedLevels } +} + +/** sourceSha256 over the folder as it will be: `files` written into a copy first, so nothing in the module changes for a dry run. */ +export async function sourceHashOf(folder, document, files = {}) { + if (!Object.keys(files).length) return moduleNativeSourceSha256(folder, document) + const copy = mkdtempSync(join(tmpdir(), 'module-qualify-')) + try { + cpSync(folder, copy, { recursive: true, verbatimSymlinks: true }) + for (const [path, text] of Object.entries(files)) { mkdirSync(dirname(join(copy, path)), { recursive: true }); writeFileSync(join(copy, path), text) } + return await moduleNativeSourceSha256(copy, document) + } finally { rmSync(copy, { recursive: true, force: true }) } +} + +/** Every string in resources and tests still marked DRAFT, by its path. */ +export function draftedFields(document) { + const found = [], walk = (value, path) => { + if (typeof value === 'string') { if (value.includes(DRAFT.trim())) found.push(path) } + else if (Array.isArray(value)) value.forEach((item, i) => walk(item, path + '[' + i + ']')) + else if (value && typeof value === 'object') for (const [key, item] of Object.entries(value)) walk(item, path + '.' + key) + } + walk(document.resources, 'resources'); walk(document.tests, 'tests') + return found +} + +/** The changes from one manifest to another, a line a field: "~ path: old -> new", "+ path: new", "- path: old". */ +export function fieldDiff(before, after) { + const flat = (value, path = '', out = new Map()) => { + if (value && typeof value === 'object') { const entries = Array.isArray(value) ? value.map((item, i) => [path + '[' + i + ']', item]) : Object.entries(value).map(([key, item]) => [path ? path + '.' + key : key, item]); if (!entries.length) out.set(path, JSON.stringify(value)); for (const [at, item] of entries) flat(item, at, out) } + else out.set(path, JSON.stringify(value)) + return out + } + const a = flat(before), b = flat(after), cut = text => text.length > 160 ? text.slice(0, 157) + '...' : text, lines = [] + for (const [path, value] of b) if (!a.has(path)) lines.push('+ ' + path + ': ' + cut(value)); else if (a.get(path) !== value) lines.push('~ ' + path + ': ' + cut(a.get(path)) + ' -> ' + cut(value)) + for (const [path, value] of a) if (!b.has(path)) lines.push('- ' + path + ': ' + cut(value)) + return lines +} + +/** The module's files that differ from `revision` (the tested commit), by Git's blob hashes, wherever the folder sat then + * (a draft moves to sdk/octatrack/modules at its release). Null when this clone lacks the commit or the folder. */ +export function changedSince(root, folder, revision) { + const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 32 * 1024 * 1024 }) + const id = basename(folder), files = [] + const list = (dir, prefix = '') => { for (const entry of readdirSync(dir, { withFileTypes: true })) { if (entry.name === '__pycache__' || entry.name.endsWith('.pyc') || entry.name === '.DS_Store') continue; if (entry.isDirectory()) list(join(dir, entry.name), prefix + entry.name + '/'); else if (entry.isFile()) files.push(prefix + entry.name) } } + list(folder) + for (const at of ['sdk/octatrack/modules/' + id, 'sdk/drafts/' + id, 'sdk/octabam/modules/' + id]) { + let listing + try { listing = git('ls-tree', '-r', revision, '--', at + '/') } catch { return null } + if (!listing.trim()) continue + const then = new Map(listing.trim().split('\n').map(line => { const [meta, path] = line.split('\t'); return [path.slice(at.length + 1), meta.split(' ')[2]] })) + const hashes = files.length ? git('hash-object', '--', ...files.map(path => join(folder, path))).trim().split('\n') : [] + const changed = files.filter((path, i) => then.get(path) !== hashes[i] && path !== 'octamod.module.json') + return { at, changed, removed: [...then.keys()].filter(path => !files.includes(path)) } + } + return null +} + +/** What --check (and module:doctor's qualification line) refuses: a stale sourceSha256, with what changed since the tested commit and + * the command that refreshes it, and fields still marked DRAFT. `nativeSha`: the folder's moduleNativeSourceSha256, when known. */ +export async function qualifyProblems({ root, folder, document, nativeSha, evidence = true }) { + const problems = [], q = document.tests?.qualification, id = document.id + const baseline = (() => { try { return parseQualificationBaseline(JSON.parse(readFileSync(resolve(root, BASELINE_PATH), 'utf8'))) } catch { return new Map() } })() + if (q && !document.tests.retainedEvidence && baseline.get(id)?.version !== document.version) { + const now = nativeSha ?? await moduleNativeSourceSha256(folder, document) + if (now !== q.sourceSha256) { + const since = q.hardware?.sourceRevision && changedSince(root, folder, q.hardware.sourceRevision) + problems.push({ detail: 'tests.qualification.sourceSha256 is ' + short(q.sourceSha256) + ', the source now hashes to ' + short(now) + + (since ? '; changed since the tested commit ' + short(q.hardware.sourceRevision) + ': ' + ([...since.changed, ...since.removed.map(path => path + ' (removed)')].join(', ') || 'nothing but the manifest') : ''), + fix: 'if only evidence, presentation or other files that are not code changed: npm run module:qualify -- ' + id + ' --rehash --write; if code changed, run the test procedure again and npm run module:qualify -- ' + id + ' --procedure DIR --write' }) + } + } + const drafted = draftedFields(document) + if (drafted.length) problems.push({ detail: drafted.length + ' field' + (drafted.length === 1 ? ' is' : 's are') + ' still marked as drafted by module:qualify: ' + drafted.slice(0, 4).join(', ') + (drafted.length > 4 ? ' and ' + (drafted.length - 4) + ' more' : ''), + fix: 'read each against the evidence, edit it, and delete "' + DRAFT.trim() + '" (docs/MODULE_QUALIFICATION.md#write-the-record-from-the-evidence)' }) + // The evidence's own versions (module:doctor has its own lines for these, so it passes evidence: false). + if (evidence) for (const [path, name] of [[PERFORMANCE_RECORD, 'perf:audit'], [FRAME_COST_RECORD, 'device:price --curve'], [CPU_PRICE_RECORD, 'device:price']]) { + const record = readJson(join(folder, path)), of = record?.version + if (record && of !== document.version) problems.push({ detail: path + ' is for ' + of + ', not ' + document.version, fix: 'measure this version (' + name + '), then npm run module:qualify -- ' + id + ' --procedure DIR --write' }) + } + return problems +} + +async function main() { + const { values: args, positionals } = parseArgs({ allowPositionals: true, options: { procedure: { type: 'string' }, package: { type: 'string' }, base: { type: 'string' }, + image: { type: 'string' }, tester: { type: 'string' }, model: { type: 'string' }, write: { type: 'boolean' }, check: { type: 'boolean' }, rehash: { type: 'boolean' }, draft: { type: 'boolean' }, help: { type: 'boolean', short: 'h' } } }) + if (args.help || positionals.length !== 1) { + console.log('Usage: npm run module:qualify -- [--procedure DIR] [--package FILE.mwrm] [--base TEXT] [--image SHA] [--tester LOGIN] [--model MKI|MKII] [--draft] [--write]\n' + + ' npm run module:qualify -- --check | npm run module:qualify -- --rehash [--write] (docs/MODULE_QUALIFICATION.md)') + process.exit(args.help ? 0 : 2) + } + if (args.image && !/^[a-f0-9]{64}$/.test(args.image)) throw new Error('--image takes the tested image\'s SHA-256 (64 hex digits)') + if (args.model && !['MKI', 'MKII'].includes(args.model)) throw new Error('--model is MKI or MKII') + const root = resolve(import.meta.dirname, '..'), id = positionals[0], folder = qualifyFolder(root, id, args.draft) + if (!folder) { console.error('No module named ' + id + ' under sdk/octatrack/modules or sdk/drafts.'); process.exit(2) } + const manifestPath = join(folder, 'octamod.module.json'), text = readFileSync(manifestPath, 'utf8'), original = JSON.parse(text), where = relative(root, folder) + + if (args.check) { + const problems = await qualifyProblems({ root, folder, document: original }) + if (!problems.length) console.log(where + ': the qualification record matches the source, and nothing is left marked as a draft.') + for (const problem of problems) console.log('✗ ' + problem.detail + '\n fix: ' + problem.fix) + process.exitCode = problems.length ? 1 : 0 + return + } + let document, files = {}, notes = [], reads = [], changedLevels = [] + if (args.rehash) { + if (!original.tests.qualification) { console.error(where + ' has no tests.qualification to rehash.'); process.exit(2) } + document = structuredClone(original) + const revision = original.tests.qualification.hardware?.sourceRevision, since = revision && changedSince(root, folder, revision) + if (since) console.log('Changed since the tested commit ' + short(revision) + ' (' + since.at + '): ' + ([...since.changed, ...since.removed.map(path => path + ' (removed)')].join(', ') || 'nothing but the manifest') + + '.\nIf any of these is code, the evidence is for other source: run the test procedure again instead.') + } else { + const evidence = readEvidence({ folder, procedure: args.procedure && resolve(args.procedure), packagePath: args.package && resolve(args.package) }) + ;({ document, files, notes, reads, changedLevels } = draftRecord({ document: original, evidence, options: { base: args.base, image: args.image, tester: args.tester, model: args.model } })) + } + if (document.tests.qualification) document.tests.qualification.sourceSha256 = await sourceHashOf(folder, document, files) // last: over everything above + let invalid = null + try { parseModuleDocument(document) } catch (error) { invalid = error.message } + let releasable = null + if (!invalid) try { requireModuleQualificationForPublication(parseModuleDocument(document)) } catch (error) { releasable = error.message } + + const diff = fieldDiff(original, document) + console.log('module:qualify ' + id + ' (' + where + ')' + (args.procedure ? ' from ' + args.procedure : '')) + console.log(diff.length ? '\nChanges to octamod.module.json:\n' + diff.map(line => ' ' + line).join('\n') : '\nNo change to octamod.module.json.') + for (const [path, body] of Object.entries(files)) console.log(' ' + (existsSync(join(folder, path)) ? (readFileSync(join(folder, path), 'utf8') === body ? '= ' : '~ ') : '+ ') + path) + if (reads.length) console.log('\nRead these: drafted from the data and marked "' + DRAFT.trim() + '"; --check and module:doctor fail until you edit each and delete the mark:\n' + reads.map(line => ' - ' + line).join('\n')) + if (changedLevels.length) console.log('\nGauge levels kept as written:\n' + changedLevels.map(line => ' - ' + line).join('\n')) + if (notes.length) console.log('\nLeft out or kept:\n' + notes.map(line => ' - ' + line).join('\n')) + if (invalid) console.log('\nThe drafted manifest does not parse: ' + invalid + '. Nothing is written.') + else if (releasable) console.log('\nNot releasable yet: ' + releasable) + if (!args.write || invalid) { if (!invalid && (diff.length || Object.keys(files).length)) console.log('\nRun it again with --write to write this.'); process.exitCode = invalid ? 1 : 0; return } + for (const [path, body] of Object.entries(files)) { mkdirSync(dirname(join(folder, path)), { recursive: true }); writeFileSync(join(folder, path), body) } + writeFileSync(manifestPath, manifestJson(document, text)) + console.log('\nWrote ' + [where + '/octamod.module.json', ...Object.keys(files).map(path => where + '/' + path)].join(', ') + '. Then: npm run module:qualify -- ' + id + ' --check, and npm run module:doctor -- ' + (where.startsWith('sdk/drafts') ? '--draft ' : '') + id + '.') +} + +if (import.meta.filename === process.argv[1]) await main() diff --git a/scripts/module-qualify.test.mjs b/scripts/module-qualify.test.mjs new file mode 100644 index 0000000000..307b4ff8c0 --- /dev/null +++ b/scripts/module-qualify.test.mjs @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: Elastic-2.0 +// Copyright (c) 2026 Jannik Aßfalg (repeat98) +// module:qualify on Mackity's real evidence (fixtures/module-qualify/mackity: its manifest as released on 25 November 2026, its +// perf:audit, device:price and capture records, and the test procedure's procedure.json and price.json of that day). +import { afterEach, expect, it } from 'vitest' +import { execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { parseModuleDocument, requireModuleQualificationForPublication } from '../src/catalog/module-contract.ts' +import { moduleNativeSourceSha256 } from './module-qualification.mjs' +import { DRAFT, changedSince, draftRecord, draftedFields, fieldDiff, packageFacts, qualifyFolder, qualifyProblems, readEvidence, sourceHashOf } from './module-qualify.mjs' +import { writePrice } from './octatrack-price.mjs' +import { STEPS, plan } from './test-procedure.mjs' + +const FIXTURE = resolve(import.meta.dirname, 'fixtures/module-qualify/mackity') +const fixture = name => JSON.parse(readFileSync(join(FIXTURE, name), 'utf8')) +const BASE = 'development twin 8fd6d456 of base 0.8.1 (eb6679620d0c9ed7), the owner\'s MKII, OS 1.40C' +const REVISION = 'ccbb96b6c06ae074159be45d66f69812d450793f' +const roots = [] +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) }) + +/** A package with Mackity's header (472 bytes of ColdFire code and data, a DSP effect of 208 words, 32 state words), filled with + * zeros: no built image enters the repository, so its SHA-256 stands in for the real package's in the procedure. */ +function mackityPackage() { + const data = Buffer.alloc(80 + 472 + 4 * 208) + data.write('MWRM'); data.writeUInt16BE(9, 4); data.writeUInt32BE(472, 8); data.writeUInt32BE(208, 32) + data[38] = 26; data[39] = 3; data.writeUInt16BE(226, 44); data[46] = 1; data[47] = 32; data.write('Mackity', 50, 'latin1') + return data +} +const UNMEASURED = { label: 'Storage', display: 'Not measured', value: null, unit: 'unknown', method: 'unmeasured', conditions: 'No measurements exist yet.', source: 'TESTING.md' } + +/** Mackity in a scratch checkout: listed or a draft; `fresh` takes away everything module:qualify writes, as before the release. */ +function layout({ draft = false, fresh = false } = {}) { + const root = mkdtempSync(join(tmpdir(), 'module-qualify-test-')); roots.push(root) + const folder = join(root, draft ? 'sdk/drafts/mackity' : 'sdk/octatrack/modules/mackity'), procedure = join(root, 'proc') + for (const dir of ['evidence', 'media']) mkdirSync(join(folder, dir), { recursive: true }) + mkdirSync(procedure) + const pkg = mackityPackage(), sha = createHash('sha256').update(pkg).digest('hex') + writeFileSync(join(procedure, 'mackity.mwrm'), pkg) + for (const [name, text] of [['manifest.py', '# fixture: Mackity\'s native manifest\n'], ['mackity.asm', '; fixture: Mackity\'s DSP source\n'], ['TESTING.md', '# Mackity 0.1.0-experimental\n'], ['README.md', '# Mackity\n'], ['LICENSE', 'MIT\n']]) + writeFileSync(join(folder, name), text) + writeFileSync(join(folder, 'evidence/performance.json'), readFileSync(join(FIXTURE, 'performance.json'))) + writeFileSync(join(folder, 'media/capture.json'), JSON.stringify({ ...fixture('capture.json'), packageSha256: sha }, null, 1) + '\n') + const document = fixture('module.json') + if (fresh) { + delete document.tests.qualification; delete document.resources.impact; delete document.resources.cpuPrice + Object.assign(document.resources, { recorded: 'Not measured', storage: UNMEASURED, processing: { ...UNMEASURED, label: 'CPU / DSP load' } }) + Object.assign(document.tests, { hardwareStatus: 'untested', summary: 'No tests have been run.', evidenceRevision: 'b8deefc88b2c3e5f3c6158e364eb741df1924e1d' }) + } else for (const name of ['cpu-price.json', 'frame-cost.json']) writeFileSync(join(folder, 'evidence', name), readFileSync(join(FIXTURE, name))) + writeFileSync(join(folder, 'octamod.module.json'), JSON.stringify(document, null, 2) + '\n') + const record = fixture('procedure.json') + record.build.package = { path: join(procedure, 'mackity.mwrm'), sha256: sha } + writeFileSync(join(procedure, 'procedure.json'), JSON.stringify(record, null, 1) + '\n') + writeFileSync(join(procedure, 'price.json'), readFileSync(join(FIXTURE, 'price.json'))) + return { root, folder, procedure, sha, document } +} + +it('reads a package header: code and data, DSP words and state', () => { + expect(packageFacts(mackityPackage())).toMatchObject({ abi: 9, imageBytes: 472, bssBytes: 0, dspWords: 208, stateWords: 32, bufferWords: 0, cycles: 226, cyclesKind: 1 }) + expect(() => packageFacts(Buffer.from('not a package at all, really not one'))).toThrow(/MWRM/) +}) + +it('drafts a draft\'s whole release record from Mackity\'s evidence, its price and curve included', async () => { + const { root, folder, procedure, sha, document } = layout({ draft: true, fresh: true }) + expect(qualifyFolder(root, 'mackity')).toBe(folder) + const evidence = readEvidence({ folder, procedure }) + expect(evidence.package).toMatchObject({ sha256: sha, dspWords: 208 }) + const { document: drafted, files, notes } = draftRecord({ document, evidence, options: { base: BASE } }) + expect(notes).toEqual([]) + + // The price and the curve, as device:price --write would have written them into a listed module. + const real = fixture('cpu-price.json'), price = JSON.parse(files['evidence/cpu-price.json']) + expect(price).toMatchObject({ module: 'mackity', version: '0.1.0-experimental', base: BASE, seconds: 8, readings: 3, measuredAt: real.measuredAt, inputs: { transport: 'playing' } }) + expect(price.result).toEqual(real.result) + expect(drafted.resources.cpuPrice).toMatchObject({ value: 0.1, unit: 'percent-of-frame', measure: 'frame-interrupt', date: '2026-11-25', source: 'evidence/cpu-price.json' }) + expect(drafted.resources.cpuPrice.conditions).toMatch(/3 readings of 8 s a state\. Frame interrupt 32\.2 % before, 32\.2 % installed and used nowhere, 32\.3 % on T1 FX2/) + const curve = JSON.parse(files['evidence/frame-cost.json']), realCurve = fixture('frame-cost.json') + for (const key of ['module', 'version', 'seconds', 'measuredAt', 'tracks', 'rest', 'first', 'each', 'points', 'adds', 'admission', 'notes']) expect(curve[key]).toEqual(realCurve[key]) + + // The numbers and identities, from the procedure, the package and the performance record. + const q = drafted.tests.qualification + expect(q.hardware).toMatchObject({ kind: 'functional', status: 'reported', model: 'MKII', testedOn: '2026-11-25', tester: 'repeat98', sourceRevision: REVISION, imageSha256: sha, report: 'TESTING.md' }) + expect(drafted.tests).toMatchObject({ hardwareStatus: 'reported', evidenceRevision: REVISION }) + expect(q.cycles).toEqual([expect.objectContaining({ processor: 'dsp', worstCase: 251, maxConfiguration: 1004, maxInstances: 8, budget: 3120, unit: 'cycles/sample', method: 'static', report: 'evidence/performance.json' })]) + expect(q.memory).toMatchObject({ perInstanceBytes: 96, sharedBytes: 1096, maxInstances: 8, totalBytes: 1864 }) + expect(q.memory.regions.map(region => [region.space, region.words, region.scope])).toEqual([['dsp-p', 208, 'shared'], ['dsp-x', 32, 'instance'], ['cpu-ram', 472, 'shared']]) + expect(drafted.resources).toMatchObject({ recorded: '2026-11-25', storage: { display: '208 words / 32-word state', method: 'static' }, processing: { display: '228 instructions/sample per instance', method: 'emulator' } }) + // The levels Mackity's author chose by hand, suggested from the same measurements. + expect(drafted.resources.impact).toMatchObject({ cpu: { level: 'minimal' }, dsp: { level: 'moderate' }, memory: { level: 'low' } }) + + // Words a person stands behind are drafted, marked, and refused until edited; the record already parses and would publish. + const marked = draftedFields(drafted) + expect(marked).toEqual(expect.arrayContaining(['tests.summary', 'tests.qualification.hardware.summary', 'tests.qualification.hardware.limitations[0]', 'tests.qualification.cycles[0].conditions.modeSwitching', 'resources.impact.dsp.rationale', 'tests.qualification.documentation.tutorial.steps[0]'])) + expect(q.hardware.limitations).toContain(DRAFT + 'Not run: emulator rehearsal (no emulator session (--emulator-socket SOCK, an ot_emu with --usb-host on a development base)).') + q.sourceSha256 = await sourceHashOf(folder, drafted, files) + expect(() => requireModuleQualificationForPublication(parseModuleDocument(drafted))).not.toThrow() + + // sourceSha256 is the folder's once the files are written: nothing to recompute by hand. + for (const [path, text] of Object.entries(files)) writeFileSync(join(folder, path), text) + writeFileSync(join(folder, 'octamod.module.json'), JSON.stringify(drafted, null, 2) + '\n') + expect(await moduleNativeSourceSha256(folder, drafted)).toBe(q.sourceSha256) + const problems = await qualifyProblems({ root, folder, document: drafted }) + expect(problems.map(problem => problem.detail)).toEqual([expect.stringMatching(/fields are still marked as drafted by module:qualify/)]) +}) + +it('keeps Mackity\'s hand-written record as it is: only sourceSha256 follows the folder', async () => { + const { folder, procedure, document } = layout() + const { document: drafted, files, notes, reads, changedLevels } = draftRecord({ document, evidence: readEvidence({ folder, procedure }), options: { base: BASE } }) + expect(files).toEqual({}) + expect(notes).toEqual([expect.stringMatching(/already holds this run/)]) + expect(reads).toEqual([]) + expect(changedLevels).toEqual([]) + expect(fieldDiff(document, drafted)).toEqual([]) + drafted.tests.qualification.sourceSha256 = await sourceHashOf(folder, drafted) + expect(fieldDiff(document, drafted)).toEqual([expect.stringMatching(/^~ tests\.qualification\.sourceSha256: "7271f6d9/)]) + expect(draftedFields(drafted)).toEqual([]) +}) + +it('leaves out what has no source, and says what would supply it', () => { + const { folder, procedure, document } = layout({ draft: true, fresh: true }) + const { document: drafted, files, notes } = draftRecord({ document, evidence: readEvidence({ folder, procedure }) }) + expect(files).toEqual({}) + expect(drafted.resources.cpuPrice).toBeUndefined() + expect(notes).toEqual(expect.arrayContaining([expect.stringMatching(/name the base the unit ran with --base TEXT/), expect.stringMatching(/resources\.impact is not written: cpu has no measurement/)])) + expect(() => draftRecord({ document: { ...document, version: '0.1.1-experimental' }, evidence: readEvidence({ folder, procedure }) })).toThrow(/tested mackity 0\.1\.0-experimental, not mackity 0\.1\.1-experimental/) + const failed = { ...readEvidence({ folder, procedure }) } + failed.procedure = { ...failed.procedure, steps: failed.procedure.steps.map(step => step.id === 'soak' ? { ...step, status: 'failed' } : step) } + const { document: refused, notes: why } = draftRecord({ document, evidence: failed, options: { base: BASE } }) + expect(refused.tests.qualification).toBeUndefined() + expect(why).toEqual(expect.arrayContaining([expect.stringMatching(/the procedure failed at Soak: no hardware record/)])) +}) + +it('reports a stale sourceSha256 with what changed since the tested commit and the command that refreshes it', async () => { + const { root, folder, document } = layout() + const git = (...args) => execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@example.com', ...args], { cwd: root, stdio: 'pipe' }).toString().trim() + git('init', '-q'); git('add', '-A'); git('commit', '-qm', 'tested') + const tested = git('rev-parse', 'HEAD') + document.tests.qualification.hardware.sourceRevision = tested + document.tests.qualification.sourceSha256 = await moduleNativeSourceSha256(folder, document) + expect(await qualifyProblems({ root, folder, document })).toEqual([]) + writeFileSync(join(folder, 'evidence/frame-cost.json'), JSON.stringify({ ...fixture('frame-cost.json'), notes: ['read again'] }, null, 2) + '\n') + expect(changedSince(root, folder, tested)).toEqual({ at: 'sdk/octatrack/modules/mackity', changed: ['evidence/frame-cost.json'], removed: [] }) + const [problem] = await qualifyProblems({ root, folder, document }) + expect(problem.detail).toMatch(/source now hashes to .*changed since the tested commit .*: evidence\/frame-cost\.json$/) + expect(problem.fix).toMatch(/npm run module:qualify -- mackity --rehash --write; if code changed, run the test procedure again/) +}) + +it('test:procedure --price-base has step 9 write the price and the curve into the module\'s folder', () => { + const ctx = { kind: 'module', id: 'mackity', share: '/tmp/share.sock', out: '/tmp/proc', source: true, target: 'unit', scene: 'C04' } + const command = context => plan(STEPS.find(step => step.id === 'cost-unit'), context).commands[0].join(' ') + expect(command(ctx)).not.toMatch(/--write/) + expect(command({ ...ctx, priceBase: 'base 0.8.1' })).toMatch(/--scene C04 --write --base base 0\.8\.1 --curve T1,T3,T6,T7/) + expect(command({ ...ctx, priceBase: 'base 0.8.1', source: false })).not.toMatch(/--write/) +}) + +it('device:price --write puts a draft\'s price beside it, in sdk/drafts', () => { + const { root, folder } = layout({ draft: true, fresh: true }), price = fixture('price.json') + const said = writePrice({ root, result: price.results[0], base: BASE, scene: price.scene, seconds: price.seconds, measuredAt: price.measuredAt, readings: price.readings, inputs: price.inputs }) + expect(said).toBe('wrote 0.1 % of a frame into sdk/drafts/mackity/octamod.module.json and its readings into evidence/cpu-price.json') + expect(JSON.parse(readFileSync(join(folder, 'evidence/cpu-price.json'), 'utf8')).result).toEqual(fixture('cpu-price.json').result) + expect(JSON.parse(readFileSync(join(folder, 'octamod.module.json'), 'utf8')).resources.cpuPrice.value).toBe(0.1) +}) diff --git a/scripts/octatrack-midi-bridge.py b/scripts/octatrack-midi-bridge.py index 744695f834..af9f6b973b 100644 --- a/scripts/octatrack-midi-bridge.py +++ b/scripts/octatrack-midi-bridge.py @@ -8,8 +8,10 @@ "On Windows, from WSL"), where WSL reaches it on 127.0.0.1 through mirrored networking as it reaches the USB bridge. Each line holds MIDI messages as hex words ('c003', 'fa', 'b0307f'); they go out back to back, and the line is answered 'ok N' (messages sent) or 'error: ...'. Windows sends through winmm (ctypes, nothing to install); other -systems through mido, if it is installed. Short messages only, no SysEx. --list prints the MIDI outputs and exits.""" -import argparse, socket, socketserver, sys +systems through mido, if it is installed. Short messages only, no SysEx. --list prints the MIDI outputs and exits. +A RAM boot or a crash restarts the unit and its USB MIDI enumerates again, which leaves the open port dead: a send that +fails closes it, opens the output of that name again (waiting up to 5 s for it to come back) and sends once more.""" +import argparse, socket, socketserver, sys, time def parse(line): @@ -24,58 +26,120 @@ def parse(line): class Winmm: - def __init__(self, name): + """Windows' MIDI outputs through winmm.""" + + def __init__(self): import ctypes from ctypes import wintypes - self.w = w = ctypes.WinDLL('winmm') + self.ctypes, self.wintypes, self.w = ctypes, wintypes, ctypes.WinDLL('winmm') class Caps(ctypes.Structure): _fields_ = [('mid', wintypes.WORD), ('pid', wintypes.WORD), ('ver', wintypes.DWORD), ('name', wintypes.WCHAR * 32), ('tech', wintypes.WORD), ('voices', wintypes.WORD), ('notes', wintypes.WORD), ('mask', wintypes.WORD), ('support', wintypes.DWORD)] - self.names = [] - for i in range(w.midiOutGetNumDevs()): - c = Caps() - w.midiOutGetDevCapsW(i, ctypes.byref(c), ctypes.sizeof(c)) - self.names.append(c.name) - self.handle = None - if name is None: - return - found = [i for i, n in enumerate(self.names) if name.lower() in n.lower()] - if not found: - raise SystemExit('No MIDI output named like %r: %s' % (name, ', '.join(self.names) or 'none')) - self.handle = wintypes.HANDLE() - if w.midiOutOpen(ctypes.byref(self.handle), found[0], None, None, 0): - raise SystemExit('Could not open %s (another program may hold it).' % self.names[found[0]]) - self.opened = self.names[found[0]] + self.Caps = Caps - def send(self, data): - word = data[0] | (data[1] << 8 if len(data) > 1 else 0) | (data[2] << 16 if len(data) > 2 else 0) - if self.w.midiOutShortMsg(self.handle, word): - raise OSError('midiOutShortMsg refused %s' % data.hex()) + def names(self): # read again each time: the device numbers change when the unit enumerates again + names = [] + for i in range(self.w.midiOutGetNumDevs()): + c = self.Caps() + self.w.midiOutGetDevCapsW(i, self.ctypes.byref(c), self.ctypes.sizeof(c)) + names.append(c.name) + return names + + def open(self, name): + w, handle = self.w, self.wintypes.HANDLE() + if w.midiOutOpen(self.ctypes.byref(handle), self.names().index(name), None, None, 0): + raise OSError('Could not open %s (another program may hold it).' % name) + + class Port: + def send(self, data): + word = data[0] | (data[1] << 8 if len(data) > 1 else 0) | (data[2] << 16 if len(data) > 2 else 0) + if w.midiOutShortMsg(handle, word): + raise OSError('midiOutShortMsg refused %s' % data.hex()) + + def close(self): w.midiOutClose(handle) + return Port() class Mido: - def __init__(self, name): + """The MIDI outputs elsewhere, through mido.""" + + def __init__(self): import mido - self.names = mido.get_output_names() - self.port = None - if name is None: - return - found = [n for n in self.names if name.lower() in n.lower()] - if not found: - raise SystemExit('No MIDI output named like %r: %s' % (name, ', '.join(self.names) or 'none')) - self.port, self.opened = mido.open_output(found[0]), found[0] self.mido = mido + def names(self): return self.mido.get_output_names() + + def open(self, name): + mido, port = self.mido, self.mido.open_output(name) + + class Port: + def send(self, data): + try: port.send(mido.Message.from_bytes(list(data))) + except Exception as e: raise OSError('%s refused %s: %s' % (name, data.hex(), e)) + + def close(self): port.close() + return Port() + + +class Output: + """The first output named like `name`, through `system` (Winmm or Mido), opened again once when a send fails.""" + + def __init__(self, system, name, wait=time.sleep, log=print): + self.system, self.name, self.wait, self.log, self.reopened = system, name, wait, log, 0 + self.port = self._open() + + def _open(self): + names = self.system.names() + found = [n for n in names if self.name.lower() in n.lower()] + if not found: raise LookupError('No MIDI output named like %r: %s' % (self.name, ', '.join(names) or 'none')) + port = self.system.open(found[0]) + self.opened = found[0] + return port + + def close(self): + port, self.port = self.port, None + try: + if port: port.close() + except OSError: pass # a dead handle may refuse its close too + def send(self, data): - self.port.send(self.mido.Message.from_bytes(list(data))) + try: + if self.port is None: raise OSError('the port is closed') + return self.port.send(data) + except OSError as e: + failed = e + self.close() + for attempt in range(10): # the unit may still be enumerating: every half second, 5 s at most + try: + self.port = self._open() + break + except (LookupError, OSError) as e: + missing = e + self.wait(0.5) + else: + raise OSError('%s; opening %r again failed: %s' % (failed, self.name, missing)) + self.reopened += 1 + self.log('reopened %s after: %s' % (self.opened, failed), flush=True) + self.port.send(data) # once: a second failure is the answer + + +def answer(out, line): + """One request line -> its reply line.""" + try: + messages = parse(line) + for m in messages: + out.send(m) + return 'ok %d\n' % len(messages) + except (ValueError, OSError) as e: + return 'error: %s\n' % e -def output(name): +def system(): if sys.platform == 'win32': - return Winmm(name) + return Winmm() try: - return Mido(name) + return Mido() except ImportError: raise SystemExit('Outside Windows this bridge needs mido (pip install mido python-rtmidi).') @@ -87,22 +151,18 @@ def main(): ap.add_argument('--list', action='store_true') a = ap.parse_args() if a.list: - print('\n'.join(output(None).names)) + print('\n'.join(system().names())) return - out = output(a.name) + try: + out = Output(system(), a.name) + except (LookupError, OSError) as e: + raise SystemExit(str(e)) class Handler(socketserver.StreamRequestHandler): def handle(self): self.connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # a reply per line, no batching for raw in self.rfile: - try: - messages = parse(raw.decode('ascii', 'replace')) - for m in messages: - out.send(m) - reply = 'ok %d\n' % len(messages) - except (ValueError, OSError) as e: - reply = 'error: %s\n' % e - self.wfile.write(reply.encode()) + self.wfile.write(answer(out, raw.decode('ascii', 'replace')).encode()) self.wfile.flush() socketserver.TCPServer.allow_reuse_address = True diff --git a/scripts/octatrack-part-state.mjs b/scripts/octatrack-part-state.mjs new file mode 100644 index 0000000000..1872c86c3b --- /dev/null +++ b/scripts/octatrack-part-state.mjs @@ -0,0 +1,162 @@ +#!/usr/bin/env node +// The Part a test run starts on, read before the run changes anything and put back after it, so the next run finds the test +// bank as clean as this one did (docs/TEST_PROCEDURE.md: steps 6 and 10, and #a-test-bank). +// +// node scripts/octatrack-part-state.mjs read --socket SOCK --out FILE [--programs 32-35] +// node scripts/octatrack-part-state.mjs restore --socket SOCK --start FILE +// +// `read` notes the bank, pattern, Part and transport and, for the current bank (and every bank --programs reaches), which of +// its four Parts has a working copy equal to its saved one. A clean current Part is SAVEd once, stopped, as device:test does: +// the same bytes, but after a RAM boot RELOAD refuses a Part not saved since (SAVE PART FIRST!). `restore` stops the transport +// if it was stopped at the start, goes back to that bank, pattern and Part, RELOADs the Part when it was clean at the start and +// differs now, and checks both copies against the saved copy read first. A Part that differed at the start is left as found: +// its edits are not the run's to discard. It prints one JSON line ({"part": …}) and, for each thing it could not put back, +// a line "not put back: …" with the fix; then it exits 1. OS 1.40C's addresses (docs/OCTATRACK_DRIVING.md#where-the-state-is-os-140c). +import { createHash } from 'node:crypto' +import { spawnSync } from 'node:child_process' +import { existsSync, readFileSync, writeFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { parseArgs } from 'node:util' +import { parsePrograms } from './octatrack-soak.mjs' + +export const PART = 0x80000003, BANK_POINTER = 0x46c82456, NOW = 0x800065bd, PART_BYTES = 6322 +export const bankBase = bank => 0x400e21e0 + bank * 0x9b340 +export const copyAt = (bank, part, saved) => bankBase(bank) + (saved ? 0x9504a : 0x8ed80) + part * PART_BYTES +export const where = (bank, pattern) => 'ABCDEFGHIJKLMNOP'[bank] + String(pattern + 1).padStart(2, '0') +const bankName = bank => 'bank ' + 'ABCDEFGHIJKLMNOP'[bank] +/** Programs that select patterns 1 to 4 of a bank (bank A pattern 1 is program 0, bank B pattern 1 is 16). */ +export const bankPrograms = bank => `${bank * 16}-${bank * 16 + 3}` +/** The banks a soak's program list reaches. */ +export const banksOf = programs => [...new Set(parsePrograms(programs).map(program => program >> 4))] + +const hexLines = text => String(text ?? '').split('\n').map(line => line.trim()).filter(line => /^[0-9a-f]+$/.test(line)) +const digest = hex => createHash('sha256').update(hex).digest('hex').slice(0, 16) +const mem = (at, length) => `mem:0x${at.toString(16)}:${length}` + +/** Where the unit is: transport, bank, pattern, Part and the bank pointer (one read-only line). */ +async function position(send) { + const out = await send(['state', mem(NOW, 2), mem(PART, 1), mem(BANK_POINTER, 4)].join(' ')) + const hex = hexLines(out) + if (hex.length !== 3 || !/^(stopped|playing)/m.test(out)) throw new Error('The unit did not answer the position read: ' + String(out).trim().split('\n').slice(-2).join(' / ')) + const position = { stopped: /^stopped/m.test(out), bank: parseInt(hex[0].slice(0, 2), 16), pattern: parseInt(hex[0].slice(2, 4), 16), part: parseInt(hex[1], 16) } + if (parseInt(hex[2], 16) !== bankBase(position.bank)) + throw new Error(`The current bank's base reads 0x${hex[2]}, not 0x${bankBase(position.bank).toString(16)} where OS 1.40C keeps ${bankName(position.bank)}: this tool knows only that layout`) + return position +} + +/** Each listed Part of a bank: its working and saved copies' digests, and whether they are equal. */ +async function copies(send, bank, parts = [0, 1, 2, 3]) { + const hex = hexLines(await send(parts.flatMap(part => [mem(copyAt(bank, part, false), PART_BYTES), mem(copyAt(bank, part, true), PART_BYTES)]).join(' '))) + if (hex.length !== 2 * parts.length || hex.some(line => line.length !== 2 * PART_BYTES)) throw new Error(`The Parts of ${bankName(bank)} did not read whole`) + return parts.map((part, i) => { const working = digest(hex[2 * i]), saved = digest(hex[2 * i + 1]); return { part: part + 1, working, saved, clean: working === saved } }) +} + +/** Step 6: the start, and the clean current Part SAVEd once (stopped) so that its RELOAD works at the end. */ +export async function readStart(send, { banks = [] } = {}) { + const at = await position(send), state = { ...at, saved: false, banks: {} } + for (const bank of [...new Set([at.bank, ...banks])]) state.banks[bank] = await copies(send, bank) + const start = state.banks[at.bank][at.part], name = `Part ${at.part + 1} on ${where(at.bank, at.pattern)}` + if (!start.clean) state.summary = `${name} differs from its saved copy, so the run leaves it as found and does not reload it: start on a test bank whose Part is saved (docs/TEST_PROCEDURE.md#a-test-bank)` + else if (!at.stopped) state.summary = `${name}: working = saved; not saved once, as the transport was playing, so after a RAM boot its RELOAD at the end can be refused` + else { + await send('NO w200 savepart') + const [now] = await copies(send, at.bank, [at.part]) + if (now.working !== start.saved || now.saved !== start.saved) throw new Error(`Saving ${name}, so that RELOAD works at the end, changed it: check the unit before going on`) + state.saved = true + state.summary = `${name}: working = saved, saved once so that RELOAD works at the end` + } + return state +} + +/** Step 10 (and the soak's end): the start position and the start Part as saved again. Returns {ok, summary, actions, problems}. */ +export async function restore(send, start) { + const actions = [], problems = [], name = `Part ${start.part + 1} on ${where(start.bank, start.pattern)}` + let now = await position(send) + // STOP also when it reads stopped: a MIDI STOP pauses the sequencer, which reads as stopped from base 0.8 on. + if (start.stopped) { await send('STOP w300'); if (!now.stopped) actions.push('transport stopped'); now = await position(send) } + if (now.bank !== start.bank || now.pattern !== start.pattern) { + await send(`BANK w150 TRIG${start.bank + 1} w150 TRIG${start.pattern + 1} w500`) + const was = where(now.bank, now.pattern) + now = await position(send) + if (now.bank !== start.bank || now.pattern !== start.pattern) + problems.push(`not back on ${where(start.bank, start.pattern)} (it is on ${where(now.bank, now.pattern)}): select it by hand (BANK, TRIG ${start.bank + 1}, TRIG ${start.pattern + 1}), then run this again`) + else actions.push(`back on ${where(start.bank, start.pattern)} from ${was}`) + } + if (!problems.length && now.part !== start.part) { + // A Part switch assigns that Part to the pattern (stock): the pattern's own Part again. + await send(`part${start.part + 1}`) + now = await position(send) + if (now.part !== start.part) problems.push(`Part ${start.part + 1} is not selected again (it is on Part ${now.part + 1}): select it by hand`) + else actions.push(`Part ${start.part + 1} selected again`) + } + const first = start.banks[start.bank][start.part] + if (!problems.length && first.clean) { + let [part] = await copies(send, start.bank, [start.part]) + if (part.saved !== first.saved) + problems.push(`the saved copy of ${name} changed during the run (something saved over it), so RELOAD cannot bring it back: reload the project without saving it, or put the Part back by hand (docs/OCTATRACK_DRIVING.md#the-rules)`) + else if (part.working !== first.saved) { + await send('NO w200 reload'); + [part] = await copies(send, start.bank, [start.part]) + if (part.working === first.saved && part.saved === first.saved) actions.push(`${name} reloaded`) + else { + await send('NO w200') // the SAVE PART FIRST! message + problems.push(`RELOAD did not bring ${name} back${start.saved ? '' : ' (SAVE PART FIRST!: step 6 could not save it, as the transport was playing)'}: ` + + 'put it back by hand (docs/OCTATRACK_DRIVING.md#the-rules) or reload the project without saving it, and start the next run on a stopped, saved test bank') + } + } + } + // Every other Part read at the start that was saved then and differs now: the run changed it, and only its own Part is reloaded. + for (const [bank, parts] of Object.entries(start.banks)) { + const was = parts.filter(part => part.clean && !(Number(bank) === start.bank && part.part === start.part + 1)) + if (!was.length) continue + for (const part of await copies(send, Number(bank), was.map(p => p.part - 1))) + if (!part.clean) problems.push(`Part ${part.part} of ${bankName(Number(bank))} was saved at the start and differs now: reload it by hand (a pattern on that Part, then FUNC+PART, RELOAD), and keep the run on one Part of the test bank (--soak-programs ${bankPrograms(start.bank)})`) + } + const ok = !problems.length + const summary = !ok ? problems.join('; ') + : !first.clean ? `${name} differed from its saved copy at the start, so it was left as found${actions.length ? '; ' + actions.join(', ') : ''}` + : `${name}: ${actions.join(', ') || 'nothing to put back'}; working = saved` + return { ok, summary, actions, problems } +} + +/** One `device.mjs do` line on the session, its output; a failed command throws. */ +function deviceDo(socket) { + const script = fileURLToPath(new URL('./device.mjs', import.meta.url)) + return async line => { + const run = spawnSync(process.execPath, [script, 'do', line, '--socket', socket], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }) + const output = (run.stdout ?? '') + (run.stderr ?? '') + if (run.status !== 0 || /^error: /m.test(output)) throw new Error(`device.mjs do '${line.slice(0, 60)}' failed: ` + output.trim().split('\n').slice(-2).join(' / ')) + return output + } +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const { values, positionals } = parseArgs({ allowPositionals: true, options: { + socket: { type: 'string', default: process.env.MODWERK_SHARE_SOCKET ?? '/tmp/modwerk-share.sock' }, out: { type: 'string' }, start: { type: 'string' }, programs: { type: 'string' } } }) + const [verb] = positionals + if (!['read', 'restore'].includes(verb) || (verb === 'read' && !values.out) || (verb === 'restore' && !values.start)) { + console.error('Usage: octatrack-part-state.mjs read --socket SOCK --out FILE [--programs 32-35]\n octatrack-part-state.mjs restore --socket SOCK --start FILE') + process.exit(2) + } + const send = deviceDo(values.socket) + try { + if (verb === 'read') { + const state = await readStart(send, { banks: values.programs ? banksOf(values.programs) : [] }) + writeFileSync(values.out, JSON.stringify(state, null, 1) + '\n') + console.log(JSON.stringify({ part: state })) + } else { + if (!existsSync(values.start)) { + console.log(`not put back: no reading of the Part from the start (${values.start}), so nothing was reloaded: compare the Part with its saved copy by hand (docs/OCTATRACK_DRIVING.md#where-the-state-is-os-140c)`) + process.exit(1) + } + const result = await restore(send, JSON.parse(readFileSync(values.start, 'utf8'))) + console.log(JSON.stringify({ part: result })) + for (const problem of result.problems) console.log('not put back: ' + problem) + process.exit(result.ok ? 0 : 1) + } + } catch (error) { + console.log((verb === 'read' ? 'not read: ' : 'not put back: ') + error.message) + process.exit(1) + } +} diff --git a/scripts/octatrack-part-state.test.mjs b/scripts/octatrack-part-state.test.mjs new file mode 100644 index 0000000000..088da7b17c --- /dev/null +++ b/scripts/octatrack-part-state.test.mjs @@ -0,0 +1,145 @@ +import { describe, expect, it } from 'vitest' +import { BANK_POINTER, NOW, PART, PART_BYTES, bankBase, bankPrograms, banksOf, copyAt, readStart, restore, where } from './octatrack-part-state.mjs' + +/** A unit as the device session shows it: position bytes, each Part's working and saved copy (one fill byte each), the + * transport, and the Part menu's SAVE and RELOAD; RELOAD is refused on a Part not saved since the boot (SAVE PART FIRST!). */ +function fakeUnit({ bank = 2, pattern = 0, part = 0, stopped = true, savedSinceBoot = [], dirty = [], layout = bankBase } = {}) { + const unit = { bank, pattern, part, stopped, sent: [], saves: new Set(savedSinceBoot), copies: new Map() } + const copy = (b, p) => { const key = b + ':' + p; if (!unit.copies.has(key)) unit.copies.set(key, { working: 0x11 + p, saved: 0x11 + p }); return unit.copies.get(key) } + for (const [b, p] of dirty) copy(b, p).working = 0x99 + unit.edit = (b, p, byte = 0x77) => { copy(b, p).working = byte } + unit.overwriteSaved = (b, p) => { copy(b, p).saved = 0x55 } + unit.copy = copy + const hex = (bytes, length = bytes.length) => Buffer.from(bytes.length === 1 && length > 1 ? Array(length).fill(bytes[0]) : bytes).toString('hex') + const memory = (at, length) => { + if (at === NOW) return hex([unit.bank, unit.pattern]) + if (at === PART) return hex([unit.part]) + if (at === BANK_POINTER) return layout(unit.bank).toString(16).padStart(8, '0') + for (let b = 0; b < 16; b++) for (let p = 0; p < 4; p++) for (const saved of [false, true]) + if (copyAt(b, p, saved) === at) return hex([saved ? copy(b, p).saved : copy(b, p).working], length) + throw new Error('no such address 0x' + at.toString(16)) + } + let chooseBank = false + unit.send = async line => { + unit.sent.push(line) + const out = [] + for (const step of line.split(/\s+/)) { + let m + if (step === 'state') out.push(unit.stopped ? 'stopped ' : 'playing ') + else if ((m = /^mem:0x([0-9a-f]+):(\d+)$/.exec(step))) out.push(memory(parseInt(m[1], 16), Number(m[2]))) + else if (step === 'STOP') unit.stopped = true + else if (step === 'BANK') chooseBank = 'bank' + else if ((m = /^TRIG(\d+)$/.exec(step)) && chooseBank === 'bank') { unit.bank = Number(m[1]) - 1; chooseBank = 'pattern' } + else if ((m = /^TRIG(\d+)$/.exec(step)) && chooseBank === 'pattern') { unit.pattern = Number(m[1]) - 1; chooseBank = false } + else if ((m = /^part(\d)$/.exec(step))) unit.part = Number(m[1]) - 1 + else if (step === 'savepart') { copy(unit.bank, unit.part).saved = copy(unit.bank, unit.part).working; unit.saves.add(unit.bank + ':' + unit.part) } + else if (step === 'reload') { if (unit.saves.has(unit.bank + ':' + unit.part)) copy(unit.bank, unit.part).working = copy(unit.bank, unit.part).saved } + } + return out.join('\n') + '\n' + } + return unit +} + +describe('reading the start', () => { + it('notes the position and every Part of the bank, and SAVEs a clean current Part once so that RELOAD works at the end', async () => { + const unit = fakeUnit({ bank: 2, pattern: 3 }) + const start = await readStart(unit.send) + expect(start).toMatchObject({ bank: 2, pattern: 3, part: 0, stopped: true, saved: true }) + expect(start.banks[2]).toHaveLength(4) + expect(start.banks[2].every(part => part.clean)).toBe(true) + expect(unit.sent).toContain('NO w200 savepart') + expect(start.summary).toBe('Part 1 on C04: working = saved, saved once so that RELOAD works at the end') + }) + + it('never saves over a Part that differs from its saved copy, nor while playing', async () => { + const dirty = fakeUnit({ dirty: [[2, 0]] }) + const start = await readStart(dirty.send) + expect(start.saved).toBe(false) + expect(dirty.sent.some(line => line.includes('savepart'))).toBe(false) + expect(start.summary).toMatch(/differs from its saved copy, so the run leaves it as found.*#a-test-bank/) + const playing = fakeUnit({ stopped: false }) + expect((await readStart(playing.send)).summary).toMatch(/not saved once, as the transport was playing/) + expect(playing.sent.some(line => line.includes('savepart'))).toBe(false) + }) + + it('reads the banks the soak\'s programs reach as well, and refuses a bank layout it does not know', async () => { + expect(banksOf('0-3,32-35')).toEqual([0, 2]) + expect(bankPrograms(2)).toBe('32-35') + expect(where(15, 15)).toBe('P16') + expect(Object.keys((await readStart(fakeUnit({ bank: 2 }).send, { banks: banksOf('0-3') })).banks)).toEqual(['0', '2']) + await expect(readStart(fakeUnit({ layout: () => 0x40000000 }).send)).rejects.toThrow(/OS 1.40C keeps bank C/) + }) + + it('reads every copy whole: 6,322 bytes a Part', async () => { + const unit = fakeUnit() + await readStart(unit.send) + expect(unit.sent.find(line => line.includes(':' + PART_BYTES))).toContain(`mem:0x${copyAt(2, 0, false).toString(16)}:6322 mem:0x${copyAt(2, 0, true).toString(16)}:6322`) + }) +}) + +describe('putting it back', () => { + it('stops, goes back to the start bank, pattern and Part, and RELOADs the Part the run edited', async () => { + const unit = fakeUnit({ bank: 2, pattern: 0 }) + const start = await readStart(unit.send) + // What a soak leaves: playing on bank A pattern 3, the Part switched and edited by CCs. + Object.assign(unit, { bank: 0, pattern: 2, stopped: false }) + unit.part = 1 + unit.edit(2, 0) + const result = await restore(unit.send, start) + expect(result).toMatchObject({ ok: true, problems: [] }) + expect(result.actions).toEqual(['transport stopped', 'back on C01 from A03', 'Part 1 selected again', 'Part 1 on C01 reloaded']) + expect(result.summary).toBe('Part 1 on C01: transport stopped, back on C01 from A03, Part 1 selected again, Part 1 on C01 reloaded; working = saved') + expect([unit.bank, unit.pattern, unit.part, unit.stopped]).toEqual([2, 0, 0, true]) + expect(unit.copy(2, 0).working).toBe(unit.copy(2, 0).saved) + }) + + it('changes nothing on a Part that is already as saved', async () => { + const unit = fakeUnit() + const start = await readStart(unit.send) + unit.sent.length = 0 + const result = await restore(unit.send, start) + expect(result).toMatchObject({ ok: true, actions: [], summary: 'Part 1 on C01: nothing to put back; working = saved' }) + expect(unit.sent.some(line => line.includes('reload'))).toBe(false) + }) + + it('fails loudly, with the fix, when RELOAD is refused (SAVE PART FIRST!: never saved since the RAM boot)', async () => { + const unit = fakeUnit({ stopped: false }) // playing at the start: step 6 could not save it + const start = await readStart(unit.send) + unit.edit(2, 0) + const result = await restore(unit.send, start) + expect(result.ok).toBe(false) + expect(result.problems).toEqual([expect.stringMatching(/^RELOAD did not bring Part 1 on C01 back \(SAVE PART FIRST!: step 6 could not save it.*put it back by hand \(docs\/OCTATRACK_DRIVING.md#the-rules\)/)]) + expect(unit.sent.slice(-2)[0]).toBe('NO w200') // the message closed + }) + + it('leaves a Part that differed at the start as found, never discarding edits the run did not make', async () => { + const unit = fakeUnit({ dirty: [[2, 0]], savedSinceBoot: ['2:0'] }) + const start = await readStart(unit.send) + unit.edit(2, 0, 0x66) + const result = await restore(unit.send, start) + expect(result).toMatchObject({ ok: true, summary: expect.stringMatching(/differed from its saved copy at the start, so it was left as found/) }) + expect(unit.sent.some(line => line.includes('reload'))).toBe(false) + expect(unit.copy(2, 0).working).toBe(0x66) + }) + + it('fails when the run changed another Part that was saved at the start, or saved over the start Part', async () => { + const other = fakeUnit() + const start = await readStart(other.send) + other.edit(2, 2) + expect((await restore(other.send, start)).problems).toEqual([expect.stringMatching(/^Part 3 of bank C was saved at the start and differs now: reload it by hand.*--soak-programs 32-35/)]) + const savedOver = fakeUnit() + const first = await readStart(savedOver.send) + savedOver.overwriteSaved(2, 0) + expect((await restore(savedOver.send, first)).problems).toEqual([expect.stringMatching(/saved copy of Part 1 on C01 changed during the run/)]) + }) + + it('says so when it cannot get back to the start pattern, and touches no Part then', async () => { + const unit = fakeUnit() + const start = await readStart(unit.send) + unit.bank = 5 + const send = async line => (line.startsWith('BANK') ? '' : unit.send(line)) // the bank change is lost + const result = await restore(send, start) + expect(result.problems).toEqual([expect.stringMatching(/^not back on C01 \(it is on F01\): select it by hand \(BANK, TRIG 3, TRIG 1\)/)]) + expect(unit.sent.some(line => line.includes('reload'))).toBe(false) + }) +}) diff --git a/scripts/octatrack-preflight.py b/scripts/octatrack-preflight.py new file mode 100755 index 0000000000..00d036feab --- /dev/null +++ b/scripts/octatrack-preflight.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-or-later +"""What would fail the test procedure's unit steps minutes in, found in seconds before anything is installed. + + python3 -B scripts/octatrack-preflight.py [--pick-pattern 1-16] [--midi HOST:PORT] + +Read-only requests to the session (`npm run device -- serve`, MODWERK_DEV_SOCKET), and with --midi one tune request (F6, +a message the Octatrack has nothing to do with) through scripts/octatrack-midi-bridge.py. It checks that: +- the base answers development requests (a flashed release base does not, and every unit step needs them); +- the transport is stopped, and the current Part's working copy equals its saved copy (device:test refuses otherwise); +- with --pick-pattern, the unit is on that pattern or on one with room: device:test picks the module on the pattern the + unit is on, and on a pattern with trigs on all eight tracks admission refused it (CPU FULL, 25 November 2026); +- with --midi, the MIDI bridge the soak sends through answers and can send. +Prints one line a problem with its fix (`preflight: ...`) and exits 1, or `preflight: ready` and exits 0. +npm run test:procedure runs it before step 1 and again when its unit turn starts (docs/TEST_PROCEDURE.md).""" +import argparse, importlib.util, pathlib, socket, sys + +ROOT = pathlib.Path(__file__).resolve().parents[1] +_spec = importlib.util.spec_from_file_location('octatrack_qualify', ROOT / 'scripts/octatrack-qualify.py') +qualify = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(qualify) + +CURRENT = 0x800065bd # the bank and pattern the unit is on, 0-based (octatrack-qualify.py, the soak's health) +PATTERN, TRACK = 0x8ed8, 0x91a # a pattern of the current bank and a track's 8-byte trig mask in it (octatrack-price.mjs) +ROOM = 6 # the medium pattern a release must be admitted on has trigs on six tracks (docs/TEST_PROCEDURE.md, step 9) +TUNE_REQUEST = 'f6' + + +def pattern_name(bank, pattern): return 'ABCDEFGHIJKLMNOP'[bank] + '%02d' % (pattern + 1) + + +def busy_tracks(masks): + """Eight trig masks -> the tracks (1-8) with at least one trig.""" + return [track + 1 for track, mask in enumerate(masks) if any(mask)] + + +def pattern_problem(bank, pattern, tracks, pick): + """Why a module's pick on the current pattern would be refused, or None: it is the pick pattern, or has room.""" + if pattern + 1 == pick or len(tracks) <= ROOM: return None + return ('pattern %s has trigs on %d tracks, and device:test picks the module on the pattern the unit is on: admission refused ' + 'such picks (CPU FULL). Select the empty pattern first, `npm run device -- do PATTERN+TRIG%d`, or one with trigs on ' + 'at most %d tracks' % (pattern_name(bank, pattern), len(tracks), pick, ROOM)) + + +def unit_problems(pick=None): + """The session's state, Part and pattern -> problems. Only reads (state, mem).""" + try: + state = qualify.send('state') + except OSError as e: + return ['no session answers on %s (%s): start `npm run device -- serve --share /tmp/modwerk-share.sock` in its loop ' + '(docs/OCTATRACK_DRIVING.md)' % (qualify.SOCKET, e)] + except RuntimeError as e: + if 'development requests' not in str(e): return ['the session answered %s' % e] + return ['the unit runs a base that does not answer development requests (a flashed release base): RAM-boot a development ' + 'twin (`npm run device -- boot DIR`, a build_core.py --dev build), then run again'] + problems = [] + if 'stopped' not in state: problems.append('the transport plays: stop it (`npm run device -- do STOP`)') + bank, pattern = qualify.mem(CURRENT, 2) + if not qualify.part_saved_equal(): + problems.append('Part %d of bank %s differs from its saved copy, and device:test refuses such a Part: go to a bank and Part ' + 'whose working copy equals its saved one (docs/OCTATRACK_DRIVING.md, The rules), or `npm run device -- do ' + 'reload` if its changes may go' % (qualify.mem(qualify.PART, 1)[0] + 1, 'ABCDEFGHIJKLMNOP'[bank])) + if pick: + base = qualify.u32(qualify.BANK) + masks = [qualify.mem(base + pattern * PATTERN + track * TRACK, 8) for track in range(8)] + problem = pattern_problem(bank, pattern, busy_tracks(masks), pick) + if problem: problems.append(problem) + return problems + + +def midi_problem(address, connect=socket.create_connection, seconds=10): + """One harmless message through the MIDI bridge -> None, or why the soak would fail at its first operation.""" + host, _, port = address.rpartition(':') + start = 'start scripts/octatrack-midi-bridge.py %s on the computer the unit is plugged into (on Windows with the device venv\'s Python)' % port + try: + link = connect((host or '127.0.0.1', int(port)), 3) + except OSError as e: + return 'no MIDI bridge on %s (%s): %s' % (address, e, start) + try: + link.settimeout(seconds) # a bridge reopening the unit's port after a RAM boot answers within 5 s + link.sendall((TUNE_REQUEST + '\n').encode()) + reply = link.makefile().readline().strip() + except OSError as e: + reply = 'no answer (%s): another run may hold it' % e + finally: + link.close() + if reply.startswith('ok'): return None + return ('the MIDI bridge on %s cannot send: %s. Stop it and %s; a copy from before 25 November 2026 holds a dead port ' + 'after a RAM boot, so take this checkout\'s' % (address, reply or 'no answer', start)) + + +def main(): + ap = argparse.ArgumentParser(description='The unit steps\' preflight (docs/TEST_PROCEDURE.md).') + ap.add_argument('--pick-pattern', type=int, choices=range(1, 17), metavar='1-16', help='the empty pattern of the bank (device:price --pick-pattern)') + ap.add_argument('--midi', metavar='HOST:PORT', help='the MIDI bridge the soak sends through (octatrack-soak.mjs --midi)') + args = ap.parse_args() + problems = unit_problems(args.pick_pattern) + if args.midi: problems += [p for p in [midi_problem(args.midi)] if p] + for problem in problems: print('preflight: ' + problem, flush=True) + if not problems: print('preflight: ready', flush=True) + sys.exit(1 if problems else 0) + + +if __name__ == '__main__': + main() diff --git a/scripts/octatrack-price.mjs b/scripts/octatrack-price.mjs index c43cdc6682..639d3ec3c9 100644 --- a/scripts/octatrack-price.mjs +++ b/scripts/octatrack-price.mjs @@ -3,7 +3,9 @@ // Copyright (c) 2026 Jannik Aßfalg (repeat98) // What a module costs an Octatrack, measured on a unit: the frame interrupt's share, the CPU meter and both DSPs, // before the module, with it installed but used nowhere (at rest), and for an effect on one slot (in use). -// npm run device:price -- [--memory] [--out FILE.json] [--base ID --scene TEXT] [--seconds 8] [--slot T1] [--fx-name ID=NAME…] ID|FILE.mwrm… (none: every USB package) +// npm run device:price -- [--memory] [--out FILE.json] [--base ID --scene TEXT] [--seconds 8] [--readings 3] [--key-bus live|silent] [--slot T1] [--fx-name ID=NAME…] ID|FILE.mwrm… (none: every USB package) +// Each state (before, at rest, in use) is --readings readings of --seconds: the record keeps their means, the highest longest +// frame and DSP peak, and each figure's spread. --key-bus says whether the scene plays into the key bus a key-bus effect reads. // --curve T1,T3,T6,T7 [--pick-pattern 2] [--measure-pattern 1] [--admission-pattern N] [--limit 125] [--write-costs]: what the longest frame gains with the module on // 1, 2, 3… of those empty tracks (machines) or their slots (effects), each picked on the empty pattern and read on the busy one, // and the next-instance cost from it (curveFit: `first`, then `each`); it stops at the first skipped render or past --limit % (lower it @@ -11,11 +13,17 @@ // either regenerates frame-costs.json (as npm run modules:generate does), which admission charges. // --write (needs --base and --scene): each module measured cleanly gets its price in octamod.module.json (resources.cpuPrice) and // its readings in evidence/cpu-price.json, and leaves the pending list; modules:check recomputes the price from those readings. +// A module not listed yet gets them in its draft, sdk/drafts/, curve included (moduleFolder). // It needs a development twin of the base (the guard request) behind `npm run device -- serve --share // /tmp/modwerk-share.sock`, and the scene is the caller's: select the pattern, leave the transport stopped, and say in // the record which (--scene). The unit takes a module only while stopped, so each reading is STOP, PLAY, the reading, STOP, and a // reading during which `state` says stopped is refused and ends the run. The curve does not start when the module at rest plus // its booked first instance (frame-costs.json) reaches CURVE_ROOM on --measure-pattern: pick a pattern with room. +// The unit judges picks, and hushes machines while it plays, by the cost table the last v2 set sent, kept through rollbacks +// and power cycles. So a curve installs its module as a one-package set with this checkout's table, the module's `each` +// booked at 0 (measuringCosts): a booked guess must not refuse or hush the further instances the curve is there to read +// (Grain 0.1.3, 24 November 2026: each = first = 33.3 refused T3). Its first instance and the admission runs are judged as +// booked. After the rollback the same package goes once more with this checkout's own table, which the unit then keeps. // Each module runs as a trial that is rolled back; nothing is kept. Base-bound packages are left out: // a twin does not trust them (docs/OCTATRACK_DRIVING.md). // A machine's in-use cost is read only by --curve, as the only module of its trial (its row in the list is then the sixth). @@ -24,21 +32,40 @@ import { spawn } from 'node:child_process' import { createHash } from 'node:crypto' import { connect } from 'node:net' -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' -import { homedir } from 'node:os' -import { basename, dirname, resolve } from 'node:path' +import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs' +import { homedir, tmpdir } from 'node:os' +import { basename, dirname, relative, resolve } from 'node:path' import { parseArgs } from 'node:util' import { CPU_PRICE_PENDING_PATH, CPU_PRICE_RECORD, CURVE_ROOM, FRAME_COSTS_BASE_PATH, FRAME_COSTS_PATH, FRAME_COST_RECORD, frameCostsJson, generateFrameCosts, machineDescriptors, manifestJson, measuredPrice, curveProblem } from './module-cpu-price.mjs' import { takeUnitTurn } from './unit-queue.mjs' const mean = values => values.reduce((sum, value) => sum + value, 0) / values.length, tenth = value => Math.round(value * 10) / 10 -/** One reading from the session's `guard` line and `stats` lines: percent of a frame, percent of the meter, per mille of a DSP. */ +/** One reading from the session's `guard` line and `stats` lines: percent of a frame, percent of the meter, percent of a DSP. + * A `stats` line gives each core's mean and peak (status.c: the busiest frame of its last 1,024-frame window); the reading + * keeps the means' mean and the highest peak, since admission has to hold the worst block, not the average one. */ export function reading(text) { const guard = /frame max ([\d.]+) %, latest start ([\d.]+) %, in the frame interrupt ([\d.]+) % over (\d+) frames, skipped (\d+)/.exec(text) - const stats = [...text.matchAll(/stats cpu (\d+) T1-4 (\d+)\/\d+ T5-8 (\d+)\/\d+/g)] + const stats = [...text.matchAll(/stats cpu (\d+) T1-4 (\d+)\/(\d+) T5-8 (\d+)\/(\d+)/g)] if (!guard || !stats.length) throw new Error('No guard and stats reading in: ' + text.slice(0, 200)) + const meanOf = at => tenth(mean(stats.map(m => m[at] / 10))), peakOf = at => tenth(Math.max(...stats.map(m => m[at] / 10))) return { frame: Number(guard[3]), frameMax: Number(guard[1]), frames: Number(guard[4]), skipped: Number(guard[5]), - cpu: tenth(mean(stats.map(m => m[1] / 10))), dsp1to4: tenth(mean(stats.map(m => m[2] / 10))), dsp5to8: tenth(mean(stats.map(m => m[3] / 10))) } + cpu: meanOf(1), dsp1to4: meanOf(2), dsp5to8: meanOf(4), dsp1to4Peak: peakOf(3), dsp5to8Peak: peakOf(5) } +} +/** The figures a reading averages and the ones it keeps the highest of. */ +const MEANS = ['frame', 'cpu', 'dsp1to4', 'dsp5to8'], PEAKS = ['frameMax', 'dsp1to4Peak', 'dsp5to8Peak'] +/** Several readings of one state as one record: the means averaged, the peaks the highest any reading saw, `frames` summed, + * `skipped` and the allocation the last reading's (the guard counts skips since boot), and, from two readings on, `readings` + * and each figure's `spread` (highest less lowest), so a record shows how far its own readings agreed. One reading is + * returned as it is, as before 24 November 2026. */ +export function combined(readings) { + if (readings.length < 2) return readings[0] + const values = key => readings.map(item => item[key]).filter(value => typeof value === 'number') + const out = { ...readings.at(-1), frames: values('frames').reduce((sum, value) => sum + value, 0) } + for (const key of MEANS) if (values(key).length) out[key] = tenth(mean(values(key))) + for (const key of PEAKS) if (values(key).length) out[key] = Math.max(...values(key)) + out.readings = readings.length + out.spread = Object.fromEntries([...MEANS, ...PEAKS].filter(key => values(key).length).map(key => [key, tenth(Math.max(...values(key)) - Math.min(...values(key)))])) + return out } /** Tracked allocation only. The module pool and each DSP program arena have distinct units and capacities. */ export function allocationReading(text) { @@ -48,7 +75,6 @@ export function allocationReading(text) { if (!pool || !core1 || !core0) return { unavailable: 'The development base did not report the module pool and both DSP program arenas.' } return { modulePoolBytes: Number(pool[1]), dspProgramWordsT1to4: Number(core1[1]), dspProgramWordsT5to8: Number(core0[1]) } } -/** What the second reading added to the first, in points, one decimal. */ /** What went wrong with a pick, from the session's reply (device.mjs pick's errors), or null when the slot runs it. */ export const pickFailure = reply => /error|refused|not admitted|timed out/i.test(reply) ? reply.trim().split('\n').find(line => /error|refused|not admitted|timed out/i.test(line)).slice(0, 200) : null /** The session's `state` reply says the transport is stopped (device.mjs: "stopped" or "playing"). */ @@ -63,7 +89,24 @@ export function curveRoom({ atRest, booked, pattern }) { return atRest + booked < CURVE_ROOM ? null : `no room on pattern ${pattern}: it reads ${atRest} % with the module at rest, and its booked first instance ` + `${booked} would take it to ${tenth(atRest + booked)} %, past ${CURVE_ROOM} %. Pick a pattern with room with --measure-pattern (fewer sample tracks)` } -export const added = (before, after) => Object.fromEntries(['frame', 'cpu', 'dsp1to4', 'dsp5to8'].map(key => [key, tenth(after[key] - before[key])])) +/** The table a curve installs its module with: `list` (frame-costs.json) with `id`'s `each` at 0, so admission and the + * base's hush charge a further instance nothing while the curve reads what it costs, and its `first` and `rest` as booked. + * The run's --limit and its stop at a dropped render guard the unit, as for any reading. Null when `id` is not booked: + * the unit then charges it by its descriptor, as a module's first curve always was, and the unit's table is left alone. */ +export function measuringCosts(list, id) { + const cost = list?.costs?.[id] + if (!cost) return null + return { ...list, costs: { ...list.costs, [id]: { ...cost, each: 0 } } } +} +/** What the second reading added to the first, in points, one decimal: the means, and each core's peak where both have one + * (a reading taken before 24 November 2026 kept no peak). */ +export const added = (before, after) => Object.fromEntries([...MEANS, 'dsp1to4Peak', 'dsp5to8Peak'] + .filter(key => typeof before[key] === 'number' && typeof after[key] === 'number').map(key => [key, tenth(after[key] - before[key])])) +/** What the record says played: device:price reads with the sequencer playing; the key bus's input only when the caller named it. */ +export function priceInputs(keyBus) { + if (keyBus !== undefined && !['live', 'silent'].includes(keyBus)) throw new Error('--key-bus takes live (the scene plays into the key bus) or silent') + return keyBus ? { transport: 'playing', keyBus } : { transport: 'playing' } +} /** A file trial uses the package header for its name and slots (loader.c). Its runtime id * also identifies a published module when the filename is a version or was renamed. */ @@ -78,6 +121,9 @@ export function priceFileTarget(file, data, catalogue) { } const OVERLOAD = 125 // percent of a frame: no skips up to ~115 on an MKII, drops from ~120 (22 Nov 2026) +/** Readings a state by default (--readings): one 8-s reading could not tell a module's cost from the scene's own scatter + * (±2.5 points of the longest frame between two readings, REST_NOISE below), and its spread now says how far they agree. */ +export const READINGS = 3 /** What a module adds to the longest frame while installed on no track or slot (its `rest`), in percent: the reading * installed less the one before it. Under REST_NOISE it is the readings' own scatter (±2.5 between two 8-s readings of one * scene on the owner's MKII, 22 November 2026) and counts 0, since the base adds every installed module's rest to the @@ -103,46 +149,75 @@ export const stockFit = ({ empty, quiet, awake }) => ({ reserve: tenth(Math.max( export const machinePick = (track, row = 5) => `NO w200 ${track} w300 ${track} ${track} w500 LEFT w400 UP*12 w200 DOWN*${row} w200 YES w800 NO w300` export const machineToStatic = track => `NO w200 ${track} w300 ${track} ${track} w500 LEFT w400 UP*12 w200 YES w800 NO w300` -/** --write for one module's result: its price into its manifest, its readings beside it, its line off the pending list. What it did. */ -export function writePrice({ root, result, base, scene, seconds, measuredAt }) { - const id = result.id, folder = resolve(root, 'sdk/octatrack/modules', id), manifest = resolve(folder, 'octamod.module.json') - if (!existsSync(manifest)) return 'not written: no sdk/octatrack/modules/' + id - if (result.refused || !result.rolledBack || result.restore || result.inUseError || result.notPlayed || !result.atRestAdds) return 'not written: the run was not clean' - const text = readFileSync(manifest, 'utf8'), document = JSON.parse(text) - if (document.compatibility?.location === 'Track machine' || machineDescriptors({ root, id }).length) return 'not written: a machine\'s price is what one playing track adds ("machine-render"), read on a track (docs/MODULE_PERFORMANCE.md)' - if (document.compatibility?.effectId != null && !result.inUseAdds) return 'not written: an effect is priced on a slot too, and this run has no reading on one' - if (result.version !== 'file' && result.version !== document.version) return 'not written: this measured the published ' + result.version + ' but the manifest is ' + document.version + '; measure the new build\'s .mwrm' - const record = { module: id, version: document.version, base, scene, seconds, measuredAt, result } - mkdirSync(dirname(resolve(folder, CPU_PRICE_RECORD)), { recursive: true }) - writeFileSync(resolve(folder, CPU_PRICE_RECORD), JSON.stringify(record, null, 2) + '\n') +/** Where a module's records go: its listed folder, else its draft (sdk/drafts/), so a draft's price and curve travel with + * it into its release (Mackity, 25 November 2026, had both copied in by hand). Null when it has neither. */ +export function moduleFolder(root, id) { + for (const at of ['sdk/octatrack/modules', 'sdk/drafts']) if (existsSync(resolve(root, at, id, 'octamod.module.json'))) return resolve(root, at, id) + return null +} +/** One module's clean result as its price: { record } for CPU_PRICE_RECORD and { cpuPrice } for resources.cpuPrice, or + * { problem } saying why not. Writes nothing (module:qualify drafts from it too). */ +export function priceRecord({ document, result, base, scene, seconds, measuredAt, readings = 1, inputs, machine = false }) { + if (result.refused || !result.rolledBack || result.restore || result.inUseError || result.notPlayed || !result.atRestAdds) return { problem: 'the run was not clean' } + if (document.compatibility?.location === 'Track machine' || machine) return { problem: 'a machine\'s price is what one playing track adds ("machine-render"), read on a track (docs/MODULE_PERFORMANCE.md)' } + if (document.compatibility?.effectId != null && !result.inUseAdds) return { problem: 'an effect is priced on a slot too, and this run has no reading on one' } + if (result.version !== 'file' && result.version !== document.version) return { problem: 'this measured the published ' + result.version + ' but the manifest is ' + document.version + '; measure the new build\'s .mwrm' } + const record = { module: document.id, version: document.version, base, scene, ...(inputs ? { inputs } : {}), seconds, ...(readings > 1 ? { readings } : {}), measuredAt, result } const { before, atRest, inUse } = result - document.resources.cpuPrice = { value: measuredPrice(result), unit: 'percent-of-frame', measure: 'frame-interrupt', tool: 'npm run device:price -- --write', date: measuredAt.slice(0, 10), - conditions: (scene + '; base ' + base + '; ' + seconds + ' s per reading. Frame interrupt ' + before.frame + ' % before, ' + atRest.frame + ' % installed and used nowhere' + (inUse ? ', ' + inUse.frame + ' % on ' + result.inUseOn : '') + + const cpuPrice = { value: measuredPrice(result), unit: 'percent-of-frame', measure: 'frame-interrupt', tool: 'npm run device:price -- --write', date: measuredAt.slice(0, 10), + conditions: (scene + '; base ' + base + '; ' + (readings > 1 ? readings + ' readings of ' + seconds + ' s a state' : seconds + ' s per reading') + '. Frame interrupt ' + before.frame + ' % before, ' + atRest.frame + ' % installed and used nowhere' + (inUse ? ', ' + inUse.frame + ' % on ' + result.inUseOn : '') + '; CPU meter ' + before.cpu + ' % before, ' + atRest.cpu + ' % at rest' + (inUse ? ', ' + inUse.cpu + ' % in use' : '') + '.').slice(0, 1000), source: CPU_PRICE_RECORD } + return { record, cpuPrice } +} +/** One module's clean curve as its FRAME_COST_RECORD, or { problem }. `wanted`: how many tracks the run asked for. Writes nothing. */ +export function curveRecord({ result, version, base, scene, seconds, measuredAt, wanted = 3 }) { + const { first, each, adds, tracks, notes, points, admission } = result.curve + // Fewer than three placed is fine when the curve stopped at overload: the module costs what it measured up to there. + const overloaded = notes.some(note => note.startsWith('stopped after')) + if ((tracks.length < Math.min(3, wanted) && !overloaded) || !tracks.length || !result.rolledBack || result.restore || result.notPlayed) return { problem: 'fewer than three instances, or the run was not clean' } + if (result.version !== 'file' && result.version !== version) return { problem: 'this measured the published ' + result.version + ' but the manifest is ' + version } + return { record: { module: result.id, version, base, scene, seconds, measuredAt, tracks, rest: restCost(result.before, result.atRest), first, each, points, adds, admission, notes } } +} + +/** --write for one module's result: its price into its manifest, its readings beside it, its line off the pending list. What it did. + * A draft (sdk/drafts/) gets the same as a listed module. */ +export function writePrice({ root, result, base, scene, seconds, measuredAt, readings = 1, inputs }) { + const id = result.id, folder = moduleFolder(root, id) + if (!folder) return 'not written: no sdk/octatrack/modules/' + id + ' or sdk/drafts/' + id + const manifest = resolve(folder, 'octamod.module.json'), text = readFileSync(manifest, 'utf8'), document = JSON.parse(text) + const made = priceRecord({ document, result, base, scene, seconds, measuredAt, readings, inputs, machine: machineDescriptors({ root, id }).length > 0 }) + if (made.problem) return 'not written: ' + made.problem + mkdirSync(dirname(resolve(folder, CPU_PRICE_RECORD)), { recursive: true }) + writeFileSync(resolve(folder, CPU_PRICE_RECORD), JSON.stringify(made.record, null, 2) + '\n') + document.resources.cpuPrice = made.cpuPrice // shortcut: a hand-formatted manifest (an object on one line) comes back as plain two-space JSON; keep it if review asks. // modules:check strips the price with the same serialiser to see that nothing else changed (manifestWithoutPrice). writeFileSync(manifest, manifestJson(document, text)) const pendingPath = resolve(root, CPU_PRICE_PENDING_PATH), pending = existsSync(pendingPath) ? JSON.parse(readFileSync(pendingPath, 'utf8')) : null const wasPending = Boolean(pending?.pending?.[id]) if (wasPending) { delete pending.pending[id]; writeFileSync(pendingPath, JSON.stringify(pending, null, 1) + '\n') } - return 'wrote ' + document.resources.cpuPrice.value + ' % of a frame into octamod.module.json and its readings into ' + CPU_PRICE_RECORD + (wasPending ? ', and took it off the pending list' : '') + return 'wrote ' + document.resources.cpuPrice.value + ' % of a frame into ' + relative(root, manifest) + ' and its readings into ' + CPU_PRICE_RECORD + (wasPending ? ', and took it off the pending list' : '') } if (import.meta.filename === process.argv[1]) { const { values: args, positionals } = parseArgs({ allowPositionals: true, options: { out: { type: 'string' }, seconds: { type: 'string', default: '8' }, slot: { type: 'string', default: 'T1' }, 'fx-name': { type: 'string', multiple: true }, base: { type: 'string' }, scene: { type: 'string' }, write: { type: 'boolean' }, memory: { type: 'boolean' }, - curve: { type: 'string' }, 'pick-pattern': { type: 'string', default: '2' }, 'measure-pattern': { type: 'string', default: '1' }, 'admission-pattern': { type: 'string' }, limit: { type: 'string', default: String(OVERLOAD) }, 'write-costs': { type: 'boolean' }, stock: { type: 'boolean' }, socket: { type: 'string', default: process.env.MODWERK_DEV_SOCKET ?? '/tmp/modwerk-dev.sock' }, share: { type: 'string', default: '/tmp/modwerk-share.sock' } } }) + curve: { type: 'string' }, 'pick-pattern': { type: 'string', default: '2' }, 'measure-pattern': { type: 'string', default: '1' }, 'admission-pattern': { type: 'string' }, limit: { type: 'string', default: String(OVERLOAD) }, 'write-costs': { type: 'boolean' }, stock: { type: 'boolean' }, socket: { type: 'string', default: process.env.MODWERK_DEV_SOCKET ?? '/tmp/modwerk-dev.sock' }, share: { type: 'string', default: '/tmp/modwerk-share.sock' }, + readings: { type: 'string', default: String(READINGS) }, 'key-bus': { type: 'string' } } }) // Admission is judged on the bank's medium pattern, the curve read on one with room (owner, 23 November 2026): by default the same. const admissionPattern = args['admission-pattern'] ?? args['measure-pattern'] const root = resolve(import.meta.dirname, '..'), seconds = Number(args.seconds), measuredAt = new Date().toISOString() + const readings = Number(args.readings), inputs = priceInputs(args['key-bus']) + if (!Number.isInteger(readings) || readings < 1 || readings > 9) throw new Error('--readings takes 1 to 9 readings a state') const fxNames = new Map((args['fx-name'] ?? []).map(pair => { const at = pair.indexOf('='); if (at < 1) throw new Error('--fx-name takes ID=NAME, the name the FX chooser shows'); return [pair.slice(0, at), pair.slice(at + 1)] })) if ((args.write || args['write-costs']) && !(args.base && args.scene)) throw new Error('--write and --write-costs need --base and --scene: the price names the base and what played (model, project, pattern)') if (args['write-costs'] && !args.curve && !args.stock) throw new Error('--write-costs writes a curve (--curve T1,T3,T6,T7) or the stock reserve (--stock)') // --write with --curve also writes each effect's or machine's curve: its evidence/frame-cost.json and its frame-costs.json line. const catalogue = JSON.parse(readFileSync(resolve(root, 'src/engine/assets/octatrack-module-packages.json'), 'utf8')).packages // What admission charges a module's first instance now (frame-costs.json): the curve needs that much room to be read. - const booked = existsSync(resolve(root, FRAME_COSTS_PATH)) ? JSON.parse(readFileSync(resolve(root, FRAME_COSTS_PATH), 'utf8')).costs ?? {} : {} + const costList = existsSync(resolve(root, FRAME_COSTS_PATH)) ? JSON.parse(readFileSync(resolve(root, FRAME_COSTS_PATH), 'utf8')) : null + const booked = costList?.costs ?? {} const bookedFirst = id => booked[id]?.first // An ID is a catalogue row; a path to a .mwrm is that file, for a build that is not published yet. In the order given. const files = positionals.filter(name => name.endsWith('.mwrm')), ids = positionals.filter(name => !name.endsWith('.mwrm')) @@ -153,23 +228,30 @@ if (import.meta.filename === process.argv[1]) { : catalogue.filter(row => !row.requiredBase) // All the readings are one turn on the unit (scripts/unit-queue.mjs); the trials below run inside it. await takeUnitTurn({ note: 'device:price ' + chosen.map(row => row.id).join(' ').slice(0, 100), command: 'npm run device:price -- ' + process.argv.slice(2).join(' ').slice(0, 300), - expectMs: Math.max(10, 3 * chosen.length) * 60000 }) + expectMs: Math.max(10, (2 + readings) * chosen.length) * 60000 }) const wait = ms => new Promise(done => setTimeout(done, ms)) const send = line => new Promise((done, fail) => { // one line to the session, its whole reply let reply = ''; const socket = connect(args.socket, () => socket.write(line + '\n')) socket.setTimeout(30000, () => socket.destroy(new Error('The session did not answer "' + line + '" in 30 s.'))) socket.on('data', chunk => { reply += chunk }).on('end', () => done(reply)).on('error', fail) }) - const measure = async () => { // playing: a new guard window, then its mean beside three meter readings - // STOP first: PLAY on a unit that is already playing pauses it, and that reading would be the stopped frame (frame 24 %, - // longest 32 % where the pattern plays at 75 %: the first module of a run read a false rest of 13 to 18, 23 November 2026). - await send('STOP w500 PLAY w2000 guard') - let text = '', stopped = 0 - for (let i = 0; i < 3; i++) { await wait(seconds * 1000 / 3); text += await send('stats'); if (!notPlaying(await send('state'))) continue; stopped++ } - const text2 = await send('guard') - await send('STOP w500') - if (stopped) throw new NotPlayed(`the transport was stopped at ${stopped} of 3 checks during a reading, so it measured no pattern: nothing was priced`) - const load = reading(text2 + text) + // `count` readings of one state (--readings for the before, at-rest and in-use states; the curve, the admission runs and + // --stock take one a point). Each is STOP, PLAY, a new guard window, a meter reading about every second, the window, STOP. + // STOP first: PLAY on a unit that is already playing pauses it, and that reading would be the stopped frame (frame 24 %, + // longest 32 % where the pattern plays at 75 %: the first module of a run read a false rest of 13 to 18, 23 November 2026). + const measure = async (count = 1) => { + const taken = [] + for (let n = 0; n < count; n++) { + await send('STOP w500 PLAY w2000 guard') + let text = '', stopped = 0 + const samples = Math.max(3, Math.round(seconds)) + for (let i = 0; i < samples; i++) { await wait(seconds * 1000 / samples); text += await send('stats'); if (notPlaying(await send('state'))) stopped++ } + const text2 = await send('guard') + await send('STOP w500') + if (stopped) throw new NotPlayed(`the transport was stopped at ${stopped} of ${samples} checks during a reading, so it measured no pattern: nothing was priced`) + taken.push(reading(text2 + text)) + } + const load = combined(taken) if (!args.memory) return load try { return { ...load, allocation: allocationReading(await send('memory')) } @@ -293,8 +375,12 @@ if (import.meta.filename === process.argv[1]) { const packagePath = row.file ?? resolve(root, 'public', row.path) const packageSha256 = createHash('sha256').update(readFileSync(packagePath)).digest('hex') if (row.sha256 && packageSha256 !== row.sha256) throw new Error('Package SHA-256 differs from the release catalogue for ' + row.id) - const trigs = await patternTrigs(), before = await measure(), result = { id: row.id, version: row.version, packageSha256, before } - const trial = spawn(process.execPath, [resolve(root, 'scripts/device.mjs'), 'try', packagePath, '--seconds', '600', '--socket', args.share]) + const trigs = await patternTrigs(), before = await measure(readings), result = { id: row.id, version: row.version, packageSha256, before } + // A curve: one-package set with the measuring table (measuringCosts, the header); otherwise a plain trial, which sends none. + const measuring = args.curve ? measuringCosts(costList, row.id) : null, costsFile = resolve(tmpdir(), `modwerk-price-costs-${process.pid}.json`) + if (measuring) writeFileSync(costsFile, JSON.stringify(measuring)) + const device = (...rest) => spawn(process.execPath, [resolve(root, 'scripts/device.mjs'), ...rest, '--socket', args.share]) + const trial = measuring ? device('set', packagePath, '--costs', costsFile, '--seconds', '600') : device('try', packagePath, '--seconds', '600') let log = ''; trial.stdout.on('data', chunk => { log += chunk }); trial.stderr.on('data', chunk => { log += chunk }) const ended = new Promise(done => trial.on('exit', done)) // A large package uploads for a minute: wait for the trial or the try's own end, never cut an upload short @@ -310,7 +396,7 @@ if (import.meta.filename === process.argv[1]) { } if (!result.refused) try { await wait(2000) - result.atRest = await measure(); result.atRestAdds = added(before, result.atRest) + result.atRest = await measure(readings); result.atRestAdds = added(before, result.atRest) const fx = { fx1: '1', fx2: '2', both: '2' }[row.slots] if (fx) try { // an effect: on the slot, measured, and the slot's own effect picked back const was = (await slotNames())[Number(fx)] @@ -319,7 +405,7 @@ if (import.meta.filename === process.argv[1]) { // package "SC Ringmod"): --fx-name ID=NAME names it. A pick that fails must not be measured as the effect in use. const name = fxNames.get(row.id) ?? row.name, failed = pickFailure(await send(`pick:${args.slot}:FX${fx}:${name.replaceAll(' ', '_')}`)) if (failed) throw new Error('picking ' + name + ': ' + failed) - result.inUse = await measure(); result.inUseAdds = added(before, result.inUse); result.inUseOn = args.slot + ' FX' + fx + result.inUse = await measure(readings); result.inUseAdds = added(before, result.inUse); result.inUseOn = args.slot + ' FX' + fx const back = await send(`pick:${args.slot}:FX${fx}:${was.replaceAll(' ', '_')}`) if (/error|refus|timed out/i.test(back)) result.restore = 'picking ' + was + ' back: ' + back.trim().slice(0, 120) } catch (error) { result.inUseError = error.message.slice(0, 200) } @@ -336,20 +422,30 @@ if (import.meta.filename === process.argv[1]) { trial.kill('SIGINT') // rolls the trial back await ended result.rolledBack = /rolled back/.test(log) || Boolean(result.refused) // a refused module was never in - if ((await patternTrigs()) !== trigs) result.restore = 'it wrote trigs into pattern ' + [...new Set([args['pick-pattern'], args['measure-pattern'], admissionPattern])].join(' or ') + - ', which its rollback left: clear them (or reload the project without saving) and measure it on a scratch pattern' + // The measuring table outlives the rollback: offer the package once more with this checkout's table and roll it back a second later. + if (measuring && /frame costs/.test(log)) { + let back = ''; const again = device('set', packagePath, '--seconds', '1') + again.stdout.on('data', chunk => { back += chunk }); again.stderr.on('data', chunk => { back += chunk }) + await new Promise(done => again.on('exit', done)) + if (!/frame costs/.test(back) || !/rolled back/.test(back)) result.restore = `the unit may still judge ${row.id} by the measuring table (each 0): ` + + `put this checkout's table back with npm run device -- set ${packagePath} --seconds 1 --socket ${args.share}` + } + if (measuring) try { unlinkSync(costsFile) } catch { /* already gone */ } + // Both can be needed: keep the table note when the trigs note follows it. + if ((await patternTrigs()) !== trigs) result.restore = [result.restore, 'it wrote trigs into pattern ' + [...new Set([args['pick-pattern'], args['measure-pattern'], admissionPattern])].join(' or ') + + ', which its rollback left: clear them (or reload the project without saving) and measure it on a scratch pattern'].filter(Boolean).join('; and ') results.push(result) // Written after every module: a unit that hangs on the next one must not take the finished readings with it. - if (args.out) writeFileSync(args.out, JSON.stringify({ base: args.base, scene: args.scene, seconds, slot: args.slot, measuredAt, results }, null, 1) + '\n') + if (args.out) writeFileSync(args.out, JSON.stringify({ base: args.base, scene: args.scene, inputs, seconds, readings, slot: args.slot, measuredAt, results }, null, 1) + '\n') const signed = value => (value >= 0 ? '+' : '') + value if (result.notPlayed) console.log(row.id.padEnd(28) + 'NOT MEASURED: ' + result.notPlayed + '. Stopped; check that the pattern plays (npm run device -- state) and run it again') else console.log(row.id.padEnd(28) + (result.refused ? 'not installed: ' + result.refused : `at rest frame ${signed(result.atRestAdds.frame)}, cpu ${signed(result.atRestAdds.cpu)}` + - (result.inUseAdds ? `; in use frame ${signed(result.inUseAdds.frame)}, cpu ${signed(result.inUseAdds.cpu)}, DSP ${signed(result.inUseAdds.dsp1to4)}/${signed(result.inUseAdds.dsp5to8)}` : '') + (result.inUseError ? '; in use: ' + result.inUseError : '') + + (result.inUseAdds ? `; in use frame ${signed(result.inUseAdds.frame)}, cpu ${signed(result.inUseAdds.cpu)}, DSP ${signed(result.inUseAdds.dsp1to4)}/${signed(result.inUseAdds.dsp5to8)}` + (result.inUseAdds.dsp1to4Peak === undefined ? '' : ` (peak ${signed(result.inUseAdds.dsp1to4Peak)}/${signed(result.inUseAdds.dsp5to8Peak)})`) : '') + (result.inUseError ? '; in use: ' + result.inUseError : '') + (result.restore ? '; ' + result.restore : '') + (result.rolledBack ? '' : '; THE TRIAL DID NOT ROLL BACK: stop and look'))) if (!result.rolledBack || result.restore || result.notPlayed) break // never go on over a unit left in a state nobody chose } - if (args.out) writeFileSync(args.out, JSON.stringify({ base: args.base, scene: args.scene, seconds, slot: args.slot, measuredAt, results }, null, 1) + '\n') - if (args.write) for (const result of results) console.log(result.id.padEnd(28) + writePrice({ root, result, base: args.base, scene: args.scene, seconds, measuredAt })) + if (args.out) writeFileSync(args.out, JSON.stringify({ base: args.base, scene: args.scene, inputs, seconds, readings, slot: args.slot, measuredAt, results }, null, 1) + '\n') + if (args.write) for (const result of results) console.log(result.id.padEnd(28) + writePrice({ root, result, base: args.base, scene: args.scene, seconds, measuredAt, readings, inputs })) for (const result of results.filter(result => result.curve && !result.curve.error)) { const { first, each, adds, tracks, notes } = result.curve, wanted = args.curve.split(',').length const rest = restCost(result.before, result.atRest) @@ -359,19 +455,18 @@ if (import.meta.filename === process.argv[1]) { (problem ? '\n' + ''.padEnd(28) + 'NOT RELEASABLE: ' + problem : '')) if (problem) process.exitCode = 1 // the test procedure's step 9 stops here: this build does not carry a release if (!args['write-costs'] && !args.write) continue - // Fewer than three placed is fine when the curve stopped at overload: the module costs what it measured up to there. - const overloaded = notes.some(note => note.startsWith('stopped after')) - if ((tracks.length < Math.min(3, wanted) && !overloaded) || !tracks.length || !result.rolledBack || result.restore || result.notPlayed) { console.log(result.id.padEnd(28) + 'curve not written: fewer than three instances, or the run was not clean'); continue } - const manifestPath = resolve(root, 'sdk/octatrack/modules', result.id, 'octamod.module.json') - const version = existsSync(manifestPath) ? JSON.parse(readFileSync(manifestPath, 'utf8')).version : result.version - if (result.version !== 'file' && result.version !== version) { console.log(result.id.padEnd(28) + 'curve not written: this measured the published ' + result.version + ' but the manifest is ' + version); continue } + // A listed module's folder, else its draft's: the curve travels with the draft (moduleFolder). + const folder = moduleFolder(root, result.id) + const version = folder ? JSON.parse(readFileSync(resolve(folder, 'octamod.module.json'), 'utf8')).version : result.version + const made = curveRecord({ result, version, base: args.base, scene: args.scene, seconds, measuredAt, wanted }) + if (made.problem) { console.log(result.id.padEnd(28) + 'curve not written: ' + made.problem); continue } const measured = `${result.id} ${version} on ${tracks.join(' ')}: ${args.scene}; base ${args.base}; ${seconds} s a reading; ${measuredAt.slice(0, 10)} (npm run device:price -- --curve)` let wrote - if (args.write && existsSync(manifestPath)) { // the release's own record, which module:doctor and modules:check hold its version to - const record = resolve(root, 'sdk/octatrack/modules', result.id, FRAME_COST_RECORD) + if (args.write && folder) { // the release's own record, which module:doctor and modules:check hold its version to + const record = resolve(folder, FRAME_COST_RECORD) mkdirSync(dirname(record), { recursive: true }) - writeFileSync(record, JSON.stringify({ module: result.id, version, base: args.base, scene: args.scene, seconds, measuredAt, tracks, rest, first, each, points: result.curve.points, adds, admission: result.curve.admission, notes }, null, 2) + '\n') - wrote = 'wrote first ' + first + ', each ' + each + ' into ' + FRAME_COST_RECORD + writeFileSync(record, JSON.stringify(made.record, null, 2) + '\n') + wrote = 'wrote first ' + first + ', each ' + each + ' into ' + relative(root, record) } else { // --write-costs: the base's own list (a base-bound module, or the base owner's reading of a published version) const path = resolve(root, FRAME_COSTS_BASE_PATH), list = JSON.parse(readFileSync(path, 'utf8')) writeFileSync(path, frameCostsJson({ ...list, costs: { ...list.costs, [result.id]: { rest, first, each, points: adds, measured } } })) diff --git a/scripts/octatrack-price.test.mjs b/scripts/octatrack-price.test.mjs index d57153d3d3..f74034b3fe 100644 --- a/scripts/octatrack-price.test.mjs +++ b/scripts/octatrack-price.test.mjs @@ -2,7 +2,8 @@ // Copyright (c) 2026 Jannik Aßfalg (repeat98) import { expect, it } from 'vitest' import { createHash } from 'node:crypto' -import { added, allocationReading, curveFit, curveRoom, notPlaying, restCost, REST_NOISE, machinePick, stockFit, machineToStatic, pickFailure, priceFileTarget, reading, writePrice } from './octatrack-price.mjs' +import { frameCostTable } from '../src/engine/elekloader/set-package.ts' +import { added, allocationReading, combined, curveFit, curveRoom, measuringCosts, notPlaying, priceInputs, restCost, REST_NOISE, machinePick, stockFit, machineToStatic, pickFailure, priceFileTarget, reading, writePrice } from './octatrack-price.mjs' function runtimeEffect(slots) { const data = Buffer.alloc(76) @@ -33,13 +34,36 @@ it('finds a published package by runtime id even when its file is named after th it('reads the guard window and the mean of the meter readings, and what a module added', () => { const guard = share => `frame max 112.2 %, latest start 12.2 %, in the frame interrupt ${share} % over 22000 frames, skipped 2 on T1 T3, share 80.0 %\n` - const before = reading(guard('41.1') + 'stats cpu 640 T1-4 328/338 T5-8 419/420 passes 1.0 2.0\nstats cpu 660 T1-4 330/338 T5-8 419/420 passes 1.0 2.0\n') - expect(before).toEqual({ frame: 41.1, frameMax: 112.2, frames: 22000, skipped: 2, cpu: 65, dsp1to4: 32.9, dsp5to8: 41.9 }) + const before = reading(guard('41.1') + 'stats cpu 640 T1-4 328/338 T5-8 419/420 passes 1.0 2.0\nstats cpu 660 T1-4 330/352 T5-8 419/420 passes 1.0 2.0\n') + expect(before).toEqual({ frame: 41.1, frameMax: 112.2, frames: 22000, skipped: 2, cpu: 65, dsp1to4: 32.9, dsp5to8: 41.9, dsp1to4Peak: 35.2, dsp5to8Peak: 42 }) const after = reading(guard('64.5') + 'stats cpu 750 T1-4 428/438 T5-8 419/420 passes 1.0 2.0\n') - expect(added(before, after)).toEqual({ frame: 23.4, cpu: 10, dsp1to4: 9.9, dsp5to8: 0 }) + expect(added(before, after)).toEqual({ frame: 23.4, cpu: 10, dsp1to4: 9.9, dsp5to8: 0, dsp1to4Peak: 8.6, dsp5to8Peak: 0 }) expect(() => reading('stats cpu 1 T1-4 1/1 T5-8 1/1')).toThrow('No guard') }) +it('keeps no peak in what a module added when the reading before it kept none (a record from before the peaks)', () => { + const old = { frame: 41, frameMax: 74.2, cpu: 60.5, dsp1to4: 38.4, dsp5to8: 45.6 } + expect(added(old, { ...old, dsp1to4: 45.9, dsp1to4Peak: 50, dsp5to8Peak: 47 })).toEqual({ frame: 0, cpu: 0, dsp1to4: 7.5, dsp5to8: 0 }) +}) + +it('takes several readings of one state as one: means averaged, peaks the highest, and how far they spread', () => { + const one = (frame, frameMax, dsp1to4, dsp1to4Peak, skipped) => ({ frame, frameMax, frames: 22000, skipped, cpu: 60, dsp1to4, dsp5to8: 40, dsp1to4Peak, dsp5to8Peak: 44 }) + const a = one(41, 74.2, 45.9, 52.1, 0) + expect(combined([a])).toBe(a) // one reading is the record it always was: no count, no spread + expect(combined([a, one(41.4, 76.9, 46.3, 58.4, 0), one(40.9, 75, 45.6, 51, 1)])).toEqual({ + frame: 41.1, frameMax: 76.9, frames: 66000, skipped: 1, cpu: 60, dsp1to4: 45.9, dsp5to8: 40, dsp1to4Peak: 58.4, dsp5to8Peak: 44, + readings: 3, spread: { frame: 0.5, cpu: 0, dsp1to4: 0.7, dsp5to8: 0, frameMax: 2.7, dsp1to4Peak: 7.4, dsp5to8Peak: 0 }, + }) + const allocation = { modulePoolBytes: 0, dspProgramWordsT1to4: 1, dspProgramWordsT5to8: 2 } + expect(combined([a, { ...a, allocation }]).allocation).toEqual(allocation) // the last reading's, read after them +}) + +it('records what played: the transport always, the key bus only when the caller says', () => { + expect(priceInputs(undefined)).toEqual({ transport: 'playing' }) + expect(priceInputs('live')).toEqual({ transport: 'playing', keyBus: 'live' }) + expect(() => priceInputs('on')).toThrow(/--key-bus takes live/) +}) + it('records the module pool and each DSP program arena in their own units', () => { const report = [ 'pool: 128 of 10912 bytes used; free 10784, largest free run 10784 (100 % of free)', @@ -76,6 +100,10 @@ it('writes a clean reading as the module\'s price, its readings beside it, and t expect(price.conditions).toBe('MKII, bank C pattern C01; base 945cc074; 8 s per reading. Frame interrupt 30.1 % before, 30.3 % installed and used nowhere, 31.4 % on T1 FX2; CPU meter 50 % before, 50.2 % at rest, 51 % in use.') expect(JSON.parse(readFileSync(join(root, 'sdk/octatrack/modules/echo/evidence/cpu-price.json'), 'utf8'))).toMatchObject({ module: 'echo', version: '0.2.0', base: '945cc074', result: { inUseAdds: { frame: 1.3 } } }) expect(JSON.parse(readFileSync(join(root, 'sdk/module-cpu-prices-pending.json'), 'utf8')).pending).toEqual({ other: 'price not yet measured' }) + // Three readings a state and a named key bus: the record says so, and so do the price's conditions. + expect(writePrice({ root, result, base: '945cc074', scene: 'MKII, bank C pattern C01', seconds: 8, measuredAt: '2026-11-24T10:00:00.000Z', readings: 3, inputs: priceInputs('live') })).toMatch(/1.3 % of a frame/) + expect(JSON.parse(readFileSync(manifest, 'utf8')).resources.cpuPrice.conditions).toMatch(/^MKII, bank C pattern C01; base 945cc074; 3 readings of 8 s a state\. Frame interrupt 30.1 % before/) + expect(JSON.parse(readFileSync(join(root, 'sdk/octatrack/modules/echo/evidence/cpu-price.json'), 'utf8'))).toMatchObject({ readings: 3, inputs: { transport: 'playing', keyBus: 'live' }, seconds: 8 }) writeFileSync(manifest, JSON.stringify({ id: 'echo', version: '0.2.0', compatibility: { location: 'Track machine' }, resources: {} })) expect(write({})).toMatch(/machine-render/) } finally { rmSync(root, { recursive: true, force: true }) } @@ -138,3 +166,17 @@ it('stops the curve before it starts when the booked first instance leaves no ro // A module nothing books yet: its first reading decides (curveProblem judges it). expect(curveRoom({ atRest: 95, booked: undefined, pattern: '1' })).toBeNull() }) + +it('reads a curve with the module\'s each booked at 0 and every other figure as booked', () => { + const list = { about: 'x', stock: { line: 95 }, costs: { grain: { first: 33.3, each: 33.3, rest: 0, points: [33.3] }, amiga: { first: 26.6, each: 4, rest: 0.1 } } } + const measuring = measuringCosts(list, 'grain') + expect(measuring.costs.grain).toEqual({ first: 33.3, each: 0, rest: 0, points: [33.3] }) + expect(measuring.costs.amiga).toBe(list.costs.amiga) + expect(measuring.stock).toBe(list.stock) + expect(list.costs.grain.each).toBe(33.3) // the checkout's table is not changed + // What the unit is sent: a further instance adds 0 per mille, the first still its booked 33.3 (wake). + expect(frameCostTable({ grain: measuring.costs.grain }, null)).toEqual([{ module: frameCostTable({ grain: list.costs.grain }, null)[0].module, use: 0, wake: 333, rest: 0 }]) + // Unbooked: the unit charges it by its descriptor, and its table is left alone. + expect(measuringCosts(list, 'syntiz')).toBeNull() + expect(measuringCosts(null, 'grain')).toBeNull() +}) diff --git a/scripts/octatrack-step-base.mjs b/scripts/octatrack-step-base.mjs index 742b4c166a..9c4d5314bd 100644 --- a/scripts/octatrack-step-base.mjs +++ b/scripts/octatrack-step-base.mjs @@ -21,6 +21,30 @@ export function stageRefusal(what, bytes, capacity, flashed = false) { 'then boot and flash this base from it (docs/OCTATRACK_TWO_SLOT_BASE.md).' } +/** Starts of an unconfirmed slot before the boot stub goes back to the other (slots.h SLOT_TRIES). */ +const SLOT_TRIES = 2 +/** What a RAM boot would cost a base update flashed into the newest slot and not yet confirmed (the SLOTS reply, + * upload-usb.ts parseBaseSlots), or undefined when it costs nothing. Every restart, a RAM boot's soft reset included, + * runs the boot stub, which spends one of that slot's starts (stub.c, slots.c slot_pick); the base confirms its slot + * only after 15 s up from it with a computer connected (flash.c confirm). With its starts spent the unit goes back to + * the previous base, UPDATE UNDONE: on 20 November 2026 a site update not yet confirmed was lost to a developer's + * RAM boots. `wait`: the update itself is running, so it confirms itself while this computer talks to it. */ +export function bootOverPendingUpdate(slots) { + if (slots?.layout !== 'two') return undefined + const [a, b] = slots.slots + const n = a.whole && b.whole ? (b.generation > a.generation ? 1 : 0) : a.whole ? 0 : b.whole ? 1 : -1 + if (n < 0 || slots.slots[n].confirmed || slots.slots[n].tries > SLOT_TRIES) return undefined + const slot = 'AB'[n], left = SLOT_TRIES - slots.slots[n].tries, override = ' To boot anyway, add --spend-tries.' + if (slots.running === n) return { wait: true, refusal: `The base update in slot ${slot} runs but has not confirmed itself (15 s after its start, ` + + `with a computer connected). A RAM boot now spends ${left ? `one of its ${left} start${left > 1 ? 's' : ''} left` : 'it: it has no start left'}, ` + + `and with none left the Octatrack goes back to the previous base. Leave it on for a moment, then boot again.${override}` } + if (!left) return { warning: `The base update in slot ${slot} has no start left, so whatever restarts next goes back to the previous base. ` + + 'Install it again from modwerk.app afterwards.' } + return { refusal: `The base update in slot ${slot} is not confirmed yet (${SLOT_TRIES - left} of its ${SLOT_TRIES} starts used). Every restart, ` + + 'a RAM boot included, spends one, and with none left the Octatrack goes back to the previous base. Power-cycle it so the update ' + + `starts from its slot, keep USB connected for 15 s (npm run device -- status then shows it confirmed), and boot again.${override}` } +} + /** The step base's build folder from the user's own OS 1.40C: NOT_FLASH_CANDIDATE.bin, MAIN.raw and proofs.json with * its identity, as `npm run device -- boot` and `flash` read them. Refuses assets that drifted from their pins and a * build that is not the published step base. */ diff --git a/scripts/octatrack-step-base.test.mjs b/scripts/octatrack-step-base.test.mjs index 3a5926d5a3..19f8a0fec4 100644 --- a/scripts/octatrack-step-base.test.mjs +++ b/scripts/octatrack-step-base.test.mjs @@ -1,7 +1,48 @@ import { spawnSync } from 'node:child_process' import { join } from 'node:path' import { describe, expect, it } from 'vitest' -import { stageRefusal } from './octatrack-step-base.mjs' +import { bootOverPendingUpdate, stageRefusal } from './octatrack-step-base.mjs' + +// SLOTS as upload-usb.ts parseBaseSlots gives them: slot A the confirmed old base, slot B the newer update. +const slots = (b, running = null) => ({ layout: 'two', running, fellBack: false, confirmed: false, slots: [ + { generation: 6, whole: true, confirmed: true, tries: 1 }, { generation: 7, whole: true, confirmed: false, tries: 0, ...b }] }) + +describe('bootOverPendingUpdate', () => { + it('lets the boot go when nothing is pending', () => { + expect(bootOverPendingUpdate(undefined)).toBeUndefined() // a base before the two slots + expect(bootOverPendingUpdate(null)).toBeUndefined() // before the base's first look + expect(bootOverPendingUpdate({ layout: 'one', running: null, fellBack: false, confirmed: false, slots: [] })).toBeUndefined() + expect(bootOverPendingUpdate(slots({ confirmed: true, tries: 1 }, 1))).toBeUndefined() + expect(bootOverPendingUpdate(slots({ tries: 3 }, 0))).toBeUndefined() // already went back: UPDATE UNDONE + expect(bootOverPendingUpdate(slots({ whole: false }, 0))).toBeUndefined() // a cut write never counts + }) + it('refuses over an update written and not yet started, and says how to confirm it', () => { + const { refusal, wait } = bootOverPendingUpdate(slots({ tries: 0 }, 0)) + expect(wait).toBeUndefined() + expect(refusal).toContain('slot B is not confirmed yet (0 of its 2 starts used)') + expect(refusal).toContain('Power-cycle it') + expect(refusal).toContain('--spend-tries') + }) + it('refuses on a RAM-booted base over an update started once (20 November 2026)', () => { + expect(bootOverPendingUpdate(slots({ tries: 1 })).refusal).toContain('(1 of its 2 starts used)') + }) + it('waits while the update itself runs, which confirms itself', () => { + const pending = bootOverPendingUpdate(slots({ tries: 1 }, 1)) + expect(pending.wait).toBe(true) + expect(pending.refusal).toContain('one of its 1 start left') + expect(bootOverPendingUpdate(slots({ tries: 2 }, 1)).refusal).toContain('it has no start left') + }) + it('only warns when the update has no start left and is not running: the next restart undoes it either way', () => { + const pending = bootOverPendingUpdate(slots({ tries: 2 })) + expect(pending.refusal).toBeUndefined() + expect(pending.warning).toContain('no start left') + }) + it('takes the newest whole slot as the stub does (slots.c slot_newest)', () => { + const swapped = { layout: 'two', running: null, fellBack: false, confirmed: false, slots: [ + { generation: 9, whole: true, confirmed: false, tries: 1 }, { generation: 8, whole: true, confirmed: true, tries: 1 }] } + expect(bootOverPendingUpdate(swapped).refusal).toContain('slot A') + }) +}) describe('stageRefusal', () => { it('passes an image the running base stages', () => { diff --git a/scripts/perf-audit-analysis.mjs b/scripts/perf-audit-analysis.mjs index 227eb5059c..c3d49f6849 100644 --- a/scripts/perf-audit-analysis.mjs +++ b/scripts/perf-audit-analysis.mjs @@ -144,8 +144,11 @@ export function judgeRecord(record, options = {}) { /** Whether a record's numbers were measured on the module's current source: its `sourceSha256`, written by * `perf:audit check FILE --stamp`, against modulePerformanceSourceSha256. `required` (a module listed from the day stamps began, - * or a draft judged as a release) turns a missing stamp from a note into a failure; a stamp for other source always fails. */ -export function stampVerdict(record, sourceSha256, required, file = '/evidence/performance.json') { + * or a draft judged as a release) turns a missing stamp from a note into a failure; a stamp for other source always fails. + * `earlierSha256`, from moduleEarlierPerformanceSourceSha256, is what a stamp written before presentation/ left the hash names. */ +export function stampVerdict(record, sourceSha256, required, file = '/evidence/performance.json', earlierSha256 = undefined) { + if (earlierSha256 && record?.sourceSha256 === earlierSha256 && earlierSha256 !== sourceSha256) + return { state: 'ok', detail: 'measured on this source (' + earlierSha256.slice(0, 12) + '…, a stamp from before art left it; the next --stamp writes ' + sourceSha256.slice(0, 12) + '…)' } const fix = 'measure again on this source, then npm run perf:audit -- check ' + file + ' --stamp' if (record?.sourceSha256 === undefined) return required ? { state: 'fail', detail: 'its numbers name no source, so nothing shows they were measured on this code', fix: 'npm run perf:audit -- check ' + file + ' --stamp, right after you measure' } diff --git a/scripts/perf-audit.test.mjs b/scripts/perf-audit.test.mjs index 15a7ef2c28..7bae21f224 100644 --- a/scripts/perf-audit.test.mjs +++ b/scripts/perf-audit.test.mjs @@ -1,11 +1,11 @@ import { describe, expect, it } from 'vitest' import { spawnSync } from 'node:child_process' -import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { judgeRecord, selfTest, templateRecord, ownerWaivedPerformanceRow, stampVerdict, priceLimits, approvalCoversSource } from './perf-audit-analysis.mjs' -import { modulePerformanceSourceSha256 } from './module-qualification.mjs' +import { moduleEarlierPerformanceSourceSha256, modulePerformanceSourceSha256 } from './module-qualification.mjs' import { parseModuleDocument } from '../src/catalog/module-contract.ts' const root = fileURLToPath(new URL('../', import.meta.url)) @@ -32,9 +32,17 @@ describe('performance stamp', () => { expect(record.sourceSha256).toBe(await modulePerformanceSourceSha256(folder, document)) expect(audit('check', file, '--stamp').status).toBe(0) expect(JSON.parse(readFileSync(file, 'utf8')).sourceSha256).toBe(record.sourceSha256) + // New art for the library card is not new code: the numbers stand (Mackity, #2148, re-stamped for each thumbnail edit). + mkdirSync(join(folder, 'presentation'), { recursive: true }) + writeFileSync(join(folder, 'presentation/thumbnail.svg'), '\r\n') + expect(stampVerdict(record, await modulePerformanceSourceSha256(folder, document), true).state).toBe('ok') + // A stamp written before the art left the hash names the source with it, and holds while that source is unchanged. + const earlier = await moduleEarlierPerformanceSourceSha256(folder, document), stampedEarlier = { ...record, sourceSha256: earlier } + expect(stampVerdict(stampedEarlier, await modulePerformanceSourceSha256(folder, document), true, file, earlier)).toMatchObject({ state: 'ok', detail: expect.stringContaining('the next --stamp writes') }) // A code change after the numbers were taken: the doctor's verdict fails until they are measured and stamped again. writeFileSync(join(folder, 'native.c'), readFileSync(join(folder, 'native.c'), 'utf8') + '\n/* changed */\n') expect(stampVerdict(record, await modulePerformanceSourceSha256(folder, document), false).state).toBe('fail') + expect(stampVerdict(stampedEarlier, await modulePerformanceSourceSha256(folder, document), false, file, await moduleEarlierPerformanceSourceSha256(folder, document)).state).toBe('fail') // A record for another version is never stamped. writeFileSync(file, JSON.stringify({ ...record, version: '9.9.9' })) expect(audit('check', file, '--stamp').stderr).toContain('Not stamped') diff --git a/scripts/pr-body.mjs b/scripts/pr-body.mjs index b617363277..e55fca740d 100644 --- a/scripts/pr-body.mjs +++ b/scripts/pr-body.mjs @@ -7,10 +7,12 @@ // Reads only the description, the template, the draft flag and the changed file names: no PR code runs. // // PR_BODY="$(gh pr view --json body --jq .body)" PR_DRAFT=false PR_FILES="$(gh pr diff --name-only)" node scripts/pr-body.mjs -// node scripts/pr-body.mjs FILE.md # a description still in a file, before the pull request is open (as a ready one, with -// # this branch's files against upstream/main, or origin/main without that remote) +// npm run pr:body -- FILE.md # a description in a file, before you open or edit the pull request: as a ready one, with +// # this branch's files against upstream/main, or origin/main without that remote +// npm run pr:body -- FILE.md --draft --changed-since base/octatrack-next # as a draft, into another base; FILE - reads stdin import { execFileSync } from 'node:child_process' import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' import { pathToFileURL } from 'node:url' const OWN_TEXT = 40 @@ -46,28 +48,50 @@ const plain = line => line.replaceAll('**', '').replaceAll('`', '').replace(/^(? // because …". A table under another heading does not count, nor the template's empty row. const EDGE = /^edge cases?\b/i const EDGE_NONE = /^edge cases?\b[^:]*:\s*none\b[\s,.;:–—-]*because\s+\S/i +const EDGE_BARE_NONE = /^edge cases?\b[^:]*:\s*none\b/i const cells = row => row.replace(/^\|/, '').replace(/\|$/, '').split('|').map(cell => cell.trim()) -/** true when the description lists its edge cases, else what is wrong; `own` tells the author's lines from the template's. */ -export function edgeCases(lines, own) { - let incomplete = null +const ROW_SHAPE = '| Case | Why this change makes it a risk | How run | Result |' +/** Why a row of the edge-case table is not a finished case, or null; `row` is its cells. */ +export function rowProblem(row) { + if (row.length < 4) return `it has ${row.length} cell${row.length === 1 ? '' : 's'}, and a case has four: ${ROW_SHAPE}` + if (!row[0]) return 'its first cell, the case, is empty' + if (!row.at(-1)) return 'its last cell, the result, is empty; write "pass", "fail: what happened" or "not run: why"' + if (/^not run\W*$/i.test(row.at(-1))) return `the result says "${row.at(-1)}" without why; write "not run: "` + return null +} +/** What the edge cases say: `verdict` true when listed, else 'missing' or 'incomplete'; `rows` the unfinished rows ({ row, why }) + * and `hint` why nothing counted. `own` tells the author's lines from the template's. */ +export function edgeCaseFindings(lines, own) { + const unfinished = new Map() + let sections = 0, bareNone = false for (let index = 0; index < lines.length; index++) { if (!EDGE.test(plain(lines[index]))) continue - if (own(lines[index]) && EDGE_NONE.test(plain(lines[index]))) return true + sections++ + if (own(lines[index]) && EDGE_NONE.test(plain(lines[index]))) return { verdict: true, rows: [], hint: null } + if (own(lines[index]) && EDGE_BARE_NONE.test(plain(lines[index]))) bareNone = true let rows = 0 - for (const next of lines.slice(index + 1)) { + for (let at = index + 1; at < lines.length; at++) { + const next = lines[at] if (!next.startsWith('|')) { if ((next && rows) || isHeading(next) || /^(?:[-*]\s+)?\*\*/.test(next)) break continue } const row = cells(next) if (!own(next) || row.every(cell => /^:?-*:?$/.test(cell)) || /^case$/i.test(row[0])) continue - if (row.length < 4 || !row[0] || !row.at(-1) || /^not run\W*$/i.test(row.at(-1))) { incomplete ??= row[0] || next; continue } + const why = rowProblem(row) + if (why) { unfinished.set(at, { row: row[0] || next, why }); continue } rows++ } - if (rows && !incomplete) return true + if (rows && !unfinished.size) return { verdict: true, rows: [], hint: null } } - return incomplete ? 'incomplete' : 'missing' + if (unfinished.size) return { verdict: 'incomplete', rows: [...unfinished.values()], hint: null } + return { verdict: 'missing', rows: [], hint: bareNone ? 'It says "none" without why: write "Edge cases: none, because …".' + : sections ? 'Under "Edge cases" no table row with its case and result follows before the next heading or bold line.' + : 'No line or heading "Edge cases" was found.' } } +/** true when the description lists its edge cases, else 'missing' or 'incomplete'; `own` tells the author's lines from the template's. */ +export const edgeCases = (lines, own) => edgeCaseFindings(lines, own).verdict +const quoteRow = row => '"' + (row.length > 60 ? row.slice(0, 57) + '…' : row) + '"' /** What the description still lacks; [] when it is described, answers the guides question, and (ready, changing what runs on an * instrument) names the build that ran on a unit. A draft may still be in test, but lists its edge cases already. */ @@ -80,29 +104,82 @@ export function bodyProblems(body, template, { draft = false, files = [] } = {}) const instrument = instrumentFiles(files) if (!draft && instrument.length && !own.some(line => TESTED.test(plain(line)) || UNTESTED.test(plain(line)))) problems.push('This pull request changes what runs on an instrument (' + instrument.slice(0, 3).join(', ') + (instrument.length > 3 ? ` and ${instrument.length - 3} more` : '') + '). Keep it a draft until the exact build ran on a unit, then name it on a line of its own: "Tested on a unit: base 8d1db124 (or the package\'s sha256), MKII, what ran". If it cannot be tested, write "Not tested on a unit: " for the owner to decide. `npm run pr:ready` saying Ready means the checks pass, not that it was tested.') // Drafts too: a draft opened early lists what it will run, each case "not run: why" until it ran (owner, 20 November 2026). - const edge = instrument.length ? edgeCases(lines, isOwn) : true - if (edge !== true) problems.push('This pull request changes what runs on an instrument, so it lists the edge cases this change risks and what each showed (docs/TEST_PROCEDURE.md#edge-cases). Under a line "Edge cases", add a table with one row a case: | Case | Why this change makes it a risk | How run | Result |, the result "pass", "fail: what happened" or "not run: why". `npm run test:procedure` writes the empty table. With none, say why: "Edge cases: none, because …".' + - (edge === 'incomplete' ? ' A row there lacks its case or its result, or says "not run" without why.' : '')) + const edge = instrument.length ? edgeCaseFindings(lines, isOwn) : { verdict: true } + // An unfinished row is named with what it lacks, so the fix needs no reading of this file (#2148, 25 November 2026). + if (edge.verdict === 'incomplete') problems.push('The edge-case table under "Edge cases" has ' + (edge.rows.length === 1 ? 'a row' : edge.rows.length + ' rows') + ' still to finish: ' + + edge.rows.map(({ row, why }) => `row ${quoteRow(row)}: ${why}`).join('; ') + '. Each case is a row ' + ROW_SHAPE + ', the result "pass", "fail: what happened" or "not run: why" (docs/TEST_PROCEDURE.md#edge-cases).') + else if (edge.verdict !== true) problems.push('This pull request changes what runs on an instrument, so it lists the edge cases this change risks and what each showed (docs/TEST_PROCEDURE.md#edge-cases). ' + edge.hint + ' Under a line "Edge cases", add a table with one row a case: ' + ROW_SHAPE + ', the result "pass", "fail: what happened" or "not run: why". `npm run test:procedure` writes the empty table. With none, say why: "Edge cases: none, because …".') if (!own.some((line, index) => answersGuides(line, own[index + 1]))) problems.push('Say what the guides lacked or got wrong while you did this, and where you fixed it, on a line of its own, for example "Guides: nothing". It is how the next developer\'s agent learns what you did (AGENTS.md, Pull requests).') return problems } +/** bodyProblems against this checkout's pull request template, as CI's describe check reads it. */ +export function descriptionProblems(body, options) { + return bodyProblems(body, readFileSync(new URL('../.github/pull_request_template.md', import.meta.url), 'utf8'), options) +} + +/** The local command line: FILE (or - for stdin), --draft, --changed-since ; { error } when it cannot be read. */ +export function parseArgs(argv) { + const options = { file: null, draft: false, since: null } + for (let index = 0; index < argv.length; index++) { + const arg = argv[index] + if (arg === '--draft') options.draft = true + else if (arg === '--changed-since') { + options.since = argv[++index] + if (!options.since || options.since.startsWith('--')) return { error: '--changed-since needs a ref, such as origin/main or base/octatrack-next.' } + } else if (arg.startsWith('--')) return { error: 'Unknown option ' + arg + '.' } + else if (options.file) return { error: 'One description file at a time.' } + else options.file = arg + } + return options.file ? options : { error: 'Name the description file (or - to read it from stdin).' } +} + +/** The base a local check compares the branch with: the ref given, else upstream/main in a fork's checkout, whose origin/main is the + * fork's own and can lag by hundreds of files, else origin/main (as scripts/lane.mjs picks it). */ +export const localBase = (since, remotes) => since ?? (remotes.includes('upstream') ? 'upstream/main' : 'origin/main') + +/** A description file named on the command line: - is stdin, and a relative path is the caller's, since npm run starts in the root. */ +export const readDescription = (file, cwd = process.env.INIT_CWD ?? process.cwd()) => readFileSync(file === '-' ? 0 : resolve(cwd, file), 'utf8') + +/** The branch's changed files as CI lists them: git diff --name-only --no-renames ...HEAD (.github/workflows/pr-description.yml). */ +export function changedFiles(git, base) { + return git('diff', '--name-only', '--no-renames', base + '...HEAD').split('\n').map(file => file.trim()).filter(Boolean) +} + +const USAGE = 'Usage: npm run pr:body -- FILE [--draft] [--changed-since ] (FILE - reads stdin)' + if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - const template = readFileSync(new URL('../.github/pull_request_template.md', import.meta.url), 'utf8') - const local = !!process.argv[2] - // In CI the workflow passes the draft flag and the file names; locally, a description in a file is checked as a ready pull request - // of this branch against the base it merges into: upstream/main in a fork's checkout, whose origin/main is the fork's own and can lag - // by hundreds of files, else origin/main (as scripts/lane.mjs picks it). - let files = (process.env.PR_FILES ?? '').split('\n').map(file => file.trim()).filter(Boolean) - if (local && !process.env.PR_FILES) { + const ci = process.argv.length <= 2 + if (ci) { + // In CI the workflow passes the description, the draft flag and the changed files. + const files = (process.env.PR_FILES ?? '').split('\n').map(file => file.trim()).filter(Boolean) + const problems = descriptionProblems(process.env.PR_BODY, { draft: process.env.PR_DRAFT === 'true', files }) + for (const problem of problems) console.log('::error title=Pull request description::' + problem) + console.log(problems.length ? 'Edit the pull request description (or keep it a draft); this check runs again when you save it or mark it ready.' : 'The description says what changed and answers the guides question.') + process.exitCode = problems.length ? 1 : 0 + } else { + // Locally, a description in a file is checked as CI would check it on this branch's pull request: ready unless --draft, with the + // files this branch changes against the base it merges into (PR_FILES, when set, stands in for them). + const options = parseArgs(process.argv.slice(2)) + const git = (...args) => execFileSync('git', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) + let body, files, base = null try { - const base = execFileSync('git', ['remote'], { encoding: 'utf8' }).split('\n').includes('upstream') ? 'upstream/main' : 'origin/main' - files = execFileSync('git', ['diff', '--name-only', base + '...HEAD'], { encoding: 'utf8' }).split('\n').filter(Boolean) - } catch { files = [] } + if (options.error) throw new Error(options.error + '\n' + USAGE) + body = readDescription(options.file) + if (process.env.PR_FILES) files = process.env.PR_FILES.split('\n').map(file => file.trim()).filter(Boolean) + else { + base = localBase(options.since, git('remote').split('\n')) + try { files = changedFiles(git, base) } catch (error) { + throw new Error(`Could not list this branch's changes against ${base}: ${(error.stderr || error.message).trim().split('\n').pop()}. Fetch it (git fetch) or name the base the pull request merges into with --changed-since .`, { cause: error }) + } + } + } catch (error) { console.error(error.message); process.exit(2) } + const instrument = instrumentFiles(files) + console.log(`Checking ${options.file === '-' ? 'the description' : options.file} as a ${options.draft ? 'draft' : 'ready'} pull request: ${files.length} file${files.length === 1 ? '' : 's'} changed` + + (base ? ` since ${base}` : ' (PR_FILES)') + (instrument.length ? `, ${instrument.length} that run${instrument.length === 1 ? 's' : ''} on an instrument.` : ', none that runs on an instrument.')) + const problems = descriptionProblems(body, { draft: options.draft, files }) + for (const problem of problems) console.log('✗ ' + problem) + console.log(problems.length ? 'Not yet: CI\'s describe check would fail on the same description.' : 'Passes: CI\'s describe check reads it the same way.') + process.exitCode = problems.length ? 1 : 0 } - const problems = bodyProblems(local ? readFileSync(process.argv[2], 'utf8') : process.env.PR_BODY, template, - { draft: process.env.PR_DRAFT === 'true', files }) - for (const problem of problems) console.log('::error title=Pull request description::' + problem) - console.log(problems.length ? 'Edit the pull request description (or keep it a draft); this check runs again when you save it or mark it ready.' : 'The description says what changed and answers the guides question.') - process.exitCode = problems.length ? 1 : 0 } diff --git a/scripts/pr-body.test.mjs b/scripts/pr-body.test.mjs index 382ffae1e6..cba356bbc6 100644 --- a/scripts/pr-body.test.mjs +++ b/scripts/pr-body.test.mjs @@ -1,7 +1,10 @@ -import { readFileSync } from 'node:fs' +import { execFileSync, spawnSync } from 'node:child_process' +import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { expect, it } from 'vitest' import { parse } from 'yaml' -import { bodyProblems } from './pr-body.mjs' +import { bodyProblems, localBase, parseArgs } from './pr-body.mjs' const template = readFileSync(new URL('../.github/pull_request_template.md', import.meta.url), 'utf8') @@ -83,7 +86,7 @@ it('asks a ready pull request that changes what runs on an instrument for its ed const described = 'Octatrack base 0.7.8: a module that no track uses rests out of the per-frame hooks; checked with pr:ready.\n\nGuides: HOOKS.md.\n\nTested on a unit: base 8d1db124, MKII, the large set.' const files = ['src/engine/assets/octatrack-base.elemod'] const missing = expect.stringMatching(/^This pull request changes what runs on an instrument, so it lists the edge cases/) - const incomplete = expect.stringMatching(/lacks its case or its result/) + const incomplete = expect.stringMatching(/^The edge-case table under "Edge cases" has a row still to finish: row "/) const table = '\n\n## Edge cases\n\n| Case | Why this change makes it a risk | How run | Result |\n|---|---|---|---|\n' const row = '| A module resting while its page is open | resting skips its tick | trial, open the page, stop the transport | pass |\n' // A change that runs nowhere needs none; a draft does, and may say honestly what it has not run yet. @@ -113,3 +116,87 @@ it('asks a ready pull request that changes what runs on an instrument for its ed .replace('- **Tested on a unit:**', '- **Tested on a unit:** base 8d1db124, MKII.') expect(bodyProblems(filled, template, { files })).toEqual([]) }) + +const ready = 'Mackity 0.1.0: a desk input stage for FX1/FX2; checked with pr:ready and on the unit.\n\nGuides: nothing.\n\nTested on a unit: package 64d0386d9aa1, MKII, eight instances.' +const edgeTable = '\n\n## Edge cases\n\n| Case | Why this change makes it a risk | How run | Result |\n|---|---|---|---|\n| Eight instances at once | per-instance state | device:test | pass |\n' +const mwrm = ['public/octatrack-modules/mackity/0.1.0-experimental.mwrm'] + +it('names each unfinished edge-case row and what it lacks', () => { + // #2148: the last row said "not run" without why, and the check only asked for a table. + expect(bodyProblems(ready + edgeTable + '| Part/project reload | stored knob bytes | not run on the unit | not run |\n', template, { files: mwrm })).toEqual([ + 'The edge-case table under "Edge cases" has a row still to finish: row "Part/project reload": the result says "not run" without why; write "not run: ". Each case is a row | Case | Why this change makes it a risk | How run | Result |, the result "pass", "fail: what happened" or "not run: why" (docs/TEST_PROCEDURE.md#edge-cases).']) + const one = extra => bodyProblems(ready + edgeTable + extra, template, { files: mwrm })[0] + expect(one('| Silence after audio | limit cycles | verify.py | |\n')).toContain('row "Silence after audio": its last cell, the result, is empty; write "pass", "fail: what happened" or "not run: why"') + expect(one('| Part switches | device:test | pass |\n')).toContain('row "Part switches": it has 3 cells, and a case has four: | Case |') + expect(one('| | knob words | device:test | pass |\n')).toContain('row "| | knob words | device:test | pass |": its first cell, the case, is empty') + expect(one('| Undo | the same | trial | Not run. |\n')).toContain('the result says "Not run." without why') + expect(one('| ' + 'A very long case name that goes on and on about the Part, the project and a reload'.padEnd(80, '.') + ' | x | y | not run |\n')) + .toContain('row "A very long case name that goes on and on about the Part,…":') + // Every unfinished row, each once, though two lines name the same table. + const two = bodyProblems(ready + '\n\n## Edge cases\n\nEdge cases from the procedure:\n\n| Case | Why | How | Result |\n|---|---|---|---|\n| A | x | y | not run |\n| B | x | y | pass |\n| C | x | y | |\n', template, { files: mwrm }) + expect(two).toHaveLength(1) + expect(two[0]).toMatch(/^The edge-case table under "Edge cases" has 2 rows still to finish: row "A": the result says "not run" without why; write "not run: "; row "C": its last cell, the result, is empty/) +}) + +it('says why no edge cases were found', () => { + const missing = extra => bodyProblems(ready + extra, template, { files: mwrm }) + expect(missing('')).toEqual([expect.stringContaining('No line or heading "Edge cases" was found.')]) + expect(missing('\n\nEdge cases: none.')).toEqual([expect.stringContaining('It says "none" without why: write "Edge cases: none, because …".')]) + expect(missing('\n\n## Edge cases\n\n| Case | Why | How | Result |\n|---|---|---|---|\n')).toEqual([expect.stringContaining('no table row with its case and result follows')]) + for (const problem of [...missing(''), ...missing('\n\nEdge cases: none.')]) expect(problem).toMatch(/^This pull request changes what runs on an instrument, so it lists the edge cases/) +}) + +it('reads the local command line', () => { + expect(parseArgs(['body.md'])).toEqual({ file: 'body.md', draft: false, since: null }) + expect(parseArgs(['--draft', '-', '--changed-since', 'base/octatrack-next'])).toEqual({ file: '-', draft: true, since: 'base/octatrack-next' }) + expect(parseArgs([]).error).toMatch(/Name the description file/) + expect(parseArgs(['a.md', 'b.md']).error).toMatch(/One description file/) + expect(parseArgs(['a.md', '--changed-since']).error).toMatch(/--changed-since needs a ref/) + expect(parseArgs(['a.md', '--changed-since', '--draft']).error).toMatch(/--changed-since needs a ref/) + expect(parseArgs(['a.md', '--ready']).error).toMatch(/Unknown option --ready/) + expect(localBase(null, ['origin', 'upstream'])).toBe('upstream/main') + expect(localBase(null, ['origin'])).toBe('origin/main') + expect(localBase('base/octatrack-next', ['origin', 'upstream'])).toBe('base/octatrack-next') +}) + +it('checks a description file locally as CI would on this branch: ready or draft, against the base it merges into', () => { + const directory = realpathSync(mkdtempSync(join(tmpdir(), 'modwerk-pr-body-'))) + const env = { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: join(directory, 'no-global-config') } + for (const name of ['PR_FILES', 'PR_BODY', 'PR_DRAFT', 'INIT_CWD']) delete env[name] + const git = (...args) => execFileSync('git', ['-c', 'user.name=Description test', '-c', 'user.email=description@example.invalid', '-c', 'commit.gpgsign=false', ...args], + { cwd: directory, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim() + const run = (args, extra = {}) => spawnSync(process.execPath, [join(directory, 'scripts', 'pr-body.mjs'), ...args], { cwd: directory, encoding: 'utf8', ...extra, env: { ...env, ...extra.env } }) + try { + mkdirSync(join(directory, 'scripts')); mkdirSync(join(directory, '.github')) + copyFileSync(new URL('./pr-body.mjs', import.meta.url), join(directory, 'scripts', 'pr-body.mjs')) + copyFileSync(new URL('../.github/pull_request_template.md', import.meta.url), join(directory, '.github', 'pull_request_template.md')) + git('init', '--initial-branch=main', '.'); git('add', '.'); git('commit', '-m', 'Baseline') + git('update-ref', 'refs/remotes/origin/main', 'HEAD'); git('switch', '-c', 'topic') + mkdirSync(join(directory, 'public', 'octatrack-modules', 'mackity'), { recursive: true }) + writeFileSync(join(directory, mwrm[0]), 'package\n'); git('add', '.'); git('commit', '-m', 'Mackity') + const unfinished = ready + edgeTable + '| Part/project reload | stored knob bytes | not run on the unit | not run |\n' + writeFileSync(join(directory, 'body.md'), unfinished) + const refused = run(['body.md']) + expect(refused.status, refused.stderr).toBe(1) + expect(refused.stdout).toContain('as a ready pull request: 1 file changed since origin/main, 1 that runs on an instrument.') + expect(refused.stdout).toContain('✗ The edge-case table under "Edge cases" has a row still to finish: row "Part/project reload": the result says "not run" without why') + expect(refused.stdout).toContain('CI\'s describe check would fail') + // A draft needs no unit line yet but its edge cases; stdin and the caller's own directory work too. + const draft = ready.replace(/\n\nTested on a unit:.*$/, '') + edgeTable + '| Part/project reload | stored knob bytes | not run on the unit | not run: needs a Keep and a power cycle |\n' + expect(run(['-'], { input: draft }).status).toBe(1) + const passed = run(['-', '--draft'], { input: draft }) + expect(passed.status, passed.stdout).toBe(0) + expect(passed.stdout).toContain('Passes: CI\'s describe check reads it the same way.') + mkdirSync(join(directory, 'notes')); writeFileSync(join(directory, 'notes', 'draft.md'), draft) + expect(run(['draft.md', '--draft'], { env: { INIT_CWD: join(directory, 'notes') } }).status).toBe(0) + // Against a base that already holds the package, nothing runs on an instrument. + const since = run(['body.md', '--changed-since', 'topic']) + expect(since.stdout).toContain('0 files changed since topic, none that runs on an instrument.') + expect(since.status).toBe(0) + // A base that cannot be read stops the check rather than passing it with no files. + const unknown = run(['body.md', '--changed-since', 'nowhere/main']) + expect(unknown.status).toBe(2) + expect(unknown.stderr).toContain('Could not list this branch\'s changes against nowhere/main') + expect(run(['missing.md']).status).toBe(2) + } finally { rmSync(directory, { recursive: true, force: true }) } +}, 20_000) diff --git a/scripts/pr-ready.mjs b/scripts/pr-ready.mjs index 3acc372d63..9f67a8129d 100644 --- a/scripts/pr-ready.mjs +++ b/scripts/pr-ready.mjs @@ -4,6 +4,7 @@ // npm run pr:ready -- --commit "Message" # check a fully staged change once, commit it, then finish the PR checks // npm run pr:ready -- --author # a registered author's update: also the bot's merge scope // npm run pr:ready -- --remote upstream # the remote that holds Modwerk's main (default: upstream, else origin) +// npm run pr:ready -- --body FILE.md # also the description, as CI's describe check reads it (with --draft, as a draft) // // It reads and writes only this checkout, plus the agent board's claims and inbox (docs/AGENT_BOARD.md): no push, no GitHub API. // CI repeats the same checks against the PR's base, and the author-update bot runs the same scope inspection @@ -13,7 +14,7 @@ import { existsSync } from 'node:fs' import { resolve } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' import { alternation, moduleFolders } from './machine-folders.mjs' -import { instrumentFiles } from './pr-body.mjs' +import { changedFiles as branchFiles, descriptionProblems, instrumentFiles, readDescription } from './pr-body.mjs' const GENERATORS = [['licenses:generate'], ['machines:generate'], ['modules:generate']] @@ -78,7 +79,7 @@ export function mergeMain(git, ref) { } /** The verdict from what was found; every problem says what to do. */ -export function readiness({ python = null, dirty = [], behind = false, remote = 'upstream', regenerated = [], checkPassed = true, author = null, scope = null, guideEdits = [], gateEdits = [], baseEdits = [], instrument = [], baseDraft = instrument.some(file => BASE.test(file)), compiled = null, board = null, conflicts = [], draftOnly = false }) { +export function readiness({ python = null, dirty = [], behind = false, remote = 'upstream', regenerated = [], checkPassed = true, author = null, scope = null, guideEdits = [], gateEdits = [], baseEdits = [], instrument = [], baseDraft = instrument.some(file => BASE.test(file)), compiled = null, board = null, conflicts = [], draftOnly = false, description = null }) { const problems = [...board?.problems ?? []], notes = [...board?.notes ?? []] if (python) problems.push(python) if (gateEdits.length) problems.push(gateProblem(gateEdits)) @@ -89,6 +90,8 @@ export function readiness({ python = null, dirty = [], behind = false, remote = : `Your branch does not contain current main. Merge it (git merge ${remote}/main), resolve any conflict, then run this again.`) if (regenerated.length) problems.push('The generated files were stale. They are regenerated now; commit them: ' + regenerated.join(', ')) if (!checkPassed) problems.push('npm run check failed: fix every failure above; CI runs the same checks.') + // --body: the description, as CI's describe check reads it (scripts/pr-body.mjs); null when no description was given. + for (const problem of description ?? []) problems.push('Description: ' + problem) if (author) { if (scope?.error) problems.push(`This is not an automatic author update (${scope.error}). Keep the PR to your own module's folder and its changelog entry, or ask the owner for a review.`) else if (scope) notes.push('Automatic merge: the bot can merge this update to ' + scope.modules.join(', ') + ' once both release boxes are ticked and CI is green.') @@ -106,7 +109,8 @@ export function readiness({ python = null, dirty = [], behind = false, remote = '): open the pull request as a draft (gh pr create --draft) and mark it ready only after the developer has tested the exact build on a unit. The description then names it on a line of its own ("Tested on a unit: base 8d1db124 (or the package\'s sha256), MKII, what ran", or "Not tested on a unit: " for the owner to decide); CI refuses a ready one without it. Until then, pr:ready -- --draft and the draft\'s CI list missing qualification, captures or approval as warnings.') if (baseDraft) notes.push('Watch the existing cumulative draft’s checks with gh pr checks --watch. If main moves before the merge, run this again.') else { - notes.push('Push and open or update the PR using the description template. Check the description locally with node scripts/pr-body.mjs FILE.md.') + notes.push(description ? 'Push and open or update the PR with the description you checked.' + : 'Push and open or update the PR using the description template. Check the description first with npm run pr:body -- FILE.md (add --draft for a draft), or here with --body FILE.md: the same rules as CI\'s describe check.') if (!draftOnly && !problems.length) notes.push('Once the work and testing are complete, run gh pr view --json state,headRefOid,isDraft. On the checked commit, run gh pr ready if it is a draft. Read the state again and verify isDraft is false before reporting it ready.') notes.push('Watch gh pr checks --watch until green. If main moves before the merge, run this again and push.') } @@ -130,9 +134,10 @@ export async function boardClaims(root, base, board) { else for (const item of open) { try { // A claim says what the work is; a note its holder wrote by hand stays, and one the server refuses never costs the claim. - const request = { kind: item.kind, key: item.key, branch: board.currentBranch(root) }, note = item.claim?.note ? '' : item.note + // A run you hold that covers this item is renewed whole, so claiming the part never gives up the rest of the run. + const request = { kind: item.kind, key: item.claim?.key ?? item.key, branch: board.currentBranch(root) }, note = item.claim?.note ? '' : item.note const result = note ? await board.claim({ ...request, note }).catch(error => { if (error instanceof board.BoardError && error.status === 400) return board.claim(request); throw error }) : await board.claim(request) - notes.push((result.renewed ? 'Board: renewed your claim on ' : 'Board: claimed ') + item.kind + ' ' + item.key + ' for @' + login + '.') + notes.push((result.renewed ? 'Board: renewed your claim on ' : 'Board: claimed ') + item.kind + ' ' + request.key + ' for @' + login + '.') } catch (error) { if (error instanceof board.BoardUnavailable) { notes.push('Board: could not claim ' + item.kind + ' ' + item.key + '. ' + error.message); continue } problems.push('Board: ' + item.kind + ' ' + item.key + ': ' + error.message) @@ -179,6 +184,10 @@ async function main(argv) { // --draft: the pull request stays a draft until the exact build ran on a unit, so missing release evidence warns (scripts/modules.mjs). if (argv.includes('--draft')) process.env.MODWERK_EVIDENCE_PENDING = '1' if (argv.includes('--commit') && (!commit?.trim() || commit.startsWith('--'))) throw new Error('--commit needs a commit message.') + const bodyFile = option('--body') + if (argv.includes('--body') && (!bodyFile || bodyFile.startsWith('--'))) throw new Error('--body needs the description file (or - for stdin).') + // Read before the long check, so a wrong path stops at once. + const body = bodyFile ? readDescription(bodyFile) : null const npmCli = process.env.npm_execpath if (!npmCli) throw new Error('Run this through npm run pr:ready.') const npm = (...args) => spawnSync(process.execPath, [npmCli, 'run', ...args], { cwd: root, stdio: 'inherit' }).status === 0 @@ -245,7 +254,8 @@ async function main(argv) { const board = claimed || waiting.length ? { problems: claimed?.problems ?? [], notes: [...claimed?.notes ?? [], ...waiting] } : null const baseDraft = changed.some(file => BASE.test(file)) || /^base\/[^/]+-next$/.test(git('branch', '--show-current')) const draftOnly = process.env.MODWERK_EVIDENCE_PENDING === '1' - const verdict = readiness({ python, baseDraft, draftOnly, dirty, behind, conflicts, remote, regenerated, checkPassed, author, scope, guideEdits, gateEdits: gateEdits(changed), baseEdits: baseEdits(changed), instrument: instrumentFiles(changed), compiled, board }) + const description = body === null ? null : descriptionProblems(body, { draft: argv.includes('--draft'), files: branchFiles(git, base) }) + const verdict = readiness({ python, baseDraft, draftOnly, dirty, behind, conflicts, remote, regenerated, checkPassed, author, scope, guideEdits, gateEdits: gateEdits(changed), baseEdits: baseEdits(changed), instrument: instrumentFiles(changed), compiled, board, description }) console.log('') for (const line of verdict.problems) console.log('✗ ' + line) // Once the work is ready, the agent reviews its session and asks whether to share it with the owner (docs/AGENT_SESSIONS.md), unless the developer said never. diff --git a/scripts/pr-ready.test.mjs b/scripts/pr-ready.test.mjs index 1f488c06ab..bebb764264 100644 --- a/scripts/pr-ready.test.mjs +++ b/scripts/pr-ready.test.mjs @@ -108,6 +108,15 @@ describe('pr:ready verdict', () => { expect(verdict.notes.at(-1)).toContain('If main moves before the merge, run this again') expect(readiness({}).instrument).toBe(false) }) + it('checks the description with --body as CI\'s describe check does, and otherwise says how to', () => { + const refused = readiness({ description: ['The edge-case table under "Edge cases" has a row still to finish: row "Undo": …'] }) + expect(refused.ok).toBe(false) + expect(refused.problems).toEqual(['Description: The edge-case table under "Edge cases" has a row still to finish: row "Undo": …']) + const passed = readiness({ description: [] }) + expect(passed.ok).toBe(true) + expect(passed.notes.join(' ')).toContain('with the description you checked') + expect(readiness({}).notes.join(' ')).toContain('npm run pr:body -- FILE.md') + }) it('routes a base build to the cumulative draft without prompting for a topic PR', () => { const verdict = readiness({ instrument: ['src/engine/assets/octatrack-base.elemod'] }) expect(verdict.baseDraft).toBe(true) @@ -211,16 +220,21 @@ describe('pr:ready verdict', () => { copyFileSync(new URL('./pr-body.mjs', import.meta.url), join(checkout, 'scripts', 'pr-body.mjs')) mkdirSync(join(checkout, 'src', 'devices'), { recursive: true }) copyFileSync(new URL('../src/devices/machines.generated.json', import.meta.url), join(checkout, 'src', 'devices', 'machines.generated.json')) + // --body checks the description against the template, as CI's describe check does. + mkdirSync(join(checkout, '.github')) + copyFileSync(new URL('../.github/pull_request_template.md', import.meta.url), join(checkout, '.github', 'pull_request_template.md')) + writeFileSync(join(directory, 'body.md'), 'Moves the README line and checks it with pr:ready on the topic branch.\n') // A stale branch must stop before any generator/check invocation. - const result = spawnSync(process.execPath, [script, '--remote', 'origin'], { cwd: checkout, + const result = spawnSync(process.execPath, [script, '--remote', 'origin', '--body', join(directory, 'body.md')], { cwd: checkout, env: { ...env, npm_execpath: join(directory, 'never-run-npm.mjs') }, encoding: 'utf8' }) expect(result.status, result.stderr).toBe(1) expect(result.stdout).toContain('git merge origin/main') + expect(result.stdout).toContain('✗ Description: Say what the guides lacked') expect(result.stdout).toContain('Not ready yet.') expect(git(checkout, 'rev-parse', 'origin/main')).toBe(current) git(checkout, 'merge', '--ff-only', 'origin/main') expect(git(checkout, 'rev-parse', 'HEAD')).toBe(current) - git(checkout, 'add', 'scripts', 'src') + git(checkout, 'add', 'scripts', 'src', '.github') git(checkout, 'commit', '-m', 'Track the local check fixture') writeFileSync(join(checkout, 'new-helper.ts'), 'export const enabled = true\n') const dirty = spawnSync(process.execPath, [script], { cwd: checkout, diff --git a/scripts/scaffold-module.mjs b/scripts/scaffold-module.mjs index afb6d33a7c..c9a6e50dd0 100644 --- a/scripts/scaffold-module.mjs +++ b/scripts/scaffold-module.mjs @@ -1,4 +1,6 @@ import { readFile, mkdir, readdir, copyFile, writeFile, access } from 'node:fs/promises' +import { execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' import { resolve, dirname } from 'node:path' import { fileURLToPath } from 'node:url' import { parseModuleDocument } from '../src/catalog/module-contract.ts' @@ -78,11 +80,39 @@ this module is endorsed by, supported by, or affiliated with Elektron. Octatrack and Elektron are trademarks of Elektron Music Machines MAV AB, used only to identify the hardware this module targets. ` -if(!id||!['dsp','coldfire'].includes(kind)||!author)throw new Error('Usage: npm run module:new -- my-filter --kind dsp|coldfire --author github-login') +if(!id||!['dsp','coldfire'].includes(kind)||!author)throw new Error('Usage: npm run module:new -- my-filter --kind dsp|coldfire --author github-login [--port airwindows --upstream ]') +// A port starts from upstream's own files at the commit checked out: --port airwindows --upstream . +const port=option('--port',null),upstreamFolder=option('--upstream',null) +if((port||upstreamFolder)&&(kind!=='dsp'||port!=='airwindows'||!upstreamFolder))throw new Error('Usage: npm run module:new -- my-port --kind dsp --port airwindows --upstream /plugins/LinuxVST/src/ --author github-login') const document=JSON.parse(await readFile(resolve(root,'public/module-repository.example.json'),'utf8')) document.id=id;document.key=id.toUpperCase().replaceAll('-',' ');document.name=id.split('-').map(word=>word[0]?.toUpperCase()+word.slice(1)).join(' ');document.author={github:author,credits:[author]} if(kind==='coldfire'){document.category='playback';document.compatibility.location='Flex / Static';document.compatibility.effectId=null;document.controls=[]} parseModuleDocument(document) +const upstream=port?readUpstream(resolve(upstreamFolder)):null +if(upstream){ + document.source={repository:'https://github.com/airwindows/airwindows',revision:upstream.revision,path:upstream.path} + document.author.credits=['Chris Johnson / Airwindows: original '+upstream.name+' algorithm and MIT-licensed source'] + document.license.declaration='Chris Johnson\'s published '+upstream.name+' source and his full MIT copyright and permission notice are retained in upstream/ and LICENSE; the Octatrack adaptation is distributed under the same terms. No desktop binary, firmware, extracted stock routine or table, or memory dump is included.' + parseModuleDocument(document) +} +/** Upstream's files for a port, read from Git at HEAD (never the working tree), so the draft holds exactly one commit's bytes. */ +function readUpstream(folder){ + const git=(...args)=>execFileSync('git',['-C',folder,...args],{encoding:'utf8',stdio:['ignore','pipe','pipe']}).trim() + let top,prefix,revision + try{top=git('rev-parse','--show-toplevel');prefix=git('rev-parse','--show-prefix').replace(/\/$/,'');revision=git('rev-parse','HEAD')}catch{throw new Error('--upstream '+folder+' is not a folder in a Git clone of github.com/airwindows/airwindows')} + if(!prefix)throw new Error('--upstream names the repository itself; name the plugin\'s folder, such as plugins/LinuxVST/src/Mackity') + const blob=(path,sha)=>{const bytes=execFileSync('git',['-C',top,'cat-file','blob',sha],{maxBuffer:4*1024*1024});return{sourcePath:path,sourceBytes:bytes.length,sourceGitBlob:sha,sourceSha256:createHash('sha256').update(bytes).digest('hex'),bytes}} + const tree=path=>execFileSync('git',['-C',top,'ls-tree','-z','HEAD','--',path],{encoding:'utf8'}).split('\0').filter(Boolean).map(line=>{const[meta,name]=line.split('\t'),[mode,type,sha]=meta.split(' ');return{mode,type,sha,name}}) + const files=tree(prefix+'/').filter(entry=>entry.type==='blob') + if(!files.length)throw new Error(prefix+' holds no files at '+revision.slice(0,12)+': commit or check out the plugin first') + if(files.some(entry=>entry.mode==='120000'))throw new Error(prefix+' holds a symbolic link; copy the files it points to by hand') + if(files.length>40)throw new Error(prefix+' holds '+files.length+' files: name one plugin\'s folder') + const [licence]=tree('LICENSE') + if(!licence)throw new Error('No LICENSE at the top of '+top+' at '+revision.slice(0,12)) + const licenceFile=blob('LICENSE',licence.sha) + if(!licenceFile.bytes.toString('utf8').startsWith('MIT License'))throw new Error(top+'/LICENSE is not the MIT licence Airwindows publishes under; ask before porting (MODDING_GUIDELINES.md)') + return{revision,path:prefix,name:prefix.split('/').at(-1),licence:licenceFile,files:files.map(entry=>({...blob(entry.name,entry.sha),file:entry.name.split('/').at(-1)}))} +} // A new Octatrack module starts as a draft: sdk/octatrack/modules/ holds listed modules, and a draft there would block catalogue generation // for everyone. module:dev and module:doctor --draft stage it where the builders look while they run. const destination=output?resolve(output,id):resolve(root,'sdk/drafts',id) @@ -91,15 +121,26 @@ try{await access(destination);throw new Error('Destination exists; refusing to r await mkdir(destination,{recursive:true});await mkdir(resolve(destination,'media')) const template=resolve(root,'sdk/templates',kind),placeholder=kind==='dsp'?'_template':'_template_cf' for(const file of await readdir(template)){if(file==='manifest.py'){let source=await readFile(resolve(template,file),'utf8');source=source.replaceAll('__AUTHOR__',author).replaceAll(placeholder,id).replaceAll(kind==='dsp'?'TEMPLATE':'TEMPLATE CF',document.key).replace('abbr=b"TMPL"','abbr=b"'+document.key.replace(/[^A-Z0-9]/g,'').slice(0,4)+'"').replace('fullname=b"Template"','fullname=b"'+document.name.slice(0,12)+'"');await writeFile(resolve(destination,file),source)}else await copyFile(resolve(template,file),resolve(destination,file))} +if(upstream){ + // A port's reference model, its host test and the gates on the shared harness (sdk/octatrack/tools/dsp_gate.py), over the dsp + // template; upstream's files as they are at the pinned commit, and the import record a listing moves to sdk/imports/. + const portTemplate=resolve(root,'sdk/templates/dsp-port'),fill=text=>text.replaceAll('__ID__',id).replaceAll('__NAME__',document.name).replaceAll('__UPSTREAM__',upstream.name).replaceAll('__REVISION__',upstream.revision) + for(const entry of await readdir(portTemplate,{withFileTypes:true}))if(entry.isFile()&&entry.name!=='README.md'&&!entry.name.endsWith('.pyc'))await writeFile(resolve(destination,entry.name),fill(await readFile(resolve(portTemplate,entry.name),'utf8'))) + await mkdir(resolve(destination,'upstream')) + const vendored=[...upstream.files,{...upstream.licence,file:'LICENSE'}] + for(const item of vendored)await writeFile(resolve(destination,'upstream',item.file),item.bytes) + await writeFile(resolve(destination,'import-record.json'),JSON.stringify({schemaVersion:1,repository:document.source.repository,revision:upstream.revision,moduleVersion:document.version,root:'sdk/octabam/modules/'+id,modules:[id], + files:vendored.map(({file,sourcePath,sourceBytes,sourceGitBlob,sourceSha256})=>({path:'upstream/'+file,sourcePath,sourceBytes,sourceGitBlob,sourceSha256,vendoredSha256:sourceSha256}))},null,2)+'\n') +} await writeFile(resolve(destination,'octamod.module.json'),JSON.stringify(document,null,2)+'\n') // The author's own MIT licence, as the manifest declares (license.spdx). Octabam's LICENSE names Octabam's author and covers that -// repository, not a new module. -await writeFile(resolve(destination,'LICENSE'),mitLicence(author)) +// repository, not a new module. A port keeps upstream's licence and its notice, as its manifest declares. +await writeFile(resolve(destination,'LICENSE'),upstream?upstream.licence.bytes:mitLicence(author)) await copyFile(resolve(root,'public/module-qualification.example.json'),resolve(destination,'qualification.example.json')) await copyFile(resolve(root,'public/module-resource-impact.example.json'),resolve(destination,'resource-impact.example.json')) // A draft's README and TESTING.md: the headings a listed module needs (scripts/module-documentation.mjs), one line each. What a release // needs beyond that, module:doctor -- --draft --release lists, with the fix for each. -await writeFile(resolve(destination,'README.md'),`# ${document.name}\n\nVersion ${document.version} · by @${author} · a draft, not tested yet.\n\n## Overview\n\nWhat it does to the sound or the workflow, in two or three sentences.\n\n## Controls\n\nEach control: its name, range and default, and what it does. Keep the controls in octamod.module.json the same.\n\n## Usage\n\nWhere a musician finds it on the unit, key by key.\n\n## Quick tutorial\n\n1. Set it up.\n2. Change a control and hear what it does.\n3. Get back to where you started.\n\n## Compatibility and limitations\n\nWhat it cannot run beside, and why. Not known yet.\n\n## Tests and measurements\n\nSee [TESTING.md](TESTING.md).\n\n## Authorship and licences\n\nYour own code under the licence in LICENSE. Name anyone whose work it builds on.\n\n## Screens and audio\n\nNone yet.\n\n## Develop\n\n- Hear it: \`npm run module:dev -- ${id}\` builds it and tries it on your unit over USB; \`--watch\` does that again on every save.\n- Check it: \`npm run module:doctor -- --draft ${id}\`. Its experimental lines must be green to share the draft; its release lines say what listing it needs.\n- Before you write ${kind==='dsp'?'DSP':'ColdFire'} code: the traps in sdk/octabam/AGENTS.md, and docs/OCTATRACK_API.md for the hooks a module can use.\n`) +await writeFile(resolve(destination,'README.md'),`# ${document.name}\n\nVersion ${document.version} · by @${author} · a draft, not tested yet.\n\n## Overview\n\nWhat it does to the sound or the workflow, in two or three sentences.\n\n## Controls\n\nEach control: its name, range and default, and what it does. Keep the controls in octamod.module.json the same.\n\n## Usage\n\nWhere a musician finds it on the unit, key by key.\n\n## Quick tutorial\n\n1. Set it up.\n2. Change a control and hear what it does.\n3. Get back to where you started.\n\n## Compatibility and limitations\n\nWhat it cannot run beside, and why. Not known yet.\n\n## Tests and measurements\n\nSee [TESTING.md](TESTING.md).\n\n## Authorship and licences\n\n${upstream?`A port of Chris Johnson's Airwindows ${upstream.name} (MIT), from ${document.source.repository} at ${upstream.revision}, ${upstream.path}; his files are in upstream/ and his licence in LICENSE.`:'Your own code under the licence in LICENSE. Name anyone whose work it builds on.'}\n\n## Screens and audio\n\nNone yet.\n\n## Develop\n\n${upstream?`- Port it: upstream's algorithm into reference.py's float_model, then engine.asm and reference.Model side by side; \`python3 -B test_reference.py\` holds the model to upstream (no tools), \`python3 -B verify.py\` the assembly to the model in dsp_host, \`python3 -B perf.py\` measures it. Both fail until reference.PORTED is True. sdk/octatrack/modules/mackity/ is a finished port; sdk/templates/dsp-port/README.md says what each file is.\n`:''}- Hear it: \`npm run module:dev -- ${id}\` builds it and tries it on your unit over USB; \`--watch\` does that again on every save.\n- Check it: \`npm run module:doctor -- --draft ${id}\`. Its experimental lines must be green to share the draft; its release lines say what listing it needs.\n- Before you write ${kind==='dsp'?'DSP':'ColdFire'} code: the traps in sdk/octabam/AGENTS.md, and docs/OCTATRACK_API.md for the hooks a module can use.\n`) await writeFile(resolve(destination,'TESTING.md'),`# ${document.name} testing\n\nRecord what you ran, on which build and which unit, and what you saw. "Not tested" is a valid answer; never write a result you did not observe, and keep emulator runs apart from hardware ones.\n\n## On the unit\n\nNot tested.\n\n## Stock flows\n\nNot tested. List the stock flows you compared with and without the module (docs/module-guides/README.md, Leave stock flows alone).\n\n${document.category==='effects'?'## Sound quality\n\nNot tested. npm run fx:audit checks aliasing, DC, clipping and idle behaviour (docs/module-guides/effects.md, Sound quality).\n\n':''}## Performance\n\nNot measured. Listing it needs evidence/performance.json: npm run perf:audit -- template ${kind==='coldfire'?'coldfire':'dsp'} (docs/MODULE_PERFORMANCE.md).\n`) -console.log('Created '+destination+(output?'':'\nIt is a draft: it stays out of the library until it is listed.')+'\nHear it on your unit: npm run module:dev -- '+id+' (add --watch to rebuild and try again on every save)\nCheck it: npm run module:doctor -- --draft '+id+'\nRead docs/module-guides/'+document.category+'.md first (set the manifest category to what the module is), and docs/module-guides/sequencing.md if it acts in time.') +console.log('Created '+destination+(output?'':'\nIt is a draft: it stays out of the library until it is listed.')+(upstream?'\nUpstream: '+upstream.files.length+' files of '+upstream.path+' and its LICENSE at '+upstream.revision.slice(0,12)+' in upstream/, recorded in import-record.json. Port it as README.md says (Develop).':'')+'\nHear it on your unit: npm run module:dev -- '+id+' (add --watch to rebuild and try again on every save)\nCheck it: npm run module:doctor -- --draft '+id+'\nRead docs/module-guides/'+document.category+'.md first (set the manifest category to what the module is), and docs/module-guides/sequencing.md if it acts in time.') await claimModule() diff --git a/scripts/test-procedure.mjs b/scripts/test-procedure.mjs index a45f170eda..5aeb287547 100644 --- a/scripts/test-procedure.mjs +++ b/scripts/test-procedure.mjs @@ -20,11 +20,15 @@ // npm run test:procedure -- … --target emulator --share SOCK --dev-socket SOCK # steps 6 to 10 against an emulator session // # (npm run device -- serve --emulator): the same cases, never hardware evidence // npm run test:procedure -- … --out DIR --soak-seconds 120 --scene "A01, Part 1, stopped" +// npm run test:procedure -- … --price-base "base 0.8.1, MKII" # step 9 also writes the CPU price and the instance curve +// # into the module's folder, a draft's too (device:price --write) // npm run test:procedure -- … --soak-programs 32-35 --soak-pc-channel 11 [--soak-auto-channel 11] # the soak's program // # changes and channels, as the project receives them (octatrack-soak.mjs) // // With the unit queue (`npm run unit`, when the repository has it) the unit steps run as one turn of it, so no other session -// takes the unit between reading it and checking it was put back. +// takes the unit between reading it and checking it was put back. With a unit session, the preflight +// (scripts/octatrack-preflight.py) reads the unit before step 1 and again as the turn starts: a release base, a changed Part, +// a busy pick pattern or a dead MIDI bridge then fails step 6 in seconds, with the fix, before anything is installed. import { spawn, execFileSync } from 'node:child_process' import { createHash } from 'node:crypto' import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' @@ -32,6 +36,7 @@ import { tmpdir } from 'node:os' import { basename, dirname, join, relative, resolve } from 'node:path' import { parseArgs } from 'node:util' import { pathToFileURL } from 'node:url' +import { bankPrograms } from './octatrack-part-state.mjs' export const ROOT = resolve(import.meta.dirname, '..') @@ -40,7 +45,19 @@ export const ROOT = resolve(import.meta.dirname, '..') const SOAK_OPTIONS = [['programs', 'programs', 'soak-programs'], ['pcChannel', 'pc-channel', 'soak-pc-channel'], ['autoChannel', 'auto-channel', 'soak-auto-channel']] const soakOptions = ctx => SOAK_OPTIONS.flatMap(([key, flag]) => ctx.soak?.[key] ? ['--' + flag, String(ctx.soak[key])] : []) const soakFlags = ctx => SOAK_OPTIONS.flatMap(([key, , flag]) => ctx.soak?.[key] ? ['--' + flag, String(ctx.soak[key])] : []) -const SOAK_TOOL = 'scripts/octatrack-soak.mjs', SCAN_TOOL = 'scripts/cycle-scan.mjs' +const SOAK_TOOL = 'scripts/octatrack-soak.mjs', SCAN_TOOL = 'scripts/cycle-scan.mjs', PREFLIGHT_TOOL = 'scripts/octatrack-preflight.py' +const SOAK_MIDI = '127.0.0.1:50124' // the MIDI bridge the soak sends through (its default --midi) +const NOT_READY = 'stopped: the preflight found the unit not ready (step 6)' +// The Part the run starts on: step 6 reads it (and SAVEs a clean one once, so RELOAD works after a RAM boot), the soak's end +// and step 10 put the bank, pattern and Part back and RELOAD a Part that was clean at the start (docs/TEST_PROCEDURE.md). +const PART_TOOL = 'scripts/octatrack-part-state.mjs', NOT_PUT_BACK = /^not (?:put back|read): .*$/m +const partFile = ctx => join(ctx.out, 'part-start.json') +const partRead = ctx => node(PART_TOOL, 'read', '--socket', ctx.share, '--out', partFile(ctx), ...(ctx.soak?.programs ? ['--programs', String(ctx.soak.programs)] : [])) +const partRestore = ctx => node(PART_TOOL, 'restore', '--socket', ctx.share, '--start', partFile(ctx)) +/** The soak's program changes: those given, else patterns 1 to 4 of the bank the run started on, never the owner's bank A. */ +const soakPrograms = ctx => !ctx.soak?.programs && ctx.partStart ? ['--programs', bankPrograms(ctx.partStart.bank)] : [] +/** The part tool's JSON line ({"part": …}) in a step's output. */ +const partReading = text => { for (const line of (text ?? '').trim().split('\n').reverse()) { try { const part = JSON.parse(line).part; if (part) return part } catch { /* not this line */ } } return undefined } const REFUSED = /^refused: .*$/m // device.mjs set prints a refusal and exits 0, so the large-set steps read their output const CURVE_TRACKS = 'T1,T3,T6,T7' // empty tracks of the test bank (docs/MODULE_PERFORMANCE.md) const DEFAULT_SCENE = 'the bank, pattern and Part the unit was on, transport stopped (test:procedure)' @@ -73,7 +90,7 @@ export const STEPS = [ { id: 'unit-pass', title: 'Scripted unit pass', baseTitle: 'Large set and Undo', applies: 'both', unit: true }, { id: 'soak', title: 'Soak', applies: 'both', unit: true }, { id: 'cost-unit', title: 'Cost on the unit', applies: 'both', unit: true }, - { id: 'restore', title: 'Put back', applies: 'both', unit: true }, + { id: 'restore', title: 'Put back', applies: 'both', unit: true, always: true }, // also after a later unit step failed { id: 'by-hand', title: 'Agent by hand', applies: 'both', hand: true }, { id: 'developer', title: 'Submitter\'s own stage', applies: 'both', hand: true }, ] @@ -159,7 +176,7 @@ export function plan(step, ctx) { return { commands: [module ? node('scripts/device.mjs', 'try', pkg, '--seconds', '20', '--emulator', '--socket', ctx.emulatorSocket) : node('scripts/device.mjs', 'set', set, '--seconds', '20', '--split', '--emulator', '--socket', ctx.emulatorSocket)], emulator: true, failOn: REFUSED } case 'unit-read': - return { commands: [node('scripts/device.mjs', 'status', '--socket', ctx.share), node('scripts/device.mjs', 'do', 'inventory', '--socket', ctx.share)] } + return { commands: [node('scripts/device.mjs', 'status', '--socket', ctx.share), partRead(ctx), node('scripts/device.mjs', 'do', 'inventory', '--socket', ctx.share)], why: NOT_PUT_BACK } case 'unit-pass': if (!module) return { commands: [node('scripts/device.mjs', 'set', set, '--seconds', '30', '--split', '--socket', ctx.share)], failOn: REFUSED } return { commands: [npmRun('device:test', '--share', ctx.share, '--testing-entry', join(ctx.out, 'device-test.md'), @@ -168,19 +185,23 @@ export function plan(step, ctx) { if (ctx.target === 'emulator' && ctx.tools?.soak) return { skip: 'the fast soak sends USB MIDI to the unit\'s port, which the emulator has not' } if (!ctx.tools?.soak) return module ? { inside: 'unit-pass', note: 'ran inside the scripted pass as device:test --soak ' + ctx.soakSeconds + '; the fast seeded soak (' + SOAK_TOOL + ', pull request #1770) is not in this checkout yet' } : { skip: 'the fast seeded soak (' + SOAK_TOOL + ', pull request #1770) is not in this checkout yet' } - const soak = node(SOAK_TOOL, '--seconds', String(ctx.soakSeconds), ...soakOptions(ctx), '--log', join(ctx.out, 'soak.json')) - // A module soaks inside a trial of its own, rolled back at the end; a base soaks with whatever the unit runs. - return module ? { commands: [soak], trial: node('scripts/device.mjs', 'try', pkg, '--seconds', String(ctx.soakSeconds + 300), '--socket', ctx.share) } : { commands: [soak] } + const soak = node(SOAK_TOOL, '--seconds', String(ctx.soakSeconds), ...soakPrograms(ctx), ...soakOptions(ctx), '--log', join(ctx.out, 'soak.json')) + // A module soaks inside a trial of its own, rolled back at the end; a base soaks with whatever the unit runs. Its program + // changes and CCs move the pattern and edit the Part, so step 9 starts where step 6 did, with the Part reloaded. + return module ? { commands: [soak, partRestore(ctx)], why: NOT_PUT_BACK, trial: node('scripts/device.mjs', 'try', pkg, '--seconds', String(ctx.soakSeconds + 300), '--socket', ctx.share) } + : { commands: [soak, partRestore(ctx)], why: NOT_PUT_BACK } } case 'cost-unit': if (ctx.target === 'emulator') return { skip: EMULATOR_FIGURES } if (module && ctx.baseBound) return { skip: 'a base-bound package: device:price leaves it out, since a development twin does not trust it' } // A module also reads its instance curve and runs the admission test (alone on the empty and the medium pattern: admitted, // nothing dropped), and device:price fails the step when either does not carry a release (owner, 23 November 2026). + // --price-base names the base for the record: then the price and the curve land in the module's folder, a draft's too. return { commands: [npmRun('device:price', '--share', ctx.share, '--out', join(ctx.out, 'price.json'), '--scene', ctx.scene ?? DEFAULT_SCENE, + ...(module && ctx.priceBase && ctx.source ? ['--write', '--base', ctx.priceBase] : []), ...(module ? ['--curve', CURVE_TRACKS, ...(ctx.pickPattern ? ['--pick-pattern', ctx.pickPattern] : []), ...(ctx.measurePattern ? ['--measure-pattern', ctx.measurePattern] : []), pkg] : ctx.priceModules ?? []))] } case 'restore': - return { commands: [node('scripts/device.mjs', 'do', 'inventory', '--socket', ctx.share)], compare: 'unit-read' } + return { commands: [node('scripts/device.mjs', 'do', 'inventory', '--socket', ctx.share), partRestore(ctx)], compare: 'unit-read', compareAt: 0, why: NOT_PUT_BACK } case 'by-hand': return { todo: BY_HAND[ctx.kind] } case 'developer': return { todo: DEVELOPER[ctx.kind] } } @@ -208,7 +229,10 @@ export async function runSteps(ids, ctx, deps, results = []) { const p = plan(step, ctx) result.commands = [...(p.trial ? [p.trial] : []), ...(p.commands ?? [])].map(shown) if (p.emulator) result.emulator = true - if (stop && stop !== result) { result.reason = `stopped: step ${STEPS.findIndex(s => s.id === stop.id) + 1} (${stop.title}) failed`; continue } + if (ctx.halt) { result.reason = ctx.halt; continue } + // Put back runs after a failed unit step too, once the unit was read: a soak that failed has still edited the Part. + const putBack = step.always && results.some(r => r.id === 'unit-read' && r.status === 'passed') + if (stop && stop !== result && !putBack) { result.reason = `stopped: step ${STEPS.findIndex(s => s.id === stop.id) + 1} (${stop.title}) failed`; continue } if (p.skip) { result.reason = p.skip; continue } if (step.unit && !ctx.unit?.available) { result.reason = ctx.unit?.reason ?? 'no unit session'; continue } if (p.todo) { result.status = 'to do'; result.todo = p.todo; continue } @@ -227,13 +251,15 @@ export async function runSteps(ids, ctx, deps, results = []) { trial = deps.start(p.trial, log, ctx.env) await trial.waitFor(/^trial:.*running$/m, 60000) } - const outputs = [] + const outputs = [], codes = [] let code = 0 for (const argv of p.commands) { const run = await deps.exec(argv, log, ctx.env) - outputs.push(run.output ?? '') - if (run.code !== 0) { code = run.code; result.reason = `exit ${run.code}: ${shown(argv)}`; break } + outputs.push(run.output ?? ''); codes.push(run.code) + if (run.code !== 0) { code = run.code; result.reason = (p.why && (run.output ?? '').match(p.why)?.[0].slice(0, 400)) || `exit ${run.code}: ${shown(argv)}`; break } } + const part = partReading(outputs.join('\n')) + if (part?.summary) result.part = part.summary const refused = code === 0 && p.failOn && outputs.join('\n').match(p.failOn) if (refused) { code = 1; result.reason = refused[0].slice(0, 200) } if (trial) { @@ -246,10 +272,16 @@ export async function runSteps(ids, ctx, deps, results = []) { if (!deps.exists(ctx.pkg)) { code = 1; result.reason = 'no package at ' + ctx.pkg } else ctx.build.package = { path: ctx.pkg, sha256: deps.sha256(ctx.pkg) } } - if (code === 0 && step.id === 'unit-read') ctx.startInventory = reading(outputs.at(-1)) - if (code === 0 && p.compare) { - const now = reading(outputs.at(-1)) - if (JSON.stringify(now) !== JSON.stringify(ctx.startInventory)) { code = 1; result.reason = 'the inventory differs from the one read first: ' + JSON.stringify(ctx.startInventory) + ' then ' + JSON.stringify(now) } + if (code === 0 && step.id === 'unit-read') { ctx.startInventory = reading(outputs.at(-1)); if (part?.banks) ctx.partStart = part } + // The inventory is compared whenever its own command ran, also when the Part could not be put back after it. + const at = p.compareAt ?? p.commands.length - 1 + if (p.compare && codes[at] === 0) { + const now = reading(outputs[at]) + if (JSON.stringify(now) !== JSON.stringify(ctx.startInventory)) { + const why = 'the inventory differs from the one read first: ' + JSON.stringify(ctx.startInventory) + ' then ' + JSON.stringify(now) + result.reason = code ? result.reason + '; and ' + why : why + code ||= 1 + } } result.status = code === 0 ? 'passed' : 'failed' } catch (error) { @@ -261,10 +293,50 @@ export async function runSteps(ids, ctx, deps, results = []) { return results } +/** The preflight's command: read-only requests (with --midi, one tune request through the soak's MIDI bridge) that find in + * seconds what failed unit runs minutes in (25 November 2026). Null where it has nothing to check. A module's pick goes on + * the pattern the unit is on (device:test), so a module's run checks that pattern too; the emulator gets neither the pick's + * admission nor the soak. */ +export function preflightCommand(ctx) { + if (other(ctx) || !ctx.unit?.available) return null + const unit = ctx.target !== 'emulator' + return py(PREFLIGHT_TOOL, ...(unit && ctx.kind === 'module' ? ['--pick-pattern', String(ctx.pickPattern ?? 2)] : []), ...(unit && ctx.tools?.soak ? ['--midi', SOAK_MIDI] : [])) +} + +/** The problems the preflight printed, one with its fix each; none when it passed or had nothing to check. */ +export async function preflight(ctx, deps, log) { + const argv = preflightCommand(ctx) + if (!argv) return [] + const run = await deps.exec(argv, log, ctx.env) + if (run.code === 0) return [] + const lines = (run.output ?? '').split('\n').filter(line => line.startsWith('preflight: ')).map(line => line.slice('preflight: '.length)) + return lines.length ? lines : [`exit ${run.code}: ${shown(argv)}`] +} + +/** Step 6 failed by the preflight's problems: nothing after it ran. */ +function notReady(ctx, results, problems, log) { + Object.assign(results.find(result => result.id === 'unit-read'), { status: 'failed', reason: 'the unit is not ready: ' + problems.join('; '), log: relative(ctx.out, log) }) + return results +} + +/** The unit steps, after the preflight: a problem it finds fails step 6 before anything is installed. */ +export async function unitSteps(ctx, deps, results = []) { + const ids = STEPS.filter(step => step.unit).map(step => step.id), log = join(ctx.out, 'logs', '06-preflight.log') + const problems = await preflight(ctx, deps, log) + if (!problems.length) return runSteps(ids, ctx, deps, results) + await runSteps(ids, { ...ctx, halt: NOT_READY }, deps, results) + return notReady(ctx, results, problems, log) +} + /** The whole procedure: the steps before the unit here, the unit steps in one turn of the unit queue when there is one. */ export async function runProcedure(ctx, deps) { const local = STEPS.filter(step => !step.unit && !step.hand).map(step => step.id) const unit = STEPS.filter(step => step.unit).map(step => step.id) + // The preflight before step 1, unless another session's turn holds the unit: what it reads then is that run's (a Part it + // changed), so it waits for this run's own turn, where it runs again. + const early = join(ctx.out, 'logs', '00-preflight.log') + const problems = ctx.tools?.unitQueue && ctx.target !== 'emulator' && await deps.unitBusy?.() ? [] : await preflight(ctx, deps, early) + if (problems.length) return notReady(ctx, await runSteps(STEPS.map(step => step.id), { ...ctx, halt: NOT_READY + ', before step 1' }, deps), problems, early) const results = await runSteps(local, ctx, deps) const blocked = results.some(result => result.status === 'failed') if (!blocked && ctx.unit?.available && ctx.tools?.unitQueue && ctx.target !== 'emulator') { @@ -280,7 +352,8 @@ export async function runProcedure(ctx, deps) { results.find(result => result.id === 'unit-read').status = 'failed' results.find(result => result.id === 'unit-read').seconds = Math.round((deps.now() - started) / 100) / 10 } - } else await runSteps(unit, ctx, deps, results) + } else if (blocked) await runSteps(unit, ctx, deps, results) + else await unitSteps(ctx, deps, results) await runSteps(STEPS.filter(step => step.hand).map(step => step.id), ctx, deps, results) return results } @@ -318,7 +391,7 @@ export function recordMarkdown(record) { `Build: revision \`${build.revision.slice(0, 12)}\`${build.dirty ? ' with uncommitted changes' : ''}, ${build.package ? `package \`${basename(build.package.path)}\` SHA-256 \`${sha}\`` : 'no package named'}. ` + `\`${record.command}\`, ${record.seconds} s. Emulator results are not hardware evidence; only what ran on the unit is.`, '', '| # | Step | Layer | Result | Command | Evidence |', '|---|---|---|---|---|---|', - ...steps.map((step, index) => `| ${index + 1} | ${step.title}${step.emulator ? ' (emulator)' : ''} | ${step.layer === 'target' ? (step.emulator ? 'emulator' : 'unit') : step.layer ?? ''} | ${STATUS_WORD[step.status]}${step.reason ? ': ' + cell(step.reason) : ''} | ${step.commands.map(c => '`' + cell(c) + '`').join('
')} | ${step.log ?? ''} |`), + ...steps.map((step, index) => `| ${index + 1} | ${step.title}${step.emulator ? ' (emulator)' : ''} | ${step.layer === 'target' ? (step.emulator ? 'emulator' : 'unit') : step.layer ?? ''} | ${STATUS_WORD[step.status]}${step.reason ? ': ' + cell(step.reason) : ''}${step.part && step.status === 'passed' ? (step.reason ? '; ' : ': ') + cell(step.part) : ''} | ${step.commands.map(c => '`' + cell(c) + '`').join('
')} | ${step.log ?? ''} |`), '', '#### Edge cases for this change', '', 'Derive them from what the change touches and run each one (docs/TEST_PROCEDURE.md#edge-cases). A start, from the manifest and the changed files:', '', ...(record.edgeCases.suggested.length ? record.edgeCases.suggested.map(s => `- ${s.touches}: ${s.ask} (docs/${s.see})`) : ['- nothing matched: read the diff']), '', @@ -374,7 +447,7 @@ export function context(root, values, positionals, env = process.env) { let ctx = { kind: values.base ? 'base' : 'module', share, target, devSocket, // The session's line socket for device:test's steps; an emulator takes no turn of the unit queue. env: { ...(devSocket ? { MODWERK_DEV_SOCKET: devSocket } : {}), ...(target === 'emulator' ? { MODWERK_UNIT: 'emulator' } : {}) }, soakSeconds: Number(values['soak-seconds'] ?? 120), - soak: { programs: values['soak-programs'], pcChannel: values['soak-pc-channel'], autoChannel: values['soak-auto-channel'] }, scene: values.scene, pickPattern: values['pick-pattern'], measurePattern: values['measure-pattern'], emulatorSocket: values['emulator-socket'], + soak: { programs: values['soak-programs'], pcChannel: values['soak-pc-channel'], autoChannel: values['soak-auto-channel'] }, scene: values.scene, priceBase: values['price-base'], pickPattern: values['pick-pattern'], measurePattern: values['measure-pattern'], emulatorSocket: values['emulator-socket'], tools: { cycleScan: existsSync(join(root, SCAN_TOOL)), soak: existsSync(join(root, SOAK_TOOL)), unitQueue: !!scripts.unit }, build: { revision: git('rev-parse', 'HEAD') || 'unknown', dirty: !!git('status', '--porcelain', '--untracked-files=no') } } const named = positionals[0] @@ -454,6 +527,13 @@ function realDeps(root) { read: path => readFileSync(path, 'utf8'), sha256: path => createHash('sha256').update(readFileSync(path)).digest('hex'), exec: async (argv, log, env) => { const { state } = launch(argv, log, env); const code = await state.done; return { code, output: state.output } }, + // Another session's turn (not a hold of this checkout's): its first line, which the run prints, else null. + unitBusy: async () => { + const { checkoutOf, describe } = await import('./unit-queue.mjs'), queue = describe() + if (queue.state !== 'held' || process.env.MODWERK_UNIT_TURN || queue.holder?.checkout === checkoutOf(root).checkout) return null + console.log(`\n${queue.text.split('\n')[0]} The preflight waits for this run's own turn.`) + return queue.text.split('\n')[0] + }, start: (argv, log, env) => { const { child, state } = launch(argv, log, env) let ended = false @@ -480,14 +560,14 @@ function realDeps(root) { const OPTIONS = { base: { type: 'boolean' }, package: { type: 'string' }, published: { type: 'boolean' }, plan: { type: 'boolean' }, out: { type: 'string' }, share: { type: 'string' }, 'no-unit': { type: 'boolean' }, 'emulator-socket': { type: 'string' }, 'soak-seconds': { type: 'string' }, 'soak-programs': { type: 'string' }, 'soak-pc-channel': { type: 'string' }, 'soak-auto-channel': { type: 'string' }, scene: { type: 'string' }, 'pick-pattern': { type: 'string' }, 'measure-pattern': { type: 'string' }, - 'price-modules': { type: 'string' }, target: { type: 'string' }, 'dev-socket': { type: 'string' }, 'unit-phase': { type: 'string' }, help: { type: 'boolean', short: 'h' }, + 'price-modules': { type: 'string' }, 'price-base': { type: 'string' }, target: { type: 'string' }, 'dev-socket': { type: 'string' }, 'unit-phase': { type: 'string' }, help: { type: 'boolean', short: 'h' }, stock: { type: 'string' }, elemod: { type: 'string' }, label: { type: 'string' }, link: { type: 'boolean' }, cases: { type: 'string' }, emu: { type: 'string' } } async function main() { const { values, positionals } = parseArgs({ allowPositionals: true, options: OPTIONS }) if (values.help || (!values.base && !positionals.length)) { console.log('Usage: npm run test:procedure -- | FILE.mwrm | --base [machine] [--plan] [--package FILE] [--published] [--share SOCKET] [--no-unit]\n' + - ' [--target unit|emulator] [--dev-socket SOCK] [--emulator-socket SOCK] [--out DIR] [--soak-seconds 120] [--soak-programs 0-3] [--soak-pc-channel 1] [--soak-auto-channel 1] [--scene TEXT] [--pick-pattern 2] [--measure-pattern 1] [--price-modules a,b]\n' + + ' [--target unit|emulator] [--dev-socket SOCK] [--emulator-socket SOCK] [--out DIR] [--soak-seconds 120] [--soak-programs 0-3] [--soak-pc-channel 1] [--soak-auto-channel 1] [--scene TEXT] [--pick-pattern 2] [--measure-pattern 1] [--price-modules a,b] [--price-base TEXT]\n' + ' another machine: [--stock STOCK.syx --elemod BASE.elemod --label XX01] [--link] [--cases DIR] [--emu DTBOOT] (docs/TEST_PROCEDURE.md)') process.exit(values.help ? 0 : 2) } @@ -496,7 +576,7 @@ async function main() { const deps = realDeps(ROOT) if (values['unit-phase']) { // One turn of the unit queue: only the unit steps, their results for the run that started it. - const results = await runSteps(STEPS.filter(step => step.unit).map(step => step.id), ctx, deps) + const results = await unitSteps(ctx, deps) writeFileSync(values['unit-phase'], JSON.stringify(results, null, 1) + '\n') process.exit(results.some(result => result.status === 'failed') ? 1 : 0) } @@ -516,7 +596,7 @@ async function main() { const result = record(ctx, steps, { started, finished: Date.now(), command }) writeFileSync(join(ctx.out, 'procedure.json'), JSON.stringify(result, null, 1) + '\n') writeFileSync(join(ctx.out, 'procedure.md'), recordMarkdown(result)) - console.log('\n' + steps.map((step, index) => `${String(index + 1).padStart(2)}. ${step.title}: ${step.status}${step.reason ? ' (' + step.reason + ')' : ''}`).join('\n')) + console.log('\n' + steps.map((step, index) => `${String(index + 1).padStart(2)}. ${step.title}: ${step.status}${step.reason ? ' (' + step.reason + ')' : step.part ? ' (' + step.part + ')' : ''}`).join('\n')) console.log(`\nRecord: ${join(ctx.out, 'procedure.md')} and procedure.json, ${result.seconds} s. Fill in its edge-case table, run each case, then copy the entry to ` + (ctx.kind === 'base' ? 'docs/verification/-.md' : `the module's TESTING.md`) + ' and its last two lines to the pull request.') process.exitCode = steps.some(step => step.status === 'failed') ? 1 : 0 diff --git a/scripts/test-procedure.test.mjs b/scripts/test-procedure.test.mjs index 3f7b672f3a..5dd0fb4353 100644 --- a/scripts/test-procedure.test.mjs +++ b/scripts/test-procedure.test.mjs @@ -3,7 +3,7 @@ import { mkdtempSync, readFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' -import { context, LAYER, largeSet, plan, reading, record, recordMarkdown, runProcedure, STEPS, suggestEdgeCases } from './test-procedure.mjs' +import { context, LAYER, largeSet, plan, preflightCommand, reading, record, recordMarkdown, runProcedure, STEPS, suggestEdgeCases, unitSteps } from './test-procedure.mjs' import { bodyProblems } from './pr-body.mjs' const INVENTORY = '[{"name":"KITS","version":"0.2.0"}]' @@ -37,6 +37,7 @@ function fakeDeps({ fail = [], inventories = [INVENTORY, INVENTORY], idents = [' } } const statuses = steps => Object.fromEntries(steps.map(step => [step.id, step.status])) +const PREFLIGHT = 'python3 -B scripts/octatrack-preflight.py --pick-pattern 2' describe('the steps', () => { it('runs in the fixed order, the unit steps after the software, emulator and build steps', () => { @@ -48,14 +49,18 @@ describe('the steps', () => { const deps = fakeDeps() const steps = await runProcedure(moduleCtx(), deps) expect(deps.ran).toEqual([ + PREFLIGHT, // before step 1, and again as the unit steps start 'npm run module:doctor -- vibrato', 'npm run modules:compat -- vibrato', 'npm run module:dev -- vibrato --build-only --out /out/vibrato.mwrm', + PREFLIGHT, 'node scripts/device.mjs status --socket /tmp/share.sock', + 'node scripts/octatrack-part-state.mjs read --socket /tmp/share.sock --out /out/part-start.json', 'node scripts/device.mjs do inventory --socket /tmp/share.sock', 'npm run device:test -- --share /tmp/share.sock --testing-entry /out/device-test.md --soak 120 /out/vibrato.mwrm', expect.stringMatching(/^npm run device:price -- --share \/tmp\/share.sock --out \/out\/price.json --scene .+ --curve T1,T3,T6,T7 \/out\/vibrato.mwrm$/), // the curve and the admission run 'node scripts/device.mjs do inventory --socket /tmp/share.sock', + 'node scripts/octatrack-part-state.mjs restore --socket /tmp/share.sock --start /out/part-start.json', ]) expect(statuses(steps)).toEqual({ software: 'passed', compat: 'passed', build: 'passed', 'cost-model': 'not run', emulator: 'not run', 'unit-read': 'passed', 'unit-pass': 'passed', soak: 'passed', 'cost-unit': 'passed', restore: 'passed', 'by-hand': 'to do', developer: 'to do' }) @@ -66,7 +71,7 @@ describe('the steps', () => { it('stops at the first failure and records every later step as not run, with the step that stopped it', async () => { const deps = fakeDeps({ fail: ['modules:compat'] }) const steps = await runProcedure(moduleCtx(), deps) - expect(deps.ran).toEqual(['npm run module:doctor -- vibrato', 'npm run modules:compat -- vibrato']) + expect(deps.ran).toEqual([PREFLIGHT, 'npm run module:doctor -- vibrato', 'npm run modules:compat -- vibrato']) expect(statuses(steps)).toMatchObject({ software: 'passed', compat: 'failed', build: 'not run', 'unit-pass': 'not run', 'by-hand': 'not run', developer: 'not run' }) expect(steps.find(step => step.id === 'build').reason).toBe('stopped: step 2 (Beside every other module) failed') expect(steps.find(step => step.id === 'compat').reason).toBe('exit 1: npm run modules:compat -- vibrato') @@ -89,6 +94,56 @@ describe('the steps', () => { expect(steps.find(step => step.id === 'restore')).toMatchObject({ status: 'failed', reason: expect.stringMatching(/inventory differs/) }) }) + const START = JSON.stringify({ part: { bank: 2, pattern: 0, part: 0, stopped: true, saved: true, banks: { 2: [] }, summary: 'Part 1 on C01: working = saved, saved once so that RELOAD works at the end' } }) + const READ = 'octatrack-part-state.mjs read', RESTORE = 'octatrack-part-state.mjs restore' + + it('reads the Part at step 6, keeps the soak in that bank, and puts the bank, pattern and Part back after the soak and at step 10', async () => { + const tools = { cycleScan: false, soak: true, unitQueue: false } + const back = JSON.stringify({ part: { ok: true, summary: 'Part 1 on C01: transport stopped, back on C01 from C03, Part 1 on C01 reloaded; working = saved' } }) + const deps = fakeDeps({ said: { [READ]: START, [RESTORE]: back } }), ctx = moduleCtx({ tools }) + const steps = await runProcedure(ctx, deps) + const unit = deps.ran.slice(deps.ran.indexOf('node scripts/device.mjs status --socket /tmp/share.sock')) + expect(unit).toEqual([ + 'node scripts/device.mjs status --socket /tmp/share.sock', + 'node scripts/octatrack-part-state.mjs read --socket /tmp/share.sock --out /out/part-start.json', + 'node scripts/device.mjs do inventory --socket /tmp/share.sock', + 'npm run device:test -- --share /tmp/share.sock --testing-entry /out/device-test.md /out/vibrato.mwrm', + 'node scripts/octatrack-soak.mjs --seconds 120 --programs 32-35 --log /out/soak.json', // bank C's patterns 1-4, not the owner's bank A + 'node scripts/octatrack-part-state.mjs restore --socket /tmp/share.sock --start /out/part-start.json', // before step 9 prices the scene + expect.stringMatching(/^npm run device:price /), + 'node scripts/device.mjs do inventory --socket /tmp/share.sock', + 'node scripts/octatrack-part-state.mjs restore --socket /tmp/share.sock --start /out/part-start.json', + ]) + expect(steps.find(step => step.id === 'unit-read')).toMatchObject({ status: 'passed', part: 'Part 1 on C01: working = saved, saved once so that RELOAD works at the end' }) + expect(steps.find(step => step.id === 'restore')).toMatchObject({ status: 'passed', part: expect.stringMatching(/reloaded; working = saved$/) }) + const md = recordMarkdown(record(ctx, steps, { started: 0, finished: 1000, command: 'npm run test:procedure -- vibrato' })) + expect(md).toContain('| 10 | Put back | unit | passed: Part 1 on C01: transport stopped, back on C01 from C03, Part 1 on C01 reloaded; working = saved |') + // Programs given on the command line stay as given, and the read covers their banks too. + const given = fakeDeps({ said: { [READ]: START } }) + await runProcedure(moduleCtx({ tools, soak: { programs: '0-3' } }), given) + expect(given.ran).toContain('node scripts/octatrack-part-state.mjs read --socket /tmp/share.sock --out /out/part-start.json --programs 0-3') + expect(given.ran).toContain('node scripts/octatrack-soak.mjs --seconds 120 --programs 0-3 --log /out/soak.json') + }) + + it('fails the put-back loudly, with the fix, when the Part cannot be reloaded, and still compares the inventory', async () => { + const refused = 'not put back: RELOAD did not bring Part 1 on C01 back: put it back by hand (docs/OCTATRACK_DRIVING.md#the-rules)' + const steps = await runProcedure(moduleCtx(), fakeDeps({ said: { [READ]: START, [RESTORE]: refused }, fail: [RESTORE], inventories: [INVENTORY, '[]'] })) + expect(steps.find(step => step.id === 'restore')).toMatchObject({ status: 'failed', reason: refused + '; and the inventory differs from the one read first: [{"name":"KITS","version":"0.2.0"}] then []' }) + }) + + it('puts back after a failed soak, but not when the unit was never read', async () => { + const tools = { cycleScan: false, soak: true, unitQueue: false } + const deps = fakeDeps({ said: { [READ]: START }, fail: ['octatrack-soak.mjs'] }) + const steps = await runProcedure(moduleCtx({ tools }), deps) + expect(statuses(steps)).toMatchObject({ soak: 'failed', 'cost-unit': 'not run', restore: 'passed', 'by-hand': 'not run' }) + expect(deps.ran.at(-1)).toBe('node scripts/octatrack-part-state.mjs restore --socket /tmp/share.sock --start /out/part-start.json') + const unread = fakeDeps({ said: { [READ]: 'not read: The unit did not answer the position read' }, fail: [READ] }) + const none = await runProcedure(moduleCtx(), unread) + expect(none.find(step => step.id === 'unit-read')).toMatchObject({ status: 'failed', reason: 'not read: The unit did not answer the position read' }) + expect(none.find(step => step.id === 'restore')).toMatchObject({ status: 'not run', reason: 'stopped: step 6 (Read the unit) failed' }) + expect(unread.ran.some(line => line.includes(RESTORE))).toBe(false) + }) + it('uses a package it is given instead of building one, and names it by its SHA-256', async () => { const deps = fakeDeps(), ctx = moduleCtx({ pkg: '/p/vibrato.mwrm' }) await runProcedure(ctx, deps) @@ -123,7 +178,7 @@ describe('the steps', () => { const deps = fakeDeps() const ctx = moduleCtx({ kind: 'base', id: undefined, machine: 'octatrack', version: '0.7', pkg: '/r/octatrack-base.elemod', setPackages: ['/p/a.mwrm', '/p/b.mwrm'] }) const steps = await runProcedure(ctx, deps) - expect(deps.ran.slice(0, 2)).toEqual(['npm run sdk:check', 'npm run modules:compat']) + expect(deps.ran.slice(0, 3)).toEqual(['python3 -B scripts/octatrack-preflight.py', 'npm run sdk:check', 'npm run modules:compat']) // a base picks nothing expect(deps.ran).toContain('node scripts/device.mjs set /p/a.mwrm,/p/b.mwrm --seconds 30 --split --socket /tmp/share.sock') expect(deps.ran.find(line => line.startsWith('npm run device:price'))).toMatch(/--scene .+[^m]$/) // no package named: every USB package expect(steps.find(step => step.id === 'unit-pass').title).toBe('Large set and Undo') @@ -163,6 +218,49 @@ describe('the steps', () => { }) +describe('the preflight', () => { + // What failed unit runs minutes in on 25 November 2026, as octatrack-preflight.py prints it. + const NOT_READY = 'preflight: Part 1 of bank C differs from its saved copy, …\npreflight: no MIDI bridge on 127.0.0.1:50124 (…): start …' + + it('checks what the unit steps will need: the pick pattern for a module, the MIDI bridge when the soak runs', () => { + expect(preflightCommand(moduleCtx())).toEqual(['python3', '-B', 'scripts/octatrack-preflight.py', '--pick-pattern', '2']) + expect(preflightCommand(moduleCtx({ pickPattern: '5', tools: { soak: true } })).join(' ')).toBe('python3 -B scripts/octatrack-preflight.py --pick-pattern 5 --midi 127.0.0.1:50124') + expect(preflightCommand(moduleCtx({ kind: 'base', id: undefined, tools: { soak: true } })).join(' ')).toBe('python3 -B scripts/octatrack-preflight.py --midi 127.0.0.1:50124') + expect(preflightCommand(moduleCtx({ target: 'emulator', tools: { soak: true } })).join(' ')).toBe('python3 -B scripts/octatrack-preflight.py') + expect(preflightCommand(moduleCtx({ unit: { available: false, reason: 'none' } }))).toBeNull() + expect(preflightCommand(moduleCtx({ machine: 'analog-rytm-mkii' }))).toBeNull() + }) + + it('fails step 6 before step 1 with each problem, and builds, boots and installs nothing', async () => { + const deps = fakeDeps({ fail: ['octatrack-preflight'], said: { 'octatrack-preflight': '> state\n' + NOT_READY } }) + const ctx = moduleCtx({ tools: { soak: true } }), steps = await runProcedure(ctx, deps) + expect(deps.ran).toEqual(['python3 -B scripts/octatrack-preflight.py --pick-pattern 2 --midi 127.0.0.1:50124']) + expect(deps.started).toEqual([]) + expect(steps.find(step => step.id === 'unit-read')).toMatchObject({ status: 'failed', log: 'logs/00-preflight.log', + reason: 'the unit is not ready: Part 1 of bank C differs from its saved copy, …; no MIDI bridge on 127.0.0.1:50124 (…): start …' }) + expect(steps.filter(step => step.id !== 'unit-read').every(step => step.status === 'not run' && /not ready \(step 6\), before step 1/.test(step.reason))).toBe(true) + expect(steps.find(step => step.id === 'unit-pass').commands[0]).toMatch(/^npm run device:test/) // still named + expect(recordMarkdown(record(ctx, steps, { started: 0, finished: 1000, command: 'x' }))).toMatch(/^Not tested on a unit: the unit is not ready: Part 1 of bank C/m) + }) + + it('reads the unit again as the turn starts, and installs nothing when it is no longer ready', async () => { + const deps = fakeDeps({ fail: ['octatrack-preflight'], said: { 'octatrack-preflight': NOT_READY } }) + const steps = await unitSteps(moduleCtx(), deps) + expect(deps.ran).toEqual([PREFLIGHT]) + expect(statuses(steps)).toEqual({ 'unit-read': 'failed', 'unit-pass': 'not run', soak: 'not run', 'cost-unit': 'not run', restore: 'not run' }) + expect(steps.find(step => step.id === 'unit-pass').reason).toBe('stopped: the preflight found the unit not ready (step 6)') + expect(steps.find(step => step.id === 'unit-read').log).toBe('logs/06-preflight.log') + }) + + it('leaves the first reading to this run\'s own turn while another session holds the unit', async () => { + const deps = fakeDeps({ fail: ['npm run unit'] }) + deps.unitBusy = async () => 'The unit is in use: other-worktree (fix/x) has it since 10:00 (4m).' + await runProcedure(moduleCtx({ tools: { unitQueue: true } }), deps) + expect(deps.ran[0]).toBe('npm run module:doctor -- vibrato') + expect(deps.ran.some(line => line.includes('octatrack-preflight'))).toBe(false) // the inner run, in the turn, reads it + }) +}) + describe('every machine', () => { const RYTM = 'sdk/machines/analog-rytm-mkii/tools/' const rytm = (extra = {}) => moduleCtx({ id: 'improved-performance', machine: 'analog-rytm-mkii', machineName: 'Analog Rytm MKII', platform: 'elemod', manifest: { category: 'system', compatibility: { uiClaims: [] } }, diff --git a/sdk/catalog.json b/sdk/catalog.json index b054f48b7e..508659b988 100644 --- a/sdk/catalog.json +++ b/sdk/catalog.json @@ -62,6 +62,11 @@ "version": "0.1.0-experimental", "addedAt": "2026-11-24T11:32:33Z" }, + { + "id": "mackity", + "version": "0.1.0-experimental", + "addedAt": "2026-11-25T08:23:53Z" + }, { "id": "analog-bassdrum", "version": "0.1.7-experimental", diff --git a/sdk/cycle-scan/README.md b/sdk/cycle-scan/README.md index 0fa2f79b14..6b3d06c5fc 100644 --- a/sdk/cycle-scan/README.md +++ b/sdk/cycle-scan/README.md @@ -84,45 +84,56 @@ It is a model, not a measurement: the unit stays the judge ([MODULE_PERFORMANCE. ```bash node scripts/cycle-scan.mjs unit # anywhere: each record against its module's in-use reading; a report, it fails nothing node scripts/cycle-scan.mjs unit --markdown # the table below +node scripts/cycle-scan.mjs unit --write # writes it here; `check` fails when the committed table differs ``` Each module's `evidence/cpu-price.json` holds a reading `npm run device:price` took on an MKII: the DSP load meter of the slot's core with the effect picked on that slot in place of NONE, against the same scene without it (`inUseAdds`; T1-T4 -are core 1's meter, T5-T8 core 0's). A fresh pick starts from the effect's defaults, so the report compares it with the -scan's run at the defaults. **Scale:** one point of the meter is 45.32 cycles a sample. `status.c`'s `busy()` gives per -mille of `FRAME_CYCLES`, 72,520 (4,532 cycles a sample, the board's clock, as `CYCLE_SCAN.md`'s "% of a frame" uses, times -16 samples a frame), from idle passes whose cycles were calibrated on the unit with `--dsp-burn` (11 October 2026, -`idle_cycles` there). A module whose package requires a base DSP feature with a hardware charge in -`sdk/machines/octatrack/dsp-sites.json` (the key bus: 51) has it added to the model, since that work runs outside the -effect's proc and so outside the scan. +are core 1's meter, T5-T8 core 0's). A fresh pick starts from the effect's defaults, so the report compares the reading's +mean with the scan's run at the defaults, and its peak (the core's busiest block, which `device:price` keeps from +24 November 2026) with the dearest run, which bounds every setting. **Scale:** one point of the meter is 45.32 cycles a +sample. `status.c`'s `busy()` gives per mille of `FRAME_CYCLES`, 72,520 (4,532 cycles a sample, the board's clock, as +`CYCLE_SCAN.md`'s "% of a frame" uses, times 16 samples a frame), from idle passes whose cycles were calibrated on the +unit with `--dsp-burn` (11 October 2026, `idle_cycles` there). A module whose package requires a base DSP feature with a +`hardware` charge in `sdk/machines/octatrack/dsp-sites.json` (the key bus) has it added to the model, since that work runs +outside the effect's proc and so outside the scan. + +**Only like cases are compared.** A reading and a model are paired when they cover the same package of the record's +version, the same setting, the transport playing, the same key-bus input for a module that reads the key bus (the scan's +`dsp_host` feeds it silence; a reading names its own in `inputs.keyBus`, `live` or `silent`), and, where a base charge is added, +a reading taken on a base that charge was timed on (the identities its evidence names). Any other pair prints "not +comparable" with the reason and no ratio: re-measure on that case rather than read the gap as a model error. The readings, 18 November 2026, on development twins of base 0.7.8 (Sidechain Compressor's on another twin, `8850f539`), one 8-second reading each; modules with no DSP code moved the same meters by -0.6 to +0.6 points (±27 cycles) in the same runs, once 2.9. Records scanned 23 November 2026: -| Module | Unit, in use (points = cycles a sample) | Defaults run | Model at defaults (+ base features) | Model, dearest | Unit ÷ model | Verdict | -|---|---|---|---|---|---|---| -| airwindows-chorus 0.1.3 | – | defaults/def | 602 | 649 | – | no in-use reading on the unit | -| bbd 0.1.2 | 10.8 = 489 (T1 FX2) | STGS=1024/def | 469 | 528 | 1.04 | within 10 % | -| euclid 0.1.5 | 5.5 = 249 (T1 FX2) | RATE=1/16/def | 232 | 232 | 1.07 | within 10 % | -| everb 0.1.2 | 13.3 = 603 (T1 FX2) | REV=OFF/def | 603 | 665 | 1.00 | within 10 % | -| lofi2 0.1.1 | 10.3 = 467 (T1 FX2) | RING/def | 425 | 654 | 1.10 | within 10 % | -| miniverb 0.2.3 | 14.1 = 639 (T1 FX2) | RATE=1.01/def | 641 | 699 | 1.00 | within 10 % | -| ring-sc 0.2.1 | 7.5 = 340 (T1 FX2) | DUCK/def | 5 + 51 keybus | 122 | 6.04 | **outlier** | -| sidechain-compressor 0.2.2 | 5.5 = 249 (T5 FX1) | MON=OFF/def | 107 | 107 | 2.34 | **outlier** | -| tapehead 0.1.2 | 9.3 = 421 (T1 FX2) | COLOR=NORM/def | 425 | 426 | 0.99 | within 10 % | -| vibrato 0.1.0 | – | SHP=SINE/def | 204 | 207 | – | no in-use reading on the unit | + +| Module | Unit, in use (points = cycles a sample) | Unit, peak | Defaults run | Model at defaults (+ base features) | Model, dearest (+ base features) | Unit ÷ model | Peak ÷ dearest | Verdict | +|---|---|---|---|---|---|---|---|---| +| airwindows-chorus 0.1.3 | – | – | defaults/def | 602 | 649 | – | – | no in-use reading on the unit | +| bbd 0.1.2 | 10.8 = 489 (T1 FX2) | – | STGS=1024/def | 469 | 528 | 1.04 | – | within 10 % | +| euclid 0.1.5 | 5.5 = 249 (T1 FX2) | – | RATE=1/16/def | 232 | 232 | 1.07 | – | within 10 % | +| everb 0.1.2 | 13.3 = 603 (T1 FX2) | – | REV=OFF/def | 603 | 665 | 1.00 | – | within 10 % | +| lofi2 0.1.1 | 10.3 = 467 (T1 FX2) | – | RING/def | 425 | 654 | 1.10 | – | within 10 % | +| miniverb 0.2.3 | 14.1 = 639 (T1 FX2) | – | RATE=1.01/def | 641 | 699 | 1.00 | – | within 10 % | +| ring-sc 0.2.1 | 7.5 = 340 (T1 FX2) | – | DUCK/def | 5 + 43 keybus | 122 + 43 keybus | – | – | not comparable: the reading does not say what its key bus carried, the scan's was silent; the unit read on d3d71297, the keybus charge (43) was timed on 856cbbcf | +| sidechain-compressor 0.2.2 | 5.5 = 249 (T5 FX1) | – | MON=OFF/def | 107 | 107 | – | – | not comparable: the unit measured package 9f22861f, not the published 0.2.2-experimental (cbd0fa73); the reading does not say what its key bus carried, the scan's was silent | +| tapehead 0.1.2 | 9.3 = 421 (T1 FX2) | – | COLOR=NORM/def | 425 | 426 | 0.99 | – | within 10 % | +| vibrato 0.1.0 | – | – | SHP=SINE/def | 204 | 207 | – | – | no in-use reading on the unit | + - **Effects whose work is all in their proc:** the model at the defaults is 1 % above to 10 % below the unit (mean 3 % below), for six modules. LOFI2 (9.95 %) is the widest, and EUCLID's 7 % is within the meter's noise at its size. Upstream found its model 3.0 % *above* its own meter (`CYCLE_SCAN.md` section 1): the two meters differ, and Modwerk's - reads 7 to 19 % above octabam's slot costs for the same DSP code (LOFI2, BBD, EUCLID). -- **Key-bus effects cost far more on the unit than the scan sees.** RINGMOD SC at its defaults runs 2.5 instructions a - sample in the scan (`dsp_host` feeds no key bus, so its key path may stay idle), yet the unit read 340 cycles on core 1, - where its key-bus tap is charged 51; core 0 read +0.9 points (41). Even its dearest run plus the tap (173) leaves half - of it unexplained. Sidechain Compressor read 249 on its own core against 107 modelled, and +6.3 points (285) on the - other core, where it has no instance: its detector and the key-bus tap are base-resident code on both cores - (`dsp-sites.json`'s `sidechain` and `keybus`), outside the proc. Whether the key path, the tap (timed on 23 October on - the older 41-instruction tap) or something else costs the rest needs a unit run. + reads 7 to 19 % above octabam's slot costs for the same DSP code (LOFI2, BBD, EUCLID). None of these readings kept a + peak, so nothing is compared with the dearest run yet. +- **The key-bus effects are not comparable yet.** RINGMOD SC at its defaults runs 2.5 instructions a sample in the scan, + whose key bus is silent, while the unit's kick on T1 fed it: the unit read 340 cycles on core 1 and +0.9 points (41) on + core 0. Its reading was also taken on 0.7.8's 41-instruction tap, before the one-pass tap the charge (43) was timed on. + Sidechain Compressor read 249 on its own core and +6.3 points (285) on the other, where it has no instance: its detector + and the key-bus tap are base-resident code on both cores (`dsp-sites.json`'s `sidechain` and `keybus`), outside the + proc, and the build it was read on is not the published package. To compare them: read both on the current base with + what the key bus carried recorded, and scan their key path with the key bus fed. - **No reading to compare:** VIBRATO and Air Chorus (`airwindows-chorus`) have no `cpu-price.json` in-use reading yet; Output Matrix has no scan record (its mix is base-resident code too). diff --git a/sdk/digitakt-ii/modules/euclidean-scale/README.md b/sdk/digitakt-ii/modules/euclidean-scale/README.md index 59cdaef17b..876eba52a9 100644 --- a/sdk/digitakt-ii/modules/euclidean-scale/README.md +++ b/sdk/digitakt-ii/modules/euclidean-scale/README.md @@ -27,7 +27,7 @@ The stock indicator at the right edge marks the selected page. **FUNC + AMP** or The module targets Digitakt II OS 1.17 and the Modwerk 1.1 base with the shared audio sequencer pitch hook and active-project kit-data reset. The stock sequencer owns transport, tempo, track speed, swing and note releases. Regular trigs, MIDI tracks and explicit stock trig overrides pass through. -Saving a project saves SCF, the last reroll and both octave bounds per pattern and track. Reloading with the same kit-data layout restores all four. New projects start with SCF off and both bounds on AUTO. Projects saved with the K117 trial use its previous layout and open with default Euclidean Scale settings on this version. The Digitakt II browser builder is still in research and selects core 1.0. +Saving a project saves SCF, the last reroll and both octave bounds per pattern and track. Reloading with the same kit-data layout restores all four. New projects start with SCF off and both bounds on AUTO. Projects saved with the K117 trial use its previous layout and open with default Euclidean Scale settings on this version. ## Tests and measurements diff --git a/sdk/imports/mackity-e718c9b.json b/sdk/imports/mackity-e718c9b.json new file mode 100644 index 0000000000..b0f29690d0 --- /dev/null +++ b/sdk/imports/mackity-e718c9b.json @@ -0,0 +1,44 @@ +{ + "schemaVersion": 1, + "repository": "https://github.com/airwindows/airwindows", + "revision": "e718c9bcfcdd736deeddb08bffe6bce2aa8e0eea", + "moduleVersion": "0.1.0-experimental", + "root": "sdk/octabam/modules/mackity", + "modules": [ + "mackity" + ], + "files": [ + { + "path": "upstream/MackityProc.cpp", + "sourcePath": "plugins/LinuxVST/src/Mackity/MackityProc.cpp", + "sourceBytes": 8595, + "sourceGitBlob": "1d148b30af43e2d564c71fc27fe0a418c8efd676", + "sourceSha256": "cd87114e2a4cc878ef4a8c95125a0a440c11c67f7aafafb134fa753863ac804c", + "vendoredSha256": "cd87114e2a4cc878ef4a8c95125a0a440c11c67f7aafafb134fa753863ac804c" + }, + { + "path": "upstream/Mackity.cpp", + "sourcePath": "plugins/LinuxVST/src/Mackity/Mackity.cpp", + "sourceBytes": 4882, + "sourceGitBlob": "1354eafe5dd4e4678f3206e8f7e88f3d1d43d88e", + "sourceSha256": "ba1c6cf347a9bc53d557af760658d7d2b353d6ce0e10af46ba96d677f177af3a", + "vendoredSha256": "ba1c6cf347a9bc53d557af760658d7d2b353d6ce0e10af46ba96d677f177af3a" + }, + { + "path": "upstream/Mackity.h", + "sourcePath": "plugins/LinuxVST/src/Mackity/Mackity.h", + "sourceBytes": 2618, + "sourceGitBlob": "856be80c4737b7dd8e702a7f89c8b9289a92d7de", + "sourceSha256": "9f762af4975556fbb64744ede2da6c8d8407e9e43e90b9bd1c46c3dd58b0c0e6", + "vendoredSha256": "9f762af4975556fbb64744ede2da6c8d8407e9e43e90b9bd1c46c3dd58b0c0e6" + }, + { + "path": "upstream/LICENSE", + "sourcePath": "LICENSE", + "sourceBytes": 1070, + "sourceGitBlob": "e8feef9bdb417d8662f50cc43e6329c0bd071460", + "sourceSha256": "b4f5719b00ba3fecf8c0ce651e843651bd80f08a10cf4cf1f00e673a5bcaf23b", + "vendoredSha256": "b4f5719b00ba3fecf8c0ce651e843651bd80f08a10cf4cf1f00e673a5bcaf23b" + } + ] +} diff --git a/sdk/machines/digitakt-ii/GOAL.md b/sdk/machines/digitakt-ii/GOAL.md index 0ca0e1289b..ee16c0dec0 100644 --- a/sdk/machines/digitakt-ii/GOAL.md +++ b/sdk/machines/digitakt-ii/GOAL.md @@ -19,7 +19,7 @@ This is the Octatrack's stack on the Digitakt II ([machine recipe](../../../docs | Base updates over USB | Not started | [two-slot base](../../../docs/OCTATRACK_TWO_SLOT_BASE.md) | | MCP device tools | Not started | [device tools](../../../docs/FRONTEND_MCP.md#then-test-the-connected-device) | | Machine page | Status only. The Octatrack's unit pages (status, module sets, guided sync) are not built yet | [`OctatrackHub.tsx`](../../../src/components/OctatrackHub.tsx) is the model | -| Modules | Track Names is in the library. Downloads stay off until the owner turns them on | [modules](../../digitakt-ii/modules/), open pull requests, the board | +| Modules | Track Names, Mute Latch, Chord Arp and Euclidean Scale are in the library. Downloads stay off until the owner turns them on | [modules](../../digitakt-ii/modules/), open pull requests, the board | When a piece moves, update this table, the [recipe's table](../../../docs/MACHINE_RECIPE.md#where-each-machine-stands) and `machine.json`'s `stack` in the same pull request. @@ -57,7 +57,6 @@ OS 1.17 offers USB MIDI in all three USB modes (MIDI, Audio/MIDI and Overbridge) ## Open questions -- **Kit data that changes alone.** Does OS 1.17 save a kit when only a module's block changed? The test steps are in the [machine guide](README.md#core-hooks), and any unit owner can run them. - **More units.** The pinned base has run on one unit so far. - **A SHARC assembler.** No Modwerk build writes SHARC code yet. The first one to do so brings its toolchain, pinned through `npm run upstream:tools`, and a build check for the rules above. diff --git a/sdk/machines/digitakt-ii/README.md b/sdk/machines/digitakt-ii/README.md index bd7e450b91..cc6704aeb9 100644 --- a/sdk/machines/digitakt-ii/README.md +++ b/sdk/machines/digitakt-ii/README.md @@ -37,7 +37,7 @@ These are in [core-profile/interface.json](../../digitakt-ii/core-profile/interf One of those routines is not available to a module: `fw_card_write`, the raw block write to the +Drive, writes under the mounted file system, where one wrong block costs a musician projects and samples, so the [preflight](#build-and-recovery) refuses a build whose mod file refers to it by name or names its address, and a module keeps its data in the project and its kits (`core_projdata`, `core_kitdata`). -By the core's documentation (emulator-tested, not hardware-tested), both data areas hold bytes the stock OS writes as zeros and never reads, so a project saved with mods loads on the stock OS, which keeps them when it saves a project it loaded. Core writes them only over zeros or its own data and counts anything else in `core_store_conflicts`. **Open: kit data that changes alone.** Core writes a kit's mod data when the OS writes that kit's record. If OS 1.17 writes only the kits the musician changed, a change to a mod's own block alone (a module setting, no stock parameter touched) would not be saved, and an earlier saved value would come back after a reload. No hardware test has isolated this yet. To check on a unit: change only a kit-data module's setting on A01, SAVE PROJECT, load another project and this one again; then repeat with a stock parameter on A01 nudged and set back, and once more with only the module setting changed after a saved value. Record the image's SHA-256 and each result. Until then, tell musicians to save after any stock change, and do not rely on kit data that changes on its own. **A kit record has room for 143 bytes of kit data in all** (`core_kitdata_room()`), shared by every mod's block. Core 1.1 gives it 191, but the Modwerk base keeps the record's last 48 bytes for its project archive, so its copy of core's recipe ends the kit data there (`npm run check` refuses an overlap). One mod with a 143-byte block takes all of it and leaves any other kit-data mod out, so per-kit state that several modules will want belongs to the base, as one record per module in a table the base owns ([recipe](../../../docs/MACHINE_RECIPE.md#rules)), not to the first module that asks for the room. +By the core's documentation (emulator-tested, not hardware-tested), both data areas hold bytes the stock OS writes as zeros and never reads, so a project saved with mods loads on the stock OS, which keeps them when it saves a project it loaded. Core writes them only over zeros or its own data and counts anything else in `core_store_conflicts`. **Kit data that changes alone is saved.** Core writes a kit's mod data when the OS writes that kit's record, so a change to a mod's own block alone (a module setting, no stock parameter touched) would be lost if OS 1.17 wrote only the kits the musician changed. On 25 November 2026, Claptom-music ran the check on a Digitakt II with image `8472296a8686e5484c1ba8ba1b54e6e6119776f2adfe5a6bdedba7ccfdd08dd3` (base `8650bb8a` and Euclidean Scale 0.2.0-experimental). They changed only Euclidean Scale's HI on A01 from +1 to +2, did SAVE PROJECT, loaded another project and this one again: HI read +2. With a stock filter cutoff on A01 nudged and set back and HI at +3, it read +3. With only HI changed again, to +1, it read +1. SAVE PROJECT writes a module-only change to the kit, so a musician needs no stock change before saving. **A kit record has room for 143 bytes of kit data in all** (`core_kitdata_room()`), shared by every mod's block. Core 1.1 gives it 191, but the Modwerk base keeps the record's last 48 bytes for its project archive, so its copy of core's recipe ends the kit data there (`npm run check` refuses an overlap). One mod with a 143-byte block takes all of it and leaves any other kit-data mod out, so per-kit state that several modules will want belongs to the base, as one record per module in a table the base owns ([recipe](../../../docs/MACHINE_RECIPE.md#rules)), not to the first module that asks for the room. The Digitakt II core does not start DTIM0 and exposes no audio-render hook yet ([proposal and emulator measurements](../../../docs/verification/2026-11-10-digitakt-ii-pre-send-render.md)). Audio is rendered by the separate SHARC DSP; these hooks are not sample-accurate. diff --git a/sdk/machines/octatrack/base-binding.json b/sdk/machines/octatrack/base-binding.json index 73539f5a62..145cf9e670 100644 --- a/sdk/machines/octatrack/base-binding.json +++ b/sdk/machines/octatrack/base-binding.json @@ -1,6 +1,6 @@ { "schema": 1, - "identity": "fad2c7297a6ca7f1c51dbe4f08b0af85c4350b9c6cba865adc0ab5894e84897c", + "identity": "880c0a34538757dd5c4ba4348b0abfd74c50173788d99e4a994a45815910b498", "arena": 1089791456, "pool": 1087905840, "symbols": { @@ -15,6 +15,6 @@ "analog-bassdrum": "e77e36cf6885e7669d3935ac9ef82626a6aa9d7e015ef1a42cef3202691c83ab" }, "variants": { - "off": "fad2c7297a6ca7f1c51dbe4f08b0af85c4350b9c6cba865adc0ab5894e84897c" + "off": "880c0a34538757dd5c4ba4348b0abfd74c50173788d99e4a994a45815910b498" } } diff --git a/sdk/machines/octatrack/base-sizes.json b/sdk/machines/octatrack/base-sizes.json index 6e9978451f..613064ffe2 100644 --- a/sdk/machines/octatrack/base-sizes.json +++ b/sdk/machines/octatrack/base-sizes.json @@ -451,11 +451,11 @@ }, { "base": "0.8.2", - "identity": "8f179f5eb41220d90dc685a5537273cc8a2ff8390898549f196290b33c062046", + "identity": "880c0a34538757dd5c4ba4348b0abfd74c50173788d99e4a994a45815910b498", "layouts": { "off": { - "main": 1348186, - "container": 831600 + "main": 1349063, + "container": 832612 } } } diff --git a/sdk/machines/octatrack/base-versions.json b/sdk/machines/octatrack/base-versions.json index dbaa994788..e47ad83525 100644 --- a/sdk/machines/octatrack/base-versions.json +++ b/sdk/machines/octatrack/base-versions.json @@ -160,7 +160,7 @@ { "version": "0.8.2", "identities": [ - "fad2c7297a6ca7f1c51dbe4f08b0af85c4350b9c6cba865adc0ab5894e84897c" + "880c0a34538757dd5c4ba4348b0abfd74c50173788d99e4a994a45815910b498" ] } ] diff --git a/sdk/machines/octatrack/elekloader/build_core.py b/sdk/machines/octatrack/elekloader/build_core.py index c0c1fe9e89..775b9b08a4 100644 --- a/sdk/machines/octatrack/elekloader/build_core.py +++ b/sdk/machines/octatrack/elekloader/build_core.py @@ -242,6 +242,13 @@ def check_zero_state(elf, moved, layout, mapping, bootstrap): 'midi-scenes': 'its writes meet Elekloader\'s own sites; it needs a port', 'output-matrix': 'resident bases own its CUE CFG project-load clamp and CS1 power-up widening (cue_cfg.s); ' 'its controller package leaves those sites out'} +# Modwerk's: the frame interrupt's per-track call 0x400068e4 (twice a track, 16 times a frame, from 0x4000d340 and +# 0x4000d36c) reads the current Part from CS1 (0x100b14cf) on entry. Stock keeps the same byte in on-chip SRAM at +# 0x80000003 and writes the two together everywhere it writes either (0x40062142/8, 0x400621e2/8, 0x40087ea6/ac: SRAM +# first, the next instruction CS1; the boot's 0x4001fa76 and the reset's 0x40025aaa set CS1 and copy it to SRAM). So the +# base reads SRAM there: the same `mvzb`, the same flags, one CS1 read fewer per call. (Address, length, the stock +# instruction's SHA-256, its replacement.) The ISR's other read of the byte (0x4000d212) is a rare branch and stays. +PART_READ = (0x400068f0, 6, 'd0ec7e0980705bdda9e9859f3b6caa119d97dab71385585f3a78e9e893f81d5d', '71b980000003') # resident-runtime/cue_cfg.s: (address, guard bytes, guard SHA-256 = Output Matrix's manifest guard, the base's site). CUE_CFG_WIDENING = ((0x4008732a, 14, '968adf63466a054aefd6609f18536e3719bbcc144b6dc0a43de49794c3bb3718', dict(op='jmp', target='modwerk_cue_cfg_clamp', length=6)), @@ -2256,6 +2263,11 @@ def place(end): raise ValueError('Stock bytes at %#x are not the CUE CFG clamp/check cue_cfg.s widens.' % addr) recipe['sites'].append(dict({k: v for k, v in site.items() if k != 'length'}, addr=hex(addr), stock=stock_at(addr, site['length']).hex())) + # The frame interrupt reads the current Part from SRAM, not CS1 (PART_READ): every base. + addr, n, guard, new = PART_READ + if sha(stock_at(addr, n)) != guard: + raise ValueError('Stock bytes at %#x are not the current-Part read PART_READ names.' % addr) + recipe['sites'].append(dict(addr=hex(addr), stock=stock_at(addr, n).hex(), op='bytes', new=new)) # Stock OS fixes (stock-fixes/): every base, whatever its flags, so every layout and twin patches the same sites. for name in STOCK_FIXES.SOURCES: shutil.copyfile(HERE / 'stock-fixes' / name, source / name) diff --git a/sdk/machines/octatrack/frame-costs.json b/sdk/machines/octatrack/frame-costs.json index 8668f552bd..79f18c39f1 100644 --- a/sdk/machines/octatrack/frame-costs.json +++ b/sdk/machines/octatrack/frame-costs.json @@ -10,6 +10,7 @@ "everb": {"first":0.7,"each":0.2,"rest":0,"points":[0.7,0.8,1,-0.6],"measured":"everb 0.1.2-experimental on T1 T3 T6 T7: Dev17 C04 at 126 BPM, trigs on steps 1/5/9/13 of T1-T4, T6, T7 (T2 and T4 play samples; stock alone 79.4 %), picks on empty C02; base dce1d30e (0.8 twin); 8 s a reading; 2026-11-22 (npm run device:price -- --curve)"}, "grain": {"first":33.3,"each":33.3,"rest":0,"points":[33.3],"measured":"grain 0.1.3-experimental on T1: C04 at 126 BPM, trigs on steps 1/5/9/13 of T1-T4, T6, T7 (the scene FM Synth 0.1.5's curve used); picks on empty C02; Grain on T1, whose Flex slot holds a loaded 16-bit stereo sample. One instance: a second (T3, the other track with a loaded sample) was refused on 23 November and on T6/T7 Grain would render silence; owner's MKII; base 95adb64b (0.8 development twin, built from main 4035fdfa8); 8 s a reading; 2026-11-23 (evidence/frame-cost.json)"}, "lofi2": {"first":1,"each":0,"rest":0,"points":[1,-1.5,-0.3,-1.3],"measured":"lofi2 0.1.1-experimental on T1 T3 T6 T7: Dev17 C04 at 126 BPM, trigs on steps 1/5/9/13 of T1-T4, T6, T7 (T2 and T4 play samples), picks on empty C02; owner's MKII; base 0.8 twin 28 053fd054; 8 s a reading; 2026-11-22"}, + "mackity": {"first":0.9,"each":0.9,"rest":0,"points":[-1.8,-2.2,0.9,-2.9],"measured":"mackity 0.1.0-experimental on T1 T3 T6 T7: Project on the owner's development unit, bank C, Part 1 reloaded in RAM to its saved copy; picks on the empty C02, readings on C04 (trigs on steps 1/5/9/13 of T1-T4, T6, T7) at the project tempo; transport played by the tool; base development twin 8fd6d456 of base 0.8.1 (eb6679620d0c9ed7), the owner's MKII, OS 1.40C; 8 s a reading; 2026-11-25 (evidence/frame-cost.json)"}, "miniverb": {"first":1.5,"each":0,"rest":0,"points":[1.5,1.4,1.2,1.2],"measured":"miniverb 0.2.3-experimental on T1 T3 T6 T7: Dev17 C04 at 126 BPM, trigs on steps 1/5/9/13 of T1-T4, T6, T7 (T2 and T4 play samples; stock alone 79.4 %), picks on empty C02; base dce1d30e (0.8 twin); 8 s a reading; 2026-11-22 (npm run device:price -- --curve)"}, "poly8": {"first":51,"each":51,"measured":"0.3.4 on T1 (empty) from rest, owner's MKII, base 0.8, 22 Nov 2026, Dev17 C01 (trigs on steps 1/5/9/13 of all eight tracks), longest frame over 8 s: 88-90 -> 140.8 %, mean 39.0 -> 77.1 %, 5,260 renders dropped in 8 s, twin 64b66394; T1/T5 retrigger auditions +30.3 on base 0.7.11 (#1863)"}, "resonator": {"first":0.8,"each":0.8,"rest":0,"points":[0.1,0.7,-0.3,0.8],"measured":"resonator 0.1.0-experimental on T1 T3 T6 T7: Dev17 C04 at 126 BPM, trigs on steps 1/5/9/13 of T1-T4, T6, T7 (T2 and T4 play samples), picks on empty C02, Part 1; the effect measured on T1 FX2 in place of DELAY; owner's MKII, OS 1.40C; base development twin 8fd6d456 of base 0.8.1 (built from 9d5aec73a); 16 s a reading; 2026-11-24 (evidence/frame-cost.json)"}, diff --git a/sdk/machines/octatrack/module-adapters/standalone-recipes.json b/sdk/machines/octatrack/module-adapters/standalone-recipes.json index 46dcea6ad4..040bb522bb 100644 --- a/sdk/machines/octatrack/module-adapters/standalone-recipes.json +++ b/sdk/machines/octatrack/module-adapters/standalone-recipes.json @@ -205,8 +205,8 @@ "src/engine/coldfire-elf.ts": "319ca0d835d1b0c602c8f4b06990016d0ebfe246cedbfc596cea3cc7adfe3cd2", "src/engine/module-build.ts": "dcd8397b8cecf6fab61debd9aa2f86f612da0ca6ccf363c79d56033bc170b993", "src/catalog/modules.ts": "14304ea8450f8ec7ecaaf3ccf9e764929161288babe7b34cb37ff41e44fe1b43", - "src/engine/assets/dsp-packages.json": "111b8dad5bc68547bf938ac59316a4b889906d656b91e038941a43da7b7c468b", - "src/engine/assets/descriptor-recipes.json": "07342b7a6793e0526b0fca8776f49e750d9793461333fb53536d5414622aef4b", + "src/engine/assets/dsp-packages.json": "65cd6f2c41b67e718ea9fbb2faea3114e9fb989b9acc8070ef4e8b69544f244b", + "src/engine/assets/descriptor-recipes.json": "ff892f69baae7c18bb2b15e94a31d2dfa489fd766cffb5de18722591d2eede08", "src/engine/assets/menu-recipes.json": "427972231beb55518aee663db1df9f4cf4d8debf1d7aa6b574f97d499f6a0842", "src/engine/assets/rom-packages.json": "68d9f0e5f388910e20cd00f5b00cbc1eb606258921d90d4a0d87dab934f835cb", "upstream/elekloader/link.py": "5d31157ccbe62807ff9f05fd47e1e55b54be0475ab53565e6607a56566603ba8", @@ -440,8 +440,8 @@ "src/engine/coldfire-elf.ts": "319ca0d835d1b0c602c8f4b06990016d0ebfe246cedbfc596cea3cc7adfe3cd2", "src/engine/module-build.ts": "dcd8397b8cecf6fab61debd9aa2f86f612da0ca6ccf363c79d56033bc170b993", "src/catalog/modules.ts": "14304ea8450f8ec7ecaaf3ccf9e764929161288babe7b34cb37ff41e44fe1b43", - "src/engine/assets/dsp-packages.json": "111b8dad5bc68547bf938ac59316a4b889906d656b91e038941a43da7b7c468b", - "src/engine/assets/descriptor-recipes.json": "07342b7a6793e0526b0fca8776f49e750d9793461333fb53536d5414622aef4b", + "src/engine/assets/dsp-packages.json": "65cd6f2c41b67e718ea9fbb2faea3114e9fb989b9acc8070ef4e8b69544f244b", + "src/engine/assets/descriptor-recipes.json": "ff892f69baae7c18bb2b15e94a31d2dfa489fd766cffb5de18722591d2eede08", "src/engine/assets/menu-recipes.json": "427972231beb55518aee663db1df9f4cf4d8debf1d7aa6b574f97d499f6a0842", "src/engine/assets/rom-packages.json": "68d9f0e5f388910e20cd00f5b00cbc1eb606258921d90d4a0d87dab934f835cb", "upstream/elekloader/link.py": "5d31157ccbe62807ff9f05fd47e1e55b54be0475ab53565e6607a56566603ba8", diff --git a/sdk/octabam/licenses/THIRD_PARTY_NOTICES.txt b/sdk/octabam/licenses/THIRD_PARTY_NOTICES.txt index 15d4c95908..338dcd6930 100644 --- a/sdk/octabam/licenses/THIRD_PARTY_NOTICES.txt +++ b/sdk/octabam/licenses/THIRD_PARTY_NOTICES.txt @@ -36,9 +36,9 @@ SOFTWARE. ======================================================================== -Airwindows Chorus +Airwindows Chorus and Mackity SPDX: MIT -Used in: modules/airwindows-chorus: Chorus +Used in: modules/airwindows-chorus: Chorus; modules/mackity: Mackity Notice source: https://raw.githubusercontent.com/airwindows/airwindows/e718c9bcfcdd736deeddb08bffe6bce2aa8e0eea/LICENSE MIT License diff --git a/sdk/octabam/licenses/manifest.json b/sdk/octabam/licenses/manifest.json index 9ce45c71ec..b784be6f91 100644 --- a/sdk/octabam/licenses/manifest.json +++ b/sdk/octabam/licenses/manifest.json @@ -20,7 +20,7 @@ }, { "id": "airwindows", - "name": "Airwindows Chorus", + "name": "Airwindows Chorus and Mackity", "spdx": "MIT", "noticeFile": "airwindows.txt", "sources": [ @@ -31,7 +31,8 @@ } ], "usedIn": [ - "modules/airwindows-chorus: Chorus" + "modules/airwindows-chorus: Chorus", + "modules/mackity: Mackity" ] }, { @@ -328,6 +329,9 @@ "airwindows-chorus": [ "airwindows" ], + "mackity": [ + "airwindows" + ], "lofi2": [ "lofi2" ], diff --git a/sdk/octatrack/modules/mackity/LICENSE b/sdk/octatrack/modules/mackity/LICENSE new file mode 100644 index 0000000000..1d3a9abb89 --- /dev/null +++ b/sdk/octatrack/modules/mackity/LICENSE @@ -0,0 +1,30 @@ +MIT License + +Copyright (c) 2018 Chris Johnson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +This licence covers this module's own source code and documentation only. It +does not extend to any Elektron Music Machines firmware, which is not +distributed here and remains the property of its copyright holder. Nothing in +this module is endorsed by, supported by, or affiliated with Elektron. +Octatrack and Elektron are trademarks of Elektron Music Machines MAV AB, used +only to identify the hardware this module targets. diff --git a/sdk/octatrack/modules/mackity/README.md b/sdk/octatrack/modules/mackity/README.md new file mode 100644 index 0000000000..35064b79a4 --- /dev/null +++ b/sdk/octatrack/modules/mackity/README.md @@ -0,0 +1,91 @@ +# Mackity + +Version 0.1.0-experimental · Chris Johnson's Airwindows Mackity. + +## Overview + +Mackity is Airwindows' model of the input stage of a Mackie-style mixing desk. +The track's audio passes a gentle low cut (13 Hz), the desk's high-frequency +rolloff (19.16 kHz), the IN TRIM gain and the console's clip, rounded by its +curve (v − 0.1768 v⁵), then a second rolloff and a DC blocker (2 Hz). At TRIM 13 +it adds only the desk's colour. Turning TRIM up drives the channel into the +clip, from warm thickening to hard, square distortion. PAD sets the output level. + +This is upstream's whole algorithm, unchanged, in the Octatrack DSP's 24-bit +fixed point at its 44.1 kHz. It is a stereo insert with no buffer, so it runs +on FX1 or FX2 of any track. + +## Controls + +| Knob | Name | Range | Default | What it does | +|---|---|---|---|---| +| A | TRIM | 0–127 | 13 | In Trim: gain (TRIM/13)², the original's (10·A)² with A = TRIM/130. 13 is 0 dB, 26 is +12 dB, 52 is +24 dB, 127 is +39.6 dB, 0 is silence. | +| B | PAD | 0–127 | 127 | Out Pad: output level PAD/128. 127 is exactly 0 dB, 64 is −6 dB. | + +Both knobs glide over about 1.5 ms, so turning them does not click. The +original's TRIM reaches +40 dB at its top; here it stops 0.4 dB short, so that +13 is exactly 0 dB. + +## Usage + +1. Select an audio track that plays something. +2. Hold FUNC and press FX1 (or FX2), highlight MACKITY with UP/DOWN and press YES. +3. Press FX1 (or FX2): knob A is TRIM, knob B is PAD. + +## Quick tutorial + +1. Put MACKITY on FX1 of a drum loop's track: hold FUNC, press FX1, turn LEVEL to Mackity and press YES. At TRIM 13 and PAD 127 the loop keeps its level and gains the desk's colour. +2. Turn TRIM to 40 on the FX1 page. The loop thickens and its peaks flatten into the clip; turn PAD to about 90 to bring the level back down. +3. Set TRIM 13 and PAD 127 to return to the clean desk, or select NONE in the FX1 chooser to remove it. + +## Compatibility and limitations + +- Tested on one MKII by the test procedure (TESTING.md); the MKI, a Part or + project reload with it saved and a power cycle were not tested by hand. +- On a pattern that already fills the CPU, a pick can be refused with CPU FULL: + on eight busy tracks it asked for 3 % more than was left. +- At high TRIM the clip makes harmonics above 22 kHz that fold back below it, + as the original does at 44.1 kHz. That is part of its sound; it is not + oversampled. +- With heavy drive the desk's second rolloff peaks up to about 0.6 dB over full + scale. The original's float output keeps those peaks; a 24-bit output limits + them. PAD 120 or lower keeps every peak. +- The value going into the trim is limited at +6 dBFS before the gain. Only + input with a large DC step and a low TRIM can reach that. +- The original's 32-bit float dither and denormal noise are left out: the + Octatrack's path is 24-bit fixed point. +- It shares nothing with other modules: no buffer, no bus, 32 words of the + track's own state block. + +## Tests and measurements + +See [TESTING.md](TESTING.md). In short: `verify.py` matches the bit-exact model +in every case it renders, `test_reference.py` holds that model to the original, +and dsp_host reads 228 instructions a sample at worst (0.79 of stock LO-FI). On +the owner's MKII the test procedure passed, with a 2-minute soak: Mackity adds +0.1 % to the frame interrupt on one slot, nothing installed and unused, and +0.9 points to the longest frame per instance. + +## Authorship and licences + +Original: [Chris Johnson / Airwindows](https://www.airwindows.com/), +[Mackity source](https://github.com/airwindows/airwindows/tree/e718c9bcfcdd736deeddb08bffe6bce2aa8e0eea/plugins/LinuxVST/src/Mackity), +MIT. His source and licence are kept unchanged in [upstream/](upstream/); the +Octatrack adaptation is distributed under the same terms. See [LICENSE](LICENSE). + +## Screens and audio + +Two captures off the unit's LCD (provenance in media/capture.json). No audio preview yet. + +![FX1 SETUP: the effect chooser with the cursor on Mackity](media/mackity-chooser.png) + +![The FX1 page running Mackity: TRIM on knob A, PAD on knob B](media/mackity-main.png) + +## Develop + +- Hear it: `npm run module:dev -- mackity` builds it and tries it on your unit over USB; `--watch` does that again on every save. +- Check it: `npm run module:doctor -- mackity`. +- `python3 -B sdk/octatrack/modules/mackity/test_reference.py` runs without tools; + `verify.py` and `perf.py` beside it need dsp_asm, dsp_host and the + disassembler from an octabam checkout (`npm run upstream:tools`). +- How the port works, in fixed point: the header of `mackity.asm`. diff --git a/sdk/octatrack/modules/mackity/TESTING.md b/sdk/octatrack/modules/mackity/TESTING.md new file mode 100644 index 0000000000..3ed5db43aa --- /dev/null +++ b/sdk/octatrack/modules/mackity/TESTING.md @@ -0,0 +1,194 @@ +# Mackity testing + +Every result below was observed on 25 November 2026, on the files with these +SHA-256 hashes: + +| File | SHA-256 | +|---|---| +| mackity.asm | `34a4bb44e0cbe605c4ded1826fcb14190beef43d58a41875c9b2f4c1ea599614` | +| reference.py | `0b14a758aabd3fdff3b62b52db0918bfae8887c6fa1e31a2a258802357a47b0c` | +| verify.py | `edb488c3c991d47ffeb809d5a3d0c01967fab33def9384d54358ea788937333e` | +| test_reference.py | `5dae0f2d7b1321690957b372a38bebcc86b7123da90c0cfe6bc852786db56722` | + +The DSP tools (dsp_asm, dsp_host, dsp56kDisassemble) were built from octabam +`f7d7290663135ff8bc4ea18aa45d2854a7b332c1`, in WSL2 on Windows 11. Upstream is +Airwindows `e718c9bcfcdd736deeddb08bffe6bce2aa8e0eea`, +`plugins/LinuxVST/src/Mackity`, kept in `upstream/`. + +## On the unit + +25 November 2026, the owner's development unit, on the released base 0.8.1 +(`eb6679620d0c9ed7`), by an agent through the unit queue. Package +`5a58d4cc9ce2e5c2878ddafab9fa4437d4ded051066e1d0788307693330b39ac`, built from this +folder with `npm run module:dev -- mackity --build-only --cycles 226 +--cycles-kind executed --state 32` (208 DSP words, 472 bytes). + +- `npm run device -- try --seconds 30`: the loader accepted it and + ran it as a trial in RAM for 30 seconds. Verdict from the unit's log: no + crash, stall, freeze or skipped track. Rolled back at the end; the unit was + back on `eb6679620d0c9ed7`, generation 2. +- The base's refusal counter rose by about one every 4 seconds during the + trial. It rose the same way with no module installed (9 to 14 in 20 + seconds, serve running): the session's requests to a release base, not the + module. +- `npm run device:test` did not run on that base: the release base answers no + development requests ("build it with --dev"). + +### Agent test on the unit (device:test), 2026-11-25 + +The same package, on the owner's MKII RAM-booted on development twin +`8fd6d456abf3865b` of base 0.8.1, through the unit queue. The project's banks +A-E play only patterns on Part 1, whose working copy differs from its saved +one; so, on the owner's choice, trigs were placed on T1 and T5 (steps 1, 5, 9, +13) of empty bank F pattern 1, whose Part 1 equals its saved copy, in the +twin's RAM only. Afterwards the release image (`eb6679620d0c9ed7`) was booted +back and the inventory read the same nine modules as before. + +Command: `npm run device:test -- --share SOCK --testing-entry run.md mackity.mwrm` + +- Installed as a trial in RAM and rolled back at the end: nothing was kept. +- Self-test with the package installed: passed; modules 1/1 intact, 1 with DSP + effects; together 1/1 ran (last batch `- - - - 0x1a - - -`); peaks CPU 45.5 %, + T1-4 33.8 %, T5-8 49.8 %; longest frame 406 us; card set 4, 0/1. +- MACKITY on FX2 alone: T1 peak 419 per mille of a frame, admitted in 118 ms; + T5 peak 498 per mille, admitted in 117 ms. +- On all eight tracks at once, playing: CPU 458, T1-4 peak 663, T5-8 peak 743 + per mille. +- Part switches: 12 of 12 ran their own effects within 3 s. +- Crash test: not run (device:test has none). +- Inventory at the end: the same as before the run. Result: passed. + +Bank F's Part has no samples on its tracks, so the effect ran on silence there: +this proves install, admission, CPU and stability, not the sound. + +Not tested on the unit by an agent: listening, MIDI, scenes and recording, the +module beside the other installed modules, the Keep, a power cycle and what +survives it. + +### Test procedure on the unit, 2026-11-25 + +`npm run test:procedure -- mackity --package mackity.mwrm --pick-pattern 2 +--measure-pattern 4 --soak-seconds 120` on the owner's MKII, RAM-booted on +development twin `8fd6d456` of base 0.8.1, through the unit queue. Build: +revision `ccbb96b6c06a`, package SHA-256 +`5a58d4cc9ce2e5c2878ddafab9fa4437d4ded051066e1d0788307693330b39ac` (the same +package as above). Scene: the project's bank C, Part 1 reloaded in RAM to its +saved copy (on the owner's OK; the card kept its working copy, which the release +boot afterwards brought back), picks on the empty C02, readings on C04 (trigs on +steps 1/5/9/13 of T1-T4, T6, T7). The release image `eb6679620d0c9ed7` was booted +back afterwards and the inventory read the owner's nine kept modules, as before. + +| # | Step | Result | +|---|---|---| +| 1 | Software checks (`module:doctor`) | passed | +| 2 | Beside every other module | not run by the procedure: the doctor's compatibility line (step 1) | +| 3 | Name the build | passed | +| 4 | DSP cost model (`cycle-scan check`) | passed | +| 5 | Emulator rehearsal | not run: no emulator session | +| 6 | Read the unit | passed | +| 7 | Scripted unit pass (`device:test`) | passed: alone on FX2 of T1 and T5, eight at once while playing, 12 Part switches, self-test passed, inventory unchanged | +| 8 | Soak, 120 s | passed: no crash, stall, freeze or skipped track; rolled back | +| 9 | Cost on the unit (`device:price` with `--curve T1,T3,T6,T7`) | passed: frame interrupt +0.1 points in use on T1 FX2, 0 at rest; CPU meter +0; DSP T1-4 +8.1 points; curve first 0.9, each 0.9; admitted on C02 and C04 with no dropped render and no stall | +| 10 | Put back | passed | +| 11 | Agent by hand | the screens below; the rest not run | +| 12 | Submitter's own stage | not run: the owner asked for it to be released without it ("you can merge and get it live yourself", 25 Nov 2026) | + +Two attempts before it stopped short, and why: on C01 (eight busy tracks) the +pick was refused with CPU FULL ("MACKITY NEEDS +3 %", ColdFire CPU at 99 %), so +the picks moved to the empty C02; and the soak's first MIDI message was refused +until the Windows MIDI bridge was reopened after the RAM boot. Neither touched +the module. + +The readings are in `evidence/cpu-price.json` and `evidence/frame-cost.json`. + +#### Edge cases + +| Case | Why this change makes it a risk | How run | Result | +|---|---|---|---| +| Eight instances at once | per-instance state in r7, DSP load | device:test, all eight tracks playing | pass: CPU 458, DSP peaks 663/743 per mille | +| A trig split | glide and snap per call | verify.py `-split 5`; perf.py splits 1-15 | pass (bit-exact; worst 228.2) | +| A full pattern (CPU FULL) | admission | the pick on C01 | refused cleanly with CPU FULL; no crash | +| Part switches | knob words change with the Part | device:test, 12 switches | pass: 12 of 12 within 3 s | +| Silence after audio | a 24-bit limit cycle | verify.py, host test | pass: exact silence | +| Part/project reload, power cycle | stored knob bytes | not run: no Keep | not run | + +### Screens + +Read off the unit's LCD with the development session's `png:` step during a RAM +trial of the same package, on the twin, bank F, T2: `media/mackity-chooser.png` +(FX1 SETUP, Mackity selected) and `media/mackity-main.png` (its FX1 page). Their +provenance and hashes are in `media/capture.json`. + +## Stock flows + +Not tested. As a buffer-free insert with all its state in the track's own +block, it touches no stock flow; that is a reading of the code, not a test. + +## Host test: the model against the original + +`python3 -B test_reference.py` (no tools): 5 tests, OK. + +- The coefficient words in mackity.asm are upstream's, derived again from + MackityProc.cpp's formulas at 44.1 kHz. +- Against upstream's algorithm in double precision, with its output limited at + full scale where it goes over: the level within 0.001 dB and everything else + under −100 dB for nine cases. They cover TRIM 0, 5, 13, 40, 64 and 127, PAD 0, 100 + and 127, and tones from 100 Hz to 9.1 kHz at up to −1 dBFS. +- TRIM 13 and PAD 127 give exactly unity gain words. +- A noise burst's tail ends in exact silence at TRIM 13 and 127. +- After knob moves the glides settle exactly on their targets. + +## Render gate: the assembly against the model + +`python3 -B verify.py` (dsp_asm, dsp_host, disassembler): every gate PASS. + +- All 20 products disassemble as the signed `mpy`/`mac x0,y1` form. There is no + `rep`, `mpysu` or `macsu`. The state stays within X:(r7+$00..$1e). +- Bit for bit the model: stereo noise at the defaults; a −1 dBFS tone at + TRIM 127; knob automation over both ranges (TRIM 0–127, PAD 0–127, a + one-block step at block 60); a 5-frame trig split every block; a TRIM word + carrying an LFO's fraction bits (`-pword 0:0=1eb700`); garbage in the state + block before init (`-dirty 0x5a5a5a`); and two instances with their own knobs. +- Silence in gives exact silence out at TRIM/PAD 13/127, 127/127, 0/0 and + 64/64. A burst's tail at TRIM 127 ends in exact silence. + +## Sound quality + +`npm run fx:audit -- plan`, then each signal rendered through the assembled +module in dsp_host (mono in, both channels, 16-frame blocks), then +`fx:audit -- check`. The same signals went through upstream's algorithm in +double precision (reference.float_mackity, output limited at full scale) for +comparison. + +| Setting | Aliasing, worst tone | Rails | DC | Idle | The original | +|---|---|---|---|---|---| +| TRIM 13, PAD 127 | −28.7 dBc (9.1 kHz, −1 dBFS); −73.2 at −12 dBFS | 0 | < −140 dBFS | digital silence | identical aliasing and harmonics; residual −132 dBc against the port's −110 | +| TRIM 40, PAD 100 | −6.7 dBc (9.1 kHz, −1 dBFS); −52.9 at 1.1 kHz, −12 dBFS | 0 | ≤ −121 dBFS | digital silence | identical in every column | +| TRIM 127, PAD 127 | −6.2 dBc (9.1 kHz, −1 dBFS) | up to 11,486 | ≤ −117 dBFS | digital silence | identical, rail counts included | + +The audit's −60 dBc aliasing limit is not met above moderate levels, and it +is left that way on purpose. The original has exactly the same aliasing at +44.1 kHz: the clip and the v⁵ curve make harmonics that fold back, which is +part of Mackity's sound. Oversampling would change the algorithm being ported. +The samples on the rails at TRIM 127 are the original's own peaks over full +scale (+0.4 dB on these tones), limited by the 24-bit store. They are +deliberate and not a wrap: the original's output, limited the same way, has the +same counts. PAD 120 or lower keeps them. + +## Performance + +`python3 -B perf.py` (and `--stress`), then `npm run perf:audit -- check +evidence/performance.json --stamp`: + +| Check | Result | +|---|---| +| record | dsp record for mackity@0.1.0-experimental | +| cycles | 4 x 251 = 1,004 of 3,120 a sample per core (32 %); measured 228.2 per instance | +| stock benchmark | 228.2 vs LO-FI 290.06 (0.79x); the dearest stock effect is 330.94 | +| stress | 4 per core, eight tracks, 3 LFOs and 12 locked slots, 2 s, no clobber, no hang | + +Unsplit, every case reads 225.30 executed instructions a sample: the sample loop +has no conditional branch. The stress run's instance at core 1 position 2 put out +samples from silence: the harness writes a word a block into that audio block, as +a do-nothing module in the same layout shows. On the unit: see the test procedure +above. diff --git a/sdk/octatrack/modules/mackity/evidence/cpu-price.json b/sdk/octatrack/modules/mackity/evidence/cpu-price.json new file mode 100644 index 0000000000..5a466a167b --- /dev/null +++ b/sdk/octatrack/modules/mackity/evidence/cpu-price.json @@ -0,0 +1,146 @@ +{ + "module": "mackity", + "version": "0.1.0-experimental", + "base": "development twin 8fd6d456 of base 0.8.1 (eb6679620d0c9ed7), the owner's MKII, OS 1.40C", + "scene": "Project on the owner's development unit, bank C, Part 1 reloaded in RAM to its saved copy; picks on the empty C02, readings on C04 (trigs on steps 1/5/9/13 of T1-T4, T6, T7) at the project tempo; transport played by the tool", + "inputs": { + "transport": "playing" + }, + "seconds": 8, + "readings": 3, + "measuredAt": "2026-11-25T09:20:07.215Z", + "result": { + "id": "mackity", + "version": "file", + "packageSha256": "5a58d4cc9ce2e5c2878ddafab9fa4437d4ded051066e1d0788307693330b39ac", + "before": { + "frame": 32.2, + "frameMax": 87.3, + "frames": 67404, + "skipped": 0, + "cpu": 55.7, + "dsp1to4": 32.7, + "dsp5to8": 43.7, + "dsp1to4Peak": 35.7, + "dsp5to8Peak": 44.6, + "readings": 3, + "spread": { + "frame": 0, + "cpu": 0.3, + "dsp1to4": 0, + "dsp5to8": 0, + "frameMax": 1.9, + "dsp1to4Peak": 1.9, + "dsp5to8Peak": 0.7 + } + }, + "atRest": { + "frame": 32.2, + "frameMax": 87.1, + "frames": 69517, + "skipped": 0, + "cpu": 55.7, + "dsp1to4": 32.7, + "dsp5to8": 43.7, + "dsp1to4Peak": 33.7, + "dsp5to8Peak": 44.8, + "readings": 3, + "spread": { + "frame": 0, + "cpu": 0.1, + "dsp1to4": 0, + "dsp5to8": 0, + "frameMax": 1.5, + "dsp1to4Peak": 0, + "dsp5to8Peak": 0.9 + } + }, + "atRestAdds": { + "frame": 0, + "cpu": 0, + "dsp1to4": 0, + "dsp5to8": 0, + "dsp1to4Peak": -2, + "dsp5to8Peak": 0.2 + }, + "inUse": { + "frame": 32.3, + "frameMax": 86.2, + "frames": 69919, + "skipped": 0, + "cpu": 55.7, + "dsp1to4": 40.8, + "dsp5to8": 43.7, + "dsp1to4Peak": 41.8, + "dsp5to8Peak": 44.8, + "readings": 3, + "spread": { + "frame": 0.1, + "cpu": 0.7, + "dsp1to4": 0, + "dsp5to8": 0, + "frameMax": 1.2, + "dsp1to4Peak": 0, + "dsp5to8Peak": 0.9 + } + }, + "inUseAdds": { + "frame": 0.1, + "cpu": 0, + "dsp1to4": 8.1, + "dsp5to8": 0, + "dsp1to4Peak": 6.1, + "dsp5to8Peak": 0.2 + }, + "inUseOn": "T1 FX2", + "curve": { + "tracks": [ + "T1", + "T3", + "T6", + "T7" + ], + "points": [ + 87.1, + 85.3, + 84.9, + 88, + 84.2 + ], + "adds": [ + -1.8, + -2.2, + 0.9, + -2.9 + ], + "first": 0.9, + "each": 0.9, + "notes": [], + "admission": [ + { + "pattern": "empty", + "number": 2, + "track": "T1", + "seconds": 8, + "admitted": true, + "frameMax": 36.4, + "frame": 27.7, + "dropped": 0, + "stalls": 0 + }, + { + "pattern": "medium", + "number": 4, + "track": "T1", + "seconds": 8, + "admitted": true, + "frameMax": 83, + "frame": 32.3, + "dropped": 0, + "stalls": 0 + } + ] + }, + "rolledBack": true + } +} diff --git a/sdk/octatrack/modules/mackity/evidence/frame-cost.json b/sdk/octatrack/modules/mackity/evidence/frame-cost.json new file mode 100644 index 0000000000..bb2049383c --- /dev/null +++ b/sdk/octatrack/modules/mackity/evidence/frame-cost.json @@ -0,0 +1,55 @@ +{ + "module": "mackity", + "version": "0.1.0-experimental", + "base": "development twin 8fd6d456 of base 0.8.1 (eb6679620d0c9ed7), the owner's MKII, OS 1.40C", + "scene": "Project on the owner's development unit, bank C, Part 1 reloaded in RAM to its saved copy; picks on the empty C02, readings on C04 (trigs on steps 1/5/9/13 of T1-T4, T6, T7) at the project tempo; transport played by the tool", + "seconds": 8, + "measuredAt": "2026-11-25T09:20:07.215Z", + "tracks": [ + "T1", + "T3", + "T6", + "T7" + ], + "rest": 0, + "first": 0.9, + "each": 0.9, + "points": [ + 87.1, + 85.3, + 84.9, + 88, + 84.2 + ], + "adds": [ + -1.8, + -2.2, + 0.9, + -2.9 + ], + "admission": [ + { + "pattern": "empty", + "number": 2, + "track": "T1", + "seconds": 8, + "admitted": true, + "frameMax": 36.4, + "frame": 27.7, + "dropped": 0, + "stalls": 0 + }, + { + "pattern": "medium", + "number": 4, + "track": "T1", + "seconds": 8, + "admitted": true, + "frameMax": 83, + "frame": 32.3, + "dropped": 0, + "stalls": 0 + } + ], + "notes": [] +} diff --git a/sdk/octatrack/modules/mackity/evidence/performance.json b/sdk/octatrack/modules/mackity/evidence/performance.json new file mode 100755 index 0000000000..3caf887c25 --- /dev/null +++ b/sdk/octatrack/modules/mackity/evidence/performance.json @@ -0,0 +1,34 @@ +{ + "schema": 1, + "module": "mackity", + "version": "0.1.0-experimental", + "sourceSha256": "617cb4e6beee171d3ba2be4883e9553dfa29aac13739768327a6af6aadfe0974", + "kind": "dsp", + "cycles": { + "unit": "instructions/sample", + "static": 251, + "measured": 228.2, + "instancesPerCore": 4, + "method": "static: perf.py, by the rule tools/build/cycle_count.py prices a straight-line loop with (one cycle a word): the per-sample loop's 21 words plus twice the 115-word channel routine it calls, 251 cycles/sample; the routine has no branch and the loop no nested do or rep. The per-call setup (62 words: knob decode, seeding, the glides' snap) runs once a call and is not in this floor; bsr/rts pipeline cost is not modelled. measured: perf.py, executed instructions from dsp_host's meter, one instance on verify.py's synthetic image (no null-stub subtraction), 4,096 blocks of 16 frames of stereo noise each: fixed knobs at the defaults (TRIM 13, PAD 127) and the dearest setting (TRIM 127), and a moving pattern (both knobs swept by triangles and jumped at random every 37 blocks), each unsplit and with a trig split at every position 1-15: 48 cases. Unsplit 225.30 in every case (the sample loop has no conditional branch); worst 228.20 with a split of 1 frame, where the setup runs twice a block. Executed instructions in dsp_host, not chip cycles; no stalls modelled." + }, + "stock": { + "comparator": "LO-FI", + "comparatorWorst": 290.06, + "dearestWorst": 330.94, + "baseline": "LOFI2's record (perf.py bench on the original image, the same stock image): LO-FI through fixed, moving and trig-split-1-15 cases, worst 290.06, unsplit 275.44; DJ EQ, the dearest stock effect, 330.94 with splits, 293.38 unsplit, as benchmark_stock_dsp.py's results.json. Not re-run for Mackity; its own cases match those (fixed, moving, a split at every position 1-15).", + "stockSha256": "164f31224bf61181e3f50e7dec40df9afcae5b16dbf6e4c0d0cc5e986af0a84e", + "justification": "LO-FI is the stock effect closest in function (its distortion stage). Mackity's worst, 228.20, is 0.79x LO-FI's 290.06 and 0.69x DJ EQ's 330.94; unsplit 225.30 against 275.44 and 293.38. It does upstream's whole algorithm: two 48-bit one-pole high-passes, two direct-form biquads, the clip and the fifth-order curve, per channel." + }, + "stress": { + "instancesPerCore": 4, + "tracks": 8, + "lfosPerTrack": 3, + "lockedSlots": 12, + "seconds": 2, + "guard": true, + "dirty": true, + "clobbers": 0, + "hangs": 0, + "method": "perf.py --stress: stress_project.py needs an Octatrack template project, so the load is driven straight into dsp_host on verify.py's synthetic image with both cores (-memB, -ctxB): eight Mackity instances, four a core, each on its own stem (decaying noise bursts, a full-scale square, a 20 Hz-20 kHz sweep, full-scale noise, impulses, full-scale DC steps, silence, a three-note chord) for 2 s plus a 2 s tail; all twelve parameter words given a new value every block through -paramfile: three LFOs (triangles on TRIM and PAD with a random jump every 37 blocks, a square on slot 2) and random values on slots 3-11. Mackity has two knobs and reads only slots 0 and 1; the other ten change to show that traffic on slots it does not read leaves it alone; trig splits of 1, 3, 7, 8, 12 and 15 frames on six instances; -guard (window 14,336 words an instance) and -dirty 0x5a. Result: host exit 0, no hang; every instance 0 stray write regions and 0 clobbers, guard clean; per-core peak 913.0 and 907.1 executed instructions/sample with four instances each (4 x 228.2). The instance at core 1 position 2 fed silence still put out non-zero samples: the harness writes one word a block into that audio block, as a do-nothing init/proc module in the same layout shows (1,000 non-zero samples in 1,000 blocks), so it is not Mackity's. It exercises the DSP side only: the firmware's LFO and lock delivery, Part switches and the ColdFire side are not in it." + } +} diff --git a/sdk/octatrack/modules/mackity/mackity.asm b/sdk/octatrack/modules/mackity/mackity.asm new file mode 100755 index 0000000000..94335ee70b --- /dev/null +++ b/sdk/octatrack/modules/mackity/mackity.asm @@ -0,0 +1,240 @@ +; MACKITY -- DSP56300 port of Chris Johnson's Airwindows Mackity (MIT). +; Copyright (c) 2016 Chris Johnson (Airwindows), MIT. +; Upstream revision and full MIT licence: upstream/, LICENSE. +; +; A buffer-free stereo insert for FX1 or FX2: no allocator, no bus role, +; no absolute Y. Per channel, as MackityProc.cpp at 44.1 kHz: +; one-pole high-pass (13 Hz), 19.16 kHz low-pass biquad (Q 0.43), +; IN TRIM, clip at full scale, v - 0.1768 v^5, 19.16 kHz low-pass +; biquad (Q 1.16), one-pole high-pass (2 Hz), OUT PAD. +; The trim is applied after the first biquad instead of before it: both +; are linear, so the result is the same while the trim holds still. +; +; Fixed point. The high-passes and biquads run at quarter scale (x/4), so +; neither biquad can overflow (their impulse responses sum to 1.54 and +; 2.52). The value going into the trim is limited at twice full scale +; (+6 dBFS), which keeps a +40 dB trim inside the accumulator's guard bits. +; The one-pole states are 48 bits (a 24-bit state stalls short of its +; input); their outputs subtract the state's high word, so silence in ends +; in exact silence out. The original's float dither and denormal noise are +; left out: the Octatrack's path is 24-bit fixed point. +; +; Knobs (page 1): TRIM x:(r6+0), PAD x:(r6+1), value<<16. +; TRIM: gain (k/13)^2, the original's (10 A)^2 with A = k/130: 13 is +; exactly 0 dB, 127 is +39.6 dB, 0 is silence. +; PAD: linear output gain k/128, 127 exactly 1. +; Both glide per sample (1/64 a sample, 1.45 ms) and snap onto their +; target at the start of a call once within 64 LSB, so a knob at rest is +; exact. The first call after init starts on the knobs. +; +; State (X, offsets from r7; init clears $00..$1f): +; channel block, L at $00, R at $0c (r5 points at it in mack_chan): +; +0/+1 high-pass in, state high/low +2/+3 biquad A x1/x2 +; +4/+5 biquad A y1/y2 +6/+7 biquad B x1/x2 +; +8/+9 biquad B y1/y2 +a/+b high-pass out, state hi/lo +; $18 trim target, $19 trim run (gain/128) +; $1b pad target, $1c pad run (pad/2), $1e seeded +; $1a, $1d and $1f are reserved. Nothing above $1f is touched. +; Every product is the signed mpy/mac x0,y1 form. +; CYCLES_FORWARD_BRANCHES +init: + move r7,r5 + move #>$ffffff,m5 + clr a + do #32,>mack_zero + move a,x:(r5)+ +mack_zero: + nop + rts + +proc: + move #>$ffffff,m5 +; TRIM: (kn^2 * 16384/169) = gain/128, kn = knob/128 with its fraction. + move x:(r6+$0),a + and #>$7fffff,a + move a1,x0 + move x0,y1 + mpy x0,y1,a + move a,x0 + move #>$60f25e,y1 + mpy x0,y1,a + move a,x:(r7+$18) +; PAD: pad/2, 127 and above exactly one half. + move x:(r6+$1),a + and #>$7fffff,a + move a1,x0 + move x0,b + asr #1,b,b + move x0,a + move #>$7f0000,y0 + cmp y0,a + move #>$400000,y1 + tge y1,b + move b1,x:(r7+$1b) +; The first call after init starts on the knobs. + move x:(r7+$1e),a + tst a + bne mack_seeded + move x:(r7+$18),x0 + move x0,x:(r7+$19) + move x:(r7+$1b),x0 + move x0,x:(r7+$1c) + move #>1,x0 + move x0,x:(r7+$1e) +mack_seeded: +; A glide within 64 LSB of its target snaps onto it. + move x:(r7+$18),a + move x:(r7+$19),x0 + sub x0,a + abs a + move #>64,x0 + cmp x0,a + move x:(r7+$19),b + move x:(r7+$18),y0 + tlt y0,b + move b1,x:(r7+$19) + move x:(r7+$1b),a + move x:(r7+$1c),x0 + sub x0,a + abs a + move #>64,x0 + cmp x0,a + move x:(r7+$1c),b + move x:(r7+$1b),y0 + tlt y0,b + move b1,x:(r7+$1c) + do n7,>mack_frameend + move x:(r7+$18),a + move x:(r7+$19),x0 + sub x0,a + asr #6,a,a + add x0,a + move a1,x:(r7+$19) + move x:(r7+$1b),a + move x:(r7+$1c),x0 + sub x0,a + asr #6,a,a + add x0,a + move a1,x:(r7+$1c) + move r7,r5 + bsr mack_chan + move a,x:(r0)+ + lua (r7+$0c),r5 + bsr mack_chan + move a,x:(r0)+ +mack_frameend: + nop + rts + +; One channel: in x:(r0), state block at r5; out in a (the caller's store +; limits it to full scale). +mack_chan: +; High-pass in: s += K1 (h - s), y = h - s, h = x/4. + move x:(r0),a + asr #2,a,a + move a1,x1 + move x:(r5+$0),b + move x:(r5+$1),b0 + move x1,a + move x:(r5+$0),y0 + sub y0,a + move a,x0 + move #>$003cfa,y1 + mac x0,y1,b + move b1,x:(r5+$0) + move b0,x:(r5+$1) + move x1,a + move b1,y0 + sub y0,a + move a,x1 +; Biquad A, direct form 1, halved coefficients. + move x1,x0 + move #>$29e6d8,y1 + mpy x0,y1,a + move x:(r5+$2),x0 + move #>$53cdaf,y1 + mac x0,y1,a + move x:(r5+$3),x0 + move #>$29e6d8,y1 + mac x0,y1,a + move x:(r5+$4),x0 + move #>$afd9f8,y1 + mac x0,y1,a + move x:(r5+$5),x0 + move #>$e88aaa,y1 + mac x0,y1,a + asl #1,a,a + move x:(r5+$2),y0 + move y0,x:(r5+$3) + move x1,x:(r5+$2) + move x:(r5+$4),y0 + move y0,x:(r5+$5) + move a,x:(r5+$4) +; IN TRIM and the clip: limited at +6 dBFS, times gain, limited at 0 dBFS. + asl #1,a,a + move a,x0 + move x:(r7+$19),y1 + mpy x0,y1,a + asl #8,a,a + move a,x0 +; The curve at quarter scale: c/4 - (0.1768/4) c^5. + move x0,y1 + move y1,y0 + mpy x0,y1,a + move a,x0 + move x0,y1 + mpy x0,y1,a + move a,x0 + move #>$05a858,y1 + mpy x0,y1,a + move a,x0 + move y0,y1 + mpy x0,y1,b + move y0,a + asr #2,a,a + sub b,a + move a,x1 +; Biquad B. + move x1,x0 + move #>$344a81,y1 + mpy x0,y1,a + move x:(r5+$6),x0 + move #>$689502,y1 + mac x0,y1,a + move x:(r5+$7),x0 + move #>$344a81,y1 + mac x0,y1,a + move x:(r5+$8),x0 + move #>$9bfaa3,y1 + mac x0,y1,a + move x:(r5+$9),x0 + move #>$d2db5a,y1 + mac x0,y1,a + asl #1,a,a + move x:(r5+$6),y0 + move y0,x:(r5+$7) + move x1,x:(r5+$6) + move x:(r5+$8),y0 + move y0,x:(r5+$9) + move a,x1 + move x1,x:(r5+$8) +; High-pass out: s += K2 (u - s), y = u - s. + move x:(r5+$a),b + move x:(r5+$b),b0 + move x1,a + move x:(r5+$a),y0 + sub y0,a + move a,x0 + move #>$00096c,y1 + mac x0,y1,b + move b1,x:(r5+$a) + move b0,x:(r5+$b) + move x1,a + move b1,y0 + sub y0,a +; OUT PAD: y * (pad/2) * 8 = y * 4 * pad, back to full scale. + move a,x0 + move x:(r7+$1c),y1 + mpy x0,y1,a + asl #3,a,a + rts diff --git a/sdk/octatrack/modules/mackity/manifest.py b/sdk/octatrack/modules/mackity/manifest.py new file mode 100644 index 0000000000..075cca0a0f --- /dev/null +++ b/sdk/octatrack/modules/mackity/manifest.py @@ -0,0 +1,55 @@ +"""MACKITY -- Chris Johnson's Airwindows Mackity (MIT): the input stage of a +Mackie-style mixing desk, driven by IN TRIM. + +A buffer-free stereo insert for FX1 or FX2 of any track (no allocator, no +bus role, no absolute Y). Upstream's whole algorithm at 44.1 kHz: two +one-pole high-passes, two 19.16 kHz biquads, the clip and v - 0.1768 v^5. +verify.py holds the assembly to reference.py's model bit for bit, and +test_reference.py holds the model to upstream. Hardware operation is untested. +""" +from remix.schema import (Category, Proof, BusRole, DspSection, Formatter, Gate, Harness, Kind, + MenuEntry, Module, Param, YBase) + +BLANK = Param(b"", 0, 128, active=False, formatter=Formatter.PLAIN) + +MODULE = Module( + name="mackity", + key="MACKITY", + kind=Kind.DSP_EFFECT, + doc="Chris Johnson / Airwindows Mackity: a Mackie-style desk input stage, IN TRIM into the console's clip.", + category=Category.TRACK, author="repeat98", author_url="https://github.com/repeat98", + proof=Proof.RENDER, proof_note="verify.py renders it in dsp_host bit for bit against the model; hardware untested", + + menu=MenuEntry( + fx2_id=0x1a, # a free non-stock id (MODULES.md); the base assigns the live one + donor_desc=0x400d58b8, # DARK REV; every drawn slot is written below + abbr=b"MACK", + fullname=b"Mackity", + build_tag=False, + ), + + params=( + Param(b"TRIM", 13, 128, active=True, formatter=Formatter.PLAIN, + doc="In Trim: gain (TRIM/13)^2 into the desk; 13 is 0 dB, 127 is +39.6 dB, 0 is silence"), + Param(b"PAD", 127, 128, active=True, formatter=Formatter.PLAIN, + doc="Out Pad: output level PAD/128, 127 is exactly 0 dB"), + BLANK, BLANK, BLANK, BLANK, + BLANK, BLANK, BLANK, BLANK, BLANK, BLANK, + ), + + dsp=DspSection( + asm="modules/mackity/mackity.asm", + # BYTE-LOAD-BEARING: the donor region is packed in this order. + priority=35, + bus_role=BusRole.NONE, + ybase=YBase.NEVER, + r7_latch_slot=None, + gate_label=None, + ), + + harness=Harness(layout_char=None, is_server=False), + + gates=(Gate("modules/mackity/verify.py", remix_arg=False),), + # The work is the same at every setting; TRIM at the top keeps the clip busy. + dear={"TRIM": 127, "PAD": 127}, +) diff --git a/sdk/octatrack/modules/mackity/media/LICENSE.md b/sdk/octatrack/modules/mackity/media/LICENSE.md new file mode 100644 index 0000000000..20651d0bdd --- /dev/null +++ b/sdk/octatrack/modules/mackity/media/LICENSE.md @@ -0,0 +1,10 @@ +# LCD documentation captures + +Captured from the LCD of an Octatrack MKII over USB, for documentation of this +module. The underlying Octatrack interface remains Elektron's copyrighted +interface; it is not relicensed as module source or supplied as UI assets for +reuse. + +License identifier: LicenseRef-OT-UI-Documentation. These images contain no +firmware, executable code, factory samples or raw memory dumps. Provenance and +hashes are in capture.json. diff --git a/sdk/octatrack/modules/mackity/media/capture.json b/sdk/octatrack/modules/mackity/media/capture.json new file mode 100644 index 0000000000..f3b8512e34 --- /dev/null +++ b/sdk/octatrack/modules/mackity/media/capture.json @@ -0,0 +1,41 @@ +{ + "firmware": "1.40C", + "moduleVersion": "0.1.0-experimental", + "hardware": true, + "model": "MKII", + "capturedOn": "2026-11-25", + "capturedBy": "repeat98", + "imageSha256": "af4934ce5cdbc9816bc49864bd8848a6bad0af9af692b6752f330749b5f1b5c6", + "baseIdentity": "8fd6d456abf3865b36ac024d19324290dc36cb04a7efe29be4838ce6e825afb3", + "packageSha256": "5a58d4cc9ce2e5c2878ddafab9fa4437d4ded051066e1d0788307693330b39ac", + "sourceRevision": "ccbb96b6c06ae074159be45d66f69812d450793f", + "setup": "The owner's Octatrack MKII, OS 1.40C, RAM-booted on development twin 8fd6d456 of Modwerk base 0.8.1 (imageSha256 is that twin's MAIN image; baseIdentity is the identity the unit reported). The module ran as a RAM trial of the package named here, built by npm run module:dev -- mackity --build-only --cycles 226 --cycles-kind executed --state 32 from the source revision named here. Each picture is the unit's own LCD, read over USB by the development session's png step: 128x64 at integer scale 2 (256x128), two grey levels in an 8-bit greyscale PNG, not edited. Hardware captures, not emulator ones. The panel steps were sent by the session (bank F pattern 1; pick:T2:FX1:MACKITY; T2; FX1; FUNC+FX1).", + "palette": { + "on": [ + 24, + 24, + 24 + ], + "off": [ + 255, + 255, + 255 + ] + }, + "images": [ + { + "path": "mackity-chooser.png", + "sha256": "20bfc4bfed6244b16bf5c3bb7885caaa2f1a69020b2752c81908dc842d5a7b3c", + "scale": 2, + "page": "FX1 SETUP (effect chooser)", + "state": "Track 2 with Mackity on FX1: FUNC+FX1 opens the chooser on the current effect, Mackity." + }, + { + "path": "mackity-main.png", + "sha256": "6e303c4880734a17813ae318bde25906fd3e272de72ba73cac25ac1300c67bd6", + "scale": 2, + "page": "FX1", + "state": "Track 2 with Mackity on FX1 at the defaults (TRIM 13, PAD 127), stopped." + } + ] +} diff --git a/sdk/octatrack/modules/mackity/media/mackity-chooser.png b/sdk/octatrack/modules/mackity/media/mackity-chooser.png new file mode 100644 index 0000000000..4962387b94 Binary files /dev/null and b/sdk/octatrack/modules/mackity/media/mackity-chooser.png differ diff --git a/sdk/octatrack/modules/mackity/media/mackity-main.png b/sdk/octatrack/modules/mackity/media/mackity-main.png new file mode 100644 index 0000000000..6f8e6ee953 Binary files /dev/null and b/sdk/octatrack/modules/mackity/media/mackity-main.png differ diff --git a/sdk/octatrack/modules/mackity/octamod.module.json b/sdk/octatrack/modules/mackity/octamod.module.json new file mode 100644 index 0000000000..d35dfd6cb5 --- /dev/null +++ b/sdk/octatrack/modules/mackity/octamod.module.json @@ -0,0 +1,281 @@ +{ + "schemaVersion": 2, + "id": "mackity", + "key": "MACKITY", + "name": "Mackity", + "version": "0.1.0-experimental", + "category": "effects", + "author": { + "github": "repeat98", + "credits": [ + "Chris Johnson / Airwindows: original Mackity algorithm and MIT-licensed source" + ] + }, + "nativeManifest": "manifest.py", + "presentation": { + "label": "MACKITY", + "family": "Saturation", + "summary": "Chris Johnson's Airwindows Mackity: the input stage of a Mackie-style mixing desk, driven by IN TRIM, on FX1 or FX2 of any track.", + "overview": "Mackity is Airwindows' model of a Mackie-style desk's input stage. The track's audio passes a gentle low cut, the desk's high-frequency rolloff, the IN TRIM gain and the console's clip, rounded by its curve, then a second rolloff and a DC blocker. At TRIM 13 it adds only the desk's colour; turning TRIM up drives the channel into the clip, from warm thickening to hard, square distortion. PAD sets the output level. The algorithm is upstream's, unchanged, in 24-bit fixed point at the Octatrack's 44.1 kHz.", + "highlights": [ + "Upstream's complete Mackity algorithm, credited to Chris Johnson", + "TRIM from silence through 0 dB (13) to +39.6 dB into the console's clip", + "Stereo and buffer-free: FX1 or FX2 on any track" + ], + "usage": [ + "Put MACKITY on FX1 of a drum or bass track. At TRIM 13 and PAD 127 it adds the desk's colour without a change in level.", + "Turn TRIM up for drive: at 26 (+12 dB) a track peaking at -12 dBFS reaches the clip, and above that it clips harder.", + "Turn PAD down to set the output level after heavy drive." + ] + }, + "controls": [ + { + "name": "TRIM", + "default": 13, + "count": 128, + "labels": null, + "doc": "In Trim: the gain into the desk, (TRIM/13)^2 as in the original. 13 is 0 dB, 26 is +12 dB, 52 is +24 dB, 127 is +39.6 dB; 0 is silence. More gain drives the signal into the console's clip." + }, + { + "name": "PAD", + "default": 127, + "count": 128, + "labels": null, + "doc": "Out Pad: the output level, PAD/128; 127 is exactly 0 dB, 64 is -6 dB, 0 is silence. With heavy drive the desk's rolloff peaks up to about 0.6 dB over full scale, which the Octatrack's output limits; PAD 120 or lower keeps every peak." + } + ], + "compatibility": { + "firmware": "1.40C", + "location": "FX1 / FX2", + "conflicts": [], + "uiClaims": [], + "limitations": [ + "At high TRIM the clip makes harmonics above 22 kHz that fold back below it, as the original does at 44.1 kHz.", + "With heavy drive, peaks up to about 0.6 dB over full scale are limited by the Octatrack's output; PAD 120 or lower keeps them.", + "On a pattern that already fills the CPU, a pick can be refused with CPU FULL (it asks +3 % on a busy eight-track pattern).", + "Tested on one MKII by the test procedure; the MKI, a Part or project reload with it saved and a power cycle were not tested by hand.", + "The original's 32-bit float dither is left out: the Octatrack's path is 24-bit fixed point." + ], + "effectId": 26 + }, + "resources": { + "recorded": "2026-11-25", + "storage": { + "label": "DSP program / state", + "display": "208 words / 32-word state", + "value": null, + "unit": "see display", + "method": "static", + "conditions": "The USB package's DSP effect: 208 program words on each DSP core it runs on; 32 words of the 256-word X block per instance (31 used); no buffer, no Y memory, no ColdFire code per frame.", + "source": "TESTING.md" + }, + "processing": { + "label": "DSP instruction peak", + "display": "228 instructions/sample per instance", + "value": null, + "unit": "see display", + "method": "emulator", + "conditions": "perf.py in dsp_host, 48 cases (defaults, TRIM 127, moving knobs, each unsplit and with a trig split at 1-15): worst 228.2 with a 1-frame split, 225.3 unsplit at every setting, against 290.1 for LO-FI and 330.9 for DJ EQ, the dearest stock effect. On the unit the DSP meter on T1-T4 rose 8.1 points with it on T1 FX2. Executed instructions, not chip cycles.", + "source": "TESTING.md" + }, + "cpuPrice": { + "value": 0.1, + "unit": "percent-of-frame", + "measure": "frame-interrupt", + "tool": "npm run device:price -- --write", + "date": "2026-11-25", + "conditions": "Project on the owner's development unit, bank C, Part 1 reloaded in RAM to its saved copy; picks on the empty C02, readings on C04 (trigs on steps 1/5/9/13 of T1-T4, T6, T7) at the project tempo; transport played by the tool; base development twin 8fd6d456 of base 0.8.1 (eb6679620d0c9ed7), the owner's MKII, OS 1.40C; 3 readings of 8 s a state. Frame interrupt 32.2 % before, 32.2 % installed and used nowhere, 32.3 % on T1 FX2; CPU meter 55.7 % before, 55.7 % at rest, 55.7 % in use.", + "source": "evidence/cpu-price.json" + }, + "impact": { + "conditions": "One active instance at the dearest setting (TRIM 127) with moving knobs and trig splits; no buffer; on the unit, the frame-interrupt price on a medium pattern.", + "cpu": { + "level": "minimal", + "basis": "measured-comparison", + "rationale": "No ColdFire audio code: the stock FX page publishes the knobs. On the owner's MKII the frame interrupt rose 0.1 points with it on T1 FX2 and 0 installed and unused; the instance curve read first 0.9, each 0.9.", + "source": "TESTING.md" + }, + "dsp": { + "level": "moderate", + "basis": "measured-comparison", + "rationale": "228.2 executed instructions/sample worst case with trig splits, 0.79 of LO-FI (290.1) and 0.69 of DJ EQ (330.9), the dearest stock effect, under matching cases; the static bound for four per core is 1,004 of 3,120 cycles a sample. Chip timing is unmeasured.", + "source": "TESTING.md" + }, + "memory": { + "level": "low", + "basis": "source-estimate", + "rationale": "208 program words per core, 32 words of the 256-word X block per instance, no buffer.", + "source": "TESTING.md" + } + } + }, + "tests": { + "report": "TESTING.md", + "summary": "verify.py matches the bit-exact model in dsp_host in every case; test_reference.py holds the model to upstream's algorithm; perf:audit passes at 0.79 of LO-FI's worst; npm run test:procedure steps 1-10 passed on the owner's MKII (25 Nov 2026), with the soak, the CPU price and the instance curve, and the screens captured on the unit.", + "hardwareStatus": "reported", + "evidenceRevision": "ccbb96b6c06ae074159be45d66f69812d450793f", + "gates": [ + "Worst-case cycles under parameter modulation and maximum load", + "Exact memory region and maximum-instance totals", + "Owner-reviewed real-hardware evidence with actual coverage and limitations" + ], + "qualification": { + "moduleVersion": "0.1.0-experimental", + "sourceSha256": "7271f6d9bb015b103e2048bf65912cd8b78bdcbe6205c37cb58f7434f22af846", + "cycles": [ + { + "processor": "dsp", + "worstCase": 4078, + "maxConfiguration": 16312, + "maxInstances": 8, + "budget": 49920, + "unit": "cycles/block", + "method": "static", + "conditions": { + "parameterExtremes": "Static bound per 16-frame block from the assembled words (perf.py): the per-sample loop's 21 words plus twice the 115-word channel routine, 251 cycles a sample (x16 = 4,016), plus the 62-word per-call setup (knob decode, seeding, the glides' snap) charged once per call. The loop and the routine have no conditional branch, so every knob value runs the same words.", + "parameterModulation": "Two calls per block cover a trig split: 16 x 251 + 2 x 31 = 4,078 (the setup's words split between its two halves, each charged on every call). LFOs, locks, scenes and CC reach the same two knob words, decoded every call and glided per sample. The dsp_host measurement with moving knobs and splits at 1-15 read at most 228.2 executed instructions a sample (3,651 a block), inside the bound.", + "modeSwitching": "Mackity has no modes: TRIM and PAD are continuous and run the same code at every value. Part changes reach it as knob changes.", + "maxLoad": "Eight instances, four per DSP core (FX2 of four tracks, or FX1 and FX2 of two): 4 x 4,078 = 16,312 per core within the SDK's 49,920 module allowance (3,120 a sample x 16). On the unit, eight at once while playing ran with CPU 458 and DSP peaks 663 and 743 per mille (device:test). The 2 s eight-instance dsp_host stress run peaked at 913.0 executed instructions a sample per core (evidence/performance.json). Real-chip contention and stalls are not modelled.", + "inputConditions": "The bound does not depend on sample values: silence, impulses, full-scale and clipping input run the same straight-line code. The stress stems include full-scale squares, impulses, DC steps, noise and a 20 Hz-20 kHz sweep." + }, + "report": "evidence/performance.json" + } + ], + "memory": { + "regions": [ + { + "name": "DSP program, the package's effect on each core it runs on", + "space": "dsp-p", + "words": 208, + "wordBits": 24, + "bytes": 624, + "scope": "shared" + }, + { + "name": "Used and initialized stock X state, r7+0..0x1f", + "space": "dsp-x", + "words": 32, + "wordBits": 24, + "bytes": 96, + "scope": "instance" + }, + { + "name": "Reserved remainder of the 256-word stock X block", + "space": "dsp-x", + "words": 224, + "wordBits": 24, + "bytes": 672, + "scope": "instance" + }, + { + "name": "System stack, one bsr inside the sample loop's do, on both cores", + "space": "dsp-x", + "words": 8, + "wordBits": 24, + "bytes": 24, + "scope": "shared" + } + ], + "perInstanceBytes": 768, + "sharedBytes": 648, + "maxInstances": 8, + "totalBytes": 6792, + "conditions": "The USB package (472 bytes of code and data, no bss, one DSP effect of 208 words) as the Modwerk base loads it into each core's DSP arena; per instance the stock 256-word r7 block an FX instance gets, of which Mackity initializes $00-$1f and uses $00-$1e; no allocator buffer, no Y memory (ybase NEVER), no scratch outside r7. The system stack holds the do loop and one bsr. Logical 24-bit DSP words.", + "report": "TESTING.md" + }, + "imageSha256": "af4934ce5cdbc9816bc49864bd8848a6bad0af9af692b6752f330749b5f1b5c6", + "hardware": { + "kind": "functional", + "status": "reported", + "model": "MKII", + "testedOn": "2026-11-25", + "tester": "repeat98", + "sourceRevision": "ccbb96b6c06ae074159be45d66f69812d450793f", + "imageSha256": "af4934ce5cdbc9816bc49864bd8848a6bad0af9af692b6752f330749b5f1b5c6", + "summary": "On the owner's Octatrack MKII (OS 1.40C), RAM-booted on development twin 8fd6d456 of base 0.8.1 (imageSha256 is that twin's MAIN image), the agent in the owner's session ran npm run test:procedure on the package of this source (5a58d4cc): software checks, the cost model, device:test (alone on FX2 of T1 and T5, eight at once while playing, 12 Part switches), a 2-minute soak, device:price with the instance curve and admission on the empty C02 and the medium C04, and the inventory put back; all passed. Earlier the same day, a 30-second RAM trial on the release base 0.8.1 and device:test on an empty bank passed too. The screens were read off the unit's LCD during a trial. The owner asked for it to be released without the hands-on stage (25 Nov 2026: \"you can merge and get it live yourself\").", + "limitations": [ + "One unit and its owner's session, not an independent reviewer; the MKI was not tested.", + "The owner's listening, a Part and project save and reload, and the Keep with a power cycle were not run by hand.", + "MAIN and CUE were not recorded over USB.", + "Single 8-s readings of the DSP load scatter by about a point; the DSP cost stands on dsp_host's count.", + "A card build beside Analog BD was not built or placed." + ], + "report": "TESTING.md" + }, + "documentation": { + "tutorial": { + "title": "Quick tutorial", + "steps": [ + "Put MACKITY on FX1 of a drum loop's track: hold FUNC, press FX1, turn LEVEL to Mackity and press YES. At TRIM 13 and PAD 127 the loop keeps its level and gains the desk's colour.", + "Turn TRIM to 40 on the FX1 page. The loop thickens and its peaks flatten into the clip; turn PAD to about 90 to bring the level back down.", + "Set TRIM 13 and PAD 127 to return to the clean desk, or select NONE in the FX1 chooser to remove it." + ] + }, + "screenshots": [ + "media/mackity-chooser.png", + "media/mackity-main.png" + ], + "screenshotStyle": "black-and-white" + } + } + }, + "source": { + "repository": "https://github.com/airwindows/airwindows", + "revision": "e718c9bcfcdd736deeddb08bffe6bce2aa8e0eea", + "path": "plugins/LinuxVST/src/Mackity" + }, + "license": { + "spdx": "MIT", + "file": "LICENSE", + "declaration": "Chris Johnson's published Mackity source and his full MIT copyright and permission notice are retained in upstream/ and LICENSE; the Octatrack adaptation is distributed under the same terms. No desktop binary, firmware, extracted stock routine or table, or memory dump is included." + }, + "media": [ + { + "path": "media/mackity-chooser.png", + "captureType": "hardware", + "caption": "Select an audio track, hold FUNC and press FX1. Turn LEVEL down the list to Mackity and press YES to put it on FX1 (FX2 works the same).", + "alt": "Octatrack FX1 SETUP: the effect list from FLANGER to LO-FI with the cursor on Mackity.", + "credit": "Modwerk documentation capture; underlying Octatrack UI by Elektron", + "license": "LicenseRef-OT-UI-Documentation", + "source": "original", + "otUi": { + "page": "FX1 SETUP (effect chooser)", + "shows": "location", + "firmware": "1.40C", + "moduleVersion": "0.1.0-experimental", + "imageSha256": "af4934ce5cdbc9816bc49864bd8848a6bad0af9af692b6752f330749b5f1b5c6", + "setup": "Captured over USB from the LCD of the owner's Octatrack MKII (OS 1.40C, development twin 8fd6d456 of Modwerk base 0.8.1, RAM-booted; imageSha256 is that twin's MAIN image) with the development session's png step on 25 November 2026, during a RAM trial of this version's package 5a58d4cc, built by module:dev from source ccbb96b6c. 256x128, the 128x64 LCD at integer scale 2, two grey levels, not edited." + } + }, + { + "path": "media/mackity-main.png", + "captureType": "hardware", + "caption": "Press FX1 for its page: TRIM (knob A) drives the desk, 13 is 0 dB; PAD (knob B) sets the output level, 127 is 0 dB.", + "alt": "Octatrack FX1 page of track 2 running Mackity: knobs TRIM and PAD, FX1 Mackity in the bottom line.", + "credit": "Modwerk documentation capture; underlying Octatrack UI by Elektron", + "license": "LicenseRef-OT-UI-Documentation", + "source": "original", + "otUi": { + "page": "FX1", + "shows": "controls", + "firmware": "1.40C", + "moduleVersion": "0.1.0-experimental", + "imageSha256": "af4934ce5cdbc9816bc49864bd8848a6bad0af9af692b6752f330749b5f1b5c6", + "setup": "Captured over USB from the LCD of the owner's Octatrack MKII (OS 1.40C, development twin 8fd6d456 of Modwerk base 0.8.1, RAM-booted; imageSha256 is that twin's MAIN image) with the development session's png step on 25 November 2026, during a RAM trial of this version's package 5a58d4cc, built by module:dev from source ccbb96b6c. 256x128, the 128x64 LCD at integer scale 2, two grey levels, not edited." + } + } + ], + "access": { + "location": "FUNC + FX1 or FUNC + FX2 SETUP on an audio track: the effect chooser. TRIM and PAD are on the FX page (knobs A and B).", + "steps": [ + "Select an audio track that plays a sample.", + "Hold FUNC and press FX1 (or FX2) to open its SETUP. Turn LEVEL to Mackity and press YES.", + "Press FX1 (or FX2) for its page: TRIM on knob A, PAD on knob B.", + "Set TRIM 13 and PAD 127 for the desk's colour at unchanged level, or select NONE to remove it." + ], + "screenshots": [ + "media/mackity-chooser.png", + "media/mackity-main.png" + ] + } +} diff --git a/sdk/octatrack/modules/mackity/perf.py b/sdk/octatrack/modules/mackity/perf.py new file mode 100755 index 0000000000..de79d0dbec --- /dev/null +++ b/sdk/octatrack/modules/mackity/perf.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""MACKITY's performance measurements for evidence/performance.json, in dsp_host. + + python3 -B perf.py (the tools verify.py finds; about a minute) + +static words of the per-sample loop plus twice the channel routine it calls, one cycle a word (the rule + tools/build/cycle_count.py prices straight-line loops by; the routine has no branch); the per-call + setup (knob decode, seeding, the glides' snap) apart. Pipeline cost of bsr/rts is not modelled. +measured executed instructions a sample from dsp_host's meter, one instance on verify.py's synthetic image (no + null-stub subtraction): fixed knobs at the defaults and the dearest setting, a moving pattern (both knobs + swept and jumped every block), each unsplit and with a trig split at every position 1-15. +stress eight instances, four a core, each on its own stem (drums-like bursts, a full-scale square, a sweep, + noise, impulses, DC steps, silence, a chord), all twelve parameter words given a new value every + block through -paramfile (triangle LFOs on TRIM and PAD with random jumps, a square on slot 2, random + values on slots 3-11, which Mackity does not read), trig splits of 1, 3, 7, 8, 12 and 15 frames, 2 s of + audio and a 2 s tail, under -guard and -dirty. +""" +import math +import pathlib +import random +import re +import struct +import subprocess +import sys +import tempfile + +HERE = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import verify as V # noqa: E402 + +Q = V.Q +BLOCKS = 4096 + + +def static(work): + blob, syms = V.assemble(work) + dis = V.disassemble(blob) + words = {int(l[:6], 16): l for l in dis} + addrs = sorted(words) + size = {a: (addrs[i + 1] - a if i + 1 < len(addrs) else 1) for i, a in enumerate(addrs)} + + def span(lo, hi): + return sum(size[a] for a in addrs if lo <= a < hi) + loop_lo = next(a for a in addrs if a > syms['proc'] and re.search(r'\bdo\s+n7', words[a])) + loop_lo += size[loop_lo] + loop = span(loop_lo, syms['mack_frameend']) + chan = span(syms['mack_chan'], max(addrs) + 1) + setup = span(syms['proc'], loop_lo) + return loop + 2 * chan, loop, chan, setup + + +def meter(work, mem, syms, params, frames=16, extra=(), tag='m', blocks=BLOCKS): + n = frames * blocks + rnd = random.Random(5) + sig = [round(0.7 * Q * (rnd.random() * 2 - 1)) for _ in range(n)] + inp = work / f'{tag}.in' + inp.write_bytes(struct.pack(f'<{2 * n}i', *[s for v in sig for s in (v, v)])) + cmd = [str(V.DSP_HOST), '-mem', str(mem), '-init', f"{syms['init']:x}", '-proc', f"{syms['proc']:x}", + '-ctx', '40,41,42', '-frames', str(frames), '-blocks', str(blocks), '-stereo', '-in', str(inp), + '-out', str(work / f'{tag}.out'), *params, *extra] + r = subprocess.run(cmd, capture_output=True, text=True, timeout=900) + if r.returncode: + sys.exit(f'[FAIL] dsp_host exit {r.returncode}: {r.stdout[-1500:]}{r.stderr}') + m = re.search(r'\(([\d.]+)/sample max', r.stdout) + return float(m.group(1)), r.stdout + + +def moving(path, blocks=BLOCKS, seed=1, every_slot=False): + """TRIM and PAD swept by triangles and jumped every 37 blocks. every_slot (the stress run): a third LFO, a + square, on slot 2, and a new random value on slots 3-11 every block, so all twelve parameter words change each + block; Mackity reads only slots 0 and 1.""" + rnd = random.Random(seed) + rows = [] + for b in range(blocks): + tri = abs((b % 256) - 128) + trim, pad = min(127, tri), 127 - min(127, abs(((b + 64) % 256) - 128)) + if b % 37 == 0: + trim, pad = rnd.randrange(128), rnd.randrange(128) + rest = [127 if (b // 50) % 2 else 0] + [rnd.randrange(128) for _ in range(9)] if every_slot else [0] * 10 + rows.append(','.join(map(str, [b, trim, pad, *rest]))) + path.write_text('\n'.join(rows) + '\n') + + +def main(): + only_stress = '--stress' in sys.argv + with tempfile.TemporaryDirectory() as tmp: + work = pathlib.Path(tmp) + total, loop, chan, setup = static(work) + print(f'static: {total} cycles/sample in the loop ({loop} loop words + 2 x {chan} channel words); ' + f'per-call setup {setup} words') + blob, syms = V.assemble(work) + mem = work / 'm.mem' + V.write_mem(blob, mem) + mv = work / 'moving.params' + moving(mv) + cases = {'defaults': ['-params', '13,127,0,0,0,0,0,0,0,0,0,0'], + 'dearest': ['-params', '127,127,0,0,0,0,0,0,0,0,0,0'], + 'moving': ['-params', '13,127,0,0,0,0,0,0,0,0,0,0', '-paramfile', str(mv)]} + worst = (0.0, '') + results = {} + for name, params in ({} if only_stress else cases).items(): + for split in [0] + list(range(1, 16)): + v, _ = meter(work, mem, syms, params, extra=('-split', str(split)) if split else (), tag=name) + results[(name, split)] = v + if v > worst[0]: + worst = (v, f'{name}, split {split}') + print(f'measured {name}: unsplit {results[(name, 0)]:.2f}, worst with a split ' + f'{max(results[(name, s)] for s in range(1, 16)):.2f}') + if results: + print(f'measured worst: {worst[0]:.2f} executed instructions/sample ({worst[1]}); {len(results)} cases') + + # stress + n = 44100 * 2 + 44100 * 2 + frames = 16 + blocks = n // frames + rnd = random.Random(9) + stems = [ + [round(0.9 * Q * (rnd.random() * 2 - 1) * math.exp(-(i % 11025) / 1500)) if i < 88200 else 0 for i in range(n)], + [(Q - 1 if (i // 110) % 2 else -Q) if i < 88200 else 0 for i in range(n)], + [round(0.9 * Q * math.sin(2 * math.pi * (20 * (1000 ** (i / 88200))) * i / 44100)) if i < 88200 else 0 + for i in range(n)], + [round(Q * (rnd.random() * 2 - 1)) if i < 88200 else 0 for i in range(n)], + [(Q - 1 if i % 4410 == 0 else 0) if i < 88200 else 0 for i in range(n)], + [((Q - 1) if (i // 8820) % 2 else -Q) if i < 88200 else 0 for i in range(n)], + [0] * n, + [round(0.3 * Q * sum(math.sin(2 * math.pi * f * i / 44100) for f in (220, 277.2, 329.6))) + if i < 88200 else 0 for i in range(n)], + ] + ins, pfs = [], [] + for k, stem in enumerate(stems): + p = work / f's{k}.in' + p.write_bytes(struct.pack(f'<{2 * n}i', *[s for v in stem for s in (v, v)])) + ins.append(str(p)) + pf = work / f's{k}.params' + moving(pf, blocks, seed=k + 11, every_slot=True) + pfs += ['-params', '13,127,0,0,0,0,0,0,0,0,0,0', '-paramfile', str(pf)] + cmd = [str(V.DSP_HOST), '-mem', str(mem), '-memB', str(mem), '-init', f"{syms['init']:x}", + '-proc', f"{syms['proc']:x}", '-ctx', '40,41,42', '-ctxB', '40,41,42', '-frames', str(frames), '-blocks', str(blocks), + '-inst', '8', '-core', '0,0,0,0,1,1,1,1', '-split', '1,3,7,8,12,15,0,0', '-stereo', + '-in', ','.join(ins), '-out', str(work / 'stress.out'), *pfs, '-dirty', '0x5a', '-guard'] + r = subprocess.run(cmd, capture_output=True, text=True, timeout=1800) + print(f'stress: dsp_host exit {r.returncode}') + for line in r.stdout.splitlines(): + if re.search(r'meter|guard|clobber|stray|hang|instance \d', line, re.I): + print(' ' + line.strip()) + if r.returncode: + print(r.stdout[-2000:], r.stderr[-2000:]) + + +if __name__ == '__main__': + main() diff --git a/sdk/octatrack/modules/mackity/presentation/thumbnail.svg b/sdk/octatrack/modules/mackity/presentation/thumbnail.svg new file mode 100755 index 0000000000..d2dd952d32 --- /dev/null +++ b/sdk/octatrack/modules/mackity/presentation/thumbnail.svg @@ -0,0 +1,666 @@ + + Mackity — desk input stage + Original illustration of a compact sixteen-channel mixing desk seen from above: a blank panel with the channel numbers along its edge, colour-banded knob columns (gain, aux sends, EQ, pan), mute buttons and long faders on every strip, a master section with a stereo LED meter. Channel 5's gain (TRIM) is turned up, its strip highlighted, and the meter reaches the clip. An illustration, not a photograph, a product drawing or an Octatrack screenshot. + + + + MACKITY + FX1 / FX2 + TRIM → CLIP · v−0.18v⁵ + → PAD + + + + + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 3 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 6 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 7 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 9 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 10 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 11 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 12 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 13 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 14 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 15 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 16 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + CLIP + + + + + + + + + + + + + + + + + diff --git a/sdk/octatrack/modules/mackity/reference.py b/sdk/octatrack/modules/mackity/reference.py new file mode 100755 index 0000000000..58d414e266 --- /dev/null +++ b/sdk/octatrack/modules/mackity/reference.py @@ -0,0 +1,215 @@ +"""MACKITY's two references, imported by verify.py and test_reference.py. + +float_mackity: upstream/MackityProc.cpp in double precision at 44.1 kHz, less +its 32-bit float dither and denormal noise (the Octatrack's path is 24-bit +fixed point, where neither applies). + +Model: mackity.asm instruction by instruction, on 24-bit words and a 56-bit +accumulator, so dsp_host's render must match it to the bit. The constants +here are the ones in the assembly; verify.py checks that they are, and +test_reference.py derives them again from the upstream formulas. +""" +import math + +FS = 44100.0 +Q = 1 << 23 + +# The upstream filter design, MackityProc.cpp lines 18-45, at 44.1 kHz. +IIR_A, IIR_B = 0.001860867, 0.000287496 +FC, Q_A, Q_B = 19160.0, 0.431684981684982, 1.1582298 +CURVE = 0.1768 + + +def biquad(fc, q): + k = math.tan(math.pi * fc / FS) + norm = 1.0 / (1.0 + k / q + k * k) + b0 = k * k * norm + return b0, 2.0 * b0, b0, 2.0 * (k * k - 1.0) * norm, (1.0 - k / q + k * k) * norm + + +def q23(v): + return round(v * Q) + + +def halved(fc, q): + """The assembly's biquad words: b0, b1, b2, -a1, -a2, each halved, in Q23.""" + b0, b1, b2, a1, a2 = biquad(fc, q) + return tuple(q23(c / 2) for c in (b0, b1, b2, -a1, -a2)) + + +BQ_A = halved(FC, Q_A) +BQ_B = halved(FC, Q_B) +K1, K2 = q23(IIR_A), q23(IIR_B) +KQ = q23(CURVE / 4) +TRIMC = round(65536 * 16384 / 169) # kn^2 * TRIMC = (k/13)^2 / 128 +CONSTANTS = {"K1": K1, "K2": K2, "KQ": KQ, "TRIMC": TRIMC, + **{f"A{i}": w for i, w in enumerate(BQ_A)}, **{f"B{i}": w for i, w in enumerate(BQ_B)}} + + +def trim_a(knob): + """The original's In Trim A for a TRIM knob: (10 A)^2 = (knob/13)^2.""" + return knob / 130.0 + + +def pad_b(knob): + return 1.0 if knob >= 127 else knob / 128.0 + + +def float_mackity(left, right, a, b): + """Upstream's sample loop on floats in [-1, 1); returns two float lists.""" + in_trim = (a * 10.0) ** 2 + ba, bb = biquad(FC, Q_A), biquad(FC, Q_B) + out = [] + for ch in (left, right): + ia = ib = 0.0 + sa = [0.0] * 4 + sb = [0.0] * 4 + y = [] + for x in ch: + ia = ia * (1.0 - IIR_A) + x * IIR_A + x -= ia + x *= in_trim + o = ba[0] * x + ba[1] * sa[0] + ba[2] * sa[1] - ba[3] * sa[2] - ba[4] * sa[3] + sa = [x, sa[0], o, sa[2]] + x = max(-1.0, min(1.0, o)) + x -= x ** 5 * CURVE + o = bb[0] * x + bb[1] * sb[0] + bb[2] * sb[1] - bb[3] * sb[2] - bb[4] * sb[3] + sb = [x, sb[0], o, sb[2]] + x = o + ib = ib * (1.0 - IIR_B) + x * IIR_B + x -= ib + y.append(x * b) + out.append(y) + return out + + +# ---- the fixed-point model ------------------------------------------------- + +def s24(v): + v &= 0xffffff + return v - (1 << 24) if v & 0x800000 else v + + +def w56(a): + a &= (1 << 56) - 1 + return a - (1 << 56) if a >> 55 else a + + +def lim(a): + """move a,x0 / move a,x:(..): the limiter.""" + return max(-0x800000, min(0x7fffff, a >> 24)) + + +def hi(a): + """move a1,x0: the middle word, unlimited.""" + return s24(a >> 24) + + +def ld(x): + return x << 24 + + +def mac(a, x, y): + return w56(a + 2 * x * y) + + +def biquad_fx(x, s, c): + """Direct form 1 at quarter scale, halved coefficients; s = [x1, x2, y1, y2].""" + a = 0 + for v, k in zip((x, s[0], s[1], s[2], s[3]), c): + a = mac(a, v, k) + a = w56(a << 1) + s[1], s[0], s[3] = s[0], x, s[2] + return a + + +class Model: + """One instance of mackity.asm. call(frames, knobs) runs one proc.""" + + def __init__(self): + self.x = [0] * 32 # X:(r7+$00..$1f), as init leaves it + + def knobs(self, trim_word, pad_word): + kn = trim_word & 0x7fffff + t = lim(mac(0, lim(mac(0, kn, kn)), TRIMC)) + pn = pad_word & 0x7fffff + b = ld(pn) >> 1 + if pn >= 0x7f0000: + b = ld(0x400000) + return t, hi(b) + + def call(self, frames, trim_word, pad_word): + x = self.x + x[0x18], x[0x1b] = self.knobs(trim_word, pad_word) + if x[0x1e] == 0: + x[0x19], x[0x1c], x[0x1e] = x[0x18], x[0x1b], 1 + for t, r in ((0x18, 0x19), (0x1b, 0x1c)): + if abs(ld(x[t]) - ld(x[r])) < ld(64): + x[r] = x[t] + out = [] + for left, right in frames: + for t, r in ((0x18, 0x19), (0x1b, 0x1c)): + x[r] = hi(((ld(x[t]) - ld(x[r])) >> 6) + ld(x[r])) + out.append((self.channel(0x00, left), self.channel(0x0c, right))) + return out + + def channel(self, base, sample): + x = self.x + s = x[base:base + 12] + # high-pass in + h = hi(ld(sample) >> 2) + b = ld(s[0]) + s[1] + d = lim(ld(h) - ld(s[0])) + b = mac(b, d, K1) + s[0], s[1] = hi(b), b & 0xffffff + y = lim(ld(h) - ld(s[0])) + # biquad A + st = s[2:6] + a = biquad_fx(y, st, BQ_A) + st[2] = lim(a) + s[2:6] = st + # trim and clip + w = lim(w56(a << 1)) + c = lim(w56(mac(0, w, x[0x19]) << 8)) + # the curve + c2 = lim(mac(0, c, c)) + c4 = lim(mac(0, c2, c2)) + t = lim(mac(0, c4, KQ)) + b = mac(0, t, c) + p = lim((ld(c) >> 2) - b) + # biquad B + st = s[6:10] + a = biquad_fx(p, st, BQ_B) + u = lim(a) + st[2] = u + s[6:10] = st + # high-pass out + b = ld(s[10]) + s[11] + d = lim(ld(u) - ld(s[10])) + b = mac(b, d, K2) + s[10], s[11] = hi(b), b & 0xffffff + y = lim(ld(u) - ld(s[10])) + out = lim(w56(mac(0, y, x[0x1c]) << 3)) + x[base:base + 12] = s + return out + + +def render(left, right, knob_rows, frames=16, split=0, pwords=None): + """dsp_host's schedule in the model: blocks of `frames`, a knob row per + block (block -> (trim, pad)), and a split call first when split > 0. + pwords: slot -> companion bits 8-15 added to that knob word every call.""" + m = Model() + out_l, out_r = [], [] + cur = knob_rows.get(0, (13, 127)) + pw = pwords or {} + for blk in range((len(left) + frames - 1) // frames): + cur = knob_rows.get(blk, cur) + words = ((cur[0] << 16) | pw.get(0, 0), (cur[1] << 16) | pw.get(1, 0)) + lo = blk * frames + fr = list(zip(left[lo:lo + frames], right[lo:lo + frames])) + parts = [fr[:split], fr[split:]] if split else [fr] + for part in parts: + for l, r in m.call(part, *words): + out_l.append(l) + out_r.append(r) + return out_l, out_r, m diff --git a/sdk/octatrack/modules/mackity/test_reference.py b/sdk/octatrack/modules/mackity/test_reference.py new file mode 100755 index 0000000000..c65ee39e6d --- /dev/null +++ b/sdk/octatrack/modules/mackity/test_reference.py @@ -0,0 +1,88 @@ +"""MACKITY host test: the fixed-point model against upstream's algorithm. + + python3 -B test_reference.py (no tools, no firmware) + +What it proves: the model (reference.Model, which verify.py holds the +assembly to, bit for bit) computes Mackity: the double precision original's +level within 0.001 dB and everything else under -100 dB, with the +original's output limited at full scale where it goes over (a 24-bit +output cannot); the defaults +are exact; silence after a burst ends in exact silence. What it cannot see: +the assembly itself (verify.py), the unit, the sound. +""" +import math +import pathlib +import random +import re +import sys +import unittest + +HERE = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import reference as R # noqa: E402 + +Q = R.Q + + +def tone(f, amp, n): + return [round(amp * Q * math.sin(2 * math.pi * f * i / R.FS)) for i in range(n)] + + +def error_db(fixed, ref, skip=4410): + """(gain error in dB, residual after that gain in dB to the signal), the + original limited at full scale. The gain word's resolution at low TRIM + (0.0006 dB at TRIM 5) is a level, not noise: it is measured apart.""" + ref = [max(-1.0, min(1.0 - 1 / Q, v)) for v in ref] + fx = [v / Q for v in fixed] + s = sum(v * v for v in ref[skip:]) + g = sum(fx[i] * ref[i] for i in range(skip, len(ref))) / s + e = sum((fx[i] - g * ref[i]) ** 2 for i in range(skip, len(ref))) + return 20 * math.log10(g), 10 * math.log10(max(e, 1e-30) / s) + + +class Mackity(unittest.TestCase): + def test_constants_match_upstream_formulas(self): + """The words in mackity.asm are upstream's coefficients, halved, in Q23.""" + asm = (HERE / "mackity.asm").read_text() + chan = asm.split("\nmack_chan:")[1] + words = [int(w, 16) for w in re.findall(r"#>\$([0-9a-f]{6}),y1", chan)] + bq = [w & 0xffffff for w in (*R.BQ_A, *R.BQ_B)] + expect = [R.K1, *bq[:5], R.KQ, *bq[5:], R.K2] + self.assertEqual(words, expect) + self.assertIn(f"#>${R.TRIMC:06x},y1", asm) + + def test_matches_the_original(self): + for trim, pad, f, amp in ((13, 127, 1000, 0.5), (13, 127, 100, 0.9), (40, 127, 440, 0.5), + (127, 127, 440, 0.5), (127, 127, 9100, 0.89), (5, 127, 1000, 0.9), + (64, 100, 5300, 0.25), (0, 127, 1000, 0.5), (13, 0, 1000, 0.5)): + with self.subTest(trim=trim, pad=pad, hz=f, amp=amp): + x = tone(f, amp, 22050) + out, _, _ = R.render(x, x, {0: (trim, pad)}) + ref, _ = R.float_mackity([v / Q for v in x], [0.0], R.trim_a(trim), R.pad_b(pad)) + if not any(ref[4410:]): + self.assertFalse(any(out[4410:])) + continue + gain, residual = error_db(out, ref) + self.assertLess(abs(gain), 0.001) + self.assertLess(residual, -100) + + def test_defaults_are_exact(self): + m = R.Model() + self.assertEqual(m.knobs(13 << 16, 127 << 16), (0x010000, 0x400000)) # gain 1/128, pad 1/2 + + def test_tail_ends_in_silence(self): + rnd = random.Random(3) + burst = [round(0.5 * Q * (rnd.random() * 2 - 1)) if i < 4410 else 0 for i in range(44100 * 3)] + for trim in (13, 127): + with self.subTest(trim=trim): + out, _, _ = R.render(burst, burst, {0: (trim, 127)}) + self.assertFalse(any(out[-44100:])) + + def test_glide_settles_exactly(self): + x = tone(1000, 0.25, 4096) + _, _, m = R.render(x, x, {0: (127, 0), 8: (13, 127)}) + self.assertEqual((m.x[0x19], m.x[0x1c]), (m.x[0x18], m.x[0x1b])) + + +if __name__ == "__main__": + unittest.main() diff --git a/sdk/octatrack/modules/mackity/upstream/LICENSE b/sdk/octatrack/modules/mackity/upstream/LICENSE new file mode 100644 index 0000000000..e8feef9bdb --- /dev/null +++ b/sdk/octatrack/modules/mackity/upstream/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Chris Johnson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/sdk/octatrack/modules/mackity/upstream/Mackity.cpp b/sdk/octatrack/modules/mackity/upstream/Mackity.cpp new file mode 100644 index 0000000000..1354eafe5d --- /dev/null +++ b/sdk/octatrack/modules/mackity/upstream/Mackity.cpp @@ -0,0 +1,134 @@ +/* ======================================== + * Mackity - Mackity.h + * Copyright (c) 2016 airwindows, Airwindows uses the MIT license + * ======================================== */ + +#ifndef __Mackity_H +#include "Mackity.h" +#endif + +AudioEffect* createEffectInstance(audioMasterCallback audioMaster) {return new Mackity(audioMaster);} + +Mackity::Mackity(audioMasterCallback audioMaster) : + AudioEffectX(audioMaster, kNumPrograms, kNumParameters) +{ + A = 0.1; + B = 1.0; + + iirSampleAL = 0.0; + iirSampleBL = 0.0; + iirSampleAR = 0.0; + iirSampleBR = 0.0; + for (int x = 0; x < 15; x++) {biquadA[x] = 0.0; biquadB[x] = 0.0;} + + fpdL = 1.0; while (fpdL < 16386) fpdL = rand()*UINT32_MAX; + fpdR = 1.0; while (fpdR < 16386) fpdR = rand()*UINT32_MAX; + //this is reset: values being initialized only once. Startup values, whatever they are. + + _canDo.insert("plugAsChannelInsert"); // plug-in can be used as a channel insert effect. + _canDo.insert("plugAsSend"); // plug-in can be used as a send effect. + _canDo.insert("x2in2out"); + setNumInputs(kNumInputs); + setNumOutputs(kNumOutputs); + setUniqueID(kUniqueId); + canProcessReplacing(); // supports output replacing + canDoubleReplacing(); // supports double precision processing + programsAreChunks(true); + vst_strncpy (_programName, "Default", kVstMaxProgNameLen); // default program name +} + +Mackity::~Mackity() {} +VstInt32 Mackity::getVendorVersion () {return 1000;} +void Mackity::setProgramName(char *name) {vst_strncpy (_programName, name, kVstMaxProgNameLen);} +void Mackity::getProgramName(char *name) {vst_strncpy (name, _programName, kVstMaxProgNameLen);} +//airwindows likes to ignore this stuff. Make your own programs, and make a different plugin rather than +//trying to do versioning and preventing people from using older versions. Maybe they like the old one! + +static float pinParameter(float data) +{ + if (data < 0.0f) return 0.0f; + if (data > 1.0f) return 1.0f; + return data; +} + +VstInt32 Mackity::getChunk (void** data, bool isPreset) +{ + float *chunkData = (float *)calloc(kNumParameters, sizeof(float)); + chunkData[0] = A; + chunkData[1] = B; + /* Note: The way this is set up, it will break if you manage to save settings on an Intel + machine and load them on a PPC Mac. However, it's fine if you stick to the machine you + started with. */ + + *data = chunkData; + return kNumParameters * sizeof(float); +} + +VstInt32 Mackity::setChunk (void* data, VstInt32 byteSize, bool isPreset) +{ + float *chunkData = (float *)data; + A = pinParameter(chunkData[0]); + B = pinParameter(chunkData[1]); + /* We're ignoring byteSize as we found it to be a filthy liar */ + + /* calculate any other fields you need here - you could copy in + code from setParameter() here. */ + return 0; +} + +void Mackity::setParameter(VstInt32 index, float value) { + switch (index) { + case kParamA: A = value; break; + case kParamB: B = value; break; + default: throw; // unknown parameter, shouldn't happen! + } +} + +float Mackity::getParameter(VstInt32 index) { + switch (index) { + case kParamA: return A; break; + case kParamB: return B; break; + default: break; // unknown parameter, shouldn't happen! + } return 0.0; //we only need to update the relevant name, this is simple to manage +} + +void Mackity::getParameterName(VstInt32 index, char *text) { + switch (index) { + case kParamA: vst_strncpy (text, "In Trim", kVstMaxParamStrLen); break; + case kParamB: vst_strncpy (text, "Out Pad", kVstMaxParamStrLen); break; + default: break; // unknown parameter, shouldn't happen! + } //this is our labels for displaying in the VST host +} + +void Mackity::getParameterDisplay(VstInt32 index, char *text) { + switch (index) { + case kParamA: float2string (A, text, kVstMaxParamStrLen); break; + case kParamB: float2string (B, text, kVstMaxParamStrLen); break; + default: break; // unknown parameter, shouldn't happen! + } //this displays the values and handles 'popups' where it's discrete choices +} + +void Mackity::getParameterLabel(VstInt32 index, char *text) { + switch (index) { + case kParamA: vst_strncpy (text, "", kVstMaxParamStrLen); break; + case kParamB: vst_strncpy (text, "", kVstMaxParamStrLen); break; + default: break; // unknown parameter, shouldn't happen! + } +} + +VstInt32 Mackity::canDo(char *text) +{ return (_canDo.find(text) == _canDo.end()) ? -1: 1; } // 1 = yes, -1 = no, 0 = don't know + +bool Mackity::getEffectName(char* name) { + vst_strncpy(name, "Mackity", kVstMaxProductStrLen); return true; +} + +VstPlugCategory Mackity::getPlugCategory() {return kPlugCategEffect;} + +bool Mackity::getProductString(char* text) { + vst_strncpy (text, "airwindows Mackity", kVstMaxProductStrLen); return true; +} + +bool Mackity::getVendorString(char* text) { + vst_strncpy (text, "airwindows", kVstMaxVendorStrLen); return true; +} diff --git a/sdk/octatrack/modules/mackity/upstream/Mackity.h b/sdk/octatrack/modules/mackity/upstream/Mackity.h new file mode 100644 index 0000000000..856be80c47 --- /dev/null +++ b/sdk/octatrack/modules/mackity/upstream/Mackity.h @@ -0,0 +1,72 @@ +/* ======================================== + * Mackity - Mackity.h + * Created 8/12/11 by SPIAdmin + * Copyright (c) 2011 __MyCompanyName__, Airwindows uses the MIT license + * ======================================== */ + +#ifndef __Mackity_H +#define __Mackity_H + +#ifndef __audioeffect__ +#include "audioeffectx.h" +#endif + +#include +#include +#include + +enum { + kParamA = 0, + kParamB = 1, + kNumParameters = 2 +}; // + +const int kNumPrograms = 0; +const int kNumInputs = 2; +const int kNumOutputs = 2; +const unsigned long kUniqueId = 'mkty'; //Change this to what the AU identity is! + +class Mackity : + public AudioEffectX +{ +public: + Mackity(audioMasterCallback audioMaster); + ~Mackity(); + virtual bool getEffectName(char* name); // The plug-in name + virtual VstPlugCategory getPlugCategory(); // The general category for the plug-in + virtual bool getProductString(char* text); // This is a unique plug-in string provided by Steinberg + virtual bool getVendorString(char* text); // Vendor info + virtual VstInt32 getVendorVersion(); // Version number + virtual void processReplacing (float** inputs, float** outputs, VstInt32 sampleFrames); + virtual void processDoubleReplacing (double** inputs, double** outputs, VstInt32 sampleFrames); + virtual void getProgramName(char *name); // read the name from the host + virtual void setProgramName(char *name); // changes the name of the preset displayed in the host + virtual VstInt32 getChunk (void** data, bool isPreset); + virtual VstInt32 setChunk (void* data, VstInt32 byteSize, bool isPreset); + virtual float getParameter(VstInt32 index); // get the parameter value at the specified index + virtual void setParameter(VstInt32 index, float value); // set the parameter at index to value + virtual void getParameterLabel(VstInt32 index, char *text); // label for the parameter (eg dB) + virtual void getParameterName(VstInt32 index, char *text); // name of the parameter + virtual void getParameterDisplay(VstInt32 index, char *text); // text description of the current value + virtual VstInt32 canDo(char *text); +private: + char _programName[kVstMaxProgNameLen + 1]; + std::set< std::string > _canDo; + + + double iirSampleAL; + double iirSampleBL; + double iirSampleAR; + double iirSampleBR; + double biquadA[15]; + double biquadB[15]; + + uint32_t fpdL; + uint32_t fpdR; + //default stuff + + float A; + float B; +}; + +#endif diff --git a/sdk/octatrack/modules/mackity/upstream/MackityProc.cpp b/sdk/octatrack/modules/mackity/upstream/MackityProc.cpp new file mode 100644 index 0000000000..1d148b30af --- /dev/null +++ b/sdk/octatrack/modules/mackity/upstream/MackityProc.cpp @@ -0,0 +1,210 @@ +/* ======================================== + * Mackity - Mackity.h + * Copyright (c) 2016 airwindows, Airwindows uses the MIT license + * ======================================== */ + +#ifndef __Mackity_H +#include "Mackity.h" +#endif + +void Mackity::processReplacing(float **inputs, float **outputs, VstInt32 sampleFrames) +{ + float* in1 = inputs[0]; + float* in2 = inputs[1]; + float* out1 = outputs[0]; + float* out2 = outputs[1]; + + double overallscale = 1.0; + overallscale /= 44100.0; + overallscale *= getSampleRate(); + + double inTrim = A*10.0; + double outPad = B; + inTrim *= inTrim; + + double iirAmountA = 0.001860867/overallscale; + double iirAmountB = 0.000287496/overallscale; + + biquadB[0] = biquadA[0] = 19160.0 / getSampleRate(); + biquadA[1] = 0.431684981684982; + biquadB[1] = 1.1582298; + + double K = tan(M_PI * biquadA[0]); //lowpass + double norm = 1.0 / (1.0 + K / biquadA[1] + K * K); + biquadA[2] = K * K * norm; + biquadA[3] = 2.0 * biquadA[2]; + biquadA[4] = biquadA[2]; + biquadA[5] = 2.0 * (K * K - 1.0) * norm; + biquadA[6] = (1.0 - K / biquadA[1] + K * K) * norm; + + K = tan(M_PI * biquadB[0]); + norm = 1.0 / (1.0 + K / biquadB[1] + K * K); + biquadB[2] = K * K * norm; + biquadB[3] = 2.0 * biquadB[2]; + biquadB[4] = biquadB[2]; + biquadB[5] = 2.0 * (K * K - 1.0) * norm; + biquadB[6] = (1.0 - K / biquadB[1] + K * K) * norm; + + while (--sampleFrames >= 0) + { + double inputSampleL = *in1; + double inputSampleR = *in2; + if (fabs(inputSampleL)<1.18e-23) inputSampleL = fpdL * 1.18e-17; + if (fabs(inputSampleR)<1.18e-23) inputSampleR = fpdR * 1.18e-17; + + if (fabs(iirSampleAL)<1.18e-37) iirSampleAL = 0.0; + iirSampleAL = (iirSampleAL * (1.0 - iirAmountA)) + (inputSampleL * iirAmountA); + inputSampleL -= iirSampleAL; + if (fabs(iirSampleAR)<1.18e-37) iirSampleAR = 0.0; + iirSampleAR = (iirSampleAR * (1.0 - iirAmountA)) + (inputSampleR * iirAmountA); + inputSampleR -= iirSampleAR; + + if (inTrim != 1.0) {inputSampleL *= inTrim; inputSampleR *= inTrim;} + + double outSampleL = biquadA[2]*inputSampleL+biquadA[3]*biquadA[7]+biquadA[4]*biquadA[8]-biquadA[5]*biquadA[9]-biquadA[6]*biquadA[10]; + biquadA[8] = biquadA[7]; biquadA[7] = inputSampleL; inputSampleL = outSampleL; biquadA[10] = biquadA[9]; biquadA[9] = inputSampleL; //DF1 left + + double outSampleR = biquadA[2]*inputSampleR+biquadA[3]*biquadA[11]+biquadA[4]*biquadA[12]-biquadA[5]*biquadA[13]-biquadA[6]*biquadA[14]; + biquadA[12] = biquadA[11]; biquadA[11] = inputSampleR; inputSampleR = outSampleR; biquadA[14] = biquadA[13]; biquadA[13] = inputSampleR; //DF1 right + + if (inputSampleL > 1.0) inputSampleL = 1.0; + if (inputSampleL < -1.0) inputSampleL = -1.0; + inputSampleL -= pow(inputSampleL,5)*0.1768; + if (inputSampleR > 1.0) inputSampleR = 1.0; + if (inputSampleR < -1.0) inputSampleR = -1.0; + inputSampleR -= pow(inputSampleR,5)*0.1768; + + outSampleL = biquadB[2]*inputSampleL+biquadB[3]*biquadB[7]+biquadB[4]*biquadB[8]-biquadB[5]*biquadB[9]-biquadB[6]*biquadB[10]; + biquadB[8] = biquadB[7]; biquadB[7] = inputSampleL; inputSampleL = outSampleL; biquadB[10] = biquadB[9]; biquadB[9] = inputSampleL; //DF1 left + + outSampleR = biquadB[2]*inputSampleR+biquadB[3]*biquadB[11]+biquadB[4]*biquadB[12]-biquadB[5]*biquadB[13]-biquadB[6]*biquadB[14]; + biquadB[12] = biquadB[11]; biquadB[11] = inputSampleR; inputSampleR = outSampleR; biquadB[14] = biquadB[13]; biquadB[13] = inputSampleR; //DF1 right + + if (fabs(iirSampleBL)<1.18e-37) iirSampleBL = 0.0; + iirSampleBL = (iirSampleBL * (1.0 - iirAmountB)) + (inputSampleL * iirAmountB); + inputSampleL -= iirSampleBL; + if (fabs(iirSampleBR)<1.18e-37) iirSampleBR = 0.0; + iirSampleBR = (iirSampleBR * (1.0 - iirAmountB)) + (inputSampleR * iirAmountB); + inputSampleR -= iirSampleBR; + + if (outPad != 1.0) {inputSampleL *= outPad; inputSampleR *= outPad;} + + //begin 32 bit stereo floating point dither + int expon; frexpf((float)inputSampleL, &expon); + fpdL ^= fpdL << 13; fpdL ^= fpdL >> 17; fpdL ^= fpdL << 5; + inputSampleL += ((double(fpdL)-uint32_t(0x7fffffff)) * 5.5e-36l * pow(2,expon+62)); + frexpf((float)inputSampleR, &expon); + fpdR ^= fpdR << 13; fpdR ^= fpdR >> 17; fpdR ^= fpdR << 5; + inputSampleR += ((double(fpdR)-uint32_t(0x7fffffff)) * 5.5e-36l * pow(2,expon+62)); + //end 32 bit stereo floating point dither + + *out1 = inputSampleL; + *out2 = inputSampleR; + + *in1++; + *in2++; + *out1++; + *out2++; + } +} + +void Mackity::processDoubleReplacing(double **inputs, double **outputs, VstInt32 sampleFrames) +{ + double* in1 = inputs[0]; + double* in2 = inputs[1]; + double* out1 = outputs[0]; + double* out2 = outputs[1]; + + double overallscale = 1.0; + overallscale /= 44100.0; + overallscale *= getSampleRate(); + + double inTrim = A*10.0; + double outPad = B; + inTrim *= inTrim; + + double iirAmountA = 0.001860867/overallscale; + double iirAmountB = 0.000287496/overallscale; + + biquadB[0] = biquadA[0] = 19160.0 / getSampleRate(); + biquadA[1] = 0.431684981684982; + biquadB[1] = 1.1582298; + + double K = tan(M_PI * biquadA[0]); //lowpass + double norm = 1.0 / (1.0 + K / biquadA[1] + K * K); + biquadA[2] = K * K * norm; + biquadA[3] = 2.0 * biquadA[2]; + biquadA[4] = biquadA[2]; + biquadA[5] = 2.0 * (K * K - 1.0) * norm; + biquadA[6] = (1.0 - K / biquadA[1] + K * K) * norm; + + K = tan(M_PI * biquadB[0]); + norm = 1.0 / (1.0 + K / biquadB[1] + K * K); + biquadB[2] = K * K * norm; + biquadB[3] = 2.0 * biquadB[2]; + biquadB[4] = biquadB[2]; + biquadB[5] = 2.0 * (K * K - 1.0) * norm; + biquadB[6] = (1.0 - K / biquadB[1] + K * K) * norm; + + while (--sampleFrames >= 0) + { + double inputSampleL = *in1; + double inputSampleR = *in2; + if (fabs(inputSampleL)<1.18e-23) inputSampleL = fpdL * 1.18e-17; + if (fabs(inputSampleR)<1.18e-23) inputSampleR = fpdR * 1.18e-17; + + if (fabs(iirSampleAL)<1.18e-37) iirSampleAL = 0.0; + iirSampleAL = (iirSampleAL * (1.0 - iirAmountA)) + (inputSampleL * iirAmountA); + inputSampleL -= iirSampleAL; + if (fabs(iirSampleAR)<1.18e-37) iirSampleAR = 0.0; + iirSampleAR = (iirSampleAR * (1.0 - iirAmountA)) + (inputSampleR * iirAmountA); + inputSampleR -= iirSampleAR; + + if (inTrim != 1.0) {inputSampleL *= inTrim; inputSampleR *= inTrim;} + + double outSampleL = biquadA[2]*inputSampleL+biquadA[3]*biquadA[7]+biquadA[4]*biquadA[8]-biquadA[5]*biquadA[9]-biquadA[6]*biquadA[10]; + biquadA[8] = biquadA[7]; biquadA[7] = inputSampleL; inputSampleL = outSampleL; biquadA[10] = biquadA[9]; biquadA[9] = inputSampleL; //DF1 left + + double outSampleR = biquadA[2]*inputSampleR+biquadA[3]*biquadA[11]+biquadA[4]*biquadA[12]-biquadA[5]*biquadA[13]-biquadA[6]*biquadA[14]; + biquadA[12] = biquadA[11]; biquadA[11] = inputSampleR; inputSampleR = outSampleR; biquadA[14] = biquadA[13]; biquadA[13] = inputSampleR; //DF1 right + + if (inputSampleL > 1.0) inputSampleL = 1.0; + if (inputSampleL < -1.0) inputSampleL = -1.0; + inputSampleL -= pow(inputSampleL,5)*0.1768; + if (inputSampleR > 1.0) inputSampleR = 1.0; + if (inputSampleR < -1.0) inputSampleR = -1.0; + inputSampleR -= pow(inputSampleR,5)*0.1768; + + outSampleL = biquadB[2]*inputSampleL+biquadB[3]*biquadB[7]+biquadB[4]*biquadB[8]-biquadB[5]*biquadB[9]-biquadB[6]*biquadB[10]; + biquadB[8] = biquadB[7]; biquadB[7] = inputSampleL; inputSampleL = outSampleL; biquadB[10] = biquadB[9]; biquadB[9] = inputSampleL; //DF1 left + + outSampleR = biquadB[2]*inputSampleR+biquadB[3]*biquadB[11]+biquadB[4]*biquadB[12]-biquadB[5]*biquadB[13]-biquadB[6]*biquadB[14]; + biquadB[12] = biquadB[11]; biquadB[11] = inputSampleR; inputSampleR = outSampleR; biquadB[14] = biquadB[13]; biquadB[13] = inputSampleR; //DF1 right + + if (fabs(iirSampleBL)<1.18e-37) iirSampleBL = 0.0; + iirSampleBL = (iirSampleBL * (1.0 - iirAmountB)) + (inputSampleL * iirAmountB); + inputSampleL -= iirSampleBL; + if (fabs(iirSampleBR)<1.18e-37) iirSampleBR = 0.0; + iirSampleBR = (iirSampleBR * (1.0 - iirAmountB)) + (inputSampleR * iirAmountB); + inputSampleR -= iirSampleBR; + + if (outPad != 1.0) {inputSampleL *= outPad; inputSampleR *= outPad;} + + //begin 64 bit stereo floating point dither + //int expon; frexp((double)inputSampleL, &expon); + fpdL ^= fpdL << 13; fpdL ^= fpdL >> 17; fpdL ^= fpdL << 5; + //inputSampleL += ((double(fpdL)-uint32_t(0x7fffffff)) * 1.1e-44l * pow(2,expon+62)); + //frexp((double)inputSampleR, &expon); + fpdR ^= fpdR << 13; fpdR ^= fpdR >> 17; fpdR ^= fpdR << 5; + //inputSampleR += ((double(fpdR)-uint32_t(0x7fffffff)) * 1.1e-44l * pow(2,expon+62)); + //end 64 bit stereo floating point dither + + *out1 = inputSampleL; + *out2 = inputSampleR; + + *in1++; + *in2++; + *out1++; + *out2++; + } +} diff --git a/sdk/octatrack/modules/mackity/verify.py b/sdk/octatrack/modules/mackity/verify.py new file mode 100644 index 0000000000..4f63ac48d7 --- /dev/null +++ b/sdk/octatrack/modules/mackity/verify.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""MACKITY's render gate: the assembled module, run in dsp_host. + + python3 verify.py (from anywhere; needs a built vendor tree) + +No firmware is read. mackity.asm is assembled with dsp_asm at P:0x2000 and +run from a synthetic memory image, as Resonator's gate does. Knobs arrive +as value<<16. What this cannot see: the composed image, the real +dispatcher, the panel and the sound on a unit. + +Gates: + 1. Every instruction decodes as the mnemonic written: every product is + the signed mpy/mac x0,y1 form (no mpysu/macsu), there is no rep, and + the state stays inside X:(r7+$00..$1f). + 2. Bit for bit the model in reference.py (which test_reference.py holds + to upstream's algorithm): stereo noise at the defaults, a loud tone at + TRIM 127, knob automation over both knobs' ranges, a 5-frame trig split + every block, a TRIM word carrying an LFO's fraction bits, garbage in + the state block before init, and two instances with their own knobs. + 3. Silence in is exact silence out at any setting; a burst's tail ends in + exact silence. + 4. The cycle meter, printed for TESTING.md and evidence/performance.json. +""" +import math +import os +import pathlib +import random +import re +import struct +import subprocess +import sys +import tempfile + +HERE = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import reference as R # noqa: E402 + +Q = R.Q +ORG = 0x2000 +failures = [] + + +def _tool(name, sub): + env = os.environ.get(name.upper()) + if env: + return pathlib.Path(env) + roots = [HERE, *HERE.parents, pathlib.Path.home() / ".cache/modwerk-upstream"] + for base in roots: + for root in (base, base / "sdk" / "octabam", base / "octabam"): + p = root / "vendor/dsp56300/build/source" / sub + if p.exists(): + return p + sys.exit(f"[FAIL] {sub} not found: npm run upstream:tools, then make setup in that octabam checkout, " + f"or set {name.upper()}") + + +DSP_ASM = _tool("dsp_asm", "dsp_host/dsp_asm") +DSP_HOST = _tool("dsp_host", "dsp_host/dsp_host") +DISASM = _tool("dsp_disasm", "disassemble/dsp56kDisassemble") + + +def gate(name, ok, detail=""): + print(f"[{'PASS' if ok else 'FAIL'}] {name} {detail}".rstrip(), flush=True) + if not ok: + failures.append(name) + + +def assemble(work): + asm, blob, sym = work / "m.asm", work / "m.bin", work / "m.sym" + asm.write_text((HERE / "mackity.asm").read_text()) + r = subprocess.run([str(DSP_ASM), "-in", str(asm), "-org", f"{ORG:x}", "-out", str(blob), "-sym", str(sym)], + capture_output=True, text=True) + if r.returncode: + sys.exit(f"[FAIL] dsp_asm: {r.stdout}{r.stderr}") + syms = {k: int(v, 16) for k, v in (l.split() for l in sym.read_text().splitlines() if l.strip())} + return blob, syms + + +def disassemble(blob): + r = subprocess.run([str(DISASM), "-in", str(blob), "-pc", f"{ORG:x}", "-le"], capture_output=True, text=True) + return [l for l in r.stdout.splitlines() if re.match(r"^[0-9a-f]{6}:", l)] + + +def rec(sp, addr, words): + return struct.pack(" knobs from that block on (-paramfile). split: frames before a trig split, + this instance only. core: 0, or 1 to run it on the second core.""" + left: Sequence[int] + right: Sequence[int] = None + knobs: Sequence[int] = () + rows: Mapping[int, Sequence[int]] = None + split: int = None + core: int = 0 + + +@dataclasses.dataclass +class Render: + outputs: list # [(left, right)] per instance, 24-bit signed, as long as the longest input + meters: dict # core -> executed instructions a sample, the worst block + means: dict # core -> the same, the mean block + layout: list # [(core, position)] per instance + per_instance: list # executed instructions a sample, per instance + nonzero: list # non-zero output samples, per instance + stray: list # stray write regions per instance (-guard) + clobbers: list # writes over a loaded module per instance (-guard) + returncode: int + stdout: str + command: list + + @property + def meter(self): + return max(self.meters.values()) if self.meters else None + + def harness_word(self, k): + """Whether instance k is the one dsp_host itself writes a word a block into (eight instances).""" + return len(self.layout) == 8 and self.layout[k] == HARNESS_WORD + + +def knob_row(knobs): + row = list(knobs)[:SLOTS] + return row + [0] * (SLOTS - len(row)) + + +def s24(values): + return [((v & 0xffffff) ^ 0x800000) - 0x800000 for v in values] + + +def _pwords(spec): + if spec is None or isinstance(spec, str): + return spec + return ",".join(f"{inst}:{slot:x}={word & 0xffffff:x}" for inst, slot, word in spec) + + +def run(asm, instances, *, image=None, image_b=None, frames=FRAMES, ctx=CTX, ctx_b=None, split=None, + pwords=None, dirty=None, guard=False, extra=(), tag="r", timeout=900, check=True): + """Render `instances` (Instance, or (left, right, knobs) tuples) through `asm` in one dsp_host run. + + image: the -mem file (default asm.image()); image_b and ctx_b: core 1's, when an instance runs there + (default: the same). split: frames before a trig split, every instance (an Instance's own split wins). + pwords: "inst:slot=word,..." or [(inst, slot, word)], whole 24-bit knob words (an LFO's fraction bits). + dirty: the word init's state block holds before init. guard: True, or the words to guard. extra: more + dsp_host arguments. check: raise HostError on a non-zero exit (a guard clobber exits 3).""" + insts = [i if isinstance(i, Instance) else Instance(*i) for i in instances] + if not 1 <= len(insts) <= 8: + raise ValueError("dsp_host runs one to eight instances") + work = asm.work + image = image or asm.image() + n = max(len(i.left) for i in insts) + cmd = [str(tool("dsp_host")), "-mem", str(image), "-init", f"{asm.syms['init']:x}", + "-proc", f"{asm.syms['proc']:x}", "-ctx", ",".join(f"{c:x}" for c in ctx), "-frames", str(frames), + "-blocks", str((n + frames - 1) // frames), "-inst", str(len(insts)), "-stereo"] + if any(i.core for i in insts): + cmd += ["-memB", str(image_b or image), "-ctxB", ",".join(f"{c:x}" for c in (ctx_b or ctx)), + "-core", ",".join(str(i.core) for i in insts)] + if any(i.split is not None for i in insts): + cmd += ["-split", ",".join(str((split or 0) if i.split is None else i.split) for i in insts)] + elif split: + cmd += ["-split", str(split)] + ins = [] + for k, inst in enumerate(insts): + left = list(inst.left) + [0] * (n - len(inst.left)) + right = left if inst.right is None else list(inst.right) + [0] * (n - len(inst.right)) + path = work / f"{tag}{k}.in" + path.write_bytes(struct.pack(f"<{2 * n}i", *[s for pair in zip(left, right) for s in pair])) + ins.append(str(path)) + rows = dict(inst.rows or {}) + knobs = inst.knobs if len(inst.knobs) or not rows else rows[min(rows)] + cmd += ["-params", ",".join(map(str, knob_row(knobs)))] + if rows: + pf = work / f"{tag}{k}.params" + pf.write_text("".join(f"{b},{','.join(map(str, knob_row(v)))}\n" for b, v in sorted(rows.items()))) + cmd += ["-paramfile", str(pf)] + out = work / f"{tag}.out" + for k in range(len(insts)): + pathlib.Path(f"{out}.i{k}" if k else out).unlink(missing_ok=True) + cmd += ["-in", ",".join(ins), "-out", str(out)] + if pwords: + cmd += ["-pword", _pwords(pwords)] + if dirty is not None: + cmd += ["-dirty", hex(dirty)] + if guard: + cmd += ["-guard"] + ([] if guard is True else [str(guard)]) + cmd += [str(a) for a in extra] + r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) + if check and r.returncode: + raise HostError(f"dsp_host exit {r.returncode}:\n{r.stdout[-2000:]}{r.stderr}") + outputs = [] + for k in range(len(insts)): + path = pathlib.Path(f"{out}.i{k}" if k else out) + data = path.read_bytes() if path.exists() else b"" + o = s24(struct.unpack(f"<{len(data) // 4}i", data)) + outputs.append((o[0::2][:n], o[1::2][:n])) + return _parse(r.stdout, len(insts), outputs, r.returncode, cmd) + + +def _parse(stdout, count, outputs, returncode, cmd): + meters, means = {}, {} + for m in re.finditer(r"core (\d+) meter: .*?\(([\d.]+)/sample max, ([\d.]+)/sample mean", stdout): + meters[int(m.group(1))], means[int(m.group(1))] = float(m.group(2)), float(m.group(3)) + layout = [None] * count + for m in re.finditer(r"^instance (\d+): core (\d+) pos (\d+)", stdout, re.M): + if int(m.group(1)) < count: + layout[int(m.group(1))] = (int(m.group(2)), int(m.group(3))) + per, nonzero, stray, clobbers = [None] * count, [None] * count, [0] * count, [0] * count + for m in re.finditer(r"instance (\d+): ([\d.]+) instructions/sample", stdout): + per[int(m.group(1))] = float(m.group(2)) + for m in re.finditer(r"instance (\d+): (\d+) non-zero output samples(?:, (\d+) stray write regions, (\d+) CLOBBERING)?", + stdout): + k = int(m.group(1)) + nonzero[k] = int(m.group(2)) + if m.group(3): + stray[k], clobbers[k] = int(m.group(3)), int(m.group(4)) + return Render(outputs, meters, means, layout, per, nonzero, stray, clobbers, returncode, stdout, cmd) + + +# ---- signals ----------------------------------------------------------------------- + +def noise(n, amp, seed): + rnd = random.Random(seed) + return [round(amp * Q * (rnd.random() * 2 - 1)) for _ in range(n)] + + +def tone(hz, amp, n): + return [round(amp * Q * math.sin(2 * math.pi * hz * i / FS)) for i in range(n)] + + +def burst(frames, n, amp=0.5, seed=3): + """`frames` of noise, then silence to `n`.""" + return noise(frames, amp, seed) + [0] * (n - frames) + + +# ---- fx:audit ---------------------------------------------------------------------- + +def render_fx_audit(asm, plan_dir, renders, knobs, *, image=None, frames=FRAMES, timeout=1800): + """Render every signal `npm run fx:audit -- plan ` wrote (mono int32 .raw) through one instance at + `knobs`, both channels, into `renders`/.raw (interleaved L R int32), for + `npm run fx:audit -- check `. Returns the files written. Keep renders out of Git.""" + plan_dir, renders = pathlib.Path(plan_dir), pathlib.Path(renders) + plan = json.loads((plan_dir / "plan.json").read_text()) + names = [t["file"] for t in plan["tones"]] + [plan["idle"]["file"], plan["noise"]["file"]] + renders.mkdir(parents=True, exist_ok=True) + written = [] + for name in names: + raw = (plan_dir / f"{name}.raw").read_bytes() + x = list(struct.unpack(f"<{len(raw) // 4}i", raw)) + (l, r), = run(asm, [Instance(x, x, knobs=knobs)], image=image, frames=frames, tag="audit", + timeout=timeout).outputs + path = renders / f"{name}.raw" + path.write_bytes(struct.pack(f"<{2 * len(x)}i", *(v for pair in zip(l, r) for v in pair))) + written.append(path) + return written + + +# ---- gate output --------------------------------------------------------------------- + +class Gates: + """[PASS]/[FAIL] lines; finish() exits 1 naming the failures.""" + + def __init__(self, name): + self.name, self.failures = name, [] + + def __call__(self, name, ok, detail=""): + print(f"[{'PASS' if ok else 'FAIL'}] {name} {detail}".rstrip(), flush=True) + if not ok: + self.failures.append(name) + return ok + + def same(self, name, got, want): + """got, want: (left, right). Bit for bit over want's length; the first difference named.""" + (gl, gr), (wl, wr) = got, want + bad = next((i for i in range(len(wl)) if i >= len(gl) or (gl[i], gr[i]) != (wl[i], wr[i])), None) + return self(name, bad is None, "" if bad is None else + f"first difference at frame {bad} (block {bad // FRAMES}): " + f"{(gl[bad], gr[bad]) if bad < len(gl) else 'missing'} vs model {(wl[bad], wr[bad])}") + + def finish(self): + if self.failures: + sys.exit(f"[FAIL] {len(self.failures)}: {', '.join(self.failures)}") + print(f"[PASS] {self.name}") + + +def workdir(prefix="dsp-gate-"): + """A temporary folder for one gate run (a context manager).""" + return tempfile.TemporaryDirectory(prefix=prefix) diff --git a/sdk/templates/dsp-port/README.md b/sdk/templates/dsp-port/README.md new file mode 100644 index 0000000000..8685a1dafd --- /dev/null +++ b/sdk/templates/dsp-port/README.md @@ -0,0 +1,33 @@ +# Port template: an Airwindows plugin as an Octatrack DSP effect + +`npm run module:new -- --kind dsp --port airwindows --upstream --author ` +lays these files over the `dsp` template in the new draft (this README stays here). `` is a +folder in your own clone of github.com/airwindows/airwindows, such as +`plugins/LinuxVST/src/Mackity`. The scaffold copies that folder's files and the repository's `LICENSE` from +the commit checked out (`HEAD`, not the working tree) into `upstream/`, records each with its SHA-256 and Git +blob in `import-record.json`, and fills in the manifest's `source`, credits and licence. + +| File | What it is | Runs where | +|---|---|---| +| `upstream/` | upstream's files at the pinned commit, unchanged | read only | +| `reference.py` | `float_model` (upstream in double precision) and `Model` (the assembly, bit for bit) | imported | +| `test_reference.py` | `Model` against `float_model`, silence, the tail | host test: no tools, `sdk:check` and `module:doctor` | +| `verify.py` | `engine.asm` in dsp_host against `Model`: decode traps, automation, splits, LFO bits, garbage state, two instances, silence | needs the DSP tools | +| `perf.py` | meters for `evidence/performance.json`: three settings by sixteen splits, then the eight-instance stress run | needs the DSP tools | + +`verify.py` and `perf.py` use the shared harness, `sdk/octatrack/tools/dsp_gate.py` (its docstring +lists what it offers; its tests are `sdk/tests/test_dsp_gate.py`): tool lookup, assembly, the synthetic +image, `run()` for one to eight instances, the assembler-trap check and the fx:audit renders. Both fail, +on purpose, until `reference.PORTED` is `True`. Any DSP effect's gate can import it the same way: the +`_library()` lookup at the top of `verify.py` finds it from the module folder, its mirror under +`sdk/octabam/modules` or `sdk/drafts`. It is not module source, so changing it moves no module's package +or native fingerprint; record its hash (`dsp_gate.provenance()`, which `verify.py` prints) in TESTING.md +beside your own files'. Modules written before it keep their own copies until a release moves them. + +The loop: port upstream's `processReplacing` into `float_model`; write `engine.asm` and `Model` side by +side; `python3 -B test_reference.py` (seconds), then `python3 -B verify.py`; hear it with +`npm run module:dev -- `. `sdk/octatrack/modules/mackity/` is the finished example. + +When it is listed, move `import-record.json` to `sdk/imports/-.json`, add the module to +the `airwindows` entry of `sdk/octabam/licenses/manifest.json`, and run `npm run licenses:generate` +(docs/ADD_A_MODULE.md, Octatrack, step 1). diff --git a/sdk/templates/dsp-port/perf.py b/sdk/templates/dsp-port/perf.py new file mode 100644 index 0000000000..d03a2fcd59 --- /dev/null +++ b/sdk/templates/dsp-port/perf.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""__NAME__'s performance measurements for evidence/performance.json, in dsp_host. + + python3 -B perf.py (the tools verify.py finds; a few minutes) + python3 -B perf.py --stress (the stress run only) + +measured executed instructions a sample from dsp_host's meter, one instance on verify.py's synthetic image: + the defaults, the dearest setting and a moving pattern (every knob swept by a triangle and jumped + every 37 blocks), each unsplit and with a trig split at every position 1-15. +stress eight instances, four a core, each on its own stem (bursts, a full-scale square, a sweep, noise, + impulses, DC steps, silence, a chord), all twelve parameter words given a new value every block, + trig splits of 1, 3, 7, 8, 12 and 15 frames, under -guard and -dirty. dsp_host itself writes a word a + block into the instance at core 1 position 2 (dsp_gate.HARNESS_WORD): its output from silence is + not the module's. + +Add a static count once the sample loop is written: the loop's words from the disassembly, priced as +sdk/octabam/tools/build/cycle_count.py prices straight-line loops (sdk/octatrack/modules/mackity/perf.py). +Then npm run perf:audit -- check evidence/performance.json --stamp (docs/MODULE_PERFORMANCE.md). +""" +import math +import pathlib +import random +import sys + +HERE = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import verify as V # noqa: E402 (finds sdk/octatrack/tools) + +G, R = V.G, V.R +Q = G.Q +BLOCKS = 4096 +SECONDS = 2 + + +def moving(blocks, seed=1, every_slot=False): + """Every knob swept by a triangle (each a quarter turn apart) and jumped every 37 blocks; every_slot also + gives the slots the module does not read a new random value every block.""" + rnd = random.Random(seed) + rows = {} + for b in range(blocks): + knobs = [127 - abs(((b + 64 * k) % 256) - 128) for k in range(len(R.KNOBS))] + knobs = [min(127, max(0, v)) for v in knobs] + if b % 37 == 0: + knobs = [rnd.randrange(128) for _ in R.KNOBS] + rest = [rnd.randrange(128) for _ in range(12 - len(knobs))] if every_slot else [] + rows[b] = tuple(knobs + rest) + return rows + + +def stems(n, live): + rnd = random.Random(9) + on = lambda i, v: v if i < live else 0 # noqa: E731 + return [ + [on(i, round(0.9 * Q * (rnd.random() * 2 - 1) * math.exp(-(i % 11025) / 1500))) for i in range(n)], + [on(i, Q - 1 if (i // 110) % 2 else -Q) for i in range(n)], + [on(i, round(0.9 * Q * math.sin(2 * math.pi * (20 * (1000 ** (i / live))) * i / G.FS))) for i in range(n)], + [on(i, round(Q * (rnd.random() * 2 - 1))) for i in range(n)], + [on(i, Q - 1 if i % 4410 == 0 else 0) for i in range(n)], + [on(i, (Q - 1) if (i // 8820) % 2 else -Q) for i in range(n)], + [0] * n, + [on(i, round(0.3 * Q * sum(math.sin(2 * math.pi * f * i / G.FS) for f in (220, 277.2, 329.6)))) + for i in range(n)], + ] + + +def main(): + G.require_tools(HERE) + with G.workdir("__ID__-perf-") as tmp: + work = pathlib.Path(tmp) + asm = G.assemble(V.SOURCE, work) + if "--stress" not in sys.argv: + sig = G.noise(16 * BLOCKS, 0.7, 5) + cases = {"defaults": dict(knobs=R.DEFAULTS), "dearest": dict(knobs=R.DEAREST), + "moving": dict(rows=moving(BLOCKS))} + worst = (0.0, "") + for name, knobs in cases.items(): + found = {} + for split in range(16): + found[split] = G.run(asm, [G.Instance(sig, sig, **knobs)], split=split or None, tag=name).meter + if found[split] > worst[0]: + worst = (found[split], f"{name}, split {split}") + print(f"measured {name}: unsplit {found[0]:.2f}, worst with a split {max(found[s] for s in range(1, 16)):.2f}") + print(f"measured worst: {worst[0]:.2f} executed instructions a sample ({worst[1]})") + + n = G.FS * SECONDS * 2 + insts = [G.Instance(s, s, rows=moving(n // 16, seed=k + 11, every_slot=True), split=split, core=k // 4) + for k, (s, split) in enumerate(zip(stems(n, G.FS * SECONDS), (1, 3, 7, 8, 12, 15, 0, 0)))] + r = G.run(asm, insts, dirty=0x5a, guard=True, check=False, tag="stress", timeout=1800) + print(f"stress: dsp_host exit {r.returncode}; meters {r.meters}; clobbers {sum(r.clobbers)}, stray {sum(r.stray)}") + for k, (core, pos) in enumerate(r.layout): + note = " (dsp_host's own word lands here)" if r.harness_word(k) else "" + print(f" instance {k}: core {core} pos {pos}, {r.per_instance[k]} a sample, {r.nonzero[k]} non-zero samples{note}") + if r.returncode: + print(r.stdout[-2000:]) + + +if __name__ == "__main__": + main() diff --git a/sdk/templates/dsp-port/reference.py b/sdk/templates/dsp-port/reference.py new file mode 100644 index 0000000000..62e048d455 --- /dev/null +++ b/sdk/templates/dsp-port/reference.py @@ -0,0 +1,93 @@ +"""__NAME__'s two references, imported by verify.py, perf.py and test_reference.py. + +float_model: upstream/ (Airwindows __UPSTREAM__ at __REVISION__) in double precision at 44.1 kHz, less its +32-bit float dither and denormal noise: the Octatrack's path is 24-bit fixed point, where neither applies. +test_reference.py holds Model to it. + +Model: engine.asm instruction by instruction, on 24-bit words and a 56-bit accumulator, so dsp_host's render +must match it to the bit (verify.py). As npm run module:new wrote it, engine.asm returns at once and Model +passes the audio through: port upstream's processReplacing into float_model, then write the assembly and this +model side by side, constant by constant. sdk/octatrack/modules/mackity/reference.py is a finished pair. +""" +import math # noqa: F401 (the float model's) + +FS = 44100.0 +Q = 1 << 23 + +# Set True once float_model is upstream's algorithm and Model is what engine.asm computes; verify.py and +# test_reference.py fail until then, so a pass-through never passes for a port. +PORTED = False + +# The knobs in manifest.py's slot order, their defaults and the dearest setting (manifest.py's `dear`). +KNOBS = ("P0", "P1") +DEFAULTS = (64, 0) +DEAREST = (127, 127) + + +def float_model(left, right, knobs): + """Upstream's sample loop on floats in [-1, 1) at `knobs` (the knob values, 0-127, in slot order); + returns (left, right) float lists. Map each knob to upstream's parameter (0.0-1.0) as the port does.""" + raise NotImplementedError("port upstream's processReplacing (upstream/*Proc.cpp) into float_model") + + +# ---- the fixed-point model ------------------------------------------------- + +def s24(v): + v &= 0xffffff + return v - (1 << 24) if v & 0x800000 else v + + +def w56(a): + a &= (1 << 56) - 1 + return a - (1 << 56) if a >> 55 else a + + +def lim(a): + """move a,x0 / move a,x:(..): the limiter.""" + return max(-0x800000, min(0x7fffff, a >> 24)) + + +def hi(a): + """move a1,x0: the middle word, unlimited.""" + return s24(a >> 24) + + +def ld(x): + """A 24-bit word loaded into an accumulator's middle.""" + return x << 24 + + +def mac(a, x, y): + """mac x0,y1,a: the fractional product, doubled.""" + return w56(a + 2 * x * y) + + +class Model: + """One instance of engine.asm. call(frames, words) runs one proc on [(left, right)] with the twelve knob + words (value << 16, plus any fraction bits an LFO leaves) and returns [(left, right)].""" + + def __init__(self): + self.x = [0] * 32 # X:(r7+$00..$1f), as init leaves it + + def call(self, frames, words): + return list(frames) + + +def render(left, right, knob_rows, frames=16, split=0, pwords=None): + """dsp_host's schedule in the model: blocks of `frames`, a knob row per block (block -> knob values from + then on), and a split call first when split > 0. pwords: slot -> low 16 bits added to that knob word.""" + m = Model() + out_l, out_r = [], [] + cur = knob_rows.get(0, DEFAULTS) + pw = pwords or {} + for blk in range((len(left) + frames - 1) // frames): + cur = knob_rows.get(blk, cur) + values = list(cur) + [0] * (12 - len(cur)) + words = [(v << 16) | pw.get(slot, 0) for slot, v in enumerate(values)] + lo = blk * frames + fr = list(zip(left[lo:lo + frames], right[lo:lo + frames])) + for part in ([fr[:split], fr[split:]] if split else [fr]): + for l, r in m.call(part, words): + out_l.append(l) + out_r.append(r) + return out_l, out_r, m diff --git a/sdk/templates/dsp-port/test_reference.py b/sdk/templates/dsp-port/test_reference.py new file mode 100644 index 0000000000..707b4623bd --- /dev/null +++ b/sdk/templates/dsp-port/test_reference.py @@ -0,0 +1,77 @@ +"""__NAME__ host test: the fixed-point model against upstream's algorithm. + + python3 -B test_reference.py (no tools, no firmware) + +What it proves once ported: the model (reference.Model, which verify.py holds the assembly to, bit for bit) +computes upstream's __UPSTREAM__: the level within 0.001 dB of the double precision original and everything +else under -100 dB, the original limited at full scale where it goes over (a 24-bit output cannot); silence +stays silence. Tighten or loosen the limits to what the port achieves, and say why in TESTING.md. What it +cannot see: the assembly itself (verify.py), the unit, the sound. +""" +import math +import pathlib +import random +import sys +import unittest + +HERE = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import reference as R # noqa: E402 + +Q = R.Q + + +def tone(f, amp, n): + return [round(amp * Q * math.sin(2 * math.pi * f * i / R.FS)) for i in range(n)] + + +def error_db(fixed, ref, skip=4410): + """(gain error in dB, residual after that gain in dB to the signal), the original limited at full scale.""" + ref = [max(-1.0, min(1.0 - 1 / Q, v)) for v in ref] + fx = [v / Q for v in fixed] + s = sum(v * v for v in ref[skip:]) + g = sum(fx[i] * ref[i] for i in range(skip, len(ref))) / s + e = sum((fx[i] - g * ref[i]) ** 2 for i in range(skip, len(ref))) + return 20 * math.log10(g), 10 * math.log10(max(e, 1e-30) / s) + + +class Reference(unittest.TestCase): + def test_ported(self): + self.assertTrue(R.PORTED, "reference.py still models the scaffold's pass-through: port upstream into " + "float_model and Model, then set PORTED = True") + + def test_matches_the_original(self): + for knobs, f, amp in ((R.DEFAULTS, 1000, 0.5), (R.DEFAULTS, 100, 0.9), (R.DEAREST, 440, 0.5), + (R.DEAREST, 9100, 0.89)): + with self.subTest(knobs=knobs, hz=f, amp=amp): + x = tone(f, amp, 22050) + try: + ref, _ = R.float_model([v / Q for v in x], [0.0] * len(x), knobs) + except NotImplementedError as error: + self.fail(str(error)) + out, _, _ = R.render(x, x, {0: knobs}) + if not any(ref[4410:]): + self.assertFalse(any(out[4410:])) + continue + gain, residual = error_db(out, ref) + self.assertLess(abs(gain), 0.001) + self.assertLess(residual, -100) + + def test_silence_stays_silence(self): + z = [0] * 4096 + for knobs in (R.DEFAULTS, R.DEAREST): + with self.subTest(knobs=knobs): + out_l, out_r, _ = R.render(z, z, {0: knobs}) + self.assertFalse(any(out_l + out_r)) + + def test_tail_ends_in_silence(self): + rnd = random.Random(3) + burst = [round(0.5 * Q * (rnd.random() * 2 - 1)) if i < 4410 else 0 for i in range(44100 * 2)] + for knobs in (R.DEFAULTS, R.DEAREST): + with self.subTest(knobs=knobs): + out_l, out_r, _ = R.render(burst, burst, {0: knobs}) + self.assertFalse(any(out_l[-22050:] + out_r[-22050:])) + + +if __name__ == "__main__": + unittest.main() diff --git a/sdk/templates/dsp-port/verify.py b/sdk/templates/dsp-port/verify.py new file mode 100644 index 0000000000..47f55f6f81 --- /dev/null +++ b/sdk/templates/dsp-port/verify.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""__NAME__'s render gate: engine.asm assembled and run in dsp_host, held to reference.py's model. + + python3 -B verify.py (needs the DSP tools; about a minute) + python3 -B verify.py --fx-audit PLAN RENDERS (renders npm run fx:audit -- plan PLAN at the dearest + setting into RENDERS, for npm run fx:audit -- check) + +No firmware is read: the harness is sdk/octatrack/tools/dsp_gate.py, a synthetic image and dsp_host. Knobs +arrive as value << 16. What this cannot see: the composed image, the real dispatcher, the panel and the sound +on a unit. + +Gates: + 1. Every instruction decodes as written: no mpysu/macsu, no rep, every product the signed mpy/mac x0,y1 + form, and the state inside X:(r7+$00..$1f). + 2. Bit for bit the model: stereo noise at the defaults, a loud tone at the dearest setting, knob automation + over every knob's range, a 5-frame trig split every block, a knob word carrying an LFO's fraction bits, + garbage in the state block before init, and two instances with their own knobs. + 3. Silence in is exact silence out at the defaults, the dearest setting and every knob at 0; a burst's tail + ends in exact silence. + 4. The cycle meter, printed for TESTING.md and evidence/performance.json (perf.py measures the rest). +""" +import pathlib +import sys + +HERE = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) + + +def _library(): + """sdk/octatrack/tools, from the module folder, its mirror under sdk/octabam/modules or sdk/drafts.""" + for base in HERE.parents: + if (base / "sdk/octatrack/tools/dsp_gate.py").is_file(): + return base / "sdk/octatrack/tools" + sys.exit("[FAIL] sdk/octatrack/tools/dsp_gate.py not found: run this inside a Modwerk checkout") + + +sys.path.insert(0, str(_library())) +import dsp_gate as G # noqa: E402 +import reference as R # noqa: E402 + +SOURCE = HERE / "engine.asm" +STATE_LAST = 0x1f # the last word of X:(r7+...) the module may use + + +def rows_over_ranges(): + """Every knob swept over its range, one at a time, then a one-block step and back to the defaults.""" + rows, block = {0: R.DEFAULTS}, 10 + for slot in range(len(R.KNOBS)): + for value in (0, 127, 64): + row = list(R.DEFAULTS) + row[slot] = value + rows[block] = tuple(row) + block += 10 + rows[block], rows[block + 1], rows[block + 2] = R.DEAREST, R.DEFAULTS, R.DEAREST + rows[block + 30] = R.DEFAULTS + return rows + + +def main(): + G.require_tools(HERE) + gate = G.Gates("__ID__") + with G.workdir("__ID__-verify-") as tmp: + work = pathlib.Path(tmp) + asm = G.assemble(SOURCE, work) + if "--fx-audit" in sys.argv: + plan, renders = sys.argv[sys.argv.index("--fx-audit") + 1:][:2] + for path in G.render_fx_audit(asm, plan, renders, R.DEAREST): + print(path.name, flush=True) + return + + # 1. decodes as written + problems = G.trap_problems(asm, forms=("x0,y1",)) + gate("1 decodes as written: signed mpy/mac x0,y1, no rep, no mpysu/macsu", not problems, + "; ".join(problems[:4])) + offsets = G.state_offsets(SOURCE.read_text()) + gate("1 state inside X:(r7+$00..$1f)", not offsets or offsets[-1] <= STATE_LAST, + f"(highest ${offsets[-1]:02x})" if offsets else "(no state yet)") + + # 2. bit for bit the model + n = 16 * 160 + nl, nr = G.noise(n, 0.7, 1), G.noise(n, 0.7, 2) + t = G.tone(440, 0.9, n) + + def same(name, inst, **kw): + r = G.run(asm, [inst], split=kw.get("split"), pwords=kw.get("pwords"), dirty=kw.get("dirty")) + rows = inst.rows or {0: inst.knobs} + want = R.render(inst.left, inst.right, rows, split=kw.get("split") or 0, pwords=kw.get("model_pwords")) + gate.same(name, r.outputs[0], want[:2]) + return r + + meter_def = same("2 defaults, stereo noise", G.Instance(nl, nr, knobs=R.DEFAULTS)).meter + meter_dear = same("2 the dearest setting, a loud tone and noise", G.Instance(t, nl, knobs=R.DEAREST)).meter + rows = rows_over_ranges() + same("2 knob automation", G.Instance(nl, nr, rows=rows)) + same("2 a trig split every block", G.Instance(nl, nr, rows=rows), split=5) + word = (R.DEFAULTS[0] << 16) | 0xb700 + same("2 a knob word with an LFO's fraction bits", G.Instance(nl, nr, knobs=R.DEFAULTS), + pwords=[(0, 0, word)], model_pwords={0: 0xb700}) + same("2 garbage state before init", G.Instance(nl, nr, rows=rows), dirty=0x5a5a5a) + a, b = G.run(asm, [G.Instance(nl, nr, knobs=R.DEFAULTS), G.Instance(t, t, knobs=R.DEAREST)]).outputs + gate.same("2 two instances: the first", a, R.render(nl, nr, {0: R.DEFAULTS})[:2]) + gate.same("2 two instances: the second", b, R.render(t, t, {0: R.DEAREST})[:2]) + + # 3. silence + z = [0] * n + for knobs in (R.DEFAULTS, R.DEAREST, (0,) * len(R.KNOBS)): + (l, r), = G.run(asm, [G.Instance(z, z, knobs=knobs)], tag="zero").outputs + gate(f"3 silence in, silence out at {dict(zip(R.KNOBS, knobs))}", not any(l + r)) + m = G.FS * 2 + x = G.burst(4410, m) + (l, r), = G.run(asm, [G.Instance(x, x, knobs=R.DEAREST)], tag="tail").outputs + gate("3 a burst's tail ends in silence", not any(l[-G.FS // 2:] + r[-G.FS // 2:])) + + # 4. cost + print(f"[INFO] cycle meter: {meter_def} a sample at the defaults, {meter_dear} at the dearest setting") + print(f"[INFO] dsp_gate.py {G.provenance(HERE)['dsp_gate.py']}") + gate("reference.py models upstream, not the scaffold's pass-through", R.PORTED, + "" if R.PORTED else "(port it, then set PORTED = True)") + gate.finish() + + +if __name__ == "__main__": + main() diff --git a/sdk/templates/dsp/README.md b/sdk/templates/dsp/README.md index 576f02f092..49df117d48 100644 --- a/sdk/templates/dsp/README.md +++ b/sdk/templates/dsp/README.md @@ -21,4 +21,6 @@ What is unresolved. How a reader reproduces the measurements, in order. `tools/verify/verify_character.py` is the pattern: predict the arithmetic exactly, drive both signs, refuse to -run if the id it resolves is the fallback rather than the effect. +run if the id it resolves is the fallback rather than the effect. A render gate +in dsp_host imports `sdk/octatrack/tools/dsp_gate.py` rather than copying +another module's harness; `sdk/templates/dsp-port/verify.py` shows how. diff --git a/sdk/tests/test_dsp_gate.py b/sdk/tests/test_dsp_gate.py new file mode 100644 index 0000000000..1b4af6c6cd --- /dev/null +++ b/sdk/tests/test_dsp_gate.py @@ -0,0 +1,164 @@ +"""The shared DSP host-test library, sdk/octatrack/tools/dsp_gate.py. + + python3 -B -m unittest discover -s sdk/tests -p test_dsp_gate.py -v + +The image, the knob rows and the parsing of dsp_host's report run everywhere. The renders need dsp_asm, +dsp_host and the disassembler (npm run upstream:tools, then make setup in that octabam checkout) and skip +without them: CI has none. +""" +import json +import pathlib +import struct +import sys +import tempfile +import unittest + +ROOT = pathlib.Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "sdk/octatrack/tools")) +import dsp_gate as G # noqa: E402 + +TOOLS = G.tools_present() +NOTHING = "init:\n rts\nproc:\n rts\n" # sdk/templates/dsp/engine.asm: leaves the audio in place + +REPORT = """instance 0: core 0 pos 0, r7 = X:0x06200 (idx 0), base = Y:0x04000 (X:0x256 idx 0), audio X:0x00700, init P:0x02000 proc P:0x02001 +instance 1: core 1 pos 2, r7 = X:0x06400 (idx 1), base = Y:0x04000 (X:0x257 idx 1), audio X:0x00700, init P:0x02000 proc P:0x02001 +ran 4 blocks x 16 frames on 2 instance(s), 2 core(s) lock-step + core 0 meter: max 120 instructions in block 2, mean 100 (7.5/sample max, 6.3/sample mean at 16 frames); inits 12 + core 1 meter: max 160 instructions in block 0, mean 150 (10.0/sample max, 9.4/sample mean at 16 frames); inits 12 + instance 0: 6.2 instructions/sample (4 calls) + instance 0: 0 non-zero output samples, 0 stray write regions, 0 CLOBBERING a loaded module + instance 1: 9.1 instructions/sample (4 calls) + instance 1: 4 non-zero output samples, 1 stray write regions, 2 CLOBBERING a loaded module +""" + + +class Offline(unittest.TestCase): + def test_image_layout(self): + with tempfile.TemporaryDirectory() as tmp: + path = G.write_image([0x00000c, 0x00000c], pathlib.Path(tmp) / "m.mem", + extra=[(G.P, 0x3000, [1, 2, 3])], x={0x20d: 8}) + data, records = path.read_bytes(), [] + while True: + space, addr, count = struct.unpack_from(" 1 else self.listed[0] + + def open(self, name): + system, number = self, len(self.ports) + + class Port: + closed = False + def send(self, data): + if number in system.dead: raise OSError('midiOutShortMsg refused %s' % data.hex()) + system.sent.append((number, data)) + def close(self): self.closed = True + self.ports.append(Port()) + return self.ports[-1] + + +class Bridge(unittest.TestCase): + def output(self, system): + self.waits, self.logged = [], [] + return bridge.Output(system, 'Octatrack', wait=self.waits.append, log=lambda *a, **k: self.logged.append(a[0])) + + def test_it_sends_on_the_port_it_opened(self): + system = System([['Microsoft GS Wavetable Synth', 'Elektron Octatrack']]) + out = self.output(system) + self.assertEqual(out.opened, 'Elektron Octatrack') + self.assertEqual(bridge.answer(out, 'c001 fa\n'), 'ok 2\n') + self.assertEqual(system.sent, [(0, b'\xc0\x01'), (0, b'\xfa')]) + self.assertEqual(out.reopened, 0) + + def test_a_dead_port_is_opened_again_and_the_message_sent_once_more(self): + # 25 November 2026: after a RAM boot every send answered `midiOutShortMsg refused c001` until the bridge restarted. + system = System([['Elektron Octatrack']], dead={0}) + out = self.output(system) + self.assertEqual(bridge.answer(out, 'c001\n'), 'ok 1\n') + self.assertTrue(system.ports[0].closed) + self.assertEqual(system.sent, [(1, b'\xc0\x01')]) + self.assertEqual(out.reopened, 1) + self.assertEqual(self.logged, ['reopened Elektron Octatrack after: midiOutShortMsg refused c001']) + self.assertEqual(bridge.answer(out, 'fa\n'), 'ok 1\n') # and it stays on the new port + self.assertEqual(out.reopened, 1) + + def test_it_waits_for_the_unit_to_come_back_on_usb(self): + system = System([['Elektron Octatrack'], [], [], ['Elektron Octatrack']], dead={0}) + out = self.output(system) + self.assertEqual(bridge.answer(out, 'fc\n'), 'ok 1\n') + self.assertEqual(self.waits, [0.5, 0.5]) + + def test_it_answers_an_error_when_the_unit_stays_away_and_tries_again_on_the_next_line(self): + system = System([['Elektron Octatrack']] + [[]] * 10 + [['Elektron Octatrack']], dead={0}) + out = self.output(system) + reply = bridge.answer(out, 'c001\n') + self.assertTrue(reply.startswith('error: midiOutShortMsg refused c001; opening \'Octatrack\' again failed: No MIDI output named like'), reply) + self.assertEqual(len(self.waits), 10) # 5 s at most + self.assertIsNone(out.port) + self.assertEqual(bridge.answer(out, 'c001\n'), 'ok 1\n') # back now: the next line reopens it + + def test_a_port_that_fails_again_after_reopening_is_the_answer(self): + system = System([['Elektron Octatrack']], dead={0, 1}) + out = self.output(system) + self.assertEqual(bridge.answer(out, 'c001\n'), 'error: midiOutShortMsg refused c001\n') + self.assertEqual(len(system.ports), 2) # one retry, not a loop + + def test_a_malformed_line_never_reaches_the_port(self): + system = System([['Elektron Octatrack']]) + out = self.output(system) + self.assertEqual(bridge.answer(out, 'f0 7e\n'), 'error: not a short MIDI message: f0\n') + self.assertEqual(system.sent, []) + + def test_no_output_of_that_name_stops_it_at_the_start(self): + with self.assertRaises(LookupError): + self.output(System([['Microsoft GS Wavetable Synth']])) + + +if __name__ == '__main__': + unittest.main() diff --git a/sdk/tests/test_octatrack_preflight.py b/sdk/tests/test_octatrack_preflight.py new file mode 100755 index 0000000000..1809545e09 --- /dev/null +++ b/sdk/tests/test_octatrack_preflight.py @@ -0,0 +1,115 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""scripts/octatrack-preflight.py against a fake session and a fake MIDI bridge: what it finds, and that it only reads.""" +import importlib.util +import pathlib +import socket +import sys +import unittest +from unittest import mock + +ROOT = pathlib.Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location('octatrack_preflight', ROOT / 'scripts/octatrack-preflight.py') +preflight = importlib.util.module_from_spec(spec) +spec.loader.exec_module(preflight) +qualify = preflight.qualify + +BANK_BASE = 0x46d00000 + + +class Unit: + """A session's answers: `state`, and `mem:` reads of the bank and pattern, the Part number, the bank pointer and trig masks.""" + + def __init__(self, state='stopped', bank=2, pattern=0, part=0, busy=8, equal=True): + self.state, self.bank, self.pattern, self.part, self.busy, self.equal, self.sent = state, bank, pattern, part, busy, equal, [] + + def send(self, sequence): + self.sent.append(sequence) + if sequence == 'state': return self.state + '\n' + raise AssertionError('not a read the preflight makes: ' + sequence) + + def mem(self, addr, n): + self.sent.append('mem:%#x:%d' % (addr, n)) + if addr == preflight.CURRENT: return bytes([self.bank, self.pattern]) + if addr == qualify.PART: return bytes([self.part]) + if addr == qualify.BANK: return BANK_BASE.to_bytes(4, 'big') + track = (addr - BANK_BASE - self.pattern * preflight.PATTERN) // preflight.TRACK + return bytes([0x11] * 8) if track < self.busy else bytes(8) + + def __enter__(self): + self.patches = [mock.patch.object(qualify, 'send', self.send), mock.patch.object(qualify, 'mem', self.mem), + mock.patch.object(qualify, 'part_saved_equal', lambda: self.equal)] + for p in self.patches: p.start() + return self + + def __exit__(self, *a): + for p in self.patches: p.stop() + + +class Preflight(unittest.TestCase): + def test_a_ready_unit_passes_with_reads_only(self): + with Unit(pattern=1, busy=0) as unit: + self.assertEqual(preflight.unit_problems(pick=2), []) + self.assertTrue(all(s == 'state' or s.startswith('mem:') for s in unit.sent)) + + def test_a_flashed_release_base_is_told_apart_from_no_session(self): + refused = RuntimeError('state: error: This base does not answer development requests: build it with --dev.') + with mock.patch.object(qualify, 'send', side_effect=refused): + [problem] = preflight.unit_problems(pick=2) + self.assertIn('does not answer development requests', problem) + self.assertIn('npm run device -- boot DIR', problem) + with mock.patch.object(qualify, 'send', side_effect=FileNotFoundError(2, 'No such file')): + [problem] = preflight.unit_problems() + self.assertIn('no session answers on', problem) + + def test_a_playing_transport_and_a_changed_part_are_both_named(self): + with Unit(state='playing', part=2, equal=False, busy=0): + problems = preflight.unit_problems(pick=2) + self.assertEqual(len(problems), 2) + self.assertIn('the transport plays', problems[0]) + self.assertIn('Part 3 of bank C differs from its saved copy', problems[1]) + + def test_a_busy_pattern_fails_unless_it_is_the_pick_pattern(self): + # 25 November 2026: C01 with all eight tracks playing refused the pick (CPU FULL); the empty pattern 2 took it. + with Unit(bank=2, pattern=0, busy=8): + [problem] = preflight.unit_problems(pick=2) + self.assertIn('pattern C01 has trigs on 8 tracks', problem) + self.assertIn('PATTERN+TRIG2', problem) + with Unit(bank=2, pattern=1, busy=8): + self.assertEqual(preflight.unit_problems(pick=2), []) # on the pick pattern: the caller chose it + with Unit(bank=2, pattern=0, busy=6): + self.assertEqual(preflight.unit_problems(pick=2), []) # the medium pattern's six tracks have room + with Unit(bank=2, pattern=0, busy=8): + self.assertEqual(preflight.unit_problems(), []) # a base: no picks on the current pattern + + def test_the_midi_bridge_must_answer_and_send(self): + class Link: + def __init__(self, reply): self.reply, self.sent = reply, b'' + def settimeout(self, s): pass + def sendall(self, data): self.sent += data + def makefile(self): + import io + return io.StringIO(self.reply) + def close(self): pass + + ok = Link('ok 1\n') + self.assertIsNone(preflight.midi_problem('127.0.0.1:50124', connect=lambda *a: ok)) + self.assertEqual(ok.sent, b'f6\n') # a tune request: nothing the unit acts on + refused = preflight.midi_problem('127.0.0.1:50124', connect=lambda *a: Link('error: midiOutShortMsg refused f6\n')) + self.assertIn('cannot send: error: midiOutShortMsg refused f6', refused) + self.assertIn('octatrack-midi-bridge.py 50124', refused) + + def absent(*a): raise ConnectionRefusedError(111, 'Connection refused') + self.assertIn('no MIDI bridge on 127.0.0.1:50124', preflight.midi_problem('127.0.0.1:50124', connect=absent)) + + def test_it_prints_one_line_a_problem_and_exits_1(self): + with Unit(state='playing', busy=0), mock.patch.object(sys, 'argv', ['octatrack-preflight.py', '--midi', '127.0.0.1:1']), \ + mock.patch.object(preflight, 'midi_problem', return_value='no MIDI bridge on 127.0.0.1:1'), \ + mock.patch('builtins.print') as printed: + with self.assertRaises(SystemExit) as c: preflight.main() + self.assertEqual(c.exception.code, 1) + self.assertEqual([call.args[0] for call in printed.call_args_list], + ['preflight: the transport plays: stop it (`npm run device -- do STOP`)', 'preflight: no MIDI bridge on 127.0.0.1:1']) + + +if __name__ == '__main__': + unittest.main() diff --git a/server/api.ts b/server/api.ts index b54b5fed63..4eea17d9d7 100644 --- a/server/api.ts +++ b/server/api.ts @@ -17,6 +17,7 @@ import { communityModule, moduleThreadId } from '../src/community/modules' import { ensureDiscussionThread, ensureModuleThreadsOnce } from './module-threads' import { validateDigiIssueContext } from '../src/community/digi-issue-context' import { recordAnonymousCount, recordUsage, recordModuleDownload, usageStatistics } from './usage' +import { kofiCoverage, kofiWebhook } from './kofi' import { sharedModuleStatistics } from './module-statistics' import { worksReportCount } from './hardware-reports' import { workingReportRoute } from './working-reports' @@ -60,6 +61,11 @@ export async function handleApi(request: Request, env: Env): Promise { if (!env.DB) throw new HttpError(503,'Community services are not connected yet.') return response(await handleGithubWebhook(request,env,env.DB,await boundedBody(request,1024*1024))) } + // Ko-fi posts payments server-to-server without an Origin; its verification token authenticates them. + if (path === '/api/kofi/webhook' && request.method === 'POST') { + if (!env.DB) throw new HttpError(503,'Community services are not connected yet.') + return await kofiWebhook(request,env,env.DB) + } // The Pages job authenticates server-to-server with GitHub OIDC after its approved deployment. if (path === '/api/module-releases/sync') { if (!env.DB) throw new HttpError(503,'Community services are not connected yet.') @@ -95,6 +101,7 @@ export async function handleApi(request: Request, env: Env): Promise { if (path === '/api/usage/events' && request.method === 'POST') return await recordUsage(request,env,db) if (path === '/api/usage/module-downloads' && request.method === 'POST') return await recordModuleDownload(request,env,db) if (path === '/api/usage/count' && request.method === 'POST') return await recordAnonymousCount(request,env,db) + if (path === '/api/support/coverage' && request.method === 'GET') return await kofiCoverage(env,db) if (path === '/api/catalog' && request.method === 'GET') return response((await db.prepare("SELECT s.module_id,s.title,s.repository_url,s.description,s.usage,s.resource_notes,s.test_report_url,s.reviewed_at,strftime('%Y-%m-%dT%H:%M:%SZ',s.reviewed_at) AS updated_at,(SELECT strftime('%Y-%m-%dT%H:%M:%SZ', MIN(first.reviewed_at)) FROM submissions first WHERE first.module_id=s.module_id AND first.status='approved') AS added_at,u.github_login AS author FROM module_publications p JOIN submissions s ON s.id=p.submission_id JOIN users u ON u.id=s.owner_id ORDER BY s.reviewed_at DESC").all()).results) if(path==='/api/community/summary'&&request.method==='GET')return response(await sharedModuleStatistics(db,url.searchParams.get('fresh')==='1'&&await throttle(db,'summary-fresh:'+(request.headers.get('CF-Connecting-IP')??'local'),30).then(()=>true,()=>false))) // past the limit, the shared answer if(path==='/api/community/online'&&request.method==='GET')return response(await membersOnline(db)) diff --git a/server/configuration-reports.ts b/server/configuration-reports.ts index 3f84403913..b35db22fd8 100644 --- a/server/configuration-reports.ts +++ b/server/configuration-reports.ts @@ -5,11 +5,13 @@ import { followReportedModules } from './module-updates' import type { Database, Env, User } from './platform' import { HttpError, jsonBody, optional, required, response } from './security' import { configurationSummary, validateConfigurationReportContext } from '../src/community/configuration-report' -import { IssueInputError } from '../src/community/issue-context' +import { IssueInputError, isDigiIssue } from '../src/community/issue-context' import { OT_LOG_MAX_BYTES, OtLogError, parseOtLog } from '../src/community/ot-log' import { communityModule } from '../src/community/modules' +import { SUPPORT_ATTACHMENT_BYTES } from '../src/community/support-report' +import { validateSupportAttachment } from './support-attachment' -const FIELDS = ['title', 'steps', 'expected', 'actual', 'context', 'log', 'maintainerSharing', 'visibility', 'notifyUpdates'] +const FIELDS = ['title', 'steps', 'expected', 'actual', 'context', 'log', 'usbEvents', 'maintainerSharing', 'visibility', 'notifyUpdates'] function input(read: () => T): T { try { return read() } catch (error) { if (error instanceof IssueInputError || error instanceof OtLogError) throw new HttpError(400, error.message); throw error } } /** @@ -19,7 +21,7 @@ function input(read: () => T): T { try { return read() } catch (error) { if ( */ export async function createConfigurationReport(request: Request, env: Env, db: Database, user: User | null) { const owner = needMember(user) - const body = await jsonBody(request, OT_LOG_MAX_BYTES + 32 * 1024) + const body = await jsonBody(request, OT_LOG_MAX_BYTES + SUPPORT_ATTACHMENT_BYTES + 32 * 1024) if (Object.keys(body).some(key => !FIELDS.includes(key))) throw new HttpError(400, 'Unexpected report field. Files and firmware are not accepted.') if (body.notifyUpdates !== undefined && typeof body.notifyUpdates !== 'boolean') throw new HttpError(400, 'Choose whether to follow module updates.') if (body.visibility !== undefined && body.visibility !== 'forum' && body.visibility !== 'private') throw new HttpError(400, 'Choose a public forum report or a private report.') @@ -31,6 +33,11 @@ export async function createConfigurationReport(request: Request, env: Env, db: const log = attached ? input(() => parseOtLog(body.log as string)) : null // An attached log records the configuration the device ran; otherwise the reporter names it. const { context, modules } = input(() => validateConfigurationReportContext(body.context, log?.summary ?? null)) + // USB events the reporter chose to attach (support-report.ts): kept with the configuration, which reaches GitHub on the + // same terms as the log. + const usb = body.usbEvents === undefined || body.usbEvents === null ? undefined : validateSupportAttachment(body.usbEvents) + if (usb && isDigiIssue(context)) throw new HttpError(400, 'USB events come from an Octatrack. Remove them and post the report again.') + if (usb && JSON.stringify(usb).length > SUPPORT_ATTACHMENT_BYTES) throw new HttpError(400, 'The attached USB events are too long. Remove them and post the report again.') // Member first, so one member's refused reports never fill the address's or the site's counter. await throttle(db, 'issue-member:' + owner.id, 10) await throttle(db, 'issue-ip:' + (request.headers.get('CF-Connecting-IP') ?? 'local'), 10) @@ -47,7 +54,7 @@ export async function createConfigurationReport(request: Request, env: Env, db: db.prepare('INSERT INTO forum_posts(id,thread_id,user_id,body) VALUES(?,?,?,?)').bind(postId, threadId, owner.id, 'Configuration (' + configurationSummary(modules.length) + '): ' + modules.map(module => module.name + ' ' + module.version).join(', ') + '\n\n' + details), db.prepare('INSERT INTO forum_follows(thread_id,user_id) VALUES(?,?)').bind(threadId, owner.id), ] : [] - statements.push(db.prepare("INSERT INTO issues(id,module_id,author_login,reporter_id,title,body,context_json,github_state,maintainer_sharing,forum_thread_id,public_json,scope) VALUES(?,?,?,?,?,?,?,?,?,?,?,'configuration')").bind(id, anchor.id, anchor.author, owner.id, title, details, JSON.stringify(context), github ? 'pending' : 'none', Number(publicReport || body.maintainerSharing === true), threadId, publicDetails && JSON.stringify(publicDetails))) + statements.push(db.prepare("INSERT INTO issues(id,module_id,author_login,reporter_id,title,body,context_json,github_state,maintainer_sharing,forum_thread_id,public_json,scope) VALUES(?,?,?,?,?,?,?,?,?,?,?,'configuration')").bind(id, anchor.id, anchor.author, owner.id, title, details, JSON.stringify(usb ? { ...context, usb } : context), github ? 'pending' : 'none', Number(publicReport || body.maintainerSharing === true), threadId, publicDetails && JSON.stringify(publicDetails))) for (const module of modules) statements.push(db.prepare('INSERT INTO issue_modules(issue_id,module_id,version) VALUES(?,?,?) ON CONFLICT DO NOTHING').bind(id, module.id, module.version)) if (log) statements.push(db.prepare('INSERT INTO issue_logs(issue_id,text,bytes,summary_json) VALUES(?,?,?,?)').bind(id, log.text, log.text.length, JSON.stringify(log.summary))) if (body.notifyUpdates !== false) statements.push(...followReportedModules(db, modules.map(module => module.id), owner.id)) diff --git a/server/github.ts b/server/github.ts index 0d098b2640..438a3f9883 100644 --- a/server/github.ts +++ b/server/github.ts @@ -8,6 +8,7 @@ import { profilePath } from '../src/community/forum-links' import { FLASH_STATES, type IssueContext } from '../src/community/issue-context' import { REPORT_CLOSURE_REASONS, REPORT_COMMANDS, type ReportClosureReason } from '../src/community/report-closure' import { digest } from './security' +import { supportBlock, type SupportAttachment } from '../src/community/support-report' const API = 'https://api.github.com' const BODY_LIMIT = 60000 @@ -69,7 +70,7 @@ const quote = (text: string) => inert(text).split(/\r?\n/).map(line => '> ' + li */ export type PublicBugDetails = { device: string; version: string; steps: string; expected: string; actual: string; modules?: { id: string; name: string; version: string }[]; full?: boolean } /** A whole-configuration report lists every module in `moduleIds`; `module_id` is then only the first of them. */ -export type MirroredIssue = { id: string; module_id: string; scope?: 'module' | 'configuration'; moduleIds?: string[]; title: string; reporter: string | null; owners: string[]; details: PublicBugDetails; context?: IssueContext; log?: string } +export type MirroredIssue = { id: string; module_id: string; scope?: 'module' | 'configuration'; moduleIds?: string[]; title: string; reporter: string | null; owners: string[]; details: PublicBugDetails; context?: IssueContext; log?: string; usb?: SupportAttachment } export function issueTitle(issue: Pick) { return ('[' + (issue.scope === 'configuration' ? 'configuration' : issue.module_id) + '] ' + issue.title).slice(0, 256) } const GITHUB_LOGIN = /^[A-Za-z0-9-]{1,39}$/ @@ -115,8 +116,10 @@ export function issueMarkdown(issue: MirroredIssue, app?: string) { 'Only the registered release author can use `resolve`, after verifying that exact published download fixes the report on their unit. Ordinary closures claim no new firmware fix.', '', 'A merged PR alone does not resolve a report. [Author release steps](https://github.com/repeat98/modwerk/blob/main/docs/MODULE_AUTHOR_UPDATES.md).', ] - const log = issue.log ? ['### Device log', '', ...logBlock(issue.log, BODY_LIMIT - [...report, ...rest].join('\n').length)] : [] - return [...report, ...log, ...rest].join('\n').slice(0, BODY_LIMIT) + // The reporter attached them themselves (support-report.ts); checked to numbers, codes and hashes when they posted. + const usb = issue.usb ? ['### USB events', '', ...supportBlock(issue.usb)] : [] + const log = issue.log ? ['### Device log', '', ...logBlock(issue.log, BODY_LIMIT - [...report, ...usb, ...rest].join('\n').length)] : [] + return [...report, ...usb, ...log, ...rest].join('\n').slice(0, BODY_LIMIT) } export async function createGithubIssue(config: GithubConfig, issue: MirroredIssue, app?: string) { @@ -178,8 +181,8 @@ export async function mirrorIssue(db: Database, env: Env, id: string, stale = fa const details = JSON.parse(row.public_json) as PublicBugDetails // Only reporters who agreed to publish them get their configuration and log on GitHub. const log = details.full ? (await db.prepare('SELECT text FROM issue_logs WHERE issue_id=?').bind(id).first<{ text: string }>())?.text : undefined - const context = details.full && row.context_json ? JSON.parse(row.context_json) as IssueContext : undefined - const created = await createGithubIssue(config, { id: row.id, module_id: row.module_id, scope: row.scope, moduleIds, title: row.title, reporter: row.reporter, owners, details, context, log }, env.APP_URL) + const context = details.full && row.context_json ? JSON.parse(row.context_json) as IssueContext & { usb?: SupportAttachment } : undefined + const created = await createGithubIssue(config, { id: row.id, module_id: row.module_id, scope: row.scope, moduleIds, title: row.title, reporter: row.reporter, owners, details, context, log, ...(context?.usb ? { usb: context.usb } : {}) }, env.APP_URL) await db.prepare("UPDATE issues SET github_state='synced',github_number=?,github_url=?,github_error='' WHERE id=?").bind(created.number, created.url, id).run() return { state: 'synced' as const, url: created.url } } catch (error) { diff --git a/server/kofi.ts b/server/kofi.ts new file mode 100644 index 0000000000..f0547adfda --- /dev/null +++ b/server/kofi.ts @@ -0,0 +1,36 @@ +import type { Database, Env } from './platform' +import { boundedBody, HttpError, response } from './security' + +/** Ko-fi posts each payment server-to-server: a form field `data` holding JSON with the account's verification token. + * Only Ko-fi's message ID (so a repeated delivery counts once), the UTC month, the amount, the currency and whether it + * counts are kept. The payer's name, email address, message and links are read for nothing but the test check and dropped. + * Donations and subscriptions count toward the running costs; shop orders and commissions do not. A payer at example.com + * (reserved for examples, RFC 2606) is Ko-fi's "Send test" and never counts. */ +const COUNTED_TYPES = new Set(['Donation', 'Subscription']) + +function sameText(a: string, b: string) { if (a.length !== b.length) return false; let difference = 0; for (let index = 0; index < a.length; index++) difference |= a.charCodeAt(index) ^ b.charCodeAt(index); return difference === 0 } + +export async function kofiWebhook(request: Request, env: Env, db: Database) { + const token = env.KOFI_VERIFICATION_TOKEN?.trim() ?? '' + if (!token) throw new HttpError(503, 'Ko-fi payments are not connected.') + let payload: Record | null = null + try { payload = JSON.parse(new URLSearchParams(new TextDecoder().decode(await boundedBody(request, 16 * 1024))).get('data') ?? '') } catch { /* refused below */ } + if (!payload || typeof payload !== 'object') throw new HttpError(400, 'Invalid payload.') + if (typeof payload.verification_token !== 'string' || !sameText(payload.verification_token, token)) throw new HttpError(401, 'Invalid token.') + const id = payload.message_id, type = payload.type, currency = payload.currency, amount = Number(payload.amount) + if (typeof id !== 'string' || !/^[A-Za-z0-9-]{8,64}$/.test(id) || typeof type !== 'string' || typeof currency !== 'string' || !/^[A-Z]{3}$/.test(currency) || !Number.isFinite(amount) || amount < 0 || amount > 100000) throw new HttpError(400, 'Invalid payment.') + const test = typeof payload.email === 'string' && /@example\.com$/i.test(payload.email.trim()) + const time = typeof payload.timestamp === 'string' ? Date.parse(payload.timestamp) : NaN + const month = new Date(Number.isFinite(time) ? time : Date.now()).toISOString().slice(0, 7) + await db.prepare('INSERT INTO kofi_payments(message_id,month,amount_cents,currency,counted) VALUES(?,?,?,?,?) ON CONFLICT(message_id) DO NOTHING') + .bind(id, month, Math.round(amount * 100), currency, COUNTED_TYPES.has(type) && !test ? 1 : 0).run() + return response({ ok: true }) +} + +/** Public: this UTC month's counted Ko-fi payments in euros for the support dialogs, or null while the webhook is not set up. */ +export async function kofiCoverage(env: Env, db: Database, now = new Date()) { + const month = now.toISOString().slice(0, 7) + if (!env.KOFI_VERIFICATION_TOKEN?.trim()) return response({ month, euros: null }) + const row = await db.prepare("SELECT COALESCE(SUM(amount_cents),0) AS cents FROM kofi_payments WHERE month=? AND counted=1 AND currency='EUR'").bind(month).first<{ cents: number }>() + return response({ month, euros: (row?.cents ?? 0) / 100 }) +} diff --git a/server/platform.ts b/server/platform.ts index 24e12a1f36..ebcff3d63e 100644 --- a/server/platform.ts +++ b/server/platform.ts @@ -12,7 +12,7 @@ export interface Bucket { } /** A Durable Object namespace, as far as the remote session relay uses it. */ export interface DurableNamespace { idFromName(name: string): unknown; get(id: unknown): { fetch(request: Request): Promise } } -export type Env = { DB?: Database; MEDIA?: Bucket; REMOTE_SESSIONS?: DurableNamespace; APP_URL?: string; SESSION_TRANSPORT?: 'cookie' | 'bearer'; REGISTRATION_OPEN?: string; PRIVACY_READY?: string; ADMIN_KEY_SHA256?: string; DIAGNOSTICS_READ_KEY_SHA256?: string; RESEND_API_KEY?: string; EMAIL_FROM?: string; AUTH_SECRET?: string; AUTH_BASE_URL?: string; SSO_GOOGLE_CLIENT_ID?: string; SSO_GOOGLE_CLIENT_SECRET?: string; SSO_GITHUB_CLIENT_ID?: string; SSO_GITHUB_CLIENT_SECRET?: string; SSO_DISCORD_CLIENT_ID?: string; SSO_DISCORD_CLIENT_SECRET?: string; GITHUB_OAUTH_CLIENT_ID?: string; GITHUB_OAUTH_CLIENT_SECRET?: string; GITHUB_OAUTH_CALLBACK_URL?: string; GITHUB_TOKEN?: string; GITHUB_REPOSITORY?: string; RELEASE_REPOSITORY_ID?: string; RELEASE_REPOSITORY_OWNER_ID?: string; GITHUB_WEBHOOK_SECRET?: string; ACCOUNT_MAIL_DAILY_LIMIT?: string; ACCOUNT_MAIL_MONTHLY_LIMIT?: string; RESET_MAIL_DAILY_LIMIT?: string; RESET_MAIL_MONTHLY_LIMIT?: string; WELCOME_MAIL_DAILY_LIMIT?: string; WELCOME_MAIL_MONTHLY_LIMIT?: string; ACTIVITY_MAIL_DAILY_LIMIT?: string; ACTIVITY_MAIL_MONTHLY_LIMIT?: string; NEWS_MAIL_DAILY_LIMIT?: string; NEWS_MAIL_MONTHLY_LIMIT?: string; WELCOME_MAIL_ENABLED?: string; WEB_PUSH_ENABLED?: string; VAPID_PUBLIC_KEY?: string; VAPID_PRIVATE_KEY?: string; VAPID_SUBJECT?: string; MAINTENANCE_BOT_KEY_SHA256?: string; MAINTENANCE_BOT_GITHUB_TOKEN?: string; TELEGRAM_BOT_TOKEN?: string; TELEGRAM_CHAT_ID?: string; TELEGRAM_WEBHOOK_SECRET?: string } +export type Env = { DB?: Database; MEDIA?: Bucket; REMOTE_SESSIONS?: DurableNamespace; APP_URL?: string; SESSION_TRANSPORT?: 'cookie' | 'bearer'; REGISTRATION_OPEN?: string; PRIVACY_READY?: string; ADMIN_KEY_SHA256?: string; DIAGNOSTICS_READ_KEY_SHA256?: string; RESEND_API_KEY?: string; EMAIL_FROM?: string; AUTH_SECRET?: string; AUTH_BASE_URL?: string; SSO_GOOGLE_CLIENT_ID?: string; SSO_GOOGLE_CLIENT_SECRET?: string; SSO_GITHUB_CLIENT_ID?: string; SSO_GITHUB_CLIENT_SECRET?: string; SSO_DISCORD_CLIENT_ID?: string; SSO_DISCORD_CLIENT_SECRET?: string; GITHUB_OAUTH_CLIENT_ID?: string; GITHUB_OAUTH_CLIENT_SECRET?: string; GITHUB_OAUTH_CALLBACK_URL?: string; GITHUB_TOKEN?: string; GITHUB_REPOSITORY?: string; RELEASE_REPOSITORY_ID?: string; RELEASE_REPOSITORY_OWNER_ID?: string; GITHUB_WEBHOOK_SECRET?: string; ACCOUNT_MAIL_DAILY_LIMIT?: string; ACCOUNT_MAIL_MONTHLY_LIMIT?: string; RESET_MAIL_DAILY_LIMIT?: string; RESET_MAIL_MONTHLY_LIMIT?: string; WELCOME_MAIL_DAILY_LIMIT?: string; WELCOME_MAIL_MONTHLY_LIMIT?: string; ACTIVITY_MAIL_DAILY_LIMIT?: string; ACTIVITY_MAIL_MONTHLY_LIMIT?: string; NEWS_MAIL_DAILY_LIMIT?: string; NEWS_MAIL_MONTHLY_LIMIT?: string; WELCOME_MAIL_ENABLED?: string; WEB_PUSH_ENABLED?: string; VAPID_PUBLIC_KEY?: string; VAPID_PRIVATE_KEY?: string; VAPID_SUBJECT?: string; MAINTENANCE_BOT_KEY_SHA256?: string; MAINTENANCE_BOT_GITHUB_TOKEN?: string; TELEGRAM_BOT_TOKEN?: string; TELEGRAM_CHAT_ID?: string; TELEGRAM_WEBHOOK_SECRET?: string; KOFI_VERIFICATION_TOKEN?: string } export type User = { id: string; display_name: string; username?: string | null; avatar_id?: string | null; email_verified?: number; suspended?: number; is_admin?: number; beta_tester?: number; github_id?: string; github_login?: string } export type Submission = { id: string; owner_id: string; module_id: string; title: string; repository_url: string; description: string; usage: string; test_report_url: string; stress_notes: string; quality_notes: string; resource_notes: string; license: string; status: 'draft' | 'pending' | 'approved' | 'rejected'; review_note: string; created_at: string } export type Media = { id: string; submission_id: string; kind: 'image' | 'audio'; mime: string; caption: string; capture_type: string; object_key: string } diff --git a/server/support-attachment.ts b/server/support-attachment.ts new file mode 100644 index 0000000000..d137dc9ca5 --- /dev/null +++ b/server/support-attachment.ts @@ -0,0 +1,38 @@ +import { HttpError } from './security' +import { validateDiagnostic } from './octatrack-diagnostics' +import { DIAGNOSTIC_USB_EVENTS } from '../src/community/octatrack-diagnostics-contract' +import { SUPPORT_ATTACHED_EVENTS, SUPPORT_LAYOUTS, type SupportAttachment, type SupportEvent } from '../src/community/support-report' + +const object = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v) +const hash = (v: unknown) => typeof v === 'string' && /^[a-f0-9]{64}$/.test(v) +/** validateDiagnostic wants a record id; an attached event has none of its own. */ +const NO_ID = '00000000-0000-4000-8000-000000000000' +/** The link's own events: no device log (the collector reads that, not the link) and no browser or build events. */ +const LINK_EVENTS: readonly string[] = [...DIAGNOSTIC_USB_EVENTS.filter(event => event !== 'device_log'), 'link_failed'] +const refuse = (): never => { throw new HttpError(400, 'The attached USB events are unreadable. Remove them and post the report again.') } +const checked = (record: Record) => { try { return validateDiagnostic({ id: NO_ID, ...record }) } catch { return refuse() } } + +/** + * USB events a member attached to a problem report (support-report.ts): the trail's records, each held to the shared + * diagnostics' field rules (validateDiagnostic), with when the page saw it, plus the unit's base, version, layout, model + * text and running set, and the browser family. Anything else is refused, so no free text reaches the issue. + */ +export function validateSupportAttachment(value: unknown): SupportAttachment { + if (!object(value) || value.schema !== 1 || !Object.keys(value).every(key => ['schema', 'unit', 'client', 'events'].includes(key))) return refuse() + const { unit, client, events } = value + if (unit !== undefined && !(object(unit) && Object.keys(unit).every(key => ['base', 'version', 'layout', 'model', 'active'].includes(key)) && hash(unit.base) + && (unit.version === undefined || typeof unit.version === 'string' && /^[0-9]{1,3}(?:\.[0-9]{1,3}){1,3}$/.test(unit.version)) + && (unit.layout === undefined || SUPPORT_LAYOUTS.includes(unit.layout as string)) + && (unit.model === undefined || typeof unit.model === 'string' && /^[A-Za-z0-9 ._+-]{1,16}$/.test(unit.model)) + && (unit.active === undefined || hash(unit.active)))) return refuse() + if (client !== undefined) checked({ event: 'connected', phase: 'ready', client }) + if (!Array.isArray(events) || !events.length || events.length > SUPPORT_ATTACHED_EVENTS) return refuse() + const list = events.map(entry => { + if (!object(entry) || typeof entry.at !== 'string' || entry.at.length > 30 || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?Z$/.test(entry.at) || !Number.isFinite(Date.parse(entry.at))) return refuse() + const { at, ...record } = entry + if (!LINK_EVENTS.includes(record.event as string) || 'modules' in record || 'client' in record) return refuse() + checked(record) + return { at, ...record } as SupportEvent + }) + return { schema: 1, ...(unit ? { unit: unit as unknown as SupportAttachment['unit'] } : {}), ...(client ? { client: client as SupportAttachment['client'] } : {}), events: list } +} diff --git a/src/App.tsx b/src/App.tsx index 515bb4ba97..ae76c773d4 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -88,7 +88,7 @@ import type { ZoomLink } from './engine/zoom/zoom-link' import { DIGI_DEVICES, DIGI_MODS, isDigiDevice, type DigiMod } from './devices/digi-mods' import { configurationDevice, type Configuration } from './config/workspace' import './devices/devices.css' -import { SupportButton, SupportDialog } from './components/SupportDialog' +import { SupportButton, SupportDialog, SupportMilestone, SupportMilestonePreview } from './components/SupportDialog' import { OverviewPage } from './overview/OverviewPage' import { DevelopCard } from './overview/DevelopCard' import { developHighlight, machineOverview } from './overview/overview' @@ -133,6 +133,7 @@ const MoreModsPrompt = lazy(() => import('./components/MoreModsPrompt').then(mod const BetaModuleSets = lazy(() => beta().then(module => ({ default: module.BetaModuleSets }))) const FirmwareFeedbackPreview = import.meta.env.DEV ? lazy(() => import('./components/FirmwareFeedbackPreview')) : () => null const firmwareFeedbackPreview = import.meta.env.DEV && typeof window !== 'undefined' && new URLSearchParams(window.location.search).get('preview') === 'firmware-feedback' +const supportThanksPreview = import.meta.env.DEV && typeof window !== 'undefined' && new URLSearchParams(window.location.search).get('preview') === 'support-thanks' // Dev previews of the USB card and the base install prompt against a pretend unit. const usbPreview = import.meta.env.DEV && typeof window !== 'undefined' ? new URLSearchParams(window.location.search).get('preview') : null const usbLinkPreview = usbPreview === 'usb-link' || usbPreview === 'screen' || usbPreview === 'base-install' @@ -661,6 +662,7 @@ export default function App() { {supportOpen && setSupportOpen(false)} />} +
@@ -687,6 +689,7 @@ export default function App() {
{firmwareFeedbackPreview && } + {supportThanksPreview && } {!accountRoute && } {!accountRoute && !developerRoute && !configuration && machineView !== 'configuration' && !adminRoute && !['privacy', 'impressum', 'community-rules', 'modding-guidelines', 'report-content'].includes(route) && } {workspace.storageError &&
{workspace.storageError} Export important configurations before closing this tab.
} diff --git a/src/catalog/module-authors.test.ts b/src/catalog/module-authors.test.ts index 7222c60f27..82b605b0ff 100644 --- a/src/catalog/module-authors.test.ts +++ b/src/catalog/module-authors.test.ts @@ -1,12 +1,22 @@ import { describe, expect, it } from 'vitest' import { MODULES } from './modules' import { DISPLAY_AUTHORS, displayName, ownerCredit } from './module-authors' +import { COMMUNITY_MODULES } from '../community/modules' describe('module credits', () => { it('shows a port under its original author alone, while its porter keeps it', () => { const chorus = MODULES.find(module => module.id === 'airwindows-chorus')! expect(chorus).toMatchObject({ author: 'repeat98', authorName: 'Chris Johnson', authorUrl: 'https://github.com/airwindows' }) expect(chorus.contributors ?? []).toEqual([]) + const mackity = MODULES.find(module => module.id === 'mackity')! + expect(mackity).toMatchObject({ author: 'repeat98', authorName: 'Chris Johnson', authorUrl: 'https://github.com/airwindows' }) + expect(mackity.contributors ?? []).toEqual([]) + }) + it('never pings a display author on reports: maintainers come from the manifest author', () => { + for (const [id, shown] of Object.entries(DISPLAY_AUTHORS)) { + const module = COMMUNITY_MODULES.find(entry => entry.moduleId === id && entry.machine === 'octatrack')! + expect(module.maintainers).not.toContain(shown.github) + } }) it('names the owner on every module they author', () => { const owned = MODULES.filter(module => module.author === 'repeat98' && !DISPLAY_AUTHORS[module.id]) diff --git a/src/catalog/module-authors.ts b/src/catalog/module-authors.ts index 5a1fd17d38..14a1fedc20 100644 --- a/src/catalog/module-authors.ts +++ b/src/catalog/module-authors.ts @@ -11,7 +11,10 @@ export const ownerCredit = (text: string) => text.replace(/Jannik A(?:ss|ß)falg /** Ports shown under their original author's name in place of their porter's, everywhere the site names an author, and * without a support cup (owner, 17 November 2026). Display only: the manifest's author still owns and releases the module. */ -export const DISPLAY_AUTHORS: Readonly>> = { 'airwindows-chorus': { github: 'airwindows', name: 'Chris Johnson' } } +export const DISPLAY_AUTHORS: Readonly>> = { + 'airwindows-chorus': { github: 'airwindows', name: 'Chris Johnson' }, + mackity: { github: 'airwindows', name: 'Chris Johnson' }, +} export const contributorSearchText = (contributors?: readonly ModuleContributor[]) => contributors?.map(person => person.github + ' ' + (person.name ?? '')).join(' ') ?? '' diff --git a/src/catalog/module-documents.json b/src/catalog/module-documents.json index a36c26a915..cf862fe0d1 100644 --- a/src/catalog/module-documents.json +++ b/src/catalog/module-documents.json @@ -4134,6 +4134,287 @@ } ] }, + { + "schemaVersion": 2, + "id": "mackity", + "key": "MACKITY", + "name": "Mackity", + "version": "0.1.0-experimental", + "category": "effects", + "source": { + "repository": "https://github.com/airwindows/airwindows", + "revision": "e718c9bcfcdd736deeddb08bffe6bce2aa8e0eea", + "path": "plugins/LinuxVST/src/Mackity" + }, + "access": { + "location": "FUNC + FX1 or FUNC + FX2 SETUP on an audio track: the effect chooser. TRIM and PAD are on the FX page (knobs A and B).", + "steps": [ + "Select an audio track that plays a sample.", + "Hold FUNC and press FX1 (or FX2) to open its SETUP. Turn LEVEL to Mackity and press YES.", + "Press FX1 (or FX2) for its page: TRIM on knob A, PAD on knob B.", + "Set TRIM 13 and PAD 127 for the desk's colour at unchanged level, or select NONE to remove it." + ], + "screenshots": [ + "media/mackity-chooser.png", + "media/mackity-main.png" + ] + }, + "author": { + "github": "repeat98", + "credits": [ + "Chris Johnson / Airwindows: original Mackity algorithm and MIT-licensed source" + ] + }, + "nativeManifest": "manifest.py", + "presentation": { + "label": "MACKITY", + "family": "Saturation", + "summary": "Chris Johnson's Airwindows Mackity: the input stage of a Mackie-style mixing desk, driven by IN TRIM, on FX1 or FX2 of any track.", + "overview": "Mackity is Airwindows' model of a Mackie-style desk's input stage. The track's audio passes a gentle low cut, the desk's high-frequency rolloff, the IN TRIM gain and the console's clip, rounded by its curve, then a second rolloff and a DC blocker. At TRIM 13 it adds only the desk's colour; turning TRIM up drives the channel into the clip, from warm thickening to hard, square distortion. PAD sets the output level. The algorithm is upstream's, unchanged, in 24-bit fixed point at the Octatrack's 44.1 kHz.", + "highlights": [ + "Upstream's complete Mackity algorithm, credited to Chris Johnson", + "TRIM from silence through 0 dB (13) to +39.6 dB into the console's clip", + "Stereo and buffer-free: FX1 or FX2 on any track" + ], + "usage": [ + "Put MACKITY on FX1 of a drum or bass track. At TRIM 13 and PAD 127 it adds the desk's colour without a change in level.", + "Turn TRIM up for drive: at 26 (+12 dB) a track peaking at -12 dBFS reaches the clip, and above that it clips harder.", + "Turn PAD down to set the output level after heavy drive." + ] + }, + "controls": [ + { + "name": "TRIM", + "default": 13, + "count": 128, + "doc": "In Trim: the gain into the desk, (TRIM/13)^2 as in the original. 13 is 0 dB, 26 is +12 dB, 52 is +24 dB, 127 is +39.6 dB; 0 is silence. More gain drives the signal into the console's clip.", + "labels": null + }, + { + "name": "PAD", + "default": 127, + "count": 128, + "doc": "Out Pad: the output level, PAD/128; 127 is exactly 0 dB, 64 is -6 dB, 0 is silence. With heavy drive the desk's rolloff peaks up to about 0.6 dB over full scale, which the Octatrack's output limits; PAD 120 or lower keeps every peak.", + "labels": null + } + ], + "compatibility": { + "firmware": "1.40C", + "effectId": 26, + "location": "FX1 / FX2", + "conflicts": [], + "uiClaims": [], + "limitations": [ + "At high TRIM the clip makes harmonics above 22 kHz that fold back below it, as the original does at 44.1 kHz.", + "With heavy drive, peaks up to about 0.6 dB over full scale are limited by the Octatrack's output; PAD 120 or lower keeps them.", + "On a pattern that already fills the CPU, a pick can be refused with CPU FULL (it asks +3 % on a busy eight-track pattern).", + "Tested on one MKII by the test procedure; the MKI, a Part or project reload with it saved and a power cycle were not tested by hand.", + "The original's 32-bit float dither is left out: the Octatrack's path is 24-bit fixed point." + ] + }, + "resources": { + "recorded": "2026-11-25", + "storage": { + "label": "DSP program / state", + "display": "208 words / 32-word state", + "value": null, + "unit": "see display", + "method": "static", + "conditions": "The USB package's DSP effect: 208 program words on each DSP core it runs on; 32 words of the 256-word X block per instance (31 used); no buffer, no Y memory, no ColdFire code per frame.", + "source": "TESTING.md" + }, + "processing": { + "label": "DSP instruction peak", + "display": "228 instructions/sample per instance", + "value": null, + "unit": "see display", + "method": "emulator", + "conditions": "perf.py in dsp_host, 48 cases (defaults, TRIM 127, moving knobs, each unsplit and with a trig split at 1-15): worst 228.2 with a 1-frame split, 225.3 unsplit at every setting, against 290.1 for LO-FI and 330.9 for DJ EQ, the dearest stock effect. On the unit the DSP meter on T1-T4 rose 8.1 points with it on T1 FX2. Executed instructions, not chip cycles.", + "source": "TESTING.md" + }, + "impact": { + "conditions": "One active instance at the dearest setting (TRIM 127) with moving knobs and trig splits; no buffer; on the unit, the frame-interrupt price on a medium pattern.", + "cpu": { + "level": "minimal", + "basis": "measured-comparison", + "rationale": "No ColdFire audio code: the stock FX page publishes the knobs. On the owner's MKII the frame interrupt rose 0.1 points with it on T1 FX2 and 0 installed and unused; the instance curve read first 0.9, each 0.9.", + "source": "TESTING.md" + }, + "dsp": { + "level": "moderate", + "basis": "measured-comparison", + "rationale": "228.2 executed instructions/sample worst case with trig splits, 0.79 of LO-FI (290.1) and 0.69 of DJ EQ (330.9), the dearest stock effect, under matching cases; the static bound for four per core is 1,004 of 3,120 cycles a sample. Chip timing is unmeasured.", + "source": "TESTING.md" + }, + "memory": { + "level": "low", + "basis": "source-estimate", + "rationale": "208 program words per core, 32 words of the 256-word X block per instance, no buffer.", + "source": "TESTING.md" + } + }, + "cpuPrice": { + "value": 0.1, + "unit": "percent-of-frame", + "measure": "frame-interrupt", + "tool": "npm run device:price -- --write", + "date": "2026-11-25", + "conditions": "Project on the owner's development unit, bank C, Part 1 reloaded in RAM to its saved copy; picks on the empty C02, readings on C04 (trigs on steps 1/5/9/13 of T1-T4, T6, T7) at the project tempo; transport played by the tool; base development twin 8fd6d456 of base 0.8.1 (eb6679620d0c9ed7), the owner's MKII, OS 1.40C; 3 readings of 8 s a state. Frame interrupt 32.2 % before, 32.2 % installed and used nowhere, 32.3 % on T1 FX2; CPU meter 55.7 % before, 55.7 % at rest, 55.7 % in use.", + "source": "evidence/cpu-price.json" + } + }, + "tests": { + "report": "TESTING.md", + "summary": "verify.py matches the bit-exact model in dsp_host in every case; test_reference.py holds the model to upstream's algorithm; perf:audit passes at 0.79 of LO-FI's worst; npm run test:procedure steps 1-10 passed on the owner's MKII (25 Nov 2026), with the soak, the CPU price and the instance curve, and the screens captured on the unit.", + "hardwareStatus": "reported", + "evidenceRevision": "ccbb96b6c06ae074159be45d66f69812d450793f", + "gates": [ + "Worst-case cycles under parameter modulation and maximum load", + "Exact memory region and maximum-instance totals", + "Owner-reviewed real-hardware evidence with actual coverage and limitations" + ], + "qualification": { + "documentation": { + "tutorial": { + "title": "Quick tutorial", + "steps": [ + "Put MACKITY on FX1 of a drum loop's track: hold FUNC, press FX1, turn LEVEL to Mackity and press YES. At TRIM 13 and PAD 127 the loop keeps its level and gains the desk's colour.", + "Turn TRIM to 40 on the FX1 page. The loop thickens and its peaks flatten into the clip; turn PAD to about 90 to bring the level back down.", + "Set TRIM 13 and PAD 127 to return to the clean desk, or select NONE in the FX1 chooser to remove it." + ] + }, + "screenshots": [ + "media/mackity-chooser.png", + "media/mackity-main.png" + ], + "screenshotStyle": "black-and-white" + }, + "moduleVersion": "0.1.0-experimental", + "sourceSha256": "7271f6d9bb015b103e2048bf65912cd8b78bdcbe6205c37cb58f7434f22af846", + "imageSha256": "af4934ce5cdbc9816bc49864bd8848a6bad0af9af692b6752f330749b5f1b5c6", + "cycles": [ + { + "processor": "dsp", + "worstCase": 4078, + "maxConfiguration": 16312, + "maxInstances": 8, + "budget": 49920, + "unit": "cycles/block", + "method": "static", + "conditions": { + "parameterExtremes": "Static bound per 16-frame block from the assembled words (perf.py): the per-sample loop's 21 words plus twice the 115-word channel routine, 251 cycles a sample (x16 = 4,016), plus the 62-word per-call setup (knob decode, seeding, the glides' snap) charged once per call. The loop and the routine have no conditional branch, so every knob value runs the same words.", + "parameterModulation": "Two calls per block cover a trig split: 16 x 251 + 2 x 31 = 4,078 (the setup's words split between its two halves, each charged on every call). LFOs, locks, scenes and CC reach the same two knob words, decoded every call and glided per sample. The dsp_host measurement with moving knobs and splits at 1-15 read at most 228.2 executed instructions a sample (3,651 a block), inside the bound.", + "modeSwitching": "Mackity has no modes: TRIM and PAD are continuous and run the same code at every value. Part changes reach it as knob changes.", + "maxLoad": "Eight instances, four per DSP core (FX2 of four tracks, or FX1 and FX2 of two): 4 x 4,078 = 16,312 per core within the SDK's 49,920 module allowance (3,120 a sample x 16). On the unit, eight at once while playing ran with CPU 458 and DSP peaks 663 and 743 per mille (device:test). The 2 s eight-instance dsp_host stress run peaked at 913.0 executed instructions a sample per core (evidence/performance.json). Real-chip contention and stalls are not modelled.", + "inputConditions": "The bound does not depend on sample values: silence, impulses, full-scale and clipping input run the same straight-line code. The stress stems include full-scale squares, impulses, DC steps, noise and a 20 Hz-20 kHz sweep." + }, + "report": "evidence/performance.json" + } + ], + "memory": { + "regions": [ + { + "name": "DSP program, the package's effect on each core it runs on", + "space": "dsp-p", + "words": 208, + "wordBits": 24, + "bytes": 624, + "scope": "shared" + }, + { + "name": "Used and initialized stock X state, r7+0..0x1f", + "space": "dsp-x", + "words": 32, + "wordBits": 24, + "bytes": 96, + "scope": "instance" + }, + { + "name": "Reserved remainder of the 256-word stock X block", + "space": "dsp-x", + "words": 224, + "wordBits": 24, + "bytes": 672, + "scope": "instance" + }, + { + "name": "System stack, one bsr inside the sample loop's do, on both cores", + "space": "dsp-x", + "words": 8, + "wordBits": 24, + "bytes": 24, + "scope": "shared" + } + ], + "perInstanceBytes": 768, + "sharedBytes": 648, + "maxInstances": 8, + "totalBytes": 6792, + "conditions": "The USB package (472 bytes of code and data, no bss, one DSP effect of 208 words) as the Modwerk base loads it into each core's DSP arena; per instance the stock 256-word r7 block an FX instance gets, of which Mackity initializes $00-$1f and uses $00-$1e; no allocator buffer, no Y memory (ybase NEVER), no scratch outside r7. The system stack holds the do loop and one bsr. Logical 24-bit DSP words.", + "report": "TESTING.md" + }, + "hardware": { + "kind": "functional", + "status": "reported", + "model": "MKII", + "testedOn": "2026-11-25", + "tester": "repeat98", + "sourceRevision": "ccbb96b6c06ae074159be45d66f69812d450793f", + "imageSha256": "af4934ce5cdbc9816bc49864bd8848a6bad0af9af692b6752f330749b5f1b5c6", + "summary": "On the owner's Octatrack MKII (OS 1.40C), RAM-booted on development twin 8fd6d456 of base 0.8.1 (imageSha256 is that twin's MAIN image), the agent in the owner's session ran npm run test:procedure on the package of this source (5a58d4cc): software checks, the cost model, device:test (alone on FX2 of T1 and T5, eight at once while playing, 12 Part switches), a 2-minute soak, device:price with the instance curve and admission on the empty C02 and the medium C04, and the inventory put back; all passed. Earlier the same day, a 30-second RAM trial on the release base 0.8.1 and device:test on an empty bank passed too. The screens were read off the unit's LCD during a trial. The owner asked for it to be released without the hands-on stage (25 Nov 2026: \"you can merge and get it live yourself\").", + "limitations": [ + "One unit and its owner's session, not an independent reviewer; the MKI was not tested.", + "The owner's listening, a Part and project save and reload, and the Keep with a power cycle were not run by hand.", + "MAIN and CUE were not recorded over USB.", + "Single 8-s readings of the DSP load scatter by about a point; the DSP cost stands on dsp_host's count.", + "A card build beside Analog BD was not built or placed." + ], + "report": "TESTING.md" + } + } + }, + "license": { + "spdx": "MIT", + "file": "LICENSE", + "declaration": "Chris Johnson's published Mackity source and his full MIT copyright and permission notice are retained in upstream/ and LICENSE; the Octatrack adaptation is distributed under the same terms. No desktop binary, firmware, extracted stock routine or table, or memory dump is included." + }, + "media": [ + { + "path": "media/mackity-chooser.png", + "captureType": "hardware", + "caption": "Select an audio track, hold FUNC and press FX1. Turn LEVEL down the list to Mackity and press YES to put it on FX1 (FX2 works the same).", + "alt": "Octatrack FX1 SETUP: the effect list from FLANGER to LO-FI with the cursor on Mackity.", + "credit": "Modwerk documentation capture; underlying Octatrack UI by Elektron", + "license": "LicenseRef-OT-UI-Documentation", + "source": "original", + "otUi": { + "page": "FX1 SETUP (effect chooser)", + "shows": "location", + "firmware": "1.40C", + "moduleVersion": "0.1.0-experimental", + "imageSha256": "af4934ce5cdbc9816bc49864bd8848a6bad0af9af692b6752f330749b5f1b5c6", + "setup": "Captured over USB from the LCD of the owner's Octatrack MKII (OS 1.40C, development twin 8fd6d456 of Modwerk base 0.8.1, RAM-booted; imageSha256 is that twin's MAIN image) with the development session's png step on 25 November 2026, during a RAM trial of this version's package 5a58d4cc, built by module:dev from source ccbb96b6c. 256x128, the 128x64 LCD at integer scale 2, two grey levels, not edited." + } + }, + { + "path": "media/mackity-main.png", + "captureType": "hardware", + "caption": "Press FX1 for its page: TRIM (knob A) drives the desk, 13 is 0 dB; PAD (knob B) sets the output level, 127 is 0 dB.", + "alt": "Octatrack FX1 page of track 2 running Mackity: knobs TRIM and PAD, FX1 Mackity in the bottom line.", + "credit": "Modwerk documentation capture; underlying Octatrack UI by Elektron", + "license": "LicenseRef-OT-UI-Documentation", + "source": "original", + "otUi": { + "page": "FX1", + "shows": "controls", + "firmware": "1.40C", + "moduleVersion": "0.1.0-experimental", + "imageSha256": "af4934ce5cdbc9816bc49864bd8848a6bad0af9af692b6752f330749b5f1b5c6", + "setup": "Captured over USB from the LCD of the owner's Octatrack MKII (OS 1.40C, development twin 8fd6d456 of Modwerk base 0.8.1, RAM-booted; imageSha256 is that twin's MAIN image) with the development session's png step on 25 November 2026, during a RAM trial of this version's package 5a58d4cc, built by module:dev from source ccbb96b6c. 256x128, the 128x64 LCD at integer scale 2, two grey levels, not edited." + } + } + ] + }, { "schemaVersion": 2, "id": "analog-bassdrum", diff --git a/src/community/ConfigurationReport.tsx b/src/community/ConfigurationReport.tsx index 4c3cbbe739..92ebbd2327 100644 --- a/src/community/ConfigurationReport.tsx +++ b/src/community/ConfigurationReport.tsx @@ -1,4 +1,6 @@ -import { useEffect, useId, useRef, useState, type FormEvent } from 'react' +import { useContext, useEffect, useId, useRef, useState, type FormEvent } from 'react' +import { OctatrackLinkContext } from '../hooks/useOctatrackLink' +import { SUPPORT_ATTACHED_EVENTS, supportBase, supportLines } from './support-report' import { createPortal } from 'react-dom' import { Icon } from '../components/Icon' import { DEVICES_BY_ID } from '../devices/registry' @@ -23,7 +25,13 @@ export function ConfigurationReportDialog({ machine, configurationId, onClose }: const dialog = useRef(null), heading = useId(), success = useRef(null), logHelp = useId() const { session } = useCommunity(), workspace = useWorkspaceReportContext(machine), device = DEVICES_BY_ID[machine] const { file, input: logInput, read: readLog, remove: removeLog } = useOtLogFile(), digi = machine !== 'octatrack' - const [model, setModel] = useState(''), [flash, setFlash] = useState('') + // The USB link fills in what it knows, all of it editable: what the Octatrack runs, the last error the page showed, + // and its recent USB events, which the reporter sees and can remove before posting (support-report.ts). IDENTIFY names + // the stock OS, not MKI or MKII, so the model stays the reporter's choice. + const link = useContext(OctatrackLinkContext), usbLink = digi ? null : link + const [attachment] = useState(() => usbLink?.supportAttachment?.(SUPPORT_ATTACHED_EVENTS)) + const [attach, setAttach] = useState(() => !!attachment?.events.length), lastError = usbLink?.trail?.lastError?.text ?? '' + const [model, setModel] = useState(''), [flash, setFlash] = useState(() => usbLink?.getState().identity ? 'usb' : '') const [sent, setSent] = useState(null), [busy, setBusy] = useState(false), [error, setError] = useState('') useEffect(() => { const element = dialog.current, previousFocus = document.activeElement @@ -50,7 +58,7 @@ export function ConfigurationReportDialog({ machine, configurationId, onClose }: const context: IssueContext = digi ? { machine: machine as 'digitakt' | 'digitone', model: fields.model, flash: fields.flash as FlashState, os: fields.os, moduleVersion: resolved.modules[0]?.version ?? '', modules: resolved.modules, keepStockFx2: null, build: '' } : { model: model as OtModel, flash: flash as FlashState, os: file.log?.summary.os ?? REPORT_OS, modules: resolved.modules, keepStockFx2: resolved.keepStockFx2, build: resolved.build } - const result = await post('/configuration-reports', { title: fields.title, steps: fields.steps, expected: fields.expected, actual: fields.actual, context, visibility: 'forum', notifyUpdates: fields.notifyUpdates === 'on', ...(file.log ? { log: file.log.text } : {}) }) + const result = await post('/configuration-reports', { title: fields.title, steps: fields.steps, expected: fields.expected, actual: fields.actual, context, visibility: 'forum', notifyUpdates: fields.notifyUpdates === 'on', ...(file.log ? { log: file.log.text } : {}), ...(!digi && attach && attachment?.events.length ? { usbEvents: attachment } : {}) }) setSent(result) for (const module of catalogued) refreshModuleIssues(module.id) window.dispatchEvent(new Event('modwerk-module-updates')) @@ -90,8 +98,15 @@ export function ConfigurationReportDialog({ machine, configurationId, onClose }: {modules > catalogued.length && catalogued.length > 0 &&

{modules - catalogued.length} {modules - catalogued.length === 1 ? 'module is' : 'modules are'} no longer in the catalog and cannot be notified.

} -