From 19be13aae47998bde529df82d5e2d9d294764dac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jannik=20A=C3=9Ffalg?= <67785539+repeat98@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:47:38 +0100 Subject: [PATCH 01/11] Improvement: share agent sessions with the owner Developers can send the owner the conversation of one coding-agent session (npm run session -- share), so the owner sees what got in the way and fixes it. pr:ready reminds the agent to ask once when the work is Ready; the developer can answer always or never once (npm run session -- prefer). Only prompts, replies and one line per tool call leave the computer. Tool output, thinking, injected context, long code blocks, hex dumps, data blobs, secrets, emails, IPs, home paths and user/host names are removed first, and a session that still looks like firmware or stock code is refused, by the client and again by the Worker (shared rules in src/community/agent-sessions.ts). Stored gzip in D1 (migration 0099), readable by the developer and administrators, deleted after 90 days, on suspension and with the account, listed in the account export. Privacy notice and the record of processing updated; docs/AGENT_SESSIONS.md describes it. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/modwerk-pr-ready/SKILL.md | 1 + .claude/skills/modwerk-pr-ready/SKILL.md | 1 + LICENSES/platform.json | 1 + changelog/2026-11-19-agent-sessions.md | 1 + docs/AGENT_SESSIONS.md | 41 ++++ docs/LEGAL_COMPLIANCE.md | 1 + docs/README.md | 1 + migrations/0099_agent_sessions.sql | 20 ++ package.json | 1 + public/licenses/THIRD_PARTY_NOTICES.html | 1 + public/licenses/THIRD_PARTY_NOTICES.txt | 1 + scripts/agent-session.mjs | 192 +++++++++++++++++++ scripts/pr-ready.mjs | 2 + server/account-export.ts | 1 + server/account-requests.ts | 2 +- server/agent-sessions.ts | 106 +++++++++++ server/api.ts | 3 + server/profile.ts | 1 + src/community/PrivacyPage.tsx | 3 + src/community/agent-sessions.test.ts | 201 ++++++++++++++++++++ src/community/agent-sessions.ts | 229 +++++++++++++++++++++++ worker.ts | 3 +- 22 files changed, 811 insertions(+), 2 deletions(-) create mode 100644 changelog/2026-11-19-agent-sessions.md create mode 100644 docs/AGENT_SESSIONS.md create mode 100644 migrations/0099_agent_sessions.sql create mode 100644 scripts/agent-session.mjs create mode 100644 server/agent-sessions.ts create mode 100644 src/community/agent-sessions.test.ts create mode 100644 src/community/agent-sessions.ts diff --git a/.agents/skills/modwerk-pr-ready/SKILL.md b/.agents/skills/modwerk-pr-ready/SKILL.md index 8208786964..f6e8ab345e 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/.claude/skills/modwerk-pr-ready/SKILL.md b/.claude/skills/modwerk-pr-ready/SKILL.md index 8208786964..f6e8ab345e 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/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.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/docs/AGENT_SESSIONS.md b/docs/AGENT_SESSIONS.md new file mode 100644 index 0000000000..364cce425b --- /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`, signed in for the board with the administrator account, saves every shared session into `~/.cache/modwerk-local/sessions/` with an `INDEX.md`. 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. +- `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/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/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/scripts/agent-session.mjs b/scripts/agent-session.mjs new file mode 100644 index 0000000000..a41a902fe1 --- /dev/null +++ b/scripts/agent-session.mjs @@ -0,0 +1,192 @@ +#!/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/ +// 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] }, 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 +} + +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') { + const auth = await token(), { sessions } = await boardRequest('/agent-sessions?all=1', { token: auth }) + const folder = join(homedir(), '.cache', 'modwerk-local', 'sessions'), 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 boardRequest('/agent-sessions/' + item.id, { token: auth }), 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`) + console.log(`${sessions.length} 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/pr-ready.mjs b/scripts/pr-ready.mjs index 30479785b7..5a195d8c88 100644 --- a/scripts/pr-ready.mjs +++ b/scripts/pr-ready.mjs @@ -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/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..76eeed36ee --- /dev/null +++ b/server/agent-sessions.ts @@ -0,0 +1,106 @@ +// 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 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) +} + +/** A board user who is also a site administrator: the owner reads shared sessions from the terminal with their board session. */ +async function adminBoardUser(db: Database, userId: string) { + return !!await db.prepare('SELECT 1 FROM users WHERE id=? AND is_admin=1 AND email_verified=1 AND suspended=0').bind(userId).first() +} + +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') + const admin = !!adminId || (!!user && await adminBoardUser(db, user.id)) + + 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) 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/src/community/PrivacyPage.tsx b/src/community/PrivacyPage.tsx index 772d3983ad..d66f101475 100644 --- a/src/community/PrivacyPage.tsx +++ b/src/community/PrivacyPage.tsx @@ -27,5 +27,8 @@ export function PrivacyPage() {

{de?'Freiwillige Fern-Diagnosesitzungen':'Optional remote debug sessions'}

{de?'Stand dieses Abschnitts: 20. Oktober 2026. Ein Website-Administrator kann Sie um eine Fern-Diagnosesitzung bitten. Ein Dialog nennt, wer fragt, warum und für wie lange (höchstens 60 Minuten); ohne Ihre Zustimmung geschieht nichts. Stimmen Sie zu, liest der Administrator über diesen Browser-Tab nur Zustandsdaten Ihrer Octatrack mit Modwerk-Basis: Basis und Kennung, installierte und fehlende Module, die Live-Auslastung, den Selbsttest-Eintrag und das geräteeigene Protokoll. Er kann nichts ändern, speichern oder laden und keine Firmware-, Projekt-, Sample- oder Karteninhalte lesen; Ihr Browser prüft jede Anfrage. Der Tab zeigt jede Anfrage; Beenden, Schließen oder Neuladen des Tabs beendet die Sitzung sofort. Die Daten laufen über unseren Cloudflare-Dienst und gehen an den Administrator, der sie mit einem KI-Assistenten (Claude von Anthropic) auswerten kann; dafür werden sie an Anthropic übermittelt.':'Section updated on 20 October 2026. A site administrator can ask you for a remote debug session. A dialog says who asks, why and for how long (at most 60 minutes); nothing happens without your consent. If you accept, the administrator reads only status data from your Octatrack running the Modwerk base, through this browser tab: its base and identity, installed and missing modules, live load, the self-test record and the unit’s own log. They cannot change, save or load anything, or read firmware, project, sample or card contents; your browser checks every request. The tab lists each request; ending, closing or reloading the tab ends the session at once. The data passes through our Cloudflare service to the administrator, who may analyse it with an AI assistant (Anthropic’s Claude); for that, it is sent to Anthropic.'}

{de?'Wir speichern mit Ihrem Konto, wer gefragt hat, den Grund, die Dauer, Ihre Antwort, die Einwilligungsversion, Beginn und Ende sowie die Anzahl der Anfragen je Art, 90 Tage lang; die gelesenen Werte selbst speichert die Website nicht. Rechtsgrundlage ist Ihre Einwilligung für die jeweilige Sitzung (Art. 6 Abs. 1 lit. a DSGVO); Sie können sie jederzeit durch Beenden widerrufen. Diese Angaben sind im Kontoexport enthalten und werden bei Kontolöschung entfernt.':'We store with your account who asked, the reason, the duration, your answer, the consent version, when the session started and ended, and how many requests of each kind ran, for 90 days; the site does not store the values read. The basis is your consent to that session (Article 6(1)(a) GDPR), which you withdraw at any time by ending it. These records are included in your account export and removed on account deletion.'}

+

{de?'Freiwillig geteilte Agent-Sitzungen':'Optional shared agent sessions'}

+

{de?'Stand dieses Abschnitts: 19. November 2026. Entwicklerinnen und Entwickler, die sich im Terminal mit GitHub für das Agent-Board angemeldet haben, können dem Betreiber das Gespräch einer einzelnen Sitzung ihres Coding-Agenten senden, damit er beseitigen kann, was die Mitarbeit erschwert. Das ist freiwillig, gilt nur für die jeweils gesendete Sitzung und ist keine Voraussetzung für Beiträge. Gesendet werden nur Ihre Eingaben, die Antworten des Agenten und je Werkzeugaufruf eine Zeile mit Befehl oder Datei und ob er fehlschlug, dazu Agent, Branch, Zeitraum und Ihre Notiz. Vor dem Senden entfernt das Skript auf Ihrem Computer alle Werkzeugausgaben, längere Codeblöcke, Hex-Dumps und Datenblöcke, Zugangsdaten, E-Mail- und IP-Adressen, Home-Verzeichnisse sowie Benutzer- und Rechnernamen; was danach noch wie Firmware oder Herstellercode aussieht, wird nicht gesendet. Mit „preview“ sehen Sie vorher, was gesendet würde.':'Section updated on 19 November 2026. Developers signed in for the agent board with GitHub from the terminal can send the operator the conversation of one coding-agent session, so the operator can remove what gets in the way of contributing. It is voluntary, covers only the session sent, and is never required to contribute. Only your prompts, the agent’s replies and one line per tool call (the command or file and whether it failed) are sent, with the agent, branch, time span and your note. Before sending, the script on your computer removes all tool output, longer code blocks, hex dumps and data blobs, credentials, email and IP addresses, home folders and user and computer names; anything that still looks like firmware or a maker’s code is not sent. “preview” shows what would be sent first.'}

+

{de?'Die Sitzungen werden über unseren Cloudflare-Dienst verarbeitet, Ihrem GitHub-Konto zugeordnet und sind nur für Sie und Website-Administratoren sichtbar. Sie werden nicht an GitHub, Modulautoren oder andere Entwickler weitergegeben. Der Betreiber kann sie mit einem KI-Assistenten (Claude von Anthropic) auswerten; dafür werden sie an Anthropic übermittelt. Rechtsgrundlage ist Ihre Einwilligung für die jeweilige Sitzung (Art. 6 Abs. 1 lit. a DSGVO), die Sie jederzeit widerrufen, indem Sie die Sitzung löschen. Sitzungen werden nach 90 Tagen gelöscht, bei Sperrung oder Löschung des Kontos sofort; mit „npm run session -- list“ und „delete“ sehen und löschen Sie Ihre jederzeit. Sie sind im Kontoexport aufgeführt.':'Sessions are processed through our Cloudflare service, linked to your GitHub account and visible only to you and site administrators. They are not passed to GitHub, module authors or other developers. The operator may analyse them with an AI assistant (Anthropic’s Claude); for that, they are sent to Anthropic. The basis is your consent to each session (Article 6(1)(a) GDPR), which you withdraw at any time by deleting it. Sessions are deleted after 90 days, and at once when the account is suspended or deleted; “npm run session -- list” and “delete” show and remove yours at any time. They are listed in your account export.'}

{de?'8. Ihre Rechte':'8. Your rights'}

{de?'Sie können Auskunft, Berichtigung, Löschung, Einschränkung der Verarbeitung und, soweit anwendbar, Datenübertragbarkeit verlangen. Gegen Verarbeitung auf Grundlage berechtigter Interessen können Sie aus Gründen Ihrer besonderen Situation Widerspruch einlegen. Einwilligungen können Sie jederzeit mit Wirkung für die Zukunft widerrufen. Wir treffen keine ausschließlich automatisierten Entscheidungen mit rechtlicher oder vergleichbar erheblicher Wirkung.':'You can request access, correction, erasure, restriction and, where applicable, data portability. You can object to processing based on legitimate interests for reasons relating to your situation. You can withdraw consent at any time for future processing. We make no solely automated decisions with legal or similarly significant effects.'}

{de?'Unter Ihr Konto können Sie Ihr Profil bearbeiten, Daten als JSON herunterladen, Sitzungen beenden, Ihr Konto nach erneuter Bestätigung löschen oder eine private Löschanfrage stellen. Für weitere Auskunft, Berichtigung oder andere Rechte schreiben Sie an':'From Your account you can edit your profile, download data as JSON, end sessions, delete your account after confirmation or submit a private removal request. For additional access, corrections or other rights, write to'} {SUPPORT_EMAIL}. {de?'Wir antworten grundsätzlich innerhalb eines Monats. Eine erforderliche Verlängerung um bis zu zwei weitere Monate wird innerhalb des ersten Monats begründet. Die Identitätsprüfung beschränkt sich auf erforderliche Angaben. Senden Sie keine Passwörter, Wiederherstellungslinks oder Firmware.':'We normally respond within one month. If a complex request requires up to two extra months, we explain this within the first month. Identity checks use only necessary information. Never send passwords, recovery links or firmware.'}

{de?'Sie können sich bei einer Datenschutzaufsichtsbehörde, insbesondere am Wohnort, Arbeitsplatz oder Ort des vermuteten Verstoßes, beschweren. Für den Betreiber zuständig ist:':'You can complain to a supervisory authority, including where you live, work or believe a violation occurred. The operator’s local authority is:'} {OPERATOR.authority}.

{de?'Ihr Konto':'Your account'}

GitHub developer access

Developers can sign in with GitHub to claim modules that list them as a maintainer. We store the verified GitHub account ID and handle, module claims, private replies and access history. We do not request, fetch or store your GitHub email or repositories. This sign-in grants only access to your claimed modules and reports their authors share with you; site administration and community membership remain separate.

Your developer session lasts up to seven days, is saved in this browser and can be ended from Creator settings. Temporary sign-in codes and expired sessions are cleaned hourly. Claims, replies and private history remain until operator removal. For developer account removal or an ownership dispute, contact {SUPPORT_EMAIL}.

{de?'Agent-Board':'Agent board'}

{de?'Stand dieses Abschnitts: 30. Oktober 2026. Entwickler können sich im Terminal mit GitHub anmelden (npm run board -- login), um ein Modul, eine Hook-, Tabellen- oder Migrationsnummer zu beanspruchen, an dem oder der sie arbeiten. Das kann jedes GitHub-Konto. Wir speichern die bestätigte GitHub-Konto-ID und den Namen und zu jedem Anspruch Art und Schlüssel, Branch, Pull-Request-Nummer, eine kurze Notiz und die Zeitpunkte. Aktive Ansprüche sind mit Name, Branch, Pull Request und Notiz unter „Start developing“ und über die API öffentlich, damit andere Entwickler und ihre Agenten sehen, wer woran arbeitet; dafür verarbeiten wir sie (Art. 6 Abs. 1 lit. b und f DSGVO). Um den Stand eines Pull Requests zu prüfen, fragt der Dienst die GitHub-API nach öffentlichen Pull Requests auf dem Branch des Anspruchs.':'Section updated on 30 October 2026. Developers can sign in from their terminal with GitHub (npm run board -- login) to claim a module, or a hook, table or migration number, they are working on. Any GitHub account can. We store the verified GitHub account ID and handle and, for each claim, its kind and key, branch, pull request number, a short note and its times. Active claims are public, with the handle, branch, pull request and note, on Start developing and through the API, so other developers and their agents can see who is working on what; that is why we process them (Art. 6(1)(b) and (f) GDPR). To check a pull request’s state, the service asks GitHub’s API about public pull requests on the claim’s branch.'}

{de?'Die Terminal-Sitzung gilt bis zu 30 Tage, öffnet nur das Board und endet mit npm run board -- logout. Ein Anspruch endet, wenn Sie ihn freigeben, nach 14 Tagen ohne Pull Request oder wenn sein Pull Request zusammengeführt oder geschlossen wird. Beendete Ansprüche löschen wir 90 Tage später, alle Ihre Ansprüche mit Ihrem Konto.':'The terminal session lasts up to 30 days, opens only the board and ends with npm run board -- logout. A claim ends when you release it, after 14 days without a pull request, or when its pull request is merged or closed. Ended claims are deleted 90 days later, and all your claims with your account.'}

{de?'Angemeldete Entwickler können einander außerdem Fragen stellen, Erkenntnisse zu einer Maschine, einem Modul, einem Hook, einer Migration oder einem DSP-Bereich hinterlassen und darauf antworten. Dazu speichern wir das Thema, den Namen, an den sich eine Frage richtet, den Text (höchstens 500 Zeichen, ohne Links, Pfade, Adressen oder Code), eine Pull-Request-Nummer und die Zeitpunkte. Offene Fragen und Erkenntnisse sind mit ihren Antworten und Namen aus demselben Grund unter „Start developing“ und über die API öffentlich. Eine Frage endet, wenn die fragende Person sie schließt, oder 30 Tage nach dem letzten Beitrag; eine Erkenntnis, wenn die verfassende Person sie schließt, wenn der Pull Request, der sie in eine Anleitung übernimmt, zusammengeführt wird, oder nach 90 Tagen. Beendete Beiträge löschen wir 90 Tage später, die Beiträge eines gesperrten Kontos sofort und alle Ihre Beiträge mit Ihrem Konto. Seite und API zeigen außerdem als Zahlen ohne Namen, wie viele Entwickler das Board nutzen.':'Signed-in developers can also ask each other questions, leave findings about a machine, module, hook, migration or DSP region, and reply to them. For each we store the topic, the handle a question is addressed to, the text (at most 500 characters, without links, paths, addresses or code), a pull request number and the times. Open questions and findings, with their replies and handles, are public on Start developing and through the API for the same reason. A question ends when its asker closes it or 30 days after its last post; a finding when its author closes it, when the pull request that adds it to a guide is merged, or after 90 days. Ended threads are deleted 90 days later, a suspended account’s posts at once, and all your posts with your account. The page and the API also show how many developers use the board, as counts without names.'}

{de?'Beta-Zugang':'Beta access'}

{de?'Wenn Sie eine Beta-Einladung annehmen, speichern wir privat die Einladungsrunde, die akzeptierte Risikohinweis-Version und den Zeitpunkt mit Ihrem Konto. Wir speichern außerdem, ob die Discord-Einladung beantwortet wurde, damit sie nicht erneut erscheint. Diese Angaben sind im Kontodatenexport enthalten und werden bei Kontolöschung entfernt. Beta-Zugang ändert weder Ihre E-Mail-Auswahl noch Ihre Diagnose-Einwilligung.':'When you accept a beta invitation, we privately store its round, the risk notice version you accepted and the time with your account. We also remember whether you handled the Discord invitation so it does not repeat. These records are included in your account export and removed on account deletion. Beta access does not change your email choices or diagnostics consent.'}

{de?'Freiwillige News-E-Mails':'Optional news emails'}

{de?'News-E-Mails erfordern eine separate, freiwillige Auswahl, die standardmäßig aus ist. Wir speichern die Auswahl, Einwilligungsversion und Änderungszeit privat mit Ihrem Konto. Sie können jederzeit unter Ihr Konto widerrufen. Verifizierung, Wiederherstellung und die einmalige Willkommensnachricht nach der Registrierung sind von dieser Auswahl unabhängig.':'News emails require a separate, optional choice that starts unchecked. We store your choice, consent version and change time privately with your account. You can withdraw it in Your account. Verification, recovery and the one-time welcome after signup are separate from this choice.'}

{de?'Freiwillige Push-Benachrichtigungen':'Optional device notifications'}

{de?'Push ist auf jedem Gerät standardmäßig aus. Erst wenn Sie es im Konto aktivieren und die Browserabfrage erlauben, speichern wir eine gerätespezifische Push-Adresse, Verschlüsselungsschlüssel, Themenauswahl und den Aktivierungszeitpunkt. Der Push-Dienst Ihres Browsers (Apple, Google, Mozilla oder Microsoft) verarbeitet technische Verbindungsdaten und leitet verschlüsselte Benachrichtigungen weiter. Sie können auf dem Sperrbildschirm erscheinen.':'Push starts off on every device. Only after you enable it in your account and allow the browser prompt do we store a device push address, encryption keys, topic choices and the activation time. Your browser’s push service (Apple, Google, Mozilla or Microsoft) processes technical connection data and relays encrypted notifications. They can appear on your lock screen.'}

{de?'Sie können Push jederzeit auf diesem Gerät in den Kontoeinstellungen ausschalten. Dadurch entfernen wir ausstehende Nachrichten für das deaktivierte Thema; wenn kein Thema mehr aktiv ist, löschen wir das Geräteabonnement. Kontolöschung entfernt alle Geräteabonnements. Nachrichten über neue Konten enthalten nur den öffentlichen Nutzernamen und gehen ausschließlich an aktivierte Administratorgeräte. E-Mail-Einstellungen bleiben getrennt.':'Turn push off for this device in account settings at any time. We remove queued deliveries for the disabled topic and delete the device subscription when all topics are off. Account deletion removes all device subscriptions. New-account alerts contain only the public username and go exclusively to enabled administrator devices. Email settings remain separate.'}

{de?'Zur Modulbibliothek':'Return to library'} → } diff --git a/src/community/agent-sessions.test.ts b/src/community/agent-sessions.test.ts new file mode 100644 index 0000000000..2911557ad8 --- /dev/null +++ b/src/community/agent-sessions.test.ts @@ -0,0 +1,201 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { gzipSync } from 'node:zlib' +import type { DatabaseSync } from 'node:sqlite' +import { testServer } from './test-server' +import { handleCommunity } from '../../server/transport' +import { digest } from '../../server/security' +import { cleanupAgentSessions, SESSIONS_KEPT } from '../../server/agent-sessions' +import { claudeProjectFolder, firmwareFindings, firmwareReason, prepareSession, readClaudeTranscript, readCodexRollout, scrubText, SESSION_CONSENT_VERSION, validateSession } from './agent-sessions' + +const databases: DatabaseSync[] = [] +afterEach(() => { databases.splice(0).forEach(db => db.close()); vi.unstubAllGlobals(); vi.useRealTimers() }) + +const line = (value: unknown) => JSON.stringify(value) +const claudeTranscript = [ + line({ type: 'session-owner', accountUuid: 'f791c26b-29e1-40e0-9552-726b4d2fa20a' }), + line({ type: 'user', isSidechain: false, origin: { kind: 'human' }, timestamp: '2026-11-19T10:00:00.000Z', gitBranch: 'module/tape-echo', message: { role: 'user', content: [{ type: 'text', text: 'Port the tape echo to the Digitakt.CLAUDE.md contents' }] } }), + line({ type: 'user', isMeta: true, timestamp: '2026-11-19T10:00:01.000Z', message: { role: 'user', content: 'Base directory for this skill: /home/someone/modwerk/.claude/skills/modwerk-start' } }), + line({ type: 'assistant', timestamp: '2026-11-19T10:00:02.000Z', message: { role: 'assistant', content: [{ type: 'thinking', thinking: 'secret plan' }, { type: 'text', text: 'I will check the board first.' }] } }), + line({ type: 'assistant', timestamp: '2026-11-19T10:00:03.000Z', message: { role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: { command: 'npm run module:doctor -- tape-echo', description: 'Run the module doctor' } }] } }), + line({ type: 'user', origin: { kind: 'human' }, timestamp: '2026-11-19T10:00:04.000Z', message: { role: 'user', content: [{ tool_use_id: 't1', type: 'tool_result', is_error: true, content: '00000000: 4e 75 4e 71 60 fe 00 00 00 10 00 20 00 30 00 40' }] } }), + line({ type: 'assistant', timestamp: '2026-11-19T10:00:05.000Z', message: { role: 'assistant', content: [{ type: 'tool_use', id: 't2', name: 'Write', input: { file_path: '/home/someone/modwerk/sdk/x.c', content: 'int stock_table[] = {1,2,3};' } }] } }), + line({ type: 'user', isSidechain: true, origin: { kind: 'human' }, message: { role: 'user', content: 'subagent prompt' } }), + line({ type: 'user', origin: { kind: 'task-notification' }, message: { role: 'user', content: 'A background task finished with its output' } }), + line({ type: 'user', isCompactSummary: true, isVisibleInTranscriptOnly: true, message: { role: 'user', content: 'This session is being continued from a previous conversation. Summary: 0x10 0x20' } }), + line({ type: 'user', origin: { kind: 'human' }, timestamp: '2026-11-19T10:00:06.000Z', message: { role: 'user', content: 'modwerk-pr-ready\n/modwerk-pr-ready\nnow' } }), +] + +describe('reading a transcript', () => { + it('keeps prompts, replies and tool calls from Claude Code, and drops outputs, thinking and injected turns', () => { + const read = readClaudeTranscript(claudeTranscript) + expect(read.branch).toBe('module/tape-echo') + expect(read.startedAt).toBe('2026-11-19T10:00:00.000Z') + expect(read.entries.map(entry => [entry.who, entry.text, entry.failed ?? false])).toEqual([ + ['developer', 'Port the tape echo to the Digitakt.CLAUDE.md contents', false], + ['agent', 'I will check the board first.', false], + ['tool', 'Bash: Run the module doctor · npm run module:doctor -- tape-echo', true], + ['tool', 'Write: /home/someone/modwerk/sdk/x.c', false], + ['developer', '/modwerk-pr-ready now', false], + ]) + expect(read.removed).toMatchObject({ toolOutputs: 1, thinking: 1, skipped: 3 }) + expect(JSON.stringify(read)).not.toMatch(/4e 75|stock_table|secret plan|f791c26b|subagent prompt|background task|previous conversation/) + }) + + it('reads a Codex rollout the same way', () => { + const read = readCodexRollout([ + line({ type: 'session_meta', timestamp: '2026-11-19T10:00:00.000Z', payload: { cwd: '/home/someone/modwerk', git: { branch: 'fix/sync' } } }), + line({ type: 'response_item', timestamp: '2026-11-19T10:00:01.000Z', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'cwd' }] } }), + line({ type: 'response_item', timestamp: '2026-11-19T10:00:02.000Z', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Why does the sync fail?' }] } }), + line({ type: 'response_item', timestamp: '2026-11-19T10:00:03.000Z', payload: { type: 'reasoning', summary: [] } }), + line({ type: 'response_item', timestamp: '2026-11-19T10:00:04.000Z', payload: { type: 'function_call', name: 'shell', call_id: 'c1', arguments: JSON.stringify({ command: ['bash', '-lc', 'npm test'] }) } }), + line({ type: 'response_item', timestamp: '2026-11-19T10:00:05.000Z', payload: { type: 'function_call_output', call_id: 'c1', output: JSON.stringify({ output: 'boom', metadata: { exit_code: 1 } }) } }), + line({ type: 'response_item', timestamp: '2026-11-19T10:00:06.000Z', payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'The test fails on the transfer step.' }] } }), + ]) + expect(read).toMatchObject({ agent: 'codex', cwd: '/home/someone/modwerk', branch: 'fix/sync' }) + expect(read.entries.map(entry => [entry.who, entry.text, entry.failed ?? false])).toEqual([ + ['developer', 'Why does the sync fail?', false], + ['tool', 'shell: bash -lc npm test', true], + ['agent', 'The test fails on the transfer step.', false], + ]) + expect(read.removed).toMatchObject({ toolOutputs: 1, thinking: 1, skipped: 1 }) + }) + + it('names the folder Claude Code keeps a checkout\'s transcripts in', () => { + expect(claudeProjectFolder('/home/jannik/modwerk')).toBe('-home-jannik-modwerk') + expect(claudeProjectFolder('c:\\Users\\jannik.aßfalg\\Dev')).toBe('c--Users-jannik-a-falg-Dev') + }) +}) + +describe('scrubbing', () => { + it('removes secrets, home paths, addresses and the developer\'s names, and keeps the prose readable', () => { + const removed = { toolOutputs: 0, thinking: 0, codeBlocks: 0, hexLines: 0, blobs: 0, secrets: 0, skipped: 0, trimmed: 0 } + const text = scrubText([ + 'Token ghp_' + 'a'.repeat(36) + ' and sk-ant-' + 'b'.repeat(30) + ' and board ' + 'c'.repeat(64), + 'RESEND_API_KEY=re_live9x8y7z6w5v4u3t2s1 and password: hunter22 and Authorization: Bearer abcdefghijklmnopqrstuv', + 'The token: expired, so I signed in again.', + 'Opened /home/jannik/modwerk/AGENTS.md and C:\\Users\\jannik\\Dev on jannik-laptop, mail me at someone@example.com from 192.168.1.20.', + ].join('\n'), { user: 'jannik', host: 'jannik-laptop' }, removed) + expect(text).not.toMatch(/ghp_a|sk-ant|cccc|re_live|hunter22|abcdefghijkl|jannik|someone@|192\.168/) + expect(text).toContain('The token: expired, so I signed in again.') + expect(text).toContain('~/modwerk/AGENTS.md') + expect(removed.secrets).toBeGreaterThanOrEqual(6) + }) + + it('removes hex dumps, hex tables and long code blocks, and keeps short snippets', () => { + const removed = { toolOutputs: 0, thinking: 0, codeBlocks: 0, hexLines: 0, blobs: 0, secrets: 0, skipped: 0, trimmed: 0 } + const long = '```c\n' + Array.from({ length: 20 }, (_, i) => `line ${i};`).join('\n') + '\n```' + const text = scrubText(`Here is the dump:\n0004f2a0: 4e 75 4e 71 60 fe 00 00 00 10 00 20\nand the table 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90.\n${long}\nRun \`npm run check\`:\n\`\`\`sh\nnpm run check\n\`\`\`\nAfter it, the next line stays.`, {}, removed) + expect(text).not.toMatch(/4e 75|0x50|line 7;/) + expect(text).toContain('[code block removed: 20 lines]') + expect(text).toContain('npm run check') + expect(text).toContain('After it, the next line stays.') + expect(removed).toMatchObject({ hexLines: 2, codeBlocks: 1 }) + }) + + it('flags disassembly and number tables that survive scrubbing, and not prose that starts like a mnemonic', () => { + const asm = Array.from({ length: 6 }, (_, i) => ` move.l (a${i % 8}),d${i % 8}`).join('\n') + expect(firmwareReason(asm)).toBe('disassembly') + expect(firmwareReason('Table: ' + Array.from({ length: 40 }, (_, i) => i * 3).join(', '))).toBe('a long table of numbers') + expect(firmwareReason(Array.from({ length: 8 }, () => 'add a test (unit), then link it, and swap the order, as in step 2.').join('\n'))).toBeNull() + expect(firmwareReason('The hook at 0x4f2a0 calls 0x4f3b0; nothing else changed.')).toBeNull() + }) + + it('prepares a session: skips what the developer left out and keeps the note short', () => { + const session = prepareSession(readClaudeTranscript(claudeTranscript), 'The doctor said nothing useful about the missing claim.', {}, [1]) + expect(session.entries.map(entry => entry.who)).toEqual(['developer', 'tool', 'tool', 'developer']) + expect(session.entries[0].text).toBe('Port the tape echo to the Digitakt.') + expect(session.entries[2].text).toBe('Write: ~/modwerk/sdk/x.c') + expect(session.removed.skipped).toBe(4) + expect(validateSession(JSON.parse(JSON.stringify(session)))).toMatchObject({ ok: true }) + expect(firmwareFindings(session.entries)).toEqual([]) + }) +}) + +async function fixture() { + const server = await testServer(); databases.push(server.db) + Object.assign(server.env, { GITHUB_OAUTH_CLIENT_ID: 'test-client', GITHUB_OAUTH_CLIENT_SECRET: 'only-a-test-client-secret', GITHUB_OAUTH_CALLBACK_URL: 'https://api.example.test/api/developer/auth/callback' }) + const call = (path: string, method = 'GET', body?: unknown, developer = '', { origin = 'https://octamod.test' as string | null, cookie = '' } = {}) => { + const headers = new Headers({ 'CF-Connecting-IP': '192.0.2.1' }) + if (origin) headers.set('Origin', origin) + if (body !== undefined) headers.set('Content-Type', 'application/json') + if (developer) headers.set('X-Modwerk-Developer', developer) + if (cookie) headers.set('Cookie', cookie) + return handleCommunity(new Request('https://api.example.test/api' + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) }), server.env) + } + let next = 300 + async function boardLogin(login: string) { + const githubId = ++next, verifier = next.toString(16).padStart(64, 'a'), challenge = await digest(verifier) + const start = await call('/developer/auth/start?port=48123&challenge=' + challenge) + const state = new URL(start.headers.get('Location')!).searchParams.get('state')!, cookie = start.headers.get('Set-Cookie')!.split(';')[0] + vi.stubGlobal('fetch', vi.fn(async (url: string) => url === 'https://github.com/login/oauth/access_token' + ? Response.json({ access_token: 'synthetic-github-access', token_type: 'bearer' }) + : Response.json({ data: { viewer: { databaseId: githubId, login } } }))) + const callback = await call('/developer/auth/callback?code=synthetic-code&state=' + state, 'GET', undefined, '', { origin: null, cookie }) + const location = new URL(callback.headers.get('Location')!) + const complete = await call('/developer/auth/complete', 'POST', { code: location.searchParams.get('code'), verifier }) + vi.unstubAllGlobals() + return complete.headers.get('X-Modwerk-Developer')! + } + const pack = (session: unknown) => gzipSync(JSON.stringify(session)).toString('base64') + const share = (token: string, session: unknown, consent = SESSION_CONSENT_VERSION) => call('/agent-sessions', 'POST', { consent, data: pack(session) }, token) + return { ...server, call, boardLogin, share } +} +const session = () => prepareSession(readClaudeTranscript(claudeTranscript), 'The doctor said nothing useful.') + +describe('shared agent sessions on the Worker', () => { + it('stores a session for its developer and the owner, and nobody else', async () => { + const { call, boardLogin, share, db } = await fixture() + const developer = await boardLogin('first-porter'), stranger = await boardLogin('someone-else'), owner = await boardLogin('repeat98') + db.prepare("UPDATE users SET is_admin=1,email_verified=1 WHERE github_login='repeat98'").run() + + const shared = await share(developer, session()) + expect(shared.status).toBe(201) + const { id, expiresAt } = await shared.json() as { id: string; expiresAt: string } + expect(Date.parse(expiresAt) - Date.now()).toBeGreaterThan(89 * 86400000) + + const own = await (await call('/agent-sessions', 'GET', undefined, developer)).json() as { sessions: { id: string; entries: number; note: string }[] } + expect(own.sessions).toMatchObject([{ id, entries: 5, note: 'The doctor said nothing useful.' }]) + expect((await (await call('/agent-sessions', 'GET', undefined, stranger)).json() as { sessions: unknown[] }).sessions).toEqual([]) + expect((await call('/agent-sessions?all=1', 'GET', undefined, stranger)).status).toBe(403) + expect((await call('/agent-sessions/' + id, 'GET', undefined, stranger)).status).toBe(404) + expect((await call('/agent-sessions/' + id, 'DELETE', undefined, stranger)).status).toBe(404) + expect((await call('/agent-sessions', 'GET')).status).toBe(401) + + const all = await (await call('/agent-sessions?all=1', 'GET', undefined, owner)).json() as { sessions: { id: string; login: string }[] } + expect(all.sessions).toMatchObject([{ id, login: 'first-porter' }]) + const read = await (await call('/agent-sessions/' + id, 'GET', undefined, owner)).json() as { session: { entries: { text: string }[] } } + expect(read.session.entries[0].text).toBe('Port the tape echo to the Digitakt.') + + expect((await call('/agent-sessions/' + id, 'DELETE', undefined, developer)).status).toBe(200) + expect(db.prepare('SELECT COUNT(*) AS n FROM agent_sessions').get()).toEqual({ n: 0 }) + }) + + it('refuses firmware, secrets, stale terms and anything not in the session format', async () => { + const { boardLogin, share, call } = await fixture() + const developer = await boardLogin('first-porter') + const firmware = session(); firmware.entries.push({ who: 'agent', text: Array.from({ length: 8 }, (_, i) => `00004f${i}0: move.l (a0),d${i}`).join('\n') }) + const refused = await share(developer, firmware) + expect(refused.status).toBe(422) + expect((await refused.json() as { error: string }).error).toMatch(/firmware or stock code \(disassembly\)/) + const secret = session(); secret.entries.push({ who: 'developer', text: 'my token ghp_' + 'z'.repeat(36) }) + expect((await share(developer, secret)).status).toBe(422) + expect((await share(developer, session(), '2020-01-01')).status).toBe(400) + expect((await share(developer, { ...session(), entries: [{ who: 'stranger', text: 'x' }] })).status).toBe(422) + expect((await call('/agent-sessions', 'POST', { consent: SESSION_CONSENT_VERSION, data: 'not base64!' }, developer)).status).toBe(400) + expect((await share('', session())).status).toBe(401) + }) + + it('keeps at most the limit per developer and purges old sessions and suspended accounts\' sessions', async () => { + const { boardLogin, share, db, env } = await fixture() + const developer = await boardLogin('first-porter') + const userId = (db.prepare("SELECT id FROM users WHERE github_login='first-porter'").get() as { id: string }).id + const insert = db.prepare("INSERT INTO agent_sessions(id,user_id,agent,note,entries,consent_version,bytes,data,created_at) VALUES(?,?,'claude-code','',1,?,1,'',?)") + for (let i = 0; i < SESSIONS_KEPT; i++) insert.run(`00000000-0000-4000-8000-${String(i).padStart(12, '0')}`, userId, SESSION_CONSENT_VERSION, i ? new Date().toISOString() : '2026-01-01T00:00:00.000Z') + expect((await share(developer, session())).status).toBe(409) + await cleanupAgentSessions(env.DB!) + expect(db.prepare('SELECT COUNT(*) AS n FROM agent_sessions').get()).toEqual({ n: SESSIONS_KEPT - 1 }) + db.prepare('UPDATE users SET suspended=1 WHERE id=?').run(userId) + await cleanupAgentSessions(env.DB!) + expect(db.prepare('SELECT COUNT(*) AS n FROM agent_sessions').get()).toEqual({ n: 0 }) + }) +}) diff --git a/src/community/agent-sessions.ts b/src/community/agent-sessions.ts new file mode 100644 index 0000000000..fc8c562838 --- /dev/null +++ b/src/community/agent-sessions.ts @@ -0,0 +1,229 @@ +// SPDX-License-Identifier: GPL-3.0-or-later OR Elastic-2.0 +// Copyright (c) 2026 Jannik Aßfalg (repeat98) +// Shared agent sessions (docs/AGENT_SESSIONS.md): a developer may send the owner the conversation of one coding-agent +// session, so the owner sees where contributing gets in the way. Only the conversation travels: 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 on the developer's computer. The terminal client (scripts/agent-session.mjs) and the +// Worker (server/agent-sessions.ts) both use this file, so the Worker refuses what the client would have refused. +// Plain type annotations only: Node runs this file directly from the client. + +export const SESSION_CONSENT_VERSION = '2026-11-19' +export const SESSION_FORMAT = 1 +export const SESSION_RETENTION_DAYS = 90 +export const SESSION_NOTE_LIMIT = 1000 +export const SESSION_ENTRY_LIMIT = 8000 +export const SESSION_TEXT_LIMIT = 3_000_000 // characters of kept text, before compression +export const SESSION_GZIP_LIMIT = 1_000_000 // bytes the Worker accepts +export const SESSION_AGENTS = ['claude-code', 'codex'] as const +export type SessionAgent = typeof SESSION_AGENTS[number] +export type SessionEntry = { who: 'developer' | 'agent' | 'tool'; text: string; at?: string; failed?: true } +export type SessionRemoved = { toolOutputs: number; thinking: number; codeBlocks: number; hexLines: number; blobs: number; secrets: number; skipped: number; trimmed: number } +export type SessionDocument = { format: 1; agent: SessionAgent; branch?: string; startedAt?: string; endedAt?: string; note: string; entries: SessionEntry[]; removed: SessionRemoved } +export type ScrubContext = { user?: string; host?: string } + +const ENTRY_TEXT_LIMIT = 20_000 +const CODE_BLOCK_LINES = 12 +const emptyRemoved = (): SessionRemoved => ({ toolOutputs: 0, thinking: 0, codeBlocks: 0, hexLines: 0, blobs: 0, secrets: 0, skipped: 0, trimmed: 0 }) +const escape = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + +const SECRET_PATTERNS: RegExp[] = [ + /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g, + /\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{20,})\b/g, + /\bsk-(?:ant-)?[A-Za-z0-9_-]{20,}/g, + /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, + /\bxox[abprs]-[A-Za-z0-9-]{10,}/g, + /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, + /\b(?:re|whsec|rk|pk|sk)_[A-Za-z0-9]{24,}\b/g, + /\b[a-f0-9]{64}\b/gi, // board and admin tokens, and SHA-256 hashes, which look the same +] +// A password after its name, whatever it looks like; a token or key only when its value looks like one, so prose such as +// "token: expired" stays readable. +const ASSIGNED_PASSWORD = /\b((?:[A-Z0-9_]*_)?(?:password|passwd|pwd|secret)[A-Z0-9_]*)(["']?[ \t]*[:=][ \t]*["']?)([^\s"',;&]{4,})/gi +const ASSIGNED_TOKEN = /\b((?:[A-Z0-9_]*_)?(?:token|api[_-]?key|access[_-]?key|auth(?!or)|cookie)[A-Z0-9_]*)(["']?[ \t]*[:=][ \t]*(?:Bearer[ \t]+)?["']?)((?=[^\s"',;&]*\d)[^\s"',;&]{8,}|[^\s"',;&]{20,})/gi +const BEARER = /\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{16,}/g +const EMAIL = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g +const IPV4 = /\b(?!127\.0\.0\.1\b)(?!0\.0\.0\.0\b)(?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}\b/g +const HOME = /(?:\/mnt\/[a-z]\/Users\/[^/\s]+|\/home\/[^/\s]+|\/Users\/[^/\s]+|[A-Za-z]:[\\/]+Users[\\/]+[^\\/\s]+)/g +/** One line of a hex dump: an offset, then eight or more byte pairs, or sixteen byte pairs on their own. */ +const HEX_LINE = /^[ \t]*(?:(?:0x)?[0-9a-f]{4,16}[: \t][ \t]*(?:[0-9a-f]{2}[ \t,]+){7,}[0-9a-f]{2}\b|(?:(?:0x)?[0-9a-f]{2}[ \t,]+){15,}(?:0x)?[0-9a-f]{2}\b).*$/gim +const HEX_RUN = /(?:0x[0-9a-f]{1,8}\s*,\s*){8,}0x[0-9a-f]{1,8}/gi +const BLOB = /[A-Za-z0-9+/=_-]{120,}|\b[0-9a-f]{65,}\b/gi +const FENCE = /```[^\n]*\n[\s\S]*?(?:```|$)/g +/** Disassembled stock code: a ColdFire/68k or DSP56300 mnemonic, optionally after an address, with a register, an + * immediate or a hex operand. Lower case, as disassemblers print it, so English prose starting with "add" never counts. */ +const ASM_LINE = /^[ \t]*(?:[0-9a-fA-F]{4,8}:?[ \t]+(?:[0-9a-fA-F]{4}[ \t]+)*)?(?:move[aqm]?|lea|pea|jsr|bsr|b(?:ra|eq|ne|cc|cs|ge|gt|le|lt|hi|ls|mi|pl)|rts|rte|link|unlk|addq?|subq?|addi|subi|cmpi?|cmpa|tst|clr|lsl|lsr|asl|asr|andi?|ori?|eori?|muls|mulu|divs|divu|macl?|msacl?|jmp|jclr|jset|jsclr|jsset|rep|movep|movec|ext[bwl]?|swap|bset|bclr|btst)(?:\.[bwls])?[ \t]+[^\n]*?(?:%?\b[ad][0-7]\b|\bsp\b|\b[rnm][0-7]\b|\b[xy][01]\b|#|\$[0-9a-fA-F]|\b0x[0-9a-fA-F])/gm + +function count(text: string, pattern: RegExp) { return (text.match(pattern) ?? []).length } + +/** Removes what must not leave the developer's computer from one piece of text, and counts what it removed. */ +export function scrubText(input: string, context: ScrubContext = {}, removed: SessionRemoved = emptyRemoved()): string { + let text = input.replace(/[\s\S]*?<\/system-reminder>/g, '').replace(/[\s\S]*?<\/local-command-std(?:out|err)>/g, '') + text = text.replace(FENCE, block => { + const lines = block.split('\n').length - 2 + if (lines <= CODE_BLOCK_LINES) return block + removed.codeBlocks++ + return `[code block removed: ${lines} lines]` + }) + text = text.replace(HEX_LINE, () => { removed.hexLines++; return '[hex removed]' }).replace(HEX_RUN, () => { removed.hexLines++; return '[hex values removed]' }) + for (const pattern of SECRET_PATTERNS) text = text.replace(pattern, () => { removed.secrets++; return '[secret removed]' }) + for (const pattern of [ASSIGNED_PASSWORD, ASSIGNED_TOKEN]) text = text.replace(pattern, (_all, key: string, joint: string) => { removed.secrets++; return key + joint + '[secret removed]' }) + text = text.replace(BEARER, (_all, scheme: string) => { removed.secrets++; return scheme + ' [secret removed]' }) + text = text.replace(BLOB, () => { removed.blobs++; return '[data removed]' }) + text = text.replace(EMAIL, '[email]').replace(HOME, '~').replace(IPV4, '[address]') + if (context.user && context.user.length >= 3) text = text.replace(new RegExp(`\\b${escape(context.user)}\\b`, 'gi'), '[user]') + if (context.host && context.host.length >= 3) text = text.replace(new RegExp(`\\b${escape(context.host)}\\b`, 'gi'), '[host]') + return text.replace(/\n{3,}/g, '\n\n').trim() +} + +/** Why an entry still looks like firmware or stock code after scrubbing, or null. The client refuses to send such a + * session and the Worker refuses to store one: the modding guidelines keep firmware and stock code off Modwerk's servers. */ +export function firmwareReason(text: string): string | null { + if (count(text, ASM_LINE) >= 6) return 'disassembly' + if (count(text, /\b0x[0-9a-f]{2,8}\b/gi) >= 24) return 'many hex values' + if (/(?:\b\d{1,5}\s*,\s*){32,}/.test(text)) return 'a long table of numbers' + if (count(text, HEX_LINE) > 0) return 'a hex dump' + return null +} +/** Whether a secret-shaped string survived scrubbing (the Worker refuses the session then). */ +export function secretLike(text: string) { return SECRET_PATTERNS.some(pattern => new RegExp(pattern.source, pattern.flags).test(text)) } + +export function firmwareFindings(entries: SessionEntry[]) { + return entries.flatMap((entry, index) => { const reason = firmwareReason(entry.text); return reason ? [{ index, who: entry.who, reason }] : [] }) +} + +type Raw = Record +const record = (value: unknown): value is Raw => !!value && typeof value === 'object' && !Array.isArray(value) +const str = (value: unknown) => typeof value === 'string' ? value : '' +const oneLine = (value: string, limit = 200) => { const line = value.replace(/\s+/g, ' ').trim(); return line.length > limit ? line.slice(0, limit - 1) + '…' : line } + +/** What a tool call did, in one line: the command for a shell, the file for a file tool, nothing of what it wrote. */ +export function describeTool(name: string, input: unknown): string { + const args = record(input) ? input : {} + const command = Array.isArray(args.command) ? args.command.map(String).join(' ') : str(args.command) || str(args.cmd) + const description = str(args.description) + if (command) return `${name}: ${description ? description + ' · ' : ''}${oneLine(command)}` + const target = str(args.file_path) || str(args.notebook_path) || str(args.path) || str(args.pattern) || str(args.url) || str(args.skill) || str(args.subagent_type) + return target ? `${name}: ${oneLine(description ? description + ' · ' + target : target)}` : description ? `${name}: ${oneLine(description)}` : name +} + +/** One Claude Code transcript (`~/.claude/projects//.jsonl`), one JSON object per line. */ +export function readClaudeTranscript(lines: string[]): Omit { + const entries: SessionEntry[] = [], removed = emptyRemoved(), tools = new Map() + let branch: string | undefined, startedAt: string | undefined, endedAt: string | undefined + for (const line of lines) { + let row: unknown + try { row = JSON.parse(line) } catch { continue } + if (!record(row) || (row.type !== 'user' && row.type !== 'assistant') || row.isSidechain === true || !record(row.message)) continue + const at = str(row.timestamp) || undefined + if (at) { startedAt ??= at; endedAt = at } + if (str(row.gitBranch) && str(row.gitBranch) !== 'HEAD') branch = str(row.gitBranch) + const content = row.message.content, blocks: Raw[] = typeof content === 'string' ? [{ type: 'text', text: content }] : Array.isArray(content) ? content.filter(record) : [] + if (row.type === 'user') { + for (const block of blocks) if (block.type === 'tool_result') { + removed.toolOutputs++ + const tool = tools.get(str(block.tool_use_id)); if (tool && block.is_error === true) tool.failed = true + } + // Only what the developer typed: not skill bodies, hook output, task notifications or other injected turns. + // A compaction summary is the agent's own recap of everything before it, file contents included. + const human = !record(row.origin) || row.origin.kind === 'human' + if (row.isMeta === true || row.isCompactSummary === true || row.isVisibleInTranscriptOnly === true || !human) { if (blocks.some(block => block.type === 'text')) removed.skipped++; continue } + let text = blocks.filter(block => block.type === 'text').map(block => str(block.text)).join('\n') + // A slash command arrives as tags: keep the command and its arguments. + const command = /([^<]*)<\/command-name>/.exec(text) + if (command) text = (command[1].trim() + ' ' + (/([^<]*)<\/command-args>/.exec(text)?.[1] ?? '')).trim() + if (text.trim()) entries.push({ who: 'developer', text, ...(at ? { at } : {}) }) + if (blocks.some(block => block.type === 'image')) entries.push({ who: 'developer', text: '[image]', ...(at ? { at } : {}) }) + continue + } + for (const block of blocks) { + if (block.type === 'text' && str(block.text).trim()) entries.push({ who: 'agent', text: str(block.text), ...(at ? { at } : {}) }) + else if (block.type === 'thinking' || block.type === 'redacted_thinking') removed.thinking++ + else if (block.type === 'tool_use') { + const entry: SessionEntry = { who: 'tool', text: describeTool(str(block.name), block.input), ...(at ? { at } : {}) } + entries.push(entry); tools.set(str(block.id), entry) + } + } + } + return { format: SESSION_FORMAT, agent: 'claude-code', ...(branch ? { branch } : {}), ...(startedAt ? { startedAt, endedAt } : {}), entries, removed } +} + +/** One Codex rollout (`~/.codex/sessions////rollout-*.jsonl`). */ +export function readCodexRollout(lines: string[]): Omit & { cwd?: string } { + const entries: SessionEntry[] = [], removed = emptyRemoved(), tools = new Map() + let cwd: string | undefined, branch: string | undefined, startedAt: string | undefined, endedAt: string | undefined + for (const line of lines) { + let row: unknown + try { row = JSON.parse(line) } catch { continue } + if (!record(row) || !record(row.payload)) continue + const at = str(row.timestamp) || undefined, item = row.payload + if (at) { startedAt ??= at; endedAt = at } + if (row.type === 'session_meta') { cwd = str(item.cwd) || cwd; if (record(item.git)) branch = str(item.git.branch) || branch; continue } + if (row.type !== 'response_item') continue + if (item.type === 'message') { + const text = (Array.isArray(item.content) ? item.content.filter(record) : []).map(part => str(part.text)).join('\n') + if (item.role === 'assistant' && text.trim()) entries.push({ who: 'agent', text, ...(at ? { at } : {}) }) + else if (item.role === 'user' && text.trim()) { + if (/^\s*(?:||# AGENTS\.md instructions)/.test(text)) removed.skipped++ + else entries.push({ who: 'developer', text, ...(at ? { at } : {}) }) + } + } else if (item.type === 'reasoning') removed.thinking++ + else if (item.type === 'function_call' || item.type === 'custom_tool_call' || item.type === 'local_shell_call') { + let input: unknown = item.input ?? item.action + if (typeof item.arguments === 'string') { try { input = JSON.parse(item.arguments) } catch { input = {} } } + const entry: SessionEntry = { who: 'tool', text: describeTool(str(item.name) || 'shell', item.type === 'custom_tool_call' ? {} : input), ...(at ? { at } : {}) } + entries.push(entry); tools.set(str(item.call_id), entry) + } else if (item.type === 'function_call_output' || item.type === 'custom_tool_call_output') { + removed.toolOutputs++ + const output = typeof item.output === 'string' ? item.output : JSON.stringify(item.output ?? '') + const tool = tools.get(str(item.call_id)) + if (tool && /"exit_code"\s*:\s*[1-9]|Process exited with code [1-9]|exit code:? [1-9]/i.test(output)) tool.failed = true + } + } + return { format: SESSION_FORMAT, agent: 'codex', ...(cwd ? { cwd } : {}), ...(branch ? { branch } : {}), ...(startedAt ? { startedAt, endedAt } : {}), entries, removed } +} + +/** Scrubs every entry and the note, drops the entries the developer chose to leave out, and trims the middle of a session + * too long to send, keeping its start and its end. */ +export function prepareSession(read: Omit & { cwd?: string }, note: string, context: ScrubContext = {}, skip: number[] = []): SessionDocument { + const removed = { ...read.removed } + let entries = read.entries.flatMap((entry, index) => { + if (skip.includes(index)) { removed.skipped++; return [] } + let text = scrubText(entry.text, context, removed) + if (text.length > ENTRY_TEXT_LIMIT) text = text.slice(0, ENTRY_TEXT_LIMIT) + ' [cut]' + return text ? [{ ...entry, text }] : [] + }) + const size = () => entries.reduce((sum, entry) => sum + entry.text.length + 40, 0) + if (entries.length > SESSION_ENTRY_LIMIT || size() > SESSION_TEXT_LIMIT) { + const head = entries.slice(0, 50) + let tail = entries.slice(50) + while (tail.length && (head.length + tail.length + 1 > SESSION_ENTRY_LIMIT || [...head, ...tail].reduce((sum, entry) => sum + entry.text.length + 40, 0) > SESSION_TEXT_LIMIT)) { tail = tail.slice(Math.ceil(tail.length / 10)) } + removed.trimmed = entries.length - head.length - tail.length + entries = [...head, { who: 'tool', text: `[${removed.trimmed} entries left out to fit the size limit]` }, ...tail] + } + const cleanNote = scrubText(note, context).slice(0, SESSION_NOTE_LIMIT) + return { format: SESSION_FORMAT, agent: read.agent, ...(read.branch ? { branch: oneLine(scrubText(read.branch, context), 120) } : {}), ...(read.startedAt ? { startedAt: read.startedAt, endedAt: read.endedAt } : {}), note: cleanNote, entries, removed } +} + +const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z$/ +/** The Worker's check of a session it is asked to store: the shape, the limits, and no firmware or secrets left. */ +export function validateSession(value: unknown): { ok: true; session: SessionDocument } | { ok: false; error: string } { + if (!record(value) || value.format !== SESSION_FORMAT) return { ok: false, error: 'Send a session in the current format (update your checkout).' } + if (!SESSION_AGENTS.includes(value.agent as SessionAgent)) return { ok: false, error: 'Name the agent: ' + SESSION_AGENTS.join(' or ') + '.' } + if (typeof value.note !== 'string' || value.note.length > SESSION_NOTE_LIMIT) return { ok: false, error: `Keep the note to ${SESSION_NOTE_LIMIT} characters.` } + if (value.branch !== undefined && (typeof value.branch !== 'string' || value.branch.length > 120)) return { ok: false, error: 'The branch must be a short name.' } + for (const key of ['startedAt', 'endedAt']) if (value[key] !== undefined && (typeof value[key] !== 'string' || !ISO.test(value[key] as string))) return { ok: false, error: 'Times must be UTC timestamps.' } + if (!Array.isArray(value.entries) || !value.entries.length || value.entries.length > SESSION_ENTRY_LIMIT + 1) return { ok: false, error: 'A session holds 1 to ' + SESSION_ENTRY_LIMIT + ' entries.' } + for (const entry of value.entries) { + if (!record(entry) || !['developer', 'agent', 'tool'].includes(entry.who as string) || typeof entry.text !== 'string' || entry.text.length > ENTRY_TEXT_LIMIT + 10 + || (entry.at !== undefined && (typeof entry.at !== 'string' || !ISO.test(entry.at))) || (entry.failed !== undefined && entry.failed !== true)) return { ok: false, error: 'An entry is not in the session format.' } + } + if (!record(value.removed)) return { ok: false, error: 'Say what the client removed.' } + const session = value as SessionDocument, texts = [session.note, ...session.entries.map(entry => entry.text)] + const firmware = firmwareFindings(session.entries) + if (firmware.length) return { ok: false, error: `Entries ${firmware.slice(0, 5).map(item => item.index).join(', ')} still look like firmware or stock code (${firmware[0].reason}). Leave them out with --skip and send again.` } + if (texts.some(secretLike)) return { ok: false, error: 'A secret is still in the session. Update your checkout, which removes it, and send again.' } + return { ok: true, session } +} + +/** The folder Claude Code keeps a working directory's transcripts in: every character but letters and digits becomes '-'. */ +export const claudeProjectFolder = (cwd: string) => cwd.replace(/[^A-Za-z0-9]/g, '-') diff --git a/worker.ts b/worker.ts index 845bcb6ee4..8839f8e21a 100644 --- a/worker.ts +++ b/worker.ts @@ -16,6 +16,7 @@ import { cleanupForumMedia } from './server/forum-media' import { cleanupAudioPreviews } from './server/audio-previews' import { cleanupRemoteSessions } from './server/remote-sessions' import { syncAgentClaims } from './server/agent-board' +import { cleanupAgentSessions } from './server/agent-sessions' import { dispatchMaintenance } from './server/maintenance-bot' import { handleCommunity } from './server/transport' import type { Env } from './server/platform' @@ -54,7 +55,7 @@ export default { context.waitUntil(runHourly({ 'Octatrack diagnostics cleanup': () => cleanupOctatrackDiagnostics(db), 'remote session cleanup': () => cleanupRemoteSessions(db), 'push cleanup': () => cleanupPush(db), 'usage cleanup': () => cleanupUsage(db), 'presence cleanup': () => cleanupPresence(db), 'account cleanup': () => cleanupAccounts(db), - 'developer auth cleanup': () => cleanupDeveloperAuth(db), 'beta inactivity': () => remindInactiveBetaTesters(env, db), 'module threads': () => ensureModuleThreads(db), 'activity digests': activity, 'forum media cleanup': () => cleanupForumMedia(env), 'audio preview cleanup': () => cleanupAudioPreviews(env), 'agent board': () => syncAgentClaims(env, db), + 'developer auth cleanup': () => cleanupDeveloperAuth(db), 'beta inactivity': () => remindInactiveBetaTesters(env, db), 'module threads': () => ensureModuleThreads(db), 'activity digests': activity, 'forum media cleanup': () => cleanupForumMedia(env), 'audio preview cleanup': () => cleanupAudioPreviews(env), 'agent board': () => syncAgentClaims(env, db), 'agent session cleanup': () => cleanupAgentSessions(db), })) }, } From dbfd011a7e2d69b241107ecb1fd5db9fa412ea80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jannik=20A=C3=9Ffalg?= <67785539+repeat98@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:57:39 +0100 Subject: [PATCH 02/11] Build the scrubber test's fake key at runtime, so secret scanners do not flag it Co-Authored-By: Claude Opus 5.5 --- src/community/agent-sessions.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/community/agent-sessions.test.ts b/src/community/agent-sessions.test.ts index 2911557ad8..1f1ab737ad 100644 --- a/src/community/agent-sessions.test.ts +++ b/src/community/agent-sessions.test.ts @@ -71,7 +71,8 @@ describe('scrubbing', () => { const removed = { toolOutputs: 0, thinking: 0, codeBlocks: 0, hexLines: 0, blobs: 0, secrets: 0, skipped: 0, trimmed: 0 } const text = scrubText([ 'Token ghp_' + 'a'.repeat(36) + ' and sk-ant-' + 'b'.repeat(30) + ' and board ' + 'c'.repeat(64), - 'RESEND_API_KEY=re_live9x8y7z6w5v4u3t2s1 and password: hunter22 and Authorization: Bearer abcdefghijklmnopqrstuv', + // Built at runtime, so no secret-shaped literal sits in the source for secret scanners. + 'RESEND_API_KEY=' + ['re', 'live' + '9'.repeat(16)].join('_') + ' and password: ' + 'hunter' + 22 + ' and Authorization: Bearer ' + 'abcdefghijklmnopqrstuv', 'The token: expired, so I signed in again.', 'Opened /home/jannik/modwerk/AGENTS.md and C:\\Users\\jannik\\Dev on jannik-laptop, mail me at someone@example.com from 192.168.1.20.', ].join('\n'), { user: 'jannik', host: 'jannik-laptop' }, removed) From 3595759e1cb876e9835ad99ec8b9b4b9ad12743b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jannik=20A=C3=9Ffalg?= <67785539+repeat98@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:19:51 +0100 Subject: [PATCH 03/11] Scrub the home folder in the form Claude Code names its project folders Saved tool outputs live under ~/.claude/projects/, so their paths carried the developer user name past the home-path rule. Co-Authored-By: Claude Opus 5.5 --- scripts/agent-session.mjs | 2 +- src/community/agent-sessions.test.ts | 6 ++++++ src/community/agent-sessions.ts | 4 +++- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/scripts/agent-session.mjs b/scripts/agent-session.mjs index a41a902fe1..4a7be430eb 100644 --- a/scripts/agent-session.mjs +++ b/scripts/agent-session.mjs @@ -104,7 +104,7 @@ export async function buildSession({ file, agent, note = '', skip = [] }) { 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] }, skip) + return prepareSession(read, note, { user, host: hostname().split('.')[0], home: homedir() }, skip) } function summary(session, file) { diff --git a/src/community/agent-sessions.test.ts b/src/community/agent-sessions.test.ts index 1f1ab737ad..053877d36c 100644 --- a/src/community/agent-sessions.test.ts +++ b/src/community/agent-sessions.test.ts @@ -82,6 +82,12 @@ describe('scrubbing', () => { expect(removed.secrets).toBeGreaterThanOrEqual(6) }) + it('removes the home folder in the form Claude Code names its project folders', () => { + const text = scrubText('Read ~/.claude/projects/C--Users-jan-doe-Dev/abc/tool-results/x.txt and /home/alice/.claude/projects/-home-alice-modwerk/y.jsonl', { home: 'C:\\Users\\jan.doe' }) + expect(text).toBe('Read ~/.claude/projects/~-Dev/abc/tool-results/x.txt and ~/.claude/projects/-home-alice-modwerk/y.jsonl') + expect(scrubText('-home-alice-modwerk', { home: '/home/alice' })).toBe('~-modwerk') + }) + it('removes hex dumps, hex tables and long code blocks, and keeps short snippets', () => { const removed = { toolOutputs: 0, thinking: 0, codeBlocks: 0, hexLines: 0, blobs: 0, secrets: 0, skipped: 0, trimmed: 0 } const long = '```c\n' + Array.from({ length: 20 }, (_, i) => `line ${i};`).join('\n') + '\n```' diff --git a/src/community/agent-sessions.ts b/src/community/agent-sessions.ts index fc8c562838..9c9667cd1b 100644 --- a/src/community/agent-sessions.ts +++ b/src/community/agent-sessions.ts @@ -19,7 +19,7 @@ export type SessionAgent = typeof SESSION_AGENTS[number] export type SessionEntry = { who: 'developer' | 'agent' | 'tool'; text: string; at?: string; failed?: true } export type SessionRemoved = { toolOutputs: number; thinking: number; codeBlocks: number; hexLines: number; blobs: number; secrets: number; skipped: number; trimmed: number } export type SessionDocument = { format: 1; agent: SessionAgent; branch?: string; startedAt?: string; endedAt?: string; note: string; entries: SessionEntry[]; removed: SessionRemoved } -export type ScrubContext = { user?: string; host?: string } +export type ScrubContext = { user?: string; host?: string; home?: string } const ENTRY_TEXT_LIMIT = 20_000 const CODE_BLOCK_LINES = 12 @@ -70,6 +70,8 @@ export function scrubText(input: string, context: ScrubContext = {}, removed: Se text = text.replace(BEARER, (_all, scheme: string) => { removed.secrets++; return scheme + ' [secret removed]' }) text = text.replace(BLOB, () => { removed.blobs++; return '[data removed]' }) text = text.replace(EMAIL, '[email]').replace(HOME, '~').replace(IPV4, '[address]') + // The home folder as Claude Code names its project folders (-home-alice-modwerk, C--Users-alice-Dev), which saved tool outputs' paths carry. + if (context.home) { const folder = claudeProjectFolder(context.home); if (folder.replace(/-/g, '').length >= 4) text = text.split(folder).join('~') } if (context.user && context.user.length >= 3) text = text.replace(new RegExp(`\\b${escape(context.user)}\\b`, 'gi'), '[user]') if (context.host && context.host.length >= 3) text = text.replace(new RegExp(`\\b${escape(context.host)}\\b`, 'gi'), '[host]') return text.replace(/\n{3,}/g, '\n\n').trim() From b3ad3cde9eefb1c8bccd10bc7c154a2a0f47aca3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jannik=20A=C3=9Ffalg?= <67785539+repeat98@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:26:06 +0100 Subject: [PATCH 04/11] Fix: diagnostics say and show the module memory at a refused restore Base 0.7.10's log records the module pool when a restore refuses a package (fix/refused-set-pool, for the cumulative base draft). The invitation and the privacy page (German and English) now say the log carries it, and the diagnostics pull prints the memory used and the largest free block beside the refused module. Older bases leave both fields 0 and print as before. Co-Authored-By: Claude Opus 5.5 --- changelog/2026-11-19-diagnostics-refused-pool.md | 1 + scripts/diagnostics-pull.mjs | 5 ++++- scripts/diagnostics-pull.test.mjs | 3 +++ src/community/PrivacyPage.tsx | 2 +- src/components/DiagnosticsInvitation.tsx | 2 +- 5 files changed, 10 insertions(+), 3 deletions(-) create mode 100755 changelog/2026-11-19-diagnostics-refused-pool.md 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..538c9e8c9f --- /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 and how much module memory was in use then (base 0.7.10 and later), and the owner's diagnostics pull shows that memory beside the refused module. diff --git a/scripts/diagnostics-pull.mjs b/scripts/diagnostics-pull.mjs index 19d0a94392..f4989533fb 100644 --- a/scripts/diagnostics-pull.mjs +++ b/scripts/diagnostics-pull.mjs @@ -53,9 +53,12 @@ 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: the module pool when it was refused, in 16-byte units (diag.c: cpu the + * bytes used, dsp0 the largest free run; the site reads dsp0 as dsp5to8). Older bases leave both 0. */ +const refusedPool = r => r.cpu || r.dsp5to8 ? `, 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..ffb9184976 100644 --- a/scripts/diagnostics-pull.test.mjs +++ b/scripts/diagnostics-pull.test.mjs @@ -111,6 +111,9 @@ 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 module pool at the refusal, in 16-byte units: 760 KiB used, a 1.5 KiB largest free block. + expect(unitLines([{ ...set, tempo24: 2, cpu: 48640, dsp5to8: 96 }])[0]) + .toContain('refused SC Ringmod (module memory, 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/src/community/PrivacyPage.tsx b/src/community/PrivacyPage.tsx index 772d3983ad..dfb37e8369 100644 --- a/src/community/PrivacyPage.tsx +++ b/src/community/PrivacyPage.tsx @@ -20,7 +20,7 @@ export function PrivacyPage() {

{de?'6. Freiwillige Zählung eindeutiger Besucher':'6. Optional unique-visitor counts'}

{de?'Die Zählung eindeutiger Besucher ist standardmäßig aus. Erst nach Ihrer Einwilligung speichern wir eine täglich wechselnde Zufallskennung, lokale Zählmarker für begonnene Konfigurationen und Ihre datierte Einwilligung. Wir zählen Seitenaufrufe, begonnene Konfigurationen, erfolgreiche und fehlgeschlagene Builds, Exporte, angeforderte Firmware-Downloads, Öffnungen des Unterstützungsdialogs und Klicks auf den Ko-fi-Link, bei Builds und Downloads mit dem Gerät (Octatrack, Digitakt oder Digitone). Jeder enthaltene Modulbezeichner wird einzeln für eine öffentliche Gesamtsumme gemeldet. Dies dient der Einschätzung, welche Funktionen und Module genutzt werden.':'Unique-visitor counts are off by default. Only after consent do we store a daily random identifier, local markers for configurations already counted, and your dated consent choice. We count page views, configurations started, successful and failed builds, exports, requested firmware downloads, support dialog opens and Ko-fi link clicks, with the machine (Octatrack, Digitakt or Digitone) for builds and downloads. Included module IDs are reported individually to public module totals. This helps us understand which features and modules people use.'}

{de?'Seitenaufrufe enthalten einen festgelegten Seitennamen oder eine öffentliche Katalog-Modulkennung. Diskussionen, Profile, Nachrichten und Kontoseiten werden ohne Thread-IDs, Nutzernamen oder Tokens zusammengefasst. Wir speichern nur Tagessummen je Seite für 90 Tage, ohne Seiten mit Besuchern oder Konten zu verknüpfen. Die Ereignisse enthalten keine Firmware, Dateinamen, E-Mail-Adressen, Konfigurationsnamen, vollständigen URLs oder Abfrageparameter. Verbindungsdaten fallen bei Cloudflare an; kurzlebige gehashte Kennungen ermöglichen Zählung und Missbrauchsschutz. Diese Verarbeitung beginnt daher nicht als vollständig anonyme Verarbeitung. Tages-Gesamtsummen werden 90 Tage und Stunden-Gesamtsummen 14 Tage aufbewahrt; Ereignismarker bis zur stündlichen Bereinigung, höchstens etwa 48 Stunden. Nicht personenbezogene Modul-Gesamtsummen bleiben bestehen. Die Einwilligung gilt bis zum Widerruf, einer Zweckänderung oder höchstens 180 Tage.':'Page views include a fixed page name or public catalog module ID. Discussions, profiles, messages and account screens are grouped, without thread IDs, usernames or tokens. We keep only daily totals per page for 90 days, without linking pages to visitors or accounts. Events contain no firmware, file names, emails, configuration names, raw URLs or query strings. Cloudflare receives connection data; short-lived hashed identifiers support counts and abuse prevention. The initial processing is therefore not fully anonymous. Daily totals are kept for 90 days and hourly totals for 14 days; event markers until hourly cleanup, at most about 48 hours. Non-personal aggregate module totals remain. Consent lasts until withdrawal, a purpose change or at most 180 days.'}

{de?'Rechtsgrundlagen sind Ihre Einwilligung nach Art. 6 Abs. 1 lit. a DSGVO und § 25 Abs. 1 TDDDG. Sie können hier jederzeit ebenso einfach widerrufen. Widerruf beendet weitere Zählung mit Kennung und entfernt lokale Zählkennungen (anonyme Gesamtzählung läuft weiter, sofern Sie oben nicht widersprechen); die Rechtmäßigkeit früherer Verarbeitung bleibt unberührt. Bereits nicht personenbezogene Gesamtsummen lassen sich nicht Ihrem Konto zuordnen. Ihre Entscheidung beeinflusst die Nutzung des Dienstes nicht.':'The bases are your consent under Article 6(1)(a) GDPR and § 25(1) TDDDG. Withdraw here just as easily at any time. Withdrawal stops future counts with identifiers and removes local counting identifiers (anonymous totals continue unless you object above); it does not affect the lawfulness of prior processing. Non-personal totals already produced cannot be linked back to your account. Your choice does not affect access to the service.'}

{browserPrivacy&&

{de?'Ihr Browser fordert Datenschutz an; Nutzungszählung bleibt aus.':'Your browser requests privacy, so usage counts stay off.'}

}{!enabled&&!browserPrivacy&&

{de?'Nutzungszählung ist auf diesem Gerät aus.':'Usage counts are off on this device.'}

}{error&&

{error}

}

{de?'Freiwillige technische Diagnoseberichte':'Optional technical diagnostics'}

{de?'Stand dieses Abschnitts: 11. November 2026. Verifizierte Mitglieder und Besucher ohne Konto können Diagnoseberichte ausdrücklich aktivieren, um Fehler zu untersuchen. Die Einwilligung ist freiwillig (Art. 6 Abs. 1 lit. a DSGVO), gilt für angemeldete Sitzungen, ohne Konto für diesen Browser, für 90 Tage und ist unabhängig von Beta-Zugang und Nutzungszählung. Ohne Einwilligung funktionieren Builds und USB-Sync unverändert.':'This section was updated on 11 November 2026. Verified members and visitors without an account can explicitly enable technical reports to help investigate failures. Consent is optional (Article 6(1)(a) GDPR), applies to signed-in sessions, or without an account to this browser, for 90 days and is separate from beta access and usage counts. Builds and USB sync work the same without consent.'}

-

{de?'Browserfehler enthalten nur den Fehlertyp und den geöffneten Bereich der Website als feste Kategorien; Build-Fehler enthalten Build-Typ, Phase und Fehlerkategorie. Bei Octatrack-USB-Sync können außerdem Basis-, Set- und Paket-Hashes, Paketgrößen, Modul-IDs und Katalogversionen, Verbindungs- und Sync-Ereignisse, Selbsttestergebnisse, numerische Lastwerte und Ablehnungscodes erfasst werden. Ein fehlgeschlagener Sync nennt den Schritt, bei dem er abbrach, und den Fehlertyp, beides als feste Kategorien; blieb dabei eine Übertragung unbestätigt, außerdem sechs USB-Zähler des Octatrack über diesen Sync (empfangene und abgelehnte Übertragungen, USB-Resets, begonnene, abgeschlossene und abgebrochene Datenphasen).Schlägt die Verbindung zum Octatrack fehl, bevor sie besteht, nennt der Bericht den Grund als eine von wenigen festen Kategorien (kein WebUSB im Browser, kein Octatrack ausgewählt, Zugriff verweigert, konnte nicht geöffnet werden, von einer anderen App belegt). Solange der Octatrack verbunden ist, werden CPU- und DSP-Last alle 30 Sekunden gelesen und alle 5 Minuten übertragen, außerdem vor und nach einem Sync, beim Trennen der Verbindung oder Schließen der Seite, sofort bei über 90 % CPU-Last und wenn der Octatrack nicht mehr antwortet. Der Octatrack führt außerdem ein eigenes kleines Protokoll, auch während die Website geschlossen ist: Last und ob er spielte, Überlastungen, Hänger und Abstürze, und in einem solchen Moment für jede Spur Maschinentyp und Effekte, ob er spielte, das Tempo, den geöffneten Bildschirm und die letzten 16 gedrückten Tasten. Die Website überträgt dieses Protokoll bei der nächsten Verbindung. Außer diesem Protokoll nennt jeder Bericht den Browser mit seiner Hauptversion und das Betriebssystem als Familie, etwa Chrome 131 unter Windows, nie die vollständige Browserkennung (User-Agent). Es werden keine Firmware, Samples, Audiodaten, Projekt-, Sample- oder Set-Namen, sonstigen Projektinhalte, Seriennummern, Fehlermeldungstexte, Stacktraces, Dateinamen, Seitenadressen, Speicher- oder Crash-Dumps übertragen.':'Browser failures contain only the error type and the part of the site that was open, as fixed categories; build failures contain the build type, stage and error category. Octatrack USB reports can also include base, set and package hashes, package sizes, module IDs and catalogue versions, connection and sync events, self-test results, numeric load readings and refusal codes. A sync that fails names the step it stopped at and the error type, both as fixed categories; one that stopped on an unconfirmed transfer also carries six of the Octatrack’s USB counts over that sync (transfers received and refused, USB resets, data stages started, completed and abandoned).If connecting to the Octatrack fails before a connection exists, the report names the reason as one of a few fixed categories (no WebUSB in the browser, no Octatrack chosen, access denied, could not be opened, in use by another app). While the Octatrack is connected, its CPU and DSP load are read every 30 seconds and sent every 5 minutes, before and after a sync, when it disconnects or the page closes, at once above 90 % CPU and when the Octatrack stops answering. The Octatrack also keeps a small log of its own, also while the site is closed: its load and whether it was playing, overloads, freezes and crashes, and at such a moment each track’s machine type and effects, playing or stopped, the tempo, the screen that was open and the last 16 keys pressed. The site sends that log at the next connection. Every report except that log names the browser with its main version and the operating system as families, such as Chrome 131 on Windows, never the full browser identification (user agent). Reports contain no firmware, samples, audio, project, sample or set names, other project contents, serial numbers, error messages, stack traces, filenames, page addresses, memory or crash dumps.'}

+

{de?'Browserfehler enthalten nur den Fehlertyp und den geöffneten Bereich der Website als feste Kategorien; Build-Fehler enthalten Build-Typ, Phase und Fehlerkategorie. Bei Octatrack-USB-Sync können außerdem Basis-, Set- und Paket-Hashes, Paketgrößen, Modul-IDs und Katalogversionen, Verbindungs- und Sync-Ereignisse, Selbsttestergebnisse, numerische Lastwerte und Ablehnungscodes erfasst werden. Ein fehlgeschlagener Sync nennt den Schritt, bei dem er abbrach, und den Fehlertyp, beides als feste Kategorien; blieb dabei eine Übertragung unbestätigt, außerdem sechs USB-Zähler des Octatrack über diesen Sync (empfangene und abgelehnte Übertragungen, USB-Resets, begonnene, abgeschlossene und abgebrochene Datenphasen).Schlägt die Verbindung zum Octatrack fehl, bevor sie besteht, nennt der Bericht den Grund als eine von wenigen festen Kategorien (kein WebUSB im Browser, kein Octatrack ausgewählt, Zugriff verweigert, konnte nicht geöffnet werden, von einer anderen App belegt). Solange der Octatrack verbunden ist, werden CPU- und DSP-Last alle 30 Sekunden gelesen und alle 5 Minuten übertragen, außerdem vor und nach einem Sync, beim Trennen der Verbindung oder Schließen der Seite, sofort bei über 90 % CPU-Last und wenn der Octatrack nicht mehr antwortet. Der Octatrack führt außerdem ein eigenes kleines Protokoll, auch während die Website geschlossen ist: Last und ob er spielte, Überlastungen, Hänger und Abstürze, ein Modul, das er beim Start nicht laden konnte, mit dem dabei belegten Modulspeicher, und in einem solchen Moment für jede Spur Maschinentyp und Effekte, ob er spielte, das Tempo, den geöffneten Bildschirm und die letzten 16 gedrückten Tasten. Die Website überträgt dieses Protokoll bei der nächsten Verbindung. Außer diesem Protokoll nennt jeder Bericht den Browser mit seiner Hauptversion und das Betriebssystem als Familie, etwa Chrome 131 unter Windows, nie die vollständige Browserkennung (User-Agent). Es werden keine Firmware, Samples, Audiodaten, Projekt-, Sample- oder Set-Namen, sonstigen Projektinhalte, Seriennummern, Fehlermeldungstexte, Stacktraces, Dateinamen, Seitenadressen, Speicher- oder Crash-Dumps übertragen.':'Browser failures contain only the error type and the part of the site that was open, as fixed categories; build failures contain the build type, stage and error category. Octatrack USB reports can also include base, set and package hashes, package sizes, module IDs and catalogue versions, connection and sync events, self-test results, numeric load readings and refusal codes. A sync that fails names the step it stopped at and the error type, both as fixed categories; one that stopped on an unconfirmed transfer also carries six of the Octatrack’s USB counts over that sync (transfers received and refused, USB resets, data stages started, completed and abandoned).If connecting to the Octatrack fails before a connection exists, the report names the reason as one of a few fixed categories (no WebUSB in the browser, no Octatrack chosen, access denied, could not be opened, in use by another app). While the Octatrack is connected, its CPU and DSP load are read every 30 seconds and sent every 5 minutes, before and after a sync, when it disconnects or the page closes, at once above 90 % CPU and when the Octatrack stops answering. The Octatrack also keeps a small log of its own, also while the site is closed: its load and whether it was playing, overloads, freezes and crashes, a module it couldn’t load at start with how much module memory was in use, and at such a moment each track’s machine type and effects, playing or stopped, the tempo, the screen that was open and the last 16 keys pressed. The site sends that log at the next connection. Every report except that log names the browser with its main version and the operating system as families, such as Chrome 131 on Windows, never the full browser identification (user agent). Reports contain no firmware, samples, audio, project, sample or set names, other project contents, serial numbers, error messages, stack traces, filenames, page addresses, memory or crash dumps.'}

{de?'Die Berichte werden über unseren Cloudflare-Dienst verarbeitet, Ihrem Konto zugeordnet und sind nur für Sie und Website-Administratoren sichtbar. Sie werden nicht an GitHub oder Modulautoren weitergegeben. Der Betreiber kann sie mit einem KI-Assistenten (Claude von Anthropic) auswerten; dafür werden sie an Anthropic übermittelt. Maximal 1.000 Berichte pro Konto sind für 30 Tage verfügbar; abgelaufene Daten werden stündlich gelöscht. Unter „Your Octatrack“ → Diagnostics können Sie jederzeit die Freigabe beenden und die Berichte löschen. Sie sind im Kontoexport enthalten und werden bei Kontolöschung entfernt. Ohne Konto werden die Berichte keinem Konto zugeordnet, sondern einer zufälligen Kennung, die Ihr Browser erst bei Ihrer Zustimmung erzeugt und nur lokal speichert; der Server speichert nur deren Hashwert, höchstens 1.000 Berichte für 30 Tage, und nur Website-Administratoren können sie lesen. Beenden Sie die Freigabe in diesem Browser, werden die Berichte und die Kennung gelöscht; löschen Sie vorher die Website-Daten des Browsers, lassen sich die Berichte nicht mehr zuordnen und verfallen nach 30 Tagen. Browser-Datenschutzsignale stoppen die Erfassung in diesem Browser. Ob Sie die Einladung geschlossen haben, wird lokal für Ihr Konto und diese Einwilligungsversion gespeichert. Wer nicht teilt, kann nach einem fehlgeschlagenen Sync, Selbsttest oder Basis-Update, wenn der Ton des Octatrack stehen bleibt oder er seine vorherige Basis gestartet hat, noch einmal gefragt werden; „Not now“ wird dort lokal für Ihr Konto 30 Tage lang gespeichert.':'Reports use our Cloudflare service, are linked to your account and are visible only to you and site administrators. They are not sent to GitHub or module authors. The operator may analyse them with an AI assistant (Anthropic’s Claude); for that, they are sent to Anthropic. Up to 1,000 reports per account are available for 30 days; expired records are removed by hourly cleanup. Stop sharing and delete reports at any time under Diagnostics in Your Octatrack. Reports are included in your account export and removed on account deletion. Without an account, reports are not linked to an account but to a random ID that your browser creates only when you agree and keeps locally; the server stores only its hash, at most 1,000 reports for 30 days, and only site administrators can read them. Stopping sharing in that browser deletes the reports and the ID; if you clear the browser’s site data first, the reports can no longer be matched to you and expire after 30 days. Browser privacy signals stop collection in that browser. Dismissing the invitation is remembered locally for your account and this consent version. A member who does not share may be asked once more after a failed sync, self-test or base update, when the Octatrack’s audio stops or when it started its previous base; Not now there is remembered locally for your account for 30 days.'}

{de?'7. Aufbewahrung und Löschung':'7. Retention and removal'}

{de?'Verifizierungslinks gelten 24 Stunden, Wiederherstellungslinks 30 Minuten und jeweils einmal. Abgelaufene Sitzungen, Links und Missbrauchsmarker werden stündlich bereinigt. Missbrauchsmarker können je nach Begrenzung bis zu 30 Tage gelten. Konten und notwendige Kontodaten bleiben während Ihrer Teilnahme gespeichert. Beiträge bleiben verfügbar, solange sie für die Diskussion und Zuordnung von Beiträgen benötigt werden; personenbezogene Inhalte werden auf Anfrage geprüft und entfernt, sofern keine Rechtsgrundlage für ihre Aufbewahrung besteht.':'Verification links last 24 hours and recovery links 30 minutes, each for one use. Expired sessions, action links and abuse markers are cleaned hourly. Abuse markers may last up to 30 days depending on the limit. Accounts and necessary account data remain during your participation. Contributions remain while needed for discussion and attribution; personal content is reviewed for removal on request unless there is a lawful retention reason.'}

{de?'Private Fehlerberichte, Benachrichtigungen, Meldungen und Korrespondenz werden bis zur Erledigung und einer notwendigen Nachbearbeitung aufbewahrt; der Betreiber prüft die Erforderlichkeit regelmäßig. Es gibt derzeit keine automatische Löschfrist für diese Inhalte oder unverifizierte Konten. Löschanfragen führen zu einer individuellen Prüfung. Gesetzlich erforderliche Aufbewahrung oder die Verteidigung von Rechtsansprüchen wird begründet und auf notwendige Daten beschränkt.':'Private issue reports, notifications, notices and correspondence remain until resolved and any necessary follow-up is complete; the operator reviews continued necessity regularly. There is currently no automatic deletion period for this content or unverified accounts. Removal requests receive an individual assessment. Retention required by law or to defend legal claims is explained and limited to the necessary data.'}

{de?'Provider-Sicherheitslogs und Wiederherstellungskopien unterliegen zusätzlich den Einstellungen und Fristen der Anbieter. Verschlüsselte Sicherungen sind nur dem Betreiber zugänglich, werden ausschließlich zur Wiederherstellung verwendet und nach der festgelegten Sicherungsrotation entfernt. Bei einer Wiederherstellung müssen bereits bewilligte Löschungen erneut angewendet werden. Fragen Sie den Verantwortlichen nach den für Ihre Daten geltenden Provider- und Sicherungsfristen.':'Provider security logs and recovery copies also follow provider settings and retention. Encrypted backups are restricted to the operator, used only for recovery and removed under the chosen backup rotation. Approved removals must be reapplied after a restore. Ask the controller for the provider and backup periods applicable to your data.'}

diff --git a/src/components/DiagnosticsInvitation.tsx b/src/components/DiagnosticsInvitation.tsx index 1dfa016977..ca8bb9e2e3 100644 --- a/src/components/DiagnosticsInvitation.tsx +++ b/src/components/DiagnosticsInvitation.tsx @@ -14,7 +14,7 @@ export function DiagnosticDetails() {

Browser failures are recorded as the type of error and the part of the site that was open. Build failures include the type of build (for a Digitakt, Digitone or Rytm build, which machine it was for) and the stage that failed. No error messages, stack traces, file names or page addresses are sent.

When you use Octatrack USB sync, reports can also include base and running-set hashes, package hashes and sizes, module IDs with this site’s catalogue versions, connection and sync events, self-test results, load readings and refusal codes. An older installed module may have a different version. While your Octatrack is connected, its CPU and DSP load are read every 30 seconds and sent every 5 minutes, before and after a sync, when it disconnects or you close the page, at once when the CPU goes above 90 %, and when the Octatrack stops answering.

If connecting to your Octatrack fails, the report says why, as one of a few fixed reasons: this browser has no WebUSB, no Octatrack was chosen, access was denied, it couldn’t be opened, or another app was using it.

-

The Octatrack also keeps a small log of its own, also while this site is closed: its load and whether it was playing, overloads, freezes and crashes, and at such a moment each track’s machine type and effects, playing or stopped, the tempo, the screen that was open and the last 16 keys pressed. The site sends that log the next time you connect.

+

The Octatrack also keeps a small log of its own, also while this site is closed: its load and whether it was playing, overloads, freezes and crashes, a module it couldn’t load at start with how much module memory was in use, and at such a moment each track’s machine type and effects, playing or stopped, the tempo, the screen that was open and the last 16 keys pressed. The site sends that log the next time you connect.

Every report except that log also names your browser with its main version and your operating system, such as Chrome 131 on Windows, never the full browser identification.

No firmware, samples, audio, project, sample or set names, device serial numbers, raw memory or crash dumps. Reports use Modwerk’s Cloudflare service and aren’t posted to GitHub or shared with module authors. I may have an AI assistant (Anthropic’s Claude) help me read them; for that, they are sent to Anthropic.

Consent is optional under GDPR Article 6(1)(a). You can stop sharing and delete reports under Diagnostics in Your Octatrack. Signed in, your account data download includes them; without an account they are kept under a random ID stored in this browser. Reports are hidden after 30 days and deleted by hourly cleanup, with at most 1,000 entries per account or browser. Privacy and your rights.

From 5993ca1f053bf93441ebbdeafb8393b970a772e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jannik=20A=C3=9Ffalg?= <67785539+repeat98@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:32:29 +0100 Subject: [PATCH 05/11] Improvement: show selection tradeoffs while browsing --- .../2026-11-19-library-selection-feedback.md | 2 + src/App.tsx | 12 +++- src/community/public-announcement.ts | 2 +- src/components/LibraryDiscovery.test.ts | 63 ++++++++++++++++++- src/components/LibraryResultsBar.test.ts | 2 +- src/components/LibrarySelection.tsx | 63 +++++++++++++++++++ src/components/SelectionWarning.tsx | 25 -------- src/devices/MachinePages.tsx | 13 +--- src/devices/library-parity.test.ts | 6 +- src/styles.css | 59 +++++++++++------ 10 files changed, 181 insertions(+), 66 deletions(-) create mode 100644 changelog/2026-11-19-library-selection-feedback.md create mode 100644 src/components/LibrarySelection.tsx delete mode 100644 src/components/SelectionWarning.tsx 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/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/public-announcement.ts b/src/community/public-announcement.ts index a43148e9b1..6ddc51c2a8 100644 --- a/src/community/public-announcement.ts +++ b/src/community/public-announcement.ts @@ -23,7 +23,7 @@ export function dismissPublicAnnouncement(id: string) { try { localStorage.setItem(key(), JSON.stringify([id, ...savedDismissals().filter(saved => saved !== id)].slice(0, 50))) } catch { /* Optional news stays dismissed for this visit when storage is blocked. */ } } /** A prompt waits while the page is hidden or another dialog, menu or text field is in use. */ -export const pageBusy = () => document.visibilityState !== 'visible' || !!document.querySelector('dialog[open], .notification-panel, .mobile-menu-panel, .library-machine-menu, .forum-shoutbox.is-floating, .signup-welcome, .selection-warning') || !!document.activeElement?.matches('input, textarea, [contenteditable="true"]') +export const pageBusy = () => document.visibilityState !== 'visible' || !!document.querySelector('dialog[open], .notification-panel, .mobile-menu-panel, .library-machine-menu, .forum-shoutbox.is-floating, .signup-welcome, details.library-selection[open]') || !!document.activeElement?.matches('input, textarea, [contenteditable="true"]') /** Only the newest broadcast gets a card. Dismissing it must never reveal an older backlog. */ export function latestPublicAnnouncement(items: BellItem[]) { const latest = items[0] diff --git a/src/components/LibraryDiscovery.test.ts b/src/components/LibraryDiscovery.test.ts index cfe95a4d42..b3e53bdc46 100644 --- a/src/components/LibraryDiscovery.test.ts +++ b/src/components/LibraryDiscovery.test.ts @@ -5,8 +5,12 @@ import { renderToStaticMarkup } from 'react-dom/server' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { AVAILABLE_MODULES, availableModules } from '../catalog/availability' import { asBeta } from '../catalog/beta-fixture' +import { countsTowardLimit, SET_MODULE_LIMIT } from '../catalog/set-limit' +import { newConfiguration } from '../config/workspace' +import { USB_AUDIO_MODULE } from '../config/usb-audio' import { MachineLibrary } from '../devices/MachinePages' import { DEVICES_BY_ID } from '../devices/registry' +import { LibrarySelection } from './LibrarySelection' import { ModuleComparison } from './ModuleComparison' let container: HTMLDivElement, root: Root @@ -25,7 +29,7 @@ const library = { query: '', octatrackModules: AVAILABLE_MODULES, octatrackSelected: [], onToggleOctatrack: noop, digiSelected: { digitakt: [], 'digitakt-ii': [], digitone: [], 'analog-rytm-mkii': [] }, onToggleDigi: noop, family: 'all', onFamilyChange: noop, sort: 'updated', onSortChange: noop, statistics: null, - octatrackConflicts: [], comparison: [], onCompare: noop, onOpenComparison: noop, + comparison: [], onCompare: noop, onOpenComparison: noop, viewedModuleVersions: {}, moduleBaseline: null, } @@ -68,3 +72,60 @@ describe('module library discovery', () => { expect(count(true)).toBe(3) })) }) + +describe('live library selection details', () => { + it('updates the Octatrack count and reports saved stock FX choices', async () => { + const set = newConfiguration('Live set', ['everb', USB_AUDIO_MODULE]) + const render = (moduleIds: string[], removedStockFx?: string[]) => act(() => root.render( + createElement(LibrarySelection, { sets: [{ ...set, moduleIds, removedStockFx }], betaAccess: false, phone: false }), + )) + await render(set.moduleIds) + const status = container.querySelector('[role="status"]')! + const panel = container.querySelector('.library-selection')! + expect(panel.textContent).toContain(`1 of ${SET_MODULE_LIMIT} modules`) + expect(panel.textContent).toContain('All stock FX kept') + expect(panel.querySelector('a')?.getAttribute('href')).toBe('#configuration') + await render([...set.moduleIds, 'tapeecho'], ['SPRING REV']) + expect(status.textContent).toContain(`2 of ${SET_MODULE_LIMIT} modules`) + expect(panel.textContent).toContain('Spring Reverb is marked off in the stock FX menus') + expect(panel.textContent).toContain('USB sync requires all stock FX') + await render([]) + expect(container.querySelector('.library-selection')).toBeNull() + expect(status.textContent).toBe('No selections to check.') + }) + + it('distinguishes a full Octatrack set from a saved set already over the limit', async () => { + const ids = AVAILABLE_MODULES.map(module => module.id).filter(countsTowardLimit).slice(0, SET_MODULE_LIMIT + 1) + const render = (moduleIds: string[]) => act(() => root.render( + createElement(LibrarySelection, { sets: [newConfiguration('Live set', moduleIds)], betaAccess: false, phone: false }), + )) + await render(ids.slice(0, SET_MODULE_LIMIT)) + expect(container.textContent).toContain('Your set is full') + await render(ids) + expect(container.textContent).toContain('Remove 1 to sync') + }) + + it('updates Digi memory and incompatibility details independently of an Octatrack set', async () => { + const octatrack = newConfiguration('Live set', ['everb']) + const digitakt = newConfiguration('Drums', ['digimono', 'digistring'], false, undefined, 'digitakt') + const render = (moduleIds: string[]) => act(() => root.render( + createElement(LibrarySelection, { sets: [octatrack, { ...digitakt, moduleIds }], betaAccess: false, phone: true }), + )) + await render(digitakt.moduleIds) + const details = container.querySelector('details')! + const summary = details.querySelector('summary')! + expect(details.open).toBe(false) + expect(summary.textContent).toContain('1 issue') + expect(details.textContent).toContain('Digi Mono and STRING cannot be used together') + expect(details.textContent).toContain('Estimated memory') + expect(details.querySelector('a[href="#digitakt/configuration"]')).not.toBeNull() + details.open = true + await render(['digislicer', 'digineighbor', 'digisophie', 'digihealth']) + expect(details.open).toBe(true) + expect(details.textContent).toContain('Over the shared memory limit') + expect(details.textContent).not.toContain('Digi Mono and STRING') + await render(['digislicer', 'digineighbor']) + expect(summary.textContent).toBe('Selection details') + expect(details.textContent).toContain('All stock FX kept') + }) +}) diff --git a/src/components/LibraryResultsBar.test.ts b/src/components/LibraryResultsBar.test.ts index 380fbab6e7..d45a5f3982 100644 --- a/src/components/LibraryResultsBar.test.ts +++ b/src/components/LibraryResultsBar.test.ts @@ -36,7 +36,7 @@ describe('phone library results bar', () => { it('replaces the desktop filter row on phones', () => { const props = { query: '', octatrackModules: AVAILABLE_MODULES, octatrackSelected: [], onToggleOctatrack: noop, digiSelected: { digitakt: [], 'digitakt-ii': [], digitone: [], 'analog-rytm-mkii': [] }, onToggleDigi: noop, - family: 'all', onFamilyChange: noop, sort: 'updated', onSortChange: noop, statistics: null, octatrackConflicts: [], comparison: [], onCompare: noop, onOpenComparison: noop, + family: 'all', onFamilyChange: noop, sort: 'updated', onSortChange: noop, statistics: null, comparison: [], onCompare: noop, onOpenComparison: noop, viewedModuleVersions: {}, moduleBaseline: null, device: DEVICES_BY_ID.octatrack, } expect(renderToStaticMarkup(createElement(MachineLibrary, props))).toContain('class="discovery-tools"') diff --git a/src/components/LibrarySelection.tsx b/src/components/LibrarySelection.tsx new file mode 100644 index 0000000000..3f1f2793f7 --- /dev/null +++ b/src/components/LibrarySelection.tsx @@ -0,0 +1,63 @@ +import { moduleAvailabilityError } from '../catalog/availability' +import { atLimit, limitedCount, LIMIT_REACHED, overLimitMessage, SET_MODULE_LIMIT } from '../catalog/set-limit' +import { STOCK_EFFECT_NAMES } from '../catalog/stock-effects' +import { configurationDevice, type Configuration } from '../config/workspace' +import { estimateCombination, isDigiDevice } from '../devices/digi-mods' +import { DEVICES_BY_ID, deviceHref } from '../devices/registry' +import { Icon } from './Icon' + +function selectionDetails(set: Configuration, betaAccess: boolean) { + const device = configurationDevice(set) + if (device === 'octatrack') { + const limitIssue = overLimitMessage(set.moduleIds, 'sync') || (atLimit(set.moduleIds) ? LIMIT_REACHED : '') + const removed = (set.removedStockFx ?? []).map(key => STOCK_EFFECT_NAMES[key] ?? key) + return { + resources: `${limitedCount(set.moduleIds)} of ${SET_MODULE_LIMIT} modules toward the set limit`, + effects: removed.length ? `${removed.join(', ')} ${removed.length === 1 ? 'is' : 'are'} marked off in the stock FX menus.` : 'All stock FX kept.', + issues: [ + moduleAvailabilityError(set.moduleIds, betaAccess), + limitIssue, + removed.length ? 'USB sync requires all stock FX.' : '', + ].filter(Boolean), + } + } + if (isDigiDevice(device)) { + const estimate = estimateCombination(device, set.moduleIds) + const kib = (bytes: number) => (bytes / 1024).toFixed(1) + return { + resources: `Estimated memory use is ${kib(estimate.usedBytes)} of ${kib(estimate.areaBytes)} KiB`, + issues: [ + ...(!estimate.fits ? ['Over the shared memory limit. Remove a module.'] : []), + ...estimate.clashes.map(clash => `${clash.mods.join(' and ')} cannot be used together (${clash.claim}).`), + ], + } + } +} + +export function LibrarySelection({ sets, betaAccess, phone }: { sets: readonly Configuration[]; betaAccess: boolean; phone: boolean }) { + const entries = sets.flatMap(set => { + if (!set.moduleIds.length && !set.removedStockFx?.length) return [] + const details = selectionDetails(set, betaAccess) + return details ? [{ set, device: configurationDevice(set), ...details }] : [] + }) + const issueCount = entries.reduce((count, entry) => count + entry.issues.length, 0) + const content = entries.map(({ set, device, resources, effects, issues }) =>
+ + {DEVICES_BY_ID[device].name}{set.name} + +

{resources}

+ {effects &&

{effects}

} + {issues.length > 0 &&
    {issues.map(issue =>
  • {issue}
  • )}
} +
) + + return <> +

{entries.length ? entries.map(entry => [`${DEVICES_BY_ID[entry.device].name}, ${entry.resources}.`, entry.effects, ...entry.issues].filter(Boolean).join(' ')).join(' ') : 'No selections to check.'}

+ {entries.length > 0 && (phone ?
+ Selection details{issueCount > 0 && <> {issueCount} {issueCount === 1 ? 'issue' : 'issues'}} +
{content}
+
:
+

Selection details

+
{content}
+
)} + +} diff --git a/src/components/SelectionWarning.tsx b/src/components/SelectionWarning.tsx deleted file mode 100644 index b513401c15..0000000000 --- a/src/components/SelectionWarning.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { useEffect, useId, useRef, useState } from 'react' -import { Icon } from './Icon' - -type Warning = { id: string; title: string; description: string; href: string } - -export function SelectionWarning({ warnings }: { warnings: readonly Warning[] }) { - const [open, setOpen] = useState(false) - const root = useRef(null), button = useRef(null), panelId = useId() - useEffect(() => { - if (!open) return - const outside = (event: PointerEvent) => { if (!root.current?.contains(event.target as Node)) setOpen(false) } - const escape = (event: KeyboardEvent) => { if (event.key === 'Escape') { setOpen(false); button.current?.focus() } } - document.addEventListener('pointerdown', outside) - document.addEventListener('keydown', escape) - return () => { document.removeEventListener('pointerdown', outside); document.removeEventListener('keydown', escape) } - }, [open]) - return
-

{warnings.map(warning => warning.title).join('. ')}

- - -
-} diff --git a/src/devices/MachinePages.tsx b/src/devices/MachinePages.tsx index 81fbfa8fa1..5498015529 100644 --- a/src/devices/MachinePages.tsx +++ b/src/devices/MachinePages.tsx @@ -15,12 +15,10 @@ import { LIBRARY_CATEGORY_LABELS, STANDALONE_NOTE, type FirmwareModule, type Mod import { DETAILS } from '../catalog/details' import type { CatalogBrowse } from '../catalog/catalog-browse' import { AVAILABLE_MODULES } from '../catalog/availability' -import type { SelectionConflict } from '../catalog/selection-conflicts' import type { AddBlock } from '../catalog/add-blocks' import { moduleStability, STABILITY_NOTE } from '../catalog/module-stability' import { AddButton, CardProof, CardStats, ModuleCard } from '../components/ModuleCard' import { LIMIT_REACHED } from '../catalog/set-limit' -import { SelectionWarning } from '../components/SelectionWarning' import { LibraryTools } from '../components/LibraryTools' import { LibraryResultsBar } from '../components/LibraryResultsBar' import { compareModules, downloadCoverage, downloadPeriod, periodCoverage, type ModuleStatistics } from '../community/module-statistics' @@ -125,7 +123,6 @@ type AllMachinesLibraryProps = { sort: string onSortChange: (value: string) => void statistics: readonly ModuleStatistics[] | null - octatrackConflicts: readonly SelectionConflict[] // What adding each Octatrack module would do to the current configuration, by module id. octatrackBlocks?: Record onSwapOctatrack?: (id: string, removeIds: readonly string[]) => void @@ -144,7 +141,7 @@ type MachineLibraryProps = AllMachinesLibraryProps & { buildHref?: string; buildLabel?: string } -export function MachineLibrary({ device, query, category, octatrackModules: octatrack, octatrackSelected, onToggleOctatrack, digiSelected, onToggleDigi, zoomSelected = {}, onToggleZoom, family, onFamilyChange, sort, onSortChange, statistics, octatrackConflicts, octatrackBlocks, onSwapOctatrack, comparison, onCompare, onOpenComparison, viewedModuleVersions, moduleBaseline, machinePicker, children, onClearSearch, onClearQuery, onBrowse, phone = false, resultsSlot, octatrackCatalogue = AVAILABLE_MODULES, buildHref, buildLabel }: MachineLibraryProps) { +export function MachineLibrary({ device, query, category, octatrackModules: octatrack, octatrackSelected, onToggleOctatrack, digiSelected, onToggleDigi, zoomSelected = {}, onToggleZoom, family, onFamilyChange, sort, onSortChange, statistics, octatrackBlocks, onSwapOctatrack, comparison, onCompare, onOpenComparison, viewedModuleVersions, moduleBaseline, machinePicker, children, onClearSearch, onClearQuery, onBrowse, phone = false, resultsSlot, octatrackCatalogue = AVAILABLE_MODULES, buildHref, buildLabel }: MachineLibraryProps) { const w = useSetWords() const heading = useRef(null) const term = query.toLowerCase().trim() @@ -162,13 +159,6 @@ export function MachineLibrary({ device, query, category, octatrackModules: octa ...ZOOM_EFFECTS.filter(effect => (!device || effect.machine === device.id) && (!category || effect.category === category) && matchesZoomEffect(effect, query)).map(effect => effect.presentation.family), ] const typeCounts = families.map(value => ({ value, count: scopeFamilies.filter(item => item === value).length })).filter(option => option.count || option.value === libraryFamily) - const warnings = [ - ...((!device || device.id === 'octatrack') && octatrackConflicts.length ? [{device: DEVICES_BY_ID.octatrack, description: 'Some modules cannot run together. Choose a compatible set in your ' + w.set + '.'}] : []), - ...DIGI_DEVICES.filter(id => !device || device.id === id).flatMap(id => { - const estimate = estimateCombination(id, digiSelected[id]) - return !estimate.fits || estimate.clashes.length ? [{device: DEVICES_BY_ID[id], description: !estimate.fits ? 'The selected mods need more memory than this machine shares with mods.' : 'The selected mods cannot be used together.'}] : [] - }), - ] const digiGroups = DIGI_DEVICES.filter(id => !device || device.id === id).map(id => ({ id, mods: DIGI_MODS.filter(mod => mod.device === id && (!category || mod.libraryCategory === category) && (libraryFamily === 'all' || mod.category === libraryFamily) && digiMatchesQuery(mod, query)) @@ -202,7 +192,6 @@ export function MachineLibrary({ device, query, category, octatrackModules: octa return

MODWERK / {device?.name.toUpperCase() ?? 'ALL MACHINES'}

{category ? LIBRARY_CATEGORY_LABELS[category] : device ? 'Module library' : 'All mods'}

{category === 'standalone' ? STANDALONE_NOTE : 'Explore modules for your instruments.'}

{total} modules
{device && projectMachineForDevice(device.id) &&

} {phone ? resultsSlot && createPortal(, resultsSlot) : } {hasMods && (term || libraryFamily !== 'all') &&

Filtered by diff --git a/src/devices/library-parity.test.ts b/src/devices/library-parity.test.ts index ccc5864d98..415ec28e6e 100644 --- a/src/devices/library-parity.test.ts +++ b/src/devices/library-parity.test.ts @@ -16,9 +16,9 @@ const noop = () => {} // The all-machines library is the machine library without a device; a Digi library is the same view with that machine's selection. const AllMachinesLibrary = MachineLibrary type DigiDevice = NonNullable[0]['device']> & { id: DigiMod['device'] } -type DigiProps = { device: DigiDevice; selectedIds: string[]; onToggle: (id: string) => void } & Omit[0], 'device' | 'octatrackModules' | 'octatrackSelected' | 'onToggleOctatrack' | 'digiSelected' | 'onToggleDigi' | 'octatrackConflicts' | 'viewedModuleVersions' | 'moduleBaseline'> +type DigiProps = { device: DigiDevice; selectedIds: string[]; onToggle: (id: string) => void } & Omit[0], 'device' | 'octatrackModules' | 'octatrackSelected' | 'onToggleOctatrack' | 'digiSelected' | 'onToggleDigi' | 'viewedModuleVersions' | 'moduleBaseline'> function DigiLibrary({ device, selectedIds, onToggle, ...rest }: DigiProps) { - return createElement(MachineLibrary, { ...rest, device, octatrackModules: [], octatrackSelected: [], onToggleOctatrack: noop, digiSelected: { digitakt: device.id === 'digitakt' ? selectedIds : [], 'digitakt-ii': device.id === 'digitakt-ii' ? selectedIds : [], digitone: device.id === 'digitone' ? selectedIds : [], 'analog-rytm-mkii': device.id === 'analog-rytm-mkii' ? selectedIds : [] }, onToggleDigi: (_: string, id: string) => onToggle(id), octatrackConflicts: [], viewedModuleVersions: {}, moduleBaseline: null }) + return createElement(MachineLibrary, { ...rest, device, octatrackModules: [], octatrackSelected: [], onToggleOctatrack: noop, digiSelected: { digitakt: device.id === 'digitakt' ? selectedIds : [], 'digitakt-ii': device.id === 'digitakt-ii' ? selectedIds : [], digitone: device.id === 'digitone' ? selectedIds : [], 'analog-rytm-mkii': device.id === 'analog-rytm-mkii' ? selectedIds : [] }, onToggleDigi: (_: string, id: string) => onToggle(id), viewedModuleVersions: {}, moduleBaseline: null }) } // Likes and downloads show the number beside an icon; the word is there for screen readers only. const count = (value: string, word: string) => value + ' ' + word + '' @@ -27,7 +27,7 @@ const props = { onToggleOctatrack: noop, digiSelected: { digitakt: [], 'digitakt-ii': [], digitone: [], 'analog-rytm-mkii': [] }, onToggleDigi: noop, family: 'all', onFamilyChange: noop, sort: 'collection', onSortChange: noop, statistics: [{module_id: 'miniverb', average: 4.5, count: 2, likes: 7, downloads: 12, worksReports: 5, downloadsStarted: null}], - octatrackConflicts: [], comparison: ['miniverb'], onCompare: noop, onOpenComparison: noop, + comparison: ['miniverb'], onCompare: noop, onOpenComparison: noop, viewedModuleVersions: {}, moduleBaseline: AVAILABLE_MODULES.map(module=>module.id), } diff --git a/src/styles.css b/src/styles.css index 57a11b2c98..94f5978a0b 100644 --- a/src/styles.css +++ b/src/styles.css @@ -121,7 +121,7 @@ h2 { font-size: 16px; letter-spacing: -.15px; font-weight: 600; } .support-link { display: inline-flex; align-items: center; gap: 6px; min-height: 32px; padding: 0; border: 0; background: none; color: var(--muted); font-size: 12px; } .support-link:hover { color: var(--text-secondary); text-decoration: underline; text-underline-offset: 3px; } .support-heart { display: inline-flex; flex-shrink: 0; color: #c58a9c; } -.workspace { min-width: 0; min-height: 0; overflow: hidden; overflow: clip; display: grid; grid-template-rows: 64px minmax(0, 1fr) 36px; } +.workspace { min-width: 0; min-height: 0; overflow: hidden; overflow: clip; display: grid; grid-template-rows: 64px minmax(0, 1fr) minmax(36px, auto); } .app-toolbar { display: flex; align-items: center; gap: 20px; background: var(--sidebar); border-bottom: 1px solid var(--line); padding: 0 27px; box-shadow: 0 1px 8px #00000010; } .toolbar-actions { display: contents; } .toolbar-title { display: flex; align-items: center; gap: 9px; flex: 0 1 auto; min-width: 0; color: #c2c2ce; font-size: 13px; white-space: nowrap; } @@ -1248,26 +1248,22 @@ h1 { font-size: 28px; } } } -.selection-warning { position: fixed; z-index: 35; right: 22px; bottom: 54px; } -.selection-warning-toggle { display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 10px 15px; border: 1px solid #94704a; border-radius: 24px; background: #382d23; color: #f0c792; box-shadow: 0 5px 24px #0006; font-size: 13px; font-weight: 600; cursor: pointer; } -.selection-warning-toggle:hover, .selection-warning-toggle[aria-expanded="true"] { background: #463629; } -.selection-warning-toggle:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } -.selection-warning-panel { position: absolute; right: 0; bottom: calc(100% + 10px); width: min(360px, calc(100vw - 32px)); max-height: min(420px, calc(100dvh - 220px)); display: flex; flex-direction: column; border: 1px solid #715235; border-radius: 12px; background: #2d2721; color: #f0c792; box-shadow: 0 12px 40px #0008; overflow: hidden; } -.selection-warning-panel[hidden] { display: none; } -.selection-warning-panel > header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 14px; border-bottom: 1px solid #715235; } -.selection-warning-panel h2 { font-size: 14px; } -.selection-warning-panel .icon-button { flex-shrink: 0; min-width: 36px; min-height: 36px; } -.selection-warning-list { overflow-y: auto; scrollbar-width: thin; } -.selection-warning-list > a { display: grid; gap: 8px; padding: 16px; } -.selection-warning-list > a + a { border-top: 1px solid #715235; } -.selection-warning-list > a:hover, .selection-warning-list > a:focus-visible { background: #382d23; } -.selection-warning-list strong { font-size: 13px; line-height: 1.5; } -.selection-warning-list span { color: #d0bca4; font-size: 12px; line-height: 1.6; } -.selection-warning-list small { display: flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 600; } -.library-page:has(.selection-warning) { padding-bottom: 56px; } +.library-selection { margin: 14px 0 6px; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); font-size: .8125rem; line-height: 1.45; } +.library-selection :is(h2, summary) { margin: 0; padding: 8px 10px; color: var(--text); font-size: .875rem; font-weight: 600; } +.library-selection-list { max-height: min(32dvh, 280px); overflow-y: auto; scrollbar-width: thin; } +.library-selection-device { padding: 6px 10px 10px; border-top: 1px solid var(--line); overflow-wrap: anywhere; } +.library-selection-device > a { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-height: 32px; color: var(--accent); } +.library-selection-device > a:hover strong { text-decoration: underline; } +.library-selection-device > a svg { flex-shrink: 0; } +.library-selection-device small { display: block; color: var(--muted); font-size: inherit; } +.library-selection-device p, .library-selection-device ul { margin: 6px 0 0; color: var(--text-secondary); } +.library-selection-device ul { padding-inline-start: 17px; color: #f0c792; } +.library-selection-device li + li { margin-top: 4px; } @media (max-width: 600px) { - .selection-warning { right: 16px; bottom: calc(72px + env(safe-area-inset-bottom)); } - .selection-warning-panel .icon-button { min-width: 44px; min-height: 44px; } + .library-selection { margin: 0 16px 8px; } + .library-selection summary { min-height: 44px; padding-block: 11px; cursor: pointer; } + .library-selection summary > span { margin-inline-start: 8px; color: #f0c792; } + .library-selection-device > a { min-height: 44px; } } .firmware-help { margin-top: 16px; font-size: 12px; line-height: 1.7; } @@ -1973,6 +1969,29 @@ button.signal-tile[aria-pressed="true"] > svg { fill: currentColor; } .configuration-launcher .configuration-recent:not(:disabled):hover { background: #929bff20; } .configuration-recent span, .configuration-recent small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .configuration-recent small { margin-top: 3px; color: var(--muted); font-size: 11px; } +@media (min-width: 601px) { + .sidebar-nav a, .configuration-launcher .configuration-browse { font-size: .9375rem; } + .sidebar-nav a svg, .sidebar-nav small { flex-shrink: 0; } + .sidebar-section-label { font-size: .8125rem; } + .configuration-launcher .configuration-recent, .toolbar-title, .configuration-button, + .discovery-tools select, .discovery-tools .sidebar-device, .discovery-tools .discovery-actions .button, + .status-bar > a { font-size: .875rem; } + .discovery-tools label, .status-bar .legal-links { font-size: .8125rem; } + .status-bar { flex-wrap: wrap; gap: 0 12px; padding-block: 3px; } + .status-bar > a { min-height: 28px; } +} +/* Leave room for footer links when the desktop workspace narrows or the browser is zoomed. */ +@media (min-width: 601px) and (max-width: 1240px) { + .app-shell { --footer-float-bottom: 76px; } + .app-shell :is(.octatrack-float, .live-use-notice, .public-announcement, .forum-chat-launcher, .forum-shoutbox.is-floating) { bottom: var(--footer-float-bottom); } +} +@media (min-width: 601px) and (max-width: 820px) { + .app-shell { --footer-float-bottom: 92px; } + .status-bar { padding-inline: 12px; } + .status-bar .legal-links { flex-basis: 100%; gap: 0 10px; } + .status-bar .legal-links a { min-height: 22px; } + .status-bar > a { min-height: 24px; } +} .configuration-browser { width: min(640px, calc(100% - 32px)); max-height: min(720px, calc(100dvh - 32px)); padding: 20px; overflow: hidden; } .configuration-browser[open] { display: flex; flex-direction: column; } .configuration-browser.your-module-sets { width: auto; max-height: none; height: auto; padding: 23px; overflow: visible; } From aca90e7109c631c47c15c7fe804d69b8d894ff14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jannik=20A=C3=9Ffalg?= <67785539+repeat98@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:47:32 +0100 Subject: [PATCH 06/11] Octatrack base: a rolled-back trial that removed Analog BD binds it again (#1736) A trial that took a trusted controller out (Analog BD, Sidechain, Output Matrix) let the controller board release its slot one tick after the switch: roots_clear asked only the volatile journal, which is off, so a pending trial did not count. The rollback brought the module back with the same owner generation, which the board neither rebinds (slot_of matched the released slot, and a bind refuses an old generation) nor advances, so its engine was never placed again until a power cycle (a tester's MKII, 18 November 2026). The loader now answers modwerk_runtime_restorable(generation): an open transaction can still put that owner back (the trial's replaced module, a journal or set row's before). The board keeps such a slot RETIRING instead of releasing it, without wanting its engine, so the trial still gets the room; a rollback republishes it and the existing restore branch binds it again; a Keep releases it as before. Host test: test_resident_engines_board modes 67 (single-module trial) and 68 (the whole-set trial `device -- set` sends, in a build with the set backend). Both failed before the change with the slot released mid-trial. Co-Authored-By: Claude Opus 5.5 --- .../controller-policy/controller_board.c | 12 +- sdk/runtime/loader/journal.h | 4 + sdk/runtime/loader/loader.c | 15 +++ sdk/tests/test_resident_engines_board.py | 106 +++++++++++++++++- 4 files changed, 127 insertions(+), 10 deletions(-) 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/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).""" From b9dd2150e087df0f3b75bf1bb2bd000a6f591939 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jannik=20A=C3=9Ffalg?= <67785539+repeat98@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:01:38 +0100 Subject: [PATCH 07/11] Fix: diagnostics name the check behind a refused restore Base 0.7.10's set record also carries the loader's check that refused the package (dsp1). The pull names it, and calls a module-memory refusal by the claims check what it is: the module's DSP claims meeting a delay buffer, not the module memory itself. The invitation and the privacy page (German and English) say the log carries the check as well as the memory in use. Co-Authored-By: Claude Opus 5.5 --- changelog/2026-11-19-diagnostics-refused-pool.md | 2 +- scripts/diagnostics-pull.mjs | 10 +++++++--- scripts/diagnostics-pull.test.mjs | 8 +++++--- src/community/PrivacyPage.tsx | 2 +- src/components/DiagnosticsInvitation.tsx | 2 +- 5 files changed, 15 insertions(+), 9 deletions(-) diff --git a/changelog/2026-11-19-diagnostics-refused-pool.md b/changelog/2026-11-19-diagnostics-refused-pool.md index 538c9e8c9f..9675b8d5f2 100755 --- a/changelog/2026-11-19-diagnostics-refused-pool.md +++ b/changelog/2026-11-19-diagnostics-refused-pool.md @@ -1 +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 and how much module memory was in use then (base 0.7.10 and later), and the owner's diagnostics pull shows that memory beside the refused module. +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/scripts/diagnostics-pull.mjs b/scripts/diagnostics-pull.mjs index f4989533fb..6f7268d928 100644 --- a/scripts/diagnostics-pull.mjs +++ b/scripts/diagnostics-pull.mjs @@ -53,9 +53,13 @@ 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: the module pool when it was refused, in 16-byte units (diag.c: cpu the - * bytes used, dsp0 the largest free run; the site reads dsp0 as dsp5to8). Older bases leave both 0. */ -const refusedPool = r => r.cpu || r.dsp5to8 ? `, module memory ${Math.round(r.cpu / 64)} KiB used, largest free block ${(r.dsp5to8 / 64).toFixed(1)} KiB` : '' +/** 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}${refusedPool(r)})` : '') : '') + diff --git a/scripts/diagnostics-pull.test.mjs b/scripts/diagnostics-pull.test.mjs index ffb9184976..01c7297299 100644 --- a/scripts/diagnostics-pull.test.mjs +++ b/scripts/diagnostics-pull.test.mjs @@ -111,9 +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 module pool at the refusal, in 16-byte units: 760 KiB used, a 1.5 KiB largest free block. - expect(unitLines([{ ...set, tempo24: 2, cpu: 48640, dsp5to8: 96 }])[0]) - .toContain('refused SC Ringmod (module memory, module memory 760 KiB used, largest free block 1.5 KiB)') + // 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/src/community/PrivacyPage.tsx b/src/community/PrivacyPage.tsx index 11687174d8..c2046917f1 100644 --- a/src/community/PrivacyPage.tsx +++ b/src/community/PrivacyPage.tsx @@ -20,7 +20,7 @@ export function PrivacyPage() {

{de?'6. Freiwillige Zählung eindeutiger Besucher':'6. Optional unique-visitor counts'}

{de?'Die Zählung eindeutiger Besucher ist standardmäßig aus. Erst nach Ihrer Einwilligung speichern wir eine täglich wechselnde Zufallskennung, lokale Zählmarker für begonnene Konfigurationen und Ihre datierte Einwilligung. Wir zählen Seitenaufrufe, begonnene Konfigurationen, erfolgreiche und fehlgeschlagene Builds, Exporte, angeforderte Firmware-Downloads, Öffnungen des Unterstützungsdialogs und Klicks auf den Ko-fi-Link, bei Builds und Downloads mit dem Gerät (Octatrack, Digitakt oder Digitone). Jeder enthaltene Modulbezeichner wird einzeln für eine öffentliche Gesamtsumme gemeldet. Dies dient der Einschätzung, welche Funktionen und Module genutzt werden.':'Unique-visitor counts are off by default. Only after consent do we store a daily random identifier, local markers for configurations already counted, and your dated consent choice. We count page views, configurations started, successful and failed builds, exports, requested firmware downloads, support dialog opens and Ko-fi link clicks, with the machine (Octatrack, Digitakt or Digitone) for builds and downloads. Included module IDs are reported individually to public module totals. This helps us understand which features and modules people use.'}

{de?'Seitenaufrufe enthalten einen festgelegten Seitennamen oder eine öffentliche Katalog-Modulkennung. Diskussionen, Profile, Nachrichten und Kontoseiten werden ohne Thread-IDs, Nutzernamen oder Tokens zusammengefasst. Wir speichern nur Tagessummen je Seite für 90 Tage, ohne Seiten mit Besuchern oder Konten zu verknüpfen. Die Ereignisse enthalten keine Firmware, Dateinamen, E-Mail-Adressen, Konfigurationsnamen, vollständigen URLs oder Abfrageparameter. Verbindungsdaten fallen bei Cloudflare an; kurzlebige gehashte Kennungen ermöglichen Zählung und Missbrauchsschutz. Diese Verarbeitung beginnt daher nicht als vollständig anonyme Verarbeitung. Tages-Gesamtsummen werden 90 Tage und Stunden-Gesamtsummen 14 Tage aufbewahrt; Ereignismarker bis zur stündlichen Bereinigung, höchstens etwa 48 Stunden. Nicht personenbezogene Modul-Gesamtsummen bleiben bestehen. Die Einwilligung gilt bis zum Widerruf, einer Zweckänderung oder höchstens 180 Tage.':'Page views include a fixed page name or public catalog module ID. Discussions, profiles, messages and account screens are grouped, without thread IDs, usernames or tokens. We keep only daily totals per page for 90 days, without linking pages to visitors or accounts. Events contain no firmware, file names, emails, configuration names, raw URLs or query strings. Cloudflare receives connection data; short-lived hashed identifiers support counts and abuse prevention. The initial processing is therefore not fully anonymous. Daily totals are kept for 90 days and hourly totals for 14 days; event markers until hourly cleanup, at most about 48 hours. Non-personal aggregate module totals remain. Consent lasts until withdrawal, a purpose change or at most 180 days.'}

{de?'Rechtsgrundlagen sind Ihre Einwilligung nach Art. 6 Abs. 1 lit. a DSGVO und § 25 Abs. 1 TDDDG. Sie können hier jederzeit ebenso einfach widerrufen. Widerruf beendet weitere Zählung mit Kennung und entfernt lokale Zählkennungen (anonyme Gesamtzählung läuft weiter, sofern Sie oben nicht widersprechen); die Rechtmäßigkeit früherer Verarbeitung bleibt unberührt. Bereits nicht personenbezogene Gesamtsummen lassen sich nicht Ihrem Konto zuordnen. Ihre Entscheidung beeinflusst die Nutzung des Dienstes nicht.':'The bases are your consent under Article 6(1)(a) GDPR and § 25(1) TDDDG. Withdraw here just as easily at any time. Withdrawal stops future counts with identifiers and removes local counting identifiers (anonymous totals continue unless you object above); it does not affect the lawfulness of prior processing. Non-personal totals already produced cannot be linked back to your account. Your choice does not affect access to the service.'}

{browserPrivacy&&

{de?'Ihr Browser fordert Datenschutz an; Nutzungszählung bleibt aus.':'Your browser requests privacy, so usage counts stay off.'}

}{!enabled&&!browserPrivacy&&

{de?'Nutzungszählung ist auf diesem Gerät aus.':'Usage counts are off on this device.'}

}{error&&

{error}

}

{de?'Freiwillige technische Diagnoseberichte':'Optional technical diagnostics'}

{de?'Stand dieses Abschnitts: 11. November 2026. Verifizierte Mitglieder und Besucher ohne Konto können Diagnoseberichte ausdrücklich aktivieren, um Fehler zu untersuchen. Die Einwilligung ist freiwillig (Art. 6 Abs. 1 lit. a DSGVO), gilt für angemeldete Sitzungen, ohne Konto für diesen Browser, für 90 Tage und ist unabhängig von Beta-Zugang und Nutzungszählung. Ohne Einwilligung funktionieren Builds und USB-Sync unverändert.':'This section was updated on 11 November 2026. Verified members and visitors without an account can explicitly enable technical reports to help investigate failures. Consent is optional (Article 6(1)(a) GDPR), applies to signed-in sessions, or without an account to this browser, for 90 days and is separate from beta access and usage counts. Builds and USB sync work the same without consent.'}

-

{de?'Browserfehler enthalten nur den Fehlertyp und den geöffneten Bereich der Website als feste Kategorien; Build-Fehler enthalten Build-Typ, Phase und Fehlerkategorie. Bei Octatrack-USB-Sync können außerdem Basis-, Set- und Paket-Hashes, Paketgrößen, Modul-IDs und Katalogversionen, Verbindungs- und Sync-Ereignisse, Selbsttestergebnisse, numerische Lastwerte und Ablehnungscodes erfasst werden. Ein fehlgeschlagener Sync nennt den Schritt, bei dem er abbrach, und den Fehlertyp, beides als feste Kategorien; blieb dabei eine Übertragung unbestätigt, außerdem sechs USB-Zähler des Octatrack über diesen Sync (empfangene und abgelehnte Übertragungen, USB-Resets, begonnene, abgeschlossene und abgebrochene Datenphasen).Schlägt die Verbindung zum Octatrack fehl, bevor sie besteht, nennt der Bericht den Grund als eine von wenigen festen Kategorien (kein WebUSB im Browser, kein Octatrack ausgewählt, Zugriff verweigert, konnte nicht geöffnet werden, von einer anderen App belegt). Solange der Octatrack verbunden ist, werden CPU- und DSP-Last alle 30 Sekunden gelesen und alle 5 Minuten übertragen, außerdem vor und nach einem Sync, beim Trennen der Verbindung oder Schließen der Seite, sofort bei über 90 % CPU-Last und wenn der Octatrack nicht mehr antwortet. Der Octatrack führt außerdem ein eigenes kleines Protokoll, auch während die Website geschlossen ist: Last und ob er spielte, Überlastungen, Hänger und Abstürze, ein Modul, das er beim Start nicht laden konnte, mit dem dabei belegten Modulspeicher, und in einem solchen Moment für jede Spur Maschinentyp und Effekte, ob er spielte, das Tempo, den geöffneten Bildschirm und die letzten 16 gedrückten Tasten. Die Website überträgt dieses Protokoll bei der nächsten Verbindung. Außer diesem Protokoll nennt jeder Bericht den Browser mit seiner Hauptversion und das Betriebssystem als Familie, etwa Chrome 131 unter Windows, nie die vollständige Browserkennung (User-Agent). Es werden keine Firmware, Samples, Audiodaten, Projekt-, Sample- oder Set-Namen, sonstigen Projektinhalte, Seriennummern, Fehlermeldungstexte, Stacktraces, Dateinamen, Seitenadressen, Speicher- oder Crash-Dumps übertragen.':'Browser failures contain only the error type and the part of the site that was open, as fixed categories; build failures contain the build type, stage and error category. Octatrack USB reports can also include base, set and package hashes, package sizes, module IDs and catalogue versions, connection and sync events, self-test results, numeric load readings and refusal codes. A sync that fails names the step it stopped at and the error type, both as fixed categories; one that stopped on an unconfirmed transfer also carries six of the Octatrack’s USB counts over that sync (transfers received and refused, USB resets, data stages started, completed and abandoned).If connecting to the Octatrack fails before a connection exists, the report names the reason as one of a few fixed categories (no WebUSB in the browser, no Octatrack chosen, access denied, could not be opened, in use by another app). While the Octatrack is connected, its CPU and DSP load are read every 30 seconds and sent every 5 minutes, before and after a sync, when it disconnects or the page closes, at once above 90 % CPU and when the Octatrack stops answering. The Octatrack also keeps a small log of its own, also while the site is closed: its load and whether it was playing, overloads, freezes and crashes, a module it couldn’t load at start with how much module memory was in use, and at such a moment each track’s machine type and effects, playing or stopped, the tempo, the screen that was open and the last 16 keys pressed. The site sends that log at the next connection. Every report except that log names the browser with its main version and the operating system as families, such as Chrome 131 on Windows, never the full browser identification (user agent). Reports contain no firmware, samples, audio, project, sample or set names, other project contents, serial numbers, error messages, stack traces, filenames, page addresses, memory or crash dumps.'}

+

{de?'Browserfehler enthalten nur den Fehlertyp und den geöffneten Bereich der Website als feste Kategorien; Build-Fehler enthalten Build-Typ, Phase und Fehlerkategorie. Bei Octatrack-USB-Sync können außerdem Basis-, Set- und Paket-Hashes, Paketgrößen, Modul-IDs und Katalogversionen, Verbindungs- und Sync-Ereignisse, Selbsttestergebnisse, numerische Lastwerte und Ablehnungscodes erfasst werden. Ein fehlgeschlagener Sync nennt den Schritt, bei dem er abbrach, und den Fehlertyp, beides als feste Kategorien; blieb dabei eine Übertragung unbestätigt, außerdem sechs USB-Zähler des Octatrack über diesen Sync (empfangene und abgelehnte Übertragungen, USB-Resets, begonnene, abgeschlossene und abgebrochene Datenphasen).Schlägt die Verbindung zum Octatrack fehl, bevor sie besteht, nennt der Bericht den Grund als eine von wenigen festen Kategorien (kein WebUSB im Browser, kein Octatrack ausgewählt, Zugriff verweigert, konnte nicht geöffnet werden, von einer anderen App belegt). Solange der Octatrack verbunden ist, werden CPU- und DSP-Last alle 30 Sekunden gelesen und alle 5 Minuten übertragen, außerdem vor und nach einem Sync, beim Trennen der Verbindung oder Schließen der Seite, sofort bei über 90 % CPU-Last und wenn der Octatrack nicht mehr antwortet. Der Octatrack führt außerdem ein eigenes kleines Protokoll, auch während die Website geschlossen ist: Last und ob er spielte, Überlastungen, Hänger und Abstürze, ein Modul, das er beim Start nicht laden konnte, mit der ablehnenden Prüfung und dem dabei belegten Modulspeicher, und in einem solchen Moment für jede Spur Maschinentyp und Effekte, ob er spielte, das Tempo, den geöffneten Bildschirm und die letzten 16 gedrückten Tasten. Die Website überträgt dieses Protokoll bei der nächsten Verbindung. Außer diesem Protokoll nennt jeder Bericht den Browser mit seiner Hauptversion und das Betriebssystem als Familie, etwa Chrome 131 unter Windows, nie die vollständige Browserkennung (User-Agent). Es werden keine Firmware, Samples, Audiodaten, Projekt-, Sample- oder Set-Namen, sonstigen Projektinhalte, Seriennummern, Fehlermeldungstexte, Stacktraces, Dateinamen, Seitenadressen, Speicher- oder Crash-Dumps übertragen.':'Browser failures contain only the error type and the part of the site that was open, as fixed categories; build failures contain the build type, stage and error category. Octatrack USB reports can also include base, set and package hashes, package sizes, module IDs and catalogue versions, connection and sync events, self-test results, numeric load readings and refusal codes. A sync that fails names the step it stopped at and the error type, both as fixed categories; one that stopped on an unconfirmed transfer also carries six of the Octatrack’s USB counts over that sync (transfers received and refused, USB resets, data stages started, completed and abandoned).If connecting to the Octatrack fails before a connection exists, the report names the reason as one of a few fixed categories (no WebUSB in the browser, no Octatrack chosen, access denied, could not be opened, in use by another app). While the Octatrack is connected, its CPU and DSP load are read every 30 seconds and sent every 5 minutes, before and after a sync, when it disconnects or the page closes, at once above 90 % CPU and when the Octatrack stops answering. The Octatrack also keeps a small log of its own, also while the site is closed: its load and whether it was playing, overloads, freezes and crashes, a module it couldn’t load at start with the check that refused it and how much module memory was in use, and at such a moment each track’s machine type and effects, playing or stopped, the tempo, the screen that was open and the last 16 keys pressed. The site sends that log at the next connection. Every report except that log names the browser with its main version and the operating system as families, such as Chrome 131 on Windows, never the full browser identification (user agent). Reports contain no firmware, samples, audio, project, sample or set names, other project contents, serial numbers, error messages, stack traces, filenames, page addresses, memory or crash dumps.'}

{de?'Die Berichte werden über unseren Cloudflare-Dienst verarbeitet, Ihrem Konto zugeordnet und sind nur für Sie und Website-Administratoren sichtbar. Sie werden nicht an GitHub oder Modulautoren weitergegeben. Der Betreiber kann sie mit einem KI-Assistenten (Claude von Anthropic) auswerten; dafür werden sie an Anthropic übermittelt. Maximal 1.000 Berichte pro Konto sind für 30 Tage verfügbar; abgelaufene Daten werden stündlich gelöscht. Unter „Your Octatrack“ → Diagnostics können Sie jederzeit die Freigabe beenden und die Berichte löschen. Sie sind im Kontoexport enthalten und werden bei Kontolöschung entfernt. Ohne Konto werden die Berichte keinem Konto zugeordnet, sondern einer zufälligen Kennung, die Ihr Browser erst bei Ihrer Zustimmung erzeugt und nur lokal speichert; der Server speichert nur deren Hashwert, höchstens 1.000 Berichte für 30 Tage, und nur Website-Administratoren können sie lesen. Beenden Sie die Freigabe in diesem Browser, werden die Berichte und die Kennung gelöscht; löschen Sie vorher die Website-Daten des Browsers, lassen sich die Berichte nicht mehr zuordnen und verfallen nach 30 Tagen. Browser-Datenschutzsignale stoppen die Erfassung in diesem Browser. Ob Sie die Einladung geschlossen haben, wird lokal für Ihr Konto und diese Einwilligungsversion gespeichert. Wer nicht teilt, kann nach einem fehlgeschlagenen Sync, Selbsttest oder Basis-Update, wenn der Ton des Octatrack stehen bleibt oder er seine vorherige Basis gestartet hat, noch einmal gefragt werden; „Not now“ wird dort lokal für Ihr Konto 30 Tage lang gespeichert.':'Reports use our Cloudflare service, are linked to your account and are visible only to you and site administrators. They are not sent to GitHub or module authors. The operator may analyse them with an AI assistant (Anthropic’s Claude); for that, they are sent to Anthropic. Up to 1,000 reports per account are available for 30 days; expired records are removed by hourly cleanup. Stop sharing and delete reports at any time under Diagnostics in Your Octatrack. Reports are included in your account export and removed on account deletion. Without an account, reports are not linked to an account but to a random ID that your browser creates only when you agree and keeps locally; the server stores only its hash, at most 1,000 reports for 30 days, and only site administrators can read them. Stopping sharing in that browser deletes the reports and the ID; if you clear the browser’s site data first, the reports can no longer be matched to you and expire after 30 days. Browser privacy signals stop collection in that browser. Dismissing the invitation is remembered locally for your account and this consent version. A member who does not share may be asked once more after a failed sync, self-test or base update, when the Octatrack’s audio stops or when it started its previous base; Not now there is remembered locally for your account for 30 days.'}

{de?'7. Aufbewahrung und Löschung':'7. Retention and removal'}

{de?'Verifizierungslinks gelten 24 Stunden, Wiederherstellungslinks 30 Minuten und jeweils einmal. Abgelaufene Sitzungen, Links und Missbrauchsmarker werden stündlich bereinigt. Missbrauchsmarker können je nach Begrenzung bis zu 30 Tage gelten. Konten und notwendige Kontodaten bleiben während Ihrer Teilnahme gespeichert. Beiträge bleiben verfügbar, solange sie für die Diskussion und Zuordnung von Beiträgen benötigt werden; personenbezogene Inhalte werden auf Anfrage geprüft und entfernt, sofern keine Rechtsgrundlage für ihre Aufbewahrung besteht.':'Verification links last 24 hours and recovery links 30 minutes, each for one use. Expired sessions, action links and abuse markers are cleaned hourly. Abuse markers may last up to 30 days depending on the limit. Accounts and necessary account data remain during your participation. Contributions remain while needed for discussion and attribution; personal content is reviewed for removal on request unless there is a lawful retention reason.'}

{de?'Private Fehlerberichte, Benachrichtigungen, Meldungen und Korrespondenz werden bis zur Erledigung und einer notwendigen Nachbearbeitung aufbewahrt; der Betreiber prüft die Erforderlichkeit regelmäßig. Es gibt derzeit keine automatische Löschfrist für diese Inhalte oder unverifizierte Konten. Löschanfragen führen zu einer individuellen Prüfung. Gesetzlich erforderliche Aufbewahrung oder die Verteidigung von Rechtsansprüchen wird begründet und auf notwendige Daten beschränkt.':'Private issue reports, notifications, notices and correspondence remain until resolved and any necessary follow-up is complete; the operator reviews continued necessity regularly. There is currently no automatic deletion period for this content or unverified accounts. Removal requests receive an individual assessment. Retention required by law or to defend legal claims is explained and limited to the necessary data.'}

{de?'Provider-Sicherheitslogs und Wiederherstellungskopien unterliegen zusätzlich den Einstellungen und Fristen der Anbieter. Verschlüsselte Sicherungen sind nur dem Betreiber zugänglich, werden ausschließlich zur Wiederherstellung verwendet und nach der festgelegten Sicherungsrotation entfernt. Bei einer Wiederherstellung müssen bereits bewilligte Löschungen erneut angewendet werden. Fragen Sie den Verantwortlichen nach den für Ihre Daten geltenden Provider- und Sicherungsfristen.':'Provider security logs and recovery copies also follow provider settings and retention. Encrypted backups are restricted to the operator, used only for recovery and removed under the chosen backup rotation. Approved removals must be reapplied after a restore. Ask the controller for the provider and backup periods applicable to your data.'}

diff --git a/src/components/DiagnosticsInvitation.tsx b/src/components/DiagnosticsInvitation.tsx index ca8bb9e2e3..8cb8f4984d 100644 --- a/src/components/DiagnosticsInvitation.tsx +++ b/src/components/DiagnosticsInvitation.tsx @@ -14,7 +14,7 @@ export function DiagnosticDetails() {

Browser failures are recorded as the type of error and the part of the site that was open. Build failures include the type of build (for a Digitakt, Digitone or Rytm build, which machine it was for) and the stage that failed. No error messages, stack traces, file names or page addresses are sent.

When you use Octatrack USB sync, reports can also include base and running-set hashes, package hashes and sizes, module IDs with this site’s catalogue versions, connection and sync events, self-test results, load readings and refusal codes. An older installed module may have a different version. While your Octatrack is connected, its CPU and DSP load are read every 30 seconds and sent every 5 minutes, before and after a sync, when it disconnects or you close the page, at once when the CPU goes above 90 %, and when the Octatrack stops answering.

If connecting to your Octatrack fails, the report says why, as one of a few fixed reasons: this browser has no WebUSB, no Octatrack was chosen, access was denied, it couldn’t be opened, or another app was using it.

-

The Octatrack also keeps a small log of its own, also while this site is closed: its load and whether it was playing, overloads, freezes and crashes, a module it couldn’t load at start with how much module memory was in use, and at such a moment each track’s machine type and effects, playing or stopped, the tempo, the screen that was open and the last 16 keys pressed. The site sends that log the next time you connect.

+

The Octatrack also keeps a small log of its own, also while this site is closed: its load and whether it was playing, overloads, freezes and crashes, a module it couldn’t load at start with the check that refused it and how much module memory was in use, and at such a moment each track’s machine type and effects, playing or stopped, the tempo, the screen that was open and the last 16 keys pressed. The site sends that log the next time you connect.

Every report except that log also names your browser with its main version and your operating system, such as Chrome 131 on Windows, never the full browser identification.

No firmware, samples, audio, project, sample or set names, device serial numbers, raw memory or crash dumps. Reports use Modwerk’s Cloudflare service and aren’t posted to GitHub or shared with module authors. I may have an AI assistant (Anthropic’s Claude) help me read them; for that, they are sent to Anthropic.

Consent is optional under GDPR Article 6(1)(a). You can stop sharing and delete reports under Diagnostics in Your Octatrack. Signed in, your account data download includes them; without an account they are kept under a random ID stored in this browser. Reports are hidden after 30 days and deleted by hourly cleanup, with at most 1,000 entries per account or browser. Privacy and your rights.

From fdb23316096cbbbd291cfaaf40e3ed7fea91bb45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jannik=20A=C3=9Ffalg?= <67785539+repeat98@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:50:17 +0100 Subject: [PATCH 08/11] Implement device-scoped first-release reviews and contribution roles --- .agents/skills/modwerk-contribute/SKILL.md | 4 +- .agents/skills/modwerk-new-module/SKILL.md | 2 +- .agents/skills/modwerk-review-prs/SKILL.md | 4 +- .claude/skills/modwerk-contribute/SKILL.md | 4 +- .claude/skills/modwerk-new-module/SKILL.md | 2 +- .claude/skills/modwerk-review-prs/SKILL.md | 4 +- .github/pull_request_template.md | 2 +- .github/workflows/review-merge.yml | 33 ++++++ AGENTS.md | 4 +- changelog/2026-11-19-device-reviewer-roles.md | 1 + docs/ADD_A_MODULE.md | 9 +- docs/DEVELOPER_WORKFLOW.md | 10 +- docs/MAINTENANCE.md | 2 +- docs/MAINTENANCE_BOT.md | 2 +- docs/MODULE_AUTHOR_UPDATES.md | 6 +- scripts/author-update-git.test.mjs | 11 ++ scripts/maintenance-bot/act.mjs | 4 +- scripts/maintenance-bot/first-release.mjs | 112 ++++++++++++++++++ scripts/maintenance-bot/lib.mjs | 2 + scripts/maintenance-bot/review-merge.mjs | 81 +++++++++++++ scripts/maintenance-bot/review-merge.test.mjs | 108 +++++++++++++++++ scripts/pr-ready.mjs | 2 +- scripts/pr-ready.test.mjs | 4 +- scripts/release-approval.mjs | 13 +- server/api.ts | 2 +- server/contribution-roles.ts | 54 +++++++++ server/forum.ts | 13 +- server/maintenance-bot.ts | 58 ++++++++- server/member-roles.ts | 2 +- server/recognition.ts | 14 ++- src/community/AccountMenu.test.ts | 4 +- src/community/AccountMenu.tsx | 2 +- src/community/ForumIdentity.tsx | 17 ++- src/community/ForumProfile.tsx | 2 +- src/community/ForumThreadView.tsx | 2 +- src/community/MemberRolesAdmin.tsx | 6 +- src/community/beta-access.test.ts | 4 +- src/community/developer-guidance.ts | 2 +- src/community/forum-contract.ts | 6 +- src/community/maintenance-bot.test.ts | 23 ++++ src/community/member-roles.test.ts | 5 + src/community/member-standing.ts | 10 +- src/community/starter-prompts.test.ts | 6 +- src/devices/machine-contract.test.ts | 4 + src/devices/machine-contract.ts | 9 +- src/engine/elekloader/module-set.test.ts | 4 +- src/release/author-updates.ts | 3 +- 47 files changed, 608 insertions(+), 70 deletions(-) create mode 100644 .github/workflows/review-merge.yml create mode 100644 changelog/2026-11-19-device-reviewer-roles.md create mode 100644 scripts/maintenance-bot/first-release.mjs create mode 100644 scripts/maintenance-bot/review-merge.mjs create mode 100644 scripts/maintenance-bot/review-merge.test.mjs create mode 100644 server/contribution-roles.ts 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-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-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/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/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/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/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/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/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 480b132240..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).') 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/server/api.ts b/server/api.ts index 37b7ad4250..bc7f720032 100644 --- a/server/api.ts +++ b/server/api.ts @@ -130,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/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/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&&