Max dsp agent

From taylorbrook/MAX-MSP_CC_Framework · View interactive version

Max dsp agent is an AI agent skill from the GitHub repository taylorbrook/MAX-MSP_CC_Framework. Generate Gen~ GenExpr DSP code, signal processing patches, and audio effect chains

How to use this skill

Skill file

DSP/Gen~ Specialist Agent

The DSP agent generates audio signal processing components: GenExpr code for gen~ objects, MSP signal chains, and audio effect architectures. It handles everything that operates at audio rate.

Domain Context Loading

Before any generation:

  1. Read CLAUDE.md at project root -- follow MSP and Gen~ domain-specific rules
  2. Read .claude/skills/references/genexpr-rules.md before writing or editing any GenExpr (codebox, .gendsp, mc.gen~) -- the full gen~ rule set with derivations and evidence
  3. Read .claude/skills/references/shared-capabilities.md "Max for Live Device Rules" before any M4L / .amxd device work and "bach (package) Rules" before using any bach object (both moved out of CLAUDE.md)
  4. Use ObjectDatabase from src.maxpat.db_lookup for all object lookups -- it loads all domains, resolves aliases, and checks PD blocklist automatically. No need to read individual domain JSON files.
  5. Check .claude/max-objects/pd-blocklist.json if you need to browse PD equivalents in bulk
  6. Read project config.json via load_project_config() from src.maxpat.project for allowed packages. Pass allowed_packages to Patcher(allowed_packages=allowed) so package objects outside the project's selection are blocked at creation time. If load_project_config() returns None (no config.json), use allowed = [] (core-only), never None -- None allows every package.

Domain focus: MSP (signal processing) and Gen~ (DSP operators). Other domains are handled by their respective agents.

Capabilities

GenExpr Code Generation

Gen~ Patch Integration

Gen~ Pattern Library

Reusable .gendsp files in patterns/gen/ provide sample-accurate alternatives to common anti-patterns. Consult patterns/gen/INDEX.md for the full pattern table with I/O counts, params, and use cases.

Using External .gendsp Patterns

Create a gen~ pattern-name newobj box (NOT via add_gen() which is for inline codebox):

gen_box = patcher.add_box("gen~", ["smooth-ramp"])
gen_box.numinlets = 1    # Must match .gendsp I/O count
gen_box.numoutlets = 1
gen_box.outlettype = ["signal"]  # Use ["signal", "signal"] for stereo

File placement: Copy the .gendsp file from patterns/gen/ to the project's generated/ directory alongside the .maxpat.

Param messages: Send as plain name messages: time 50 or time $1 (NOT @time 50).

Don't Hand-Roll

| Problem | Don't Build | Use Instead |

|---------|-------------|-------------|

| Smooth parameter transitions | Custom line~ message chains | one-pole-smooth or smooth-ramp |

| ADSR envelopes | function + line~ combos | adsr-envelope |

| Timing/clocks | metro + counter | master-clock + subdivider |

| Soft clipping | clip~ 0 1 | soft-clipper |

| Parameter smoothing | Nothing (zipper noise) | one-pole-smooth |

| Volume control | Raw *~ at full level | safe-gain |

Layout and Finalization

Signal Chain Construction

Bpatcher Argument Substitution (for reusable DSP subpatches)

Audio Architecture Patterns

Control-Rate Fan-Out in DSP Patches

Shared Capabilities: See .claude/skills/references/shared-capabilities.md for Control-Rate Fan-Out Rule, Assistance Comments, Aesthetic Capabilities, Layout Options, Editing Functions, and Edit Workflow reference.

Max for Live devices (experimental, unconfirmed in Live): lead audio-effect and instrument builds with Patcher.add_m4l_device(kind, params) (or add_m4l_gen_synth(params) for a gen~ synth body), save the .maxpat, then write the .amxd with export_amxd(maxpat_path) from src.maxpat.m4l_device. Signatures and reuse / refusal rules: "Builder API" in .claude/skills/references/shared-capabilities.md; device rules: "Max for Live Device Rules" in the same file.

Package Intelligence

When generating patches with package objects (BEAP, Vizzie, etc.), read .claude/max-objects/PACKAGES.md for:

Community DSP Packages

Before generating with community package objects, verify get_package_info(name)["extracted"] is true.

BEAP and MSP Integration

BEAP modules use MSP signals internally but with modular conventions:

Package Workflow Templates

Structured signal chain blueprints for generating working package patches. Each template specifies objects, connection order, I/O types, parameter ranges, and gotchas. Templates are generation guidance -- not pre-built .maxpat files.

FluCoMa: Real-Time Audio Analysis Chain

Use case: Extract spectral features from live audio for visualization or ML input

Chain: audio source -> fluid.melbands~ (or fluid.mfcc~ / fluid.pitch~ / fluid.loudness~) -> fluid.stats -> downstream; optional normalization through fluid.normalize~ via the fluid.list2buf / fluid.buf2list bridge

| # | Source | Outlet | Destination | Inlet | Type |

|---|--------|--------|-------------|-------|------|

| 1 | (audio source) | 0 | fluid.melbands~ | 0 (audio in) | signal |

| 2 | fluid.melbands~ | 0 (band magnitudes list) | fluid.stats | 0 (input list) | list |

| 3 | fluid.stats | 0 (rolling mean list; outlet 1 = standard deviation list) | (downstream) or fluid.list2buf | 0 | list |

| 4 | fluid.list2buf | 0 (buffer <name> reply) | message transformpoint $2 <normbuf> -> fluid.normalize~ | 0 | message |

| 5 | fluid.normalize~ | 0 (reply) | fluid.buf2list @source <normbuf> (send bang) | 0 | bang |

Parameter ranges (from the installed refpages):

Gotchas:

FluCoMa: Offline Buffer Processing Pipeline

Use case: Analyze pre-recorded audio into a corpus and query it by nearest neighbour

Chain: buffer~ (source) -> fluid.bufmfcc~ (or fluid.bufmelbands~) -> fluid.bufstats~ -> addpoint into fluid.dataset~ -> fit fluid.kdtree~ -> knearest queries

| # | Source | Outlet | Destination | Inlet | Type |

|---|--------|--------|-------------|-------|------|

| 1 | button | 0 | fluid.bufmfcc~ @source <src> @features <feat> | 0 | bang (starts processing) |

| 2 | fluid.bufmfcc~ | 0 (done) | fluid.bufstats~ @stats <statsbuf> | 0 | message (as in the fluid.buf2list help) |

| 3 | fluid.bufstats~ | 0 (done) | t b -> message addpoint <id> <statsbuf> -> fluid.dataset~ | 0 | message |

| 4 | message fit <dataset> | 0 | fluid.kdtree~ | 0 | message |

| 5 | (query list) -> fluid.list2buf | 0 (buffer <name>) | message knearest $2 -> fluid.kdtree~ | 0 | message |

| 6 | fluid.kdtree~ | 0 (reply) | route knearest -> (downstream) | 0 | list of identifiers |

Parameters (from the installed refpages):

Gotchas:

FluCoMa: ML Classification Pipeline

Use case: Train a classifier on audio features, then classify new audio in real-time

Train phase: fluid.buf* analysis -> fluid.dataset~ (features, addpoint) + fluid.labelset~ (labels, addlabel) -> fit <dataset> <labelset> -> fluid.mlpclassifier~

Predict phase: real-time fluid.mfcc~ list -> fluid.list2buf -> predictpoint $2 -> fluid.mlpclassifier~ -> route predictpoint -> result mapping

| # | Phase | Source | Outlet | Destination | Inlet | Type |

|---|-------|--------|--------|-------------|-------|------|

| 1 | Train | fluid.bufmfcc~ (or fluid.bufmelbands~) | 0 (done) | t b -> addpoint <id> <buf> -> fluid.dataset~ | 0 | message |

| 2 | Train | message fit <dataset> <labelset> | 0 | fluid.mlpclassifier~ | 0 | message |

| 3 | Predict | (audio source) | 0 | fluid.mfcc~ | 0 | signal |

| 4 | Predict | fluid.mfcc~ | 0 (coefficient list) | fluid.list2buf | 0 | list |

| 5 | Predict | fluid.list2buf | 0 (buffer <name>) | message predictpoint $2 -> fluid.mlpclassifier~ | 0 | message |

| 6 | Predict | fluid.mlpclassifier~ | 0 (reply) | route fit predictpoint -> (result mapping) | 0 | message |

Parameters (from the installed refpage):

Gotchas:

BEAP: FM Synthesis Chain

Extends the canonical BEAP templates in .claude/max-objects/PACKAGES.md (see also the BEAP section of max-patch-agent SKILL.md). Port roles below come from the installed BEAP module patchers' panel labels and the BEAP help patches.

Use case: FM voice with an LFO modulating FM depth, filtered and enveloped

Chain: bp.Keyboard (pitch + gate) -> bp.FM (LFO on Depth) -> bp.LPF -> bp.VCA (bp.ADSR on CV) -> bp.Stereo

| # | Source | Outlet | Destination | Inlet | Type |

|---|--------|--------|-------------|-------|------|

| 1 | bp.Keyboard | 0 (1v/oct) | bp.FM | 0 (1v/oct) | CV |

| 2 | bp.LFO | 0 (Sine) | bp.FM | 1 (Depth) | CV |

| 3 | bp.FM | 0 (output) | bp.LPF | 0 (Signal) | audio |

| 4 | bp.LPF | 0 (output) | bp.VCA | 0 (signal input) | audio |

| 5 | bp.Keyboard | 1 (Gate) | bp.ADSR | 0 (Gate) | CV |

| 6 | bp.ADSR | 0 (envelope) | bp.VCA | 1 (CV input) | CV |

| 7 | bp.VCA | 0 (scaled output) | bp.Stereo | 0 and 1 (L and R) | audio |

Port reference:

Gotchas:

BEAP: Sequenced Pattern

Use case: Step sequencer driving oscillator pitch and envelope

Chain: bp.Sequencer (CV + Gate) -> bp.Oscillator (pitch from CV) AND bp.ADSR (envelope from Gate) -> bp.VCA (envelope on CV inlet) -> bp.Stereo

| # | Source | Outlet | Destination | Inlet | Type |

|---|--------|--------|-------------|-------|------|

| 1 | bp.Sequencer | 0 (CV) | bp.Oscillator | 0 (CV1 1v/oct) | CV |

| 2 | bp.Sequencer | 1 (Gate) | bp.ADSR | 0 (Gate) | CV |

| 3 | bp.Oscillator | 0 (signal) | bp.VCA | 0 (signal input) | audio |

| 4 | bp.ADSR | 0 (envelope) | bp.VCA | 1 (CV input) | CV |

| 5 | bp.VCA | 0 (scaled output) | bp.Stereo | 0 and 1 (L and R) | audio |

Port reference:

Gotchas:

Editing Existing Patches (via /max-iterate)

Domain focus: Edit signal chains, oscillator parameters, filter settings, gen~ codebox content.

Output Protocol (New Patches)

  1. Generate GenExpr code and/or MSP signal chain
  2. If GenExpr: validate with validate_genexpr() from src.maxpat.code_validation
  3. If .maxpat with signal objects: finalize_patch(patcher, is_new=True) -- applies styling, layout, assistance comments, and midpoint generation for all patchers and subpatchers. It raises LayoutRefusedError (from src.maxpat.layout import LayoutRefusedError, a ValueError) before changing anything when the patcher, or a subpatcher the layout recurses into, has more than 120 boxes or was saved by MAX: for a large NEW build call finalize_patch(patcher, is_new=True, force_layout=True); for a build that embeds a MAX-saved patcher or edits a file from disk never force -- use finalize_patch(patcher, is_new=False) or edit_patch(path). Then serialize via patch_dict = patcher.to_dict() and validate a copy via results = validate_patch(copy.deepcopy(patch_dict), db=patcher.db). Proposed removals mean inspect, don't save: if any result has proposed_removal set, inspect each (src_id, outlet, dst_id, inlet) -- fix a real wiring mistake and re-validate, or keep a false-positive cord and report the checker gap; call apply_fixes(patch_dict, results) only when removal is explicitly wanted, then re-validate
  4. If standalone .gendsp: generate via generate_gendsp()
  5. Return output for critic review (DSP critic checks signal flow, gen~ I/O matching)
  6. Apply revisions if critic requests them
  7. Only when has_blocking_errors(results, is_new=True) is False, write final output via save_patch_roundtrip(patch_dict, path) or write_gendsp() to project's generated/ directory

Output Protocol (Edited Patches)

Follow "Output Protocol (Edited Patches)" in .claude/skills/references/shared-capabilities.md.

DSP Pre-Flight Simulation

Before saving a waveguide patch, agent checks for an opt-in numpy

stability fixture and gates the save on its result. See

src/maxpat/dsp_sim/ and tests/dsp_sim/README.md for the topology

catalogue and threshold defaults.

Codebox smoke test (advisory)

After writing or editing a gen~ codebox, run the offline GenExpr smoke test on the saved file.

It runs every codebox at the default and per-Param min/max corners; UNSUPPORTED never passes.

Report any FAIL or UNSUPPORTED finding to the user, but never block a save on it. Details:

src/maxpat/dsp_sim/README.md.

gain~ / a meter through signal consumers is audio and gets every check (NaN/inf, peak > 4,

permanent silence, self-sustain such as a latched tanh(x*g)/tanh(g) loop, DC, denormal). Any

other outlet is control (Hz, ms, indices, flags) and gets only the NaN/inf FAIL and the

denormal WARN. Inlets get a stimulus by what feeds them (click~ -> gate, sig~ / line~ ->

control, nothing -> zero, else audio noise).

among sibling .maxpat files, and with no host every port is audio.

as // smoke: control out2 trigger in1 in3=phasor:2 (control outN, audio outN,

trigger inN, inN=SPEC) overrides the inferred kinds. An unusable token is a

smoke_directive WARN.

noise) is not a defect; only silence that survives the rerun FAILs.

codebox safe-construct rules in genexpr-rules.md.

python3 -m src.maxpat.dsp_sim smoke patches/<project>/generated/<name>.maxpat

When to Run (D-07) -- filename convention

patches/bassoon-model/generated/bassoon-model.maxpat -> bassoon-model).

fixture commit freely (D-04).

How to Invoke (T-02 mitigation: argv form, no shell)

import importlib.util
import subprocess
import sys
from pathlib import Path
from src.maxpat.hooks import PatchValidationError

REPO_ROOT = Path.cwd()  # the framework root: run from the directory holding src/
stem = Path(patch_path).stem
fixture = REPO_ROOT / "tests" / "dsp_sim" / f"test_{stem}.py"
if fixture.exists():
    if importlib.util.find_spec("pytest") is None:
        raise PatchValidationError(
            f"DSP pre-flight simulation for {stem} cannot run: pytest is not "
            f"installed for {sys.executable} (pip install -r requirements-dev.txt)"
        )
    result = subprocess.run(
        [sys.executable, "-m", "pytest", str(fixture), "-q", "-p", "no:cacheprovider",
         "-o", "addopts="],
        cwd=str(REPO_ROOT),
        check=False,
        capture_output=True,
        text=True,
    )
    if result.returncode != 0:
        # VALID-05 'error' severity -- HARD BLOCK the save (D-04).
        raise PatchValidationError(
            f"DSP pre-flight simulation failed for {stem}:\n{result.stdout}\n{result.stderr}"
        )

-o addopts= clears the maintainer pytest.ini addopts (-n auto), so the gate stays serial and needs no pytest-xdist in any checkout.

sys.executable -m pytest with cwd=REPO_ROOT is what makes the gate work in

a release install: tests/ is not shipped there, so a registered fixture has

no __init__.py or conftest, and bare pytest would put tests/dsp_sim (not

the root) on sys.path and fail collection with No module named 'src'.

python -m puts the working directory on sys.path, and it needs no pytest

on PATH.

Use the argv list form ALWAYS. Never invoke pytest through a shell (no

shell kwarg set to true) and never string-interpolate stem or

patch_path into a command string -- the path comes from the filesystem

and may contain metacharacters; argv form treats it as a single opaque

token.

How to Register a New Sim Test

For a patch at patches/<project>/generated/<name>.maxpat:

  1. Pick a topology from src/maxpat/dsp_sim/topologies/ (reed_bore,

reed_bore_post_radiation; bore_only was removed in Q25) or write a custom mirror.

  1. Create tests/dsp_sim/test_<name>.py calling

run_simulation(patch_path=..., topology=..., params=..., sweep_param=..., sweep=(lo, hi, n)).

  1. Assert report.verdict == "pass".

The (patch_path, param_name, sweep_range) triple in that fixture file is

the ENTIRE binding (D-02 / DSPSIM-05). No sidecar JSON, no patch-comment

annotation, no config block.

Failure Handling (VALID-05 'error' tier)

If the gate fails, surface in the agent's summary:

runaway).

Then HARD BLOCK the commit. The author either fixes the DSP issue OR, if

intentional, deletes / skip-marks the fixture (D-10) -- opt-out is

auditable in git history; there is no --skip-dsp-sim flag.

Verdict & Fix Reference

| Verdict | Threshold | Suggested fix (from CLAUDE.md Gen~ rule "Waveguide loop filters"; derivation: genexpr-rules.md) |

|---------|-----------|----------------------------------------------------------------------|

| phase_drift | range > 5 cents across sweep | Use phase delay (atan2-based) compensation, not group delay |

| mode_competition | any step > 50 cents jump | Move the high-Q (Q > ~1) filter post-loop |

| no_oscillation | RMS < 1e-4 at any step | Loop dissipation likely too high; check damping coefficients |

| runaway | peak > 10.0 OR NaN/Inf | Loop gain >= 1; add saturator or reduce reflection scalar |

Verdict priority on multi-mode runs (D-09):

runaway > no_oscillation > mode_competition > phase_drift > pass.

Single verdict per run.

When to Use

When NOT to Use

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.