diff --git a/.agents/skills/modwerk-contribute/SKILL.md b/.agents/skills/modwerk-contribute/SKILL.md index 62bf888fcd..f33dada60c 100644 --- a/.agents/skills/modwerk-contribute/SKILL.md +++ b/.agents/skills/modwerk-contribute/SKILL.md @@ -1,11 +1,11 @@ --- name: modwerk-contribute -description: Find something worth fixing or improving in Modwerk and send it as a small pull request the owner can merge or decline on its own. Use when a developer wants to help or contribute but has no task or idea of their own. +description: Find something worth fixing or improving in Modwerk and send it as a small pull request a repository maintainer can review independently. Use when a developer wants to help or contribute but has no task or idea of their own. --- # /modwerk-contribute [instrument or area] -You find the work, the developer picks, and each change goes out as its own small pull request. The owner merges what fits and declines the rest, so a pull request must stand alone and be quick to judge. +You find the work, the developer picks, and each change goes out as its own small pull request. A repository maintainer reviews the contributor's PR. A modder submitting a first module uses `/modwerk-new-module` and asks a device reviewer or maintainer to review it. 1. **Ask, in one message:** how they test (their unit over USB, the emulator, or neither yet), and whether they want an instrument or area (the site, the tools, the guides) or leave it to you. Check the setup and sign them in for the board as `/modwerk-start` step 2 does. 2. **Gather candidates** on current `main` (`git fetch upstream` in a fork), in this order: diff --git a/.agents/skills/modwerk-new-module/SKILL.md b/.agents/skills/modwerk-new-module/SKILL.md index 38eae50612..1ce003a005 100644 --- a/.agents/skills/modwerk-new-module/SKILL.md +++ b/.agents/skills/modwerk-new-module/SKILL.md @@ -34,4 +34,4 @@ Follow `docs/ADD_A_MODULE.md` and the rules in `AGENTS.md`, in this order. - 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 fix what applies; - then `/modwerk-pr-ready` and the pull request. - A new module ships in a pull request of its own, and a maintainer of its machine or the owner reviews its first release (`docs/DEVELOPER_WORKFLOW.md#who-reviews-a-first-release`). A push, merge or "Firmware ready" is not a release: after the merge, verify the live version and a saved download. + A new module ships in a pull request of its own, and a device reviewer or repository maintainer reviews and merges its first release. For a new modder, include the submitting author's verified numeric GitHub ID in `.github/module-authors.json` (`docs/DEVELOPER_WORKFLOW.md#who-reviews-a-first-release`). A push, merge or "Firmware ready" is not a release: after the merge, verify the live version and a saved download. diff --git a/.agents/skills/modwerk-pr-ready/SKILL.md b/.agents/skills/modwerk-pr-ready/SKILL.md index 042976a569..587c6e274a 100644 --- a/.agents/skills/modwerk-pr-ready/SKILL.md +++ b/.agents/skills/modwerk-pr-ready/SKILL.md @@ -15,3 +15,4 @@ Follow `docs/DEVELOPER_WORKFLOW.md#make-it-mergeable`. - 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. 5. **Answer what pr:ready asks:** a guide edit for what you learned, or "nothing" in the pull request. +6. **Offer to share the session** when pr:ready prints the session-sharing line: ask the developer once whether to share this session with the owner, and on a yes run `npm run session -- share --note "…"` with a few sentences on what got in the way. "Always" or "never" from the developer goes into `npm run session -- prefer always|never` (`docs/AGENT_SESSIONS.md`). diff --git a/.agents/skills/modwerk-review-prs/SKILL.md b/.agents/skills/modwerk-review-prs/SKILL.md index 6c2b054b06..0943486039 100644 --- a/.agents/skills/modwerk-review-prs/SKILL.md +++ b/.agents/skills/modwerk-review-prs/SKILL.md @@ -1,6 +1,6 @@ --- name: modwerk-review-prs -description: Review Modwerk's open pull requests, answer their authors where something must change or is unclear, then present the invoker with options for each (merge, refresh, wait, decline). Use when the owner or a maintainer asks to review pull requests, or names some to review. +description: Review Modwerk's open pull requests, answer their authors where something must change or is unclear, then present the invoker with options for each (merge, refresh, wait, decline). Use when a device reviewer, the owner or a maintainer asks to review pull requests, or names some to review. --- # /modwerk-review-prs [number ...] @@ -20,7 +20,7 @@ description: Review Modwerk's open pull requests, answer their authors where som - runs waiting for approval (`action_required`): nothing else moves until they run; - what the triage bot's next run would do. - A machine maintainer reviews first releases for their machine and hands an approved release to the owner to merge. Send their own modules and changes outside that scope to the owner for review (`docs/DEVELOPER_WORKFLOW.md#who-reviews-a-first-release`). + A device reviewer handles first releases for their assigned device and checks any new author registry entry against the submitting GitHub account. A repository maintainer can review across devices. For the invoker's own first release, ask another reviewer. When the invoker picks merge on a reviewed submission, get the head SHA they reviewed, submit an APPROVE review bound to it (`gh api repos/OWNER/REPO/pulls/N/reviews -f event=APPROVE -f commit_id=SHA`), then post `/modwerk merge SHA` as a new PR comment. Follow **Merge a reviewed submission** in GitHub Actions. If it starts held first-contributor checks, wait for green and repost the same command on the same head. Follow publication to completion (`docs/DEVELOPER_WORKFLOW.md#who-reviews-a-first-release`). 2. **Talk back where needed**, at most one comment per pull request: a change it must make, a question only its author can answer, or a refresh it needs. - Ask for everything it still needs in that one comment, so the next pass can finish it. - Write plainly and friendly, in the invoker's voice, and post from a file. diff --git a/.claude/skills/modwerk-contribute/SKILL.md b/.claude/skills/modwerk-contribute/SKILL.md index 62bf888fcd..f33dada60c 100644 --- a/.claude/skills/modwerk-contribute/SKILL.md +++ b/.claude/skills/modwerk-contribute/SKILL.md @@ -1,11 +1,11 @@ --- name: modwerk-contribute -description: Find something worth fixing or improving in Modwerk and send it as a small pull request the owner can merge or decline on its own. Use when a developer wants to help or contribute but has no task or idea of their own. +description: Find something worth fixing or improving in Modwerk and send it as a small pull request a repository maintainer can review independently. Use when a developer wants to help or contribute but has no task or idea of their own. --- # /modwerk-contribute [instrument or area] -You find the work, the developer picks, and each change goes out as its own small pull request. The owner merges what fits and declines the rest, so a pull request must stand alone and be quick to judge. +You find the work, the developer picks, and each change goes out as its own small pull request. A repository maintainer reviews the contributor's PR. A modder submitting a first module uses `/modwerk-new-module` and asks a device reviewer or maintainer to review it. 1. **Ask, in one message:** how they test (their unit over USB, the emulator, or neither yet), and whether they want an instrument or area (the site, the tools, the guides) or leave it to you. Check the setup and sign them in for the board as `/modwerk-start` step 2 does. 2. **Gather candidates** on current `main` (`git fetch upstream` in a fork), in this order: diff --git a/.claude/skills/modwerk-new-module/SKILL.md b/.claude/skills/modwerk-new-module/SKILL.md index 38eae50612..1ce003a005 100644 --- a/.claude/skills/modwerk-new-module/SKILL.md +++ b/.claude/skills/modwerk-new-module/SKILL.md @@ -34,4 +34,4 @@ Follow `docs/ADD_A_MODULE.md` and the rules in `AGENTS.md`, in this order. - 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 fix what applies; - then `/modwerk-pr-ready` and the pull request. - A new module ships in a pull request of its own, and a maintainer of its machine or the owner reviews its first release (`docs/DEVELOPER_WORKFLOW.md#who-reviews-a-first-release`). A push, merge or "Firmware ready" is not a release: after the merge, verify the live version and a saved download. + A new module ships in a pull request of its own, and a device reviewer or repository maintainer reviews and merges its first release. For a new modder, include the submitting author's verified numeric GitHub ID in `.github/module-authors.json` (`docs/DEVELOPER_WORKFLOW.md#who-reviews-a-first-release`). A push, merge or "Firmware ready" is not a release: after the merge, verify the live version and a saved download. diff --git a/.claude/skills/modwerk-pr-ready/SKILL.md b/.claude/skills/modwerk-pr-ready/SKILL.md index 042976a569..587c6e274a 100644 --- a/.claude/skills/modwerk-pr-ready/SKILL.md +++ b/.claude/skills/modwerk-pr-ready/SKILL.md @@ -15,3 +15,4 @@ Follow `docs/DEVELOPER_WORKFLOW.md#make-it-mergeable`. - 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. 5. **Answer what pr:ready asks:** a guide edit for what you learned, or "nothing" in the pull request. +6. **Offer to share the session** when pr:ready prints the session-sharing line: ask the developer once whether to share this session with the owner, and on a yes run `npm run session -- share --note "…"` with a few sentences on what got in the way. "Always" or "never" from the developer goes into `npm run session -- prefer always|never` (`docs/AGENT_SESSIONS.md`). diff --git a/.claude/skills/modwerk-review-prs/SKILL.md b/.claude/skills/modwerk-review-prs/SKILL.md index 6c2b054b06..0943486039 100644 --- a/.claude/skills/modwerk-review-prs/SKILL.md +++ b/.claude/skills/modwerk-review-prs/SKILL.md @@ -1,6 +1,6 @@ --- name: modwerk-review-prs -description: Review Modwerk's open pull requests, answer their authors where something must change or is unclear, then present the invoker with options for each (merge, refresh, wait, decline). Use when the owner or a maintainer asks to review pull requests, or names some to review. +description: Review Modwerk's open pull requests, answer their authors where something must change or is unclear, then present the invoker with options for each (merge, refresh, wait, decline). Use when a device reviewer, the owner or a maintainer asks to review pull requests, or names some to review. --- # /modwerk-review-prs [number ...] @@ -20,7 +20,7 @@ description: Review Modwerk's open pull requests, answer their authors where som - runs waiting for approval (`action_required`): nothing else moves until they run; - what the triage bot's next run would do. - A machine maintainer reviews first releases for their machine and hands an approved release to the owner to merge. Send their own modules and changes outside that scope to the owner for review (`docs/DEVELOPER_WORKFLOW.md#who-reviews-a-first-release`). + A device reviewer handles first releases for their assigned device and checks any new author registry entry against the submitting GitHub account. A repository maintainer can review across devices. For the invoker's own first release, ask another reviewer. When the invoker picks merge on a reviewed submission, get the head SHA they reviewed, submit an APPROVE review bound to it (`gh api repos/OWNER/REPO/pulls/N/reviews -f event=APPROVE -f commit_id=SHA`), then post `/modwerk merge SHA` as a new PR comment. Follow **Merge a reviewed submission** in GitHub Actions. If it starts held first-contributor checks, wait for green and repost the same command on the same head. Follow publication to completion (`docs/DEVELOPER_WORKFLOW.md#who-reviews-a-first-release`). 2. **Talk back where needed**, at most one comment per pull request: a change it must make, a question only its author can answer, or a refresh it needs. - Ask for everything it still needs in that one comment, so the next pass can finish it. - Write plainly and friendly, in the invoker's voice, and post from a file. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 170d745ab5..b9caf761d9 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -22,7 +22,7 @@ Registered module authors can opt into [automatic publication](../docs/MODULE_AU - [ ] Automatically merge and publish my module update after checks pass. - [ ] I verified the source, licences, UI and qualification reports, including instance isolation and Part/project/reboot persistence where applicable; no required acceptance check is failed or untested. -Reviewer (a maintainer of its machine or the owner for a first release, the registered author for their own update): +Reviewer (an assigned device reviewer or a repository maintainer for a first release, the registered author for their own update): - [ ] I checked the cycle and memory reports against the worst case, the attributed hardware evidence against the submitted source and build, and the screenshots, tutorial and access steps against the current UI. diff --git a/.github/workflows/review-merge.yml b/.github/workflows/review-merge.yml new file mode 100644 index 0000000000..406e2a0af9 --- /dev/null +++ b/.github/workflows/review-merge.yml @@ -0,0 +1,33 @@ +# SPDX-License-Identifier: Elastic-2.0 +# Copyright (c) 2026 Jannik Aßfalg (repeat98) +name: Merge a reviewed submission +on: + issue_comment: + types: [created] +permissions: + contents: read + pull-requests: read + actions: write # start the checked PR workflow for a first-time contributor +jobs: + review-merge: + if: github.event.issue.pull_request && startsWith(github.event.comment.body, '/modwerk merge ') && vars.MAINTENANCE_BOT_ENABLED == 'true' + runs-on: ubuntu-24.04 + timeout-minutes: 8 + concurrency: + group: reviewed-merge-${{ github.event.issue.number }} + cancel-in-progress: false + steps: + # Only trusted main is executed with the maintenance credential. PR objects are inspected as data. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: main + persist-credentials: false + fetch-depth: 0 + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 + with: + node-version: 24 + - run: node scripts/maintenance-bot/review-merge.mjs + env: + GITHUB_TOKEN: ${{ github.token }} + COMMUNITY_API_URL: ${{ vars.COMMUNITY_API_URL }} + MAINTENANCE_BOT_KEY: ${{ secrets.MAINTENANCE_BOT_KEY }} diff --git a/AGENTS.md b/AGENTS.md index 15e1c3751f..666dd99244 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,7 @@ Modwerk is a community workshop for opening up electronic music hardware to mods - **Every machine grows the same stack.** A base whose hooks own shared sites, the USB link, the device tools and a machine page. Modwerk builds its own implementations. - **Musicians can trust what they install.** Any set of modules runs side by side and never bricks the unit. The official OS always restores it, and every claim was seen on a real unit. - **Good for the makers.** Nothing is copied, no protection is broken, nothing a maker sells gets unlocked, and nothing passes as official ([modding guidelines](MODDING_GUIDELINES.md)). -- **The community runs it.** Authors release their own modules, maintainers look after their machines, and the owner keeps the guidelines and the safety of the units. +- **The community runs it.** Modders release updates, device reviewers approve first releases, maintainers oversee the repository, and the owner safeguards the guidelines and instruments. When these pull apart, the unit's safety and the guidelines come first. Then working beside everything else, then the musician, then the newcomer's path, then speed. @@ -47,7 +47,7 @@ Skills load on clone: Claude Code reads `.claude/skills/`, Codex the identical ` ## Pull requests -- Branch off current `main`. Never push there because it deploys. Add this session's work to your open pull request with an updated description; open another only when none is open, for each `/modwerk-contribute` change, and for a module release or new module, which ships alone. Base changes join their machine's cumulative `base/-next` pull request, a draft until extensively tested on a unit ([how](docs/DEVELOPER_WORKFLOW.md#change-a-base)). Push once the developer's testing is done, then `gh pr create` before reporting it done; a built package stays a draft until that exact build ran on a unit, named in the description. [Machine maintainers](docs/DEVELOPER_WORKFLOW.md#who-reviews-a-first-release) or the owner review a module's first release. The owner merges it; registered authors then release their own updates ([docs/MODULE_AUTHOR_UPDATES.md](docs/MODULE_AUTHOR_UPDATES.md)). +- Branch off current `main`. Never push there because it deploys. Add this session's work to your open pull request with an updated description; open another only when none is open, for each `/modwerk-contribute` change, and for a module release or new module, which ships alone. Base changes join their machine's cumulative `base/-next` pull request, a draft until extensively tested on a unit ([how](docs/DEVELOPER_WORKFLOW.md#change-a-base)). Push once the developer's testing is done, then `gh pr create` before reporting it done; a built package stays a draft until that exact build ran on a unit, named in the description. [Device reviewers](docs/DEVELOPER_WORKFLOW.md#who-reviews-a-first-release) or repository maintainers approve and merge a module's first release through the maintenance worker. Registered authors then release their own updates ([docs/MODULE_AUTHOR_UPDATES.md](docs/MODULE_AUTHOR_UPDATES.md)). - Fold what you learn back into the context. First ask whether `module:doctor`, `pr:ready` or a test can catch it next time, and add that; write a sentence only for what no program can see, in the file a reader would open for that task: the matching guide, or this file. Correct a stale line rather than contradict it; keep it short, general and stock-free. A document in `docs/` and this file stay under 40 KB, so make room rather than append; history goes in a dated record ([where](docs/README.md)). Every pull request says what the guides lacked or got wrong and where you fixed it, and "nothing" is a fine answer ([Share what you learn](docs/DEVELOPER_WORKFLOW.md#share-what-you-learn)). - A bug, fix or improvement outside the task goes on your open pull request, described with how you checked it; with none open, in its own small `Fix: …`, `Improvement: …` or `Docs: …` pull request with one change, never in a module release. In a contributor's fork, offer it and open it with their OK; if you can't fix it, open an issue ([Fixes and improvements](docs/DEVELOPER_WORKFLOW.md#fixes-and-improvements)). diff --git a/LICENSES/platform.json b/LICENSES/platform.json index bcfcceacf3..ec09654733 100644 --- a/LICENSES/platform.json +++ b/LICENSES/platform.json @@ -20,6 +20,7 @@ "src/catalog/modules.ts", "src/catalog/set-limit.ts", "src/catalog/versions.ts", + "src/community/agent-sessions.ts", "src/community/configuration-report.ts", "src/community/creator-support.ts", "src/community/digi-issue-context.ts", diff --git a/changelog/2026-11-19-agent-sessions-admin-pull.md b/changelog/2026-11-19-agent-sessions-admin-pull.md new file mode 100644 index 0000000000..5cfebbea56 --- /dev/null +++ b/changelog/2026-11-19-agent-sessions-admin-pull.md @@ -0,0 +1 @@ +The owner pulls shared agent sessions by signing in to their Modwerk account with the administrator role (`npm run session -- pull`), instead of with a board session. The password is never stored and the pull signs out when it is done. diff --git a/changelog/2026-11-19-agent-sessions.md b/changelog/2026-11-19-agent-sessions.md new file mode 100644 index 0000000000..0da9229b2a --- /dev/null +++ b/changelog/2026-11-19-agent-sessions.md @@ -0,0 +1 @@ +Developers can share the conversation of a coding-agent session with the owner, so what got in the way gets fixed. The agent asks once when the work is done; only prompts, replies and tool calls are sent, with tool output, code, firmware-like content and secrets removed first (`npm run session`, docs/AGENT_SESSIONS.md). diff --git a/changelog/2026-11-19-device-reviewer-roles.md b/changelog/2026-11-19-device-reviewer-roles.md new file mode 100644 index 0000000000..c063acf55f --- /dev/null +++ b/changelog/2026-11-19-device-reviewer-roles.md @@ -0,0 +1 @@ +Device reviewers can approve and merge a first module release for their assigned instrument and register its author as a modder in the same pull request. GitHub collaborators with write access can maintain submissions across instruments. The maintenance worker records the reviewer and the exact revision they approved. diff --git a/changelog/2026-11-19-diagnostics-refused-pool.md b/changelog/2026-11-19-diagnostics-refused-pool.md new file mode 100755 index 0000000000..9675b8d5f2 --- /dev/null +++ b/changelog/2026-11-19-diagnostics-refused-pool.md @@ -0,0 +1 @@ +Diagnostics: the invitation and the privacy page now say that the Octatrack's own log also notes a module it couldn't load at start, with the check that refused it and how much module memory was in use then (base 0.7.10 and later). The owner's diagnostics pull shows both beside the refused module, and names a "module memory" refusal that came from a module's DSP claims meeting a delay buffer rather than from the module memory itself. diff --git a/changelog/2026-11-19-library-selection-feedback.md b/changelog/2026-11-19-library-selection-feedback.md new file mode 100644 index 0000000000..4d08ce4366 --- /dev/null +++ b/changelog/2026-11-19-library-selection-feedback.md @@ -0,0 +1,2 @@ +See stock FX choices, compatibility issues and selection limits while browsing modules. +Desktop navigation, library controls and footer links use larger type. diff --git a/changelog/2026-11-19-octatrack-analog-bd-after-rollback.md b/changelog/2026-11-19-octatrack-analog-bd-after-rollback.md new file mode 100644 index 0000000000..c52a643f11 --- /dev/null +++ b/changelog/2026-11-19-octatrack-analog-bd-after-rollback.md @@ -0,0 +1 @@ +Fix: Octatrack base 0.7.10 plays Analog BD again after a trial that took it out and was rolled back. A trial that removed Analog BD, Sidechain or Output Matrix (to make room for another module, say) let the base let go of the module's engine for good while the trial was still running, so after the rollback the module was listed and could be picked but made no sound until a power cycle. The base now keeps the module ready to come back until the trial is kept or rolled back, while still giving its DSP room to the trial. Reproduced and fixed on an MKII running a development copy of the beta base, with the same `set` trial the report used, and in host tests for both the single-module and the whole-set trial. diff --git a/docs/ADD_A_MODULE.md b/docs/ADD_A_MODULE.md index 6432b6cb79..79f5668284 100644 --- a/docs/ADD_A_MODULE.md +++ b/docs/ADD_A_MODULE.md @@ -4,7 +4,7 @@ For contributors and their coding agents: read this, then your machine's section Start with the [developer workflow and distribution context](DEVELOPER_WORKFLOW.md) for submission, release verification, report handling and catalogue boundaries. Instruments without an SDK follow [Add a machine](ADD_A_MACHINE.md) before module scaffolding. -For an existing published module, start with [author updates](MODULE_AUTHOR_UPDATES.md). Telling a coding agent “fix issue ” in your fork starts the guided fix, version, hardware-test and release flow. The owner approves first releases; registered authors can publish their own later updates after checks pass. +For an existing published module, start with [author updates](MODULE_AUTHOR_UPDATES.md). Telling a coding agent “fix issue ” in your fork starts the guided fix, version, hardware-test and release flow. Device reviewers or repository maintainers approve first releases; registered authors can publish their own later updates after checks pass. ## Read the guide for your category first @@ -28,7 +28,7 @@ Every module follows [the guide for its category](module-guides/README.md): effe - Ask the author first. Before you change the code, behaviour or wording of a module that names someone else as its author, get their OK on GitHub or Discord and link it in the pull request ([Ask the author first](DEVELOPER_WORKFLOW.md#ask-the-author-first)). When you import someone's module, @mention them on the pull request (or open an issue on their repository) before it merges. Say what was imported or changed and give them a chance to review: Modwerk lists them as the author, and users bring their problems to them. The licence may not require it; do it anyway. - Code or behaviour changes inside a module folder need a higher semantic `version` in its manifest, and the same version in `sdk/catalog.json` once listed. Documentation/media/prose-only edits need a version bump only when requesting automatic author publication. - No module depends on another. Each builds, installs and works when it is the only module chosen: no `requires`, no hooks into another module's code, no "needs X" selection rule, no pull request stacked on another module's. Shared code goes into the base or the shared SDK first, or the features ship as one module. Review refuses a dependent module, with no exception ([cross-compatibility](module-guides/README.md#cross-compatibility)). -- One module per pull request. A machine maintainer or the owner approves the first release; the owner, changes beyond the registered author's scope. Later scoped updates can use automatic author publication after evidence verification and required checks. +- One module per pull request. An assigned device reviewer or repository maintainer approves the first release. Later scoped updates can use automatic author publication after evidence verification and required checks. ## Persistence and multiple instances @@ -175,7 +175,7 @@ Its folder, `sdk//modules//`, holds: - `media/` with real black-and-white screenshots of where the module is selected and of its control pages, and their provenance in `capture.json`. A module that draws nothing of its own gives `access.noUiReason` instead ([rule](MODULE_UI_CAPTURES.md#manifest-contract)); - an original 320×192 SVG thumbnail: `presentation/thumbnail.svg` on the Octatrack, `media/thumbnail.svg` on the elemod machines, where `npm run pr:ready` refuses the template's placeholder. -The checks reject missing sections, coloured screenshots and a version that did not increase. They cannot tell whether the documentation is true; a machine maintainer or the owner reviews first releases and registered authors verify their scoped updates. +The checks reject missing sections, coloured screenshots and a version that did not increase. They cannot tell whether the documentation is true; a device reviewer or repository maintainer reviews first releases and registered authors verify their scoped updates. ## Module thumbnail style @@ -298,8 +298,7 @@ In the toolchain image set `ELEKLOADER_DSP_ASM`; restore old versions it deletes It binds the native source hash: every file in the folder but `octamod.module.json`, `media/`, Markdown and licences, so `evidence/performance.json`, the thumbnail and `manifest.py` are final before the owner signs. Without it `modules:generate` refuses the module, and the package builder takes the display name from the generated documents: -folder complete, approval, `modules:generate`, then the package. List the module in `module-set.test.ts`'s -published packages, `module-qualification.test.ts`'s owner-approved releases and `resource-indicators.test.ts`'s +folder complete, approval, `modules:generate`, then the package. List the module in `module-qualification.test.ts`'s owner-approved releases and `resource-indicators.test.ts`'s exceptions. A module back after removal counts as new: one changelog entry. Taking an id off `REMOVED_MODULE_IDS` moves `src/catalog/modules.ts`, which Tape Echo's and Euclid's standalone recipes pin. diff --git a/docs/AGENT_SESSIONS.md b/docs/AGENT_SESSIONS.md new file mode 100644 index 0000000000..9af1040241 --- /dev/null +++ b/docs/AGENT_SESSIONS.md @@ -0,0 +1,41 @@ +# Shared agent sessions: show the owner where contributing gets in the way + +Since 19 November 2026. Developers build with coding agents on their own computers, and what slows them down (a guide that sent the agent the wrong way, a check that failed without saying why, a setup step that took an hour) mostly stays in their sessions. A developer can now send the owner the conversation of one session, so the owner can fix what got in the way. Sharing is voluntary, one session at a time, and never needed to contribute. + +## Ask once, at the end + +When a task is done (`npm run pr:ready` says Ready, or the developer stops), the agent asks the developer once, in one line, whether to share this session. `pr:ready` prints the reminder, and `npm run session -- status` says what to do: + +- **ask** (the default): ask, and share only on a yes. Write the developer's answer and the agent's own short account of what got in the way as the note: `npm run session -- share --note "…"`. +- **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. + +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 + +Only the conversation: the developer's prompts, the agent's replies, and one line per tool call (the command or file it touched, and whether it failed). The script finds the session's transcript (Claude Code's in `~/.claude/projects/`, Codex's in `~/.codex/sessions/`) and removes, before anything is sent: + +- every tool output, the agent's thinking, injected context (skill bodies, hook output, compaction summaries, context files) and subagent turns; +- code blocks longer than 12 lines, hex dumps, runs of hex values and long data blobs; +- secrets (tokens, keys, passwords, bearer headers), email addresses, IP addresses, home folders, the computer's user and host name. + +What remains still looking like firmware or stock code (disassembly, long hex or number tables) stops the upload: the script names the entries, and `--skip 3,7` leaves them out. `npm run session -- preview` writes what would be sent to `~/.cache/modwerk/session-preview.json` without sending anything; offer it when the developer wants to look first. The Worker runs the same checks again and refuses what fails them. + +## Who reads it, and for how long + +Only the developer who shared it and the site's administrators. The owner may analyse sessions with Claude, which sends them to Anthropic. Nothing reaches GitHub, module authors or other developers. A session is kept 90 days, then deleted; `npm run session -- list`, `get ` and `delete ` show and remove your own at any time. Suspending an account deletes its sessions at once, deleting the account deletes them too, and the account export lists them. At most 30 kept per developer and 10 shares a day. The record of processing is in [LEGAL_COMPLIANCE.md](LEGAL_COMPLIANCE.md). + +## The owner's side + +`npm run session -- pull` saves every shared session into `~/.cache/modwerk-local/sessions/` with an `INDEX.md`. It signs in to the owner's Modwerk account, the one with the administrator role, as the site's sign-in does: email and password at a prompt (the password hidden), or from `MODWERK_EMAIL` and `MODWERK_PASSWORD` for that one command. The password is never stored, and the pull signs out when it is done. A board session never reads other developers' sessions, even on an administrator's account. The owner runs it in their own terminal, so the password never passes through an agent. Developers' names and quotes stay there and in chat, like diagnostics ([MAINTENANCE.md](MAINTENANCE.md)). What a session shows becomes a guide edit, a check or a fix, written without names. + +## API + +Writes need the board session (`X-Modwerk-Developer`) and the site's `Origin`. + +- `POST /api/agent-sessions` `{consent, data}`: `data` is the session JSON, gzip, base64, at most 1 MB packed. `consent` is `SESSION_CONSENT_VERSION`; a stale client is refused. +- `GET /api/agent-sessions`: your own; `?all=1` everyone's, for administrators (`X-Octamod-Admin` from `POST /api/auth/admin`, or a member account with the administrator role). +- `GET /api/agent-sessions/` and `DELETE /api/agent-sessions/`: yours, or any for administrators. + +The format, the scrubbing and the checks are in `src/community/agent-sessions.ts`, shared by the client (`scripts/agent-session.mjs`) and the Worker (`server/agent-sessions.ts`); the table is `agent_sessions` (migration 0099). diff --git a/docs/DEVELOPER_WORKFLOW.md b/docs/DEVELOPER_WORKFLOW.md index 4ebd4248d5..784593c682 100644 --- a/docs/DEVELOPER_WORKFLOW.md +++ b/docs/DEVELOPER_WORKFLOW.md @@ -80,7 +80,13 @@ The required PR check includes the description and hardware-evidence verdict. Ed ### Who reviews a first release -The GitHub logins under `maintainers` in `sdk/machines//machine.json` review that machine's first releases and hand approved pull requests to the owner. The owner merges each first release from their own GitHub account so publication can verify the merge. Only the owner names or removes one, in a pull request of the owner's own, and assigns them review access. The owner reviews releases for machines without maintainers. A maintainer reviews by the [pull request worker's checklist](MAINTENANCE.md#pull-request-worker), never reviews their own module, and hands these to the owner instead of deciding them: +A **contributor** can submit a PR with `/modwerk-contribute` or a new module with `/modwerk-new-module`. A **modder** builds modules. A registered modder can release updates to their own published modules. Existing verified module claims and granted developer badges display as Modder. A **device reviewer** (`device-reviewer`) can approve and merge another author's first release on an assigned device. A **maintainer** is a GitHub collaborator with write, maintain or admin access and can handle submissions across devices. A person can hold several roles. + +Assign device reviewers by adding their numeric GitHub IDs to `deviceReviewers` in `sdk/machines//machine.json` through a maintainer-reviewed PR and running `npm run machines:generate`. Get the ID with `gh api users/LOGIN --jq .id`. Assignments take effect on main. Old `maintainers` login lists and forum badges grant no merge permission. For a new modder, include only their lowercase login and numeric ID in the existing accounts map in `.github/module-authors.json`, in the same PR as their first module. + +Review the exact commit with `/modwerk-review-prs` and [merge the first release](MODULE_AUTHOR_UPDATES.md#merge-a-first-release). Another reviewer or maintainer handles your own module. + +Send these to a repository maintainer or the owner: - anything beyond the module's own folder and catalogue rows: the base, a hook, the shared SDK, a builder, a check, another machine; - any question under the [modding guidelines](../MODDING_GUIDELINES.md): a port's permission or licence, a source that is unclear, a likeness to a maker's product; @@ -138,7 +144,7 @@ A beta report from a USB sync has no device log (its build fingerprint reads "No Use `resolve` only after the exact published download and hardware fix have actually been verified. Other closure reasons are `configuration`, `duplicate`, `not_reproducible`, `insufficient_information` and `withdrawn`; each needs an explanation and claims no firmware fix. Private reports offer the same triage and closure choices on their access-controlled page. GitHub-only issues use authorized native GitHub closure. Private details remain access-controlled and consent-based. -Routine updates to an author's approved modules use the existing automatic PR workflow: prepare the fix, pass CI, personally verify the evidence and check both publication boxes. The bot merges and starts site/API publication without an owner review. First releases, shared code, ownership/licence changes and exceptions still need owner review. See [Author updates](MODULE_AUTHOR_UPDATES.md). +Routine updates to an author's approved modules use the existing automatic PR workflow: prepare the fix, pass CI, personally verify the evidence and check both publication boxes. The bot merges and starts site/API publication without an owner review. Device reviewers or maintainers review first releases. Shared code, ownership/licence changes and exceptions go to a maintainer or the owner. See [Author updates](MODULE_AUTHOR_UPDATES.md). For a specific GitHub reply, check its signed webhook delivery, each intended recipient's bell entry, and that member's email/push preferences and digest due time. A successful webhook response proves processing, not that every participant received a notification; check members who joined through Modwerk separately, and never route by a typed GitHub mention of a Modwerk username. The `emailed` flag also settles read or expired entries and turned-off topics, so it is not a delivery receipt. Aggregate provider-acceptance counters cannot prove that a particular message arrived in an inbox. diff --git a/docs/LEGAL_COMPLIANCE.md b/docs/LEGAL_COMPLIANCE.md index 2e56a90792..e9dfdff0f3 100644 --- a/docs/LEGAL_COMPLIANCE.md +++ b/docs/LEGAL_COMPLIANCE.md @@ -25,6 +25,7 @@ Maintain this as the Article 30 record with operator contacts, recipients/transf | Public participation | Authored posts/comments/configuration snapshots, ratings/reactions, pseudonymous attribution | Requested publication, Art. 6(1)(b); maintaining discussion integrity/abuse handling, Art. 6(1)(f), only where necessary | Review relevance and personal free text at least annually and on request; erase/anonymize when unnecessary; preserve licensed source attribution where justified | | Forum images and sound clips | Files members attach to posts (compressed in the browser, photo metadata removed), descriptions, size and type; stored in Cloudflare R2 | Requested publication, Art. 6(1)(b); abuse handling, Art. 6(1)(f) | Public while the post is visible; removed by the author, an administrator or account deletion and then purged from storage within about an hour; unused uploads purged after a day | | Private features | Reports/device logs, bookmarks/follows/notifications, which operator announcements a member has read | Requested support/features, Art. 6(1)(b) | Review closed reports and old notifications quarterly, remove once follow-up is unnecessary; no automatic long-lived-content purge in this change | +| Shared agent sessions | Per session a developer chose to share: the GitHub account it belongs to; the developer's prompts, the agent's replies and one line per tool call, scrubbed on the developer's computer of tool output, long code, hex and data, credentials, email and IP addresses, home folders and user and host names, and refused when firmware-like content remains; agent, branch, time span, a note of at most 1,000 characters, the consent version and times | Letting the owner see and remove what gets in the way of contributing: consent per session, Art. 6(1)(a), withdrawn by deleting it; administrators only, and may be analysed with Claude (Anthropic, as for diagnostics) | 90 days, then deleted hourly; deleted by the developer at any time, at once on suspension and with the account; listed in the account export; at most 30 kept and 10 shares a day per developer ([AGENT_SESSIONS.md](AGENT_SESSIONS.md)) | | Agent board | GitHub account ID and handle of any developer who signs in from the terminal; per claim its kind and key, branch, pull request number, a note of at most 120 characters (no links, paths, addresses or code) and its times; per question, finding or reply its topic, the addressee's handle, text of at most 500 characters under the same filter, a pull request number and its times; a hashed 30-day board session; names-free counts of board use | Showing developers and their agents who is working on which module, hook, table or migration, and letting them ask each other and share findings, so work is not duplicated: requested service, Art. 6(1)(b); public listing of active claims and open threads, Art. 6(1)(f) — **balancing to be documented**: handles and branches are already public on GitHub, notes and messages are written to be public and filtered | Claims active while held: released by the holder, after 14 days without a pull request, on merge/close or suspension. Questions end when closed or 30 days after the last post, findings when closed, folded or after 90 days. Ended claims and threads deleted 90 days later; a suspended account's posts deleted at once; all with account deletion; the member's own claims and posts in the account export ([AGENT_BOARD.md](AGENT_BOARD.md)) | | Activity email | Recipient address; actor usernames, thread titles and short excerpts of public posts/comments; notification read/emailed state; email preferences and last digest time | Telling members about responses to their posts and modules, Art. 6(1)(f) — **balancing test to be documented before launch**: on by default for verified members, no advertising, no open/click tracking, objection at any time in settings or by one-click unsubscribe (RFC 8058) in every message. Not advertising, so § 7 UWG consent does not apply; review if digests ever include promotional content | At most one digest per 6 or 24 hours per member; unread-only, nothing older than a week; separate daily cap; notifications and preferences deleted with the account and included in export; Resend tracking must stay disabled for the domain | | News email | Recipient address; the operator's subject and markdown body; per-campaign delivery state and attempt times per account ID; consent version and time | Occasional Modwerk news to members who opted in, Art. 6(1)(a) GDPR and § 7(2) no. 2 UWG consent, unchecked at signup, never a condition of membership; no open/click tracking | Only while consent is current, rechecked for every message; withdrawal in account settings or by one-click unsubscribe (RFC 8058) in every message takes effect before the next send; campaigns and delivery rows hold no addresses; delivery rows are deleted with the account and included in export; separate daily cap | diff --git a/docs/MAINTENANCE.md b/docs/MAINTENANCE.md index b64d5483cf..72603e1af3 100644 --- a/docs/MAINTENANCE.md +++ b/docs/MAINTENANCE.md @@ -32,7 +32,7 @@ List them with `gh pr list --state open --json number,title,author,isDraft,label - **The triage bot** runs at minute 41 of every hour. Preview it with `PR_TRIAGE_DRY_RUN=1 GITHUB_REPOSITORY=repeat98/modwerk GITHUB_TOKEN=$(gh auth token) node scripts/pr-triage.mjs` and say what it would label, comment or close, above all on a pull request whose author the owner asked to wait. - **Red checks:** read the failing job (`gh run view --log-failed`) and say whether the pull request, `main` or a flaky test is at fault. - **Follow up** on a pull request quiet since its last request with one short draft; `pr-triage.yml` closes `needs-work` after 14 days. -- **Merge**, from the owner's account once the owner says so (machine maintainers hand their review to the owner, [who](DEVELOPER_WORKFLOW.md#who-reviews-a-first-release)): `gh pr merge --squash`, or `--merge` when the pull request's catalogue rows pin one of its own commits. Before a module update merges, tell the owner that publishing notifies its followers. An owner-approved update needs `sdk/approvals/-build-approval.json`, which only the owner writes: hand them the record with `sourceSha256` from `moduleNativeSourceSha256` in `scripts/module-qualification.mjs`. Then follow the merge commit's runs (`gh run list --commit `) to green and, for a module release, check that the live site lists the new version. +- **Merge**, from the owner's account once the owner says so (device reviewers and repository maintainers use the [reviewed merge command](DEVELOPER_WORKFLOW.md#who-reviews-a-first-release)): `gh pr merge --squash`, or `--merge` when the pull request's catalogue rows pin one of its own commits. Before a module update merges, tell the owner that publishing notifies its followers. An owner-approved update needs `sdk/approvals/-build-approval.json`, which only the owner writes: hand them the record with `sourceSha256` from `moduleNativeSourceSha256` in `scripts/module-qualification.mjs`. Then follow the merge commit's runs (`gh run list --commit `) to green and, for a module release, check that the live site lists the new version. ## Issue worker diff --git a/docs/MAINTENANCE_BOT.md b/docs/MAINTENANCE_BOT.md index 413f62fe1e..39de8eb98f 100644 --- a/docs/MAINTENANCE_BOT.md +++ b/docs/MAINTENANCE_BOT.md @@ -17,7 +17,7 @@ The maintenance bot does the routine part of the [daily pass](MAINTENANCE.md) on A **decision** is a question only the owner can answer, such as an OK for a port, a scope exception or a waiver. The bot does not file it as a to-do: it proposes the reply it recommends (a comment or board reply with `intent: "decision"`), and the owner's Approve posts it. Only a decision the owner stopped becomes a to-do. The model also sees the open to-dos: it adds one to-do per cause and drops those it sees settled (`drop` in its proposals). -The bot never pushes, releases, deploys, touches secrets, or works on firmware, a unit or an emulator. Those become **to-dos**, each with the `/modwerk-*` command that does it, kept in the ledger (`maintenance_bot_todos`, migration 0092). In any session at the owner's computer, `/modwerk-todo` lists them (`npm run todo`, signed in with the owner's `npm run board -- login`), runs the command, and ticks it off. A to-do whose item closes is dropped on the next daily run. Every action pins the head commit and comment count it was proposed against. If either changes before the action runs, the action is dropped and proposed again next pass. A merge is checked again for green checks at the moment it runs. The Worker then merges it in the owner's name (`POST /api/maintenance-bot/merge`) at exactly that commit, because the site publishes only owner merges (`scripts/release-approval.mjs`), and an owner merge starts the usual push workflows. So a merge that publishes modules (module folders, `sdk/imports/`, the catalogues, module changelogs) always needs the owner's Approve: it is a release. +The bot never pushes, releases, deploys, touches secrets, or works on firmware, a unit or an emulator. Those become **to-dos**, each with the `/modwerk-*` command that does it, kept in the ledger (`maintenance_bot_todos`, migration 0092). In any session at the owner's computer, `/modwerk-todo` lists them (`npm run todo`, signed in with the owner's `npm run board -- login`), runs the command, and ticks it off. A to-do whose item closes is dropped on the next daily run. Every action pins the head commit and comment count it was proposed against. If either changes before the action runs, the action is dropped and proposed again next pass. A merge is checked again for green checks at the moment it runs. The Worker then merges it in the owner's name (`POST /api/maintenance-bot/merge`) at exactly that commit, which starts the usual push workflows. A model-proposed module release needs the owner's Approve. An explicit [reviewed merge](DEVELOPER_WORKFLOW.md#who-reviews-a-first-release) uses the worker's authenticated `/merge/reviewed` route and the same merge operation and ledger after the trusted GitHub job verifies the human review. A paused worker or an owner veto for that head stops it. Registered authors keep their separate self-merge workflow. The model's output is untrusted: it is limited to one file, every item is checked against the policy, public text may mention only the item's author and link only to Modwerk, and anything outside the policy is held back and listed in the report. Changes to `scripts/maintenance-bot/` always need the owner's OK. diff --git a/docs/MODULE_AUTHOR_UPDATES.md b/docs/MODULE_AUTHOR_UPDATES.md index 1679117949..3af2b95f6c 100644 --- a/docs/MODULE_AUTHOR_UPDATES.md +++ b/docs/MODULE_AUTHOR_UPDATES.md @@ -1,6 +1,10 @@ # Publishing updates as a module author -A machine maintainer or the owner reviews a module's first release. The owner merges the approved addition ([who](DEVELOPER_WORKFLOW.md#who-reviews-a-first-release)). After that, its registered author can request automatic merge and publication of their own updates. Open a pull request against `repeat98/modwerk` `main`; pushing to a personal upstream repository does not submit an update to Modwerk. Ownership changes, shared SDK/compiler changes and release exceptions still need owner review. +A device reviewer or repository maintainer can review and merge a module's first release and register the submitting modder ([first releases](DEVELOPER_WORKFLOW.md#who-reviews-a-first-release)). After that, its registered author can request automatic merge and publication of their own updates. Open a pull request against `repeat98/modwerk` `main`; pushing to a personal upstream repository does not submit an update to Modwerk. Ownership changes, shared SDK/compiler changes and release exceptions still need owner review. + +## Merge a first release + +Use `/modwerk-review-prs ` and the [review checklist](MAINTENANCE.md#pull-request-worker). When the reviewer chooses merge, submit an approving GitHub review for the exact commit inspected. Post a new PR comment containing `/modwerk merge ` from the same account. The **Merge a reviewed submission** workflow in GitHub Actions verifies the live review, scope and CI. If GitHub holds the first contributor's CI, the command starts only the reviewed Module PR checks. Wait for green and post the same command again. The maintenance worker records the reviewer and merges that commit. If the PR changes, review its new head. If main advances, merge main into the PR and rerun checks. For your own first release, ask another assigned reviewer or a maintainer. ## Start with an issue diff --git a/docs/README.md b/docs/README.md index 78e0af1466..f6172b0d0a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -79,6 +79,7 @@ Every document in `docs/`, one line each. [AGENTS.md](../AGENTS.md) says which t - [SINGLE_SIGN_ON.md](SINGLE_SIGN_ON.md): accounts and single sign-on. - [DEVELOPER_WORKSPACE.md](DEVELOPER_WORKSPACE.md): creator settings and private report details. - [AGENT_BOARD.md](AGENT_BOARD.md): the agent board: claims every developer's agent sees and makes (module ports, hook, table and migration numbers), the questions and findings agents leave each other, and the commands that check them. +- [AGENT_SESSIONS.md](AGENT_SESSIONS.md): sharing the conversation of an agent session with the owner, what is removed before it leaves the computer, and who reads it for how long. - [STATISTICS.md](STATISTICS.md): the admin statistics. - [WEB_PUSH.md](WEB_PUSH.md): device push notifications. - [FIRMWARE_DOWNLOAD_API.md](FIRMWARE_DOWNLOAD_API.md): building and saving firmware without a browser. diff --git a/migrations/0099_agent_sessions.sql b/migrations/0099_agent_sessions.sql new file mode 100644 index 0000000000..8d2c38e48a --- /dev/null +++ b/migrations/0099_agent_sessions.sql @@ -0,0 +1,20 @@ +-- Agent sessions a developer chose to share with the owner (docs/AGENT_SESSIONS.md): the conversation of one +-- coding-agent session, scrubbed on the developer's computer and checked again by the Worker, gzip and base64 in `data`. +-- Readable by the developer who shared it and by administrators; deleted after 90 days, by the developer, on +-- suspension and with the account. +CREATE TABLE agent_sessions ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + agent TEXT NOT NULL, + branch TEXT, + note TEXT NOT NULL DEFAULT '', + entries INTEGER NOT NULL, + started_at TEXT, + ended_at TEXT, + consent_version TEXT NOT NULL, + bytes INTEGER NOT NULL, + data TEXT NOT NULL, + created_at TEXT NOT NULL +); +CREATE INDEX agent_sessions_user ON agent_sessions(user_id, created_at); +CREATE INDEX agent_sessions_created ON agent_sessions(created_at); diff --git a/package.json b/package.json index f7a876b791..428cc22cca 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "lint": "eslint . --cache --cache-strategy content --cache-location node_modules/.cache/eslint/", "test": "vitest run", "board": "node scripts/agent-board.mjs", + "session": "node scripts/agent-session.mjs", "todo": "node scripts/maintenance-bot/todo.mjs", "check": "node scripts/check.mjs", "pr:ready": "node scripts/pr-ready.mjs", diff --git a/public/licenses/THIRD_PARTY_NOTICES.html b/public/licenses/THIRD_PARTY_NOTICES.html index 4560a12bbb..ab5c336125 100644 --- a/public/licenses/THIRD_PARTY_NOTICES.html +++ b/public/licenses/THIRD_PARTY_NOTICES.html @@ -67,6 +67,7 @@ src/catalog/modules.ts src/catalog/set-limit.ts src/catalog/versions.ts +src/community/agent-sessions.ts src/community/configuration-report.ts src/community/creator-support.ts src/community/digi-issue-context.ts diff --git a/public/licenses/THIRD_PARTY_NOTICES.txt b/public/licenses/THIRD_PARTY_NOTICES.txt index 7336fc074c..e5eaf9a42a 100644 --- a/public/licenses/THIRD_PARTY_NOTICES.txt +++ b/public/licenses/THIRD_PARTY_NOTICES.txt @@ -66,6 +66,7 @@ src/catalog/module-releases.ts src/catalog/modules.ts src/catalog/set-limit.ts src/catalog/versions.ts +src/community/agent-sessions.ts src/community/configuration-report.ts src/community/creator-support.ts src/community/digi-issue-context.ts diff --git a/public/octatrack-modules/analog-bassdrum/0.1.7-experimental.mwrm b/public/octatrack-modules/analog-bassdrum/0.1.7-experimental.mwrm index 2ca4957cb5..df70883ce5 100644 Binary files a/public/octatrack-modules/analog-bassdrum/0.1.7-experimental.mwrm and b/public/octatrack-modules/analog-bassdrum/0.1.7-experimental.mwrm differ diff --git a/public/octatrack-modules/output-matrix/0.1.1-experimental.mwrm b/public/octatrack-modules/output-matrix/0.1.1-experimental.mwrm index 76154868bb..82f4c98f05 100644 Binary files a/public/octatrack-modules/output-matrix/0.1.1-experimental.mwrm and b/public/octatrack-modules/output-matrix/0.1.1-experimental.mwrm differ diff --git a/public/octatrack-modules/sidechain-compressor/0.2.2-experimental.mwrm b/public/octatrack-modules/sidechain-compressor/0.2.2-experimental.mwrm index 312e0189b7..47ebdc0557 100644 Binary files a/public/octatrack-modules/sidechain-compressor/0.2.2-experimental.mwrm and b/public/octatrack-modules/sidechain-compressor/0.2.2-experimental.mwrm differ diff --git a/scripts/agent-session.mjs b/scripts/agent-session.mjs new file mode 100644 index 0000000000..01d0de50cd --- /dev/null +++ b/scripts/agent-session.mjs @@ -0,0 +1,253 @@ +#!/usr/bin/env node +// SPDX-License-Identifier: Elastic-2.0 +// Copyright (c) 2026 Jannik Aßfalg (repeat98) +// Share this coding-agent session with the owner (docs/AGENT_SESSIONS.md), so they see where contributing gets in the way. +// 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 -- list | get | delete +// npm run session -- pull # the owner: every shared session into ~/.cache/modwerk-local/sessions/, +// # signed in with the owner's site account (prompt, or MODWERK_EMAIL/PASSWORD) +// Only the conversation is sent: the developer's prompts, the agent's replies and which tools ran and whether they failed. +// Tool output, thinking, long code blocks, hex dumps, secrets and home paths stay here. Uses the board sign-in. +import { chmod, lstat, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises' +import { homedir, hostname, userInfo } from 'node:os' +import { dirname, join } from 'node:path' +import { execFileSync } from 'node:child_process' +import { gzipSync } from 'node:zlib' +import { parseArgs } from 'node:util' +import { pathToFileURL } from 'node:url' +import { boardRequest, readToken, BoardError, BoardUnavailable } from './agent-board.mjs' +import { claudeProjectFolder, firmwareFindings, prepareSession, readClaudeTranscript, readCodexRollout, SESSION_CONSENT_VERSION, SESSION_GZIP_LIMIT, SESSION_NOTE_LIMIT } from '../src/community/agent-sessions.ts' + +const PREFERENCES = ['ask', 'always', 'never'] +export const preferenceFile = () => process.env.MODWERK_SESSION_FILE ?? join(homedir(), '.config', 'modwerk', 'session-sharing.json') +const previewFile = () => join(homedir(), '.cache', 'modwerk', 'session-preview.json') + +export async function readPreference(file = preferenceFile()) { + try { const value = JSON.parse(await readFile(file, 'utf8')).sharing; return PREFERENCES.includes(value) ? value : 'ask' } catch { return 'ask' } +} +async function writePrivate(file, text) { + await mkdir(dirname(file), { recursive: true, mode: 0o700 }) + await writeFile(file, text, { mode: 0o600 }); await chmod(file, 0o600) +} + +/** What the agent should do about sharing at the end of a task, in one line (pr:ready prints it too). */ +export function sharingLine(preference) { + return preference === 'never' ? 'Session sharing: never. The developer chose not to be asked; do not offer it.' + : preference === 'always' ? 'Session sharing: always. When the task is done, share this session yourself (npm run session -- share --note "…") and tell the developer in a line.' + : 'Session sharing: ask. When the task is done, ask the developer once whether to share this session with the owner, so they can remove what got in the way (npm run session -- share --note "…"; only the conversation is sent, docs/AGENT_SESSIONS.md). If they answer always or never, save it with npm run session -- prefer always|never.' +} + +/** The working directories this session may have started in: where npm was called, here, and the checkout's root. */ +function places() { + const list = [process.env.INIT_CWD, process.cwd()] + try { list.push(execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()) } catch { /* not a checkout */ } + return [...new Set(list.filter(Boolean))] +} +async function newest(files) { + let best = null + for (const file of files) { + try { const info = await stat(file); if (info.isFile() && (!best || info.mtimeMs > best.mtimeMs)) best = { file, mtimeMs: info.mtimeMs } } catch { /* gone */ } + } + return best +} +async function claudeCandidates() { + const root = join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude'), 'projects'), files = [] + for (const place of places()) { + const folder = join(root, claudeProjectFolder(place)) + try { for (const name of await readdir(folder)) if (name.endsWith('.jsonl')) files.push(join(folder, name)) } catch { /* no sessions here */ } + } + return files +} +async function codexCandidates() { + const root = join(process.env.CODEX_HOME ?? join(homedir(), '.codex'), 'sessions'), files = [], wanted = places() + // Codex files sessions by day: the last three days hold the current one. + for (let back = 0; back < 3; back++) { + const day = new Date(Date.now() - back * 86400000), folder = join(root, String(day.getFullYear()), String(day.getMonth() + 1).padStart(2, '0'), String(day.getDate()).padStart(2, '0')) + let names + try { names = await readdir(folder) } catch { continue } + for (const name of names) { + if (!name.startsWith('rollout-') || !name.endsWith('.jsonl')) continue + const file = join(folder, name), first = (await readFile(file, 'utf8')).split('\n', 1)[0] + try { if (wanted.includes(JSON.parse(first).payload?.cwd)) files.push(file) } catch { /* not a rollout */ } + } + } + return files +} +/** Claude Code names the running session to the commands it starts; its transcript may sit under any project folder. */ +async function claudeSessionFile(id = process.env.CLAUDE_CODE_SESSION_ID) { + if (!id || !/^[0-9a-f-]{36}$/.test(id)) return null + const root = join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude'), 'projects') + let folders + try { folders = await readdir(root) } catch { return null } + const found = await newest(folders.map(folder => join(root, folder, id + '.jsonl'))) + return found?.file ?? null +} +/** The transcript of the session running now: Claude Code's by its session id, otherwise the most recently written one + * for this checkout. */ +export async function findTranscript({ file, agent } = {}) { + if (file) return { file, agent: agent ?? (/[\\/]\.codex[\\/]|rollout-/.test(file) ? 'codex' : 'claude-code') } + const current = agent === 'codex' ? null : await claudeSessionFile() + if (current) return { file: current, agent: 'claude-code' } + const claude = agent === 'codex' ? null : await newest(await claudeCandidates()) + const codex = agent === 'claude-code' ? null : await newest(await codexCandidates()) + const pick = claude && (!codex || claude.mtimeMs >= codex.mtimeMs) ? { file: claude.file, agent: 'claude-code' } : codex ? { file: codex.file, agent: 'codex' } : null + if (!pick) throw new Error('No Claude Code or Codex transcript found for this checkout. Name it with --file .') + return pick +} + +export async function buildSession({ file, agent, note = '', skip = [] }) { + 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) + let user = '' + try { user = userInfo().username } catch { /* none */ } + return prepareSession(read, note, { user, host: hostname().split('.')[0], home: homedir() }, skip) +} + +function summary(session, file) { + const first = session.entries.find(entry => entry.who === 'developer')?.text.replace(/\s+/g, ' ').slice(0, 100) ?? '(none)' + const counts = ['developer', 'agent', 'tool'].map(who => session.entries.filter(entry => entry.who === who).length) + const r = session.removed + return [ + `Transcript: ${file}`, + `Kept: ${counts[0]} developer prompts, ${counts[1]} agent replies, ${counts[2]} tool calls (${session.entries.filter(entry => entry.failed).length} failed).`, + `Removed: ${r.toolOutputs} tool outputs, ${r.thinking} thinking blocks, ${r.codeBlocks} long code blocks, ${r.hexLines} hex dumps, ${r.blobs} data blobs, ${r.secrets} secrets, ${r.skipped} injected or skipped turns${r.trimmed ? `, ${r.trimmed} entries trimmed to fit` : ''}.`, + `First prompt: «${first}»`, + ].join('\n') +} + +async function token() { + const value = await readToken() + if (!value) throw new BoardError('Sign in for the board first: npm run board -- login', 401) + return value +} + +// The same Worker and site the board client uses (scripts/agent-board.mjs). +const API = () => (process.env.MODWERK_API ?? 'https://octamod-community.octamod.workers.dev/api').replace(/\/$/, '') +const SITE = () => new URL(process.env.MODWERK_SITE ?? 'https://modwerk.app/').origin + +/** A request with the owner's site account session (`Authorization: Bearer`, as the site sends it). */ +export async function accountRequest(path, { method = 'GET', session, body, api = API(), fetch: send = fetch } = {}) { + const result = await send(api + path, { method, redirect: 'error', signal: AbortSignal.timeout(30000), headers: { Accept: 'application/json', ...(method === 'GET' ? {} : { Origin: SITE() }), ...(session ? { Authorization: 'Bearer ' + session } : {}), ...(body ? { 'Content-Type': 'application/json' } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) }) + let value + try { value = await result.json() } catch { throw new BoardUnavailable('The Worker did not answer with JSON (HTTP ' + result.status + ').') } + if (!result.ok) throw new BoardError(value?.error ?? 'HTTP ' + result.status, result.status) + return { value, session: result.headers.get('X-Octamod-Session') } +} +/** Signs in to the owner's site account with email and password, as the site's sign-in does, runs `work` with that + * session, then signs out again. The password is only sent to sign in and is never written anywhere. */ +export async function asAccount({ email, password }, work, options = {}) { + let signedIn + try { signedIn = await accountRequest('/auth/login', { ...options, method: 'POST', body: { email, password } }) } catch (error) { + if (error instanceof BoardError && error.status === 401) throw new BoardError(error.message + ' An account made with Google, GitHub or Discord has no password until you set one with "Forgot password" on the site.', 401) + throw error + } + if (!signedIn.session) throw new BoardError('The sign-in returned no session.', 500) + try { return await work(signedIn.session) } finally { await accountRequest('/auth/logout', { ...options, method: 'POST', session: signedIn.session }).catch(() => {}) } +} +/** Reads a line from the terminal, without echoing it when `hidden`. Enter on an empty line is ignored, so a stray + * Enter already waiting in the terminal does not answer for the person. */ +function ask(question, hidden = false) { + const input = process.stdin + if (!input.isTTY) return Promise.resolve('') + return new Promise(resolve => { + let value = '' + process.stdout.write(question) + input.setRawMode(true); input.resume(); input.setEncoding('utf8') + const done = answer => { input.setRawMode(false); input.pause(); input.off('data', onData); process.stdout.write('\n'); resolve(answer) } + const onData = chunk => { + for (const ch of chunk) { + if (ch === '\r' || ch === '\n') { if (value.trim()) return done(value); continue } + if (ch === '\u0003' || ch === '\u0004') return done('') + if (ch === '\u007f' || ch === '\b') { if (value) { value = value.slice(0, -1); if (!hidden) process.stdout.write('\b \b') } continue } + value += ch + if (!hidden) process.stdout.write(ch) + } + } + input.on('data', onData) + }) +} + +/** Saves every shared session not yet in `folder`, and an index of all of them. */ +export async function pullSessions(folder, get) { + const { sessions } = await get('/agent-sessions?all=1'), index = [] + await mkdir(folder, { recursive: true, mode: 0o700 }) + for (const item of sessions) { + const name = `${item.createdAt.slice(0, 10)}-${item.login ?? 'deleted'}-${item.id.slice(0, 8)}.json`, file = join(folder, name) + try { await stat(file) } catch { await writePrivate(file, JSON.stringify(await get('/agent-sessions/' + item.id), null, 2) + '\n') } + index.push(`- ${name}: @${item.login ?? 'deleted'}, ${item.agent}, ${item.entries} entries, ${item.branch ?? 'no branch'}${item.note ? ` — «${item.note.replace(/\s+/g, ' ').slice(0, 200)}»` : ''}`) + } + await writePrivate(join(folder, 'INDEX.md'), `# Shared agent sessions (pulled ${new Date().toISOString().slice(0, 16)}Z)\n\nPrivate: names and quotes stay in this folder and in chat.\n\n${index.join('\n')}\n`) + return sessions.length +} + +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 [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 } + if (command === 'prefer') { + if (!PREFERENCES.includes(arg)) { console.error('Choose ask, always or never.'); return 2 } + await writePrivate(preferenceFile(), JSON.stringify({ sharing: arg }) + '\n') + console.log(sharingLine(arg)); return 0 + } + if (command === 'preview' || command === 'share') { + if ((values.note ?? '').length > SESSION_NOTE_LIMIT) { console.error(`Keep the note to ${SESSION_NOTE_LIMIT} characters.`); return 2 } + const found = await findTranscript({ file: values.file, agent: values.agent }) + const session = await buildSession({ ...found, note: values.note ?? '', skip }) + await writePrivate(previewFile(), JSON.stringify(session, null, 2) + '\n') + console.log(summary(session, found.file)) + console.log(`What would be sent: ${previewFile()}`) + const firmware = firmwareFindings(session.entries) + if (firmware.length) { + console.error(`✗ Entries ${firmware.map(item => item.index).join(', ')} still look like firmware or stock code (${[...new Set(firmware.map(item => item.reason))].join(', ')}). Firmware never leaves this computer: look at them in the preview, then run this again with --skip ${firmware.map(item => item.index).join(',')}.`) + return 1 + } + if (command === 'preview') return 0 + if (!session.entries.length) { console.error('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') } }) + console.log(`Shared with the owner as ${result.id}, kept until ${result.expiresAt.slice(0, 10)}. Delete it any time: npm run session -- delete ${result.id}`) + return 0 + } + if (command === 'list') { + const { sessions } = await boardRequest('/agent-sessions', { token: await token() }) + if (!sessions.length) console.log('You have not shared any sessions.') + for (const item of sessions) console.log(`${item.id} ${item.createdAt.slice(0, 10)} ${item.agent} ${item.entries} entries ${item.branch ?? ''} kept until ${item.expiresAt.slice(0, 10)}`) + return 0 + } + if (command === 'get' || command === 'delete') { + if (!arg) { console.error(`Name the session: npm run session -- ${command} `); return 2 } + const result = await boardRequest('/agent-sessions/' + encodeURIComponent(arg), { method: command === 'get' ? 'GET' : 'DELETE', token: await token() }) + console.log(command === 'get' ? JSON.stringify(result, null, 2) : `Deleted ${result.deleted}.`) + return 0 + } + if (command === 'pull') { + // The owner's site account, which carries the administrator role: typed in, or from the environment for this command. + const email = (process.env.MODWERK_EMAIL ?? '').trim() || (await ask('Modwerk account email: ')).trim() + const password = process.env.MODWERK_PASSWORD || await ask('Password (not shown, not stored): ', true) + if (!email || !password) { console.error('Pulling needs your Modwerk account: type its email and password when asked, or set MODWERK_EMAIL and MODWERK_PASSWORD for this command.'); return 2 } + const folder = join(homedir(), '.cache', 'modwerk-local', 'sessions') + const count = await asAccount({ email, password }, session => pullSessions(folder, async path => (await accountRequest(path, { session })).value).catch(error => { + // Signed in, but the account is not an administrator: the Worker answers as for nobody signed in. + if (error instanceof BoardError && (error.status === 401 || error.status === 403)) throw new BoardError('This account does not have the administrator role, so it cannot read shared sessions.', error.status) + throw error + })) + console.log(`${count} shared sessions in ${folder} (INDEX.md lists them).`) + return 0 + } + console.log('npm run session -- status | prefer ask|always|never | preview | share --note "…" [--skip 3,7] [--file ] | list | get | delete | pull') + return command === 'help' ? 0 : 2 +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { + main().then(code => { process.exitCode = code }, error => { + console.error(error instanceof BoardError || error instanceof BoardUnavailable ? error.message : error.stack ?? String(error)) + process.exitCode = 1 + }) +} diff --git a/scripts/agent-session.test.mjs b/scripts/agent-session.test.mjs new file mode 100644 index 0000000000..c19979f555 --- /dev/null +++ b/scripts/agent-session.test.mjs @@ -0,0 +1,64 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { mkdtemp, readFile, readdir, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { gzipSync } from 'node:zlib' +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 { BoardError } from './agent-board.mjs' + +const password = 'private session pull test passphrase' +const cleanup = [] +afterEach(async () => { vi.unstubAllGlobals(); for (const step of cleanup.splice(0)) await step() }) + +async function fixture() { + const server = await testServer() + const site = process.env.MODWERK_SITE + process.env.MODWERK_SITE = 'https://octamod.test' + cleanup.push(() => { server.db.close(); if (site === undefined) delete process.env.MODWERK_SITE; else process.env.MODWERK_SITE = site }) + // Account mail goes out through fetch: keep the verification link it carries. + const mails = [] + vi.stubGlobal('fetch', vi.fn(async (_url, init) => { mails.push(JSON.parse(String(init.body))); return Response.json({ id: 'mock-email' }) })) + async function member(username, admin = false) { + const email = username + '@example.test' + expect((await server.call('/auth/register', 'POST', { rulesVersion: COMMUNITY_RULES_VERSION, username, email, password })).status).toBe(202) + const token = mails.at(-1).text.match(/#account\/verify\/([^\s]+)/)[1] + expect((await server.call('/auth/verify', 'POST', { token, password })).status).toBe(200) + if (admin) server.db.prepare('UPDATE users SET is_admin=1 WHERE username=?').run(username) + return email + } + const options = { api: 'https://api.example.test/api', fetch: (url, init) => handleCommunity(new Request(url, { ...init, headers: { 'CF-Connecting-IP': '192.0.2.1', ...init.headers } }), server.env) } + server.db.prepare("INSERT INTO users(id,username,display_name,github_id,github_login) VALUES('u1','porter','Porter',7,'first-porter')").run() + const session = { format: 1, agent: 'claude-code', note: 'The doctor said nothing.', entries: [{ who: 'developer', text: 'Port the tape echo.' }], removed: {} } + server.db.prepare("INSERT INTO agent_sessions(id,user_id,agent,note,entries,consent_version,bytes,data,created_at) VALUES('00000000-0000-4000-8000-000000000001','u1','claude-code','The doctor said nothing.',1,?,10,?,?)") + .run(SESSION_CONSENT_VERSION, gzipSync(JSON.stringify(session)).toString('base64'), new Date().toISOString()) + const folder = await mkdtemp(join(tmpdir(), 'sessions-')) + cleanup.push(() => rm(folder, { recursive: true, force: true })) + return { ...server, member, options, folder } +} + +describe('npm run session -- pull', () => { + it('signs in with the owner\'s account, saves every shared session, and signs out again', async () => { + const { member, options, folder } = await fixture() + const email = await member('owner', true) + let used + const count = await asAccount({ email, password }, session => { used = session; return pullSessions(folder, async path => (await accountRequest(path, { ...options, session })).value) }, options) + expect(count).toBe(1) + const files = (await readdir(folder)).sort() + expect(files).toEqual([expect.stringMatching(/^\d{4}-\d{2}-\d{2}-first-porter-00000000\.json$/), 'INDEX.md']) + expect(JSON.parse(await readFile(join(folder, files[0]), 'utf8'))).toMatchObject({ login: 'first-porter', session: { entries: [{ text: 'Port the tape echo.' }] } }) + expect(await readFile(join(folder, 'INDEX.md'), 'utf8')).toContain('«The doctor said nothing.»') + // Signed out: the session the pull used no longer reads anything. + await expect(accountRequest('/agent-sessions?all=1', { ...options, session: used })).rejects.toBeInstanceOf(BoardError) + }) + + it('refuses a wrong password and an account without the administrator role', async () => { + const { member, options, folder } = await fixture() + const admin = await member('owner', true), plain = await member('somebody') + await expect(asAccount({ email: admin, password: 'not the right passphrase' }, () => { throw new Error('must not run') }, options)).rejects.toBeInstanceOf(BoardError) + await expect(asAccount({ email: plain, password }, session => pullSessions(folder, async path => (await accountRequest(path, { ...options, session })).value), options)).rejects.toMatchObject({ status: 401 }) + }) +}) diff --git a/scripts/author-update-git.test.mjs b/scripts/author-update-git.test.mjs index 7d018abe7b..d5107ce773 100644 --- a/scripts/author-update-git.test.mjs +++ b/scripts/author-update-git.test.mjs @@ -126,6 +126,17 @@ describe('independent author release verification', () => { const f = fixture(); github(f, { owner: true, withdraw: true }) expect(await fetchReleaseApproval(repository, f.merge, ownerId, 'fixture', 1, 0, { root: f.root })).toMatchObject({ moduleApproverId: ownerId, mergedBy: 'repeat98' }) }) + it('publishes a worker merge only with the recorded base and head as its two parents', async () => { + const f = fixture(), tree = f.git('rev-parse', f.head + '^{tree}') + for (const base of [f.base, 'f'.repeat(40)]) { + const message = 'Modwerk reviewed merge\nBase: ' + base + '\nHead: ' + f.head + '\nReview: 81\nApproved by: tester (42, device-reviewer)' + f.merge = f.git('commit-tree',tree,'-p',f.base,'-p',f.head,'-m','Merge reviewed PR','-m',message) + github(f, { owner:true }) + const evidence = fetchReleaseApproval(repository,f.merge,ownerId,'fixture',1,0,{ root:f.root }) + if (base === f.base) await expect(evidence).resolves.toMatchObject({ authorization:'device-reviewer', reviewerId:42, reviewId:81 }) + else await expect(evidence).rejects.toThrow('parents differ') + } + }) it.each([{ botId: 1 }, { withdraw: true }, { head: 'f'.repeat(40) }, { author: { ...author, id: 1 } }, { conclusion: 'failure' }, { base: 'f'.repeat(40) }])('keeps the previous release when GitHub evidence is invalid: %j', async options => { const f = fixture(); github(f, options) await expect(fetchReleaseApproval(repository, f.merge, ownerId, 'fixture', 1, 0, { root: f.root })).rejects.toThrow() diff --git a/scripts/diagnostics-pull.mjs b/scripts/diagnostics-pull.mjs index 19d0a94392..6f7268d928 100644 --- a/scripts/diagnostics-pull.mjs +++ b/scripts/diagnostics-pull.mjs @@ -53,9 +53,16 @@ const REFUSALS = Object.assign(['no refusal', 'malformed', 'module memory', 'con /** An incident from the unit's own log (diag.c): when in its session, what, and what the unit was doing. */ const ids = r => [...r.machines, ...r.fx, ...r.keys].slice(0, 4 * r.a).map((b, i, all) => i % 4 ? '' : all.slice(i, i + 4).map(x => x.toString(16).padStart(2, '0')).join('')).filter(Boolean) const STATELESS = ['crash', 'stall', 'set', 'base'] // records that carry no cpu, keys or screen +/** A refused restore's set record from base 0.7.10 on (diag.c): the loader's check that refused it (dsp1, read as dsp1to4; + * loader.h runtime_check) and the module pool then, in 16-byte units (cpu the bytes used, dsp0 the largest free run, read as + * dsp5to8). Older bases leave all three 0. A module-memory refusal by the claims check is a DSP claim meeting a delay buffer. */ +const REFUSED_CHECKS = ['', 'the module pool', 'its DSP claims', 'the machine metadata', 'the DSP limits'] +const refusedPool = r => !(r.cpu || r.dsp5to8 || r.dsp1to4) ? '' : + (r.dsp1to4 ? `, by ${r.tempo24 === 2 && r.dsp1to4 === 2 ? 'its DSP claims meeting a delay buffer' : REFUSED_CHECKS[r.dsp1to4] ?? 'check ' + r.dsp1to4}` : '') + + `, module memory ${Math.round(r.cpu / 64)} KiB used, largest free block ${(r.dsp5to8 / 64).toFixed(1)} KiB` const incident = r => `#${r.seq} start ${r.boot} +${Math.floor(r.second / 60)}m${r.second % 60}s ${r.kind}` + (r.kind === 'base' ? ` ${r.a.toString(16).padStart(8, '0')}` : r.kind === 'set' ? ` ${r.a} installed: ${ids(r).map(id => MODULE_NAMES.get(id) ?? id).join(', ') || 'none'}` + - (r.tempo24 === 0x101 ? '; all held: the last start crashed or froze' : r.screen ? `; refused ${MODULE_NAMES.get(r.screen.toString(16).padStart(8, '0')) ?? r.screen.toString(16).padStart(8, '0')} (${REFUSALS[r.tempo24] ?? 'refusal ' + r.tempo24})` : '') : '') + + (r.tempo24 === 0x101 ? '; all held: the last start crashed or froze' : r.screen ? `; refused ${MODULE_NAMES.get(r.screen.toString(16).padStart(8, '0')) ?? r.screen.toString(16).padStart(8, '0')} (${REFUSALS[r.tempo24] ?? 'refusal ' + r.tempo24}${refusedPool(r)})` : '') : '') + (r.kind === 'freeze' ? (r.a ? ` ${(r.a * 16 / 44100).toFixed(1)} s` : ' until a restart') : r.kind === 'hot' ? ` (${r.a} half-seconds at 90 %+)` : r.kind === 'crash' ? ` pc 0x${r.a.toString(16)}` : r.kind === 'stall' ? ` reason ${r.a}` : r.kind === 'cpu' ? ` ${r.a & 0xffffff} machines refused for CPU, tracks ${[...Array(8).keys()].filter(t => r.a >>> 24 >> t & 1).map(t => t + 1).join(',')}` : r.kind === 'shed' ? ` ${r.a & 0xffffff} renders skipped, tracks ${[...Array(8).keys()].filter(t => r.a >>> 24 >> t & 1).map(t => t + 1).join(',')}` : '') + (STATELESS.includes(r.kind) ? '' : `, cpu ${percent(r.cpu)} T1-4 ${percent(r.dsp1to4)} T5-8 ${percent(r.dsp5to8)}, ${r.playing ? 'playing' : 'stopped'} at ${(r.tempo24 / 24).toFixed(1)} BPM, screen 0x${r.screen.toString(16)}` + `, keys ${r.keys.filter(k => k !== 255).map(k => k.toString(16)).join(' ') || '-'}, fx ${r.fx.map(f => f.toString(16)).join(' ')}, machines ${r.machines.join(' ')}`) diff --git a/scripts/diagnostics-pull.test.mjs b/scripts/diagnostics-pull.test.mjs index 461b8f2af8..01c7297299 100644 --- a/scripts/diagnostics-pull.test.mjs +++ b/scripts/diagnostics-pull.test.mjs @@ -111,6 +111,11 @@ describe('diagnostics pull', () => { const set = { seq: 4, boot: 3, second: 5, kind: 'set', a: 1, cpu: 0, dsp1to4: 0, dsp5to8: 0, machines: [0x3c, 0xbe, 0xdc, 0x9c, ...Array(20).fill(0)], fx: Array(16).fill(0), keys: Array(16).fill(0), screen: 0x773c84aa, tempo24: 5, playing: false } expect(unitLines([set])[0]).toContain('1 installed: Mini Verb; refused SC Ringmod (busy)') + // Base 0.7.10 adds the loader's check that refused it and the module pool then, in 16-byte units. + expect(unitLines([{ ...set, tempo24: 2, dsp1to4: 2, cpu: 10084, dsp5to8: 39068 }])[0]) + .toContain('refused SC Ringmod (module memory, by its DSP claims meeting a delay buffer, module memory 158 KiB used, largest free block 610.4 KiB)') + expect(unitLines([{ ...set, tempo24: 2, dsp1to4: 1, cpu: 48640, dsp5to8: 96 }])[0]) + .toContain('refused SC Ringmod (module memory, by the module pool, module memory 760 KiB used, largest free block 1.5 KiB)') }) it('calls a stall found at a start on another base an OS upgrade, and one on the same base nothing', () => { const at = (seq, boot, kind, a = 0) => ({ seq, boot, second: 0, kind, a, cpu: 0, dsp1to4: 0, dsp5to8: 0, machines: Array(24).fill(0), diff --git a/scripts/maintenance-bot/act.mjs b/scripts/maintenance-bot/act.mjs index ce1aa91ebe..c938b67fff 100644 --- a/scripts/maintenance-bot/act.mjs +++ b/scripts/maintenance-bot/act.mjs @@ -7,7 +7,7 @@ import { tagDiscordLinks } from '../../server/site-link-tags.ts' import { existsSync, readFileSync } from 'node:fs' import { join } from 'node:path' import { TODO_COMMAND, actionId, classify } from './policy.mjs' -import { MARKER, discord, github, ledger, pages, readBoardTarget, readDiscordTarget, readTarget } from './lib.mjs' +import { MARKER, approveRun, discord, github, ledger, pages, readBoardTarget, readDiscordTarget, readTarget } from './lib.mjs' import { dailyReport } from './report.mjs' const daily = process.env.BOT_MODE === 'daily', dir = process.env.BOT_DIR ?? 'bot' @@ -171,7 +171,7 @@ async function carryOut(action) { case 'approve_run': { const runs = (await api('/actions/runs?status=action_required&head_sha=' + now.head + '&per_page=30')).workflow_runs ?? [] if (!runs.length) return ['expired', 'no run waits any more'] - for (const run of runs) await api('/actions/runs/' + run.id + '/approve', 'POST') + for (const run of runs) await approveRun(api, run.id) return ['done', runs.length + ' run' + (runs.length === 1 ? '' : 's') + ' started'] } case 'close': diff --git a/scripts/maintenance-bot/first-release.mjs b/scripts/maintenance-bot/first-release.mjs new file mode 100644 index 0000000000..90cc395af8 --- /dev/null +++ b/scripts/maintenance-bot/first-release.mjs @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: Elastic-2.0 +// Copyright (c) 2026 Jannik Aßfalg (repeat98) +// Inspect PR objects as data from a checkout of trusted main. Never run or check out module code here. +import { execFileSync } from 'node:child_process' +import { isDeepStrictEqual as equal } from 'node:util' +import { parseAuthorRegistry } from '../../src/release/author-updates.ts' + +const registry = '.github/module-authors.json' +const safeId = /^[a-z0-9]+(?:-[a-z0-9]+)*$/ +function requireScope(ok, message) { if (!ok) throw new Error(message) } + +function oneNewRow(before, after, field, id) { + const rows = after[field].filter(row => row.id === id) + requireScope(rows.length === 1 && !before[field].some(row => row.id === id) && + equal(before, { ...after, [field]: after[field].filter(row => row.id !== id) }), 'Only the new module row may change in ' + field) + return rows[0] +} + +export function inspectFirstRelease(root, base, head, author, reviewer) { + requireScope([head, base].every(sha => /^[a-f0-9]{40}$/.test(sha)), 'Expected exact commits') + const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 32 * 1024 * 1024 }) + git('merge-base', '--is-ancestor', base, head) + const json = (ref, path) => JSON.parse(git('show', ref + ':' + path)) + const paths = git('diff', '--no-renames', '--name-only', '-z', base, head).split('\0').filter(Boolean) + const manifest = paths.filter(path => /^sdk\/[a-z0-9-]+\/modules\/[a-z0-9-]+\/(octamod|modwerk)\.module\.json$/.test(path)) + requireScope(manifest.length === 1, 'Expected one new module') + const path = manifest[0], folder = path.slice(0, path.lastIndexOf('/')), doc = json(head, path) + const octatrack = path.endsWith('/octamod.module.json'), machine = octatrack ? 'octatrack' : doc.machine, id = doc.id + requireScope(typeof id === 'string' && safeId.test(id) && typeof machine === 'string' && safeId.test(machine) && + !git('ls-tree', base, '--', folder), 'Expected a new module folder') + const profile = json(base, 'sdk/machines/' + machine + '/machine.json') + requireScope(profile.id === machine && folder === profile.sdk?.modules + '/' + id, 'Module is outside its device folder') + requireScope(profile.deviceReviewers?.includes(reviewer.id), 'Reviewer is not assigned to ' + machine) + const login = author.login.toLowerCase() + requireScope(author.type === 'User' && Number.isSafeInteger(author.id) && author.id > 0 && doc.author?.github?.toLowerCase() === login, 'The submitting GitHub user must be the module author') + const owners = [doc.author.github, ...(doc.maintainers ?? []), ...(doc.author.contributors ?? []).map(person => person.github)] + requireScope(author.id !== reviewer.id && !owners.some(name => name.toLowerCase() === reviewer.login.toLowerCase()), 'A reviewer cannot approve their own module') + requireScope(!doc.tests?.releaseWaiver && doc.tests?.qualification?.hardware?.kind !== 'owner-waived', 'Waivers need owner review') + + const accounts = parseAuthorRegistry(json(base, registry)).accounts + const nextAccounts = parseAuthorRegistry(json(head, registry)).accounts + requireScope((!Object.hasOwn(accounts, login) || accounts[login] === author.id) && + !Object.entries(accounts).some(([name, id]) => name !== login && id === author.id) && + equal(nextAccounts, { ...accounts, [login]: author.id }), 'Register only the submitting modder with their numeric GitHub ID') + + const key = octatrack ? id : machine + '-' + id + const allowed = new Set([registry, 'src/community/module-changelogs/' + key + '.json']) + const added = new Set(git('diff', '--no-renames', '--diff-filter=A', '--name-only', '-z', base, head).split('\0').filter(Boolean)) + requireScope(added.has('src/community/module-changelogs/' + key + '.json'), 'First release requires new release notes') + // Git modes are part of the diff. A link, submodule, or mode change cannot borrow an allowed filename. + const diff = git('diff', '--raw', '-z', '--no-renames', base, head).trimEnd().split('\0') + for (let i = 0; i < diff.length - 1; i += 2) { + const [oldMode, mode] = diff[i].slice(1).split(' ') + requireScope(['100644', '100755', '000000'].includes(mode) && ['100644','100755','000000'].includes(oldMode) && + (mode === '000000' || oldMode === '000000' || mode === oldMode), 'Only regular module files may change') + } + + if (octatrack) { + for (const [file, field] of [['sdk/catalog.json', 'modules'], ['src/catalog/module-documents.json', 'modules'], ['src/engine/assets/octatrack-module-packages.json', 'packages']]) { + const row = oneNewRow(json(base, file), json(head, file), field, id) + requireScope(row.version === doc.version, 'Release versions must match') + allowed.add(file) + if (field === 'packages') { + const binary = 'public/octatrack-modules/' + id + '/' + doc.version + '.mwrm' + requireScope('public/' + row.path === binary && added.has(binary), 'Expected a new module package') + allowed.add(binary) + } + } + } + const fxIds = 'sdk/machines/' + machine + '/fx-ids.json' + if (paths.includes(fxIds)) { + const before = json(base, fxIds), after = json(head, fxIds) + const slots = Object.keys(after.ids).filter(slot => !Object.hasOwn(before.ids, slot)) + requireScope(slots.length === 1 && /^[1-9]\d?$/.test(slots[0]) && Number(slots[0]) <= 63 && after.ids[slots[0]] === id && + !Object.values(before.ids).includes(id) && equal(after, { ...before, ids: { ...before.ids, [slots[0]]: id } }), 'Only the new effect id may be assigned') + allowed.add(fxIds) + } + const deviceKey = machine === 'digitakt' || machine === 'digitone' ? machine + '-mk1' : machine.replace(/-(?:mk)?ii$/, '-mk2').replace(/-mki$/, '-mk1') + for (const file of paths.filter(path => /^sdk\/imports\/[a-z0-9.-]+\.json$/.test(path))) { + requireScope(added.has(file), 'Existing import records cannot change') + const record = json(head, file) + if (file.startsWith('sdk/imports/elekloader-')) { + requireScope(profile.sdk.platform === 'elemod' && record.cores?.length === 0 && record.mods?.length > 0, 'Expected a module package record') + for (const pin of record.mods) { + requireScope(pin.id === id && pin.device === deviceKey && [doc.version, doc.version.split('-')[0]].includes(pin.version) && + /^[a-zA-Z0-9._-]+\.elemod$/.test(pin.file), 'Package belongs to another module, device or version') + const served = 'vendor/elekloader/catalog/' + pin.file + requireScope(added.has(served), 'A first release must ship its own new package') + const artifact = json(head, served) + requireScope(artifact.id === id && artifact.target?.device === deviceKey && artifact.version === pin.version, 'Package identity differs from its pin') + for (const target of ['vendor/elekloader/catalog/' + pin.file, 'sdk/imports/packages/' + id + '/' + pin.file]) { + if (paths.includes(target)) { requireScope(added.has(target), 'Existing packages cannot change'); allowed.add(target) } + } + } + } else { + requireScope(record.module === machine + '/' + id || (octatrack && equal(record.modules, [id]) && record.files?.every(f => f.path.startsWith('modules/' + id + '/'))), 'Import must name only this module') + } + allowed.add(file) + } + if (profile.sdk.platform === 'zdl' && /^[a-z0-9._-]+\.zdl$/i.test(doc.platform?.file)) { + const binary = 'public/zoom-effects/' + id + '/' + doc.version + '/' + doc.platform.file + requireScope(added.has(binary), 'Expected a new ZDL binary') + allowed.add(binary) + } + for (const file of paths) { + if (file.startsWith(folder + '/') || allowed.has(file)) continue + // An Octatrack draft can be removed when its own finished module moves into the library. + if (octatrack && file.startsWith('sdk/drafts/' + id + '/') && !git('ls-tree', head, '--', file)) continue + throw new Error('Outside the first release: ' + file) + } + return { machine, module: key, registered: !Object.hasOwn(accounts, login) } +} diff --git a/scripts/maintenance-bot/lib.mjs b/scripts/maintenance-bot/lib.mjs index e080d7563b..0b5a271c97 100644 --- a/scripts/maintenance-bot/lib.mjs +++ b/scripts/maintenance-bot/lib.mjs @@ -6,6 +6,8 @@ import { githubApi, pages } from '../author-release-api.mjs' export { pages } export const MARKER = '' +export const approveRun = (api, id) => api('/actions/runs/' + id + '/approve', 'POST') + export function github() { const repository = process.env.GITHUB_REPOSITORY, token = process.env.GITHUB_TOKEN if (!repository || !token) throw new Error('GITHUB_REPOSITORY and GITHUB_TOKEN are required.') diff --git a/scripts/maintenance-bot/review-merge.mjs b/scripts/maintenance-bot/review-merge.mjs new file mode 100644 index 0000000000..82f923c465 --- /dev/null +++ b/scripts/maintenance-bot/review-merge.mjs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: Elastic-2.0 +// Copyright (c) 2026 Jannik Aßfalg (repeat98) +// An explicit command in a new PR comment, backed by the sender's current approving GitHub review. +import { execFileSync } from 'node:child_process' +import { readFileSync } from 'node:fs' +import { pathToFileURL } from 'node:url' +import { authorChecks, githubApi, pages } from '../author-release-api.mjs' +import { readChangeScope } from '../change-scope.mjs' +import { inspectFirstRelease } from './first-release.mjs' +import { approveRun, ledger } from './lib.mjs' + +export function mergeCommand(event) { + const actor = event.comment?.user, head = /^\/modwerk merge ([0-9a-f]{40})$/.exec(event.comment?.body?.trim() ?? '')?.[1] + if (event.action !== 'created' || !event.issue?.pull_request || !head || actor?.type !== 'User' || + !Number.isSafeInteger(actor.id) || actor.id <= 0 || actor.id !== event.sender?.id || actor.login !== event.sender.login || + !Number.isSafeInteger(event.issue.number) || event.issue.number < 1) throw new Error('Expected a new merge command for an exact PR commit') + return { actor, head, number: event.issue.number } +} + +export function currentApproval(reviews, actorId, head) { + const latest = reviews.filter(review => review.user?.id === actorId && ['APPROVED', 'CHANGES_REQUESTED', 'DISMISSED'].includes(review.state)).at(-1) + if (!latest || latest.state !== 'APPROVED' || latest.commit_id !== head) throw new Error('Approve the current PR commit before requesting its merge') + return latest.id +} + +export async function mergeReviewed({ event, repository, api, bot, root = process.cwd() }) { + const { number, head, actor } = mergeCommand(event) + const pull = () => api('/pulls/' + number) + function checkPull(pr, base) { + if (pr.state !== 'open' || pr.draft || pr.base.ref !== 'main' || pr.base.repo.full_name !== repository || + pr.base.sha !== base || pr.head.sha !== head || pr.user.id === actor.id) throw new Error('Expected an open, independently reviewed PR at the checked base and head') + } + const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore','pipe','pipe'] }).trim() + const pr = await pull(), base = git('rev-parse', 'HEAD') + checkPull(pr, base) + const reviews = () => pages(api, '/pulls/' + number + '/reviews') + currentApproval(await reviews(), actor.id, head) + git('fetch', '--no-tags', 'origin', 'refs/pull/' + number + '/head') + if (git('rev-parse', 'FETCH_HEAD') !== head) throw new Error('The reviewed head changed') + git('merge-base', '--is-ancestor', base, head) + + // Permission is GitHub's current effective repository permission. Read and triage remain device-scoped. + const permissions = await api('/collaborators/' + encodeURIComponent(actor.login) + '/permission').catch(error => { + if (error.message.endsWith(' HTTP 404')) return {} + throw error + }) + const maintainer = permissions.user?.id === actor.id && ['admin', 'maintain', 'write'].includes(permissions.permission) + if (maintainer && actor.id !== event.repository?.owner?.id && git('diff', '--name-only', base, head, '--', 'sdk/approvals/')) { + throw new Error('Owner-signed build approvals require the repository owner') + } + const scope = maintainer ? {} : inspectFirstRelease(root, base, head, pr.user, actor) + const waiting = await api('/actions/workflows/module-pr.yml/runs?event=pull_request&status=action_required&head_sha=' + head + '&per_page=1') + const run = waiting.workflow_runs[0] + if (run) { + if (!Number.isSafeInteger(run.id) || run.id < 1 || run.event !== 'pull_request' || run.head_sha !== head || + run.repository?.full_name !== repository || run.head_repository?.full_name !== pr.head.repo?.full_name || + !run.head_repository?.full_name || run.head_branch !== pr.head.ref || run.path !== '.github/workflows/module-pr.yml' || + run.pull_requests?.length && !run.pull_requests.some(p => p.number === number)) throw new Error('Waiting CI run does not match the reviewed submission') + if ((await bot('/state')).paused) throw new Error('Maintenance is paused') + currentApproval(await reviews(), actor.id, head) + checkPull(await pull(), base) + await approveRun(api, run.id) + console.log('Started Module PR checks for PR #' + number + '. After they pass, post the merge command again for ' + head + '.') + return + } + const changes = readChangeScope({ root, base, head }) + const checkRun = await authorChecks(api, repository, head, base, { octatrack: changes.modules, elemodCompile: changes.elemod, requireAggregate: true }) + const review = currentApproval(await reviews(), actor.id, head) + checkPull(await pull(), base) + if ((await api('/git/ref/heads/main')).object.sha !== base) throw new Error('Main changed during review') + const result = await bot('/merge/reviewed', 'POST', { number, sha: head, method: 'merge', review: { + base, id: review, actorId: actor.id, login: actor.login, role: maintainer ? 'maintainer' : 'device-reviewer', ...scope, checkRun, + } }) + console.log('Merged PR #' + number + ' at ' + result.sha + ' on approval by @' + actor.login) +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const repository = process.env.GITHUB_REPOSITORY + await mergeReviewed({ event: JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8')), repository, + api: githubApi(repository, process.env.GITHUB_TOKEN), bot: ledger() }) +} diff --git a/scripts/maintenance-bot/review-merge.test.mjs b/scripts/maintenance-bot/review-merge.test.mjs new file mode 100644 index 0000000000..7f1c0a745a --- /dev/null +++ b/scripts/maintenance-bot/review-merge.test.mjs @@ -0,0 +1,108 @@ +import { describe, expect, it, afterEach, vi } from 'vitest' +import { execFileSync } from 'node:child_process' +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { tmpdir } from 'node:os' +import { inspectFirstRelease } from './first-release.mjs' +import { mergeCommand, currentApproval, mergeReviewed } from './review-merge.mjs' + +const roots = [], reviewer = { login: 'tester', id: 42, type: 'User' }, author = { login: 'maker', id: 77, type: 'User' } +const repo = 'org/repo', profile = 'sdk/machines/digitakt/machine.json', registry = '.github/module-authors.json' +const manifest = 'sdk/digitakt/modules/example/modwerk.module.json' +const draft = { machine: 'digitakt', id: 'example', version: '1.0.0', author: { github: 'maker' } } +const event = head => ({ action: 'created', sender: reviewer, issue: { number: 3, pull_request: {} }, comment: { user: reviewer, body: '/modwerk merge ' + head } }) +afterEach(() => roots.splice(0).forEach(dir => rmSync(dir, { recursive: true, force: true }))) + +function fixture(edits = {}, baseFiles = {}) { + const root = mkdtempSync(join(tmpdir(), 'modwerk-device-review-')); roots.push(root) + const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore','pipe','pipe'] }).trim() + function commit(files) { + for (const [name, value] of Object.entries(files)) { + const path = join(root, name) + mkdirSync(dirname(path), { recursive: true }) + writeFileSync(path, JSON.stringify(value)) + } + git('add','.'); git('commit','-qm','fixture') + return git('rev-parse','HEAD') + } + git('init','-q'); git('config','user.name','Fixture'); git('config','user.email','test@example.com') + const base = commit({ [profile]: { id: 'digitakt', sdk: { modules: 'sdk/digitakt/modules', platform: 'elemod' }, deviceReviewers: [42] }, + [registry]: { schemaVersion: 1, accounts: { owner: 99 } }, ...baseFiles }) + const head = commit({ [registry]: { schemaVersion: 1, accounts: { owner: 99, maker: 77 } }, [manifest]: draft, + 'src/community/module-changelogs/digitakt-example.json': [], ...edits }) + git('update-ref','refs/pull/3/head',head); git('remote','add','origin',root); git('checkout','-q',base) + return { root, base, head, inspect: () => inspectFirstRelease(root,base,head,author,reviewer) } +} + +describe('device-scoped first releases', () => { + it('registers the submitting modder in the same release and accepts already registered authors', () => { + expect(fixture().inspect()).toEqual({ machine: 'digitakt', module: 'digitakt-example', registered: true }) + expect(fixture({}, { [registry]: { schemaVersion: 1, accounts: { owner: 99, maker: 77 } } }).inspect().registered).toBe(false) + }) + it('accepts native package imports only for the new module and its device', () => { + const name = 'example-1.0.0.elemod', target = { device:'digitakt-mk1' } + const files = { + 'sdk/imports/elekloader-example.json': { cores:[],mods:[{ id:'example',device:target.device,version:'1.0.0',file:name }] }, + 'sdk/imports/example.json': { module:'digitakt/example' }, + ['vendor/elekloader/catalog/'+name]: { id:'example',version:'1.0.0',target }, + } + expect(fixture(files).inspect().machine).toBe('digitakt') + files['vendor/elekloader/catalog/'+name].target = { device:'digitone-mk1' } + expect(fixture(files).inspect).toThrow('identity') + }) + it.each([ + [{ 'sdk/digitone/modules/other/x.c': 'foreign' }, {}], + [{ 'sdk/digitakt/core/change.c': 'shared' }, {}], + [{ [registry]: { schemaVersion: 1, accounts: { owner: 99, maker: 12 } } }, {}], + [{ [registry]: { schemaVersion: 1, accounts: { maker: 77 } } }, {}], + [{ [registry]: { schemaVersion: 1, accounts: { owner: 99, maker: 77, extra: 23 } } }, {}], + [{ [profile]: { id: 'digitakt', deviceReviewers: [42] } }, { [profile]: { id: 'digitakt', sdk: { modules: 'sdk/digitakt/modules' }, deviceReviewers: [43] } }], + [{ [manifest]: { ...draft, maintainers: ['Tester'] } }, {}], + [{ [manifest]: { ...draft, author: { github:'maker', contributors:[{github:'tester'}] } } }, {}], + [{ [manifest]: { ...draft, author: { github: 'elsewhere' } } }, {}], + [{ [manifest]: { ...draft, tests: { releaseWaiver: true } } }, {}], + [{}, { [manifest]: { ...draft, version: '0.0.1' } }], + [{ 'sdk/imports/elekloader-example.json': { cores: [], mods: [{ id: 'example', file: 'other.elemod', device: 'digitone-mk1' }] } }, {}], + ])('rejects changes outside the assignment or registration', (changes, base) => { + expect(fixture(changes,base).inspect).toThrow() + }) + it('requires the original sender and their latest independent approval at the exact commit', () => { + const head = 'a'.repeat(40), approved = { id: 19, state: 'APPROVED', user: reviewer, commit_id: head } + expect(mergeCommand(event(head))).toMatchObject({ head, number: 3 }) + expect(() => mergeCommand({ ...event(head), action: 'edited' })).toThrow() + expect(() => mergeCommand({ ...event(head), sender: author })).toThrow() + expect(currentApproval([approved],42,head)).toBe(19) + for (const state of ['DISMISSED','CHANGES_REQUESTED']) expect(() => currentApproval([approved,{ ...approved,state }],42,head)).toThrow() + expect(() => currentApproval([approved],42,'b'.repeat(40))).toThrow() + }) + it.each([['read','device-reviewer'],['write','maintainer']])('uses the existing worker with the live %s role and checked CI', async (permission, role) => { + const { root,base,head } = fixture(), review = { id: 19, state: 'APPROVED', user: reviewer, commit_id: head } + const pr = { state: 'open', draft: false, base: { ref: 'main', repo: { full_name: repo }, sha: base }, head: { sha: head,ref:'first-release',repo:{full_name:'maker/repo'} }, user: author } + const results = { + '/pulls/3': pr, '/pulls/3/reviews?per_page=100&page=1': [review], '/collaborators/tester/permission': { permission, user: reviewer }, + ['/actions/workflows/module-pr.yml/runs?event=pull_request&status=action_required&head_sha='+head+'&per_page=1']: { workflow_runs:[] }, + '/actions/workflows/module-pr.yml': { id: 51 }, ['/actions/workflows/51/runs?event=pull_request&head_sha='+head+'&per_page=1']: { workflow_runs: [ + { id: 98, head_sha: head, status: 'completed', conclusion: 'success', workflow_id: 51, repository: { full_name: repo }, path: '.github/workflows/module-pr.yml', event: 'pull_request' }] }, + '/actions/runs/98/jobs?filter=latest&per_page=100&page=1': { jobs: ['scope / '+base+' / '+head,'module-contract','elemod-source','octatrack-source','module-pr-ok'].map(name => ({ name,status:'completed',conclusion:'success' })) }, + '/git/ref/heads/main': { object: { sha: base } }, + } + const api = vi.fn(path => Promise.resolve(results[path])), bot = vi.fn(async path => path === '/state' ? { paused:false } : { sha: 'abc' }) + await mergeReviewed({ event:event(head), repository:repo, api, bot, root }) + expect(bot).toHaveBeenCalledWith('/merge/reviewed','POST',expect.objectContaining({ number:3, sha:head, review: expect.objectContaining({ role,base,actorId:42,id:19,checkRun:98 }) })) + results['/git/ref/heads/main'].object.sha = 'f'.repeat(40) + await expect(mergeReviewed({ event:event(head), repository:repo, api, bot, root })).rejects.toThrow('Main changed') + expect(bot).toHaveBeenCalledTimes(1) + results['/git/ref/heads/main'].object.sha = base + const held = { id:71,event:'pull_request',head_sha:head,head_branch:pr.head.ref,head_repository:pr.head.repo,repository:pr.base.repo, + path:'.github/workflows/module-pr.yml',pull_requests:[] } + results['/actions/workflows/module-pr.yml/runs?event=pull_request&status=action_required&head_sha='+head+'&per_page=1'].workflow_runs.push(held) + api.mockClear(); bot.mockClear() + await mergeReviewed({ event:event(head), repository:repo, api, bot, root }) + expect(api).toHaveBeenCalledWith('/actions/runs/71/approve','POST') + expect(bot.mock.calls).toEqual([['/state']]) + held.head_repository = { full_name:'other/repo' } + api.mockClear() + await expect(mergeReviewed({ event:event(head), repository:repo, api, bot, root })).rejects.toThrow('does not match') + expect(api).not.toHaveBeenCalledWith('/actions/runs/71/approve','POST') + }) +}) diff --git a/scripts/pr-ready.mjs b/scripts/pr-ready.mjs index 53420d51a0..0c62789fb9 100644 --- a/scripts/pr-ready.mjs +++ b/scripts/pr-ready.mjs @@ -67,7 +67,7 @@ export function readiness({ python = null, dirty = [], behind = false, remote = 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.') - } else notes.push('Without --author this is a new module or a shared change: the owner reviews it and merges it with one click once CI is green.') + } else notes.push('For a first release, ask a device reviewer or repository maintainer to review and merge once CI is green. Shared changes go to a maintainer.') // pr:ready has no toolchain, so it can only say which packages CI rebuilds in Docker and how to reproduce them first (DEVELOPER_WORKFLOW.md, "Compiled packages"). if (compiled?.octatrack) notes.push('CI rebuilds the Octatrack packages (octatrack-source) and requires the committed ones to match. pr:ready cannot run that: before you push, reproduce them with bash scripts/build-modules-isolated.sh from a clean, committed tree ("Compiled packages" in docs/DEVELOPER_WORKFLOW.md).') if (compiled?.elemod) notes.push('CI rebuilds the Digitakt, Digitone, Rytm and Four packages (elemod-source) and requires the committed ones to match. pr:ready cannot run that: before you push, run bash scripts/build-elemod-isolated.sh and node scripts/verify-elemod-release-exports.mjs from a clean, committed tree ("Compiled packages" in docs/DEVELOPER_WORKFLOW.md).') @@ -162,6 +162,8 @@ async function main(argv) { const verdict = readiness({ python, dirty, behind, remote, regenerated, checkPassed, author, scope, guideEdits, gateEdits: gateEdits(changed), baseEdits: baseEdits(changed), instrument: instrumentFiles(changed), compiled, board }) console.log('') for (const line of verdict.problems) console.log('✗ ' + line) + // Once the work is ready, the agent asks whether to share the session with the owner (docs/AGENT_SESSIONS.md), unless the developer said never. + if (verdict.ok) { const sharing = await import('./agent-session.mjs'), preference = await sharing.readPreference(); if (preference !== 'never') verdict.notes.push(sharing.sharingLine(preference)) } for (const line of verdict.notes) console.log('· ' + line) console.log(!verdict.ok ? 'Not ready yet.' : verdict.instrument ? 'Ready to open as a draft: the checks pass. Mark it ready for review once the exact build has run on a unit (above).' diff --git a/scripts/pr-ready.test.mjs b/scripts/pr-ready.test.mjs index 271f4a760e..24000f4d61 100644 --- a/scripts/pr-ready.test.mjs +++ b/scripts/pr-ready.test.mjs @@ -33,9 +33,9 @@ describe('pr:ready verdict', () => { expect(refused.ok).toBe(false) expect(refused.problems[0]).toContain('Licence text changes require owner review.') }) - it('tells everyone else that the owner merges once CI is green, and to rerun when main moves', () => { + it('tells everyone else who reviews first releases, and to rerun when main moves', () => { const { notes } = readiness({}) - expect(notes[0]).toContain('owner reviews it and merges it with one click') + expect(notes[0]).toContain('device reviewer or repository maintainer to review and merge') expect(notes.at(-1)).toContain('If main moves before the merge, run this again') }) it('says a change to what runs on an instrument opens as a draft until the exact build ran on a unit', () => { diff --git a/scripts/release-approval.mjs b/scripts/release-approval.mjs index fcffe81844..5bd6155e7b 100644 --- a/scripts/release-approval.mjs +++ b/scripts/release-approval.mjs @@ -11,7 +11,18 @@ export async function fetchReleaseApproval(repository, commit, ownerId, token = const api = githubApi(repository, token), root = options.root ?? fileURLToPath(new URL('../', import.meta.url)) const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim() for (let attempt = 1; attempt <= attempts; attempt++) { - try { return await fetchOwnerApproval(repository, commit, ownerId, token, 1, 0) } + try { + const approval = await fetchOwnerApproval(repository, commit, ownerId, token, 1, 0) + // The Worker merges in the owner's name. A base advance during GitHub's merge must stop publication. + const message = git('show', '-s', '--format=%b', commit) + if (message.startsWith('Modwerk reviewed merge\n')) { + const parents = git('show', '-s', '--format=%P', commit).split(' ') + const receipt = /^Modwerk reviewed merge\nBase: ([0-9a-f]{40})\nHead: ([0-9a-f]{40})\nReview: (\d+)\nApproved by: ([a-z\d-]+) \((\d+), (maintainer|device-reviewer)\)$/i.exec(message) + if (!receipt || parents.length !== 2 || parents[0] !== receipt[1] || parents[1] !== receipt[2]) throw new Error('Reviewed merge parents differ from the authorized base and head.') + return { ...approval, authorization: receipt[6], reviewId: Number(receipt[3]), reviewerId: Number(receipt[5]), checkedBase: parents[0], checkedHead: parents[1] } + } + return approval + } catch (error) { if (!error.message.startsWith('No owner-merged PR')) throw error } const pulls = await pages(api, '/commits/' + commit + '/pulls') for (const item of pulls) { diff --git a/sdk/machines/octatrack/base-binding.json b/sdk/machines/octatrack/base-binding.json index 42bbbcc447..cbb3f3c8fa 100644 --- a/sdk/machines/octatrack/base-binding.json +++ b/sdk/machines/octatrack/base-binding.json @@ -1,26 +1,26 @@ { "schema": 1, - "identity": "0d52edc1b4dffbd9d6dfe66c1b3ccb7e42b30fce7ff6701525c67bba783cabb7", + "identity": "a5f1dd2d95c126bbde27c45e6ac1e77c3d793c8a7ad41b7568eb31b1f7a76db8", "arena": 1089834464, "pool": 1087861072, "symbols": { - "modwerk_controller_write_begin": 1084872416, - "modwerk_controller_write_end": 1084872444, - "modwerk_cue_cfg_clamp": 1085109324, - "modwerk_raise_ev_mute_keep": 1085112222 + "modwerk_controller_write_begin": 1084872424, + "modwerk_controller_write_end": 1084872452, + "modwerk_cue_cfg_clamp": 1085109484, + "modwerk_raise_ev_mute_keep": 1085112382 }, "controllers": { - "sidechain-compressor": "50f6630fd2aefb1d7b33699722dfdfb2e291ea60bf56982c2b337f1d7cc0ee4f", - "output-matrix": "d2158533ed991f56948cc9ae24cf667280027a2627a03ddc71b0ba89fb20285e", - "analog-bassdrum": "c6c06f25c6a9abc771139b39d8ed803a05e5f8512a7aea9f60de07e044d332a6" + "sidechain-compressor": "567941e0575445f302ca038df2c6fbd03b1e824e076af298a6e4b9d51ffc8799", + "output-matrix": "de4418cd48194ce4d35255fd0c88617395179bb6b1fde357bf4907823f93e04e", + "analog-bassdrum": "31bc77d728b8899e1d6fef6337113acf6351ea43a81afdce93c9a1bde19e529f" }, "variants": { - "tracks-main-cue": "0d52edc1b4dffbd9d6dfe66c1b3ccb7e42b30fce7ff6701525c67bba783cabb7", - "tracks": "16ef05c1da3de47871ce73f80155d3e658df7c62bc05028f694ac1e405232d24", - "tracks-post": "08ee39dfee67ed19761e0d04917b5fdc08eb33b03b6121644f82e4324f53e983", - "main-cue": "ad8c5256987836fbfc9f6f36f671e09730ab5e0ef7dd4ccd2aa28d28af4af1ad", - "main": "78ac84091f96f057be1588ab9edd47fcdb80e871c474cc2b89e79d89395ec9c7", - "master": "f4a19eb0ea98f99dd46ada8532fe79b8d522c418c721ef3fbec78a62008e9288", - "off": "3399ca6053330dc208118d73f0cf304c3b888ecf0a685d04cc5c2277fcea7abd" + "tracks-main-cue": "a5f1dd2d95c126bbde27c45e6ac1e77c3d793c8a7ad41b7568eb31b1f7a76db8", + "tracks": "b194425c0c0d4aae99dbee8a5e02ee3fc064242643bc67719d4b74386f5d9fa5", + "tracks-post": "e84815d9e7d79bdd35b9781346c8759f6440c9c073e9fb3b5747f51d1f832823", + "main-cue": "b87f8d78201589badc44dd208d355333afaf31bad022e08a9de5fb9f4e3a531d", + "main": "f942c4bf226e5d90be253554f1583c40f8ecfc0c55850b55456f2539245f8fec", + "master": "3bda53381402ae2b466342d34b731ee1f62397bdd9ea76584e4646d03f88c827", + "off": "c3d67146768e34e1e9ca4d1ead7bc54d9c1ee1ccc8c99b49e7b895a0f211130c" } } diff --git a/sdk/machines/octatrack/base-versions.json b/sdk/machines/octatrack/base-versions.json index cff13db1be..6e5d2d4377 100644 --- a/sdk/machines/octatrack/base-versions.json +++ b/sdk/machines/octatrack/base-versions.json @@ -112,13 +112,13 @@ { "version": "0.7.10", "identities": [ - "0d52edc1b4dffbd9d6dfe66c1b3ccb7e42b30fce7ff6701525c67bba783cabb7", - "16ef05c1da3de47871ce73f80155d3e658df7c62bc05028f694ac1e405232d24", - "08ee39dfee67ed19761e0d04917b5fdc08eb33b03b6121644f82e4324f53e983", - "ad8c5256987836fbfc9f6f36f671e09730ab5e0ef7dd4ccd2aa28d28af4af1ad", - "78ac84091f96f057be1588ab9edd47fcdb80e871c474cc2b89e79d89395ec9c7", - "f4a19eb0ea98f99dd46ada8532fe79b8d522c418c721ef3fbec78a62008e9288", - "3399ca6053330dc208118d73f0cf304c3b888ecf0a685d04cc5c2277fcea7abd" + "a5f1dd2d95c126bbde27c45e6ac1e77c3d793c8a7ad41b7568eb31b1f7a76db8", + "b194425c0c0d4aae99dbee8a5e02ee3fc064242643bc67719d4b74386f5d9fa5", + "e84815d9e7d79bdd35b9781346c8759f6440c9c073e9fb3b5747f51d1f832823", + "b87f8d78201589badc44dd208d355333afaf31bad022e08a9de5fb9f4e3a531d", + "f942c4bf226e5d90be253554f1583c40f8ecfc0c55850b55456f2539245f8fec", + "3bda53381402ae2b466342d34b731ee1f62397bdd9ea76584e4646d03f88c827", + "c3d67146768e34e1e9ca4d1ead7bc54d9c1ee1ccc8c99b49e7b895a0f211130c" ] } ] diff --git a/sdk/machines/octatrack/module-adapters/controller-policies.json b/sdk/machines/octatrack/module-adapters/controller-policies.json index 7e23d1c3d5..ca30d41bde 100644 --- a/sdk/machines/octatrack/module-adapters/controller-policies.json +++ b/sdk/machines/octatrack/module-adapters/controller-policies.json @@ -2,7 +2,7 @@ { "module": "sidechain-compressor", "moduleId": 2513434262, - "controllerSha256": "50f6630fd2aefb1d7b33699722dfdfb2e291ea60bf56982c2b337f1d7cc0ee4f", + "controllerSha256": "567941e0575445f302ca038df2c6fbd03b1e824e076af298a6e4b9d51ffc8799", "sourcePolicySha256": "33d3ebe65c4f2a593644ef6b44dd8bc9a0ed66ba30ca4a8d2e05d9145c7bd283", "revisions": [ 1, @@ -21,7 +21,7 @@ { "module": "output-matrix", "moduleId": 3404814517, - "controllerSha256": "d2158533ed991f56948cc9ae24cf667280027a2627a03ddc71b0ba89fb20285e", + "controllerSha256": "de4418cd48194ce4d35255fd0c88617395179bb6b1fde357bf4907823f93e04e", "sourcePolicySha256": "0994f291fc10c4b89c827cf60802e30ba152bf49c6572027e9edc0a22524a232", "revisions": [ 1, @@ -40,7 +40,7 @@ { "module": "output-matrix", "moduleId": 3404814517, - "controllerSha256": "d2158533ed991f56948cc9ae24cf667280027a2627a03ddc71b0ba89fb20285e", + "controllerSha256": "de4418cd48194ce4d35255fd0c88617395179bb6b1fde357bf4907823f93e04e", "sourcePolicySha256": "0994f291fc10c4b89c827cf60802e30ba152bf49c6572027e9edc0a22524a232", "revisions": [ 1, @@ -59,7 +59,7 @@ { "module": "output-matrix", "moduleId": 3404814517, - "controllerSha256": "d2158533ed991f56948cc9ae24cf667280027a2627a03ddc71b0ba89fb20285e", + "controllerSha256": "de4418cd48194ce4d35255fd0c88617395179bb6b1fde357bf4907823f93e04e", "sourcePolicySha256": "0994f291fc10c4b89c827cf60802e30ba152bf49c6572027e9edc0a22524a232", "revisions": [ 1, @@ -78,7 +78,7 @@ { "module": "analog-bassdrum", "moduleId": 2883261509, - "controllerSha256": "c6c06f25c6a9abc771139b39d8ed803a05e5f8512a7aea9f60de07e044d332a6", + "controllerSha256": "31bc77d728b8899e1d6fef6337113acf6351ea43a81afdce93c9a1bde19e529f", "sourcePolicySha256": "de01b055720964e15ef927d224c4bc63bd93e75bc8062d5a76248a914f22b30a", "revisions": [ 1, diff --git a/sdk/machines/octatrack/module-adapters/controller-policy/controller_board.c b/sdk/machines/octatrack/module-adapters/controller-policy/controller_board.c index 3c89219c1e..7eb2527775 100644 --- a/sdk/machines/octatrack/module-adapters/controller-policy/controller_board.c +++ b/sdk/machines/octatrack/module-adapters/controller-policy/controller_board.c @@ -402,13 +402,15 @@ static int resources_idle(void *u, const struct mw_controller_binding *b) static int writes_blocked(void *u) { (void)u; return modwerk_saved_set_busy() != 0; } static int publication_confirmed(void *u, const struct mw_controller_binding *b) { (void)u; return live(b) && !modwerk_runtime_broken(); } -/* Nothing can resume or point into the image: unpublished, no journal that - * could roll back to it, no reviewed UI root, and for Matrix no destination - * codes left for stock to read as cue levels. */ +/* Nothing can resume or point into the image: unpublished, no journal or + * trial that could roll back to it (#1736: released while a trial ran, a + * rolled-back controller came back unbound until a power cycle), no reviewed + * UI root, and for Matrix no destination codes left for stock to read as cue + * levels. */ static int roots_clear(void *u, const struct mw_controller_binding *b) { (void)u; - if (modwerk_runtime_volatile_busy() || live(b)) return 0; + if (modwerk_runtime_volatile_busy() || modwerk_runtime_restorable(b->generation) || live(b)) return 0; if (b->identity.feature == 2u && (READ8(MATRIX_MODE) == 2u || READ8(MATRIX_MODE_CS1) == 2u)) return 0; return b->canonical_extent <= UINTPTR_MAX - b->extent_bytes && UI_CLEAR(b->canonical_extent, b->canonical_extent + b->extent_bytes); } @@ -546,6 +548,8 @@ static int engine_wanted(unsigned at) const struct mw_controller_slot *s = ®ISTRY.slots[at]; if (!held(s)) return 0; if (parked[at]) return s->state != MW_CTL_RETIRING; + /* Removed by a trial that can still roll back (#1736): kept only for the rollback, so its room is the trial's. */ + if (s->state == MW_CTL_RETIRING && modwerk_runtime_restorable(s->binding.generation)) return 0; if (roomless[at] && s->state <= MW_CTL_BOUND) return 0; return (used & s->binding.identity.feature) || s->touched || s->state > MW_CTL_BOUND; } diff --git a/sdk/machines/octatrack/module-adapters/machine-recipes.json b/sdk/machines/octatrack/module-adapters/machine-recipes.json index 62c8a9ea85..71327fe16d 100644 --- a/sdk/machines/octatrack/module-adapters/machine-recipes.json +++ b/sdk/machines/octatrack/module-adapters/machine-recipes.json @@ -493,7 +493,7 @@ }, "analog-bassdrum": { "schema": 1, - "imageSha256": "20dd04a75af737516f60a56e194b1558566f7a391ab3410167583fba66a37261", + "imageSha256": "7f90cf148938e147e024e595caa07eeca4d7c36544b54cd5b480fb009fa1380a", "sources": { "sdk/machines/octatrack/module-adapters/analog_bd_runtime.py": "b9c0e0f96632a0d0ab5283387edaae1b604e4e82e27e26b3fdc1666867d31daf", "sdk/machines/octatrack/module-adapters/analog_bd_write_lease.py": "3e6a3766f32176e9be69627ef2b71272970f2d02a2088e77673946b640d365c7", diff --git a/sdk/runtime/loader/journal.h b/sdk/runtime/loader/journal.h index 2293e5d5b0..91d6a32a2a 100644 --- a/sdk/runtime/loader/journal.h +++ b/sdk/runtime/loader/journal.h @@ -55,6 +55,10 @@ int modwerk_machine_journal_accept(const struct runtime_journal_view *,unsigned) * reopen the journal. */ void modwerk_machine_journal_idle(uint32_t generation); int modwerk_runtime_volatile_busy(void); +/* An open transaction can still put this owner generation back at a position: a trial's replaced module, or a journal + * or set row's `before`, until the trial is kept or rolled back. The controller board keeps such a slot instead of + * releasing it, so a rollback finds it held (#1736). */ +int modwerk_runtime_restorable(uint32_t generation); /* Trusted engine calls only, with captured caller context. Each function * acquires the real stable lock at its use boundary. The journal owns its * generation, candidates and baseline until exact rollback or Keep. */ diff --git a/sdk/runtime/loader/loader.c b/sdk/runtime/loader/loader.c index d3b967e0a0..f662727bf1 100644 --- a/sdk/runtime/loader/loader.c +++ b/sdk/runtime/loader/loader.c @@ -407,6 +407,21 @@ static int reachable(const struct runtime_module *m) #endif return m == candidate || m == previous; } +int modwerk_runtime_restorable(uint32_t generation) +{ + if (!generation) return 0; + for (unsigned i = 0; i < owners; ++i) { + if (owner_identity[i].generation != generation) continue; + const struct runtime_module *m = owned[i]; + if (m == previous) return 1; + for (unsigned k = 0; k < journal.progress.records; ++k) if (journal.row[k].before == m) return 1; +#ifdef MODWERK_RUNTIME_SETS + for (unsigned k = 0; k < change_set.count; ++k) if (change_set.row[k].before == m) return 1; +#endif + return 0; + } + return 0; +} /* Locked: free every extent that no position, the transaction or a paused * task's stack or saved registers can reach. Unknown task state frees nothing. */ static void reclaim(const struct runtime_context *context) diff --git a/sdk/tests/test_resident_engines_board.py b/sdk/tests/test_resident_engines_board.py index 6ca077b4cd..a172e7a91e 100644 --- a/sdk/tests/test_resident_engines_board.py +++ b/sdk/tests/test_resident_engines_board.py @@ -27,6 +27,8 @@ parked or never-used module. Mode 59: an engine is placed on all its cores or none. Mode 61 (owner, 24 October 2026): a reader goes in whatever room the Part leaves; the pick that brings its effect pays the key bus's price, or is DSP FULL. Mode 64: a core's owned channel closed from outside the engines (MKII, 27 October 2026) refuses at admission. +Modes 67-68 (#1736): a trial that removes Analog BD frees its engine's room but keeps its slot, so a rollback binds it +again; 68 is the whole-set trial `device -- set` sends, run in a build with the set backend. """ import importlib.util import hashlib @@ -435,6 +437,24 @@ def expected(units): for (unsigned k = 0; k < 4; ++k) empty[28 + k] = (uint8_t)(module >> (24 - 8 * k)); return empty; } +#ifdef MODWERK_RUNTIME_SETS +#include "journal.h" +/* An MWMS set of these packages (set_package.h) on the journal's current baseline, as `npm run device -- set` sends. */ +static uint8_t set_buf[65536]; +static unsigned set_of(const uint8_t *const *package, const unsigned *length, unsigned count) +{ + memset(set_buf, 0, sizeof set_buf); memcpy(set_buf, "MWMS", 4); set_buf[5] = 1; set_buf[7] = (uint8_t)count; + unsigned at = 80; + for (unsigned i = 0; i < count; ++i) { + assert(at + 4u + length[i] + 3u <= sizeof set_buf); + for (unsigned k = 0; k < 4; ++k) set_buf[at + k] = (uint8_t)(length[i] >> (24 - 8 * k)); + memcpy(set_buf + at + 4, package[i], length[i]); at += 4u + length[i] + (4u - length[i] % 4u) % 4u; + } + for (unsigned k = 0; k < 4; ++k) set_buf[8 + k] = (uint8_t)(at >> (24 - 8 * k)); + assert(modwerk_runtime_journal_digest(set_buf + 48)); + return at; +} +#endif static const struct mw_controller_slot *slot_for(uint32_t module, unsigned state) { for (unsigned i = 0; i < MW_CONTROLLER_SLOTS; ++i) @@ -1817,6 +1837,66 @@ def expected(units): bank_module = 0; ++board_bank; run(400); assert(slot_for(AB, MW_CTL_RETIRING)); unplaced(0, 4); unplaced(1, 4); + } else if (mode == 67) { + /* #1736 (a tester's MKII, 18 November 2026): a trial that removes Analog BD and is rolled back left it silent + * until a power cycle. The rollback brings back the same owner generation, so the board must still hold its + * slot then: it may retire it only once no transaction can restore that image. Kept, the removal releases it. */ + assert(install(pkg_ab, sizeof pkg_ab) == MU_APPLIED); + run(600); + const struct mw_controller_slot *was = slot_for(AB, MW_CTL_ACTIVE); + assert(was && dsp_mask[0] == 4 && dsp_mask[1] == 4); + placed_at(0, 4, top - 998u); placed_at(1, 4, top - 998u); + uint32_t generation = was->binding.generation; + leasing = 0; /* the trial's set no longer names it: no track renders it */ + assert(refused(removal(AB), 32) == RUNTIME_BUSY); + run(20); + assert(loader->enter(0) && loader->prepare(0, removal(AB), 32) && loader->publish(0) == MU_APPLIED); + run(400); /* the trial runs */ + assert(slot_for(AB, MW_CTL_RETIRING) && !slot_for(AB, MW_CTL_RELEASED)); + unplaced(0, 4); unplaced(1, 4); /* its room is free for the trial's modules */ + assert(loader->restore(0) && loader->leave(0)); /* rolled back */ + leasing = 0xffu; + run(600); + const struct mw_controller_slot *back = slot_for(AB, MW_CTL_ACTIVE); + assert(back && back->binding.generation == generation && dsp_mask[0] == 4 && dsp_mask[1] == 4); + placed_at(0, 4, top - 998u); placed_at(1, 4, top - 998u); + /* The same removal kept: released, its engine unplaced. */ + leasing = 0; + assert(refused(removal(AB), 32) == RUNTIME_BUSY); + run(20); + assert(install(removal(AB), 32) == MU_APPLIED); + run(400); + assert(slot_for(AB, MW_CTL_RELEASED) && !slot_for(AB, MW_CTL_RETIRING)); + unplaced(0, 4); unplaced(1, 4); +#ifdef MODWERK_RUNTIME_SETS + } else if (mode == 68) { + /* #1736 as the tester ran it: a whole-set trial (`device -- set`) that takes Analog BD out, rolled back. The set + * publishes over several calls (BUSY until the board has quiesced it) and restores one row per call. */ + assert(install(pkg_ab, sizeof pkg_ab) == MU_APPLIED); + run(600); + const struct mw_controller_slot *was = slot_for(AB, MW_CTL_ACTIVE); + assert(was && dsp_mask[0] == 4 && dsp_mask[1] == 4); + uint32_t generation = was->binding.generation; + const struct mu_backend *sets = &modwerk_runtime_set_backend; + leasing = 0; + const uint8_t *package[1] = {removal(AB)}; const unsigned length[1] = {32}; + unsigned n = set_of(package, length, 1); + assert(sets->enter(0) && sets->prepare(0, set_buf, n)); + enum mu_publication p; unsigned tries = 0; + while ((p = sets->publish(0)) == MU_PUBLISHING_MORE) { assert(++tries < 400u); run(1); } + assert(p == MU_APPLIED); + run(400); /* the trial runs */ + assert(slot_for(AB, MW_CTL_RETIRING) && !slot_for(AB, MW_CTL_RELEASED)); + unplaced(0, 4); unplaced(1, 4); + tries = 0; + while (!sets->restore(0)) { assert(++tries < 50u); run(1); } /* rolled back */ + assert(sets->leave(0)); + leasing = 0xffu; + run(600); + const struct mw_controller_slot *back = slot_for(AB, MW_CTL_ACTIVE); + assert(back && back->binding.generation == generation && dsp_mask[0] == 4 && dsp_mask[1] == 4); + placed_at(0, 4, top - 998u); placed_at(1, 4, top - 998u); +#endif } else assert(0); return 0; } @@ -1907,8 +1987,9 @@ def array(name, data, kind='uint8_t'): + MODEL) -def build(work): - flags = ['-std=c11', '-Wall', '-Wextra', '-Werror', *SANITIZE, '-fno-omit-frame-pointer', +def build(work, sets=False): + """The fixture binary; `sets` builds it with the whole-set backend (build_core.py's --module-sets) for mode 68.""" + flags = [*(['-DMODWERK_RUNTIME_SETS'] if sets else []), '-std=c11', '-Wall', '-Wextra', '-Werror', *SANITIZE, '-fno-omit-frame-pointer', '-DDL_NATIVE_TEST', '-DMW_CONTROLLER_TRANSPORT_TEST', '-DMW_CONTROLLER_BOARD_TEST', '-DMW_ENGINES_TEST', '-DMODWERK_RESIDENT_STOCK_HOOKS', '-DMODWERK_RESIDENT_ON_DEMAND', '-DMODWERK_DEV', '-DMODWERK_RUNTIME_METADATA_EXTERNAL', '-DMODWERK_FX_IDS=64', '-DMODWERK_DSP_TABLE0=%d' % TABLE, @@ -1916,9 +1997,9 @@ def build(work): '-DMODWERK_DSP_ALLOWANCE0=3120', '-DMODWERK_DSP_ALLOWANCE1=3565', '-DBOARD_ROWS', '-DBOARD_MANAGER', '-I' + str(work), '-I' + str(POLICY), '-I' + str(ADAPTER), '-I' + str(RUNTIME), '-I' + str(ELEK), '-I' + str(ROOT / 'sdk/runtime/loader'), '-I' + str(ROOT / 'sdk/runtime/upload')] - out = work / 'engines-board' + out = work / ('engines-board-sets' if sets else 'engines-board') # The board alone sees the key window through the fixture's board_buffer_ranges_idle (mode 48). - board = work / 'controller_board.o' + board = work / ('controller_board-sets.o' if sets else 'controller_board.o') built = subprocess.run(['cc', *flags, '-Ddl_hook_buffer_ranges_idle=board_buffer_ranges_idle', '-c', str(POLICY / 'controller_board.c'), '-o', str(board)], capture_output=True, text=True) if built.returncode: @@ -1927,13 +2008,13 @@ def build(work): POLICY / 'controller_association.c', ROOT / 'sdk/runtime/loader/loader.c', ROOT / 'sdk/runtime/upload/sha256.c', ADAPTER / 'machine_lifetime.c', work / 'manager_unit.c', work / 'allocator.c', work / 'buffers.c', RUNTIME / 'stock_hooks.c', RUNTIME / 'stock_hook_resources.c', RUNTIME / 'resident_engines.c', - work / 'resident-engines-data.c'] + work / 'resident-engines-data.c', *([ROOT / 'sdk/runtime/upload/upload.c'] if sets else [])] return out, subprocess.run(['cc', *flags, *map(str, sources), '-o', str(out)], capture_output=True, text=True) @unittest.skipUnless(shutil.which('cc'), 'host C compiler unavailable') class ResidentEnginesBoard(unittest.TestCase): - MODES = 67 + MODES = 68 def test_place_switch_run_disable_unswitch_free_and_their_refusals(self): with tempfile.TemporaryDirectory() as temp: @@ -1946,6 +2027,19 @@ def test_place_switch_run_disable_unswitch_free_and_their_refusals(self): result = subprocess.run([str(binary), str(mode)], capture_output=True, text=True) self.assertEqual(result.returncode, 0, result.stderr) + def test_a_rolled_back_removal_binds_again_on_both_backends(self): + """#1736: a trial that removes Analog BD, rolled back, leaves it bound, placed and switched on again; built with + the whole-set backend, both the single-module trial (67) and the set trial `device -- set` sends (68).""" + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + generated(work, bundles()) + binary, result = build(work, sets=True) + self.assertEqual(result.returncode, 0, result.stderr) + for mode in (67, 68): + with self.subTest(mode=mode): + result = subprocess.run([str(binary), str(mode)], capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + def test_relocation_in_c_matches_resident_dsp_relocate(self): """The base's relocator (mw_engine_relocate) against resident_dsp.relocate, at several bases, on made-up units and on the edge words (0, 0xffffff, wrap both ways).""" diff --git a/server/account-export.ts b/server/account-export.ts index 5fb0a666bc..1a4cab4aac 100644 --- a/server/account-export.ts +++ b/server/account-export.ts @@ -26,6 +26,7 @@ export async function accountExport(request:Request,db:Database,owner:User|null, octatrackDiagnosticsConsent:'SELECT enabled,version,changed_at FROM octatrack_diagnostic_consent WHERE user_id=?', agentClaims:'SELECT id,kind,claim_key,branch,pull_request,note,created_at,renewed_at,expires_at,released_at,released_reason FROM agent_claims WHERE user_id=?', agentMessages:'SELECT id,kind,parent_id,topic_kind,topic_key,to_login,body,pull_request,priority,created_at,active_at,ended_at,ended_reason FROM agent_messages WHERE user_id=?', + agentSessions:'SELECT id,agent,branch,note,entries,started_at,ended_at,consent_version,bytes,created_at FROM agent_sessions WHERE user_id=?', remoteSessions:'SELECT id,requester_name,reason,scope,minutes,status,consent_version,created_at,answered_at,ends_at,ended_at,ended_by,summary_json FROM remote_sessions WHERE member_id=?', octatrackDiagnostics:"SELECT event_id,consent_version,data_json,created_at FROM octatrack_diagnostic_events WHERE user_id=? AND created_at>=strftime('%Y-%m-%dT%H:%M:%fZ','now','-30 days')", welcomeEmail:'SELECT state,template_version,accepted_at,first_attempt_at,attempts FROM member_welcome_mail WHERE user_id=?', diff --git a/server/account-requests.ts b/server/account-requests.ts index bda30a95f8..a07f12892a 100644 --- a/server/account-requests.ts +++ b/server/account-requests.ts @@ -28,7 +28,7 @@ export async function reviewAccountRequest(request:Request,db:Database,id:string if(!requestRow)throw new HttpError(404,'Request not found.') if(!['requested','reviewing'].includes(requestRow.status))throw new HttpError(409,'This request has already ended.') if(body.status==='completed'){ - const privateChecks=[['auth_users','id'],['auth_accounts','userId'],['auth_sessions','userId'],['account_tokens','user_id'],['auth_verifications','value'],['sessions','user_id'],['issues','reporter_id'],['configurations','user_id'],['forum_bookmarks','user_id'],['forum_follows','user_id'],['module_update_opt_outs','user_id'],['push_subscriptions','user_id'],['signup_events','user_id'],['notifications','user_id'],['notification_preferences','user_id'],['announcement_reads','user_id'],['forum_reports','user_id'],['forum_shout_reports','user_id'],['forum_shouts','user_id'],['messages','user_id'],['conversation_members','user_id'],['message_blocks','user_id'],['message_reports','user_id'],['forum_media','user_id'],['developer_sessions','user_id'],['developer_auth_codes','user_id'],['agent_claims','user_id'],['agent_messages','user_id'],['module_maintainers','user_id'],['issue_replies','user_id'],['developer_events','actor_id'],['issue_triage_events','actor'],['account_policy_acceptances','user_id'],['account_news_preferences','user_id'],['member_welcome_mail','user_id'],['member_discord_invites','user_id'],['member_base_install_prompts','user_id'],['member_owner_notes','user_id'],['octatrack_diagnostic_consent','user_id'],['octatrack_diagnostic_events','user_id'],['remote_sessions','member_id'],['news_deliveries','member_id'],['member_beta_invitations','user_id'],['member_beta_discord_invites','user_id'],['member_presence','user_id'],['site_presence','user_id'],['site_presence','signed_out_user_id'],['forum_thread_reads','member_id'],['forum_visits','member_id']] as const + const privateChecks=[['auth_users','id'],['auth_accounts','userId'],['auth_sessions','userId'],['account_tokens','user_id'],['auth_verifications','value'],['sessions','user_id'],['issues','reporter_id'],['configurations','user_id'],['forum_bookmarks','user_id'],['forum_follows','user_id'],['module_update_opt_outs','user_id'],['push_subscriptions','user_id'],['signup_events','user_id'],['notifications','user_id'],['notification_preferences','user_id'],['announcement_reads','user_id'],['forum_reports','user_id'],['forum_shout_reports','user_id'],['forum_shouts','user_id'],['messages','user_id'],['conversation_members','user_id'],['message_blocks','user_id'],['message_reports','user_id'],['forum_media','user_id'],['developer_sessions','user_id'],['developer_auth_codes','user_id'],['agent_claims','user_id'],['agent_messages','user_id'],['agent_sessions','user_id'],['module_maintainers','user_id'],['issue_replies','user_id'],['developer_events','actor_id'],['issue_triage_events','actor'],['account_policy_acceptances','user_id'],['account_news_preferences','user_id'],['member_welcome_mail','user_id'],['member_discord_invites','user_id'],['member_base_install_prompts','user_id'],['member_owner_notes','user_id'],['octatrack_diagnostic_consent','user_id'],['octatrack_diagnostic_events','user_id'],['remote_sessions','member_id'],['news_deliveries','member_id'],['member_beta_invitations','user_id'],['member_beta_discord_invites','user_id'],['member_presence','user_id'],['site_presence','user_id'],['site_presence','signed_out_user_id'],['forum_thread_reads','member_id'],['forum_visits','member_id']] as const const checks=privateChecks.map(([table,column])=>`EXISTS(SELECT 1 FROM ${table} WHERE ${column}=?)`) checks.push('EXISTS(SELECT 1 FROM module_audio_previews WHERE user_id=?)') checks.push("EXISTS(SELECT 1 FROM users WHERE id=? AND (username IS NOT NULL OR github_id IS NOT NULL OR github_login IS NOT NULL OR email_verified=1 OR suspended=0 OR display_name!='Deleted member'))") diff --git a/server/agent-sessions.ts b/server/agent-sessions.ts new file mode 100644 index 0000000000..a504336841 --- /dev/null +++ b/server/agent-sessions.ts @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: Elastic-2.0 +// Copyright (c) 2026 Jannik Aßfalg (repeat98) +// Shared agent sessions (docs/AGENT_SESSIONS.md). A developer signed in for the board sends the conversation of one +// coding-agent session, scrubbed on their computer; the Worker checks it again with the same rules and keeps it for the +// owner for 90 days. Only the developer who shared it and administrators (through the admin sign-in) read it; the developer +// deletes it at any time. +import type { Database, Env } from './platform' +import { throttle } from './auth' +import { HttpError, jsonBody, response } from './security' +import { boardUser } from './agent-board' +import { SESSION_CONSENT_VERSION, SESSION_GZIP_LIMIT, SESSION_RETENTION_DAYS, validateSession } from '../src/community/agent-sessions' + +export const SESSIONS_PER_DAY = 10, SESSIONS_KEPT = 30 +const DAY = 86400000, UNPACKED_LIMIT = 8_000_000 +const ID = /^[0-9a-f-]{36}$/ + +type SessionRow = { id: string; user_id: string; github_login: string | null; agent: string; branch: string | null; note: string; entries: number; started_at: string | null; ended_at: string | null; bytes: number; created_at: string } +const SELECT = 'SELECT s.id,s.user_id,u.github_login,s.agent,s.branch,s.note,s.entries,s.started_at,s.ended_at,s.bytes,s.created_at FROM agent_sessions s JOIN users u ON u.id=s.user_id' +const expires = (createdAt: string) => new Date(Date.parse(createdAt) + SESSION_RETENTION_DAYS * DAY).toISOString() +const view = (row: SessionRow) => ({ id: row.id, login: row.github_login, agent: row.agent, branch: row.branch, note: row.note, entries: row.entries, startedAt: row.started_at, endedAt: row.ended_at, bytes: row.bytes, createdAt: row.created_at, expiresAt: expires(row.created_at) }) + +function decodeBase64(value: string) { + if (!/^[A-Za-z0-9+/]+={0,2}$/.test(value)) throw new HttpError(400, 'Send the session as base64.') + const binary = atob(value), bytes = new Uint8Array(binary.length) + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i) + return bytes +} +/** Unpacks a gzip body, stopping at the limit so a small upload cannot expand into a large one. */ +async function gunzip(bytes: Uint8Array) { + const reader = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip')).getReader(), parts: Uint8Array[] = [] + let size = 0 + try { + for (;;) { + const { done, value } = await reader.read() + if (done) break + size += value.length + if (size > UNPACKED_LIMIT) { await reader.cancel(); throw new HttpError(413, 'The session is too large.') } + parts.push(value) + } + } catch (error) { if (error instanceof HttpError) throw error; throw new HttpError(400, 'The session is not valid gzip.') } + const all = new Uint8Array(size); let at = 0 + for (const part of parts) { all.set(part, at); at += part.length } + return new TextDecoder().decode(all) +} + +export async function agentSessionRoutes(request: Request, env: Env, db: Database, adminId: string | null): Promise { + const url = new URL(request.url), path = url.pathname + if (path !== '/api/agent-sessions' && !path.startsWith('/api/agent-sessions/')) return null + const user = await boardUser(request, env, db) + if (!user && !adminId) throw new HttpError(401, 'Sign in for the board first: npm run board -- login') + // Administrators read through the site's admin sign-in (X-Octamod-Admin, or a member account with the role), never a board session. + const admin = !!adminId + + if (path === '/api/agent-sessions' && request.method === 'POST') { + if (!user) throw new HttpError(401, 'Share a session from the terminal: npm run session -- share') + const body = await jsonBody(request, Math.ceil(SESSION_GZIP_LIMIT * 4 / 3) + 1024) + if (body.consent !== SESSION_CONSENT_VERSION) throw new HttpError(400, 'Update your checkout: the sharing terms changed (docs/AGENT_SESSIONS.md).') + if (typeof body.data !== 'string') throw new HttpError(400, 'Send the session.') + const packed = decodeBase64(body.data) + if (packed.length > SESSION_GZIP_LIMIT) throw new HttpError(413, 'The session is too large.') + let parsed: unknown + try { parsed = JSON.parse(await gunzip(packed)) } catch (error) { if (error instanceof HttpError) throw error; throw new HttpError(400, 'The session is not valid JSON.') } + const checked = validateSession(parsed) + if (!checked.ok) throw new HttpError(422, checked.error) + const kept = await db.prepare('SELECT COUNT(*) AS n FROM agent_sessions WHERE user_id=?').bind(user.id).first<{ n: number }>() + if ((kept?.n ?? 0) >= SESSIONS_KEPT) throw new HttpError(409, `You have ${SESSIONS_KEPT} shared sessions. Delete one first: npm run session -- list, then delete .`) + await throttle(db, 'agent-session:' + user.id, SESSIONS_PER_DAY, 86400) + const { session } = checked, id = crypto.randomUUID(), now = new Date().toISOString() + await db.prepare('INSERT INTO agent_sessions(id,user_id,agent,branch,note,entries,started_at,ended_at,consent_version,bytes,data,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)') + .bind(id, user.id, session.agent, session.branch ?? null, session.note, session.entries.length, session.startedAt ?? null, session.endedAt ?? null, SESSION_CONSENT_VERSION, packed.length, body.data, now).run() + return response({ id, expiresAt: expires(now) }, 201) + } + + if (path === '/api/agent-sessions' && request.method === 'GET') { + const all = url.searchParams.get('all') === '1' + if (all && !admin) throw new HttpError(403, 'Only the owner reads everyone\'s shared sessions.') + if (!all && !user) throw new HttpError(401, 'Sign in for the board first: npm run board -- login') + const rows = all + ? (await db.prepare(SELECT + ' ORDER BY s.created_at DESC LIMIT 500').all()).results + : (await db.prepare(SELECT + ' WHERE s.user_id=? ORDER BY s.created_at DESC').bind(user!.id).all()).results + return response({ sessions: rows.map(view) }) + } + + const id = path.slice('/api/agent-sessions/'.length) + if (!ID.test(id)) throw new HttpError(404, 'Session not found.') + const row = await db.prepare(SELECT + ' WHERE s.id=?').bind(id).first() + // Someone else's session answers like a missing one. + if (!row || (!admin && row.user_id !== user?.id)) throw new HttpError(404, 'Session not found.') + if (request.method === 'GET') { + const data = await db.prepare('SELECT data FROM agent_sessions WHERE id=?').bind(id).first<{ data: string }>() + return response({ ...view(row), session: JSON.parse(await gunzip(decodeBase64(data!.data))) }) + } + if (request.method === 'DELETE') { + await db.prepare('DELETE FROM agent_sessions WHERE id=?').bind(id).run() + return response({ deleted: id }) + } + throw new HttpError(405, 'Use GET or DELETE.') +} + +/** Hourly: sessions older than 90 days and those of suspended accounts go. */ +export async function cleanupAgentSessions(db: Database, now = new Date()) { + await db.prepare('DELETE FROM agent_sessions WHERE created_at { if (remote) return remote const board = await agentBoardRoutes(request,env,db,adminId) if (board) return board + const sessions = await agentSessionRoutes(request,env,db,adminId) + if (sessions) return sessions const push = await pushRoutes(request,env,db,user,admin) if(push)return push const signedDeveloper = await developerUser(request,env,db) @@ -127,7 +130,7 @@ export async function handleApi(request: Request, env: Env): Promise { if(messages)return messages const pages = await forumPublic(request,env,db) if(pages)return pages - const discussion = await forum(request,db,user,admin,adminId) + const discussion = await forum(request,db,user,admin,adminId,env) if(discussion)return discussion const notifications = await notificationRoutes(request,env,db,user) if(notifications)return notifications diff --git a/server/contribution-roles.ts b/server/contribution-roles.ts new file mode 100644 index 0000000000..a55e672555 --- /dev/null +++ b/server/contribution-roles.ts @@ -0,0 +1,54 @@ +import registry from '../.github/module-authors.json' +import machines from '../src/devices/machines.generated.json' +import type { MachineProfile } from '../src/devices/machine-contract' +import type { ContributionRoles } from '../src/community/member-standing' +import type { Database, Env } from './platform' + +const authors = new Set(Object.values(registry.accounts)) +const profiles: readonly Pick[] = machines +export function contributionRoles(ids: readonly number[], collaborators: ReadonlySet, devices = profiles): ContributionRoles { + const reviews = devices.filter(machine => machine.deviceReviewers?.some(id => ids.includes(id))).map(machine => machine.id) + const roles: ContributionRoles['roles'] = [] + if (ids.some(id => authors.has(id))) roles.push('modder') + if (reviews.length) roles.push('device-reviewer') + if (ids.some(id => collaborators.has(id))) roles.push('maintainer') + return { roles: roles.length ? roles : ['contributor'], reviewDevices: reviews } +} + +// Public badges only. The merge job always checks the approving account's current permission on GitHub. +let cache: { repo: string; expires: number; ids: Promise> } | undefined +async function collaboratorIds(env?: Env) { + const token = env?.MAINTENANCE_BOT_GITHUB_TOKEN, repo = env?.GITHUB_REPOSITORY ?? 'repeat98/modwerk' + if (!token || !/^[\w.-]+\/[\w.-]+$/.test(repo)) return new Set() + if (cache?.repo === repo && cache.expires > Date.now()) return cache.ids + const ids = (async () => { + const result = new Set() + for (let page = 1; ; page++) { + const reply = await fetch('https://api.github.com/repos/' + repo + '/collaborators?per_page=100&page=' + page, { + headers: { Authorization: 'Bearer ' + token, Accept: 'application/vnd.github+json', 'User-Agent': 'modwerk-role-badges' }, + redirect: 'error', signal: AbortSignal.timeout(3000), + }) + if (!reply.ok) throw new Error('Collaborator lookup failed') + const rows = await reply.json() as { id: number; permissions?: { push?: boolean } }[] + for (const row of rows) if (row.permissions?.push) result.add(row.id) + if (rows.length < 100) return result + } + })().catch(() => new Set()) + cache = { repo, expires: Date.now() + 300_000, ids } + return ids +} + +export async function contributionBadges(db: Database, members: string[], env?: Env) { + const ids = [...new Set(members)], badges = new Map() + if (!ids.length) return badges + const slots = ids.map(() => '?').join(',') + const { results } = await db.prepare(`SELECT u.id, u.github_id AS github FROM users u WHERE u.suspended=0 AND u.id IN (${slots}) + UNION SELECT u.id, a.accountId FROM users u JOIN auth_accounts a ON a.userId=u.id + WHERE u.suspended=0 AND a.providerId='github' AND u.id IN (${slots})`).bind(...ids,...ids).all<{ id: string; github: string | null }>() + const collaborators = results.some(row => row.github) ? await collaboratorIds(env) : new Set() + for (const member of ids) { + const identity = results.filter(row => row.id === member) + if (identity.length) badges.set(member, contributionRoles(identity.flatMap(row => row.github ? [Number(row.github)] : []), collaborators)) + } + return badges +} diff --git a/server/forum.ts b/server/forum.ts index 035a855a4b..9561c2a08c 100644 --- a/server/forum.ts +++ b/server/forum.ts @@ -1,5 +1,7 @@ import { issueStatusStatements } from './issue-notifications' -import type { Database, User } from './platform' +import { publicContributions } from '../src/community/member-standing' +import { contributionBadges } from './contribution-roles' +import type { Database, Env, User } from './platform' import { ADMIN_ACTOR, needMember, throttle } from './auth' import { HttpError, jsonBody, required, response } from './security' import { FORUM_CATEGORIES, forumMachine, REQUEST_STATUSES, sharedConfiguration } from '../src/community/forum-contract' @@ -52,7 +54,7 @@ async function moduleId(db: Database, value: unknown) { if (!communityModule(value)) { try { await ensureDiscussionThread(db,value) } catch(error) { if(error instanceof HttpError&&error.status===404)throw new HttpError(400,'Choose a known module.'); throw error } } return value } -export async function forum(request: Request, db: Database, user: User|null, admin: boolean, adminId: string|null = admin ? ADMIN_ACTOR : null): Promise { +export async function forum(request: Request, db: Database, user: User|null, admin: boolean, adminId: string|null = admin ? ADMIN_ACTOR : null, env?: Env): Promise { const url = new URL(request.url), path = url.pathname if (!path.startsWith('/api/forum') && !path.startsWith('/api/admin/forum')) return null const chat = await shoutbox(request,db,user,admin) @@ -180,7 +182,7 @@ export async function forum(request: Request, db: Database, user: User|null, adm return Response.json(await forumHighlights(db),{headers:{'Cache-Control':'public, max-age=300','X-Content-Type-Options':'nosniff'}}) } if ((match=path.match(/^\/api\/forum\/profiles\/([a-z0-9_]{3,24})$/)) && request.method === 'GET') { - const profile = await memberProfile(db,match[1]) + const profile = await memberProfile(db,match[1],env) if (!profile) throw new HttpError(404,'Profile not found.') return response(profile) } @@ -202,8 +204,9 @@ export async function forum(request: Request, db: Database, user: User|null, adm if(reader&&last)await recordThreadRead(db,reader,thread.id,last.id).run() const request=(thread.section??thread.category)==='requests' const canSetRequestStatus=request&&!!user?.email_verified&&!user.suspended&&(admin||await maintainsModule(db,thread.module_id,user.id)) - const [attachments,roles,betaTesters] = await Promise.all([postAttachments(db,posts.slice(0,30).filter(post=>admin||!post.hidden).map(post=>post.id)),memberRoles(db,posts.slice(0,30).filter(post=>!post.hidden&&post.user_id!==SYSTEM_AUTHOR).map(post=>post.user_id)),betaTesterIds(db,posts.slice(0,30).filter(post=>!post.hidden&&post.user_id!==SYSTEM_AUTHOR).map(post=>post.user_id))]) - return response({thread:summary,posts:posts.slice(0,30).map(post=>({attachments:attachments.get(post.id)??[],canRemoveMedia:!post.hidden&&post.user_id===user?.id&&!!user?.email_verified,id:post.id,body:post.hidden&&!admin?'':post.body,username:post.hidden&&!admin?null:post.username,avatar:post.hidden&&!admin?null:post.avatar,displayName:post.hidden&&!admin?null:post.displayName,created_at:post.created_at,edited_at:post.edited_at,hidden:post.hidden,likes:post.hidden?0:post.likes,liked:!post.hidden&&!!post.liked,canEdit:!thread.locked&&!post.hidden&&post.user_id===user?.id&&!!user?.email_verified,official:post.user_id===SYSTEM_AUTHOR,maintainer:!post.hidden&&!!post.maintainer,role:roles.get(post.user_id)??null,betaTester:betaTesters.has(post.user_id),...(admin?{user_id:post.user_id}:{})})),configuration:thread.configuration_json?JSON.parse(thread.configuration_json):null,issue:thread.issue_json?JSON.parse(thread.issue_json):null,following,bookmarked,voted:!!voted,canSetRequestStatus,hasMore:posts.length>30,...(reader?{firstUnread:unreadId?{id:unreadId,page:unreadPage??0}:null}:{})}) + const members = posts.slice(0,30).filter(post=>!post.hidden&&post.user_id!==SYSTEM_AUTHOR).map(post=>post.user_id) + const [attachments,roles,betaTesters,badges] = await Promise.all([postAttachments(db,posts.slice(0,30).filter(post=>admin||!post.hidden).map(post=>post.id)),memberRoles(db,members),betaTesterIds(db,members),contributionBadges(db,members,env)]) + return response({thread:summary,posts:posts.slice(0,30).map(post=>({attachments:attachments.get(post.id)??[],canRemoveMedia:!post.hidden&&post.user_id===user?.id&&!!user?.email_verified,id:post.id,body:post.hidden&&!admin?'':post.body,username:post.hidden&&!admin?null:post.username,avatar:post.hidden&&!admin?null:post.avatar,displayName:post.hidden&&!admin?null:post.displayName,created_at:post.created_at,edited_at:post.edited_at,hidden:post.hidden,likes:post.hidden?0:post.likes,liked:!post.hidden&&!!post.liked,canEdit:!thread.locked&&!post.hidden&&post.user_id===user?.id&&!!user?.email_verified,official:post.user_id===SYSTEM_AUTHOR,maintainer:!post.hidden&&!!post.maintainer,contributions:post.hidden?undefined:publicContributions(badges.get(post.user_id),roles.get(post.user_id)),role:roles.get(post.user_id)??null,betaTester:betaTesters.has(post.user_id),...(admin?{user_id:post.user_id}:{})})),configuration:thread.configuration_json?JSON.parse(thread.configuration_json):null,issue:thread.issue_json?JSON.parse(thread.issue_json):null,following,bookmarked,voted:!!voted,canSetRequestStatus,hasMore:posts.length>30,...(reader?{firstUnread:unreadId?{id:unreadId,page:unreadPage??0}:null}:{})}) } const member = needMember(user) await throttle(db,'forum:'+member.id,60) diff --git a/server/maintenance-bot.ts b/server/maintenance-bot.ts index fcda1b121f..4022f256ed 100644 --- a/server/maintenance-bot.ts +++ b/server/maintenance-bot.ts @@ -392,7 +392,7 @@ export async function dispatchMaintenance(env: Env, db: Database, now = new Date * The site publishes only owner merges (scripts/release-approval.mjs), and an owner merge starts the push workflows. * GitHub refuses unless the head is still exactly the commit the bot checked. */ -async function mergeAsOwner(env: Env, body: Record) { +async function mergeAsOwner(env: Env, body: Record, message?: string) { const token = env.MAINTENANCE_BOT_GITHUB_TOKEN?.trim(), { number, sha, method } = body if (!token) throw new HttpError(503, 'The bot has no GitHub token to merge with.') if (!Number.isSafeInteger(number) || (number as number) < 1 || typeof sha !== 'string' || !/^[a-f0-9]{40}$/.test(sha) || (method !== 'merge' && method !== 'squash')) throw new HttpError(400, 'A merge needs a number, the checked commit and merge or squash.') @@ -400,13 +400,66 @@ async function mergeAsOwner(env: Env, body: Record) { const reply = await fetch('https://api.github.com/repos/' + repository + '/pulls/' + number + '/merge', { method: 'PUT', redirect: 'manual', signal: AbortSignal.timeout(20000), headers: { Authorization: 'Bearer ' + token, Accept: 'application/vnd.github+json', 'User-Agent': 'modwerk-maintenance-bot', 'X-GitHub-Api-Version': '2022-11-28', 'Content-Type': 'application/json' }, - body: JSON.stringify({ sha, merge_method: method }), + body: JSON.stringify({ sha, merge_method: method, ...(message ? { commit_message: message } : {}) }), }) const result = await reply.json().catch(() => null) as { merged?: boolean; sha?: string; message?: string } | null if (!reply.ok || !result?.merged || !result.sha) throw new HttpError(409, 'GitHub refused the merge: ' + (result?.message ?? 'HTTP ' + reply.status)) return { merged: true, sha: result.sha } } +/** Save the human approval before sending the merge to GitHub. */ +async function reviewedMerge(env: Env, db: Database, body: Record) { + if (!body.review || typeof body.review !== 'object') throw new HttpError(400, 'A review receipt is required.') + const review = body.review as Record, number = Number(body.number) + const { base, id, actorId, role, login, checkRun } = review + if (!Number.isSafeInteger(number) || number < 1 || body.method !== 'merge' || !/^[a-f0-9]{40}$/.test(String(base)) || + !/^[a-f0-9]{40}$/.test(String(body.sha)) || ![id, actorId, checkRun].every(n => Number.isSafeInteger(n) && Number(n) > 0) || + !/^[a-z0-9-]{1,39}$/i.test(String(login)) || !['maintainer','device-reviewer'].includes(String(role))) throw new HttpError(400, 'Invalid review receipt.') + if ((await state(db)).paused) throw new HttpError(409, 'Maintenance is paused.') + const veto = await db.prepare("SELECT 1 FROM maintenance_bot_actions WHERE target=? AND kind='merge' AND status='vetoed' AND json_extract(payload_json,'$.head')=?").bind(number,body.sha).first() + if (veto) throw new HttpError(409, 'The owner stopped this merge.') + const key = (await digest('github-review:' + number + ':' + id)).slice(0,16), stamp = now() + const summary = 'Merge #' + number + ' approved by @' + login + const claim = await db.prepare(`INSERT INTO maintenance_bot_actions(id,kind,target,tier,summary,reason,payload_json,status,due_at,decided_at,created_at,updated_at) + VALUES(?,'review_merge',?,'notify',?,?,?,'running',?,?,?,?) + ON CONFLICT(id) DO UPDATE SET status='running',updated_at=excluded.updated_at WHERE status='failed' OR (status='running' AND updated_at() + if (row?.status === 'done') return { merged: true, sha: row.result } + throw new HttpError(409, 'This review is being processed.') + } + const message = ['Modwerk reviewed merge', 'Base: ' + base, 'Head: ' + body.sha, 'Review: ' + id, 'Approved by: ' + login + ' (' + actorId + ', ' + role + ')'].join('\n') + const read = async (path: string) => { + const token = env.MAINTENANCE_BOT_GITHUB_TOKEN?.trim() + if (!token) throw new HttpError(503, 'The bot has no GitHub token to merge with.') + const repo = env.GITHUB_REPOSITORY?.trim() || 'repeat98/modwerk' + const reply = await fetch('https://api.github.com/repos/' + repo + path, { headers: { Authorization: 'Bearer ' + token, 'User-Agent': 'modwerk-maintenance-bot' }, redirect: 'error', signal: AbortSignal.timeout(15000) }) + if (!reply.ok) throw new HttpError(502, 'Unable to verify reviewed merge on GitHub.') + return reply.json() + } + try { + const pull = await read('/pulls/' + number) as { state: string; draft: boolean; merged: boolean; merge_commit_sha: string; head: { sha: string }; base: { ref: string; sha: string } } + let result + if (pull.merged) { + // Recover a successful GitHub write if the Worker stopped before recording its result. + const commit = await read('/git/commits/' + pull.merge_commit_sha) as { message: string; parents: { sha: string }[] } + if (!commit.message.endsWith('\n\n' + message) || commit.parents.length !== 2 || commit.parents[0].sha !== base || commit.parents[1].sha !== body.sha) throw new HttpError(409, 'This PR was merged under a different decision.') + result = { merged: true, sha: pull.merge_commit_sha } + } else { + if (pull.state !== 'open' || pull.draft || pull.base.ref !== 'main' || pull.base.sha !== base || pull.head.sha !== body.sha) throw new HttpError(409, 'The reviewed PR changed before merge.') + const decision = await read('/pulls/' + number + '/reviews/' + id) as { state: string; commit_id: string; user: { id: number } } + if (decision.state !== 'APPROVED' || decision.commit_id !== body.sha || decision.user.id !== actorId) throw new HttpError(409, 'The GitHub approval changed before merge.') + result = await mergeAsOwner(env, body, message) + } + await db.prepare("UPDATE maintenance_bot_actions SET status='done',result=?,updated_at=? WHERE id=?").bind(result.sha,now(),key).run() + return result + } catch (error) { + await db.prepare("UPDATE maintenance_bot_actions SET status='failed',result=?,updated_at=? WHERE id=?").bind(String(error).slice(0,200),now(),key).run() + throw error + } +} + /** Routes under /api/maintenance-bot/. They run server-to-server, before the Origin check. */ export async function maintenanceBotRoutes(request: Request, env: Env, db: Database, path: string): Promise { if (!path.startsWith('/api/maintenance-bot/')) return null @@ -420,6 +473,7 @@ export async function maintenanceBotRoutes(request: Request, env: Env, db: Datab if (route === '/todos' && method === 'POST') return response(await addTodos(env, db, await jsonBody(request, 64 * 1024))) if (route === '/diagnostics' && method === 'GET') return response(await diagnostics(db)) if (route === '/merge' && method === 'POST') return response(await mergeAsOwner(env, await jsonBody(request))) + if (route === '/merge/reviewed' && method === 'POST') return response(await reviewedMerge(env, db, await jsonBody(request))) if (route === '/forum' && method === 'GET') return response(await forumActivity(env, db)) // TARS's profile picture, through the site's own avatar upload (size, type and storage checks included). if (route === '/tars/avatar' && method === 'POST') { diff --git a/server/member-roles.ts b/server/member-roles.ts index 1d9254ceba..6c95617727 100644 --- a/server/member-roles.ts +++ b/server/member-roles.ts @@ -39,7 +39,7 @@ export async function adminRoleRoutes(request: Request, db: Database, path: stri const match = path.match(/^\/api\/admin\/forum\/roles\/([a-z0-9_]{3,24})$/) if (!match || request.method !== 'PUT') return null const body = await jsonBody(request), reason = required(body.reason, 'Reason', 1000) - if (!isMemberRole(body.role) || body.role === 'owner') throw new HttpError(400, 'Choose Member or Developer.') + if (!isMemberRole(body.role) || body.role === 'owner') throw new HttpError(400, 'Choose Member or Modder.') const member = await db.prepare('SELECT id,role FROM users WHERE username=? AND suspended=0').bind(match[1]).first<{ id: string; role: string }>() if (!member) throw new HttpError(404, 'Member not found.') if (member.role === 'owner') throw new HttpError(409, 'The owner role cannot be changed here.') diff --git a/server/profile.ts b/server/profile.ts index 7326109908..8069983fde 100644 --- a/server/profile.ts +++ b/server/profile.ts @@ -55,6 +55,7 @@ export async function profileRoutes(request: Request, env: Env, db: Database, pa db.prepare('DELETE FROM member_beta_discord_invites WHERE user_id=?').bind(owner.id), db.prepare('DELETE FROM octatrack_diagnostic_events WHERE user_id=?').bind(owner.id), db.prepare('DELETE FROM octatrack_diagnostic_consent WHERE user_id=?').bind(owner.id), + db.prepare('DELETE FROM agent_sessions WHERE user_id=?').bind(owner.id), db.prepare('DELETE FROM remote_session_tickets WHERE session_id IN (SELECT id FROM remote_sessions WHERE member_id=?)').bind(owner.id), db.prepare('DELETE FROM remote_sessions WHERE member_id=?').bind(owner.id), db.prepare('DELETE FROM module_working_reports WHERE user_id=?').bind(owner.id), diff --git a/server/recognition.ts b/server/recognition.ts index ab54bafb5a..174fc2cdcb 100644 --- a/server/recognition.ts +++ b/server/recognition.ts @@ -1,7 +1,8 @@ -import type { Database } from './platform' +import type { Database, Env } from './platform' import { COMMUNITY_MODULES, communityModule } from '../src/community/modules' import { SYSTEM_AUTHOR } from './module-threads' -import { effectiveRole } from '../src/community/member-standing' +import { contributionBadges } from './contribution-roles' +import { effectiveRole, publicContributions } from '../src/community/member-standing' import type { ProfileLinks } from '../src/community/profile-links' /** Members with a public profile: verified, not suspended and finished with sign-up. */ @@ -31,7 +32,7 @@ export async function maintainedByMember(db: Database, userId: string) { type ProfileRow = { id: string; username: string; displayName: string; bio: string; avatar: string | null; memberSince: string; threads: number; replies: number; likesReceived: number; reports: number; role: string; betaTester: number } & ProfileLinks /** A public profile with its contribution counts and latest replies; null when there is no public member by that name. */ -export async function memberProfile(db: Database, username: string) { +export async function memberProfile(db: Database, username: string, env?: Env) { const row = await db.prepare(`SELECT u.id,u.username,u.display_name AS displayName,u.profile_bio AS bio,u.avatar_id AS avatar,u.created_at AS memberSince,u.instagram_url AS instagramUrl,u.soundcloud_url AS soundcloudUrl,u.bandcamp_url AS bandcampUrl, (SELECT COUNT(*) FROM forum_threads t WHERE t.user_id=u.id AND t.hidden=0) AS threads, (SELECT COUNT(*) FROM forum_posts p JOIN forum_threads t ON t.id=p.thread_id WHERE p.user_id=u.id AND p.hidden=0 AND t.hidden=0 AND ${REPLY}) AS replies, @@ -39,13 +40,14 @@ export async function memberProfile(db: Database, username: string) { (SELECT COUNT(*) FROM issues i WHERE i.reporter_id=u.id AND i.public_json IS NOT NULL) AS reports,u.role,u.beta_tester AS betaTester FROM users u WHERE u.username=? AND ${PUBLIC_MEMBER}`).bind(username).first() if (!row) return null - const [recentReplies, maintains] = await Promise.all([ + const [recentReplies, maintains, badges] = await Promise.all([ db.prepare(`SELECT p.id,p.thread_id,p.created_at,substr(p.body,1,220) AS excerpt,t.title,${PAGE} FROM forum_posts p JOIN forum_threads t ON t.id=p.thread_id WHERE p.user_id=? AND p.hidden=0 AND t.hidden=0 AND ${REPLY} ORDER BY p.created_at DESC,p.rowid DESC LIMIT 6`).bind(row.id).all(), - maintainedByMember(db, row.id), + maintainedByMember(db, row.id), contributionBadges(db, [row.id], env), ]) const { username: name, displayName, bio, avatar, memberSince, threads, replies, likesReceived, reports, instagramUrl, soundcloudUrl, bandcampUrl } = row // Only public reports count: a private report's existence stays between the reporter and the maintainers. - return { username: name, displayName, bio, avatar, memberSince, instagramUrl, soundcloudUrl, bandcampUrl, role: effectiveRole(row.role, maintains.length > 0), betaTester: !!row.betaTester, threads, replies, likesReceived, reports, maintains, recentReplies: recentReplies.results } + const role = effectiveRole(row.role, maintains.length > 0) + return { username: name, displayName, bio, avatar, memberSince, instagramUrl, soundcloudUrl, bandcampUrl, contributions: publicContributions(badges.get(row.id), role), role, betaTester: !!row.betaTester, threads, replies, likesReceived, reports, maintains, recentReplies: recentReplies.results } } /** The forum home's "This month" block: the most liked posts and reply authors of the last 30 days and the newest diff --git a/src/App.tsx b/src/App.tsx index 01d81b4e54..48678eb218 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -34,7 +34,6 @@ import { api, onCommunityReconnect } from './community/api' import { compareModules, DEFAULT_MODULE_SORT, MODULE_STATISTICS_CHANGED, type ModuleStatistics } from './community/module-statistics' import { ModulePopularity } from './community/ModulePopularity' import { addAllMessage, withSetLimit } from './catalog/set-limit' -import type { SelectionConflict } from './catalog/selection-conflicts' import type { AddBlock } from './catalog/add-blocks' import { useCommunity } from './community/context' import { accountHref } from './community/member-access' @@ -84,6 +83,7 @@ import { MachineLibrary, DigiConfiguration, DigiModDetail } from './devices/Mach import { ZoomEffectDetail } from './devices/ZoomEffectDetail' import { ZOOM_EFFECTS, isZoomSetDevice } from './devices/zoom-effects' import { LibraryDock } from './components/LibraryDock' +import { LibrarySelection } from './components/LibrarySelection' import { ALL_MACHINES, DEVICES, DEVICES_BY_ID, deviceHref, parseDeviceRoute, rememberDevice, rememberedDevice, type DeviceProfile } from './devices/registry' import { parseZoomHubRoute, zoomHubHref } from './devices/zoom-hub-route' import type { ZoomLink } from './engine/zoom/zoom-link' @@ -389,7 +389,12 @@ export default function App() { } }, [overviewRoute, projectsRoute, faqRoute, route,detailModule,digiMod,zoomEffect,forumRoute,accountRoute,betaInvitationRoute,developerRoute,developer?.user,allRoute,machineView,currentDevice.name,w,hubRoute,zoomHubName]) const availabilityError = moduleAvailabilityError(selectedIds, betaAccess) - const { conflicts, blocks: addBlockMap } = withSetLimit<{ conflicts: SelectionConflict[]; blocks: Record }>({ conflicts: [], blocks: {} }, selectedIds) + const { blocks: addBlockMap } = withSetLimit<{ blocks: Record }>({ blocks: {} }, selectedIds) + const showSelection = (onLibrary && (allMachines || currentDevice.id === 'octatrack' || isDigiDevice(currentDevice.id))) + || (!phoneLayout && !!(detailModule || digiMod)) + const browsingSets = ready && showSelection + ? (allMachines ? ['octatrack', ...DIGI_DEVICES] : [currentDevice.id]).flatMap(device => activeFor(device) ?? []) + : [] const libraryFilter = allRoute ? allCategory ?? 'all' : filter const libraryFamily = allRoute || accessibleModules.some(module=>DETAILS[module.id].family===family) ? family : 'all' const visibleModules = accessibleModules.filter((module) => @@ -521,6 +526,7 @@ export default function App() { })} {phoneLibrary &&
} + {showSelection && } {octatrackUi ? {(() => { const pedal = zoomHub?.device ?? (hubRoute || configuration ? undefined : zoomConnected) if (pedal) return <>{zoomLink && setZoomInstall(true)} />} @@ -597,7 +603,7 @@ export default function App() { {(configuration || machineView === 'configuration' || route.startsWith('module-set')) && } }> {projectsRoute ? : faqRoute ? : route === 'credits' ? : route === 'base' ? : overviewRoute ? : !ready ?
Opening your workspace…
: <> - {onLibrary ? setQuery('')} onBrowse={rememberBrowse} device={allMachines ? undefined : currentDevice} machinePicker={phoneLayout ? undefined : machinePicker} phone={phoneLayout} resultsSlot={resultsSlot} query={query} category={libraryCategory as ModuleCategory | undefined} octatrackModules={visibleModules} family={family} onFamilyChange={setFamily} sort={sort} onSortChange={setSort} statistics={statistics} octatrackConflicts={conflicts} octatrackBlocks={addBlockMap} onSwapOctatrack={swapModule} comparison={comparison} onCompare={toggleComparison} onOpenComparison={() => setCompareOpen(true)} viewedModuleVersions={viewedModuleVersions} moduleBaseline={moduleBaseline} octatrackSelected={selectedIds} onToggleOctatrack={toggleModule} digiSelected={digiSelected} onToggleDigi={(device, id) => workspace.toggleModule(id, device)} zoomSelected={zoomSelected} onToggleZoom={(device, id) => workspace.toggleModule(id, device)} onClearSearch={() => { setQuery(''); setFamily('all') }}> + {onLibrary ? setQuery('')} onBrowse={rememberBrowse} device={allMachines ? undefined : currentDevice} machinePicker={phoneLayout ? undefined : machinePicker} phone={phoneLayout} resultsSlot={resultsSlot} query={query} category={libraryCategory as ModuleCategory | undefined} octatrackModules={visibleModules} family={family} onFamilyChange={setFamily} sort={sort} onSortChange={setSort} statistics={statistics} octatrackBlocks={addBlockMap} onSwapOctatrack={swapModule} comparison={comparison} onCompare={toggleComparison} onOpenComparison={() => setCompareOpen(true)} viewedModuleVersions={viewedModuleVersions} moduleBaseline={moduleBaseline} octatrackSelected={selectedIds} onToggleOctatrack={toggleModule} digiSelected={digiSelected} onToggleDigi={(device, id) => workspace.toggleModule(id, device)} zoomSelected={zoomSelected} onToggleZoom={(device, id) => workspace.toggleModule(id, device)} onClearSearch={() => { setQuery(''); setFamily('all') }}> {!allMachines && currentDevice.id === 'octatrack' && !!catalog.filter((item,index,items)=>!MODULES.some(module=>module.id===item.module_id)&&items.findIndex(other=>other.module_id===item.module_id)===index).length &&

Community modules

{catalog.filter((item,index,items)=>!MODULES.some(module=>module.id===item.module_id)&&items.findIndex(other=>other.module_id===item.module_id)===index).sort((a,b)=>compareModules({id:a.module_id,name:a.title,authorName:a.author,addedAt:a.added_at??undefined,updatedAt:a.updated_at??undefined},{id:b.module_id,name:b.title,authorName:b.author,addedAt:b.added_at??undefined,updatedAt:b.updated_at??undefined},sort,statistics)).map(item=>)}
}
: digiDevice && digiMod ? toggleMachineModule(digiMod.id)} /> : zoomEffect ? toggleMachineModule(zoomEffect.id)} /> : digiDevice && machineView === 'configuration' ? machineActive && setReportingConfiguration({ machine: digiDevice.id, id: machineActive.id })} device={digiDevice} configuration={machineActive} configurations={machineConfigurations} onSelect={id => { workspace.selectConfiguration(id) }} onDialog={setConfigDialog} onToggle={toggleMachineModule} onImport={item => workspace.importConfiguration(item.name,item.moduleIds,false,item.moduleVersions,digiDevice.id,undefined,undefined,undefined,item.storageLock)} onStorageLock={workspace.saveStorageLock} /> : missingRoute?

{pausedModule ? 'Module temporarily unavailable' : 'Page not found'}

{pausedModule ? pausedModule.name + ' is temporarily unavailable.' : 'This module or page is not in the current catalog.'}

Open module library
:zoomHub? setZoomInstall(true)} {...isZoomSetDevice(zoomHub.device.id) ? { sets: configurationsFor(zoomHub.device.id), selectedId: activeFor(zoomHub.device.id)?.id, onSelect: (id: string) => { workspace.selectConfiguration(id); window.location.assign(zoomHubHref(zoomHub.device.id, 'set')) }, onNew: () => newConfiguration(zoomHub.device.id), onSetAction: setAction, onToggle: (effect: string) => workspace.toggleModule(effect, zoomHub.device.id) } : {}} />:hubRoute?hubPage:route==='module-sets'||route.startsWith('module-set/')?(octatrackUi ? {workspace.importConfiguration(name,ids);window.location.assign('#configuration')}}/> : {workspace.importConfiguration(name,ids);window.location.assign('#configuration')}}/>):forumRoute ? {const device=config.device??'octatrack';workspace.importConfiguration(config.name,config.moduleIds,config.keepStockFx2,config.moduleVersions,device,config.usbAudio);openEditedSet(device)}}/> : developerRoute ? : accountRoute ? betaInvitationRoute ? : : route === 'privacy' ? : ['impressum','community-rules','modding-guidelines','report-content'].includes(route) ? : route.startsWith('submit') ? : route === 'review'||route === 'admin' ? : communityModule ? : detailModule ? swapModule(detailModule.id, removeIds)} usbAudio={active?.usbAudio} configurationName={active?.name} configurationId={active?.id} onConfigureUsbAudio={configureUsbAudio} onToggle={() => toggleModule(detailModule.id)} /> : null} diff --git a/src/community/AccountMenu.test.ts b/src/community/AccountMenu.test.ts index 8c0c1d66bf..7fdca2ff51 100644 --- a/src/community/AccountMenu.test.ts +++ b/src/community/AccountMenu.test.ts @@ -27,9 +27,9 @@ describe('sidebar account row', () => { expect(html).toContain('aria-expanded="false"') expect(html).not.toContain('Sign out') }) - it('names the admin and developer roles and marks account pages as current', () => { + it('names the admin and modder roles and marks account pages as current', () => { const html = render({ ...member, admin: true }, 'developer', { available: true, user: { login: 'member' } }) - expect(html).toContain('Admin · Developer') + expect(html).toContain('Admin · Modder') expect(html).toContain('sidebar-account-row active') }) }) diff --git a/src/community/AccountMenu.tsx b/src/community/AccountMenu.tsx index f98c299c95..d588785831 100644 --- a/src/community/AccountMenu.tsx +++ b/src/community/AccountMenu.tsx @@ -28,7 +28,7 @@ export function AccountMenu({ route }: { route: string }) { const current = route === 'account' || route.startsWith('account/') || route === 'developer' || route.startsWith('developer/') || route === 'admin' || route === 'review' const user = session.user?.verified ? session.user : null if (!user) return - const roles = [session.admin && 'Admin', developer?.user && 'Developer', user.betaTester && 'Beta tester'].filter(Boolean).join(' · ') + const roles = [session.admin && 'Admin', developer?.user && 'Modder', user.betaTester && 'Beta tester'].filter(Boolean).join(' · ') async function signOut() { setBusy(true); setError('') try { await post('/auth/logout', {}); await refresh(); setOpen(false); window.location.assign('#account/login') } diff --git a/src/community/ForumIdentity.tsx b/src/community/ForumIdentity.tsx index 1e77219922..aba9f18255 100644 --- a/src/community/ForumIdentity.tsx +++ b/src/community/ForumIdentity.tsx @@ -2,7 +2,7 @@ import { FORUM_CATEGORIES, type ForumCategory } from './forum-contract' import { DEVICES_BY_ID } from '../devices/registry' import { apiUrl, assetUrl } from '../hosting' import { profileHref } from '../routing' -import { ROLE_LABELS, type MemberRole } from './member-standing' +import { CONTRIBUTION_LABELS, ROLE_LABELS, type ContributionRoles, type MemberRole } from './member-standing' export function ForumCategoryBadge({ category }: { category: ForumCategory }) { return @@ -26,11 +26,18 @@ export function ForumAuthorName({ username, official, missing = 'Deleted member' } // Only a claim confirmed on both sides earns this: the reviewed catalog names the GitHub handle and the member verified it. -export function ForumMaintainerBadge({ profile }: { profile?: boolean }) { - return {profile ? 'Module maintainer' : 'Maintainer'} +export function ForumMaintainerBadge() { + return Module maintainer } // Member roles and the independent beta tester class carry their own badges. -export function ForumRoleBadge({ role, betaTester }: { role?: MemberRole | null; betaTester?: boolean }) { - return <>{role && role !== 'user' && {ROLE_LABELS[role]}}{betaTester && Beta tester} +export function ForumRoleBadge({ role, betaTester, contributions }: { role?: MemberRole | null; betaTester?: boolean; contributions?: ContributionRoles }) { + const showSiteRole = role && role !== 'user' && !(role === 'developer' && contributions?.roles.includes('modder')) + return <> + {contributions?.roles.map(kind => + {CONTRIBUTION_LABELS[kind]}{kind === 'device-reviewer' && ' · ' + contributions.reviewDevices.map(id => DEVICES_BY_ID[id]?.name ?? id).join(', ')} + )} + {showSiteRole && {ROLE_LABELS[role]}} + {betaTester && Beta tester} + } diff --git a/src/community/ForumProfile.tsx b/src/community/ForumProfile.tsx index 4275c20e1a..bd0140a698 100644 --- a/src/community/ForumProfile.tsx +++ b/src/community/ForumProfile.tsx @@ -21,7 +21,7 @@ export function ForumProfile({ username, onLoad }: { username: string; onLoad?: useEffect(() => { let cancelled = false; void api('/forum/profiles/' + encodeURIComponent(username)).then(value => { if (!cancelled) { setProfile(value); onLoad?.(value) } }).catch(error => { if (!cancelled) setError(error.message) }); return () => { cancelled = true } }, [username, onLoad]) if (!profile) return

{error || 'Loading member profile…'}

return <>
-

{profile.displayName}{profile.maintains.length > 0 && }

+

{profile.displayName}{profile.maintains.length > 0 && }

@{profile.username} · Member since {memberSince(profile.memberSince)}

{profile.bio &&

{profile.bio}

} diff --git a/src/community/ForumThreadView.tsx b/src/community/ForumThreadView.tsx index 85caaafc91..8dab723b03 100644 --- a/src/community/ForumThreadView.tsx +++ b/src/community/ForumThreadView.tsx @@ -36,7 +36,7 @@ function PostCard({item,author,locked,opening,refresh,onQuote,onVisitor}:{item:F // The first post is the thread itself, so only replies can be deleted. async function remove(){if(window.confirm('Delete this post? This cannot be undone.')){await act('/forum/posts/'+item.id,{},'DELETE');window.dispatchEvent(new Event(MODULE_STATISTICS_CHANGED))}} async function removeMedia(id:string){if(!window.confirm('Remove this file from your post? This cannot be undone.'))return;setBusy(true);setError('');try{const result=await apiFetch('/forum/media/'+id,{method:'DELETE'});if(!result.ok)throw new Error(((await result.json().catch(()=>({}))) as {error?:string}).error??'The file could not be removed.');await refresh()}catch(error){setError(errorText(error))}finally{setBusy(false)}} - return
{item.official||item.username?<>:{item.hidden?'Removed post':item.displayName??'Deleted member'}}{item.username&&item.username===author&&Thread author}{item.maintainer&&}{!!item.hidden&&Hidden}
{item.edited_at&&Edited}
{item.hidden&&!session.admin?

This post was removed.

:editing?
{event.preventDefault();void act('/forum/posts/'+item.id,{body},'PATCH')}}>
:} + return
{item.official||item.username?<>:{item.hidden?'Removed post':item.displayName??'Deleted member'}}{item.username&&item.username===author&&Thread author}{item.maintainer&&}{!!item.hidden&&Hidden}
{item.edited_at&&Edited}
{item.hidden&&!session.admin?

This post was removed.

:editing?
{event.preventDefault();void act('/forum/posts/'+item.id,{body},'PATCH')}}>
:} {(!item.hidden||session.admin)&&void removeMedia(attachment.id):undefined}/>} {!item.hidden&&