@kairotic/app 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -2
- package/index.html +1101 -0
- package/kairotic/api.cljs +362 -0
- package/kairotic/assistant.cljs +505 -0
- package/kairotic/backends/gun-backend.js +371 -0
- package/kairotic/canvas.cljs +751 -0
- package/kairotic/code.cljs +108 -0
- package/kairotic/components.cljs +838 -0
- package/kairotic/core.cljs +96 -0
- package/kairotic/corefns.cljs +473 -0
- package/kairotic/docs.mjs +2 -0
- package/kairotic/engine.cljs +482 -0
- package/kairotic/examples.mjs +96 -0
- package/kairotic/faust.cljs +225 -0
- package/kairotic/help.cljs +1036 -0
- package/kairotic/hiccup.cljs +566 -0
- package/kairotic/input.cljs +271 -0
- package/kairotic/kfile.mjs +138 -0
- package/kairotic/library.cljs +214 -0
- package/kairotic/links.cljs +41 -0
- package/kairotic/mt.cljs +1604 -0
- package/kairotic/mtboxes.cljs +276 -0
- package/kairotic/packages/analysis.mjs +64 -0
- package/kairotic/packages/controls.mjs +28 -0
- package/kairotic/packages/data.mjs +22 -0
- package/kairotic/packages/faust-units/cmaes.mjs +82 -0
- package/kairotic/packages/faust-units/graph.mjs +212 -0
- package/kairotic/packages/faust-units/listen.mjs +125 -0
- package/kairotic/packages/faust-units/notation.mjs +139 -0
- package/kairotic/packages/faust-units/parse.mjs +439 -0
- package/kairotic/packages/faust-units/recipe.mjs +195 -0
- package/kairotic/packages/faust-units/render.mjs +69 -0
- package/kairotic/packages/faust-units/units.mjs +130 -0
- package/kairotic/packages/faust-units/view.mjs +353 -0
- package/kairotic/packages/faust-units.mjs +9 -0
- package/kairotic/packages/io.mjs +58 -0
- package/kairotic/packages/net.mjs +28 -0
- package/kairotic/packages/patterns.mjs +34 -0
- package/kairotic/packages/spatial.mjs +22 -0
- package/kairotic/packages/spectral/shift.mjs +169 -0
- package/kairotic/packages/spectral.mjs +16 -0
- package/kairotic/packages/synth.mjs +28 -0
- package/kairotic/packages/theory/counterpoint.mjs +798 -0
- package/kairotic/packages/theory/mirror.mjs +221 -0
- package/kairotic/packages/theory.mjs +46 -0
- package/kairotic/patterns.cljs +538 -0
- package/kairotic/presets.cljs +227 -0
- package/kairotic/quantize.cljs +782 -0
- package/kairotic/record.cljs +169 -0
- package/kairotic/release.cljs +90 -0
- package/kairotic/ring.cljs +129 -0
- package/kairotic/ringaudio.cljs +232 -0
- package/kairotic/ringcore.mjs +270 -0
- package/kairotic/score.cljs +176 -0
- package/kairotic/shapes.cljs +283 -0
- package/kairotic/signal.cljs +327 -0
- package/kairotic/sounds.cljs +565 -0
- package/kairotic/sounds.mjs +108 -0
- package/kairotic/span.cljs +129 -0
- package/kairotic/spell.cljs +281 -0
- package/kairotic/structure.cljs +145 -0
- package/kairotic/talk.cljs +115 -0
- package/kairotic/tempo.cljs +226 -0
- package/kairotic/treecanvas.cljs +299 -0
- package/kairotic/tutorials.mjs +1283 -0
- package/kairotic/vendor/codemirror.mjs +23 -0
- package/package.json +23 -4
- package/page/00-work.cljs +862 -0
- package/page/01-commands.cljs +1219 -0
- package/page/02-patch-view.cljs +1051 -0
- package/page/03-history-view.cljs +481 -0
- package/page/04-panels.cljs +448 -0
- package/page/05-gestures.cljs +1247 -0
- package/page/06-connection.cljs +219 -0
- package/page/07-claude.cljs +430 -0
- package/page/08-sessions.cljs +423 -0
- package/page/09-learn.cljs +602 -0
- package/page/10-embed.cljs +469 -0
- package/page/11-startup.cljs +61 -0
- package/page/12-feedback.cljs +172 -0
- package/page/13-perform.cljs +325 -0
- package/page/14-editor.cljs +656 -0
- package/page/15-presets.cljs +230 -0
- package/page/16-release.cljs +242 -0
- package/page/17-sounds.cljs +147 -0
- package/page/18-lines.cljs +594 -0
- package/page/19-files.cljs +247 -0
- package/page/19-html.cljs +152 -0
- package/page/20-talk.cljs +527 -0
- package/page/21-net.cljs +110 -0
- package/page/22-learn.cljs +303 -0
- package/page/23-ids.cljs +233 -0
- package/page/24-clipboard.cljs +136 -0
- package/page/25-tidy.cljs +74 -0
- package/page/26-probes.cljs +111 -0
- package/sources.mjs +2 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// Generated by site/build.mjs from docs/
|
|
2
|
+
export default {"pages":{"guide":{"en":"# Guide\n\n*[Leer en castellano](guide.es.md)* · [Documentation](README.md)\n\nKairotic is a patcher of music — boxes joined by lines, as in Max or Pure Data — where **the patch\nand its code are the same work**, and every gesture stays in a history you can travel, branch and\nshare. This guide walks through the interface; [Concepts](concepts.md) explains what is behind it.\n\n## 1. Open a work\n\nOpen [the app](https://bonuoq.github.io/kairotic/) (or the Kairotic artifact inside claude.ai). The\n**Sessions** window offers three ways in:\n\n- **Solo** — your own works, saved (in claude.ai, in your account; on Pages, encrypted in your browser).\n- **Shared rooms** — a work that everyone in the room edits at the same time, each gesture in the same\n history.\n- **Try locally, without saving** — a patch to play with; nothing is kept.\n\nA solo work can be copied into a room and a room into a solo work (with its history). **Sessions**, at\nthe top right, brings this window back.\n\nOn Pages, rooms sync through a **relay**. **Relay**, in the same window, shows the ones in use and\nwhether they answer; a community can run its own (`npx @kairotic/relay`) and choose it there, and the\nlinks you share carry it. See [Kairotic Pages](pages.md).\n\n## 2. Make a patch\n\n- **Create a box**: double-click an empty place, write its text — the class and its arguments, such as\n `osc~ 440` — and press Enter. Classes ending in `~` are sound.\n- **Connect**: drag from an outlet (the small marks under a box) to an inlet (above another box). You need\n not hit the mark: near an outlet it lights up and the pointer becomes a cross, and a wire dropped on a\n box, or just above one of its inlets, lands on the nearest inlet. Wires are curves, here and in the\n patch of a `faust~`, which works the same way.\n- **Ids**: every box has an id (`:b7`), which code, the REPL and Room messages name it by. It shows over the\n box's top right corner when the box is hovered or selected; **I** shows them all. **`(`** on the patch opens\n a line of the REPL there (as the field of a new box does when what you write starts with `(`), with the same\n editor as the REPL — completion, brackets closed: Enter runs it once its brackets are balanced and shows\n what it gave below, ↑ ↓ go through the REPL's history, Esc closes it. While a line of code\n waits for a box — the REPL, the Code tab, that line, a Room message — after a space, `(` `[` `{` or `:`\n (`@` in a message), a click on a box writes its id there instead of selecting it, as a click on a cell does\n in a spreadsheet formula: `(connect ` click, `0 ` click, `0)`.\n- **The Code tab and the patch**: selecting boxes marks their lines in the Code tab (their box, lines, data…)\n and scrolls to them; putting the cursor on a line of a box selects that box (both boxes, on a `connect`).\n Lines longer than 160 characters — the source of a code box, a buffer kept as data — are folded after\n their beginning, saying how many characters they hide; a click shows them, and they stay shown.\n- **Boxes over one another**: a box's real size is only known once it is drawn (a `faust~` grows with its\n sliders, a score with its notation). `(overlaps)` lists the boxes that cover each other, and `(tidy)` moves\n boxes down until none does, in their columns, as one event.\n- **Probes on wires**: ⌥/Alt+click a wire (or `(probe :b1 0 :b2 0)`) and it shows, at its middle, the last\n value that went along it, flashing when one passes, and how many a second when they come often. Again takes it\n away; `(unprobe-all!)` takes them all. Probes are only for this tab: they are not part of the work, its history\n or its code. Wires out of a sub-patch box, and signal wires, show nothing yet.\n- **Select** a box or a line by clicking it. **⌘/Ctrl+click** a box to edit it below (its arguments,\n and its text). **Delete** removes what is selected.\n- **Select several**: ⇧+click adds a box to the selection (or takes it out); a frame drawn from an\n empty place of the paper selects every box it touches (⇧ adds them); ⌘/Ctrl+A selects all. Drag one\n of them and they all move; Delete removes them all.\n- **Copy, cut, paste, duplicate**: ⌘/Ctrl+C copies the selected boxes, ⌘/Ctrl+X cuts them, ⌘/Ctrl+V pastes\n them where the pointer is, keeping their layout, and ⌘/Ctrl+D duplicates them a little below and to the\n right (`(duplicate :b3 :b4)` from code). Pasted boxes get new ids and keep their lines among themselves, and\n their lines to boxes that were not copied when those are in the patch. A paste is one event of the\n history. What is copied is the boxes' code, so it can also be pasted in a message or a document; pasting\n reads its last line as data and never runs it.\n- **Move** a box by dragging it. Playable boxes — `bang`, `msg`, `number`, knobs — are selected by the\n grip on their left; their body is for playing.\n- **Which box is on top**: boxes are drawn in the order they were made, the newest on top, and the box\n you drag comes to the front, so that what you move is never hidden. That is only how your tab shows them,\n as the selection is: it is not part of the work, its history or its code.\n- **Type a value**: double-click a numeric control — a `number`, a knob (or any component that is\n dragged for a number), a slider of a `faust~` box or its value — and write the number: `440`, `-3.5`,\n `0,5`, `3/2`. Enter applies it, as a drag would (a knob keeps it in its text, within its range; a\n slider within its min and max); Esc closes the field and leaves the value as it was. What is not a\n number is refused and the field stays open.\n- **Edit a box's text**: double-click it. Code boxes (`faust~`, `script`, `component`, `tree`):\n in the patch they show one row of their code; double-click it to open the **code editor**, a window\n you can move by its bar and resize by its corner, with line numbers, automatic indentation, matching\n brackets, structural editing for Clojure (Ctrl+→ / Ctrl+← move over forms, Alt+↑ widens the\n selection), search (Ctrl/⌘+F) and completion. Ctrl/⌘+Enter applies the code and keeps the window\n open; Esc closes it, asking first if something is not applied.\n\nA first patch:\n\n```clojure\n(box :b1 \"osc~ 440\" 40 40)\n(box :b2 \"gain~ 0.2\" 40 100)\n(box :b3 \"dac~ 1 2\" 40 160)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n(connect :b2 0 :b3 1)\n```\n\nYou can make it with the mouse, or write it in the **Code** tab (Run · Ctrl+Enter), or in the REPL at\nthe bottom, one call at a time. The three are the same work: what you draw appears as code, and what\nyou write appears as boxes.\n\nThe Code tab and the REPL use the same code editor as code boxes (brackets that close and match,\ncompletion of the commands). In the REPL, Enter evaluates when every bracket is closed — otherwise it\nstarts a new line, and ⇧+Enter always does — and ↑ ↓ bring back what you wrote before.\n\n**Functions as boxes.** A box named after a pure function of `clojure.core` (or `clojure.string`, as\n`str/…`) is that function, with no component to write: its other words are its arguments, read as EDN,\nand the message that arrives goes last, as with `->>`. `%` puts it elsewhere. The text reads as Clojure,\nthe inlets as Max: wherever `%` is written, the message is always the **left inlet, the only hot one**;\nthe other arguments have an inlet each on the right, in the order they are written, which replaces them\nwithout sending. A bang on the left sends again with the last message; a result that is `nil` sends\nnothing.\n\n| box | message | sends | inlets |\n|---|---|---|---|\n| `into [440]` | `[1 2]` | `[440 1 2]` | the message · `[440]` |\n| `conj % 440` | `[1 2]` | `[1 2 440]` | the message · `440` |\n| `vector % 0 0` | `1` | `[1 0 0]` | the message · `0` · `0` (a *pack*) |\n| `hash-map :freq % :amp 0.5` | `440` | `{:freq 440 :amp 0.5}` | the message · `:freq` · `:amp` · `0.5` |\n| `map inc` | `[1 2]` | `[2 3]` | the message · `inc` |\n| `str/upper-case` | `\"do\"` | `\"DO\"` | the message |\n\nOnly pure functions are there (`map`, `filter`, `take`, `assoc`, `sort`, `frequencies`…), so these boxes\nare safe in a shared room; a class with the same name (`+`, `print`) comes first.\n\n**Data as functions.** As in Clojure, a keyword, a set or a map written first is a function too, and\nthe message goes first, `(:freq msg)`:\n\n| box | message | sends |\n|---|---|---|\n| `:freq` | `{:freq 440 :amp 1}` | `440` — a field of an event |\n| `:freq 220` | `{:amp 1}` | `220` — the default, which has an inlet |\n| `#{60 64 67}` | `64` · `62` | `64` · nothing — a filter |\n| `{60 :c 64 :e}` | `64` | `:e` — a table |\n\n**Every inlet hot: `^:hot`.** Written before the class, as Clojure writes metadata, `^:hot` makes a new\nargument send at once with the last message (`nil` before the first one), like `pak` in Max:\n`^:hot vector % 0 0`.\n\n**Over a stream: `xf/`.** `xf/` before a function makes its *transducer* a box with memory: it goes\nthrough the messages that arrive one by one, not through a collection, and what it lets through goes out\none message at a time.\n\n| box | does |\n|---|---|\n| `xf/partition-all 4` | collects 4 messages and sends them as a vector |\n| `xf/partition 4 1` | the last 4 at every message (a sliding window) |\n| `xf/dedupe` | lets a message through only when it changes |\n| `xf/take 1` | the first message only (a bang is a message too) |\n| `xf/filter odd?`, `xf/map inc`, `xf/mapcat reverse`… | as in Clojure, message by message |\n\n`:flush` completes it (`partition-all` sends what it holds) and starts again, `:clear` starts again\nwithout sending, and a new argument on the right starts again too. The help of each of these boxes (**?**)\nlinks to its page at [clojuredocs.org](https://clojuredocs.org) and to the reference at\n[clojure.org](https://clojure.org/reference/transducers).\n\n**Choosing a way: `dispatch`.** `dispatch n` sends what arrives on the left by one of its n outlets, numbered\nfrom 0 as every port is. The right inlet chooses: `msg 1` (outlet 1), `msg nil` or `msg false` (closed:\nnothing goes out), `msg true` (outlet 0, so `dispatch 1` is a gate that opens and closes). A function chooses\nfor each message, and nil lets it through nowhere: a map `{60 0 64 1}`, a keyword `:to` (the way written in\nthe event), a name or a form (`even?`, `(comp …)`); a set lets its members through outlet 0. The selector\ncan be written after n: `dispatch 2 {60 0 64 1}`. It is named after the *dispatch function* of\nClojure's multimethods, which looks at a value and chooses where it goes.\n\n**Functions through the wires.** A function travels as its form, EDN data. `comp`, `partial`, `juxt`,\n`complement`, `fnil`, `constantly`, `every-pred` and `some-fn` are boxes that send one on a bang:\n`comp inc (partial * 2)` sends `(comp inc (partial * 2))`. Wherever a box takes an argument, a name or such\na form *is* that function, so a form sent into the inlet of `inc` in `map inc` changes the function live\n(`xf/filter odd?`, `sort-by :freq` likewise). Forms can also be written in a box and nest:\n`map (partial * 2)`, `map (juxt inc dec)`. With `%`, a builder takes the function that arrives:\n`comp % inc`. Only these pure functions (and `+ - * /`) are ever made from a form, and each browser\nrebuilds it from them, so it is as safe in a shared room as any argument; a name it does not know (or a\ncall such as `(inc 1)` in place of a function) is not sent and is written in the REPL. To send a function\nby its name, a `msg` with the name: `msg inc` (a keyword, `msg :inc`, stays a keyword: a key, and a\nfunction by itself).\n\n## 3. Sound and time\n\n- **▶** (or the space bar) starts the sound and time: audio, `metro`, `ramp`, `loadbang`, `mt play`.\n The first ▶ also asks the browser for permission to play sound.\n- **■** silences and brings every box back to its initial state.\n- **`print`** writes what reaches it in the REPL, after its label: `print out0` writes `out0: 60` (without\n one, `print: 60`); a string as it is, anything else as EDN. To shape the text, **`format`** before it, as\n Clojure's (Java's printf): `format \"%.1f Hz\"` sends `\"440.1 Hz\"`, `apply format \"%s Hz · %.1f dB\"` fills\n several from a list — `%s`, `%d`, `%.2f`, `%e`, `%x`, widths (`%5.1f`, `%-8s`, `%03d`) and `%%`.\n- Messages travel without ▶: a click on a `bang` or a `msg`, a number dragged, a data box that changed.\n- A `msg` sends what is written in it, read as in Clojure: numbers (`msg 0 8 4`), **keywords with their\n colon** (`msg :stop`, `msg :rec 4`), **names** (`msg inc`: a function where a box takes one; also free\n text such as a note `e4`, a ratio `6/5`, a URL or an OSC address), `true`, `false`, `nil`, **text\n between quotes as a string** (`msg \"https://…/voice.ogg\"`, `msg \"two words\"`) and EDN forms\n (`msg [0 4 7]`, `msg {:freq 440}`), alone or in a list (`msg :url \"github:…\" 3`). A word without its\n colon is a name, not a keyword: `msg stop` does not stop a `metro`, `msg :stop` does.\n- **Stochastic synthesis**: `gendy~ 110` (in `@kairotic/synth`) is an oscillator after Xenakis's GENDY:\n a wave of breakpoints whose amplitudes and durations take random walks cycle after cycle — a pitch\n that drifts, a timbre that keeps changing. `[:x-step 40]` lets the pitch wander, `[:y-step 0.2]` the\n timbre; a signal on its inlet modulates its frequency. Its help patch has four steps.\n- **Faust as a patch** (Study 31, `@kairotic/faust-units`): the code of a `faust~` opens beside its box\n with its **patch** on the left, the same code as Faust's own elements — primitives (`+ * ' @ sin\n select2`…), controls (`hslider button`…), library functions (`os.osc fi.lowpass en.adsr`…), `in` and\n `out`. Double-click the paper for a new box (a name, a number, or any Faust expression, kept as a box of\n code), drag from an outlet to an inlet, Delete removes. Editing the patch rewrites the code beside it,\n editing the code redraws the patch; Ctrl/⌘+Enter or Apply applies, as always. A loop must go through the\n one-sample delay `'` (in code, `~`). Code the boxes cannot read still plays, with the patch marked out of\n date. **Patch** in the window's bar hides it. The window opens beside the box, so its parameters stay in\n sight in the patch.\n- **A recipe from a sound** (Study 35): **Recipe** in the bar of a `faust~`'s window finds the values of\n its sliders that sound closest to a sound — a sample box of the patch, or a sound file. It plays the code\n offline, a note of one second (a `gate` button, if there is one, held for 0.65 s), many times: random\n settings first, then a search that listens as `features~` does, the pitch heard as `pitch~` hears it\n and held, on a slider called `pitch`, `key`, `note` or `midi` (MIDI) or `freq` (Hz). *quick* plays it\n about 200 times, *careful* about 450; **Stop** stops it. The values found are written in the code, each\n slider starting there: edited, not applied, so Ctrl/⌘+Enter applies them as one event and the box shows\n them in its parameters. **▶ sound** and **▶ found** play the second it listened to and what it found.\n It compares timbres apart from loudness; a log scale where the code says `[scale:log]` helps it.\n- **Descriptors as a score: `realize~`** (Study 37, `@kairotic/analysis`): a box before a `faust~` that\n plays it from four descriptors — **loudness** (dB, or a level 0…1 as `features~` sends `rms`),\n **brightness** (the spectral centroid, Hz), **noisiness** (the spectral flatness, 0…1) and **pitch** (Hz as\n `pitch~` sends it, 0 for none; MIDI with `realize~ midi`). The `faust~`'s `pitch` or `freq` slider takes\n the pitch, its `gain` slider the loudness, and its other sliders are set to the settings of that `faust~`\n that sound nearest to the brightness and noisiness written. To know them it **learns** the `faust~` its\n left outlet reaches: when the first values arrive (or on `:learn`, after changing its code) it plays a few\n hundred steady settings offline and listens to them. What comes in can be `features~` and `pitch~` of\n another sound — sing, and a synth follows your loudness, brightness, noisiness and pitch with its own\n sound — or curves drawn on canvases read by `reader~` and `snapshot~`. Its right outlet says how far the\n nearest setting is from what is written (above 1, the `faust~` cannot sound like that: noise as dark as a\n tone, say); a `monitor` shows what is written beside what `features~` hears in the result. It can\n **listen to what it plays**: a `features~ 20` on the `faust~`, its three outlets (rms, centroid, flatness)\n into the last three inlets of `realize~`, and it asks for more where what is heard falls short of what is\n written, little by little, within limits — the loudness then means the level as `features~` hears it.\n- **Faust in several voices**: a `faust~` whose source declares `declare options \"[nvoices:8]\";` is\n polyphonic. Its voice uses `freq`, `gain` and `gate`, set note by note; Hz go to its left inlet and\n voice ids to its right one, as with `synth~` (a `keyboard` 0→0, 1→1, 3→0; `mt play` 0→0, 1→1), in any\n tuning; `effect = …;` in the same source is applied to the sum of the voices. Its help patch shows it.\n- **Sound from outside**: `adc~ 1` is the microphone (or an input of the sound card: `adc~ 1 2`). At ▶\n the browser asks for it once; its sound comes as it is, without the processing made for calls.\n `scope~` draws a signal and `snapshot~ 50 db` turns it into numbers (its level), so what is heard can\n drive the patch. Use headphones before sending an `adc~` to `dac~`: it feeds back.\n- **Recording**: a `sample` box records what reaches it on `:rec` until `:stop` (or its length:\n `sample 10`), and a `reader~` with the sample on its right plays it at the position on its left, in\n seconds — or, as `reader~ norm`, from 0 to 1: a `phasor~` straight in, with `!/ 1` turning its length (its\n left outlet) into the speed of the phasor~; any other speed plays it faster, slower or backwards. Every\n reader and reader~ reads this way: in the units of its buffer (the X axis of a canvas, the time of a\n freqt, seconds), or 0…1 with `norm`. The sound stays in this browser; the work keeps its picture, so a work\n opened elsewhere shows it and says it is not there. `(load-sound! :bN)` brings in a file,\n `(save-sound :bN)` saves it as WAV. A sound **from a URL** — `(load-sound! :bN \"https://…/voice.ogg\")`,\n a string sent to the sample, or `(sample! :bN {:url \"…\"})` in the code — is fetched by every browser that\n opens the work, so a shared session or a link has the same sounds everywhere (a URL of another site\n must allow it: CORS). Two sources always work: `github:owner/repo@ref/path.wav`, any file of a public\n GitHub repository, served by jsDelivr (for instance the banks of\n [Dirt-Samples](https://github.com/tidalcycles/Dirt-Samples): `github:tidalcycles/Dirt-Samples@master/bd/BT0A0A7.wav`),\n and `freesound:id`, a sound of [Freesound](https://freesound.org) with your own API key, kept only in\n your browser (`(freesound-key! \"…\")`, from freesound.org/apiv2/apply). `(sounds \"rain\" {:max 10})`\n searches Freesound and prints the line that loads each result; a Freesound sound keeps its author and\n licence, and `(credits)` lists them for the work.\n- **Listening**: the package `@kairotic/analysis` (it comes into a work when one of its classes is\n written) turns what is heard into data: `pitch~` the pitch by YIN (Hz, and 0 when it stops hearing\n one), `onset~` a bang at each attack, `chroma~` the 12 pitch classes and the strongest one,\n `features~ rms centroid flatness …` descriptors (with Meyda), and `spectrum~` draws the spectrum.\n `monitor 6 rms centroid chroma` draws whatever arrives on its inlets over the last 6 seconds, one lane\n each: numbers as lines, lists (chroma, mfcc) as strips, bangs and words as marks.\n `form~` compares every moment with the others (a self-similarity matrix of a chroma or an mfcc, drawn): a\n bang where a section begins, the period that repeats, and a `[:segment …]` that makes `onset~` start afresh.\n `transcribe` writes what `pitch~` hears into a `freqt` — `:rec`, play, `:stop` — as notes at their pitch\n or, with `transcribe 60 glide`, as contours that follow the voice (an `onset~` on its right splits\n repeated notes); the freqt shown as a score previews it in notation, and a `quantize` box (the freqt's\n second outlet on its right inlet, a bang) writes it in measures as a tree, for a `tree` box — with the\n meter, the divisions and the other options you give it, and `:time :track` for a phrase sung freely.\n- **Recording a gesture**: `record [lo hi]` writes any stream of numbers into a `canvas` as strokes over\n time — a knob, an envelope (`snapshot~ 50 rms`), a descriptor (`features~ 20 centroid`) —: `:rec`,\n play, `:stop`. A value holds until the next one; the axes follow the take. Edit it like any drawing and\n read it back with `phasor~` → `reader~ norm` as an automation.\n- **Recording from a point**: `:rec t` (`msg :rec 4`) on a `sample`, `record` or `transcribe` keeps what\n was there before t (seconds; beats for transcribe) and records from t on, replacing what came after —\n a punch-in. `:ovr t` (`msg :ovr 4`; `:ovr` alone, from 0) overwrites only what the take covers, from t\n to where it stops, and keeps what came after it — a punch-in/out. A canvas or freqt takes `[:cut t]`\n for that (everything from t on) and `[:cut t1 t2]` (what is between them; a stroke across is split).\n- **A span of time with heads**: a `ring [seconds]` keeps the messages of the last seconds, each at its\n time; its write head goes round as a tape head. A `reader` on its right outlet is a head of its own:\n `reader d 1` follows the ring's head 1 s behind — a canon, a delay; two readers, a canon in three voices;\n `reader d 1 speed 0.5`, an augmentation; at −1 it goes back over what was written. A number on a\n reader's left moves it instead (a ramp, a counter), either way; a move larger than its `jump` is a seek.\n A `writer` (what to write · the ring's buffer · a position) writes where it is, from any source, erasing\n what it passes (or `writer mix`, leaving it); `:rec t` / `:ovr t` send it to t at speed 1. A reader into\n a writer on the same ring is feedback: a round.\n- **The same with sound**: `ring~ [seconds]` keeps the last seconds of the sound on its left (with nothing\n there its own head does not write: the ring is what its `writer~`s write). A `reader~` on its right\n outlet without a position signal follows its head: `reader~ d 1` a delay, `reader~ d 1 speed 0.5` an\n octave down and falling behind, `speed -1` backwards; a new `d` (`msg :d 0.25`) glides, the pitch bending,\n or seeks with a crossfade. With a position signal it reads there (seconds; `norm`: 0…1, a `phasor~`). A\n `writer~` (sound · the ring~'s buffer · a position signal) writes as a tape head — `ovr` replaces, silence\n too; `writer~ mix 0.8` adds, keeping what was there times 0.8. Up to 8 heads share the ring~'s one node, so\n a feedback inside it is exact (through other boxes it costs a block of 128 samples). A `faust~` between a\n `reader~` and a `writer~` of the same ring~ (`reader~ → faust~ → writer~`) runs inside the ring's node, one\n sample at a time: the loop stays exact, so a short d with a lowpass in the loop is a plucked string\n (Study 49).\n\n## 4. The history\n\nEvery gesture is an event of the history, at the bottom of the page.\n\n- **Ctrl+Z** goes back, **Ctrl+Shift+Z** (or Ctrl+Y) forward; or click any point of the history.\n- Doing something after going back makes a **branch**: nothing is lost.\n- **Merge…** brings the events of another branch here, when they do not clash.\n- In a room, the gestures of others arrive in the same history; *Follow the front* keeps you at the\n newest point.\n- **◆ Snapshot** — `(snapshot)`, or `(snapshot \"intro\")` with a name — writes a keyframe: a point of\n the history with the work as it is now. It is drawn as a square.\n\n### Lines\n\nA work can have several **lines**: independent histories, each a tab above the patch. The main line\n(★) is the work as it always was; the others are studies, sketches, parts — each with its own patch,\nits own branches, merges and snapshots.\n\n- **+** makes a new, empty line — `(new-line \"sketch\")`. Click a tab to put its line on screen —\n `(go-line \"sketch\")`; each tab comes back at the point where you left it.\n- Double-click the tab on screen to rename it — `(rename-line \"intro\")`; **×** archives it (it is kept,\n with its history, and comes back from *archived* — `(restore-line \"sketch\")`). `(work-lines)` lists them.\n- The line on screen is what the patch, Perform, Share/Export, Release and Claude work on.\n- The engine plays the line where you pressed ▶ (its tab shows ▶ too): changing tabs does not stop it, and the\n transport says which line plays. The messages of the tab on screen still travel; its audio boxes stay quiet\n until you press ▶ there, which makes it the line that plays. In a room, the others' positions are drawn only on the line they are on;\n following someone onto another line opens their tab.\n- Lines do not change while you perform, in a lesson or in the scratch patch.\n\n**A line inside another.** `patch @name` uses the line called *name* as a sub-patch (spaces in its name are\nwritten `-`: `patch @bass-line`); its `inlet` / `outlet` boxes are the box's ports. Double-click opens the line\nin its tab.\n\n- It **follows** the line (↻): it is the line at its newest point, so it changes as the line advances, for every\n box that uses it. `(pin-ref :b3)` **pins** it to the point it reads now (⌖ and that moment);\n `(follow-ref :b3)` follows again. A line cannot contain itself, nor a line that uses it.\n- While you perform, the lines followed stay where they were when Perform started. A snapshot keeps where they\n are, and its point plays them so: going back in the history, a point after a snapshot hears the lines as they\n were then (at the newest point, as they are now).\n- Inside a line used so, `adc~` and `dac~` are quiet: they play when the line plays alone (its own ▶), so a line\n can be tried with its own input and output. Sound goes in and out through `inlet~` / `outlet~`; the box warns\n (⚠) when its line has a `dac~` and no `outlet~`, or an `adc~` and no `inlet~`.\n- Renaming a line rewrites the boxes on screen that use it; boxes elsewhere still find it by its old name.\n- While the line that plays uses the line on screen (and its tab is at its newest point), the tab shows it\n where it plays, and what you play there goes to every box that uses it (the transport says ×2, ×3…).\n To play one of them alone, play the line that uses it.\n- The inspector of a patch box (⌘/Ctrl+click) has what it can do with lines: an embedded patch can be\n **extracted** to a new line, with the history it had inside the box — `(extract-line :b3 \"filters\")`; a\n `patch @name` can be pinned, followed, opened, or **inlined** — `(inline-ref :b3)`: a copy of its line\n inside the box, detached from it.\n- A link (Share/Export) or a release carries **one line**: every `patch @name` in it becomes an embedded patch\n holding its line as it plays there — at each keyframe of a release, as the snapshot kept it.\n\n### Compose and Perform\n\nComposing is the usual mode: every change to the work is a point of the history. **Perform** opens a\ntime of its own to rehearse, try and improvise with the work: what you change makes a *take* that\nstarts from where you are and stays out of the history (the patch has a red frame while you perform).\n\n- Ctrl+Z / ◀ take back your last changes of the take; ▶ brings them again.\n- A snapshot in Perform writes the take so far into the history, and the take goes on from there.\n- Pressing **Perform** again goes back to Compose: *Keep it as a new point* writes the take as a branch\n from where it started (closed by a filled square), *Discard* goes back to where you were.\n- In a room, whoever performs from the same point of the history plays the same take: a **jam**. Only\n they receive each other's changes; the others are invited to join it.\n- From the REPL: `(perform)`, `(compose)`, `(compose :keep)`, `(compose :discard)`, `(jam \"id\")`.\n Perform and Present are independent: you can perform with the whole patch or with the panel.\n\n### Presets: keyframes to recall, morph and generate\n\nEvery keyframe — a snapshot, or a take kept from Perform — is also a **preset** of the work: the text of\neach box at that moment (its arguments, and the values controls keep there: a knob, an envelope, a\npad), sub-patches included. A `presets` box plays them:\n\n- A number or a label into its left inlet — `2`, `intro` — **recalls** that keyframe: every box that\n is also there takes its text of then, as one event of the history (one Ctrl+Z undoes it). Boxes added\n or removed since, lines and buffers stay as they are.\n- A position into its right inlet **morphs**: `1.5` puts the controls halfway between the first\n keyframe and the second. They move as messages, as a drag does (live, and played in a jam), and\n nothing is written until `:keep`. A knob that drives the morph is not moved by it.\n- A **bang** makes a new preset from what changes and what remains: what is the same in every keyframe\n stays; a number that changes takes a value within its range (geometric for a `log` knob, whole if it\n always was); a word that changes is one of its words. `[:generate 42]` gives the same preset every\n time; snapshot it to keep it as one more keyframe.\n- Its outlet sends the values of the controls it set, `{:b3 0.5 :b5 880}`.\n- Keyframes are numbered in order of moment, the same in every tab of a room. `presets intro verse`\n uses only those snapshots, in that order.\n- From the REPL, with every keyframe of the work: `(keyframes)`, `(recall 2)`, `(recall \"intro\")`,\n `(morph 1 2 0.5)`, `(morph :keep)`, `(generate)`, `(generate 42)`. In Perform, all of it goes to\n the take, as any change does.\n- The tutorial *Presets: recall, morph, generate* (Help → tutorials, or `(tutorial \"presets\")`) walks\n through all of it with an FM synthesizer.\n\n### Release, and points forgotten\n\nKeyframes live in the history, and the patch's code, a link or an embed carry only the patch. To make\npresets travel, a `presets` box can **keep** them: `(store-presets! :b18)` copies into it the keyframes it\nuses, only what changes between them. A box that keeps presets uses them instead of the history, and the\nwork's code writes them as `(presets! :b18 […])`, so they go wherever the patch goes. `(presets! :b18 nil)`\nforgets them.\n\n- **Release…** (in the history bar), or `(release)`, makes a **new work** with a compact history: one\n point per keyframe, with its label, each written as the changes from the one before, and then the work\n as it is. Every presets box keeps its presets in it. The work you released from stays as it was, with\n all its history.\n- In a solo or local work you can **forget points**: ⇧+click them in the history, then **Forget…**. The\n work at those moments is lost (and a snapshot there with it), and the moments after them stay exactly as\n they are. The tip of a branch and a point where a branch starts cannot be forgotten, and in a shared room\n the history belongs to everyone, so there a release is the way to a compact version. From the REPL:\n `(forget-points [[\"segment\" 3] …])`.\n\n## 5. The tabs on the right\n\nThe panel on the right can make way for the patch: **»** in its header (or **›** on the bar between them)\nhides it, and **‹** brings it back; asking for a tab — **?** or F1 on a box, `(docs …)`, a tutorial —\nshows it too. Drag the bar between the patch and the panel to give it another width; a double-click on\nthe bar hides or shows it. This browser remembers how you left it. From the REPL: `(side-panel false)`,\n`(side-panel true)`, `(side-panel 480)`, `(side-panel :auto)`.\n\n- **Code** — the work as **Calls** (`box`, `connect`, …), editable: Ctrl/⌘+Enter runs them and rebuilds\n the patch. **Data** shows the same work as data (EDN): the state the history produces, every key of\n every box, read-only, to inspect it (folding and search with Ctrl/⌘+F). Edits not run yet stay in the\n calls while you look at the data.\n- **Components** — the classes this work knows. The boxes that define them (`component`) are kept\n here, not in the patch, since they have no inlets nor outlets: **New component**, **Edit** (its code\n in the code window), **Publish**, ×; a click on a row chooses it for Claude to change. Import\n published ones, or use those of the shared library.\n- **Claude** — Claude makes a patch (or changes the open one), or writes a component, from what you\n describe. See [Asking Claude](ask.md).\n- **Help** — this **documentation** (guide, concepts, topics, reference), a page for every class,\n inlet by inlet, with a help patch (some have several steps, one use each, that ◀ ▶ travel like a\ntutorial), and the **tutorials**. Select a box and press **?** (or F1) to see\n its page; `(docs \"concepts\")` in the REPL opens a page of the documentation.\n\n- **Feedback** — during the alpha: report what fails, propose an idea or ask a question. It writes a\n GitHub issue for you, with the patch on screen, recent errors and your browser if you want; you\n publish it on GitHub. The open issues are listed, so you can add to one instead of writing it twice.\n\n## 6. Music as data\n\nA `tree` box holds music in EDN — voices, measures, notes, chords, dynamics:\n`[:voice [:measure {:meter [4 4]} \"c4/1 e4 g4/2\"]]`. Shown as a score (⇄ in its header), or connected to a `freqt` shown as a score, it is drawn as notation;\nthrough `mt` boxes it is transformed (`mt transpose 7`, `mt retrograde`, `mt canon 2 7`); with\n`mt play` → `synth~` it sounds. Click a note in a score to edit it (↑ ↓ + − ← → a…g Delete), or a rest to make it a note again (Enter). See\n[Musical trees](mt.md).\n\nA `canvas`, a `freqt` and a score are resized by their bottom-right corner, as one event of the history\n(`(resize :b3 640 300)`); a double-click on the corner brings back their size. A score takes the width\nyou give it and reflows its notation; its height follows the notation.\n\n**Seeing it as geometry.** The package `@kairotic/theory` draws what sounds as music theory:\n`pcclock` a pitch-class set on the clock face (its prime form, interval vector and axes of symmetry),\n`fourier` its six Fourier coefficients (chromatic … diatonic, whole-tone), `tonnetz` the triads on the\nTonnetz and the path of the harmony. They take lists of pitches, notes one by one, or a chroma from\n`chroma~`, and their parts can be pressed (a pitch class comes out).\n\n**Drawing from messages.** A `draw [w h]` box draws the shapes that reach it — the same shapes as a\ncomponent's view: `[:circle {:cx 40 :cy 40 :r 10 :fill :accent}]`, `[:line …]`, `[:path …]`,\n`[:curve …]`, `[:text …]`, `[:group {:x :y :rotate} […]]` — or as a msg writes them: `msg :circle 40 40 10\n:accent :hit :sun`. A list replaces them all, `[:set k shape]` moves the one called k, `:clear` empties it,\nand a shape with `:hit k` sends k when it is pressed.\n\n## 7. Annotations and layers\n\n**Annotate** (above the patch) opens a bar to write on the patch: **Draw** a line by hand, an\n**Arrow**, a **Text**, **Move** a mark or **Erase** it. Moving a mark keeps the anchor of each point (a\npoint anchored to a box still follows it, from where you left it); dragging one end of a line or an\narrow moves only that end, and anchors it again to the box nearest where you let it go. Each point is anchored to the box nearest it — the mark follows the\nbox when it moves — or to the paper when no box is near; a box deleted leaves its marks where they were.\nWhat is drawn goes to a **layer** (`notes` unless you name another), over or under the boxes, shown in the\npatch view, in the presentation or in both; each mark is one event of the history and part of the code:\n\n```clojure\n(layer :notes {:z :over :show #{:patch :present}})\n(mark :notes :a1 {:kind :arrow :pts [[:b1 120 10] [:b4 -6 10]]})\n(mark :notes {:kind :text :at [:patch 300 40] :txt \"breathe\"})\n(move-mark :a1 20 -10)\n(unmark :a1)\n```\n\nA layer can also hold **projections**: the view of a box drawn again, at another size —\n`(project :b9 :viz [40 40 800 480])` puts a `monitor`, a `spectrum~` or a `tonnetz` large behind the\npresentation, drawn from what it shows (not scaled), while the box keeps its place. `(unproject :b9)`.\n\n## 8. Presentation\n\n**Present** shows only the boxes you put in the presentation — `(present :b4 x y)`, or ⌥+drag them in\npresentation mode — as a performer's panel. **Edit** goes back.\nIn presentation the paper is for playing: a double-click creates no box and nothing is selected with\nthe mouse. A plain drag plays a box (or does nothing): to move a presented box, drag it with ⌥/Alt\nheld, so a freqt, a canvas or a knob is not moved by its header or its grip by mistake.\n\nIf boxes are selected when you press **Present** and some of them are not in the presentation yet, it\nasks first: *Present the selection* puts them in it where they are in the patch (one event of the\nhistory), *Present without them* leaves them out. From the REPL: `(present-in-place :b3 :b4)`.\n\n## 9. Share and embed\n\n- In a room, everyone is in the same work.\n- **The work as a file**: the first thing in **Share/Export** (and *Download this work* in **Sessions**) saves\n the work as a `.kairotic` file — every line, its whole history and the sounds recorded — or a release of it;\n *anonymous* leaves out who made it. **Sessions → Open a file…** opens one as a new work (solo, or local\n without a database): a backup, or a way to take a work from Pages to claude.ai and back. Samples loaded from\n a URL stay references. `(export-work)`, `(export-work {:release true :anonymous true})`.\n A `.kairotic` is a zip of EDN (`manifest.edn`, `work.edn`, `lines.edn`, `history.edn`, `people.edn`) and\n `sounds/<hash>.wav` (32-bit float).\n- **Share/Export** gives a link and an iframe with this patch (or this tutorial step) for Notion, a blog or a\n course; *Release/Perform* gives a release of it that opens in Perform, showing only the panel. See [Embedding](embed.md).\n- A request to Claude can be shared in the\n [Gallery](https://github.com/bonuoq/kairotic/discussions/categories/gallery).\n\n## 10. Keys\n\n| | |\n|---|---|\n| double-click empty space | a new box (what starts with `(` is a line of the REPL) |\n| `(` on the patch | a line of the REPL, there (Enter runs it, ↑ ↓ its history, Esc closes) |\n| I | show the id of every box (hovered or selected, a box always shows it) |\n| click a box while a line of code waits for one | write its id there (`:b7`, `@b7` in a Room message) |\n| double-click a number, knob or slider | type its value (Enter applies, Esc closes) |\n| Delete / Backspace | delete the selected boxes or line |\n| ⌘/Ctrl+C · X · V · D | copy · cut · paste (where the pointer is) · duplicate the selected boxes |\n| ⌘/Ctrl+click | edit a box below it (its arguments and text) |\n| ⇧+click · a frame · ⌘/Ctrl+A | select several boxes · all |\n| Esc | deselect, or close the box editor |\n| drag the corner of a canvas, freqt or score | resize it (double-click: its default size) |\n| drag the bar beside the panel · » · ‹ | resize the panel on the right · hide it · show it |\n| space | ▶ / ■ |\n| ? or F1 | help of the selected box |\n| Ctrl+Z · Ctrl+Shift+Z · Ctrl+Y | back · forward in the history (in Perform, in the take) |\n| Ctrl+Enter | apply code (Code tab, code boxes, Claude tab) |\n| ↑ ↓ + − ← → Delete | edit the selected note of a score, or the stroke of a canvas |\n| Enter · a…g | the selected rest of a score becomes a note (a…g also re-pitches a note) |\n","es":"# Guía\n\n*[Read in English](guide.md)* · [Documentación](README.es.md)\n\nKairotic es un patcher de música —cajas unidas por líneas, como en Max o Pure Data— donde **el patch y\nsu código son la misma obra**, y cada gesto queda en una historia que puedes recorrer, ramificar y\ncompartir. Esta guía recorre la interfaz; [Conceptos](concepts.es.md) explica lo que hay detrás.\n\n## 1. Abrir una obra\n\nAbre [la app](https://bonuoq.github.io/kairotic/) (o el artefacto de Kairotic dentro de claude.ai). La\nventana **Sessions** ofrece tres entradas:\n\n- **Solo** — tus obras, guardadas (en claude.ai, en tu cuenta; en Pages, cifradas en tu navegador).\n- **Shared rooms** — una obra que todos los de la sala editan a la vez, cada gesto en la misma historia.\n- **Try locally, without saving** — un patch para jugar; no se guarda nada.\n\nUna obra solo puede copiarse a una sala y una sala a una obra solo (con su historia). **Sessions**, arriba\na la derecha, vuelve a abrir esta ventana.\n\nEn Pages, las salas se sincronizan a través de un **relay**. **Relay**, en la misma ventana, muestra los\nque se usan y si responden; una comunidad puede tener el suyo (`npx @kairotic/relay`) y elegirlo ahí, y\nlos enlaces que compartes lo llevan. Ver [Kairotic Pages](pages.es.md).\n\n## 2. Hacer un patch\n\n- **Crear una caja**: doble clic en un sitio vacío, escribe su texto —la clase y sus argumentos, como\n `osc~ 440`— y pulsa Intro. Las clases que acaban en `~` son sonido.\n- **Conectar**: arrastra desde una salida (las marcas pequeñas bajo una caja) hasta una entrada (encima\n de otra caja). No hace falta acertar en la marca: cerca de una salida se ilumina y el puntero se vuelve\n una cruz, y un cable que sueltas sobre una caja, o justo encima de una de sus entradas, llega a la\n entrada más cercana. Los cables son curvos, aquí y en el patch de un `faust~`, que funciona igual.\n- **Ids**: cada caja tiene un id (`:b7`), que es como la nombran el código, la REPL y los mensajes de Room.\n Aparece sobre su esquina superior derecha cuando pasas por encima o la seleccionas; **I** los muestra\n todos. **`(`** en el patch abre ahí una línea de la REPL (como el campo de una caja nueva cuando lo que\n escribes empieza por `(`), con el mismo editor que la REPL —sugerencias, paréntesis que se cierran—: Intro\n la ejecuta cuando sus paréntesis están equilibrados y muestra debajo lo que dio, ↑ ↓ recorren la historia\n de la REPL, Esc la cierra. Mientras una línea de código espera una caja —la REPL, la pestaña Code, esa línea, un\n mensaje de Room— tras un espacio, `(` `[` `{` o `:` (`@` en un mensaje), un clic en una caja escribe ahí su\n id en vez de seleccionarla, como un clic en una celda dentro de una fórmula de hoja de cálculo:\n `(connect ` clic, `0 ` clic, `0)`.\n- **La pestaña Code y el patch**: al seleccionar cajas, sus líneas se marcan en la pestaña Code (su caja, sus\n líneas, sus datos…) y la pestaña se desplaza hasta ellas; poner el cursor en una línea de una caja la\n selecciona (las dos cajas, en un `connect`). Las líneas de más de 160 caracteres —el código de una caja de\n código, un buffer guardado como datos— se pliegan tras su principio, diciendo cuántos caracteres ocultan; un\n clic las muestra, y se quedan así.\n- **Cajas unas encima de otras**: el tamaño real de una caja solo se sabe al dibujarla (un `faust~` crece con\n sus deslizadores, una partitura con su notación). `(overlaps)` lista las cajas que se tapan, y `(tidy)` baja\n cajas hasta que ninguna tape a otra, cada una en su columna, en un solo evento.\n- **Sondas en las conexiones**: ⌥/Alt+clic en una conexión (o `(probe :b1 0 :b2 0)`) y muestra, en su mitad, el\n último valor que pasó por ella, con un destello cuando pasa uno, y cuántos por segundo cuando llegan seguidos.\n Otra vez la quita; `(unprobe-all!)` las quita todas. Las sondas son solo de esta pestaña: no forman parte de la\n obra, ni de su historia ni de su código. Las conexiones que salen de una caja de sub-patch, y las de señal, aún\n no muestran nada.\n- **Seleccionar** una caja o una línea con un clic. **⌘/Ctrl+clic** en una caja la edita debajo (sus\n argumentos y su texto). **Supr** borra lo seleccionado.\n- **Seleccionar varias**: ⇧+clic añade una caja a la selección (o la quita); un marco dibujado desde un\n sitio vacío del papel selecciona todas las cajas que toca (con ⇧ se añaden); ⌘/Ctrl+A las selecciona\n todas. Al arrastrar una se mueven todas; Supr las borra todas.\n- **Copiar, cortar, pegar, duplicar**: ⌘/Ctrl+C copia las cajas seleccionadas, ⌘/Ctrl+X las corta, ⌘/Ctrl+V\n las pega donde está el puntero, conservando su disposición, y ⌘/Ctrl+D las duplica un poco más abajo y a la\n derecha (`(duplicate :b3 :b4)` desde código). Las cajas pegadas reciben ids nuevos y conservan sus líneas\n entre ellas, y sus líneas con cajas que no se copiaron si esas cajas están en el patch. Pegar es un solo\n evento de la historia. Lo que se copia es el código de las cajas, así que también se puede pegar en un\n mensaje o un documento; al pegar, su última línea se lee como datos y nunca se ejecuta.\n- **Mover** una caja arrastrándola. Las cajas para tocar —`bang`, `msg`, `number`, knobs— se seleccionan\n por el asa de su izquierda; su cuerpo es para tocar.\n- **Qué caja queda encima**: las cajas se dibujan en el orden en que se crearon, la más nueva encima, y\n la caja que arrastras pasa al frente, para que lo que mueves no quede nunca tapado. Es solo cómo las\n muestra tu pestaña, como la selección: no forma parte de la obra, de su historia ni de su código.\n- **Escribir un valor**: doble clic en un control numérico —un `number`, un knob (o cualquier componente\n que se arrastra para dar un número), un deslizador de una caja `faust~` o su valor— y escribe el\n número: `440`, `-3.5`, `0,5`, `3/2`. Intro lo aplica, como lo haría un arrastre (un knob lo guarda en su\n texto, dentro de su rango; un deslizador, entre su mínimo y su máximo); Esc cierra el campo y deja el\n valor como estaba. Lo que no es un número se rechaza y el campo sigue abierto.\n- **Editar el texto** de una caja: doble clic. Cajas de código (`faust~`, `script`, `component`, `tree`):\n en el patch muestran una fila de su código; con doble clic se abre el **editor de código**, una ventana\n que se mueve por su barra y cambia de tamaño por su esquina, con números de línea, sangría automática,\n paréntesis emparejados, edición estructural para Clojure (Ctrl+→ / Ctrl+← saltan entre formas, Alt+↑\n amplía la selección), búsqueda (Ctrl/⌘+F) y autocompletado. Ctrl/⌘+Intro aplica el código y deja la\n ventana abierta; Esc la cierra, preguntando antes si algo no está aplicado.\n\nUn primer patch:\n\n```clojure\n(box :b1 \"osc~ 440\" 40 40)\n(box :b2 \"gain~ 0.2\" 40 100)\n(box :b3 \"dac~ 1 2\" 40 160)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n(connect :b2 0 :b3 1)\n```\n\nPuedes hacerlo con el ratón, escribirlo en la pestaña **Code** (Run · Ctrl+Intro) o en la REPL de abajo,\nuna llamada cada vez. Las tres cosas son la misma obra: lo que dibujas aparece como código y lo que\nescribes aparece como cajas.\n\nLa pestaña Code y la REPL usan el mismo editor que las cajas de código (paréntesis que se cierran y se\nemparejan, autocompletado de los comandos). En la REPL, Intro evalúa cuando todos los paréntesis están\ncerrados —si no, empieza una línea nueva, y ⇧+Intro siempre lo hace— y ↑ ↓ recuperan lo escrito antes.\n\n**Funciones como cajas.** Una caja con el nombre de una función pura de `clojure.core` (o de\n`clojure.string`, como `str/…`) es esa función, sin escribir ningún componente: sus otras palabras son\nsus argumentos, leídos como EDN, y el mensaje que llega va al final, como con `->>`. `%` lo pone en otro\nsitio. El texto se lee como Clojure y las entradas como Max: esté donde esté escrito `%`, el mensaje es\nsiempre la **entrada izquierda, la única caliente**; los demás argumentos tienen cada uno una entrada a la\nderecha, en el orden en que están escritos, que los sustituye sin enviar nada. Un bang a la izquierda\nvuelve a enviar con el último mensaje; un resultado `nil` no envía nada.\n\n| caja | mensaje | envía | entradas |\n|---|---|---|---|\n| `into [440]` | `[1 2]` | `[440 1 2]` | el mensaje · `[440]` |\n| `conj % 440` | `[1 2]` | `[1 2 440]` | el mensaje · `440` |\n| `vector % 0 0` | `1` | `[1 0 0]` | el mensaje · `0` · `0` (un *pack*) |\n| `hash-map :freq % :amp 0.5` | `440` | `{:freq 440 :amp 0.5}` | el mensaje · `:freq` · `:amp` · `0.5` |\n| `map inc` | `[1 2]` | `[2 3]` | el mensaje · `inc` |\n| `str/upper-case` | `\"do\"` | `\"DO\"` | el mensaje |\n\nSolo hay funciones puras (`map`, `filter`, `take`, `assoc`, `sort`, `frequencies`…), así que estas cajas\nson seguras en una sala compartida; una clase con el mismo nombre (`+`, `print`) va primero.\n\n**Datos como funciones.** Como en Clojure, una keyword, un conjunto o un mapa escritos primero también\nson funciones, y el mensaje va primero, `(:freq msg)`:\n\n| caja | mensaje | envía |\n|---|---|---|\n| `:freq` | `{:freq 440 :amp 1}` | `440` — un campo de un evento |\n| `:freq 220` | `{:amp 1}` | `220` — el valor por defecto, que tiene entrada |\n| `#{60 64 67}` | `64` · `62` | `64` · nada — un filtro |\n| `{60 :c 64 :e}` | `64` | `:e` — una tabla |\n\n**Todas las entradas calientes: `^:hot`.** Escrito antes de la clase, como Clojure escribe los metadatos,\n`^:hot` hace que un argumento nuevo envíe enseguida con el último mensaje (`nil` antes del primero), como\n`pak` en Max: `^:hot vector % 0 0`.\n\n**Sobre un flujo: `xf/`.** `xf/` delante de una función convierte su *transductor* en una caja con\nmemoria: recorre los mensajes que llegan uno a uno, no una colección, y lo que deja pasar sale mensaje a\nmensaje.\n\n| caja | hace |\n|---|---|\n| `xf/partition-all 4` | junta 4 mensajes y los envía como un vector |\n| `xf/partition 4 1` | los últimos 4 en cada mensaje (una ventana deslizante) |\n| `xf/dedupe` | deja pasar un mensaje solo cuando cambia |\n| `xf/take 1` | solo el primer mensaje (un bang también es un mensaje) |\n| `xf/filter odd?`, `xf/map inc`, `xf/mapcat reverse`… | como en Clojure, mensaje a mensaje |\n\n`:flush` lo completa (`partition-all` envía lo que guarda) y vuelve a empezar, `:clear` vuelve a empezar\nsin enviar, y un argumento nuevo a la derecha también vuelve a empezar. La ayuda de cada una de estas cajas\n(**?**) enlaza a su página de [clojuredocs.org](https://clojuredocs.org) y a la referencia de\n[clojure.org](https://clojure.org/reference/transducers).\n\n**Elegir un camino: `dispatch`.** `dispatch n` envía lo que llega por la izquierda por una de sus n salidas,\nnumeradas desde 0 como todos los puertos. La entrada derecha elige: `msg 1` (salida 1), `msg nil` o\n`msg false` (cerrado: no sale nada), `msg true` (salida 0, así que `dispatch 1` es una puerta que se abre y se\ncierra). Una función elige para cada mensaje, y nil no lo deja pasar por ninguna: un mapa `{60 0 64 1}`, una\nkeyword `:to` (el camino escrito en el evento), un nombre o una forma (`even?`, `(comp …)`); un conjunto\ndeja pasar a sus miembros por la salida 0. El selector puede escribirse después de n:\n`dispatch 2 {60 0 64 1}`. Su nombre viene de la *dispatch function* de los multimétodos de Clojure,\nque mira un valor y elige adónde va.\n\n**Funciones por los cables.** Una función viaja como su forma, datos EDN. `comp`, `partial`, `juxt`,\n`complement`, `fnil`, `constantly`, `every-pred` y `some-fn` son cajas que envían una con un bang:\n`comp inc (partial * 2)` envía `(comp inc (partial * 2))`. Allí donde una caja toma un argumento, un\nnombre o una forma así *es* esa función, de modo que una forma enviada a la entrada de `inc` en `map inc`\ncambia la función en directo (igual con `xf/filter odd?` o `sort-by :freq`). Las formas también se pueden\nescribir en una caja y anidar: `map (partial * 2)`, `map (juxt inc dec)`. Con `%`, un constructor toma la\nfunción que llega: `comp % inc`. De una forma solo se hacen estas funciones puras (y `+ - * /`), y cada\nnavegador la reconstruye a partir de ellas, así que es tan segura en una sala compartida como cualquier\nargumento; un nombre que no conoce (o una llamada como `(inc 1)` en lugar de una función) no se envía y se\nescribe en el REPL. Para enviar una función por su nombre, un `msg` con el nombre: `msg inc` (una\nkeyword, `msg :inc`, sigue siéndolo: una clave, y una función por sí misma).\n\n## 3. Sonido y tiempo\n\n- **▶** (o la barra espaciadora) pone en marcha el sonido y el tiempo: audio, `metro`, `ramp`,\n `loadbang`, `mt play`. El primer ▶ también pide permiso al navegador para sonar.\n- **■** silencia y devuelve cada caja a su estado inicial.\n- **`print`** escribe en el REPL lo que le llega, tras su etiqueta: `print out0` escribe `out0: 60` (sin\n ella, `print: 60`); un string tal cual, lo demás como EDN. Para dar forma al texto, **`format`** delante,\n como el de Clojure (el printf de Java): `format \"%.1f Hz\"` envía `\"440.1 Hz\"`, `apply format \"%s Hz · %.1f dB\"`\n rellena varios desde una lista — `%s`, `%d`, `%.2f`, `%e`, `%x`, anchos (`%5.1f`, `%-8s`, `%03d`) y `%%`.\n- Los mensajes viajan sin ▶: un clic en un `bang` o un `msg`, un número arrastrado, una caja de datos\n que cambió.\n- Un `msg` envía lo que lleva escrito, leído como en Clojure: números (`msg 0 8 4`), **keywords con sus\n dos puntos** (`msg :stop`, `msg :rec 4`), **nombres** (`msg inc`: una función allí donde una caja toma\n una; también texto libre como una nota `e4`, un ratio `6/5`, una URL o una dirección OSC), `true`,\n `false`, `nil`, **texto entre comillas como cadena** (`msg \"https://…/voz.ogg\"`, `msg \"dos palabras\"`) y\n formas EDN (`msg [0 4 7]`, `msg {:freq 440}`), solos o en una lista (`msg :url \"github:…\" 3`). Una\n palabra sin sus dos puntos es un nombre, no una keyword: `msg stop` no para un `metro`, `msg :stop` sí.\n- **Síntesis estocástica**: `gendy~ 110` (en `@kairotic/synth`) es un oscilador a partir del GENDY de\n Xenakis: una onda de puntos de quiebre cuyas amplitudes y duraciones hacen paseos aleatorios ciclo a\n ciclo — una altura que deriva, un timbre que no deja de cambiar. `[:x-step 40]` deja vagar la altura,\n `[:y-step 0.2]` el timbre; una señal en su entrada modula su frecuencia. Su patch de ayuda tiene cuatro\n pasos.\n- **Faust como patch** (Estudio 31, `@kairotic/faust-units`): el código de un `faust~` se abre junto a su\n caja con su **patch** a la izquierda, el mismo código como elementos de Faust —primitivas (`+ * ' @ sin\n select2`…), controles (`hslider button`…), funciones de librería (`os.osc fi.lowpass en.adsr`…), `in` y\n `out`—. Doble clic en el papel para una caja nueva (un nombre, un número o cualquier expresión de Faust,\n que se queda como caja de código), arrastra de una salida a una entrada, Supr borra. Editar el patch\n reescribe el código de al lado y editar el código redibuja el patch; Ctrl/⌘+Enter o Aplicar lo aplica,\n como siempre. Un bucle debe pasar por el retardo de una muestra `'` (en código, `~`). El código que las\n cajas no pueden leer sigue sonando, con el patch marcado como desactualizado. **Patch** en la barra de la\n ventana lo oculta. La ventana se abre junto a la caja, para que sus parámetros sigan a la vista en el patch.\n- **Una receta a partir de un sonido** (Estudio 35): **Recipe** en la barra de la ventana de un `faust~`\n busca los valores de sus sliders que suenan más cerca de un sonido: una caja sample del patch o un\n archivo de sonido. Toca el código sin conexión, una nota de un segundo (un botón `gate`, si lo hay,\n pulsado 0,65 s), muchas veces: primero ajustes al azar, luego una búsqueda que escucha como `features~`,\n con la altura oída como la oye `pitch~` y fijada, en un slider llamado `pitch`, `key`, `note` o `midi`\n (MIDI) o `freq` (Hz). *quick* lo toca unas 200 veces, *careful* unas 450; **Stop** la detiene. Los\n valores encontrados se escriben en el código, cada slider empezando ahí: editado, no aplicado, así que\n Ctrl/⌘+Enter los aplica como un solo evento y la caja los muestra en sus parámetros. **▶ sound** y\n **▶ found** tocan el segundo que escuchó y lo que encontró. Compara timbres con independencia del\n volumen; una escala logarítmica donde el código dice `[scale:log]` le ayuda.\n- **Los descriptores como partitura: `realize~`** (Estudio 37, `@kairotic/analysis`): una caja delante de\n un `faust~` que lo toca a partir de cuatro descriptores: **sonoridad** (dB, o un nivel 0…1 como el `rms`\n de `features~`), **brillo** (el centroide espectral, Hz), **ruido** (la planitud espectral, 0…1) y\n **altura** (Hz como los envía `pitch~`, 0 si no hay; MIDI con `realize~ midi`). El slider `pitch` o `freq`\n del `faust~` toma la altura, su slider `gain` la sonoridad, y los demás sliders toman los ajustes de ese\n `faust~` que suenan más cerca del brillo y el ruido escritos. Para conocerlos **aprende** el `faust~` al\n que llega su salida izquierda: cuando llegan los primeros valores (o con `:learn`, tras cambiar su código)\n toca unos cientos de ajustes estables sin conexión y los escucha. Lo que entra pueden ser `features~` y\n `pitch~` de otro sonido —cantas, y un sintetizador sigue tu sonoridad, brillo, ruido y altura con su\n propio sonido— o curvas dibujadas en canvas leídos con `reader~` y `snapshot~`. Su salida derecha dice lo\n lejos que está el ajuste más cercano de lo escrito (por encima de 1, el `faust~` no puede sonar así: un\n ruido tan oscuro como un tono, por ejemplo); un `monitor` muestra lo escrito junto a lo que `features~`\n oye en el resultado. Puede **escuchar lo que toca**: un `features~ 20` sobre el `faust~`, con sus tres\n salidas (rms, centroid, flatness) en las tres últimas entradas de `realize~`, y pide más donde lo que se oye\n se queda corto de lo escrito, poco a poco y con límites; la sonoridad pasa a ser el nivel tal como lo oye\n `features~`.\n- **Faust a varias voces**: un `faust~` cuyo código declara `declare options \"[nvoices:8]\";` es\n polifónico. Su voz usa `freq`, `gain` y `gate`, que se fijan nota a nota; los Hz van a su entrada\n izquierda y los ids de voz a la derecha, como con `synth~` (un `keyboard` 0→0, 1→1, 3→0; `mt play`\n 0→0, 1→1), en cualquier afinación; `effect = …;` en el mismo código se aplica a la suma de las voces.\n Su patch de ayuda lo muestra.\n- **Sonido de fuera**: `adc~ 1` es el micrófono (o una entrada de la tarjeta de sonido: `adc~ 1 2`). Al\n pulsar ▶ el navegador lo pide una vez; su sonido llega tal cual, sin el procesado pensado para\n llamadas. `scope~` dibuja una señal y `snapshot~ 50 db` la convierte en números (su nivel), para que\n lo que se oye mueva el patch. Usa auriculares antes de enviar un `adc~` a `dac~`: se realimenta.\n- **Grabar**: una caja `sample` graba lo que le llega con `:rec` hasta `:stop` (o hasta su duración:\n `sample 10`), y un `reader~` con el sample a su derecha lo reproduce en la posición de su izquierda, en\n segundos —o, como `reader~ norm`, de 0 a 1: un `phasor~` directo, con `!/ 1` convirtiendo su duración (su\n outlet izquierdo) en la velocidad del phasor~—; cualquier otra velocidad lo toca más rápido, más lento o\n al revés. Todo reader y reader~ lee así: en las unidades de su buffer (el eje X de un canvas, el tiempo de\n un freqt, segundos), o de 0 a 1 con `norm`. El sonido se queda en este navegador; la obra\n guarda su dibujo, así que una obra abierta en otro sitio lo muestra y dice que no está.\n `(load-sound! :bN)` trae un archivo, `(save-sound :bN)` lo guarda como WAV. Un sonido **desde una\n URL** — `(load-sound! :bN \"https://…/voz.ogg\")`, una cadena enviada al sample o\n `(sample! :bN {:url \"…\"})` en el código — lo descarga cada navegador que abre la obra, así que una\n sesión compartida o un enlace tienen los mismos sonidos en todas partes (una URL de otro sitio debe\n permitirlo: CORS). Dos fuentes funcionan siempre: `github:dueño/repo@ref/ruta.wav`, cualquier archivo\n de un repositorio público de GitHub, servido por jsDelivr (por ejemplo los bancos de\n [Dirt-Samples](https://github.com/tidalcycles/Dirt-Samples): `github:tidalcycles/Dirt-Samples@master/bd/BT0A0A7.wav`),\n y `freesound:id`, un sonido de [Freesound](https://freesound.org) con tu propia clave de API, guardada\n solo en tu navegador (`(freesound-key! \"…\")`, en freesound.org/apiv2/apply). `(sounds \"lluvia\" {:max 10})`\n busca en Freesound y escribe la línea que carga cada resultado; un sonido de Freesound guarda su autor\n y su licencia, y `(credits)` los lista para la obra.\n- **Escuchar**: el paquete `@kairotic/analysis` (llega a la obra al escribir una de sus clases)\n convierte lo que se oye en datos: `pitch~` la altura por YIN (Hz, y 0 cuando deja de oír una),\n `onset~` un bang en cada ataque, `chroma~` las 12 clases de altura y la más fuerte,\n `features~ rms centroid flatness …` descriptores (con Meyda), y `spectrum~` dibuja el espectro.\n `monitor 6 rms centroid chroma` dibuja lo que llega a sus entradas en los últimos 6 segundos, un carril\n por entrada: los números como líneas, las listas (chroma, mfcc) como franjas, los bangs y las palabras\n como marcas.\n `form~` compara cada momento con los demás (una matriz de autosimilitud de un chroma o un mfcc, dibujada):\n un bang donde empieza una sección, el periodo que se repite y un `[:segment …]` que hace que `onset~` empiece de nuevo.\n `transcribe` escribe lo que oye `pitch~` en un `freqt` — `:rec`, tocar, `:stop` — como notas a su\n altura o, con `transcribe 60 glide`, como contornos que siguen la voz (un `onset~` a su derecha separa\n las notas repetidas); el freqt visto como partitura la muestra en notación, y una caja `quantize` (la\n segunda salida del freqt en su entrada derecha, un bang) la escribe en compases como árbol, para una caja\n `tree` — con el compás, las divisiones y las demás opciones que le des, y `:time :track` para una frase\n cantada libremente.\n- **Grabar un gesto**: `record [lo hi]` escribe cualquier flujo de números en un `canvas` como trazos en\n el tiempo — un knob, una envolvente (`snapshot~ 50 rms`), un descriptor (`features~ 20 centroid`) —:\n `:rec`, tocar, `:stop`. Un valor se mantiene hasta el siguiente; los ejes siguen a la toma. Se edita\n como cualquier dibujo y se vuelve a leer con `phasor~` → `reader~ norm` como automatización.\n- **Grabar desde un punto**: `:rec t` (`msg :rec 4`) en un `sample`, `record` o `transcribe` conserva lo\n que había antes de t (segundos; pulsos en transcribe) y graba desde t, sustituyendo lo que venía\n después: un punch-in. `:ovr t` (`msg :ovr 4`; `:ovr` solo, desde 0) sobrescribe solo lo que cubre la\n toma, de t a donde se para, y conserva lo que venía después: un punch-in/out. Un canvas o freqt acepta\n `[:cut t]` para eso (todo desde t) y `[:cut t1 t2]` (lo que hay entre ambos; un trazo que lo cruza se\n parte en dos).\n- **Un tramo de tiempo con cabezales**: un `ring [segundos]` guarda los mensajes de los últimos segundos,\n cada uno en su tiempo; su cabezal de escritura da la vuelta como uno de cinta. Un `reader` en su salida\n derecha es un cabezal propio: `reader d 1` sigue al cabezal del ring 1 s por detrás —un canon, un\n delay—; dos lectores, un canon a tres voces; `reader d 1 speed 0.5`, una aumentación; a −1 vuelve atrás\n por lo escrito. Un número en la izquierda de un reader lo mueve en su lugar (una rampa, un counter), en\n cualquier sentido; un movimiento mayor que su `jump` es un salto. Un `writer` (lo que escribe · el buffer\n del ring · una posición) escribe donde está, desde cualquier fuente, borrando lo que pasa (o `writer\n mix`, dejándolo); `:rec t` / `:ovr t` lo llevan a t a velocidad 1. Un reader que entra en un writer del\n mismo ring es una realimentación: un canon perpetuo.\n- **Lo mismo con sonido**: `ring~ [segundos]` guarda los últimos segundos del sonido de su izquierda (sin\n nada ahí, su cabezal no escribe: el ring es lo que escriben sus `writer~`). Un `reader~` en su salida\n derecha sin señal de posición sigue a su cabezal: `reader~ d 1` un delay, `reader~ d 1 speed 0.5` una\n octava abajo y quedándose atrás, `speed -1` al revés; una `d` nueva (`msg :d 0.25`) se desliza, doblando\n la altura, o salta con un fundido. Con una señal de posición lee ahí (segundos; `norm`: 0…1, un\n `phasor~`). Un `writer~` (sonido · el buffer del ring~ · una señal de posición) escribe como un cabezal de\n cinta: `ovr` sustituye, también con silencio; `writer~ mix 0.8` suma, conservando lo que había por 0,8.\n Hasta 8 cabezales comparten el único nodo del ring~, así que una realimentación dentro de él es exacta (a\n través de otras cajas cuesta un bloque de 128 muestras). Un `faust~` entre un `reader~` y un `writer~` del\n mismo ring~ (`reader~ → faust~ → writer~`) corre dentro del nodo del ring, muestra a muestra: el bucle sigue\n siendo exacto, así que una d corta con un paso bajo en el bucle es una cuerda pulsada (estudio 49).\n\n## 4. La historia\n\nCada gesto es un evento de la historia, abajo en la página.\n\n- **Ctrl+Z** va atrás, **Ctrl+Mayús+Z** (o Ctrl+Y) adelante; o haz clic en cualquier punto de la historia.\n- Hacer algo después de volver atrás crea una **rama**: no se pierde nada.\n- **Merge…** trae aquí los eventos de otra rama, cuando no chocan.\n- En una sala, los gestos de los demás llegan a la misma historia; *Follow the front* te mantiene en el\n punto más nuevo.\n- **◆ Snapshot** —`(snapshot)`, o `(snapshot \"intro\")` con un nombre— escribe un fotograma clave: un\n punto de la historia con la obra tal como está ahora. Se dibuja como un cuadrado.\n\n### Líneas\n\nUna obra puede tener varias **líneas**: historias independientes, cada una en una pestaña sobre el patch.\nLa línea principal (★) es la obra como siempre fue; las otras son estudios, bocetos, partes — cada una con\nsu propio patch, sus propias ramas, fusiones y snapshots.\n\n- **+** crea una línea nueva, vacía — `(new-line \"boceto\")`. Un clic en una pestaña pone su línea en\n pantalla — `(go-line \"boceto\")`; cada pestaña vuelve al punto donde la dejaste.\n- Doble clic en la pestaña en pantalla para renombrarla — `(rename-line \"intro\")`; **×** la archiva (se\n guarda, con su historia, y vuelve desde *archived* — `(restore-line \"boceto\")`). `(work-lines)` las lista.\n- La línea en pantalla es aquella con la que trabajan el patch, Perform, Share/Export, Release y Claude.\n- El motor toca la línea donde pulsaste ▶ (su pestaña también muestra ▶): cambiar de pestaña no lo para, y el\n transporte dice qué línea suena. Los mensajes de la pestaña en pantalla siguen viajando; sus cajas de audio\n callan hasta que pulsas ▶ en ella, que la convierte en la línea que suena. En una sala, las posiciones de los demás se dibujan solo en la\n línea en la que están; seguir a alguien a otra línea abre su pestaña.\n- Las líneas no cambian mientras tocas en Perform, en una lección o en el patch de pruebas.\n\n**Una línea dentro de otra.** `patch @nombre` usa la línea llamada *nombre* como subpatch (los espacios de su\nnombre se escriben `-`: `patch @linea-de-bajo`); sus cajas `inlet` / `outlet` son los puertos de la caja. Doble\nclic abre la línea en su pestaña.\n\n- **Sigue** la línea (↻): es la línea en su punto más nuevo, así que cambia cuando la línea avanza, para todas\n las cajas que la usan. `(pin-ref :b3)` la **fija** en el punto que lee ahora (⌖ y ese momento);\n `(follow-ref :b3)` vuelve a seguirla. Una línea no puede contenerse a sí misma, ni a una línea que la usa.\n- Mientras tocas en Perform, las líneas seguidas se quedan donde estaban al empezar. Un snapshot guarda dónde\n están, y su punto las toca así: volviendo atrás en la historia, un punto posterior a un snapshot oye las líneas\n como eran entonces (en el punto más nuevo, como son ahora).\n- Dentro de una línea usada así, `adc~` y `dac~` callan: suenan cuando la línea suena sola (su propio ▶), así\n que una línea se puede probar con su propia entrada y salida. El sonido entra y sale por `inlet~` / `outlet~`;\n la caja avisa (⚠) cuando su línea tiene `dac~` y ningún `outlet~`, o `adc~` y ningún `inlet~`.\n- Renombrar una línea reescribe las cajas en pantalla que la usan; las de otras partes la siguen encontrando por\n su nombre anterior.\n- Mientras la línea que suena usa la línea en pantalla (y su pestaña está en su punto más nuevo), la pestaña la\n muestra donde suena, y lo que tocas ahí va a todas las cajas que la usan (el transporte dice ×2, ×3…). Para\n tocar una sola, toca la línea que la usa.\n- El inspector de una caja patch (⌘/Ctrl+clic) tiene lo que puede hacer con las líneas: un patch embebido se\n puede **extraer** a una línea nueva, con la historia que tenía dentro de la caja — `(extract-line :b3\n \"filtros\")`; un `patch @nombre` se puede fijar, seguir, abrir o **incrustar** — `(inline-ref :b3)`: una copia de\n su línea dentro de la caja, separada de ella.\n- Un enlace (Share/Export) o un release lleva **una sola línea**: cada `patch @nombre` pasa a ser un patch\n embebido con su línea tal como suena ahí — en cada fotograma clave de un release, como lo guardó el snapshot.\n\n### Componer y tocar (Compose y Perform)\n\nComponer es el modo habitual: cada cambio en la obra es un punto de la historia. **Perform** abre un\ntiempo propio para ensayar, probar e improvisar con la obra: lo que cambias forma una *toma* que parte\nde donde estás y queda fuera de la historia (el patch tiene un marco rojo mientras tocas).\n\n- Ctrl+Z / ◀ deshacen tus últimos cambios de la toma; ▶ los rehace.\n- Un snapshot en Perform escribe en la historia la toma hasta ahí, y la toma sigue desde ese punto.\n- Pulsar otra vez **Perform** vuelve a Compose: *Keep it as a new point* escribe la toma como una rama\n desde donde empezó (cerrada por un cuadrado relleno), *Discard* vuelve a donde estabas.\n- En una sala, quienes tocan desde el mismo punto de la historia tocan la misma toma: una **jam**. Solo\n ellos reciben los cambios de los demás; al resto se le invita a unirse.\n- Desde la REPL: `(perform)`, `(compose)`, `(compose :keep)`, `(compose :discard)`, `(jam \"id\")`.\n Perform y Present son independientes: puedes tocar con el patch entero o con el panel.\n\n### Presets: fotogramas clave para recuperar, transformar y generar\n\nCada fotograma clave —un snapshot, o una toma guardada desde Perform— es también un **preset** de la\nobra: el texto de cada caja en ese momento (sus argumentos, y los valores que los controles guardan en\nél: un knob, una envolvente, un pad), con los subpatches incluidos. Una caja `presets` los toca:\n\n- Un número o una etiqueta en su entrada izquierda —`2`, `intro`— **recupera** ese fotograma: cada caja\n que también está allí toma el texto que tenía entonces, como un solo evento de la historia (un Ctrl+Z\n lo deshace). Las cajas añadidas o quitadas desde entonces, las líneas y los búferes quedan como están.\n- Una posición en su entrada derecha **transforma** (morph): `1.5` lleva los controles a medio camino\n entre el primer fotograma y el segundo. Se mueven como mensajes, igual que al arrastrarlos (en vivo, y\n se tocan en una jam), y no se escribe nada hasta `:keep`. Un knob que conduce el morph no se mueve con él.\n- Un **bang** genera un preset nuevo a partir de lo que cambia y lo que permanece: lo que es igual en\n todos los fotogramas se queda; un número que cambia toma un valor dentro de su rango (geométrico en un\n knob `log`, entero si siempre lo fue); una palabra que cambia es una de las suyas. `[:generate 42]` da\n siempre el mismo preset; haz un snapshot para guardarlo como un fotograma más.\n- Su salida envía los valores de los controles que ha cambiado, `{:b3 0.5 :b5 880}`.\n- Los fotogramas se numeran por orden de momento, igual en todas las pestañas de una sala.\n `presets intro verse` usa solo esos snapshots, en ese orden.\n- Desde la REPL, con todos los fotogramas de la obra: `(keyframes)`, `(recall 2)`, `(recall \"intro\")`,\n `(morph 1 2 0.5)`, `(morph :keep)`, `(generate)`, `(generate 42)`. En Perform, todo va a la toma,\n como cualquier cambio.\n- El tutorial *Presets: recuperar, transformar, generar* (Help → tutoriales, o `(tutorial \"presets\")`)\n lo recorre todo con un sintetizador FM.\n\n### Release, y puntos olvidados\n\nLos fotogramas clave viven en la historia, y el código del patch, un enlace o una inserción solo llevan el\npatch. Para que los presets viajen, una caja `presets` puede **guardarlos**: `(store-presets! :b18)` copia en\nella los fotogramas que usa, solo lo que cambia entre ellos. Una caja que guarda presets los usa en lugar de\nla historia, y el código de la obra los escribe como `(presets! :b18 […])`, así que van adonde vaya el\npatch. `(presets! :b18 nil)` los olvida.\n\n- **Release…** (en la barra de la historia), o `(release)`, hace una **obra nueva** con una historia\n compacta: un punto por fotograma, con su etiqueta, cada uno escrito como los cambios desde el anterior, y\n después la obra tal como está. Cada caja presets guarda en ella sus presets. La obra de la que partes\n queda como estaba, con toda su historia.\n- En una obra solo o local puedes **olvidar puntos**: ⇧+clic sobre ellos en la historia, y luego\n **Forget…**. La obra en esos momentos se pierde (y un snapshot que hubiera allí con ella), y los momentos\n posteriores quedan exactamente como están. No se pueden olvidar la punta de una rama ni un punto donde\n empieza una rama, y en una sala compartida la historia es de todos: allí el camino hacia una versión\n compacta es un release. Desde la REPL: `(forget-points [[\"segmento\" 3] …])`.\n\n## 5. Las pestañas de la derecha\n\nEl panel de la derecha puede dejar sitio al patch: **»** en su cabecera (o **›** en la barra entre ambos)\nlo oculta, y **‹** lo devuelve; pedir una pestaña —**?** o F1 sobre una caja, `(docs …)`, un tutorial—\ntambién lo muestra. Arrastra la barra entre el patch y el panel para darle otro ancho; un doble clic en\nla barra lo oculta o lo muestra. Este navegador recuerda cómo lo dejaste. Desde la REPL:\n`(side-panel false)`, `(side-panel true)`, `(side-panel 480)`, `(side-panel :auto)`.\n\n- **Code** — la obra como **Calls** (llamadas: `box`, `connect`, …), editable: Ctrl/⌘+Enter las ejecuta y\n reconstruye el patch. **Data** muestra la misma obra como datos (EDN): el estado que produce la\n historia, todas las claves de todas las cajas, en solo lectura, para inspeccionarlo (plegado y búsqueda\n con Ctrl/⌘+F). Lo que hayas editado sin ejecutar sigue en las llamadas mientras miras los datos.\n- **Components** — las clases que conoce esta obra. Las cajas que las definen (`component`) se guardan\n aquí, no en el patch, porque no tienen entradas ni salidas: **New component**, **Edit** (su código en\n la ventana de código), **Publish**, ×; un clic en una fila la elige para que Claude la cambie. Importa\n las publicadas, o usa las de la biblioteca compartida.\n- **Claude** — Claude hace un patch (o cambia el abierto), o escribe un componente, a partir de lo que\n describes. Ver [Pedírselo a Claude](ask.es.md).\n- **Help** — esta **documentación** (guía, conceptos, temas, referencia), una página para cada clase,\n entrada por entrada, con un patch de ayuda (algunas tienen varios pasos, un uso cada uno, que ◀ ▶\nrecorren como un tutorial), y los **tutoriales**. Selecciona una caja y pulsa **?** (o\n F1) para ver su página; `(docs \"concepts\")` en la REPL abre una página de la documentación.\n\n- **Feedback** — durante la alfa: cuenta qué falla, propón una idea o haz una pregunta. Escribe por ti\n un issue de GitHub, con el patch en pantalla, los errores recientes y tu navegador si quieres; tú lo\n publicas en GitHub. Se listan los issues abiertos, para sumarte a uno en vez de escribirlo dos veces.\n\n## 6. La música como datos\n\nUna caja `tree` guarda música en EDN —voces, compases, notas, acordes, dinámicas:\n`[:voice [:measure {:meter [4 4]} \"c4/1 e4 g4/2\"]]`. Mostrada como partitura (⇄ en su cabecera), o conectada a un `freqt` mostrado como partitura, se dibuja como partitura;\na través de cajas `mt` se transforma (`mt transpose 7`, `mt retrograde`, `mt canon 2 7`); con\n`mt play` → `synth~` suena. Haz clic en una nota de una partitura para editarla (↑ ↓ + − ← → a…g Supr), o en un silencio para volverlo nota (Intro). Ver\n[Árboles musicales](mt.es.md).\n\nUn `canvas`, un `freqt` y una partitura se redimensionan desde su esquina inferior derecha, como un evento\nde la historia (`(resize :b3 640 300)`); un doble clic en la esquina les devuelve su tamaño. Una partitura\ntoma el ancho que le das y redistribuye su notación; su altura sigue a la notación.\n\n**Verla como geometría.** El paquete `@kairotic/theory` dibuja lo que suena como teoría musical:\n`pcclock` un conjunto de clases de altura en la esfera del reloj (su forma prima, su vector interválico\ny sus ejes de simetría), `fourier` sus seis coeficientes de Fourier (cromático … diatónico, de tonos\nenteros), `tonnetz` las tríadas en el Tonnetz y el camino de la armonía. Reciben listas de alturas,\nnotas de una en una o un chroma de `chroma~`, y sus partes se pueden pulsar (sale una clase de altura).\n\n**Dibujar a partir de mensajes.** Una caja `draw [w h]` dibuja las figuras que le llegan —las mismas que\nla vista de un componente: `[:circle {:cx 40 :cy 40 :r 10 :fill :accent}]`, `[:line …]`, `[:path …]`,\n`[:curve …]`, `[:text …]`, `[:group {:x :y :rotate} […]]`— o como las escribe un msg: `msg :circle 40 40\n10 :accent :hit :sun`. Una lista las sustituye todas, `[:set k figura]` mueve la llamada k, `:clear` la\nvacía, y una figura con `:hit k` envía k cuando se pulsa.\n\n## 7. Anotaciones y capas\n\n**Annotate** (encima del patch) abre una barra para escribir sobre el patch: **Draw** una línea a mano,\nuna flecha (**Arrow**), un texto (**Text**), mover una marca (**Move**) o borrarla (**Erase**). Mover una\nmarca mantiene el ancla de cada punto (un punto anclado a una caja la sigue siguiendo, desde donde lo\ndejas); arrastrar un extremo de una línea o una flecha mueve solo ese extremo, y lo ancla de nuevo a la\ncaja más cercana al soltarlo. Cada punto se ancla a la caja más\ncercana —la marca la sigue cuando se mueve— o al papel si no hay ninguna cerca; una caja borrada deja sus\nmarcas donde estaban. Lo dibujado va a una **capa** (`notes` si no nombras otra), encima o debajo de las\ncajas, visible en el patch, en la presentación o en ambos; cada marca es un evento de la historia y parte\ndel código:\n\n```clojure\n(layer :notes {:z :over :show #{:patch :present}})\n(mark :notes :a1 {:kind :arrow :pts [[:b1 120 10] [:b4 -6 10]]})\n(mark :notes {:kind :text :at [:patch 300 40] :txt \"respira\"})\n(move-mark :a1 20 -10)\n(unmark :a1)\n```\n\nUna capa también puede tener **proyecciones**: la vista de una caja dibujada otra vez, a otro tamaño —\n`(project :b9 :viz [40 40 800 480])` pone un `monitor`, un `spectrum~` o un `tonnetz` en grande detrás\nde la presentación, dibujado a partir de lo que muestra (no escalado), mientras la caja sigue en su\nsitio. `(unproject :b9)`.\n\n## 8. Presentación\n\n**Present** muestra solo las cajas que has puesto en la presentación —`(present :b4 x y)`, o\narrastrándolas con ⌥ en modo presentación— como un panel para quien toca. **Edit** vuelve.\nEn presentación el papel es para tocar: un doble clic no crea cajas y no se selecciona nada con el\nratón. Un arrastre normal toca la caja (o no hace nada): para mover una caja presentada, arrástrala\ncon ⌥/Alt pulsada, así un freqt, un canvas o un knob no se mueven por error desde su cabecera o su asa.\n\nSi hay cajas seleccionadas al pulsar **Present** y alguna aún no está en la presentación, primero\npregunta: *Present the selection* las pone en ella donde están en el patch (un evento de la historia),\n*Present without them* las deja fuera. Desde la REPL: `(present-in-place :b3 :b4)`.\n\n## 9. Compartir e insertar\n\n- En una sala, todos están en la misma obra.\n- **La obra como archivo**: lo primero de **Share/Export** (y *Download this work* en **Sessions**) guarda la obra\n como un archivo `.kairotic` — cada línea, toda su historia y los sonidos grabados — o un release de ella;\n *anonymous* deja fuera quién la hizo. **Sessions → Open a file…** abre uno como una obra nueva (solo, o local\n sin base de datos): una copia de seguridad, o una manera de llevar una obra de Pages a claude.ai y al revés. Los\n samples cargados desde una URL quedan como referencias. `(export-work)`, `(export-work {:release true :anonymous true})`.\n Un `.kairotic` es un zip de EDN (`manifest.edn`, `work.edn`, `lines.edn`, `history.edn`, `people.edn`) y\n `sounds/<hash>.wav` (float de 32 bits).\n- **Share/Export** da un enlace y un iframe con este patch (o este paso de tutorial) para Notion, un blog o un\n curso; *Release/Perform* da un release que se abre en Perform, mostrando solo el panel. Ver [Insertar](embed.es.md).\n- Una petición a Claude se puede compartir en la\n [Gallery](https://github.com/bonuoq/kairotic/discussions/categories/gallery).\n\n## 10. Teclas\n\n| | |\n|---|---|\n| doble clic en un sitio vacío | una caja nueva (lo que empieza por `(` es una línea de la REPL) |\n| `(` en el patch | una línea de la REPL, ahí (Intro la ejecuta, ↑ ↓ su historia, Esc la cierra) |\n| I | mostrar el id de todas las cajas (una caja lo muestra siempre al pasar por encima o seleccionada) |\n| clic en una caja mientras una línea de código espera una | escribir ahí su id (`:b7`, `@b7` en un mensaje de Room) |\n| doble clic en un number, knob o deslizador | escribe su valor (Intro lo aplica, Esc cierra) |\n| Supr / Retroceso | borra las cajas o la línea seleccionadas |\n| ⌘/Ctrl+C · X · V · D | copiar · cortar · pegar (donde está el puntero) · duplicar las cajas seleccionadas |\n| ⌘/Ctrl+clic | edita una caja debajo de ella (sus argumentos y su texto) |\n| ⇧+clic · un marco · ⌘/Ctrl+A | selecciona varias cajas · todas |\n| Esc | deselecciona, o cierra el editor de la caja |\n| arrastrar la esquina de un canvas, freqt o partitura | la redimensiona (doble clic: su tamaño por defecto) |\n| arrastrar la barra junto al panel · » · ‹ | redimensiona el panel de la derecha · lo oculta · lo muestra |\n| espacio | ▶ / ■ |\n| ? o F1 | ayuda de la caja seleccionada |\n| Ctrl+Z · Ctrl+Mayús+Z · Ctrl+Y | atrás · adelante en la historia (en Perform, en la toma) |\n| Ctrl+Intro | aplica código (pestaña Code, cajas de código, pestaña Claude) |\n| ↑ ↓ + − ← → Supr | edita la nota seleccionada de una partitura, o el trazo de un canvas |\n| Intro · a…g | el silencio seleccionado de una partitura se vuelve nota (a…g también cambia la altura de una nota) |\n"},"concepts":{"en":"# Concepts\n\n*[Leer en castellano](concepts.es.md)* · [Documentation](README.md)\n\n## A work is data\n\nA work is a **patch**: boxes and the lines between them, written as data (EDN).\n\n```clojure\n{:boxes {:b1 {:text \"osc~ 440\" :x 40 :y 40}\n :b2 {:text \"dac~ 1 2\" :x 40 :y 100}}\n :lines [[:b1 0 :b2 0]]} ; from :b1 outlet 0 to :b2 inlet 0\n```\n\nA box's **text** is its class (the first word) and its arguments. Some boxes also keep **data** —\nthe strokes of a canvas, the source of a code box, the tree of a `tree` box — and a place in the\n**presentation**. Ports are numbered from 0, left to right.\n\nThe patch and its **code** are the same work: every gesture is a call (`box`, `connect`, `move`,\n`text!`, `stroke`, `tree!`…), and the Code tab writes the whole work as those calls. Drawing writes\ncode; writing code draws.\n\n## The history is a tree\n\nEvery gesture is an **event**. Events form a **history**, a tree: going back and doing something else\nmakes a branch; two gestures at the same time (within the *simultaneity*, 1.5 s by default) make two\nbranches. Nothing is overwritten.\n\n- The **front** is the newest point; in a room, *Follow the front* keeps you there.\n- **Merging** brings the events of another branch to where you are. Events that touch the same thing\n differently clash and are left out (for a tree box, only edits of the same node clash).\n- Authorship is per **session** (a browser tab), so two tabs of the same person are told apart.\n- A work can have several **lines** (discussion #117): independent histories, each a tree of its own,\n shown as tabs. The main line is the work as it always was. Their segments are kept with the work's\n history, each marked with its line, and their names in `<work>/lines`.\n\n## Boxes are components\n\nEvery class is a **component**: a map of data and functions with one contract —\n`:receive` (messages in, results out, pure), `:state`, `:show` (what the box shows), `:later` (things\nscheduled in time), `:audio` (Web Audio nodes), a `:view` made of shapes, `:help`.\n\nClasses come from four places: the **core**; official **packages** (`@kairotic/synth` with `adsr~` and\n`synth~`, `@kairotic/spatial` with `pan~` and `space~`, `@kairotic/controls` with `knob`), which come\ninto the work by themselves when a box uses them; **component boxes** that define a class inside the\nwork (they have no inlets nor outlets: the Components tab keeps them, not the patch); and components **imported** from npm. A `patch` box holds a sub-patch, and a class can be a\npatch (an **abstraction**, with `$1 $2` for its arguments and a panel of presented boxes). See\n[Writing a component](writing-a-component.md).\n\n## Messages and signals\n\nTwo things travel along lines:\n\n- **Messages** — numbers, keywords (`:bang`), strings, vectors, maps, musical trees — delivered at once,\n with or without ▶.\n- **Signals** — audio, between `~` boxes, once ▶ has started the sound.\n\n▶ starts sound and **time**: everything a box asks for *later* (`metro`, `ramp`, `mt play`) waits in a\nqueue on the audio clock. ■ silences and brings boxes back to their initial state.\n\nTwo rules keep the flow sane: a message that comes back to the same box 100 times in one instant is a\n**loop without time**, and it is cut (and said in the REPL); and **the same value twice changes\nnothing** that is going on — a player does not start over. See [Data that flows](flow.md).\n\n## Data boxes and views\n\n- A **canvas** is a buffer of strokes in two dimensions; a **freqt** is frequency over time (Hz on a log\n scale, tunings, bar grids). A **reader** (messages) or **reader~** (audio rate) reads\n them at a position in their units (or 0…1 with `norm`: a `phasor~`); how it moves gives the time. The representation does not decide the reading.\n- A **tree** box holds a **musical tree** and sends it whenever it changes — or when the patch after\n it changes, only toward what needs it. A **score** draws it as notation and sends back the edits made\n on it; `mt` boxes transform it; `mt play` plays it. See [Musical trees](mt.md).\n\n## Code inside the work\n\n- `faust~` — Faust compiled in the browser, played as an AudioWorklet; its parameters take messages\n `[:name value]`, what a named knob sends.\n- `script` — a ClojureScript function with the same contract as any component.\n- `component` — the definition of a class.\n\nCode written by someone else runs only when you allow it: in a **shared room**, and in a **link**,\nscripts and components wait for *Run them* / `(trust-scripts true)`. Official definitions, exactly as\nthe page brings them, run without asking.\n\n## Where works live\n\n- **Inside claude.ai** (the Kairotic artifact): works, rooms and Claude come from claude.ai and your\n account.\n- **On Kairotic Pages**: works and rooms in [GUN](https://gun.eco), synced through a relay; solo works\n are encrypted in your browser; Claude with your own Anthropic API key, kept only in your browser.\n See [Kairotic Pages](pages.md).\n- **Locally**: nothing is saved.\n\n## Claude in the work\n\nThe Claude tab makes a **patch** from a description, or changes the open one, or writes a\n**component**. Claude checks what it makes with the page's own tools (classes, ports, Faust compiled,\ncomponents evaluated) before it arrives, as one event of the history. It uses your own Claude account\nor key; every request is kept in your browser, and you can share it in the Gallery. See\n[Asking Claude](ask.md).\n\n## Links carry data\n\nA link can carry a patch (`?code=`, `?src=`), a tutorial step, a help patch or a description for\nClaude (`?ask=`) — never a key. Patch code in a link is read as data: only the calls a patch is made of,\nwith literal arguments, go through. See [Embedding](embed.md).\n","es":"# Conceptos\n\n*[Read in English](concepts.md)* · [Documentación](README.es.md)\n\n## Una obra son datos\n\nUna obra es un **patch**: cajas y las líneas entre ellas, escritas como datos (EDN).\n\n```clojure\n{:boxes {:b1 {:text \"osc~ 440\" :x 40 :y 40}\n :b2 {:text \"dac~ 1 2\" :x 40 :y 100}}\n :lines [[:b1 0 :b2 0]]} ; de la salida 0 de :b1 a la entrada 0 de :b2\n```\n\nEl **texto** de una caja es su clase (la primera palabra) y sus argumentos. Algunas cajas guardan además\n**datos** —los trazos de un canvas, la fuente de una caja de código, el árbol de una caja `tree`— y un\nlugar en la **presentación**. Los puertos se numeran desde 0, de izquierda a derecha.\n\nEl patch y su **código** son la misma obra: cada gesto es una llamada (`box`, `connect`, `move`, `text!`,\n`stroke`, `tree!`…), y la pestaña Code escribe la obra entera con esas llamadas. Dibujar escribe código;\nescribir código dibuja.\n\n## La historia es un árbol\n\nCada gesto es un **evento**. Los eventos forman una **historia**, un árbol: volver atrás y hacer otra\ncosa crea una rama; dos gestos a la vez (dentro de la *simultaneidad*, 1,5 s por defecto) crean dos\nramas. Nada se sobrescribe.\n\n- El **frente** es el punto más nuevo; en una sala, *Follow the front* te mantiene ahí.\n- **Fusionar** trae los eventos de otra rama a donde estás. Los eventos que tocan lo mismo de forma\n distinta chocan y se quedan fuera (en una caja tree, solo chocan las ediciones del mismo nodo).\n- La autoría es por **sesión** (una pestaña del navegador): dos pestañas de la misma persona se distinguen.\n- Una obra puede tener varias **líneas** (discusión #117): historias independientes, cada una un árbol\n propio, mostradas como pestañas. La línea principal es la obra como siempre fue. Sus segmentos se guardan\n con la historia de la obra, cada uno marcado con su línea, y sus nombres en `<work>/lines`.\n\n## Las cajas son componentes\n\nCada clase es un **componente**: un mapa de datos y funciones con un mismo contrato —`:receive`\n(mensajes que entran, resultados que salen, puro), `:state`, `:show` (lo que muestra la caja), `:later`\n(lo que se programa en el tiempo), `:audio` (nodos Web Audio), una `:view` hecha de formas, `:help`.\n\nLas clases vienen de cuatro sitios: el **núcleo**; los **paquetes** oficiales (`@kairotic/synth` con\n`adsr~` y `synth~`, `@kairotic/spatial` con `pan~` y `space~`, `@kairotic/controls` con `knob`), que\nentran solos en la obra cuando una caja los usa; las **cajas component** que definen una clase dentro de\nla obra (no tienen entradas ni salidas: las guarda la pestaña Components, no el patch); y los componentes **importados** de npm. Una caja `patch` guarda un sub-patch, y una clase puede\nser un patch (una **abstracción**, con `$1 $2` para sus argumentos y un panel de cajas presentadas). Ver\n[Escribir un componente](writing-a-component.es.md).\n\n## Mensajes y señales\n\nPor las líneas viajan dos cosas:\n\n- **Mensajes** —números, palabras clave (`:bang`), cadenas, vectores, mapas, árboles musicales— que se\n entregan al momento, con o sin ▶.\n- **Señales** —audio, entre cajas `~`, una vez que ▶ ha puesto en marcha el sonido.\n\n▶ pone en marcha el sonido y el **tiempo**: todo lo que una caja pide *para más tarde* (`metro`, `ramp`,\n`mt play`) espera en una cola sobre el reloj de audio. ■ silencia y devuelve las cajas a su estado\ninicial.\n\nDos reglas mantienen el flujo sano: un mensaje que vuelve a la misma caja 100 veces en un instante es un\n**bucle sin tiempo**, y se corta (y se dice en la REPL); y **el mismo valor dos veces no cambia nada** de\nlo que está en marcha —un reproductor no vuelve a empezar. Ver [Datos que fluyen](flow.es.md).\n\n## Cajas de datos y vistas\n\n- Un **canvas** es un buffer de trazos en dos dimensiones; un **freqt** es frecuencia en el tiempo (Hz\n en escala logarítmica, afinaciones, rejillas de compás). Un **reader** (mensajes) o **reader~** (a ritmo\n de audio) los lee en una posición en sus unidades (o de 0 a 1 con `norm`: un `phasor~`); cómo se mueve da el tiempo. La representación no decide la lectura.\n- Una caja **tree** guarda un **árbol musical** y lo envía cada vez que cambia —o cuando cambia el patch\n que hay después, solo hacia lo que lo necesita. Una **score** lo dibuja como partitura y devuelve las\n ediciones hechas en ella; las cajas `mt` lo transforman; `mt play` lo toca. Ver\n [Árboles musicales](mt.es.md).\n\n## Código dentro de la obra\n\n- `faust~` —Faust compilado en el navegador, tocado como AudioWorklet; sus parámetros reciben mensajes\n `[:nombre valor]`, lo que envía un knob con nombre.\n- `script` —una función ClojureScript con el mismo contrato que cualquier componente.\n- `component` —la definición de una clase.\n\nEl código escrito por otra persona solo se ejecuta cuando lo permites: en una **sala compartida** y en un\n**enlace**, los scripts y componentes esperan a *Run them* / `(trust-scripts true)`. Las definiciones\noficiales, exactamente como las trae la página, se ejecutan sin preguntar.\n\n## Dónde viven las obras\n\n- **Dentro de claude.ai** (el artefacto de Kairotic): obras, salas y Claude vienen de claude.ai y de tu\n cuenta.\n- **En Kairotic Pages**: obras y salas en [GUN](https://gun.eco), sincronizadas por un relay; las obras\n solo se cifran en tu navegador; Claude con tu propia clave de API de Anthropic, guardada solo en tu\n navegador. Ver [Kairotic Pages](pages.es.md).\n- **En local**: no se guarda nada.\n\n## Claude en la obra\n\nLa pestaña Claude hace un **patch** a partir de una descripción, o cambia el abierto, o escribe un\n**componente**. Claude comprueba lo que hace con las herramientas de la propia página (clases, puertos,\nFaust compilado, componentes evaluados) antes de que llegue, como un evento de la historia. Usa tu propia\ncuenta o clave de Claude; cada petición se guarda en tu navegador, y puedes compartirla en la Gallery. Ver\n[Pedírselo a Claude](ask.es.md).\n\n## Los enlaces llevan datos\n\nUn enlace puede llevar un patch (`?code=`, `?src=`), un paso de tutorial, un patch de ayuda o una\ndescripción para Claude (`?ask=`) —nunca una clave. El código de patch de un enlace se lee como datos:\nsolo pasan las llamadas de las que está hecho un patch, con argumentos literales. Ver [Insertar](embed.es.md).\n"},"mt":{"en":"# Musical trees (kairotic.mt)\n\n*[Versión en español](mt.es.md)*\n\nMusic in Kairotic can be written as **data**: a tree in EDN, in the *hiccup* style\n`[:tag {attributes} & children]`. It is the common language of notation, composition and CAC: boxes\nand components take trees and return trees, and a `tree` box shows one as a score (a `freqt` or a `canvas` can show one too, over their strokes).\nThe idea comes from the *llll* of [bach](https://www.bachproject.net) for Max: lists that nest freely.\nThe difference is that here attributes have names, so any extra data (bach's *slots*) is one more key.\n\n```clojure\n[:piece {:tempo 72 :defs {:cell \"e5/.5 d5 c5\"}}\n [:voice {:name \"flute\"}\n [:measure {:meter [3 4]}\n [:note {:pitch \"e5\" :dur 1 :dyn \"p\" :art [:tenuto]}]\n [:tuplet {:ratio [3 2]} \"d5/.5 c5 b4\"] ; a triplet of eighths\n [:chord {:dur 1} [:note {:pitch \"g4\"}] [:note {:pitch 64.5}]]] ; 64.5 = E a quarter tone up\n [:measure\n [:note {:pitch \"a4\" :dur 3 :gliss [[0 0] [1 -150]]}]] ; a glissando in cents\n [:measure [:use {:ref :cell :transpose -12}] [:rest {:dur 1.5}]]]\n [:voice {:name \"electronics\"}\n [:par\n [:param {:name :cutoff :value 300 :to 3000 :dur 6}] ; a ramp of a synth parameter\n [:text {:text \"slowly opening\"}]\n [:seq \"c3/2 r/1 g2/3\"]]]]\n```\n\n## Time\n\nTime is in **beats** (a quarter note = 1). `:tempo` (beats per minute, 60 by default) turns it into\nseconds when the tree is played.\n\n| tag | children are… |\n|---|---|\n| `:seq` `:voice` `:section` | one after another |\n| `:measure {:meter [3 4]}` | one after another; a measure without `:meter` keeps the previous one; `:groups [2 3]` or `\"5/8[2+3]\"` groups its units |\n| `:tuplet {:ratio [3 2]}` | one after another, 3 in the time of 2 |\n| `:par` `:piece` | at the same time |\n| `:chord {:dur 1}` | notes at the same time, lasting the chord's duration |\n\nAny node can carry `:at`: an offset from the start of its parent that does not move its cursor\n(a voice entering later, a parameter change in the middle of a note). A note or rest without\n`:dur` lasts as long as the previous one in its container (1 at first).\n\n## Leaves\n\n| tag | attributes |\n|---|---|\n| `:note` | `:pitch` (`\"c4\"`, `\"f#3\"`, `\"bb2\"`, `\"f##3\"`, `\"ebb2\"`, or a MIDI number with decimals for microtones; a name may carry `:cents`, its deviation) or `:hz`; `:dur`; and optionally `:dyn \"mf\"`, `:art [:staccato :accent :tenuto :marcato]`, `:text`, `:gliss [[x cents] …]`, `:env [[x level] …]`, `:vel`, or any key of your own |\n| `:rest` | `:dur` |\n| `:param` | `:name`, `:value`, and for a ramp `:to` and `:dur`: a parameter change coordinated with the score |\n| `:dyn` | `:mark \"mf\"`; `\"<\"` or `\">\"` with `:dur` is a hairpin |\n| `:text` | `:text \"dolce\"` |\n| `:use` | `:ref` (a key of `:defs`) and optionally `:transpose`, `:invert`, `:retrograde`, `:augment` |\n\nThe curves (`:gliss`, `:env`) go from 0 to 1 over the duration of the note, the same way a stroke\nof a freqt is drawn.\n\n**Strings** are a shorthand for notes in any container: `\"c4/1 e4/.5 r/1 c4+e4+g4/2 f4\"` (pitch/duration;\n`r` is a rest, `+` makes a chord, a token without a duration keeps the previous one).\n\n**Fragments**: `:defs` (a map in the attributes of any container) defines fragments, and\n`[:use {:ref :cell :transpose 5}]` writes them, varied. A section of a larger work can be a `:section`,\nplaced with `:at` in a `:piece`.\n\n## Proportional rhythm (`:rtm`)\n\nA rhythm can be written as **shares** instead of durations, as in the rhythm trees (RTM) of OpenMusic\nand PWGL. The idea for Kairotic comes from [Rastrum](https://github.com/smoge/Rastrum) ([discussion\n#17](https://github.com/bonuoq/kairotic/discussions/17)):\n\n```clojure\n[:measure {:meter [4 4]}\n [:rtm {:shares [1 [1 [1 1 1]] -1 2] :pitches \"c4 d4 e4 f4 g4\"}]]\n```\n\n- A number is a share; a negative number is a silence; `[weight [shares …]]` divides a share further.\n- Shares are relative: `[2 2 2]` is the same rhythm as `[1 1 1]`.\n- The `:rtm` lasts its `:dur` (in beats) or, without it, **fills its measure** (the meter in force,\n also when the measure inherits it). Outside a measure and without `:dur`, it lasts 4 beats.\n- **Note values and tuplets are not written: they follow from the shares and the meter.** When the\n equal unit of a level is a written value (a beat, half a beat, two beats…) the notes take it as it\n is; when it is not, that level becomes a tuplet of the smallest written value that is not shorter.\n Three shares of a 3/4 bar are quarters; three of a 4/4 bar, a 3:2 of halves; five in a beat, a 5:4\n of sixteenths. The example above is a 5:4 of quarters with a triplet of eighths inside.\n- `:pitches` (a melody string, or a list of pitches) go to the notes in order and **start again when\n they run out**, so rhythm and pitches can have different lengths (*talea* and *color*); `r` there\n makes that note a rest. Without `:pitches`, every note takes `:pitch` (`\"c4\"` by default).\n- `:shares` can also be RTM text, `\"(1 (1 (1 1 1)) -1 2)\"`, or an EDN list.\n\nRhythm and pitches stay apart, so a cell can be rotated or moved to another meter without touching\nits pitches. The functions `mt/cell-retrograde`, `mt/cell-rotate`, `mt/cell-at` and\n`mt/cell-replace-at` change the shares themselves; `cell-replace-at` divides a share into a cell, so\na cell can grow inside itself:\n\n```clojure\n(def seed [2 [2 [1 1 1]] 3])\n(mt/cell-replace-at seed [1] seed) ; [2 [2 [2 [2 [1 1 1]] 3]] 3]\n```\n\nThe notes of an `:rtm` are not edited one by one from a score: edit its `:shares` or `:pitches`.\n\n\n## Meters, groups and metric weight\n\nA measure can say how its units group: `{:meter [5 8] :groups [2 3]}`, or written as it reads,\n`{:meter \"5/8[2+3]\"}` (also `\"7/8[2+2+3]\"`, `\"3/4\"`). A measure without a meter keeps the previous\nmeter and its groups; a new meter without groups has none. The groups must add up to the meter.\n\nThe score writes a grouped meter as its groups (2+3 over 8) and **beams** eighths and shorter notes\nby group, or, without groups, by beat: quarters in 2/4, 3/4 and 4/4, dotted quarters in 6/8, 9/8 and\n12/8, the whole bar in 3/8. A tuplet beams its own notes. Rests break beams.\n\n**Metric weight** (after [Rastrum](https://github.com/smoge/Rastrum) and Clarence Barlow) is\ncomposition data, not notation:\n\n| function | |\n|---|---|\n| `(mt/meter-level meter beat)` | 0 at the bar, 1 at a group, deeper for each division: `[4 4]` in eighths → 0 3 2 3 1 3 2 3 |\n| `(mt/indispensability meter [pulse])` | Barlow's ranking of every pulse (the highest, the downbeat): `[3 4]` in eighths → 5 0 3 1 4 2, `[6 8]` → 5 0 2 4 1 3 |\n| `(mt/indispensability-at meter beat [pulse])` · `(mt/pulses meter [pulse])` | one position · where the pulses are, in beats |\n| `(mt/thin amount tree)` · box `mt thin 0.5` | keeps, in every measure, the notes on its strongest positions (a share of them, or how many) and turns the others into rests |\n\n3/4 and 6/8 hold the same six eighths and rank them differently, which is Barlow's argument: `mt thin 2`\nkeeps the first and fifth eighths of a 3/4 bar, and the first and fourth of a 6/8 one. A meter can be\ngiven as `[p q]`, as text `\"5/8[2+3]\"` or as a measure. For a grouped meter Kairotic ranks by metric\nlevel, then by Barlow inside each group, then the earlier group.\n\n## The work, its history and its score\n\n**A work as a tree.** In a `:piece` (and in a `:section`), voices and `:par` sound together from its\nstart, and everything else — sections in a piece, measures in a section — follows in order:\n\n```clojure\n[:piece {:tempo 80}\n [:section {:name \"A\"} [:voice {:name \"fl\"} [:measure {:meter [3 4]} \"e5/1 d5 c5\"]] [:voice {:name \"vc\"} [:measure \"c3/3\"]]]\n [:section {:name \"B\"} [:voice {:name \"fl\"} [:measure \"c5/3\"]] [:voice {:name \"vc\"} [:measure \"g2/3\"]]]]\n```\n\nThe score keeps one staff per voice name across sections, writes each section's name over its first\nbar and a double bar between sections.\n\n**A history of nodes.** The data of a `tree` box is the tree itself, and each event of its history is a\nlist of edits of nodes, addressed by **path** (the child indices from the root; attributes are not\ncounted):\n\n| edit | |\n|---|---|\n| `[:set path x]` | replaces the node (or melody string) at path |\n| `[:attrs path {…}]` | replaces its attributes |\n| `[:insert path x]` | inserts x so that it ends up at path |\n| `[:remove path]` | removes it |\n\n`(tree-edit! :b2 [:set [1 0 0 0] \"e5/.5 f5 g5\"])` writes edits as they are; `(tree! :b2 tree)` and editing\nthe text of the box write the difference with what it had (`mt/diff`). Two branches can be merged when\nthey change different nodes; if one changed a node and the other that node or something inside it,\nthe merge says which.\n\n**Editing from the score.** A tree box shown as a score (⇄ in its header), or a `freqt` shown as a score that receives a tree from a tree box, knows where each note is\nwritten. Click a note, then ↑ ↓ (pitch, ⇧ an octave), a…g (the nearest note of that name), + − (duration),\n← → (previous, next), Delete (a rest), Esc. A rest can be clicked too: Enter makes it a note again (the\npitch of the note before it), ↑ ↓ a step above or below that one, a…g that note. Each change is one `(tree-edit! …)`; a note written in a melody string is first written out\nas notes, in the same event. Notes that come from `:defs` are edited in their definition.\n\nA measure that does not add up is a warning (⚠ in the REPL and on the box), not an error, while you\nwrite.\n\n## Boxes\n\n| box | |\n|---|---|\n| `tree` | holds a tree, seen as a **score** or as a **roll** (⇄ in its header), its text in the code window ({ }): one tree, two views (below). A bang sends it; its second outlet is its notes as a buffer, for a `reader~`. Reading EDN evaluates nothing, so a tree box is safe in a shared room |\n| `mt transpose 7` · `mt invert c4` · `mt retrograde` · `mt augment 2` · `mt rotate 1` · `mt canon 4 7` · `mt thin 0.5` | transformations (the right inlet changes the amount) |\n| `mt seq` · `mt par` | joins the left tree with the right one, one after the other or at once |\n| `mt events` · `mt pitches` · `mt duration` | the tree as plain data |\n| `mt canon d 2 k P5 speed 0.5 inversion` | the canon with the words of a reader on a ring: d beats later, k away (semitones or an interval), the comes at a speed (0.5 twice as slow, −1 backwards: a crab), upside down |\n| `mt play [loop] [speed s]` | plays the last tree on a bang: Hz (0) and voice ids (1) for `synth~`, parameters `[name value]` (2), dynamics and texts (3); at a speed (`msg :speed -1`: the tree backwards) |\n| `freqt` · `canvas` | a tree on their inlet is **shown live** over their buffer; `(keep! :bN)` writes it into the buffer as one event of the history |\n\nA score shows a tree written in `:measure`s as measured notation (tuplets, chords, rests, dynamics,\narticulations, texts, changes of meter). Without measures, and for the strokes of a `freqt`, it shows them\n**quantized** into measures (below).\n\nOutside tuplets each value is written where the beats can be seen: a quarter off the beat over beat 2 of\n4/4 stays one syncopated quarter, but over the middle of the bar it becomes two tied eighths; a dotted\nquarter on beat 2 of 3/4 stays dotted, on beat 2 of 4/4 it shows beat 3. Two more keys of a note:\n`:tie true` goes on into the next note of the same pitch (one sound, tied across a barline or into a\ntuplet) and `:grace true` is a grace note before the next one (it takes no time).\n\n## One box: the tree as score and roll\n\nA `tree` box is the one box for music in time (discussion [#92](https://github.com/bonuoq/kairotic/discussions/92)):\nits data is the tree, and **score** and **roll** are its two views (⇄ in its header, or\n`(view :bN :roll)`; a new tree box is a score). Its text is not a view: **{ }** in its header (or a\ndouble-click on its right half) opens it in the code window, where Ctrl+Enter applies it as edits of the\nnodes that changed. The roll is a piano roll: its notes as strokes of frequency over time, as a freqt\ndraws them, and what is drawn there becomes edits of the tree — one event of the history each, merged between\nbranches like any edit of a tree.\n\n- **Free time** (a tree without measures): drawing adds a note placed with `:at`, dragging moves it,\n stretching (from its end) lengthens it, Delete erases it. A free tree is kept as\n `[:voice {…} [:par [:note {:at 0 :dur 1 :pitch 60} …]]]`; one written otherwise (a melody string, a\n sequence) takes that form the first time a note's time changes. Its score shows it quantized, with its\n divisions chosen by alt-click and its names by shift-alt-click, kept in the tree's `:quant`.\n- **Measures**: a change of pitch alone is written in the note (in its melody string, if it is in one); a\n change of time re-quantizes the bars it touches, in their meter; an erased note leaves a rest as long.\n A note drawn in a measured tree goes into its bar (one voice: a note drawn on a held one joins it as a\n chord). With **⌥** (dragging a note, or drawing freehand) a note leaves the measures for a free voice\n of the tree (`{:name \"free\"}`), which the score quantizes on its own staff.\n- **Its grid and tuning** are attributes of the tree's root: `(grid-x :bN 0.25 [4])` writes `:grid`,\n `(tuning :bN \"19-tet\")` writes `:tuning`. A tree is drawn in semitones (12-tet) unless it says otherwise\n (`:tuning false` is continuous frequency); a measured tree without `:grid` shows its bars.\n\n```clojure\n(view :b2 :roll) ; draw on it\n(stroke :b2 [[0 261.63] [1 261.63]]) ; or by code: a note c4 from 0 to 1\n(quantize! :b2) ; its free time written in measures (one event; undo goes back)\n(unquantize! :b2) ; its notes in free time again\n(to-tree! :b5) ; a new tree box beside the freqt :b5, with its strokes as notes\n```\n\nThe same quantization as a box of the patch: **`quantize`** takes a freqt on its right inlet (its second outlet), or a tree in\nfree time on the left, keeps the options that come as messages (`[:meter \"3/4\"]`, `[:divs [1 2 3 4]]`, `[:legato 0.25]`,\n`[:time :track]`…) and, on a bang, sends the measured tree — into a `tree` box, an `mt`. Only a bang sends: a tree written\ninto a tree box is an event of the history, so the options can be tried first, and two `quantize` boxes can write one take two ways.\n\nA `freqt` stays the buffer of raw frequency over time (what `transcribe` writes from a voice, a\ndrawing in continuous Hz): `(to-tree! :bN)` turns its drawing into a tree when it is to become a score.\n\n## Quantization: free time as measured notation\n\nA `freqt` shown as a score is quantized: its strokes become a tree of measures, tuplets, ties and grace\nnotes (issue [#86](https://github.com/bonuoq/kairotic/issues/86); after bach.quantize, FOMUS and Nauert).\n\n- **The meter** comes from the buffer's bar grid: `(grid-x :bN 0.25 [4])` is 4/4, `[3]` 3/4,\n `[1.5 1.5]` 6/8, `[1.5 1.5 1]` 8/8 in 3+3+2. Without a grid, 4/4.\n- **Each bar** is cut in spans (the beats of a simple meter, the dotted beats or groups of 6/8, 7/8 …),\n and each span takes the division (1 to 8, and those of its own units) that costs least: how far the\n notes are from its points, how deep the points it uses are (the beat, its half, its quarters; 32nds\n cost much), being a tuplet (a triplet less than a quintuplet), and notes lost (two starts on one\n point, a note shrunk to nothing). Two beats can go together (a half-note triplet), and a beat can be\n cut in halves (or a dotted beat in its eighths) with a division each (an eighth and a triplet of\n sixteenths).\n- **Voices**: notes that overlap go to different voices, each note to the free voice nearest in pitch\n (at most `:voices`, 2 by default); notes that start and end together stay one chord. All the voices\n are quantized on the same points and written as layers of one staff (the highest first, stems up). A\n note held through another voice's triplet is not written in the triplet.\n- **The notes** go on those points: chords where starts meet, rests in the gaps (a small gap before the\n next note is legato, not a rest), a tie over a barline or out of a tuplet, a grace note for a note too\n short for any point. A pitch half-way between semitones takes a quarter-tone accidental, others keep\n their cents as a text; a stroke that bends into the next note is a glissando line to it (a text,\n *gliss. ↗ +120¢*, when it bends into nothing).\n\nAt the REPL, `(quantize :bN)` gives that tree (it can be kept, edited, sent to a tree box), and options\nchange how it is made:\n\n```clojure\n(quantize :b1) ; what the score shows\n(quantize :b1 {:meter \"6/8\"}) ; another meter than the grid's\n(quantize :b1 {:divs [1 2 4] :merge [] :nest false}) ; no tuplets at all\n(quantize :b1 {:grace false :legato 0}) ; no grace notes; every gap a rest\n(quantize :b1 {:voices 1}) ; one voice: overlapping notes cut\n(qz/quantize-tree [:par [:note {:at 0 :pitch \"c4\" :dur 1.5}] …] {:meter [3 4]}) ; a tree without measures\n```\n\nThe other options are `:chord` (how close two starts are to be one chord, 0.04 beats), `:overlap` (how\nmuch a note may run into the next one and stay in its voice, 0.15 beats) and `:w`, the weights of the\ncost (`{:err 8 :off 0.35 :cpx 1 :lost 1.5 :coh 0.5}`). `:coh` is what changing kind of division (binary,\ntriplet, quintuplet…) between neighbouring beats costs: a lone triplet among eighths pays it twice, a run of\ntriplets once, so notes played a little early or late do not become tuplets (issue #108; `0` decides each\nbeat on its own). `(as-tree :bN)` still reads a freqt's strokes exactly,\nwithout quantizing them.\n\n**Choosing another division.** The quantizer guesses; when it guesses wrong, **alt-click a note** of the\nscore: its beat takes the next way to divide it (the quantizer's own first, then the others, cheapest\nfirst: another division, the beat in halves, the beat with the next one). Each choice is kept in the\nbuffer, with the options, as one event of the history:\n\n```clojure\n(quant :b1 {:meter \"6/8\" :divs [1 2 3 4 6]}) ; how this freqt's score is quantized (kept in its buffer)\n(quant :b1) ; → {:meter \"6/8\" …}\n(divisions :b1 2.5) ; the ways the beat at 2.5 can be divided, the current first\n(division! :b1 2.5) ; the next one (what alt-click does) → kept in :fix\n(division! :b1 2.5 [:merge 3]) ; this one: n, [n1 n2] (in halves) or [:merge n]\n(division! :b1 2.5 nil) ; the quantizer chooses again\n(quant :b1 nil) ; the defaults\n```\n\nThe buffer's text shows them as `:quant {:meter \"6/8\" :fix {2 [:merge 3]}}`, and a message\n`[:quantize {…}]` on the freqt's inlet sets them too (in a tree box without measures, its root's `:quant`).\n\n**Meters that change** (issue [#107](https://github.com/bonuoq/kairotic/issues/107)). `:meters` gives each bar its\nmeter, the last one going on: `(quant :b1 {:meters [\"3/4\" \"3/4\" \"5/8[2+3]\" \"4/4\"]})`. The score says each meter\nwhere it changes.\n\n**Played time** (issue [#106](https://github.com/bonuoq/kairotic/issues/106), `kairotic.tempo`). What is played\nfreely — a take of `transcribe`, notes drawn without a grid — is in seconds (or in beats at a tempo nobody chose),\nat a tempo that moves. `:time :track` finds its beats before quantizing:\n\n1. the tempo: the beat period that explains most intervals between onsets (each onset weighs as long as its note\n lasts, and as strong as it was played: its `:vel`, or the weight of its stroke, which `transcribe` writes from\n `onset~`), with a mild preference for moderate tempos;\n2. the beats: a dynamic programme (after Ellis 2007) that puts each beat where the onsets are and keeps the gap to\n the one before close to the period, so it follows rubato, accelerando and ritardando;\n3. the bar: which beats are downbeats, and the pickup if the first note is not on one.\n\nThe result is a **time map** `[[time beat] …]` (beats as a quarter = 1), linear between its points. The score is\nwritten through it, with its tempo (`:tempo`) in the tree. `(track! :bN)` finds it once and keeps it in `:quant\n:time`, so the score does not change while you edit (and alt-click divides the same beats); `(track! :bN nil)`\nforgets it.\n\n```clojure\n(quant :b1 {:time :track :meter \"3/4\"}) ; found each time\n(track! :b1 {:meter \"3/4\"}) ; found once, kept → {:tempo 97 :beats 18}\n(quantize! :b2) ; a tree box with a kept map: its measures written on those beats\n```\n\n## How pitches are written: names, keys, accidentals\n\nA pitch is written as a **letter, an alteration and an octave** (issue [#88](https://github.com/bonuoq/kairotic/issues/88)):\nG# and Ab sound alike and are written apart, and a tree keeps the name it was given. `kairotic.spell`\nplaces each name on the **line of fifths** (… Bb F C G D A E B F# C# …), where transposing, inverting and\nchoosing a name are arithmetic.\n\n- **Written names stay**: `\"bb4\"`, `\"f##3\"` (or `\"fx3\"`), `\"ebb2\"` are written as they are, and `mt/pitches`\n gives them back. A name may carry `:cents` (`{:pitch \"c4\" :cents 50}` is a quarter tone above C).\n- **Transposing keeps the spelling**: `(mt/transpose \"m3\" \"c4 e4 g4\")` is eb4 g4 bb4; by a number of\n semitones a tree moves by the interval it is usually written as (1 a minor second: c4 e4 g4 → db4 f4\n ab4; 6 the augmented fourth or the diminished fifth, whichever needs fewer alterations). Intervals are\n `\"M3\"`, `\"-P5\"`, `\"A4\"`, `\"d5\"`, `\"m9\"`… (`mt transpose M3` in a box). `mt/invert` around a written pivot\n mirrors names on the line of fifths too (c4 around e4 is g#4). A tree's keys move with it: `{:key \"eb\"}`\n transposed by `\"M3\"` is `{:key \"g\"}`.\n- **Keys**: `{:key \"eb\"}` on the tree, a section, a voice or a measure (from there on): `\"c#m\"`,\n `\"d dorian\"`, `\"f lydian\"`, a number of sharps (`3`) or flats (`-2`), or `:none`. The score writes its\n signature and its changes; an accidental lasts to the end of its bar (and comes back as a courtesy in the\n next one); `:key :none`, or `:accidentals :every` on the tree, writes every accidental (atonal music).\n- **Notes without a name** (numbers, Hz, a freqt's strokes) are named by `mt/spell`, which ->mei and the\n quantizer use: near the key (the one written, or estimated bar by bar with Temperley's profiles; without\n four pitch classes to go on, or when they fit no key clearly, as a chromatic line does, C), moving well in each voice (a chromatic line rises in sharps and falls in\n flats, no augmented second where a minor third does) and stacked well in each chord (Ab C Eb, not\n G# C D#), over the whole line at once (a Viterbi on the line of fifths). `(mt/spell tree)` writes those\n names into the tree. Without `:key` the score has no signature, only those names.\n- **Another name by hand**: on a selected note of a tree's score, `#` cycles its spelling (c#4 → db4 →\n b##3); on a freqt's score, **shift-alt-click** a note (`(enharmonic! :bN beat midi [name])`), kept in its\n `:quant` as `:spell {[beat midi] name}`. `(quant :bN {:key \"eb\"})` gives a freqt's score a key.\n- Quarter tones take quarter-tone accidentals; for tunings by ratios, HEJI (later) builds on these same\n names.\n\n## REPL and components\n\nThe functions are in `mt/`: `mt/transpose`, `mt/invert`, `mt/retrograde`, `mt/augment`, `mt/rotate`,\n`mt/canon`, `mt/expand`, `mt/events`, `mt/notes`, `mt/pitches`, `mt/duration`, `mt/problems`,\n`mt/pp`, `mt/->mei`, `mt/->strokes`, `mt/<-strokes`, `mt/schedule`, and for proportional rhythm\n`mt/cell-retrograde`, `mt/cell-rotate`, `mt/cell-at`, `mt/cell-replace-at`, and for meters `mt/meter-of`,\n`mt/meter-level`, `mt/indispensability`, `mt/indispensability-at`, `mt/pulses`, `mt/thin`. At the REPL:\n\n- `(tree! :b2 [:voice …])` writes a tree into a tree box;\n- `(as-tree :bN)` reads a tree box, or the tree a score is showing, or a freqt's strokes, as a tree;\n- `(quantize :bN [opts])` gives a freqt's strokes (or a tree without measures) quantized into measures;\n- `(quant :bN opts)`, `(divisions :bN t)`, `(division! :bN t [choice])`: how a freqt's score is quantized, kept in its buffer;\n- `(quantize! :bN [opts])`, `(unquantize! :bN)`, `(to-tree! :bN)`: a tree box's free time in measures and back, a freqt's strokes as a tree;\n- `(enharmonic! :bN beat midi [name])`: another name for a note of a freqt's score; `mt/spell`, `mt/transpose \"M3\"`, and `kairotic.spell` (`sp/parse`, `sp/interval`, `sp/parse-key`, `sp/estimate-key`…);\n- `(keep! :bN)` and `(unlive! :bN)`;\n- `(recipe :bN)` and `(remake! :bN)` (below).\n\nA component can send trees from its `:receive` and use `mt/…`. See the example `examples/claude/notation/walk.cljs`.\n\n## Recipes: where a kept buffer came from\n\n`(keep! :bN)` writes the tree a freqt or canvas is showing into its buffer, as strokes. The\nbuffer is plain data, but **beside it the box keeps the recipe that made it** (the idea comes from\n[Rastrum](https://github.com/smoge/Rastrum), [discussion #17](https://github.com/bonuoq/kairotic/discussions/17)):\n\n```clojure\n(recipe :b5)\n;; {:tree [:voice [:measure {:meter [4 4]} …]] the tree as it arrived\n;; :calls \"(box :b2 \\\"tree\\\" 40 60)\\n(box :b3 \\\"mt transpose 7\\\" …)…\" the boxes and lines upstream, as code\n;; :from :b3} the box it came from\n```\n\n- While the buffer is unchanged, a freqt **shown as a score** keeps showing the tree as measured notation (measures,\n tuplets, dynamics), not an approximation of its strokes, and `(as-tree :bN)` gives the tree itself.\n- Once the buffer changes (a stroke drawn, a message on its inlet), the recipe is kept but marked\n `:stale`: it says where the buffer came from, no longer what it is. The header says *changed since\n kept*.\n- `(remake! :bN)` writes the recipe's tree back into the buffer (one event), dropping the changes.\n- `:calls` is the code of the boxes upstream, so the recipe still says how it was made after those\n boxes are deleted or changed: paste it into the Code tab to build them again.\n- The work's code (Calls) writes each recipe as `(recipe :b5 {…})`, after the data; the Data view\n shows it as `:recipe`, beside `:data`.\n\n## History\n\nA tree lives in the work as the text of a `tree` box, so each edit is one event, with its diff, in\nthe branching history. A score that is showing a tree has not changed: its buffer only changes with\n`keep!`, which keeps the recipe beside it. Next steps: a tree that is the whole work, with sections whose edits are diffs of the tree\nitself (node by node), and scores that edit the tree directly.\n","es":"# Árboles musicales (kairotic.mt)\n\n*[English version](mt.md)*\n\nLa música en Kairotic se puede escribir como **datos**: un árbol en EDN, al estilo\n*hiccup* `[:etiqueta {atributos} & hijos]`. Es el idioma común de la notación, la composición y la CAC:\ncajas y componentes reciben árboles y devuelven árboles, y una caja `tree` muestra uno como partitura (un `freqt` o un `canvas`\npueden mostrarlo también, sobre sus trazos). La idea viene del *llll* de [bach](https://www.bachproject.net) para Max: listas que se\nanidan libremente. La diferencia es que aquí los atributos tienen nombre, así que cualquier dato extra\n(los *slots* de bach) es una clave más.\n\n```clojure\n[:piece {:tempo 72 :defs {:celula \"e5/.5 d5 c5\"}}\n [:voice {:name \"flauta\"}\n [:measure {:meter [3 4]}\n [:note {:pitch \"e5\" :dur 1 :dyn \"p\" :art [:tenuto]}]\n [:tuplet {:ratio [3 2]} \"d5/.5 c5 b4\"] ; un tresillo de corcheas\n [:chord {:dur 1} [:note {:pitch \"g4\"}] [:note {:pitch 64.5}]]] ; 64.5 = mi un cuarto de tono alto\n [:measure\n [:note {:pitch \"a4\" :dur 3 :gliss [[0 0] [1 -150]]}]] ; un glissando en cents\n [:measure [:use {:ref :celula :transpose -12}] [:rest {:dur 1.5}]]]\n [:voice {:name \"electrónica\"}\n [:par\n [:param {:name :cutoff :value 300 :to 3000 :dur 6}] ; una rampa de un parámetro de síntesis\n [:text {:text \"abriendo lentamente\"}]\n [:seq \"c3/2 r/1 g2/3\"]]]]\n```\n\n## Tiempo\n\nEl tiempo está en **pulsos** (la negra = 1). `:tempo` (pulsos por minuto, 60 por defecto) lo convierte\nen segundos al tocar el árbol.\n\n| etiqueta | sus hijos van… |\n|---|---|\n| `:seq` `:voice` `:section` | uno detrás de otro |\n| `:measure {:meter [3 4]}` | uno detrás de otro; un compás sin `:meter` conserva el anterior; `:groups [2 3]` o `\"5/8[2+3]\"` agrupa sus unidades |\n| `:tuplet {:ratio [3 2]}` | uno detrás de otro, 3 en el tiempo de 2 |\n| `:par` `:piece` | a la vez |\n| `:chord {:dur 1}` | notas a la vez, con la duración del acorde |\n\nCualquier nodo puede llevar `:at`: un desplazamiento desde el inicio de su padre que no mueve su cursor\n(una voz que entra más tarde, un cambio de parámetro en medio de una nota). Una nota o un silencio sin\n`:dur` dura lo mismo que el anterior de su contenedor (1 al principio).\n\n## Hojas\n\n| etiqueta | atributos |\n|---|---|\n| `:note` | `:pitch` (`\"c4\"`, `\"f#3\"`, `\"bb2\"`, o un número MIDI con decimales para microtonos) o `:hz`; `:dur`; y opcionalmente `:dyn \"mf\"`, `:art [:staccato :accent :tenuto :marcato]`, `:text`, `:gliss [[x cents] …]`, `:env [[x nivel] …]`, `:vel`, o cualquier clave propia |\n| `:rest` | `:dur` |\n| `:param` | `:name`, `:value`, y para una rampa `:to` y `:dur`: un cambio de parámetro coordinado con la partitura |\n| `:dyn` | `:mark \"mf\"`; `\"<\"` o `\">\"` con `:dur` es un regulador |\n| `:text` | `:text \"dolce\"` |\n| `:use` | `:ref` (una clave de `:defs`) y opcionalmente `:transpose`, `:invert`, `:retrograde`, `:augment` |\n\nLas curvas (`:gliss`, `:env`) van de 0 a 1 a lo largo de la duración de la nota, igual que se dibuja un\ntrazo en un freqt.\n\n**Los textos** son una abreviatura de notas en cualquier contenedor: `\"c4/1 e4/.5 r/1 c4+e4+g4/2 f4\"`\n(altura/duración; `r` es un silencio, `+` forma un acorde, un elemento sin duración conserva la anterior).\n\n**Fragmentos**: `:defs` (un mapa en los atributos de cualquier contenedor) define fragmentos, y\n`[:use {:ref :celula :transpose 5}]` los escribe, variados. Una sección de una obra más grande puede\nser una `:section`, colocada con `:at` dentro de una `:piece`.\n\n## Ritmo proporcional (`:rtm`)\n\nUn ritmo puede escribirse como **proporciones** en vez de duraciones, como en los árboles rítmicos\n(RTM) de OpenMusic y PWGL. La idea para Kairotic viene de [Rastrum](https://github.com/smoge/Rastrum)\n([discusión #17](https://github.com/bonuoq/kairotic/discussions/17)):\n\n```clojure\n[:measure {:meter [4 4]}\n [:rtm {:shares [1 [1 [1 1 1]] -1 2] :pitches \"c4 d4 e4 f4 g4\"}]]\n```\n\n- Un número es una proporción; un número negativo, un silencio; `[peso [proporciones …]]` divide una\n proporción.\n- Las proporciones son relativas: `[2 2 2]` es el mismo ritmo que `[1 1 1]`.\n- El `:rtm` dura su `:dur` (en pulsos) o, sin él, **llena su compás** (el compás vigente, también si\n lo hereda). Fuera de un compás y sin `:dur`, dura 4 pulsos.\n- **Las figuras y los grupos irregulares no se escriben: salen de las proporciones y del compás.**\n Cuando la unidad igual de un nivel es una figura (un pulso, medio, dos…) las notas la toman tal cual;\n cuando no, ese nivel se vuelve un grupo irregular de la figura más pequeña que no sea más corta.\n Tres proporciones de un 3/4 son negras; de un 4/4, un 3:2 de blancas; cinco en un pulso, un 5:4 de\n semicorcheas. El ejemplo de arriba es un 5:4 de negras con un tresillo de corcheas dentro.\n- `:pitches` (un texto de melodía, o una lista de alturas) van a las notas en orden y **vuelven a\n empezar cuando se acaban**: ritmo y alturas pueden tener longitudes distintas (*talea* y *color*);\n una `r` ahí hace de esa nota un silencio. Sin `:pitches`, cada nota toma `:pitch` (`\"c4\"` por defecto).\n- `:shares` también puede ser texto RTM, `\"(1 (1 (1 1 1)) -1 2)\"`, o una lista EDN.\n\nRitmo y alturas van por separado: una célula puede rotarse o pasar a otro compás sin tocar sus alturas.\nLas funciones `mt/cell-retrograde`, `mt/cell-rotate`, `mt/cell-at` y `mt/cell-replace-at` cambian las\nproporciones mismas; `cell-replace-at` divide una proporción en una célula, así una célula puede crecer\ndentro de sí misma:\n\n```clojure\n(def semilla [2 [2 [1 1 1]] 3])\n(mt/cell-replace-at semilla [1] semilla) ; [2 [2 [2 [2 [1 1 1]] 3]] 3]\n```\n\nLas notas de un `:rtm` no se editan una a una desde una partitura: edita sus `:shares` o `:pitches`.\n\n\n## Compases, grupos y peso métrico\n\nUn compás puede decir cómo se agrupan sus unidades: `{:meter [5 8] :groups [2 3]}`, o escrito como se\nlee, `{:meter \"5/8[2+3]\"}` (también `\"7/8[2+2+3]\"`, `\"3/4\"`). Un compás sin `:meter` conserva el compás\nanterior y sus grupos; un compás nuevo sin grupos no los tiene. Los grupos tienen que sumar el compás.\n\nLa partitura escribe un compás agrupado como sus grupos (2+3 sobre 8) y **barra** las corcheas y figuras\nmás breves por grupo o, sin grupos, por pulso: negras en 2/4, 3/4 y 4/4, negras con puntillo en 6/8, 9/8\ny 12/8, el compás entero en 3/8. Un grupo irregular barra sus propias notas. Los silencios cortan la barra.\n\n**El peso métrico** (a partir de [Rastrum](https://github.com/smoge/Rastrum) y de Clarence Barlow) es un\ndato de composición, no de notación:\n\n| función | |\n|---|---|\n| `(mt/meter-level compás pulso)` | 0 en el compás, 1 en un grupo, más profundo en cada división: `[4 4]` en corcheas → 0 3 2 3 1 3 2 3 |\n| `(mt/indispensability compás [pulso])` | la ordenación de Barlow de cada pulso (la más alta, la parte fuerte): `[3 4]` en corcheas → 5 0 3 1 4 2, `[6 8]` → 5 0 2 4 1 3 |\n| `(mt/indispensability-at compás pulso [pulso])` · `(mt/pulses compás [pulso])` | una posición · dónde están los pulsos, en pulsos |\n| `(mt/thin cantidad árbol)` · caja `mt thin 0.5` | conserva, en cada compás, las notas de sus posiciones más fuertes (una proporción, o cuántas) y hace silencio de las demás |\n\n3/4 y 6/8 tienen las mismas seis corcheas y las ordenan distinto, que es el argumento de Barlow: `mt thin 2`\nconserva la primera y la quinta corchea de un 3/4, y la primera y la cuarta de un 6/8. Un compás se puede\ndar como `[p q]`, como texto `\"5/8[2+3]\"` o como un compás del árbol. En un compás agrupado Kairotic ordena\npor nivel métrico, luego por Barlow dentro de cada grupo y luego el grupo anterior.\n\n## La obra, su historia y su partitura\n\n**Una obra como árbol.** En una `:piece` (y en una `:section`), las voces y los `:par` suenan a la vez\ndesde su inicio, y todo lo demás —secciones en una pieza, compases en una sección— se sucede en orden:\n\n```clojure\n[:piece {:tempo 80}\n [:section {:name \"A\"} [:voice {:name \"fl\"} [:measure {:meter [3 4]} \"e5/1 d5 c5\"]] [:voice {:name \"vc\"} [:measure \"c3/3\"]]]\n [:section {:name \"B\"} [:voice {:name \"fl\"} [:measure \"c5/3\"]] [:voice {:name \"vc\"} [:measure \"g2/3\"]]]]\n```\n\nLa partitura mantiene un pentagrama por nombre de voz a lo largo de las secciones, escribe el nombre de\ncada sección sobre su primer compás y una doble barra entre secciones.\n\n**Una historia de nodos.** El dato de una caja `tree` es el propio árbol, y cada evento de su historia es\nuna lista de ediciones de nodos, señalados por su **camino** (los índices de hijos desde la raíz; los\natributos no cuentan):\n\n| edición | |\n|---|---|\n| `[:set camino x]` | sustituye el nodo (o el texto de melodía) del camino |\n| `[:attrs camino {…}]` | sustituye sus atributos |\n| `[:insert camino x]` | inserta x para que quede en ese camino |\n| `[:remove camino]` | lo elimina |\n\n`(tree-edit! :b2 [:set [1 0 0 0] \"e5/.5 f5 g5\"])` escribe las ediciones tal cual; `(tree! :b2 árbol)` y\neditar el texto de la caja escriben la diferencia con lo que tenía (`mt/diff`). Dos ramas se pueden\nfundir cuando cambian nodos distintos; si una cambió un nodo y la otra ese nodo o algo dentro de él, la\nfusión dice cuál.\n\n**Editar desde la partitura.** Una partitura que muestra un árbol que viene de una caja tree sabe dónde\nestá escrita cada nota. Haz clic en una nota y luego ↑ ↓ (altura, ⇧ una octava), a…g (la nota más cercana con ese\nnombre), + − (duración), ← → (anterior, siguiente), Supr (un silencio), Esc. También se puede hacer clic\nen un silencio: Intro lo vuelve nota (la altura de la nota anterior), ↑ ↓ un paso por encima o por\ndebajo, a…g esa nota. Cada cambio es un `(tree-edit! …)`; una nota escrita en\nun texto de melodía se escribe primero como notas, en el mismo evento. Las notas que vienen de `:defs` se\neditan en su definición.\n\nUn compás que no cuadra es un aviso (⚠ en la REPL y en la caja), no un error, mientras escribes.\n\n## Cajas\n\n| caja | |\n|---|---|\n| `tree` | guarda un árbol, visto como **partitura** o como **roll** (⇄ en su cabecera), con su texto en la ventana de código ({ }): un árbol, dos vistas (más abajo). Un bang lo envía; su segunda salida son sus notas como buffer, para un `reader~`. Leer EDN no evalúa nada, así que una caja tree es segura en una sala compartida |\n| `mt transpose 7` · `mt invert c4` · `mt retrograde` · `mt augment 2` · `mt rotate 1` · `mt canon 4 7` · `mt thin 0.5` | transformaciones (la entrada derecha cambia la cantidad) |\n| `mt seq` · `mt par` | une el árbol de la izquierda con el de la derecha, uno detrás de otro o a la vez |\n| `mt events` · `mt pitches` · `mt duration` | el árbol como datos planos |\n| `mt canon d 2 k P5 speed 0.5 inversion` | el canon con las palabras de un reader sobre un ring: d pulsos después, a k (semitonos o un intervalo), el comes a una velocidad (0,5 el doble de lento, −1 al revés: un cangrejo), invertido |\n| `mt play [loop] [speed s]` | toca el último árbol al recibir un bang: Hz (0) e ids de voz (1) para `synth~`, parámetros `[nombre valor]` (2), dinámicas y textos (3); a una velocidad (`msg :speed -1`: el árbol al revés) |\n| `freqt` · `canvas` | un árbol en su entrada **se muestra en vivo** sobre su buffer; `(keep! :bN)` lo escribe en el buffer como un evento de la historia |\n\nUn freqt mostrado como partitura muestra un árbol escrito en `:measure` como notación medida (grupos irregulares, acordes,\nsilencios, dinámicas, articulaciones, textos, cambios de compás). Sin compases, y para los trazos de un `freqt`,\nlos muestra **cuantizados** en compases (más abajo).\n\nFuera de los grupos irregulares cada valor se escribe donde se puedan ver las partes del compás: una negra a\ncontratiempo sobre la parte 2 de un 4/4 sigue siendo una negra sincopada, pero sobre la mitad del compás pasa a\nser dos corcheas ligadas; una negra con puntillo en la parte 2 de un 3/4 se queda con su puntillo, en la parte 2\nde un 4/4 deja ver la parte 3. Dos claves más de una nota: `:tie true` sigue en la siguiente nota de la misma\naltura (un solo sonido, ligado sobre la barra o dentro de un grupo irregular) y `:grace true` es una nota de\nadorno antes de la siguiente (no ocupa tiempo).\n\n## Una caja: el árbol como partitura y roll\n\nUna caja `tree` es la caja única para la música en el tiempo (discusión [#92](https://github.com/bonuoq/kairotic/discussions/92)):\nsu dato es el árbol, y **partitura** y **roll** son sus dos vistas (⇄ en su cabecera, o `(view :bN :roll)`; una\ncaja tree nueva es una partitura). Su texto no es una vista: **{ }** en su cabecera (o un doble clic en su mitad\nderecha) lo abre en la ventana de código, donde Ctrl+Intro lo aplica como ediciones de los nodos que cambiaron.\nEl roll es un piano roll: sus notas como trazos de frecuencia en el tiempo, como los dibuja un freqt, y lo que\nse dibuja ahí se convierte en ediciones del árbol: un evento de la historia cada una, que se fusiona entre ramas\ncomo cualquier edición de un árbol.\n\n- **Tiempo libre** (un árbol sin compases): dibujar añade una nota colocada con `:at`, arrastrar la mueve, estirarla\n (desde su final) la alarga, Supr la borra. Un árbol libre se guarda como\n `[:voice {…} [:par [:note {:at 0 :dur 1 :pitch 60} …]]]`; uno escrito de otra manera (una cadena de melodía, una\n secuencia) toma esa forma la primera vez que cambia el tiempo de una nota. Su partitura lo muestra cuantizado, con\n sus divisiones elegidas con alt+clic y sus nombres con mayúsculas+alt+clic, guardados en el `:quant` del árbol.\n- **Compases**: un cambio solo de altura se escribe en la nota (en su cadena de melodía, si está en una); un cambio de\n tiempo vuelve a cuantizar los compases que toca, en su compás; una nota borrada deja un silencio igual de largo.\n Una nota dibujada en un árbol con compases entra en su compás (una voz: una nota dibujada sobre otra tenida se une\n a ella en un acorde). Con **⌥** (arrastrando una nota, o dibujando a mano alzada) una nota sale de los compases a una\n voz libre del árbol (`{:name \"free\"}`), que la partitura cuantiza en su propio pentagrama.\n- **Su rejilla y su afinación** son atributos de la raíz del árbol: `(grid-x :bN 0.25 [4])` escribe `:grid`,\n `(tuning :bN \"19-tet\")` escribe `:tuning`. Un árbol se dibuja en semitonos (12-tet) salvo que diga otra cosa\n (`:tuning false` es frecuencia continua); un árbol con compases sin `:grid` muestra sus compases.\n\n```clojure\n(view :b2 :roll) ; dibujar en él\n(stroke :b2 [[0 261.63] [1 261.63]]) ; o con código: un c4 de 0 a 1\n(quantize! :b2) ; su tiempo libre escrito en compases (un evento; deshacer vuelve)\n(unquantize! :b2) ; sus notas en tiempo libre otra vez\n(to-tree! :b5) ; una caja tree nueva junto al freqt :b5, con sus trazos como notas\n```\n\nLa misma cuantización como caja del patch: **`quantize`** toma un freqt en su entrada derecha (su segunda salida), o un árbol\nen tiempo libre por la izquierda, guarda las opciones que llegan como mensajes (`[:meter \"3/4\"]`, `[:divs [1 2 3 4]]`,\n`[:legato 0.25]`, `[:time :track]`…) y, con un bang, envía el árbol medido — a una caja `tree`, a un `mt`. Solo envía con un\nbang: un árbol escrito en una caja tree es un evento de la historia, así que las opciones se pueden probar antes, y dos cajas\n`quantize` pueden escribir una toma de dos maneras.\n\nUn `freqt` sigue siendo el buffer de frecuencia en el tiempo en bruto (lo que `transcribe` escribe desde una voz, un\ndibujo en Hz continuos): `(to-tree! :bN)` convierte su dibujo en un árbol cuando va a ser una partitura.\n\n## Cuantización: el tiempo libre como notación medida\n\nUn `freqt` mostrado como partitura se cuantiza: sus trazos pasan a ser un árbol de compases, grupos\nirregulares, ligaduras y notas de adorno (issue [#86](https://github.com/bonuoq/kairotic/issues/86); a partir\nde bach.quantize, FOMUS y Nauert).\n\n- **El compás** sale de la rejilla de compás del buffer: `(grid-x :bN 0.25 [4])` es 4/4, `[3]` 3/4,\n `[1.5 1.5]` 6/8, `[1.5 1.5 1]` 8/8 en 3+3+2. Sin rejilla, 4/4.\n- **Cada compás** se corta en tramos (las partes de un compás simple, las partes con puntillo o los grupos de\n 6/8, 7/8…), y cada tramo toma la división (de 1 a 8, y las de sus propias unidades) que menos cuesta: lo lejos\n que quedan las notas de sus puntos, lo hondos que son los puntos que usa (la parte, su mitad, sus cuartos; las\n fusas cuestan mucho), ser un grupo irregular (un tresillo menos que un quintillo) y las notas que se pierden\n (dos ataques en un punto, una nota que se queda en nada). Dos partes pueden ir juntas (un tresillo de blancas),\n y una parte se puede partir en mitades (o una parte con puntillo en sus corcheas) con una división cada una\n (una corchea y un tresillo de semicorcheas).\n- **Voces**: las notas que se solapan van a voces distintas, cada nota a la voz libre más cercana en altura (como\n mucho `:voices`, 2 por defecto); las notas que empiezan y acaban juntas siguen siendo un acorde. Todas las voces\n se cuantizan sobre los mismos puntos y se escriben como capas de un pentagrama (la más aguda primero, plicas\n arriba). Una nota tenida durante el tresillo de otra voz no se escribe dentro del tresillo.\n- **Las notas** se colocan en esos puntos: acordes donde coinciden ataques, silencios en los huecos (un hueco\n pequeño antes de la nota siguiente es legato, no un silencio), una ligadura sobre la barra o al salir de un grupo\n irregular, una nota de adorno para una nota demasiado corta para cualquier punto. Una altura a medio camino entre\n semitonos lleva una alteración de cuarto de tono, las demás conservan sus cents como texto; un trazo que se curva\n hacia la nota siguiente es una línea de glissando hasta ella (un texto, *gliss. ↗ +120¢*, si no llega a ninguna).\n\nEn el REPL, `(quantize :bN)` da ese árbol (se puede guardar, editar, mandar a una caja tree), y unas opciones\ncambian cómo se hace:\n\n```clojure\n(quantize :b1) ; lo que muestra la partitura\n(quantize :b1 {:meter \"6/8\"}) ; otro compás que el de la rejilla\n(quantize :b1 {:divs [1 2 4] :merge [] :nest false}) ; sin grupos irregulares\n(quantize :b1 {:grace false :legato 0}) ; sin notas de adorno; cada hueco un silencio\n(quantize :b1 {:voices 1}) ; una voz: las notas solapadas se cortan\n(qz/quantize-tree [:par [:note {:at 0 :pitch \"c4\" :dur 1.5}] …] {:meter [3 4]}) ; un árbol sin compases\n```\n\nLas otras opciones son `:chord` (lo cerca que deben estar dos ataques para ser un acorde, 0.04 partes), `:overlap`\n(cuánto puede entrar una nota en la siguiente y seguir en su voz, 0.15 partes) y `:w`, los pesos del coste\n(`{:err 8 :off 0.35 :cpx 1 :lost 1.5 :coh 0.5}`). `:coh` es lo que cuesta cambiar de tipo de división (binaria,\ntresillo, quintillo…) entre pulsos vecinos: un tresillo suelto entre corcheas lo paga dos veces, una serie de\ntresillos una, así que las notas tocadas un poco antes o después no se vuelven grupos irregulares (issue #108;\n`0` decide cada pulso por su cuenta). `(as-tree :bN)` sigue leyendo los trazos de un freqt tal cual, sin\ncuantizarlos.\n\n**Elegir otra división.** El cuantizador adivina; cuando se equivoca, **alt+clic en una nota** de la partitura:\nsu parte toma la siguiente manera de dividirla (primero la del cuantizador, luego las demás, de más barata a más\ncara: otra división, la parte en mitades, la parte junto con la siguiente). Cada elección se guarda en el buffer,\ncon las opciones, como un evento de la historia:\n\n```clojure\n(quant :b1 {:meter \"6/8\" :divs [1 2 3 4 6]}) ; cómo se cuantiza la partitura de este freqt (en su buffer)\n(quant :b1) ; → {:meter \"6/8\" …}\n(divisions :b1 2.5) ; las maneras de dividir la parte en 2.5, la actual primero\n(division! :b1 2.5) ; la siguiente (lo que hace el alt+clic) → en :fix\n(division! :b1 2.5 [:merge 3]) ; esta: n, [n1 n2] (en mitades) o [:merge n]\n(division! :b1 2.5 nil) ; que vuelva a elegir el cuantizador\n(quant :b1 nil) ; las opciones por defecto\n```\n\nEl texto del buffer las muestra como `:quant {:meter \"6/8\" :fix {2 [:merge 3]}}`, y un mensaje `[:quantize {…}]`\nen la entrada del freqt también las cambia (en una caja tree sin compases, el `:quant` de su raíz).\n\n**Compases que cambian** (issue [#107](https://github.com/bonuoq/kairotic/issues/107)). `:meters` da a cada compás su\nmétrica, y la última continúa: `(quant :b1 {:meters [\"3/4\" \"3/4\" \"5/8[2+3]\" \"4/4\"]})`. La partitura indica cada\nmétrica donde cambia.\n\n**Tiempo tocado** (issue [#106](https://github.com/bonuoq/kairotic/issues/106), `kairotic.tempo`). Lo que se toca\nlibremente —una toma de `transcribe`, notas dibujadas sin rejilla— está en segundos (o en partes a un tempo que nadie\neligió), a un tempo que se mueve. `:time :track` encuentra sus partes antes de cuantizar:\n\n1. el tempo: el periodo de pulso que explica más intervalos entre ataques (cada ataque pesa lo que dura su nota, y\n lo fuerte que se tocó: su `:vel`, o el grosor de su trazo, que `transcribe` escribe a partir de `onset~`), con una\n preferencia suave por tempos moderados;\n2. los pulsos: una programación dinámica (según Ellis 2007) que pone cada pulso donde están los ataques y mantiene\n la distancia al anterior cerca del periodo, así que sigue el rubato, el accelerando y el ritardando;\n3. el compás: qué pulsos son primeros de compás, y la anacrusa si la primera nota no cae en uno.\n\nEl resultado es un **mapa de tiempo** `[[tiempo parte] …]` (partes de negra = 1), lineal entre sus puntos. La\npartitura se escribe a través de él, con su tempo (`:tempo`) en el árbol. `(track! :bN)` lo encuentra una vez y lo\nguarda en `:quant :time`, así la partitura no cambia mientras editas (y el alt-clic divide los mismos pulsos);\n`(track! :bN nil)` lo olvida.\n\n```clojure\n(quant :b1 {:time :track :meter \"3/4\"}) ; se encuentra cada vez\n(track! :b1 {:meter \"3/4\"}) ; se encuentra una vez y se guarda → {:tempo 97 :beats 18}\n(quantize! :b2) ; una caja tree con un mapa guardado: sus compases escritos sobre esos pulsos\n```\n\n## Cómo se escriben las alturas: nombres, tonalidades, alteraciones\n\nUna altura se escribe como **letra, alteración y octava** (issue [#88](https://github.com/bonuoq/kairotic/issues/88)):\nsol♯ y la♭ suenan igual y se escriben distinto, y un árbol conserva el nombre que se le dio. `kairotic.spell` coloca\ncada nombre en la **línea de quintas** (… si♭ fa do sol re la mi si fa♯ do♯ …), donde transportar, invertir y elegir\nun nombre son aritmética.\n\n- **Los nombres escritos se respetan**: `\"bb4\"`, `\"f##3\"` (o `\"fx3\"`), `\"ebb2\"` se escriben tal cual, y `mt/pitches`\n los devuelve. Un nombre puede llevar `:cents` (`{:pitch \"c4\" :cents 50}` es un cuarto de tono sobre do).\n- **Transportar conserva la grafía**: `(mt/transpose \"m3\" \"c4 e4 g4\")` es eb4 g4 bb4; con un número de semitonos el\n árbol se mueve por el intervalo con que suele escribirse (1 una segunda menor: c4 e4 g4 → db4 f4 ab4; 6 la cuarta\n aumentada o la quinta disminuida, la que pida menos alteraciones). Los intervalos son `\"M3\"`, `\"-P5\"`, `\"A4\"`,\n `\"d5\"`, `\"m9\"`… (`mt transpose M3` en una caja). `mt/invert` alrededor de un pivote escrito refleja también los\n nombres en la línea de quintas (c4 alrededor de e4 es g#4). Las tonalidades de un árbol se mueven con él:\n `{:key \"eb\"}` transportado `\"M3\"` es `{:key \"g\"}`.\n- **Tonalidades**: `{:key \"eb\"}` en el árbol, una sección, una voz o un compás (desde ahí): `\"c#m\"`, `\"d dorian\"`,\n `\"f lydian\"`, un número de sostenidos (`3`) o bemoles (`-2`), o `:none`. La partitura escribe la armadura y sus\n cambios; una alteración dura hasta el final del compás (y vuelve como alteración de precaución en el siguiente);\n `:key :none`, o `:accidentals :every` en el árbol, escribe todas las alteraciones (música atonal).\n- **Las notas sin nombre** (números, Hz, los trazos de un freqt) las nombra `mt/spell`, que usan ->mei y el\n cuantizador: cerca de la tonalidad (la escrita, o estimada compás a compás con los perfiles de Temperley; sin cuatro\n clases de altura en que apoyarse, o cuando no encajan claramente en ninguna, como una línea cromática, do), moviéndose bien en cada voz (una línea cromática sube con sostenidos y baja\n con bemoles, sin segunda aumentada donde vale una tercera menor) y apiladas bien en cada acorde (la♭ do mi♭, no\n sol♯ do re♯), sobre toda la línea a la vez (un Viterbi en la línea de quintas). `(mt/spell árbol)` escribe esos\n nombres en el árbol. Sin `:key` la partitura no lleva armadura, solo esos nombres.\n- **Otro nombre a mano**: con una nota seleccionada en la partitura de un árbol, `#` recorre sus grafías (c#4 → db4 →\n b##3); en la partitura de un freqt, **mayúsculas+alt+clic** en una nota (`(enharmonic! :bN parte midi [nombre])`),\n guardado en su `:quant` como `:spell {[parte midi] nombre}`. `(quant :bN {:key \"eb\"})` da tonalidad a la partitura\n de un freqt.\n- Los cuartos de tono llevan alteraciones de cuarto de tono; para afinaciones por razones, HEJI (más adelante) se\n apoyará en estos mismos nombres.\n\n## REPL y componentes\n\nLas funciones están en `mt/`: `mt/transpose`, `mt/invert`, `mt/retrograde`, `mt/augment`, `mt/rotate`,\n`mt/canon`, `mt/expand`, `mt/events`, `mt/notes`, `mt/pitches`, `mt/duration`, `mt/problems`,\n`mt/pp`, `mt/->mei`, `mt/->strokes`, `mt/<-strokes`, `mt/schedule`, y para el ritmo proporcional\n`mt/cell-retrograde`, `mt/cell-rotate`, `mt/cell-at`, `mt/cell-replace-at`, y para los compases `mt/meter-of`,\n`mt/meter-level`, `mt/indispensability`, `mt/indispensability-at`, `mt/pulses`, `mt/thin`. En la REPL:\n\n- `(tree! :b2 [:voice …])` escribe un árbol en una caja tree;\n- `(as-tree :bN)` lee como árbol una caja tree, el árbol que muestra un freqt, o los trazos de un freqt;\n- `(quantize :bN [opciones])` da los trazos de un freqt (o un árbol sin compases) cuantizados en compases;\n- `(quant :bN opciones)`, `(divisions :bN t)`, `(division! :bN t [elección])`: cómo se cuantiza la partitura de un freqt, guardado en su buffer;\n- `(quantize! :bN [opciones])`, `(unquantize! :bN)`, `(to-tree! :bN)`: el tiempo libre de una caja tree en compases y de vuelta, los trazos de un freqt como árbol;\n- `(enharmonic! :bN parte midi [nombre])`: otro nombre para una nota de la partitura de un freqt; `mt/spell`, `mt/transpose \"M3\"`, y `kairotic.spell` (`sp/parse`, `sp/interval`, `sp/parse-key`, `sp/estimate-key`…);\n- `(keep! :bN)` y `(unlive! :bN)`;\n- `(recipe :bN)` y `(remake! :bN)` (abajo).\n\nUn componente puede enviar árboles desde su `:receive` y usar `mt/…`. Ver el ejemplo\n`examples/claude/notation/walk.cljs`.\n\n## Recetas: de dónde viene un buffer fijado\n\n`(keep! :bN)` escribe en su buffer, como trazos, el árbol que muestra un freqt o un canvas.\nEl buffer son datos sin más, pero **junto a él la caja guarda la receta que lo hizo** (la idea viene de\n[Rastrum](https://github.com/smoge/Rastrum), [discusión #17](https://github.com/bonuoq/kairotic/discussions/17)):\n\n```clojure\n(recipe :b5)\n;; {:tree [:voice [:measure {:meter [4 4]} …]] el árbol tal como llegó\n;; :calls \"(box :b2 \\\"tree\\\" 40 60)\\n(box :b3 \\\"mt transpose 7\\\" …)…\" las cajas y líneas de antes, como código\n;; :from :b3} la caja de la que vino\n```\n\n- Mientras el buffer no cambie, un freqt **mostrado como partitura** sigue mostrando el árbol en notación medida (compases,\n grupos irregulares, dinámicas), no una aproximación de sus trazos, y `(as-tree :bN)` da el árbol mismo.\n- En cuanto el buffer cambia (un trazo dibujado, un mensaje en su entrada), la receta se conserva pero\n marcada `:stale`: dice de dónde vino el buffer, ya no lo que es. La cabecera dice *changed since kept*.\n- `(remake! :bN)` vuelve a escribir en el buffer el árbol de la receta (un evento), sin los cambios.\n- `:calls` es el código de las cajas de antes, así que la receta sigue diciendo cómo se hizo aunque esas\n cajas se borren o cambien: pégalo en la pestaña Code para volver a construirlas.\n- El código de la obra (Calls) escribe cada receta como `(recipe :b5 {…})`, después de los datos; la\n vista Data la muestra como `:recipe`, junto a `:data`.\n\n## Historia\n\nUn árbol vive en la obra como el texto de una caja `tree`, así que cada edición es un evento, con su\ndiff, en la historia ramificada. Un freqt que muestra un árbol no ha cambiado: su buffer solo cambia\ncon `keep!`, que guarda junto a él la receta. Próximos pasos: un árbol que sea la obra entera, con secciones cuyas ediciones sean diffs\ndel propio árbol (nodo a nodo), y partituras que editen el árbol directamente.\n"},"flow":{"en":"# Data that flows\n\n*[Versión en español](flow.es.md)*\n\n## Messages and time\n\nMessages travel whenever something sends them — a click on a bang or a message, a number dragged, a\ndata box that changed, the REPL — with or without ▶, as in Max and Pd (where only the audio needs the\nDSP on). **▶ starts what needs a clock**: the sound (audio nodes) and time (loadbang, metro, ramp,\n`mt play`: everything that asks for something *later*). **■** silences and brings boxes back to their\ninitial state; the data boxes then send what they hold again.\n\n## Data boxes send themselves\n\nA `tree` box sends its tree **whenever it changes** — an edit of its text, `tree!`, `tree-edit!`, the\nhistory moving, someone else's edit in a room — and also when the patch around it changes (a new\nline, a new text such as `mt transpose` → `mt retrograde`), so what depends on it is always up to\ndate. It sends at most once per moment and only if something really changed. When the patch changes, the tree\ngoes again only toward what needs it: along its lines that lead to a new line or to a box that is new or\nhas a new text. Moving a knob, whose value stays in its text, sends nothing. A bang sends it again;\n`tree manual` sends only on a bang (for live performance, when you prepare a change and launch it).\n\n## Views that send their edits back\n\nA `freqt` shown as a score that shows a tree has a third outlet, **edits**: when you change a note on\nit (click, then ↑ ↓ + − ← → Delete), it sends `[:edit [[:attrs [0 1 2] {…}] …]]`. Connected back to the tree box —\na **dashed line**, drawn for you when you connect a tree to a freqt shown as a score with the mouse — the edits\nchange the tree (as `tree-edit!`, one event of the history), and the tree, changed, comes back to the\nscore. Nothing is coupled behind the patch: the loop is a line you see, in the patch and in the code.\nA tree box can also show itself as a score (⇄ in its header, `(view :bN :score)`): then its notes\nedit it directly, with no wire. The wired loop is for a score that shows the tree after `mt` boxes.\n\nThe edits name the node where each note is written, so they work through transformations: a score\nshowing `mt transpose 7` of a tree can edit the tree itself. Edits are messages like any other: they\ncan be filtered, sent to another tree, or written by a component.\n\nA tree box also takes whole trees on its inlet (a copy of another tree, or a transformed one).\n\n## Loops\n\n- **In one instant**: a message that comes back to the same box 100 times in one instant is a loop\n without time; it is cut, and the REPL says where. A loop that goes through time (metro, a delay,\n `mt play`) is not cut: that is feedback you mean.\n- **Its own tree back**: a tree box that receives its own tree, even transformed by `mt` boxes,\n does not change (and says so): otherwise it would rewrite itself for ever.\n- **By rate**: a tree box rewritten by messages 20 times in 10 seconds stops accepting them;\n `(resume! :bN)` lets them in again.\n- A score does not send what it receives, only what you edit, and a tree sends only what changed:\n the tree ⇄ score loop ends after one round.\n","es":"# Datos que fluyen\n\n*[English version](flow.md)*\n\n## Mensajes y tiempo\n\nLos mensajes viajan siempre que algo los envía —un clic en un bang o en un mensaje, un número\narrastrado, una caja de datos que ha cambiado, la REPL— con o sin ▶, como en Max y Pd (donde solo el\naudio necesita el DSP encendido). **▶ pone en marcha lo que necesita un reloj**: el sonido (los nodos de\naudio) y el tiempo (loadbang, metro, ramp, `mt play`: todo lo que pide algo *para más tarde*). **■**\nsilencia y devuelve las cajas a su estado inicial; después, las cajas de datos vuelven a enviar lo que\ncontienen.\n\n## Las cajas de datos se envían solas\n\nUna caja `tree` envía su árbol **cada vez que cambia** —una edición de su texto, `tree!`, `tree-edit!`, la\nhistoria que se mueve, la edición de otra persona en una sala— y también cuando cambia el patch a su\nalrededor (un cable nuevo, un texto nuevo como `mt transpose` → `mt retrograde`), así que lo que depende\nde ella siempre está al día. Envía como mucho una vez por momento y solo si algo cambió de verdad. Cuando cambia el patch, el árbol\nvuelve a ir solo hacia lo que lo necesita: por sus líneas que llevan a una línea nueva o a una caja nueva\no con un texto nuevo. Mover un knob, cuyo valor queda en su texto, no envía nada. Un\nbang lo vuelve a enviar; `tree manual` solo envía con un bang (para el directo, cuando preparas un\ncambio y lo lanzas tú).\n\n## Vistas que devuelven sus ediciones\n\nUn `freqt` mostrado como partitura que muestra un árbol tiene una tercera salida, **ediciones**: cuando cambias una nota en él\n(clic, y luego ↑ ↓ + − ← → Supr), envía `[:edit [[:attrs [0 1 2] {…}] …]]`. Conectado de vuelta a la caja\ntree —una **línea discontinua**, que se dibuja sola cuando conectas con el ratón un tree a un freqt mostrado como partitura— las\nediciones cambian el árbol (como `tree-edit!`, un evento de la historia), y el árbol, cambiado, vuelve a la\npartitura. Nada se acopla por detrás del patch: el bucle es una línea que se ve, en el patch y en el\ncódigo. Una caja tree también puede mostrarse como partitura (⇄ en su cabecera, `(view :bN :score)`): entonces\nsus notas la editan directamente, sin cable. El bucle con cable es para una partitura que muestra el árbol\ndespués de cajas `mt`.\n\nLas ediciones nombran el nodo donde está escrita cada nota, así que funcionan a través de\ntransformaciones: una partitura que muestra `mt transpose 7` de un árbol puede editar el propio árbol.\nLas ediciones son mensajes como cualquier otro: se pueden filtrar, mandar a otro tree o escribirlas un\ncomponente.\n\nUna caja tree también acepta árboles enteros por su entrada (la copia de otro árbol, o uno transformado).\n\n## Bucles\n\n- **En un instante**: un mensaje que vuelve a la misma caja 100 veces en un instante es un bucle sin\n tiempo; se corta, y la REPL dice dónde. Un bucle que pasa por el tiempo (metro, un retardo,\n `mt play`) no se corta: es la realimentación que sí quieres.\n- **Su propio árbol de vuelta**: una caja tree que recibe su propio árbol, aunque venga transformado\n por cajas `mt`, no cambia (y lo dice): si no, se reescribiría para siempre.\n- **Por ritmo**: una caja tree reescrita por mensajes 20 veces en 10 segundos deja de aceptarlos;\n `(resume! :bN)` vuelve a dejarlos pasar.\n- Una partitura no envía lo que recibe, solo lo que tú editas, y un tree solo envía lo que cambió: el\n bucle tree ⇄ score termina tras una vuelta.\n"},"ask":{"en":"# Asking for a patch\n\n*[Versión en español](ask.es.md)*\n\n## In the Claude tab\n\nThe Claude tab now makes **patches** as well as components. Choose *A patch*, describe it — «a hello\nworld: a sine at 440 Hz with a volume knob» — and **Make it**. With *change the open patch* checked\n(the default), Claude gets the open patch and changes it: «now add a knob that does FM synthesis».\n\nClaude answers with the patch's code, the same calls a link carries (`box`, `connect`, `code`,\n`present`, `tree!`…). Before answering it checks it with the page's own tools:\n\n- `list_classes` and `class_help`: which classes exist, what each inlet takes and each outlet sends;\n- `check_faust`: for sound the core classes do not make (FM, filters, effects), a `faust~` box whose\n parameters are driven by named knobs (`knob 50 2000 440 log carrier` sends `[:carrier v]`);\n- `check_patch`: the whole code — only patch calls, classes that exist, lines between ports that exist,\n every Faust source compiled and every component evaluated.\n\nThe page checks it again, and the patch loads as **one event of the history**: you can go back, branch\nor merge as with any other gesture. From the REPL: `(ask-patch \"…\")`, `(ask-patch \"…\" false)` for a\nnew patch.\n\n## Links that carry a description: `?ask=`\n\n```\nhttps://bonuoq.github.io/kairotic/?embed&ask=a hello world with a sine at 440 Hz and a knob that does FM\n```\n\nThe link carries **what to make, never a key**. Whoever opens it sees the description and **Make it\nwith Claude**: the patch is made with *their* Claude — their own Anthropic API key outside claude.ai\n(saved only in their browser; inside an embed, only for that frame) or their account inside claude.ai.\nNobody spends anybody else's credit, and a key never lands in a Notion page, its history or a server.\n\nWhat a browser made from a link stays in that browser: opening it again shows the same patch without\nasking again (**Make it again** asks anew). **Copy the link of this result** gives a `?code=` link\nwith the patch in it: put it in place of the description, and everyone sees the same patch without\nasking Claude.\n\n`?ask=` can go with `?code=` or `?src=`: then Claude changes that patch. The Share/Export panel has a\n*Carry a description instead* option, and the REPL `(ask-link \"…\")`, `(ask-link \"…\" :present)`.\n\n## Your requests, kept\n\nEvery request to Claude — a patch or a component — is kept **in your browser only**: what you asked,\nwhat Claude answered, the code, the checks and whether it worked. In the Claude tab, *Your requests to\nClaude* lists them: **Load** puts one again into the open work, **Copy** gives it as Markdown, **Export**\nsaves them all as a `.jsonl` file, and **Share on GitHub…** opens a discussion already written in the\n[Gallery](https://github.com/bonuoq/kairotic/discussions/categories/gallery) of the Kairotic repository — the request, a link to play it and the code — that you read and publish, under\nyour own account, or not. Nothing leaves your browser otherwise.\n\n## Safety\n\nThe patch Claude makes is read like a link (only patch calls, literal arguments). Its own scripts and\ncomponents run without asking, because you asked for them; the page's checks (Faust compiled,\ncomponents evaluated) happen before anything enters the work.\n","es":"# Pedir un patch\n\n*[English version](ask.md)*\n\n## En la pestaña Claude\n\nLa pestaña Claude ahora hace **patches** además de componentes. Elige *A patch*, descríbelo —«un hello\nworld: un seno a 440 Hz con un knob de volumen»— y **Make it**. Con *change the open patch* marcado\n(por defecto), Claude recibe el patch abierto y lo cambia: «ahora añade un knob que haga síntesis FM».\n\nClaude responde con el código del patch, las mismas llamadas que lleva un enlace (`box`, `connect`,\n`code`, `present`, `tree!`…). Antes de responder lo comprueba con las herramientas de la propia página:\n\n- `list_classes` y `class_help`: qué clases hay, qué recibe cada entrada y qué envía cada salida;\n- `check_faust`: para el sonido que no hacen las clases del núcleo (FM, filtros, efectos), una caja\n `faust~` cuyos parámetros mueven knobs con nombre (`knob 50 2000 440 log carrier` envía `[:carrier v]`);\n- `check_patch`: el código entero —solo llamadas de patch, clases que existen, líneas entre puertos que\n existen, cada Faust compilado y cada componente evaluado.\n\nLa página lo vuelve a comprobar y el patch se carga como **un evento de la historia**: puedes volver\natrás, ramificar o fusionar como con cualquier otro gesto. Desde la REPL: `(ask-patch \"…\")`, y\n`(ask-patch \"…\" false)` para un patch nuevo.\n\n## Enlaces que llevan una descripción: `?ask=`\n\n```\nhttps://bonuoq.github.io/kairotic/?embed&ask=un hello world con un seno a 440 Hz y un knob que haga FM\n```\n\nEl enlace lleva **qué hacer, nunca una clave**. Quien lo abre ve la descripción y **Make it with\nClaude**: el patch se hace con *su* Claude —su propia clave de API de Anthropic fuera de claude.ai\n(guardada solo en su navegador; dentro de un embed, solo para ese marco) o su cuenta dentro de\nclaude.ai. Nadie gasta el crédito de otro, y una clave nunca acaba en una página de Notion, su\nhistorial o un servidor.\n\nLo que un navegador hizo a partir de un enlace se queda en ese navegador: al abrirlo otra vez muestra\nel mismo patch sin volver a preguntar (**Make it again** pregunta de nuevo). **Copy the link of this\nresult** da un enlace `?code=` con el patch dentro: ponlo en lugar de la descripción y todo el mundo\nverá el mismo patch sin preguntar a Claude.\n\n`?ask=` puede ir con `?code=` o `?src=`: entonces Claude cambia ese patch. El panel Share/Export tiene la\nopción *Carry a description instead*, y la REPL `(ask-link \"…\")`, `(ask-link \"…\" :present)`.\n\n## Tus peticiones, guardadas\n\nCada petición a Claude —un patch o un componente— se guarda **solo en tu navegador**: lo que pediste,\nlo que respondió Claude, el código, las comprobaciones y si funcionó. En la pestaña Claude, *Your\nrequests to Claude* las lista: **Load** vuelve a ponerla en la obra abierta, **Copy** la da en Markdown,\n**Export** las guarda todas en un archivo `.jsonl`, y **Share on GitHub…** abre una discusión ya escrita en la\n[Gallery](https://github.com/bonuoq/kairotic/discussions/categories/gallery) del repositorio de Kairotic —la petición, un enlace para tocarla y el código— que tú lees y publicas, con tu\npropia cuenta, o no. Fuera de eso nada sale de tu navegador.\n\n## Seguridad\n\nEl patch que hace Claude se lee como un enlace (solo llamadas de patch, argumentos literales). Sus\nscripts y componentes propios se ejecutan sin preguntar, porque los pediste tú; las comprobaciones de\nla página (Faust compilado, componentes evaluados) se hacen antes de que nada entre en la obra.\n"},"embed":{"en":"# Embedding Kairotic\n\n*[Versión en español](embed.es.md)*\n\nA patch, a tutorial step or a help patch can live inside another page — a Notion page, a blog, a\ncourse — and still play there.\n\n## Making the link\n\nIn the editor, **Share/Export** (next to Present; it was called Embed) opens a panel with two choices:\n\n- **Patch**: the patch, scaled to fit the frame, with ▶ ■, the lesson bar if it is a tutorial, and\n **Kairotic ↗**, which opens the same thing in the whole editor.\n- **Release/Perform**: a **release** of the patch — its presets boxes keep their presets, as\n `(release)` makes it — that always opens in **Perform**: whatever is played or changed there is a take,\n never the work. Only the presented boxes (see `(present :bN x y)`), filling the frame, with small\n controls in a corner (▶ ■ ⛶ ↗) that fade while you play. The first touch starts the sound. Without\n presented boxes, the whole patch. This link always carries the patch, also from a tutorial or a help\n patch.\n\nThe panel gives the **link** and an **iframe**. From the REPL: `(embed-link)` and\n`(embed-link :release)` (also `:perform` or `:present`) print both and copy the link.\n\nWhat the link carries depends on what is open: a tutorial at a step (`?tutorial=work-tree&step=2`), a\nhelp patch (`?help=mt`) or, otherwise, **the patch itself** (`?code=…`, its code compressed). A patch\nlink is a copy of that moment, not the live work.\n\n## In Notion\n\nType `/embed` (or **+ → Embed**, in the *Embeds* group of the insert menu), paste the link, and\nresize the block. In other pages, paste the iframe.\n\n### Code written by hand: `?src=`\n\nBesides the compressed `?code=`, a link can carry the code as it is written:\n\n```\nhttps://bonuoq.github.io/kairotic/?embed&src=(box :b1 \"osc~ 440\" 20 20)(box :b2 \"dac~\" 20 80)(connect :b1 0 :b2 0)\n```\n\nBrowsers and Notion encode the spaces and quotes themselves; `+` stays `+`. It is read the same\nway as `?code=` (as data, only patch calls). It is useful for short patches, and for anyone — or\nany assistant — writing a link without the Kairotic editor at hand.\n\n### A `/kairotic` command?\n\nNotion does not let integrations add their own `/` commands, and its Link Preview API (which turned\nlinks into live previews) is closed to new developers; its *custom blocks* are in private alpha. So\ntoday the paths are `/embed` with a link, or asking Claude, with the Notion connector, to put a\nKairotic embed in a page from code written in it (a code block whose first line is `;; kairotic`).\n\nThat second path is written down as a **Notion skill**, *Kairotic: insertar un patch en la página\n(/kairotic)*: Notion AI, or any assistant connected to Notion, reads the `;; kairotic` code blocks of a\npage and puts below each one an embed with its `?src=` link (`;; kairotic present` for the\npresentation). An assistant writes the embed block through the Notion API as `<embed src=\"…\">`, and\nNotion shows it live, as if it had been pasted by hand. The iframe\nhas `allow=\"fullscreen\"`; where a page does not allow fullscreen inside its frames, ⛶ opens the\npresentation in a tab of its own.\n\n## Addresses\n\n| | |\n|---|---|\nEvery parameter can also be written after `#` instead of `?`: `…/kairotic/#code=…&present`. The links\nKairotic makes are written that way, since what is after `#` never reaches the server: a long patch\nis not refused there (a request too long is answered *414 URI Too Long*). After `#`, a parameter wins\nover the same one after `?`. Links made before, with `?`, open as they did.\n\n| `?code=…` | a patch (deflate-raw + base64url) |\n| `?src=…` | a patch, its code as written |\n| `?tutorial=id&step=n` | a tutorial at step n |\n| `?help=class` | the help patch of a class |\n| `?lang=es` / `?lang=en` | the language of lessons and help |\n| `?embed` | only the patch |\n| `?present` | Release/Perform: in Perform, only the presentation, filling the window |\n\nWithout `embed` or `present` the same addresses open in the whole editor, as a local work: from\nSessions it can be copied into a solo work or a room.\n\n## Safety\n\nAn embed works on its own: no relay, nothing saved, no Claude. The code in a link is read as data\nand only the calls a patch is made of go through (`box`, `connect`, `present`, `code`, `stroke`,\n`axis`, `tree!`, `inside`…), with literal arguments: a link cannot run code in the page. Its script and\ncomponent boxes wait, as in a shared room, until whoever opened it presses **Run them** — except\ndefinitions that are exactly an official package or component as the page brings it, which run\nwithout asking (also in rooms).\n\nThere is a test page with three frames at [embed-test.html](https://bonuoq.github.io/kairotic/embed-test.html).\n","es":"# Insertar Kairotic\n\n*[English version](embed.md)*\n\nUn patch, un paso de tutorial o un patch de ayuda pueden vivir dentro de otra página —una página de\nNotion, un blog, un curso— y seguir sonando allí.\n\n## Hacer el enlace\n\nEn el editor, **Share/Export** (junto a Present; antes se llamaba Embed) abre un panel con dos opciones:\n\n- **Patch**: el patch, escalado para caber en el marco, con ▶ ■, la barra de la lección si es un\n tutorial, y **Kairotic ↗**, que abre lo mismo en el editor completo.\n- **Release/Perform**: un **release** del patch —sus cajas presets guardan sus presets, como lo hace\n `(release)`— que se abre siempre en **Perform**: lo que se toque o cambie ahí es una toma, nunca la\n obra. Solo las cajas presentadas (ver `(present :bN x y)`), llenando el marco, con unos controles\n pequeños en una esquina (▶ ■ ⛶ ↗) que se atenúan mientras tocas. El primer toque pone en marcha el\n sonido. Sin cajas presentadas, el patch entero. Este enlace lleva siempre el patch, también desde un\n tutorial o un patch de ayuda.\n\nEl panel da el **enlace** y un **iframe**. Desde la REPL: `(embed-link)` y `(embed-link :release)`\n(también `:perform` o `:present`) escriben ambos y copian el enlace.\n\nLo que lleva el enlace depende de lo que está abierto: un tutorial en un paso\n(`?tutorial=work-tree&step=2`), un patch de ayuda (`?help=mt`) o, si no, **el propio patch**\n(`?code=…`, su código comprimido). Un enlace de patch es una copia de ese momento, no la obra viva.\n\n## En Notion\n\nEscribe `/embed` (o **+ → Insertar**, en el grupo *Integraciones* del menú de inserción), pega el\nenlace y ajusta el tamaño del bloque. En otras páginas, pega el iframe.\n\n### Código escrito a mano: `?src=`\n\nAdemás de `?code=` comprimido, un enlace puede llevar el código tal como se escribe:\n\n```\nhttps://bonuoq.github.io/kairotic/?embed&src=(box :b1 \"osc~ 440\" 20 20)(box :b2 \"dac~\" 20 80)(connect :b1 0 :b2 0)\n```\n\nLos navegadores y Notion codifican ellos mismos espacios y comillas; `+` se queda como `+`. Se lee\nigual que `?code=` (como datos, solo llamadas de patch). Sirve para patches cortos, y para quien —o\nel asistente que— escriba un enlace sin el editor de Kairotic a mano.\n\n### ¿Un comando `/kairotic`?\n\nNotion no deja que las integraciones añadan sus propios comandos `/`, y su API de Link Preview (que\nconvertía enlaces en vistas vivas) está cerrada a nuevos desarrolladores; sus *bloques personalizados*\nestán en alfa privada. Así que hoy los caminos son `/embed` con un enlace, o pedirle a Claude, con el\nconector de Notion, que ponga un embed de Kairotic en una página a partir del código escrito en ella\n(un bloque de código cuya primera línea es `;; kairotic`).\n\nEse segundo camino está escrito como **skill de Notion**, *Kairotic: insertar un patch en la página\n(/kairotic)*: Notion AI, o cualquier asistente conectado a Notion, lee los bloques de código\n`;; kairotic` de una página y pone debajo de cada uno un embed con su enlace `?src=`\n(`;; kairotic present` para la presentación). Un asistente escribe el bloque embed por la API de\nNotion como `<embed src=\"…\">`, y Notion lo muestra vivo, como si se hubiera pegado a mano. El\niframe lleva `allow=\"fullscreen\"`; donde una página no permite pantalla completa dentro de sus marcos,\n⛶ abre la presentación en una pestaña propia.\n\n## Direcciones\n\n| | |\n|---|---|\nCada parámetro se puede escribir también después de `#` en vez de `?`: `…/kairotic/#code=…&present`.\nLos enlaces que hace Kairotic se escriben así, porque lo que va después de `#` nunca llega al servidor:\nun patch largo no se rechaza allí (una petición demasiado larga recibe *414 URI Too Long*). Después de\n`#`, un parámetro gana al mismo después de `?`. Los enlaces hechos antes, con `?`, se abren como antes.\n\n| `?code=…` | un patch (deflate-raw + base64url) |\n| `?src=…` | un patch, su código tal como se escribe |\n| `?tutorial=id&step=n` | un tutorial en el paso n |\n| `?help=clase` | el patch de ayuda de una clase |\n| `?lang=es` / `?lang=en` | el idioma de lecciones y ayuda |\n| `?embed` | solo el patch |\n| `?present` | Release/Perform: en Perform, solo la presentación, llenando la ventana |\n\nSin `embed` ni `present` las mismas direcciones se abren en el editor completo, como obra local: desde\nSessions se puede copiar a una obra solo o a una sala.\n\n## Seguridad\n\nUn embed funciona solo: sin relay, sin guardar nada, sin Claude. El código de un enlace se lee como\ndatos y solo pasan las llamadas de las que está hecho un patch (`box`, `connect`, `present`, `code`,\n`stroke`, `axis`, `tree!`, `inside`…), con argumentos literales: un enlace no puede ejecutar código en\nla página. Sus cajas script y component esperan, como en una sala compartida, hasta que quien lo abre\npulsa **Ejecutarlos** —salvo las definiciones que son exactamente un paquete o componente oficial tal\ncomo lo trae la página, que se ejecutan sin preguntar (también en salas).\n\nHay una página de prueba con tres marcos en [embed-test.html](https://bonuoq.github.io/kairotic/embed-test.html).\n"},"pages":{"en":"# Kairotic outside claude.ai (GitHub Pages)\n\n*[Versión en español](pages.es.md)*\n\nKairotic is a static page: HTML, ClojureScript evaluated by Scittle, and a few modules. Inside\nclaude.ai the viewer gives it four things: a **database** (works and their history), **rooms**\n(presence of the people in a shared work), the **user** and **Claude**. The page asks\nfor them through one small layer, so the same page also runs elsewhere with another backend:\n\n| | inside claude.ai | Kairotic Pages (GitHub Pages) |\n|---|---|---|\n| database | the artifact's database | [GUN](https://gun.eco), a graph synced between browsers through relays |\n| solo works | only you see them | encrypted with a key pair that never leaves your browser |\n| rooms | anyone with access to the artifact | anyone with the site and the same relay |\n| user | your claude.ai account | a key pair made in this browser (no account) |\n| Claude | your claude.ai account (you allow it the first time) | **your own Anthropic API key**, pasted in the Claude tab |\n\nThe page chooses: if `window.claude` is there (claude.ai) it uses it; otherwise it uses\n`window.kairoticBackend`, which the Pages edition installs (`core/backends/gun-backend.js`).\n\n## Claude with your own key (BYOK)\n\nSince early 2026 a claude.ai subscription cannot be used to sign in from third-party apps, so on\nPages Claude works with an **API key** from [console.anthropic.com](https://console.anthropic.com)\n(billed per use to whoever owns the key). In the Claude tab, paste the key and press *Save*:\n\n- it is kept **only in this browser** (localStorage `kairotic.anthropicKey`), never in the work, the\n room or the relay;\n- it is sent **only to api.anthropic.com**, directly from the browser (header\n `anthropic-dangerous-direct-browser-access`), with no server in between;\n- *Forget* deletes it. Each person who uses the site uses their own key: nobody spends anyone\n else's usage.\n\nModels: quick → `claude-haiku-5-5`, balanced → `claude-sonnet-5-5`, complex → `claude-opus-5-5`.\n\n## Relays\n\nGUN syncs through **relays**: small Node servers that pass the graph between browsers and keep a\ncopy so a room is still there when people come back. GitHub Pages only serves files, so a relay\nruns somewhere else ([relay/](../relay/README.md)). Without a relay each browser works alone.\n\nThe site's relays are listed in `site/config.js`. In the session manager, **Relay** shows the ones the\npage syncs through and whether each answers; there a visitor can test and use another (its own\ncommunity's, [run with `npx @kairotic/relay`](../relay/README.md)), go back to the site's, or work\nwithout a relay. The page reloads with the choice, and while it is not the site's the address and the\nroom links (**Copy link**) carry it, so whoever opens them syncs through the same relay. The same can\nbe done in the address: a visitor can choose others for their browser\nwith `?peer=wss://host/gun` (several separated by commas; `?peer=none` goes back to the site's);\n`?peer=off` works alone, without any relay, until another `?peer=` (the tests open the app this way).\n\nEach browser keeps its own copy of what it has seen in IndexedDB (GUN's RAD), so works and rooms\nopen without a connection and sync when it comes back. Earlier versions kept it in localStorage,\nwhich holds only 5 MB (once full, nothing could be saved: \"localStorage max!\"); that copy is moved\nto IndexedDB the first time the page opens.\n\nWhat a relay sees: rooms in clear (as anyone in the room would), solo works encrypted.\n\n## Building and publishing\n\n```sh\nnode site/build.mjs # → _site/ (the app + GUN + adapter + config + boot)\ncd _site && python3 -m http.server 8000\n```\n\n`.github/workflows/pages.yml` builds and deploys it on every push to `main` that changes the page,\nthe adapter or the site. Once: *Settings → Pages → Source: GitHub Actions*. GitHub Pages serves\npublic repositories on every plan; a private one needs a paid plan.\n\n## Known limits\n\n- GUN has no access control by itself: anyone with the relay can write to a room. Solo works are\n safe because they are encrypted and signed by key, not because the relay protects them.\n- A key pair lives in one browser: moving to another browser means a new identity (export/import\n of the pair is future work).\n- `script` boxes in rooms still need `(trust-scripts true)`, as in claude.ai.\n","es":"# Kairotic fuera de claude.ai (GitHub Pages)\n\n*[English version](pages.md)*\n\nKairotic es una página estática: HTML, ClojureScript evaluado por Scittle y unos pocos módulos.\nDentro de claude.ai el visor le da cuatro cosas: una **base de datos** (las obras y su historia),\n**salas** (presencia de quienes están en una obra compartida), el **usuario** y **Claude**. La\npágina las pide a través de una capa pequeña, así que la misma página funciona también\nen otro sitio con otro backend:\n\n| | dentro de claude.ai | Kairotic Pages (GitHub Pages) |\n|---|---|---|\n| base de datos | la del artefacto | [GUN](https://gun.eco), un grafo que se sincroniza entre navegadores a través de relays |\n| obras solo | solo las ves tú | cifradas con un par de claves que no sale de tu navegador |\n| salas | quien tenga acceso al artefacto | quien tenga el sitio y el mismo relay |\n| usuario | tu cuenta de claude.ai | un par de claves creado en este navegador (sin cuenta) |\n| Claude | tu cuenta de claude.ai (lo permites la primera vez) | **tu propia clave de la API de Anthropic**, pegada en la pestaña Claude |\n\nLa página elige: si existe `window.claude` (claude.ai) lo usa; si no, usa `window.kairoticBackend`,\nque instala la edición Pages (`core/backends/gun-backend.js`).\n\n## Claude con tu propia clave (BYOK)\n\nDesde principios de 2026 una suscripción de claude.ai no se puede usar para iniciar sesión desde\naplicaciones de terceros, así que en Pages Claude funciona con una **clave de API** de\n[console.anthropic.com](https://console.anthropic.com) (se factura por uso a quien es dueño de la\nclave). En la pestaña Claude, pega la clave y pulsa *Save*:\n\n- se guarda **solo en este navegador** (localStorage `kairotic.anthropicKey`), nunca en la obra, la\n sala ni el relay;\n- se envía **solo a api.anthropic.com**, directamente desde el navegador (cabecera\n `anthropic-dangerous-direct-browser-access`), sin ningún servidor en medio;\n- *Forget* la borra. Cada persona que usa el sitio usa su propia clave: nadie gasta el uso de otra.\n\nModelos: rápido → `claude-haiku-5-5`, equilibrado → `claude-sonnet-5-5`, complejo → `claude-opus-5-5`.\n\n## Relays\n\nGUN se sincroniza a través de **relays**: servidores Node pequeños que pasan el grafo entre\nnavegadores y guardan una copia para que una sala siga ahí cuando la gente vuelve. GitHub Pages solo\nsirve archivos, así que el relay va en otro sitio ([relay/](../relay/README.es.md)). Sin relay, cada\nnavegador trabaja solo.\n\nLos relays del sitio están en `site/config.js`. En el gestor de sesiones, **Relay** muestra por cuáles\nse sincroniza la página y si cada uno responde; ahí se puede probar y usar otro (el de la propia\ncomunidad, [con `npx @kairotic/relay`](../relay/README.es.md)), volver a los del sitio o trabajar sin\nrelay. La página se recarga con la elección, y mientras no sea la del sitio la dirección y los enlaces a\nsalas (**Copy link**) la llevan, así que quien los abre se sincroniza por el mismo relay. Lo mismo se\nhace en la dirección: quien visita puede elegir otros para su navegador con\n`?peer=wss://host/gun` (varios separados por comas; `?peer=none` vuelve a los del sitio);\n`?peer=off` trabaja solo, sin ningún relay, hasta otro `?peer=` (así abren la app los tests).\n\nCada navegador guarda su propia copia de lo que ha visto en IndexedDB (RAD de GUN), así que obras y\nsalas se abren sin conexión y se sincronizan cuando vuelve. Las versiones anteriores la guardaban en\nlocalStorage, donde caben solo 5 MB (una vez lleno, no se podía guardar nada: «localStorage max!»);\nesa copia pasa a IndexedDB la primera vez que se abre la página.\n\nQué ve un relay: las salas en claro (como cualquiera en la sala), las obras solo cifradas.\n\n## Construir y publicar\n\n```sh\nnode site/build.mjs # → _site/ (la app + GUN + adaptador + config + boot)\ncd _site && python3 -m http.server 8000\n```\n\n`.github/workflows/pages.yml` lo construye y lo despliega con cada push a `main` que cambie la página,\nel adaptador o el sitio. Una vez: *Settings → Pages → Source: GitHub Actions*. GitHub Pages sirve\nrepositorios públicos con cualquier plan; uno privado necesita un plan de pago.\n\n## Límites conocidos\n\n- GUN no tiene control de acceso por sí mismo: quien tenga el relay puede escribir en una sala. Las\n obras solo están protegidas porque van cifradas y firmadas con la clave, no por el relay.\n- El par de claves vive en un navegador: cambiar de navegador es una identidad nueva (exportar e\n importar el par queda para más adelante).\n- Las cajas `script` en salas siguen necesitando `(trust-scripts true)`, como en claude.ai.\n"},"writing-a-component":{"en":"# Writing a component\n\n*[Leer en castellano](writing-a-component.es.md)*\n\nEvery box in a Kairotic patch is an instance of a **component**: a map of data and functions,\nwritten in ClojureScript. You can write one inside a work (a `component` box), share it in the\nlibrary of a space, or publish it on npm. This guide builds a small one step by step and then\nreads the `knob`, the first component with its own view.\n\n## 1. The smallest component\n\nIn the **Components** tab, press **New component** (or write `component` in a new box, or\n`(new-component!)` in the REPL): the code window opens with a template. A component box defines a\nclass and has no inlets nor outlets, so it is not drawn in the patch: the Components tab lists the\nwork's definitions, whether each one compiles, and opens them (**Edit**). Write:\n\n```clojure\n{:class \"twice\"\n :doc \"Doubles every number it receives.\"\n :io [1 1]\n :receive (fn [{:keys [value]}]\n (if (number? value) {:out [[0 (* 2 value)]]} {}))}\n```\n\nApply it (Ctrl/⌘+Enter). The box shows `✓ defines «twice»`, and now you can create boxes\ncalled `twice`.\n\n- `:class` is the first word of the box text.\n- `:io [inlets outlets]`.\n- `:receive` is a **pure function**: it gets a message and returns what should happen.\n\n## 2. Messages\n\n`:receive` gets a map:\n\n| key | what it is |\n|---|---|\n| `:inlet` | the inlet the message arrived at (0 is the left one) |\n| `:value` | the message: a number, a list, a keyword such as `:bang` |\n| `:state` | what the box kept last time (nil at first) |\n| `:args` | the arguments written in the box text |\n| `:at` | the time of the message on the audio clock |\n\n…and returns a map with any of:\n\n| key | what it does |\n|---|---|\n| `:out [[outlet value] …]` | sends values out, in this order |\n| `:state x` | keeps `x` for the next message |\n| `:later [[at inlet value] …]` | schedules messages to itself in the future |\n| `:effects [[k x] …]` | effects on its audio node, a task (`:tasks`), `[:keep d]`, or `[:print x]` |\n| `:show v` | what the box shows (a number box displays it; an own view draws it) |\n\n## 3. Declared arguments\n\nWrite the arguments as a section instead of parsing the text yourself:\n\n```clojure\n :args [[:factor 2]]\n```\n\nNow `twice 3` gives `(:args m)` = `{:factor 3}`, and `twice` alone gives `{:factor 2}`. The kind of\nthe default decides how the words of the box fill each argument:\n\n- a **number**, or the key of an earlier argument (`[:initial :min]`), takes the next number;\n- `true` / `false` is a **flag**, on when its own name is written (`[:log false]` ↔ `knob 20 20000 log`);\n- anything else (`nil`, a string) takes the next free **word**, as a keyword (`[:name nil]` ↔ `knob 0 1 cutoff`).\n\n## 4. A view of its own\n\nA component can be drawn in the patch and respond to dragging. The view is **data**: a list of\nshapes in box coordinates, not HTML. The values that change are **holes**, keywords that start with\n`$`, and `:derive` gives their values:\n\n```clojure\n :size [72 78]\n :derive (fn [{:keys [shown args]}] {:angle … :label …})\n :view [[:arc {:cx 36 :cy 33 :r 23 :from -135 :to :$angle :stroke :accent :weight 5}]\n [:text {:x 36 :y 72 :anchor :middle} :$label]]\n```\n\nShapes: `:rect` `:circle` `:line` `:arc` `:needle` `:path` `:text`, `:curve` (a smooth path through\n`:points`) and `:group` (`[:group {:x :y :rotate :scale} [shapes …]]`, shapes moved, turned and scaled\ntogether). Colours come from a palette that follows the light or dark theme: `:ink` `:soft` `:accent`\n`:kairos` `:bg` `:grid`, in `:stroke` and `:fill`; `:weight` is the line width and `:opacity` (0…1)\nmakes any shape lighter. Holes can also name an argument (`:$min`) or `:shown`, `:w`, `:h`.\n\nA shape with **`:hit k`** can be pressed: the `:gesture` of the box receives `:hit k` (the shape on top\nunder the press, or the group with `:hit` that holds it), so a view can have parts to click — the nodes of\nthe Tonnetz in `@kairotic/theory`, the shapes of a `draw` box.\n\n`:shown` is the last thing the box returned as `:show`. `:gesture` turns a drag into a value:\n\n```clojure\n :gesture (fn [{:keys [start dy fine]}] …) ; start = what was shown on press, dy since the press\n```\n\nThe value goes to the box's own inlet 0 while you drag. When you let go, `:gesture` is called once\nmore with `:up true`, and what it returns is written in the history as `(send! :bN value)`. A gesture\nthat ignores `:up` (a knob) repeats its last value; one that needs press and release (a keyboard)\nreturns a release message, so the history and the other people in a room never keep a note held.\n\nFor views that are hard to express as a template there is an escape hatch, `:draw (fn [m] shapes)`.\n\n## 5. Sections\n\nPut the sections in this order, with a comment line before each one:\n\n```clojure\n;; knob · a rotary control with its own view in the patch\n{;; ── about ──\n :class \"knob\" :license \"MPL-2.0\" :doc \"…\" :usage \"knob [min max initial] [log] [name]\"\n :io [1 1] :size [72 78]\n\n ;; ── arguments ──\n :args [[:min 0] [:max 1] [:initial :min] [:log false] [:name nil]]\n\n ;; ── logic ──\n :receive (fn [m] …)\n :gesture (fn [m] …)\n :derive (fn [m] …)\n\n ;; ── view ──\n :view [[:arc …] [:circle …] [:needle …] [:text … :$label]]}\n```\n\nOnly the logic is code; the rest is data that can be read, checked and changed without running\nanything. Read the whole [knob](../packages/controls/src/knob.cljs) (in `@kairotic/controls`).\n\nHelpers available in the logic come from the **Kairotic API**, `api/…`: `api/clamp`, `api/nice` (sensible rounding), `api/num-of`,\n`api/to-unit` and `api/from-unit` (a value ⇄ 0…1, linear or logarithmic), `api/padded` (the numbers\nof a box text with defaults), and for audio `api/stereo-outlets`, `api/worklet-node` (an\nAudioWorklet whose JavaScript travels inside the component) and `api/param`. The API has a version\n(`api/version`): a package declares the one it was written for, and the core only breaks it with a\nnew major version. See [`core/kairotic/api.cljs`](../core/kairotic/api.cljs).\n\n**From the sound back to the messages.** An audio node cannot send messages: it *reports* what it\nfinds to its own box with `(api/report! (:id b) value at)` (`b` is the box its `:create` got, `at` the\ntime of the sound), and the box's `:receive` gets it on inlet `:audio`, where it decides what to send,\nshow and keep, as with any other message. To listen to a signal, `(api/tap ac opts on-block)` gives a\nworklet that hands it over every `:hop` samples, as `:frames` (the samples), a `:summary` (last value,\nrms, peak) or a `:trace` (min and max per column, steady on a zero crossing, for a picture); the loops\nover samples run in the worklet. `api/retap` changes its sizes and `api/db` turns a level into\ndecibels. Read [`snapshot~` and `scope~`](../core/kairotic/input.cljs). For the form of what arrives, `api/ssm`,\n`api/novelty`, `api/novelty-at` (one frame of a stream), `api/beat-spectrum`, `api/periods` and `api/boundaries`\n(read [`form~`](../packages/analysis/src/form.cljs)). A tap made with\n`:active false` hands nothing until `(api/retap w {:active true})`, and `{:flush true}` hands at once\nwhat was heard since its last block; `(api/effect! id [k x])` asks the page for an effect of the box\neven when the engine has just stopped — [`sample`](../core/kairotic/sounds.cljs) records that way.\n\n**From outside: tasks.** `:receive` never touches the network, a file or a timer of its own. What a box\nneeds from outside is a **task**: the component declares `:tasks {:get (fn [x box] promise)}` (impure,\nlike `:audio`), its `:receive` asks for one with the effect `[:get x]`, and the engine runs it — with or\nwithout ▶ — and gives the outcome back to the same box on inlet `:task`, as\n`{:task :get :arg x :value v}` or `{:task :get :arg x :error \"…\"}`. There, as with any message, the\nbox decides what to send, show and keep. The `box` a task gets carries `:wired`, what its outlets reach\n(`[{:outlet 0 :inlet 0 :id :b4 :class \"faust~\" :data {…}} …]`): [`realize~`](../packages/analysis/src/realize.cljs)\nlearns the `faust~` it drives that way. Compare `:arg` with the request `:state` is waiting for, so a\nlate answer to an older request is dropped. What a task finds lives in this tab, like what is sounding;\nto make it part of the work, return the effect `[:keep d]`: `d` becomes the data of the box (its\n`:model` `:load` reads it) as a gesture of the history — the same for everyone in a room, and going\nback in the history does not ask again. `api/http-get` makes the request (JSON as EDN, text or EDN, with\nreasons in words when it fails) and `api/url-of` reads a URL from a message, `github:owner/repo/path`\nincluded. Read [`fetch`](../packages/data/src/fetch.cljs) (in `@kairotic/data`).\n\n## 5½. The same value twice\n\nA box can receive the same value again: data boxes (a `tree`) send what they hold again after ■, when\na line toward the box is new or a box before it changed, and when someone else's gesture reaches it in\na room. Receiving it again must change **nothing that is going on**: a player does not start over, an\naccumulator does not count it twice, a learner does not learn it twice. Compare the value with what\n`:state` already keeps and, if it is the same, return the state as it is:\n\n```clojure\n(cond (= value (:last state)) {:state state} ; the same again: nothing changes\n …)\n```\n\nA class can be a data box of its own, as `tree` is: with **`:sends (fn [box] value)`** the page sends\nthat value out of outlet 0 whenever the text or the data of the box changes, and again toward a new line\nor a box after it that changed (`box` is `{:id :text :args :data}`; return nil while it is not ready,\nsuch as a source still compiling). `pbind` and `pattern` (in\n[`@kairotic/patterns`](../packages/patterns/README.md)) send their pattern this way.\n\n## 6. A component made of a patch\n\nNot every class needs code. A **sub-patch** is a `patch` box: double-click it to open it (or\n`(enter :b5)`, and `(up)` to come back). Inside, `inlet` / `outlet` (messages) and `inlet~` /\n`outlet~` (audio) boxes are its ports, numbered from left to right. In code it reads:\n\n```clojure\n(box :b5 \"patch voice\" 40 360)\n(inside :b5\n (box :b1 \"inlet\" 20 20)\n (box :b2 \"synth~\" 20 80)\n (box :b3 \"outlet~\" 20 140)\n (connect :b1 0 :b2 0)\n (connect :b2 0 :b3 0))\n```\n\n`(abstract :b5 \"voice\")` turns it into a class: a `component` box with a `:patch` instead of\n`:receive`, and `:b5` becomes an instance. In the texts inside, `$1 $2 …` take the words written\nafter the class name:\n\n```clojure\n{:class \"detune\"\n :doc \"Multiplies every frequency by a ratio ($1).\"\n :usage \"detune ratio\"\n :patch {:boxes {:b1 {:text \"inlet\" :x 20 :y 20}\n :b2 {:text \"* $1\" :x 20 :y 70}\n :b3 {:text \"outlet\" :x 20 :y 120}}\n :lines [[:b1 0 :b2 0] [:b2 0 :b3 0]]}}\n```\n\n`detune 1.5` is then a fifth above. The engine replaces every sub-patch by its boxes (`:b5.b2`…),\nso they cost nothing at run time.\n\n### Seen from outside: panels\n\nMark boxes inside a sub-patch with `(present :b4 x y)` (or just `(present :b4)`) and the sub-patch is\ndrawn from outside as a **panel** of them, like a bpatcher in Max: its knobs can be played without\nopening it. This also works for abstractions, since `:present` travels inside `:patch`. In the work\nitself, the presented boxes make up the **presentation**: press *Present* (or `(presentation true)`)\nto see only them, where the performer needs them. Moving a box there changes its presentation place,\nnot its place in the patch.\n\n## 6½. Asking Claude to write it\n\nThe **Claude** tab (or `(ask-component \"…\")` in the REPL) writes a component from a\ndescription. Claude reads this same contract, the API and real components as examples, and before it\nanswers it tries what it wrote with the page's tools: it evaluates and validates it, sends it\nmessages and draws its view. The result is an ordinary `component` box, with a header saying it was\nwritten with Claude and what was asked; edit it like any other. With a component chosen in the Components tab (a click on its row), or\nopen in the code window, \"change the selected component\" asks for a change to it instead. It runs on the Claude account of\nwhoever uses the page, who is asked for permission the first time.\n\nIt can also write Faust (it compiles it to check it), abstractions with `faust~` boxes\nand knobs, and bpatchers (abstractions whose presented boxes make the panel of every instance), and a\npackage when it needs several definitions together. It reads examples from the\n[catalog](../examples/README.md), which is how we teach it new kinds of components.\n\n## 6¾. Its help\n\nThe Help tab (or **?** on a selected box) shows what a class does port by port, with a\nhelp patch that opens as a lesson. A component brings its own with `:help`:\n\n```clojure\n:help {:inlets [\"a number: the frequency in Hz\" \"the depth, 0…1\"] ; one line per inlet, from 0\n :outlets [\"the signal\"]\n :messages [[\"bang\" \"starts again\"]]\n :example \"(box :b1 \\\"wobble~ 4\\\" 40 30)\\n(box :b2 \\\"dac~\\\" 40 90)\\n(connect :b1 0 :b2 0)\"\n :try \"Press ▶ and change the rate.\"\n :see [\"osc~\" \"gain~\"]}\n```\n\nThe example is patch code, one gesture per line: opening the help patch makes them one by one.\n\nA box with many options can also carry `:about` — an introduction in short paragraphs (`**bold**`, `` `code` ``),\nshown first, with its whole `:doc` folded below it — and `:args`, what each of its declared arguments does, in\norder: `[[:rate \"how many wobbles a second\"] [:depth \"0…1\"]]`, the third column of its Arguments table.\n\n## 7. Sharing it\n\n- **In the work:** the `component` box travels with the work and its history (it is part of the\n work's code, `(box :bN \"component\" 0 0)` and `(code :bN …)`, though the patch does not draw it).\n- **In the library of the space:** `(publish :bN)` and, in another work, `(use! \"class\")`.\n- **On npm:** publish a module that exports the component (`export default {class, version, author,\n license, doc, source}`, the format [`packages/build.mjs`](../packages/build.mjs) writes); anyone can\n then `(import! \"npm:<your-package>@x.y.z/dist/<name>.mjs\")`.\n- **In an official package**: add it to `packages/<category>/src/` (see\n [`packages/`](../packages/README.md)). A package travels as one `component` box, and writing one of\n its classes in a work brings it in.\n\nImporting always **copies** the definition into a `component` box of the work, with a header that\nsays where it came from and under which licence: the work stays complete and sounds the same even\nif the package changes later.\n","es":"# Escribir un componente\n\n*[Read in English](writing-a-component.md)*\n\nCada caja de un patch de Kairotic es una instancia de un **componente**: un mapa de datos y\nfunciones escrito en ClojureScript. Se puede escribir dentro de una obra (una caja `component`),\ncompartir en la biblioteca de un espacio o publicar en npm. Esta guía construye uno pequeño paso a\npaso y después lee la `knob`, el primer componente con vista propia.\n\nEl código y los nombres están en inglés; el [glosario](glossary.md) da la equivalencia de cada término.\n\n## 1. El componente más pequeño\n\nEn la pestaña **Components**, pulsa **New component** (o escribe `component` en una caja nueva, o\n`(new-component!)` en la REPL): se abre la ventana de código con una plantilla. Una caja component define\nuna clase y no tiene entradas ni salidas, así que no se dibuja en el patch: la pestaña Components lista\nlas definiciones de la obra, si cada una compila, y las abre (**Edit**). Escribe:\n\n```clojure\n{:class \"twice\"\n :doc \"Doubles every number it receives.\"\n :io [1 1]\n :receive (fn [{:keys [value]}]\n (if (number? value) {:out [[0 (* 2 value)]]} {}))}\n```\n\nAplícalo (Ctrl/⌘+Enter). La caja muestra `✓ defines «twice»` y ya puedes crear cajas `twice`.\n\n- `:class` es la primera palabra del texto de la caja.\n- `:io [entradas salidas]`.\n- `:receive` es una **función pura**: recibe un mensaje y devuelve lo que debe pasar.\n\n## 2. Mensajes\n\n`:receive` recibe un mapa:\n\n| clave | qué es |\n|---|---|\n| `:inlet` | la entrada por la que llega el mensaje (0 es la izquierda) |\n| `:value` | el mensaje: un número, una lista, una palabra como `:bang` |\n| `:state` | lo que la caja guardó la última vez (nil al principio) |\n| `:args` | los argumentos escritos en el texto de la caja |\n| `:at` | el instante del mensaje en el reloj de audio |\n\n…y devuelve un mapa con cualquiera de estas claves:\n\n| clave | qué hace |\n|---|---|\n| `:out [[salida valor] …]` | manda valores, en este orden |\n| `:state x` | guarda `x` para el siguiente mensaje |\n| `:later [[at entrada valor] …]` | programa mensajes a sí misma en el futuro |\n| `:effects [[k x] …]` | efectos en su nodo de audio, una tarea (`:tasks`), `[:keep d]` o `[:print x]` |\n| `:show v` | lo que muestra la caja (una caja number lo enseña; una vista propia lo dibuja) |\n\n## 3. Argumentos declarados\n\nEscribe los argumentos como una sección en vez de interpretar el texto a mano:\n\n```clojure\n :args [[:factor 2]]\n```\n\nAhora `twice 3` da `(:args m)` = `{:factor 3}`, y `twice` solo da `{:factor 2}`. El tipo del valor\npor defecto decide cómo se rellena cada argumento con las palabras de la caja:\n\n- un **número**, o la clave de un argumento anterior (`[:initial :min]`), toma el siguiente número;\n- `true` / `false` es un **interruptor**, activo si se escribe su nombre (`[:log false]` ↔ `knob 20 20000 log`);\n- cualquier otra cosa (`nil`, un texto) toma la siguiente **palabra** libre, como keyword (`[:name nil]` ↔ `knob 0 1 cutoff`).\n\n## 4. Una vista propia\n\nUn componente puede dibujarse en el patch y responder al arrastre. La vista son **datos**: una\nlista de figuras en coordenadas de la caja, no HTML. Los valores que cambian son **huecos**,\nkeywords que empiezan por `$`, y `:derive` les da valor:\n\n```clojure\n :size [72 78]\n :derive (fn [{:keys [shown args]}] {:angle … :label …})\n :view [[:arc {:cx 36 :cy 33 :r 23 :from -135 :to :$angle :stroke :accent :weight 5}]\n [:text {:x 36 :y 72 :anchor :middle} :$label]]\n```\n\nFiguras: `:rect` `:circle` `:line` `:arc` `:needle` `:path` `:text`, `:curve` (un trazo suave que\npasa por `:points`) y `:group` (`[:group {:x :y :rotate :scale} [figuras …]]`, figuras movidas, giradas y\nescaladas juntas). Los colores salen de una paleta que sigue el tema claro u oscuro: `:ink` `:soft`\n`:accent` `:kairos` `:bg` `:grid`, en `:stroke` y `:fill`; `:weight` es el grosor y `:opacity` (0…1)\naclara cualquier figura. Un hueco también puede nombrar un argumento (`:$min`) o `:shown`, `:w`, `:h`.\n\nUna figura con **`:hit k`** se puede pulsar: el `:gesture` de la caja recibe `:hit k` (la figura de\nencima bajo la pulsación, o el grupo con `:hit` que la contiene), así una vista puede tener partes que se\npulsan —los nodos del Tonnetz de `@kairotic/theory`, las figuras de una caja `draw`.\n\n`:shown` es lo último que la caja devolvió como `:show`. `:gesture` convierte un arrastre en un valor:\n\n```clojure\n :gesture (fn [{:keys [start dy fine]}] …) ; start = lo que se veía al pulsar, dy desde la pulsación\n```\n\nEl valor llega a la entrada 0 de la propia caja mientras arrastras. Al soltar, `:gesture` se llama\nuna vez más con `:up true`, y lo que devuelve queda escrito en la historia como `(send! :bN valor)`.\nUn gesto que ignora `:up` (un knob) repite su último valor; uno que necesita pulsar y soltar (un\nteclado) devuelve un mensaje de soltar, para que ni la historia ni el resto de la sala se queden con\nuna nota pulsada.\n\nPara vistas difíciles de expresar como plantilla existe una salida de emergencia:\n`:draw (fn [m] figuras)`.\n\n## 5. Secciones\n\nEscribe las secciones en este orden, con una línea de comentario antes de cada una:\n\n```clojure\n;; knob · a rotary control with its own view in the patch\n{;; ── about ──\n :class \"knob\" :license \"MPL-2.0\" :doc \"…\" :usage \"knob [min max initial] [log] [name]\"\n :io [1 1] :size [72 78]\n\n ;; ── arguments ──\n :args [[:min 0] [:max 1] [:initial :min] [:log false] [:name nil]]\n\n ;; ── logic ──\n :receive (fn [m] …)\n :gesture (fn [m] …)\n :derive (fn [m] …)\n\n ;; ── view ──\n :view [[:arc …] [:circle …] [:needle …] [:text … :$label]]}\n```\n\nSolo la lógica es código; el resto son datos que se pueden leer, comprobar y cambiar sin ejecutar\nnada. Lee la [knob](../packages/controls/src/knob.cljs) completa (en `@kairotic/controls`).\n\nLas utilidades disponibles en la lógica vienen de la **API de Kairotic**, `api/…`: `api/clamp`, `api/nice` (redondeo razonable), `api/num-of`, `api/to-unit` y\n`api/from-unit` (un valor ⇄ 0…1, lineal o logarítmico), `api/padded` (los números del texto de una\ncaja con valores por defecto), y para audio `api/stereo-outlets`, `api/worklet-node` (un AudioWorklet\ncuyo JavaScript viaja dentro del componente) y `api/param`. La API tiene versión (`api/version`): un\npaquete declara para cuál se escribió, y el núcleo solo la rompe con una versión mayor nueva. Ver\n[`core/kairotic/api.cljs`](../core/kairotic/api.cljs).\n\n**Del sonido de vuelta a los mensajes.** Un nodo de audio no puede enviar mensajes: *informa* de lo que\nencuentra a su propia caja con `(api/report! (:id b) valor at)` (`b` es la caja que recibió su\n`:create`, `at` el instante del sonido), y el `:receive` de la caja lo recibe por el inlet `:audio`,\ndonde decide qué enviar, mostrar y guardar, como con cualquier otro mensaje. Para escuchar una señal,\n`(api/tap ac opts on-block)` da un worklet que la entrega cada `:hop` muestras, como `:frames` (las\nmuestras), un `:summary` (último valor, rms, pico) o un `:trace` (mínimo y máximo por columna, estable\nsobre un cruce por cero, para dibujarla); los bucles sobre las muestras se ejecutan en el worklet.\n`api/retap` cambia sus tamaños y `api/db` pasa un nivel a decibelios. Lee\n[`snapshot~` y `scope~`](../core/kairotic/input.cljs). Para la forma de lo que llega, `api/ssm`, `api/novelty`,\n`api/novelty-at` (un marco de un flujo), `api/beat-spectrum`, `api/periods` y `api/boundaries` (lee\n[`form~`](../packages/analysis/src/form.cljs)). Un tap creado con `:active false` no entrega\nnada hasta `(api/retap w {:active true})`, y `{:flush true}` entrega en el acto lo oído desde su\núltimo bloque; `(api/effect! id [k x])` pide a la página un efecto de la caja incluso cuando el motor\nacaba de pararse — [`sample`](../core/kairotic/sounds.cljs) graba así.\n\n**Desde fuera: tareas.** `:receive` nunca toca la red, un archivo ni un temporizador propio. Lo que una\ncaja necesita de fuera es una **tarea**: el componente declara `:tasks {:get (fn [x box] promise)}`\n(impura, como `:audio`), su `:receive` la pide con el efecto `[:get x]`, y el motor la ejecuta —con o\nsin ▶— y devuelve el resultado a la misma caja por la entrada `:task`, como\n`{:task :get :arg x :value v}` o `{:task :get :arg x :error \"…\"}`. Ahí, como con cualquier mensaje, la\ncaja decide qué envía, muestra y guarda. Compara `:arg` con la petición que espera su `:state`, para\ndescartar la respuesta tardía a una petición anterior. Lo que encuentra una tarea vive en esta pestaña,\ncomo lo que suena; para que forme parte de la obra, devuelve el efecto `[:keep d]`: `d` pasa a ser el\ndato de la caja (lo lee el `:load` de su `:model`) como un gesto de la historia —el mismo para todos en\nuna sala, y volver atrás en la historia no lo pide de nuevo—. `api/http-get` hace la petición (JSON como\nEDN, texto o EDN, con los motivos en palabras si falla) y `api/url-of` lee una URL de un mensaje,\n`github:owner/repo/ruta` incluido. Lee [`fetch`](../packages/data/src/fetch.cljs) (en `@kairotic/data`).\n\n## 5½. El mismo valor dos veces\n\nUna caja puede recibir otra vez el mismo valor: las cajas de datos (un `tree`) vuelven a enviar lo que\ntienen después de ■, cuando una línea hacia la caja es nueva o cambió una caja anterior, y cuando el\ngesto de otra persona llega en una sala. Recibirlo otra vez **no debe cambiar nada de lo que está en\nmarcha**: un reproductor no vuelve a empezar, un acumulador no lo cuenta dos veces, un aprendiz no lo\naprende dos veces. Compara el valor con lo que ya guarda `:state` y, si es el mismo, devuelve el estado\ntal cual:\n\n```clojure\n(cond (= value (:last state)) {:state state} ; lo mismo otra vez: nada cambia\n …)\n```\n\nUna clase puede ser una caja de datos propia, como `tree`: con **`:sends (fn [box] valor)`** la página\nenvía ese valor por el outlet 0 cada vez que cambian el texto o los datos de la caja, y otra vez hacia una\nlínea nueva o una caja posterior que cambió (`box` es `{:id :text :args :data}`; devuelve nil mientras no\nesté listo, como una fuente que aún se compila). `pbind` y `pattern` (en\n[`@kairotic/patterns`](../packages/patterns/README.md)) envían así su pattern.\n\n## 6. Un componente hecho de un patch\n\nNo todas las clases necesitan código. Un **sub-patch** es una caja `patch`: doble clic para abrirla\n(o `(enter :b5)`, y `(up)` para volver). Dentro, las cajas `inlet` / `outlet` (mensajes) e\n`inlet~` / `outlet~` (audio) son sus puertos, numerados de izquierda a derecha. En código se lee:\n\n```clojure\n(box :b5 \"patch voice\" 40 360)\n(inside :b5\n (box :b1 \"inlet\" 20 20)\n (box :b2 \"synth~\" 20 80)\n (box :b3 \"outlet~\" 20 140)\n (connect :b1 0 :b2 0)\n (connect :b2 0 :b3 0))\n```\n\n`(abstract :b5 \"voice\")` lo convierte en clase: una caja `component` con `:patch` en vez de\n`:receive`, y `:b5` pasa a ser una instancia. En los textos de dentro, `$1 $2 …` toman las palabras\nescritas después del nombre de la clase:\n\n```clojure\n{:class \"detune\"\n :doc \"Multiplies every frequency by a ratio ($1).\"\n :usage \"detune ratio\"\n :patch {:boxes {:b1 {:text \"inlet\" :x 20 :y 20}\n :b2 {:text \"* $1\" :x 20 :y 70}\n :b3 {:text \"outlet\" :x 20 :y 120}}\n :lines [[:b1 0 :b2 0] [:b2 0 :b3 0]]}}\n```\n\n`detune 1.5` sube entonces una quinta. El motor sustituye cada sub-patch por sus cajas (`:b5.b2`…),\nasí que no cuestan nada al sonar.\n\n### Vistos desde fuera: paneles\n\nMarca cajas dentro de un sub-patch con `(present :b4 x y)` (o solo `(present :b4)`) y el sub-patch se\ndibuja desde fuera como un **panel** con ellas, como un bpatcher de Max: sus knobs se pueden tocar sin\nabrirlo. También funciona con las abstracciones, porque `:present` viaja dentro de `:patch`. En la\nobra, las cajas presentadas forman la **presentación**: pulsa *Present* (o `(presentation true)`) para\nver solo esas, donde las necesita quien interpreta. Mover una caja ahí cambia su lugar en la\npresentación, no su lugar en el patch.\n\n## 6½. Pedírselo a Claude\n\nLa pestaña **Claude** (o `(ask-component \"…\")` en la REPL) escribe un componente a\npartir de una descripción. Claude lee este mismo contrato, la API y componentes reales como ejemplos, y\nantes de responder prueba lo que ha escrito con las herramientas de la página: lo evalúa y valida, le\nenvía mensajes y dibuja su vista. El resultado es una caja `component` normal, con una cabecera que dice\nque se escribió con Claude y qué se pidió; se edita como cualquier otra. Con un componente elegido en\nla pestaña Components (un clic en su fila), o abierto en la ventana de código, \"change the selected\ncomponent\" pide un cambio sobre él. Usa la cuenta de Claude de\nquien usa la página, a quien se pide permiso la primera vez.\n\nTambién escribe Faust (lo compila para comprobarlo), abstracciones con cajas `faust~`\ny knobs, y bpatchers (abstracciones cuyas cajas presentadas forman el panel de cada instancia), y un\npaquete cuando necesita varias definiciones juntas. Lee ejemplos del [catálogo](../examples/README.md),\nque es como le enseñamos nuevos tipos de componentes.\n\n## 6¾. Su ayuda\n\nLa pestaña Help (o **?** sobre una caja seleccionada) explica qué hace una clase,\nentrada por entrada, con un patch de ayuda que se abre como una lección. Un componente trae la suya con `:help`:\n\n```clojure\n:help {:inlets [\"un número: la frecuencia en Hz\" \"la profundidad, 0…1\"] ; una línea por entrada, desde 0\n :outlets [\"la señal\"]\n :messages [[\"bang\" \"vuelve a empezar\"]]\n :example \"(box :b1 \\\"wobble~ 4\\\" 40 30)\\n(box :b2 \\\"dac~\\\" 40 90)\\n(connect :b1 0 :b2 0)\"\n :try \"Pulsa ▶ y cambia la velocidad.\"\n :see [\"osc~\" \"gain~\"]}\n```\n\nEl ejemplo es código de patch, un gesto por línea: al abrir el patch de ayuda se hacen uno a uno.\n\nUna caja con muchas opciones puede llevar también `:about` — una introducción en párrafos cortos (`**negrita**`,\n`` `código` ``), que se muestra primero, con todo su `:doc` plegado debajo — y `:args`, qué hace cada uno de sus\nargumentos declarados, en orden: `[[:rate \"cuántas oscilaciones por segundo\"] [:depth \"0…1\"]]`, la tercera columna de\nsu tabla de argumentos.\n\n## 7. Compartirlo\n\n- **En la obra:** la caja `component` viaja con la obra y su historia (es parte del código de la obra,\n `(box :bN \"component\" 0 0)` y `(code :bN …)`, aunque el patch no la dibuje).\n- **En la biblioteca del espacio:** `(publish :bN)` y, en otra obra, `(use! \"clase\")`.\n- **En npm:** publica un módulo que exporte el componente (`export default {class, version, author,\n license, doc, source}`, el formato que escribe [`packages/build.mjs`](../packages/build.mjs));\n cualquiera podrá hacer `(import! \"npm:<tu-paquete>@x.y.z/dist/<nombre>.mjs\")`.\n- **En un paquete oficial**: añádelo a `packages/<categoría>/src/` (ver\n [`packages/`](../packages/README.es.md)). Un paquete viaja como una sola caja `component`, y escribir\n una de sus clases en una obra lo trae.\n\nImportar siempre **copia** la definición en una caja `component` de la obra, con una cabecera que\ndice de dónde viene y con qué licencia: la obra queda completa y suena igual aunque el paquete\ncambie después.\n"},"reference":{"en":"# Class reference\n\n*Made from the help of Kairotic 0.2.0-alpha (the Help tab shows the same, and the help of classes a work defines). Generated: do not edit by hand — `(reference-md)` in the REPL writes it.*\n\n### !-\n\n`!- n`\n\nArithmetic the other way round: argument - left inlet (!- 1 turns seconds into Hz); lists too.\n\n**Inlets** \n\n0. a number or a list: subtracted from the right one\n1. the minuend (stored)\n\n**Outlets** \n\n0. the difference\n\nSee also: `-`\n\n### !/\n\n`!/ n`\n\nArithmetic the other way round: argument / left inlet (!/ 1 turns seconds into Hz); lists too.\n\n**Inlets** \n\n0. a number or a list: what divides the right one (0 if it is 0)\n1. the dividend (stored)\n\n**Outlets** \n\n0. the quotient: !/ 1 gives 1 / the number\n\nSee also: `/`, `sample`\n\n### *\n\n`* n`\n\nArithmetic: left inlet * argument (or the last thing that came in on the right); lists too.\n\n**Inlets** \n\n0. a number or a list: times the right one\n1. the factor (stored)\n\n**Outlets** \n\n0. the product\n\nSee also: `+`, `/`\n\n### +\n\n`+ n`\n\nArithmetic: left inlet + argument (or the last thing that came in on the right); lists too.\n\n**Inlets** \n\n0. a number or a list: it adds the right one and sends the result\n1. the number to add (stored, nothing is sent)\n\n**Outlets** \n\n0. the sum\n\n**Try:** The right inlet only stores: change it, then drag the left number to hear (read) the result. A fifth above is + 7.\n\n```clojure\n(box :b1 \"number 60\" 40 30)\n(box :b2 \"number 7\" 130 30)\n(box :b3 \"+ 7\" 40 90)\n(box :b4 \"print\" 40 150)\n(connect :b1 0 :b3 0)\n(connect :b2 0 :b3 1)\n(connect :b3 0 :b4 0)\n```\n\nSee also: `-`, `*`, `/`\n\n### -\n\n`- n`\n\nArithmetic: left inlet - argument (or the last thing that came in on the right); lists too.\n\n**Inlets** \n\n0. a number or a list: minus the right one\n1. the number to subtract (stored)\n\n**Outlets** \n\n0. the difference\n\nSee also: `+`\n\n### /\n\n`/ n`\n\nArithmetic: left inlet / argument (or the last thing that came in on the right); lists too.\n\n**Inlets** \n\n0. a number or a list: divided by the right one (0 if it is 0)\n1. the divisor (stored)\n\n**Outlets** \n\n0. the quotient\n\nSee also: `*`, `!/`\n\n### adc~\n\n`adc~ [channel …]`\n\nAudio input (the microphone or the sound card): one outlet per input channel, the ones written after it (adc~ 1 by default; adc~ 1 2 for stereo). At ▶ it asks for the microphone, and takes its sound as it is, without the echo cancellation, noise suppression and automatic gain made for speech. Every adc~ shares one stream.\n\n**Outlets** \n\n0. one signal per input channel: those written after it (1 by default)\n\n**Try:** Press ▶ and allow the microphone: sing or clap and watch the scope and the level. It does not go to dac~, so it cannot feed back; send it through a gain~ to hear it (with headphones).\n\n```clojure\n(box :b1 \"adc~ 1\" 40 30)\n(box :b2 \"scope~ 20\" 40 80)\n(box :b3 \"snapshot~ 50 db\" 240 80)\n(box :b4 \"print\" 240 140)\n(connect :b1 0 :b2 0)\n(connect :b1 0 :b3 0)\n(connect :b3 0 :b4 0)\n```\n\nSee also: `dac~`, `snapshot~`, `scope~`\n\n### adsr~ · `@kairotic/synth`\n\n`adsr~ [a d s r]`\n\nAn envelope that follows a gate, for the factor of a gain~. Drag over it to change its shape.\n\n**Inlets** \n\n0. a gate (signal or numbers: above 0 attacks, 0 releases), a bang, or [a d s r]\n\n**Outlets** \n\n0. the envelope signal, 0…peak\n\n**Try:** Start the engine and click the bang: a plucked note. Drag over the envelope to make it longer.\n\n```clojure\n(box :b1 \"bang\" 40 30)\n(box :b2 \"adsr~ 10 300 0 400\" 40 80)\n(box :b3 \"osc~ 440\" 220 80)\n(box :b4 \"gain~ 0\" 220 220)\n(box :b5 \"dac~\" 220 270)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b4 1)\n(connect :b3 0 :b4 0)\n(connect :b4 0 :b5 0)\n(connect :b4 0 :b5 1)\n```\n\nSee also: `gain~`, `reader~`, `synth~`\n\n### bang\n\nA button: when pressed (or on receiving anything) it sends a bang.\n\n**Inlets** \n\n0. anything: it flashes and sends a bang\n\n**Outlets** \n\n0. bang\n\n**Messages and gestures**\n\n- `click`: sends a bang\n\n**Try:** Start the engine and click the bang: each click counts one more.\n\n```clojure\n(box :b1 \"bang\" 40 30)\n(box :b2 \"counter 1\" 40 90)\n(box :b3 \"print\" 40 150)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n```\n\nSee also: `msg`, `loadbang`, `metro`\n\n### cancrizans · `@kairotic/theory`\n\n`cancrizans [system] [mode] [k -7] [beats 2] [bars 6] [temp 0] [seed 1] [table] [live] [midi]`\n\n**A crab canon: the second voice is your line backwards**, both sounding at once, so the work reads the same from either end. With `table` it is also upside down: one score read by two players from opposite sides of a table — a musical ambigram.\n\n**It is written from both ends to the middle**, because the comes's first note is the dux's last: each step writes a note at the start and then one at the end. A note that breaks a rule, or from which the crab could not be closed, is corrected to the nearest one that can. On the right, the **futuribles**: the notes that can come next, each with the ways it leaves to close the work. When it closes, both voices go out as patterns (for `pbind` and `player`) and as a score (outlet 4, for a `tree` box).\n\n**live** (Study 46) plays it beat by beat. In the first half you play and the box answers each note, at the same beat, with the end of your own line; at the middle the rest of your line comes out as a score to read, and while you read it the box plays your first half backwards. Both voices sound from it, with their voice ids, on one `synth~`.\n\n**System and mode** as in `comes`, in any order, and with the flags: `cancrizans hypodorian`, `cancrizans pentatonic penta-A table live`. The mode sets the range, the notes to begin on, the final it ends on and the axis of a table canon; its tenor plays no part here.\n\nA crab canon written from both ends to the middle (Study 43): the comes is the dux backwards; with table, backwards and upside down — the score read by a second player from across the table, a musical ambigram. Each step writes a note at the start, then one at the end; the futuribles are the ways to close the work in the middle. When it closes, both voices go out as patterns.\n\n**Arguments**\n\n- `system`: the scale, its tuning and its rules: diatonic (by default), meantone, septimal31 or pentatonic\n- `mode`: one of the system's modes (dorian by default): its range, the notes to begin on, the final, the axis of table\n- `k`: how far away the comes is, in steps of the scale: −7 an octave below\n- `beats`: beats in a bar: 2 or 3\n- `bars`: its length in bars: longer, more ways to write it (and longer to count)\n- `temp`: live: chance in the box's answers (0: always the one :end says)\n- `seed`: the seed of its chance: the same seed, the same game\n- `table`: a table canon: backwards and upside down\n- `live`: played beat by beat (Study 46) instead of written by turns from both ends\n- `midi`: numbers in are MIDI notes (62), not Hz\n\n**Inlets** \n\n0. the next note (at the start, then at the end): Hz, a list of keys held, [:midi 62], an event (:freq, or a player's :hz), or MIDI with midi · :engine · :back · :reset · [:k -4], [:mode :hypodorian], [:system :pentatonic], [:bars 5], [:table true], [:axis 62]: a new work\n1. live: the pulse (a bang from a metro or a pulse): a beat, with your note or the box's for you\n\n**Outlets** \n\n0. the dux, when the work closes, as a pattern {:note [...] :dur [...]} (for a pbind) · live: the Hz of both voices, yours and the box's, as a player sends them (for a synth~)\n1. the comes, as a pattern · live: their voice ids, sent first (for a synth~'s right inlet)\n2. the futuribles: the notes that can come next ({:midi :name :futures}; live, with :end, what the box will answer at the end)\n3. where the work is: {:step :steps :writing :beat :futures :dux :comes :closed :asked :played :corrected}\n4. the score, as a musical tree (for a tree box, its score): when the work closes, both voices; live, at the middle what is left of your line to read, and at the end the whole crab\n\n**Messages and gestures**\n\n- `[:midi 62]`: a MIDI note as the next note (Hz, a keyboard's list or an event also)\n- `:engine`: the next note, written by the box (live: a beat, with the box playing your note)\n- `:back`: the last note taken back\n- `:reset`: a new work\n- `[:system :septimal31]`: another system (or an EDN map) — these start a new work\n- `[:mode :hypodorian]`: another mode of the system\n- `[:k -4]`: the comes a 5th below\n- `[:bars 5]`: another length\n- `[:table true]`: a table canon: backwards and upside down\n- `[:axis 62]`: the axis of a table canon, a MIDI note (the final by default)\n- `[:temp 2]`: live: the box draws among its answers\n- `[:seed 7]`: live: its chance (:reset plays the same game again)\n\n**Try:** Click :engine until the work closes: the box writes it from both ends, and the dux and the comes reach the pbinds. Press ▶ and click :start: the crab sounds, each voice on its own synth~ (one synth~ plays one line: a note from the other player would take the place of the last). The tree box below shows the crab as a score: read the comes from the end and it is the dux. Play notes on a keyboard into it instead (the note at the start, then the one at the end).\n\n```clojure\n(box :b1 \"msg :engine\" 40 30)\n(box :b2 \"cancrizans\" 40 80)\n(box :b3 \"pbind\" 40 150)\n(box :b4 \"pbind\" 40 260)\n(box :b9 \"msg :start\" 40 370)\n(box :b5 \"player 90\" 40 420)\n(box :b6 \"player 90\" 240 420)\n(box :b7 \"synth~\" 40 490)\n(box :b17 \"synth~\" 240 490)\n(box :b8 \"dac~\" 40 550)\n(box :b10 \"print\" 260 80)\n(box :b19 \"tree\" 40 620)\n(resize :b19 460 200)\n(connect :b2 4 :b19 0)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n(connect :b2 1 :b4 0)\n(connect :b3 0 :b5 1)\n(connect :b4 0 :b6 1)\n(connect :b9 0 :b5 0)\n(connect :b9 0 :b6 0)\n(connect :b5 0 :b7 0)\n(connect :b6 0 :b17 0)\n(connect :b7 0 :b8 0)\n(connect :b7 0 :b8 1)\n(connect :b17 0 :b8 0)\n(connect :b17 0 :b8 1)\n(connect :b2 3 :b10 0)\n```\n\n**Played live** — With live (Study 46) the crab is played beat by beat: your note, and at the same beat the box's answer — the end of your own line, written ahead. Two beats before the middle a cue; at the middle the rest of your line comes out as the score to read (outlet 4, a musical tree for a score), and the box plays your first half backwards while you read it. Both voices sound from its left outlet, after their voice ids (outlet 1): one synth~ plays both. The first note to read is the last end of your line the box wrote (with an odd number of beats the middle note is shared: the box plays it with you, an octave below); from there each voice plays what the other played, backwards.\n\n*Try:* Press ▶: the loadbang counts the futures. The html box shows where the crab is and its futuribles as a table — each note you can play, the ways it leaves to close the crab, and :end, what the box will answer at the end of your line. Play D on the keyboard: the box answers with D an octave below — both voices on one synth~, yours as the box takes it (corrected if it must be), with their voice ids (1→1). Play on: at the middle the tree box shows, as a score, what is left of your line to read — the box's answers so far, backwards —; at the end it shows the whole crab.\n\n```clojure\n(box :b11 \"keyboard 60 24\" 520 30)\n(box :b12 \"cancrizans live\" 520 150)\n(box :b13 \"synth~\" 520 230)\n(box :b15 \"loadbang\" 720 110)\n(box :b16 \"html\" 860 30)\n(resize :b16 300 230)\n(code :b16 \"[:div.col [:h4 \\\"beat \\\" :$t \\\" of \\\" :$n \\\" · \\\" :$phase] [:p.soft :$ways \\\" ways to close it\\\"] :$in]\")\n(box :b14 \"tree\" 860 290)\n(resize :b14 460 180)\n(connect :b15 0 :b12 0)\n(connect :b12 2 :b16 0)\n(connect :b12 3 :b16 0)\n(connect :b12 4 :b14 0)\n(connect :b11 0 :b12 0)\n(connect :b12 0 :b13 0)\n(connect :b12 1 :b13 1)\n(connect :b13 0 :b8 0)\n(connect :b13 0 :b8 1)\n```\n\nSee also: `comes`, `pbind`, `player`\n\n### canvas\n\nGraphic buffer for any numeric data: strokes in a plane with axes of any range, linear or log ((axis :b1 :y -1 1)). A number on the inlet (or a click) comes out on the left; edits on the inlet ([:stroke pts], [:erase :t1], [:clear], [:batch [...]]) change it, and questions ([:read x], [:strokes], [:get :t1], [:data]) are answered on the left. The right outlet is the buffer for a reader, which can read it along X or Y.\n\n**Inlets** \n\n0. a position (or a click): it comes out on the left · an edit ([:stroke [[x y] …]], [:erase :t1], [:clear], [:axis :y 0 1]… or [:batch [edits]]): it changes the buffer, as one event · a question ([:read x], [:strokes], [:get :t1], [:count], [:end], [:range], [:data]): the answer comes out on the left · a musical tree: shown over it\n\n**Outlets** \n\n0. the position, or the answer to a question\n1. the buffer, for a reader or reader~ (on their right inlet)\n\n**Messages and gestures**\n\n- `(axis :bN :x -1 1)`: range of an axis, :log for logarithmic\n- `(stroke :bN [[x y] …])`: draws\n- `the corner · (resize :bN 640 300)`: drag its bottom-right corner to resize it; a double-click there brings back its size\n- `[:stroke [[0 0] [1 1]]] · [:stroke :t3 pts]`: a stroke by message (a new id, or that one)\n- `[:move :t1 dx dy] · [:stretch :t1 k] · [:erase :t1] · [:clear]`: edit strokes by message\n- `[:axis :x lo hi] · [:axis :y lo hi :log] · [:grid-y step]`: axes and grid by message\n- `[:batch [[:clear] [:stroke pts] …]]`: several edits, one event of the history\n- `[:read 0.5] · [:read :y 0.2] · [:strokes] · [:get :t1] · [:count] · [:range] · [:data]`: questions: the answer comes out on the left\n- `{ } in the header (or a double-click on its right) · (source :bN)`: the buffer as EDN text, in the code window: edit it and apply (Ctrl+Enter); what changed is one event\n\n**Try:** Press ▶: the reader goes along X and prints the height of the stroke. Draw another stroke and listen to the list grow.\n\n```clojure\n(box :b1 \"canvas\" 40 60)\n(box :b2 \"loadbang\" 40 15)\n(box :b3 \"ramp 0 1 4 loop\" 120 15)\n(box :b4 \"reader\" 40 290)\n(box :b5 \"print\" 40 340)\n(connect :b2 0 :b3 0)\n(connect :b3 0 :b4 0)\n(connect :b1 1 :b4 1)\n(connect :b4 0 :b5 0)\n(axis :b1 :x 0 1)\n(axis :b1 :y 0 1)\n(stroke :b1 [[0 0.2] [0.5 0.9] [1 0.4]])\n```\n\n**An automation** — A reader~ goes along the canvas at audio rate: its value is a signal that can move a parameter, here the factor of a gain~ (a tremolo drawn by hand).\n\n*Try:* Press ▶: the stroke becomes the volume of the oscillator every two seconds. Draw a zigzag and listen to it.\n\n```clojure\n(box :b6 \"phasor~ 0.5\" 300 15)\n(box :b7 \"reader~ norm\" 300 290)\n(box :b8 \"osc~ 330\" 420 290)\n(box :b9 \"gain~ 0\" 420 340)\n(box :b10 \"dac~\" 420 390)\n(connect :b6 0 :b7 0)\n(connect :b1 1 :b7 1)\n(connect :b8 0 :b9 0)\n(connect :b7 0 :b9 1)\n(connect :b9 0 :b10 0)\n(connect :b9 0 :b10 1)\n```\n\n**A path in two dimensions** — With reader path, the position (0…1) goes along a stroke, and both its X and Y come out: a trajectory, for space~ or for two parameters at once.\n\n*Try:* Press ▶: print writes [x y] as the reader goes around the shape. Connect its outlet to a space~ (see its help) to move a sound along it.\n\n```clojure\n(clear :b1)\n(axis :b1 :x -1 1)\n(axis :b1 :y -1 1)\n(stroke :b1 [[0 0.8] [0.7 0.4] [0.5 -0.6] [-0.6 -0.5] [-0.7 0.5] [0 0.8]])\n(text! :b4 \"reader path\")\n```\n\nSee also: `reader`, `reader~`, `freqt`\n\n### chroma~ · `@kairotic/analysis`\n\n`chroma~ [ms]`\n\nHow much of each pitch class a signal has: 12 values from C to B, and the strongest class as a word.\n\n**Inlets** \n\n0. the signal\n\n**Outlets** \n\n0. 12 values, C to B, 0…1 (the strongest 1)\n1. the strongest pitch class (:c … :b), when it changes\n\n**Try:** Press ▶ and play a chord or a drone: the bars show its pitch classes; print writes the strongest.\n\n```clojure\n(box :b1 \"adc~ 1\" 40 30)\n(box :b2 \"chroma~\" 40 90)\n(box :b3 \"print\" 40 170)\n(connect :b1 0 :b2 0)\n(connect :b2 1 :b3 0)\n```\n\nSee also: `pitch~`, `mt`, `features~`\n\n### comes · `@kairotic/theory`\n\n`comes [system] [mode] [k -7] [d 3] [beats 2] [imitation 1] [bars 8] [upbeat 0] [temp 0] [seed 1] [fourth] [inversion] [augmentation] [live] [nocues] [midi]`\n\n**You play a line, the dux, and comes answers with a second voice, the comes, that imitates it** — a canon, a few beats later, by the rules of 16th-century counterpoint. A note that breaks a rule, or from which the canon could not be finished, is corrected to the nearest one that can be played, and the box says why.\n\n**Two ways to play.** By turns (the default): each note you send is a beat; the same note again, or `:hold`, holds it over the beat. With **live**, a pulse on the right inlet (a `metro`) gives the beats and a note lasts until you play the next one; held three beats in 2/2 the canon turns to 3/2, longer than a bar the section ends and the next note begins a new canon.\n\n**Where it plays: a system and one of its modes.** The **system** is the scale, its tuning and its rules: `diatonic` (the default), `meantone`, `septimal31`, `pentatonic`, or your own as EDN. The **mode** is one of its modes — `dorian` (the default), `hypodorian`, `ionian`, `aeolian`…; in the pentatonic `penta-C`, `penta-A`, `penta-D` — and sets the final, the range and the notes to begin on. Write them in the box in any order: `comes hypodorian`, `comes pentatonic penta-A`.\n\n**How the comes imitates.** `k` steps away (−7: an octave below) and `d` beats later. `imitation` 1 is a strict canon; lower, the comes moves more freely. `inversion` turns it upside down, `augmentation` makes it twice as slow, and `fourth` makes your line a cantus firmus (a note a bar) with the comes syncopated against it.\n\n**What comes out.** Both voices as Hz with their voice ids — one `synth~`, connected 0→0 and 1→1, plays both —; on the right the **futuribles**, the notes you can play next, the most plausible first, each with the ways it leaves to finish the canon (counted exactly), and where the canon is.\n\nCounterpoint live: you play the dux and the comes answers, as a canon in a mode (Study 41). A note that breaks a rule of the style, or from which the canon could not be finished, is corrected to the nearest one that can be played, and the box says why. Notes may be held over the beat (ties), and a dissonance may fall on a strong beat as a suspension. By turns (the default) one note in is one beat; live, a pulse on the right is a beat, and a note lasts until the next one is struck. The system (Study 42) — the scale, its tuning and its rules — is diatonic by default, or meantone, septimal31, pentatonic, or an EDN map: its modes come with it, and the notes out are tuned.\n\n**Arguments**\n\n- `system`: the scale, its tuning and its rules: diatonic (by default), meantone, septimal31 or pentatonic\n- `mode`: one of the system's modes: dorian (by default), hypodorian, ionian, mixolydian, aeolian and their plagals; penta-C, penta-A, penta-D in the pentatonic\n- `k`: how far away the comes imitates, in steps of the scale: −7 an octave below, −4 a 5th below, 0 at the unison\n- `d`: how many beats after the dux the comes comes in\n- `beats`: beats in a bar: 2 (2/2) or 3 (3/2)\n- `imitation`: 1 a strict canon · 0.5–0.9 the comes near the dux's notes · 0.2–0.4 only following its motion · below, free\n- `bars`: how long the canon is, in bars\n- `upbeat`: beats of rest before the first note (an anacrusis)\n- `temp`: chance: at 0 always the most plausible; higher, the comes (and the dux with :engine) drawn among the candidates\n- `seed`: the seed of its chance: the same seed, the same game\n- `fourth`: fourth species: your line a cantus firmus, a note a bar, and the comes syncopated\n- `inversion`: the comes upside down, about the final (or [:axis 62])\n- `augmentation`: the comes twice as slow (a strict canon, six bars at most)\n- `live`: played on a pulse (the right inlet) instead of by turns\n- `nocues`: live: it does not turn to 3/2 or end the section by itself; other boxes decide, with [:beats 3] and :end\n- `midi`: numbers in are MIDI notes (62), not Hz\n\n**Inlets** \n\n0. the dux's next note: Hz (a number, or the list of notes held, as a keyboard or midiin sends them), [:midi 62], or an event (:freq from midiin, or a player's :hz) · :hold (by turns) · [:k -4], [:d 2], [:imitation 0.5], [:mode :hypodorian], [:system :pentatonic], [:beats 3], [:species 4]: the canon changed (by turns at once, live at the next section) · :end (the section ends: the next note begins a new canon) · :engine · :back · :reset\n1. live: the pulse (a bang from a metro or a pulse): a beat\n\n**Outlets** \n\n0. the Hz of both voices sounding, the dux (as played, or corrected) and the comes, as a keyboard or a player sends them\n1. their voice ids, sent first (for a synth~'s right inlet): a note held keeps its id and goes on sounding\n2. the futuribles: the notes that can come next, the most plausible first ({:midi :name :futures :bits :score :comes})\n3. where the canon is: {:t :n :bar :beat :held :asked :played :corrected :reason :comes :futures :bits :obligations :section :meter …}, or a cue {:cue :ternary|:end :section :meter}\n\n**Messages and gestures**\n\n- `[:midi 62]`: a MIDI note as the dux's next note (Hz, a keyboard's list or an event also)\n- `:engine`: the box plays the next pair itself, the most plausible\n- `:hold`: by turns: the note held over the next beat (a tie)\n- `:back`: the last pair taken back\n- `:reset`: a new canon\n- `:end`: the section ends: the next note begins a new canon\n- `[:system :pentatonic]`: another system (or an EDN map {:tuning … :modes …}) — these change the canon: by turns at once, live at the next section\n- `[:mode :hypodorian]`: another mode of the system\n- `[:k -4]`: the comes a 5th below\n- `[:d 2]`: the comes two beats after the dux\n- `[:imitation 0.5]`: less imitation: the comes near the dux's notes\n- `[:beats 3]`: 3/2\n- `[:species 4]`: fourth species (with [:beats 2])\n- `[:transform :inversion]`: the comes upside down; :augmentation twice as slow; :canon back to a canon\n- `[:axis 62]`: the axis of the inversion, a MIDI note\n- `[:temp 1.5]`: chance in the comes, and in the dux of :engine (0: the futuribles' choice)\n- `[:seed 7]`: its chance: the same seed, the same game (:reset plays it again)\n\n**Try:** Press ▶ and play D, E, F on the keyboard: the dux. From the fourth note on the comes answers an octave below, three beats later. Play a black key, or a note against the rules: the box takes the nearest one that can be played and prints why. Click :engine to let it go on alone.\n\n```clojure\n(box :b1 \"keyboard 60 24\" 40 30)\n(box :b2 \"comes\" 40 130)\n(box :b3 \"synth~\" 40 200)\n(box :b5 \"dac~\" 40 260)\n(box :b6 \"print\" 280 200)\n(box :b7 \"msg :engine\" 220 100)\n(connect :b1 0 :b2 0)\n(connect :b7 0 :b2 0)\n(connect :b2 0 :b3 0)\n(connect :b2 1 :b3 1)\n(connect :b3 0 :b5 0)\n(connect :b3 0 :b5 1)\n(connect :b2 3 :b6 0)\n```\n\n**Live, on a pulse** — With live, a metro gives the beats: hold a key and the note is held over them (a tie); hold it three beats in 2/2 and the canon turns to 3/2; longer than a bar, and the section ends: the next note begins a new canon. That is all comes reads of time: with nocues it leaves the meter and the sections to other boxes, which send [:beats 3] and end.\n\n*Try:* Press ▶, click 1 to start the pulse and play slowly: the comes answers on the beats. Hold a note three beats: the cue :ternary is printed.\n\n```clojure\n(box :b8 \"metro 600\" 380 100)\n(box :b9 \"msg 1\" 380 70)\n(box :b10 \"comes live\" 380 160)\n(connect :b9 0 :b8 0)\n(connect :b8 0 :b10 1)\n(connect :b1 0 :b10 0)\n(connect :b10 0 :b3 0)\n(connect :b10 1 :b3 1)\n(connect :b10 3 :b6 0)\n```\n\nSee also: `keyboard`, `midiin`, `metro`, `pulse`, `tonnetz`\n\n### component\n\n`component`\n\nDefines a box class inside the work: its source is a map {:class :doc :io :receive …} with the same contract as any component.\n\n**Messages and gestures**\n\n- `source`: a map {:class \"x\" :doc … :io [1 1] :receive (fn [m] …)}: defines the class x in the work\n- `New component (Components tab) · (new-component!)`: a new definition, from a template, open in the code window\n- `Edit · × (Components tab)`: its code in the code window · removes it (one event of the history)\n- `a click on its row`: chooses it: the Claude tab can then change it\n\nSee also: `script`, `faust~`\n\n### counter\n\n`counter step [max] [min]`\n\nEach bang sends the value and advances one step; goes back to the minimum on reaching the maximum.\n\n**Inlets** \n\n0. bang (or a number): sends the value and advances one step · :reset: back to the minimum\n1. a number sets the next value\n\n**Outlets** \n\n0. the value\n\nSee also: `metro`\n\n### dac~\n\n`dac~ [channel …]`\n\nAudio output: each inlet is an output channel, the ones written after it (dac~ 1 2 by default; dac~ 1 2 3 4 … if the sound card has them).\n\n**Inlets** 2: one inlet per output channel: those written after it (1 2 by default)\n\n**Try:** Only the left channel sounds: connect the gain~ to the right inlet too.\n\n```clojure\n(box :b1 \"osc~ 330\" 40 30)\n(box :b2 \"gain~ 0.2\" 40 80)\n(box :b3 \"dac~ 1 2\" 40 130)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n```\n\nSee also: `gain~`, `pan~`, `space~`, `adc~`\n\n### dispatch\n\n`dispatch n [selector] · right: k · nil · true · a function, keyword, map or set`\n\nA message to one of several outlets, numbered from 0: dispatch n has n of them. The right inlet chooses the way: a number k is outlet k; nil or false closes it (nothing goes out); true is outlet 0, so dispatch 1 is a gate that opens and closes. A function chooses for each message — a name or a form (comp …, partial …), a keyword, a map ({60 0 64 1}): what it gives for the message is the outlet, nil lets nothing through — and a set lets its members through outlet 0. The selector can be written after n (dispatch 3 0, dispatch 2 {60 0 64 1}); a msg sends it as written (msg 1, msg nil, msg :freq). Named after the dispatch function of Clojure's multimethods, which looks at a value and chooses where it goes.\n\n**Inlets** \n\n0. a message: goes out by the outlet the selector chooses (or by none)\n1. the selector: k (outlet k, from 0) · nil or false (closed) · true (outlet 0) · a function, keyword or map that chooses for each message · a set (its members by outlet 0)\n\n**Outlets** \n\n0. outlet 0\n1. outlet 1 … (dispatch n has n)\n\n**Messages and gestures**\n\n- `msg 1`: every message by outlet 1\n- `msg nil`: nothing goes out\n- `msg {60 0 64 1}`: 60 by outlet 0, 64 by outlet 1, anything else by none\n- `msg :to`: each message by the outlet its :to says ({:freq 440 :to 1})\n\n**Try:** Click a selector on the right (0, 1, nil or the map) and then the notes on the left: each note goes out by the way chosen — the REPL says which, out0 or out1 — or by none. With the map, 60 and 64 choose their own way and 67 is held back.\n\n```clojure\n(box :b1 \"msg 60\" 40 30)\n(box :b2 \"msg 64\" 100 30)\n(box :b3 \"msg 67\" 160 30)\n(box :b4 \"msg 0\" 260 30)\n(box :b5 \"msg 1\" 320 30)\n(box :b6 \"msg nil\" 380 30)\n(box :b7 \"msg {60 0 64 1}\" 470 30)\n(box :b8 \"dispatch 2\" 40 100)\n(box :b9 \"print out0\" 40 170)\n(box :b10 \"print out1\" 200 170)\n(connect :b1 0 :b8 0)\n(connect :b2 0 :b8 0)\n(connect :b3 0 :b8 0)\n(connect :b4 0 :b8 1)\n(connect :b5 0 :b8 1)\n(connect :b6 0 :b8 1)\n(connect :b7 0 :b8 1)\n(connect :b8 0 :b9 0)\n(connect :b8 1 :b10 0)\n```\n\nSee also: `msg`, `get`\n\nReference: [Multimethods: a dispatch function chooses](https://clojure.org/reference/multimethods) · [Truthiness: nil and false](https://clojure.org/guides/learn/flow#_truth) · [Maps, sets and keywords as functions](https://clojure.org/reference/data_structures)\n\n### draw\n\n`draw [width height]`\n\nA view drawn from the messages that arrive: each shape of kairotic.shapes ([:circle {:cx 40 :cy 40 :r 10 :fill :accent}], [:line …], [:path {:points [[x y] …]}], [:text {:x :y} \"…\"], [:curve …], [:group {:x :y :rotate} [shapes]]) is added — or as a msg writes it: :circle 40 40 10 :accent, :rect x y w h, :line x1 y1 x2 y2, :arc cx cy r from to, :text x y \"words\", with a colour and :hit name; a list of shapes replaces them all; [:set k shape] (:set k :circle …) adds or replaces the shape called k (to move a cursor), [:unset k] removes it, :clear empties it. A shape with :hit k, pressed, sends k out.\n\n**Inlets** \n\n0. a shape ([:circle {:cx 40 :cy 40 :r 10 :fill :accent}]) is added; a list of shapes replaces them all; [:set k shape] adds or replaces the one called k; [:unset k] removes it; clear\n\n**Outlets** \n\n0. the :hit of a shape pressed (a shape with :hit k sends k)\n\n**Messages and gestures**\n\n- `[:circle {:cx :cy :r}]`: a circle (also :rect :line :arc :needle :path :curve :text and :group)\n- `[[:line …] [:text …]]`: a list: replaces everything\n- `[:set :cursor [:line …]]`: the shape called :cursor, added or moved\n- `[:unset :cursor]`: removes it\n- `:clear`: empties the view\n\n**Try:** Click the three messages, then press the circles: print writes :sun or :moon. From code, any shape of kairotic.shapes: (send! :b4 [:curve {:points [[10 90] [80 20] [150 80] [230 30]] :stroke :accent}]). Shapes take the theme's colours (:ink :soft :accent :kairos :bg :grid) and :opacity.\n\n```clojure\n(box :b1 \"msg :circle 60 55 22 :accent :hit :sun\" 40 30)\n(box :b2 \"msg :circle 160 55 14 :kairos :hit :moon\" 360 30)\n(box :b3 \"msg :set :label :text 20 100 \\\"press one of them\\\"\" 40 70)\n(box :b4 \"draw 240 120\" 40 120)\n(box :b5 \"print\" 40 270)\n(connect :b1 0 :b4 0)\n(connect :b2 0 :b4 0)\n(connect :b3 0 :b4 0)\n(connect :b4 0 :b5 0)\n```\n\nSee also: `monitor`, `pcclock`, `msg`\n\n### edn · `@kairotic/data`\n\n`edn [width height]`\n\nAny value as a tree, like Portal: collections open and close, values coloured by kind; picking a line sends that part (left) and its path (right).\n\n**Inlets** \n\n0. any value; :depth n opens it n levels down; bang sends the part picked again; :clear\n\n**Outlets** \n\n0. the part picked\n1. its path, for [:get …] of a fetch box\n\n**Messages and gestures**\n\n- `:depth 2`: opens it two levels down\n- `bang`: the part picked again (the whole value if none)\n- `:clear`: empties it\n- `▸ ▾ · a line · a drag`: opens or closes · picks it · scrolls (also the bar on the right)\n\n**Try:** The tree arrives: open the measure and pick a note: the note and its path go to print.\n\n```clojure\n(box :b1 \"tree\" 40 30)\n(tree! :b1 [:voice [:measure {:meter [4 4]} \"c4/1 e4 g4 c5\"]])\n(box :b2 \"edn 320 220\" 40 130)\n(box :b3 \"print\" 400 130)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n(connect :b2 1 :b3 0)\n```\n\nSee also: `fetch`, `print`, `tree`\n\n### euclid · `@kairotic/theory`\n\n`euclid [k 3] [n 8] [rotation 0] [bars 1] [midi]`\n\n**A Euclidean rhythm: k onsets spread as evenly as they can be over n pulses**, by Bjorklund's algorithm — Euclid's, for the greatest common divisor, on ones and zeros. Toussaint showed that it writes rhythms of the whole world: `euclid 3 8` is the tresillo (3-3-2), `euclid 5 8` the cinquillo, `euclid 5 16` a rotation of the bossa nova, `euclid 7 12` the bembé.\n\n**Drawn as a necklace**: the n pulses around a circle, time running clockwise from the top, the onsets joined into a polygon — the same geometry as a pitch-class set on `pcclock`. A necklace has no start; pressing a pulse makes the rhythm start there (a rotation), which may sound quite different.\n\n**Rhythm apart from pitch.** It goes out as a musical tree for a `tree` box: a bar of n pulses with an `:rtm` whose shares are the intervals between onsets (a negative share a silence). Its right inlet takes the pitches the notes take in turn, starting again when they run out — *talea* and *color*, as in an isorhythmic motet: a keyboard's chord, a melody string, a map `{:pitches …}`, the pattern of `comes`. Its middle outlet is the `:rtm` map alone, to merge with other pitches elsewhere.\n\nA Euclidean rhythm (Bjorklund, after Toussaint): k onsets as evenly as they can be over n pulses, drawn as a necklace; pressing a pulse makes it start there. Out: a musical tree with an :rtm (the intervals as shares), the :rtm map alone, and the pulses as ones and zeros. The right inlet gives the pitches its notes take in turn.\n\n**Arguments**\n\n- `k`: how many onsets\n- `n`: how many pulses in the bar\n- `rotation`: the pulse it starts on (a rotation of the necklace)\n- `bars`: how many bars: the rhythm again, the pitches going on\n- `midi`: numbers on the right inlet are MIDI notes (62), not Hz\n\n**Inlets** \n\n0. a bang: send it · a number: k · [:k 5], [:n 16], [:rotation 2], [:bars 4], [:meter \"3/4\"] (or a map of them): change it, and send it when it is new\n1. the pitches (cold, for the next time it sends): a list of Hz (a keyboard's keys held; MIDI with midi), a melody string (\"c4 e4 g4\"), a map with :pitches or :pitch, a pattern {:note [...]} of comes or cancrizans, notes or chords of a tree · :clear forgets them (every note c4)\n\n**Outlets** \n\n0. the rhythm as a musical tree, for a tree box: [:voice [:measure {:meter [4 4]} [:rtm {:shares [3 3 2] :pitches …}]] …]\n1. the :rtm map alone ({:shares [3 3 2]}, with the pitches if it has them): merge it with other pitches, and write it as a node with vector :rtm %\n2. the pulses, ones and zeros ([1 0 0 1 0 0 1 0])\n\n**Messages and gestures**\n\n- `:bang`: sends it\n- `[:k 5]`: five onsets (a number alone is k too)\n- `[:n 16]`: sixteen pulses\n- `[:rotation 2]`: starts on the third pulse\n- `[:bars 4]`: four bars, the pitches going on from bar to bar\n- `[:meter \"3/4\"]`: a bar of another meter (by default 4/4 for 8 or 16 pulses, 12/8 for 12, n/8 up to 12, else n/16; nil goes back to it)\n- `:clear`: on the right: forgets the pitches\n\n**Try:** Click bang: the tresillo, 3-3-2, in the tree box as eighths in 4/4. Click [:k 5]: the cinquillo; then [:n 16]: five in sixteen, a rotation of the bossa nova; [:rotation 3] starts it on the fourth pulse — a silence first. Press a pulse on the necklace: the rhythm starts there.\n\n```clojure\n(box :b1 \"msg :bang\" 40 20)\n(box :b2 \"msg [:k 5]\" 120 20)\n(box :b3 \"msg [:n 16]\" 210 20)\n(box :b4 \"msg [:rotation 3]\" 310 20)\n(box :b5 \"euclid 3 8\" 40 70)\n(box :b6 \"tree\" 260 70)\n(resize :b6 420 160)\n(box :b7 \"print pulses\" 40 300)\n(connect :b1 0 :b5 0)\n(connect :b2 0 :b5 0)\n(connect :b3 0 :b5 0)\n(connect :b4 0 :b5 0)\n(connect :b5 0 :b6 0)\n(connect :b5 2 :b7 0)\n```\n\n**Pitches: talea and color** — The right inlet gives the notes their pitches, in turn, starting again when they run out: three pitches over five onsets take three bars to meet the rhythm again, as the color and the talea of an isorhythmic motet. It is cold: what arrives there sounds the next time the box sends. A keyboard sends the keys held, in Hz; a melody string or a map {:pitches …} is kept as it is.\n\n*Try:* With five onsets ([:k 5] above), click {:pitches \"c4 e4 g4\"}, then [:bars 3] (it sends): C E G over the onsets, the color going on from bar to bar. Press ▶ and click the bang of mt play to hear it. Hold a chord on the keyboard and click bang above: the chord's notes, one onset each.\n\n```clojure\n(box :b8 \"keyboard 60 24\" 720 20)\n(box :b9 \"msg {:pitches \\\"c4 e4 g4\\\"}\" 720 110)\n(box :b10 \"msg [:bars 3]\" 450 20)\n(box :b11 \"mt play loop\" 260 260)\n(box :b12 \"msg :bang\" 380 230)\n(box :b13 \"synth~\" 260 310)\n(box :b14 \"dac~\" 260 360)\n(connect :b8 0 :b5 1)\n(connect :b9 0 :b5 1)\n(connect :b10 0 :b5 0)\n(connect :b6 0 :b11 0)\n(connect :b12 0 :b11 0)\n(connect :b11 0 :b13 0)\n(connect :b11 1 :b13 1)\n(connect :b13 0 :b14 0)\n(connect :b13 0 :b14 1)\n```\n\nSee also: `tree`, `mt`, `pcclock`, `pbind`\n\n### faust~\n\n`faust~`\n\nFaust code box: compiled in the page and played as an AudioWorklet. Its audio ports are those of process; the left inlet also accepts parameters ([:freq 440], a list of Hz with gate). With declare options \"[nvoices:8]\" it is polyphonic: Hz on the left and voice ids on the right, as synth~ (a keyboard, a reader, mt play), and an effect = …; for all of them.\n\n**Inlets** \n\n0. audio inputs of process (if any); the left one also takes parameters: [:freq 440]\n\n**Outlets** \n\n0. audio outputs of process\n\n**Messages and gestures**\n\n- `(code :bN \"process = …;\")`: writes its source\n- `double-click`: edit the code, beside its patch of Faust's own elements (Patch in the bar hides it); Ctrl+Enter applies\n- `Recipe (in the window's bar)`: the values of its sliders that sound closest to a sample box or a sound file, written in the code; Ctrl+Enter applies them\n- `declare options \"[nvoices:8]\"`: polyphonic: Hz on the left, voice ids on the right (a second inlet), as synth~; each id a voice\n- `[:gain 0.6] · :stop`: polyphonic: the velocity of the next notes · releases every voice\n- `effect = …;`: polyphonic: applied once to the sum of the voices\n\n**Try:** Press ▶. Then change 1200 in the code and apply with Ctrl+Enter: the filter opens.\n\n```clojure\n(box :b1 \"faust~\" 40 30)\n(box :b2 \"dac~\" 40 200)\n(connect :b1 0 :b2 0)\n(connect :b1 0 :b2 1)\n(code :b1 \"import(\\\"stdfaust.lib\\\");\\nf = hslider(\\\"freq\\\", 220, 50, 2000, 1);\\nprocess = os.sawtooth(f) * 0.1 : fi.lowpass(2, 1200);\")\n```\n\n**Polyphonic: a keyboard** — With declare options \"[nvoices:8]\" the source is a voice: its freq, gain and gate are set note by note by Faust's own allocator, for up to 8 notes at once (the oldest is taken when they run out). Hz on the left and voice ids on the right, as synth~; [:gain v] is the velocity of the next notes.\n\n*Try:* Press ▶ and play a chord (⇧-click several keys): every key a voice. Touch lower on the keys to play louder. Its other controls (cutoff) are for every voice.\n\n```clojure\n(box :b3 \"faust~\" 300 30)\n(code :b3 \"import(\\\"stdfaust.lib\\\");\\ndeclare options \\\"[nvoices:8]\\\";\\nfreq = hslider(\\\"freq\\\", 440, 40, 4000, 0.01);\\ngain = hslider(\\\"gain\\\", 0.8, 0, 1, 0.01);\\ngate = button(\\\"gate\\\");\\ncutoff = hslider(\\\"cutoff\\\", 2400, 200, 8000, 1);\\nprocess = os.sawtooth(freq) * gain * en.adsr(0.01, 0.2, 0.6, 0.6, gate) * 0.12 : fi.lowpass(2, cutoff);\")\n(box :b4 \"keyboard\" 300 210)\n(connect :b4 0 :b3 0)\n(connect :b4 1 :b3 1)\n(connect :b4 3 :b3 0)\n(connect :b3 0 :b2 0)\n(connect :b3 0 :b2 1)\n```\n\n**A score in several voices** — mt play sends the Hz of the notes sounding and their voice ids: each note of a chord, a voice of the faust~.\n\n*Try:* Press ▶ and click msg :bang: the four chords in a loop; msg :stop ends it.\n\n```clojure\n(box :b5 \"tree\" 560 30)\n(code :b5 \"\\\"c4+e4+g4/2 d4+f4+a4/2 b3+d4+g4/2 c4+e4+g4+c5/2\\\"\")\n(box :b6 \"msg :bang\" 560 150)\n(box :b7 \"msg :stop\" 640 150)\n(box :b8 \"mt play loop\" 560 190)\n(connect :b5 0 :b8 0)\n(connect :b6 0 :b8 0)\n(connect :b7 0 :b8 0)\n(connect :b8 0 :b3 0)\n(connect :b8 1 :b3 1)\n```\n\n**Any tuning** — The notes reach the voices as MIDI pitches with decimals, so any frequency sounds as written: here a just major triad (4:5:6), then the equal-tempered one.\n\n*Try:* Press ▶ and click the first two messages in turn: the just third is 14 cents lower, and it does not beat.\n\n```clojure\n(box :b9 \"msg 220 275 330\" 560 260)\n(box :b10 \"msg 220 277.18 329.63\" 700 260)\n(box :b11 \"msg :stop\" 870 260)\n(connect :b9 0 :b3 0)\n(connect :b10 0 :b3 0)\n(connect :b11 0 :b3 0)\n```\n\n**An effect for all the voices** — effect = …; in the same source is applied once, to the sum of the voices (here an echo); its controls are parameters of the box too.\n\n*Try:* Press ▶ and play the keyboard again: every note echoes. Change ef.echo(1, 0.33, 0.45) and apply it (Ctrl+Enter).\n\n```clojure\n(code :b3 \"import(\\\"stdfaust.lib\\\");\\ndeclare options \\\"[nvoices:8]\\\";\\nfreq = hslider(\\\"freq\\\", 440, 40, 4000, 0.01);\\ngain = hslider(\\\"gain\\\", 0.8, 0, 1, 0.01);\\ngate = button(\\\"gate\\\");\\ncutoff = hslider(\\\"cutoff\\\", 2400, 200, 8000, 1);\\nprocess = os.sawtooth(freq) * gain * en.adsr(0.01, 0.2, 0.6, 0.6, gate) * 0.12 : fi.lowpass(2, cutoff);\\neffect = ef.echo(1, 0.33, 0.45);\")\n```\n\nSee also: `knob`, `component`, `script`\n\n### features~ · `@kairotic/analysis`\n\n`features~ [ms] [descriptor …]`\n\nDescriptors of a signal every ms, one outlet per word: rms, energy, zcr, loudness, centroid, spread, flatness, rolloff, kurtosis, skewness, slope, crest, sharpness, perceptualSpread, mfcc, chroma (Meyda).\n\n**Inlets** \n\n0. the signal\n\n**Outlets** \n\n0. one outlet per descriptor written, in order (rms centroid flatness without words); centroid, spread and rolloff in Hz\n\n**Try:** Press ▶ and allow the microphone: whisper and then hum — the centroid (brightness) falls.\n\n```clojure\n(box :b1 \"adc~ 1\" 40 30)\n(box :b2 \"features~ 50 rms centroid\" 40 90)\n(box :b3 \"number\" 40 150)\n(box :b4 \"number\" 200 150)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n(connect :b2 1 :b4 0)\n```\n\nSee also: `pitch~`, `chroma~`, `snapshot~`\n\n### fetch · `@kairotic/data`\n\n`fetch [json|text|edn] [live]`\n\nBrings in what is at a URL (JSON read as EDN, text or EDN) as a task: it goes out on the left and is kept as the data of the box, in the history, the same for everyone; with live, only in this tab.\n\n**Inlets** \n\n0. a URL (msg https://… · github:owner/repo@ref/path · [:fetch url]); refresh; bang; [:get key …]; clear\n\n**Outlets** \n\n0. what it found (or the part a [:get …] asks for)\n1. :loading, :ready or [:error \"…\"]\n\n**Messages and gestures**\n\n- `a URL`: brings it in; a URL it already keeps is sent again, not fetched\n- `:refresh`: fetches its URL again\n- `bang`: sends what it holds\n- `:get :items 0 :name · [:get [:items 0 :name]]`: sends one part of it\n- `:clear`: forgets it\n- `(keep! :bN {:url \"…\" :value …})`: what it keeps, as the code of the work writes it\n\n**Try:** Click the message: the answer arrives in the edn box, and stays in the work (go back and forward in the history: it is not fetched again). Pick a line: its value goes to print.\n\n```clojure\n(box :b1 \"msg github:bonuoq/kairotic@main/packages/data/package.json\" 40 30)\n(box :b2 \"fetch\" 40 80)\n(box :b3 \"edn 340 260\" 40 150)\n(box :b4 \"print\" 400 150)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n(connect :b3 0 :b4 0)\n```\n\nSee also: `edn`, `sample`, `print`\n\n### form~ · `@kairotic/analysis`\n\n`form~ [seconds] [step] [kernel]`\n\nHow alike the moments of what arrives are over the last seconds (20): a self-similarity matrix of one frame every step seconds (0.25), drawn; where a segment begins, and the period that repeats.\n\n**Inlets** \n\n0. lists of numbers (a chroma~, an mfcc), or numbers (onset~'s envelope, an rms); [:seconds x] [:step x] [:kernel x] change them; :clear forgets\n\n**Outlets** \n\n0. the novelty of each frame, 0…1 (how much the music changes there; kernel seconds (2) late)\n1. a bang where a segment begins\n2. the period that repeats most, in seconds, when it changes\n3. [:segment {:t :at :length :period}] for the segment that ends\n\n**Try:** Press ▶ and play a section, then another (other chords, another register): the squares along the diagonal are the sections, a line marks where the second begins, print writes the segment, and onset~ starts the new section afresh.\n\n```clojure\n(box :b1 \"adc~ 1\" 40 30)\n(box :b2 \"chroma~\" 40 90)\n(box :b3 \"onset~\" 240 90)\n(box :b4 \"form~\" 40 170)\n(box :b5 \"print\" 280 300)\n(connect :b1 0 :b2 0)\n(connect :b1 0 :b3 0)\n(connect :b2 0 :b4 0)\n(connect :b4 3 :b3 0)\n(connect :b4 3 :b5 0)\n```\n\nSee also: `chroma~`, `onset~`, `monitor`\n\n### fourier · `@kairotic/theory`\n\n`fourier [notes]`\n\nThe six Fourier coefficients of a pitch-class distribution (chromatic, dyadic, triadic, octatonic, diatonic, whole-tone), each a point in its circle with its trail.\n\n**Inlets** \n\n0. a list of pitches (Hz, as a keyboard or midiin sends them; MIDI or 0…11 with midi), a list of 12 weights (a chroma, from chroma~), or a number: a note (the last n count: 4); :clear\n\n**Outlets** \n\n0. the six magnitudes, 0…1\n1. the six phases, in degrees\n\n**Try:** The diatonic scale fills f5; the augmented triad, f3 and f6 at 1. With adc~ → chroma~ → fourier, sing or play and watch the trails.\n\n```clojure\n(box :b1 \"msg 60 62 64 65 67 69 71\" 40 30)\n(box :b2 \"msg 60 64 68\" 240 30)\n(box :b3 \"fourier midi\" 40 80)\n(connect :b1 0 :b3 0)\n(connect :b2 0 :b3 0)\n```\n\nSee also: `pcclock`, `tonnetz`, `chroma~`\n\n### freqt\n\nGraphic buffer of frequency over time: Hz on a log scale, time from 0, tunings (Scala) and bar grids, drawn as a canvas or as a score ((view :b1 :score), ⇄ in its header). A number on the inlet (or a click) comes out on the left; edits on the inlet ([:note t \"c4\" dur], [:stroke pts], [:erase :t1], [:clear], [:batch [...]]) change it, and questions ([:read t], [:strokes], [:end], [:data]) are answered on the left. The second outlet is the buffer for a reader. A musical tree on the inlet is shown over it, measured; shown as a score, the edits you make on that tree's notes leave by the third outlet ([:edit …]): connect it back to the tree box.\n\n**Inlets** \n\n0. a time (or a click): it comes out on the left · an edit ([:note t \"c4\" dur], [:stroke [[t hz] …]], [:erase :t1], [:clear], [:tuning \"19-tet\"], [:grid-x 0.25 [4]]… or [:batch [edits]]): it changes the buffer, as one event · a question ([:read t], [:strokes], [:get :t1], [:count], [:end], [:data]): the answer comes out on the left · a musical tree: shown over it\n\n**Outlets** \n\n0. the time, or the answer to a question\n1. the buffer, for a reader or reader~\n2. shown as a score: the edits made on the notes of the tree it shows ([:edit …]), for the tree box\n\n**Messages and gestures**\n\n- `(note :bN t \"c4\" dur)`: a note\n- `(tuning :bN \"31-tet\" 261.63)`: a tuning\n- `(grid-x :bN 0.25 \"3+3+2\")`: a bar grid\n- `the corner · (resize :bN 640 300)`: drag its bottom-right corner to resize it (as a score, its width reflows the notation); a double-click there brings back its size\n- `[:note 0 \"c4\" 1] · [:note 1 64 0.5]`: a note by message (pitch as a name or MIDI)\n- `[:move :t1 dt cents] · [:stretch :t1 k] · [:erase :t1] · [:clear]`: edit notes by message\n- `[:tuning \"19-tet\" 261.63] · [:grid-x 0.25 [4]]`: tuning and grid by message\n- `[:batch [[:clear] [:note 0 \"c4\" 1] …]]`: several edits, one event of the history\n- `[:read 2] · [:strokes] · [:get :t1] · [:count] · [:end] · [:data]`: questions: the answer comes out on the left\n- `⇄ score in the header · (view :bN :score)`: the same buffer, quantized and drawn as a score: measures in the meter of its bar grid, tuplets, ties (⇄ canvas brings it back)\n- `(quantize :bN {:meter \"6/8\"})`: the tree that score shows, to keep or edit (options: :meter :divs :merge :nest :voices :grace :legato)\n- `shown as a score, alt-click a note · (division! :bN t)`: its beat divided the next way (another division, in halves, with the next beat), kept in the buffer\n- `(to-tree! :bN)`: a tree box beside it, with its strokes as notes: the drawing, now a tree\n- `(quant :bN {:meter \"6/8\" :key \"eb\"}) · [:quantize {…}]`: how its score is quantized and in which key, kept in its buffer (one event); (quant :bN nil): the defaults. {:meters [\"3/4\" \"5/8[2+3]\"]}: a meter for each bar, the last going on\n- `(track! :bN) · (quant :bN {:time :track})`: what was played freely (transcribe, at any tempo, with rubato) written on its beats: the tempo and the beats are found, and track! keeps them (the time map) so that the score stays as it is; if the bar starts in the wrong place, (track! :bN {:downbeat t}) with the time of a note that starts a bar; (track! :bN nil) forgets them\n- `shown as a score, shift-alt-click a note · (enharmonic! :bN t midi)`: another name for that note (c#4 → db4), kept in the buffer\n- `shown as a score, click a note of a tree`: ↑ ↓ pitch (⇧ octave) · a…g the nearest note of that name · + − duration · ← → next · Delete → rest\n- `click a rest`: Enter → a note (the pitch of the one before) · ↑ ↓ a step above or below it · a…g that note\n- `(keep! :bN)`: writes the tree it shows into its buffer, with its recipe beside it (the tree and the boxes that made it)\n- `(recipe :bN) · (remake! :bN)`: the recipe of a kept buffer · the tree written back, without the changes made since\n- `{ } in the header (or a double-click on its right) · (source :bN)`: the buffer as EDN text, in the code window: edit it and apply (Ctrl+Enter); what changed is one event\n\n**Try:** Press ▶: the reader~ plays the four beats again and again. Draw a stroke of your own, straight or curved: it sounds at the frequency it passes through.\n\n```clojure\n(box :b1 \"freqt\" 40 60)\n(box :b2 \"phasor~ 0.25\" 40 15)\n(box :b3 \"reader~ norm 1 gate\" 40 290)\n(box :b4 \"osc~\" 40 340)\n(box :b5 \"gain~\" 40 390)\n(box :b6 \"dac~\" 40 440)\n(connect :b2 0 :b3 0)\n(connect :b1 1 :b3 1)\n(connect :b3 0 :b4 0)\n(connect :b3 1 :b5 1)\n(connect :b4 0 :b5 0)\n(connect :b5 0 :b6 0)\n(connect :b5 0 :b6 1)\n(melody :b1 \"c4/1 e4/.5 d4/.5 g4/2\" 0)\n```\n\n**A tuning and a grid** — A freqt can have a tuning (the lines of its Y axis: any equal division, just intonation, a Scala .scl) and a grid of time with its bars. Drawing snaps to both.\n\n*Try:* Draw a few notes: they fall on the 19 degrees of the octave and on the half beats. Try (tuning :b1 \"just-5\") or (tuning :b1 nil) to draw freely again.\n\n```clojure\n(tuning :b1 \"19-tet\")\n(grid-x :b1 0.5 [4])\n```\n\n**As a score** — The same buffer can be shown as a score, quantized into measures (in the meter of its bar grid, with tuplets and ties): ⇄ score in its header, or (view :b1 :score). Nothing changes in the data; ⇄ canvas brings the drawing back, and (quantize :b1) gives the tree the score shows.\n\n*Try:* Press ▶: the score sounds the same as the drawing did. To edit notes one by one in a score, show a tree: see the help of tree.\n\n```clojure\n(tuning :b1 nil)\n(view :b1 :score)\n```\n\n**The viewer of a tree** — A freqt shown as a score is the viewer of a tree that comes transformed (tree → mt transpose 7 → freqt). Its third outlet sends the edits made on the notes back to the tree box. (A box written \"score\", from older works, is a freqt shown as a score.)\n\n*Try:* Click a note of the new score and press ↑ or ↓, + or −, Delete (a rest) and then Enter (a note again): the change goes back to the tree by the dashed line.\n\n```clojure\n(box :b7 \"bang\" 500 15)\n(box :b8 \"tree\" 500 60)\n(code :b8 \"\\\"c5/1 b4/.5 a4 g4/2\\\"\")\n(box :b9 \"freqt\" 500 160)\n(view :b9 :score)\n(connect :b7 0 :b8 0)\n(connect :b8 0 :b9 0)\n(connect :b9 2 :b8 0)\n```\n\nSee also: `canvas`, `reader`, `tree`, `quantize`, `transcribe`\n\n### ftom\n\nHz → MIDI pitch (lists too).\n\n**Inlets** \n\n0. a frequency in Hz or a list of them\n\n**Outlets** \n\n0. the MIDI pitch, with decimals for what falls between keys\n\nSee also: `mtof`\n\n### gain~\n\n`gain~ [factor]`\n\nGain: signal on the left, factor on the right — a number, or a signal (an envelope, a reader~) that then is the factor.\n\n**Inlets** \n\n0. the signal\n1. the factor: a number, or a signal (an envelope) that then is the factor\n\n**Outlets** \n\n0. the signal times the factor\n\nSee also: `osc~`, `adsr~`, `dac~`\n\n### gendy~ · `@kairotic/synth`\n\n`gendy~ [freq x-step y-min y-max y-step breakpoints]`\n\nA dynamic stochastic oscillator, after Xenakis's GENDY: a wave of breakpoints whose amplitudes and durations each take a random walk between mirror barriers, cycle after cycle — a pitch that drifts, a timbre that changes.\n\n**Inlets** \n\n0. a number: the frequency in Hz · [:x-step 30], [:y-step 0.2]…: one parameter · a list of six: all of them · a signal: added to the frequency, in Hz (FM)\n\n**Outlets** \n\n0. the sound (about ±0.15 by default: y-min and y-max are its barriers)\n\n**Messages and gestures**\n\n- `220`: the frequency\n- `[:x-step 40]`: how far the durations wander (0–100 %): the pitch drifts\n- `[:y-step 0.2]`: how far the amplitudes move each cycle: the timbre changes faster\n- `[:breakpoints 6]`: fewer breakpoints, a simpler wave (more of them, a richer one); changing it keeps the wave\n- `[220 10 -0.15 0.15 0.05 16]`: freq x-step y-min y-max y-step breakpoints\n\n**Try:** Press ▶: a buzz whose pitch and colour never settle. Write gendy~ 110 0 in the box: with no wander of the durations, the pitch holds and only the timbre moves.\n\n```clojure\n(box :b1 \"gendy~ 110\" 40 30)\n(box :b2 \"dac~\" 40 90)\n(box :b3 \"scope~ 30\" 160 90)\n(connect :b1 0 :b2 0)\n(connect :b1 0 :b2 1)\n(connect :b1 0 :b3 0)\n```\n\n**The two walks** — x-step lets the durations wander (the pitch), y-step the amplitudes (the timbre). Two knobs send them by name.\n\n*Try:* Press ▶ and turn x-step up: the pitch scatters into noise. Turn it down and y-step up: one pitch, a restless colour.\n\n```clojure\n(box :b4 \"knob 0 100 10 x-step\" 360 20)\n(box :b5 \"knob 0 0.3 0.05 y-step\" 450 20)\n(connect :b4 0 :b1 0)\n(connect :b5 0 :b1 0)\n```\n\n**Breakpoints** — Few breakpoints make a simple wave, close to a triangle or a square; many, a richer and noisier one. Changing their number keeps the wave, with no click.\n\n*Try:* Press ▶ and click both messages in turn, watching the scope.\n\n```clojure\n(box :b6 \"msg :breakpoints 4\" 360 120)\n(box :b7 \"msg :breakpoints 48\" 500 120)\n(connect :b6 0 :b1 0)\n(connect :b7 0 :b1 0)\n```\n\n**A signal on the inlet: FM** — A signal connected to the inlet is added to the frequency, in Hz: a slow one makes a vibrato, a fast one frequency modulation.\n\n*Try:* Press ▶: 5 Hz around 110 Hz. Change osc~ 5 to osc~ 80 for a rougher sound.\n\n```clojure\n(box :b8 \"osc~ 5\" 360 200)\n(box :b9 \"gain~ 300\" 360 250)\n(connect :b8 0 :b9 0)\n(connect :b9 0 :b1 0)\n```\n\nSee also: `osc~`, `synth~`, `faust~`\n\n### html\n\n`html`\n\nA small interface written as hiccup (HTML as EDN data): sliders, fields, menus, buttons and text, laid out like a page. An element with :out sends what it gives out of that outlet; one with :name keeps it as a value, shown by every hole :$name in the view, and when it is let go (a slider) or chosen (a menu, a text entered) the box keeps it in the work, as a knob keeps its value: (values! :bN {:freq 440}). A list of maps in a hole is shown as a table (a row each, a column for each key: the futuribles of comes or cancrizans), and anything else on the inlet that is not a map, a value or a bang (a number, a list) is the value :in, shown by :$in. A map on the inlet ({:freq 220}) sets values, as a number sets a knob: the elements named so show it (a slider within its range) and those with :out send it on; a bang sends again what they hold. What is not allowed (scripts, links, images, positions, unknown tags or attributes) is dropped, so it is safe in a shared room. Its view opens as text from { } (HTML can be pasted there too).\n\n**Inlets** \n\n0. a map of values {:freq 220}, or one [:freq 220]: the elements named so and the holes :$freq show them, and the named elements with :out send them on (a slider within its range); a bang sends again what they hold\n\n**Outlets** \n\n0. what each element with :out 0 gives\n1. … :out 1, and so on: as many outlets as the view asks for\n\n**Messages and gestures**\n\n- `{:freq 220}`: sets values: the elements named so show them and send them on\n- `[:freq 220]`: sets one value\n- `bang`: sends again what every named element with :out holds\n- `[{:name \"D4\" :futures 12} …]`: anything else is the value :in (:$in); a list of maps is shown as a table\n\n**Try:** Move the slider: its value goes out of the left outlet and shows beside it; let it go and the box keeps it, as a knob does (back in the history, it moves back). { } in the header opens the view as text: change it and apply.\n\n```clojure\n(box :b1 \"html\" 40 30)\n(box :b2 \"print\" 40 230)\n(box :b3 \"print\" 200 230)\n(connect :b1 0 :b2 0)\n(connect :b1 1 :b3 0)\n```\n\nSee also: `number`, `knob`, `msg`\n\n### inlet\n\nAn inlet of the sub-patch it is in (inlets are numbered left to right). Passes on the messages that arrive at it.\n\n**Outlets** \n\n0. what arrives at this inlet of the sub-patch\n\nSee also: `patch`, `outlet`, `inlet~`\n\n### inlet~\n\nAn audio inlet of the sub-patch it is in (numbered left to right, together with the message inlets).\n\n**Outlets** \n\n0. the signal that arrives at this inlet of the sub-patch\n\nSee also: `patch`, `outlet~`\n\n### loadbang\n\nSends a bang when the engine starts (▶).\n\n**Outlets** \n\n0. a bang when the engine starts (▶)\n\n**Try:** Press ▶: the bang arrives at print, which writes it in the REPL.\n\n```clojure\n(box :b1 \"loadbang\" 40 30)\n(box :b2 \"print\" 40 90)\n(connect :b1 0 :b2 0)\n```\n\nSee also: `bang`, `metro`\n\n### metro\n\n`metro ms`\n\nSends periodic bangs: 1 or bang starts it, 0 or :stop stops it.\n\n**Inlets** \n\n0. bang, 1 or :start: starts · 0 or :stop: stops\n1. the interval in ms\n\n**Outlets** \n\n0. a bang every interval\n\n**Try:** Start the engine, then 1 and 0: a pulse that counts from 0 to 7.\n\n```clojure\n(box :b1 \"msg 1\" 40 30)\n(box :b2 \"msg 0\" 100 30)\n(box :b3 \"metro 250\" 40 90)\n(box :b4 \"counter 1 8\" 40 150)\n(box :b5 \"print\" 40 210)\n(connect :b1 0 :b3 0)\n(connect :b2 0 :b3 0)\n(connect :b3 0 :b4 0)\n(connect :b4 0 :b5 0)\n```\n\nSee also: `counter`, `ramp`, `loadbang`\n\n### monitor · `@kairotic/analysis`\n\n`monitor [seconds] [name …]`\n\nDraws the messages that arrive over the last seconds, one lane per inlet: a number as a line, a list as a strip of cells, a bang or a word as a mark.\n\n**Inlets** \n\n0. anything, drawn in the first lane; with names (monitor 6 rms centroid chroma) one inlet per name, left to right\n\n**Try:** Press ▶ and allow the microphone: speak, then sing a long note — the centroid falls, the chroma strip settles on one row, each syllable leaves a mark.\n\n```clojure\n(box :b1 \"adc~ 1\" 40 30)\n(box :b2 \"features~ 20 rms centroid\" 40 90)\n(box :b3 \"chroma~\" 260 90)\n(box :b4 \"onset~\" 460 90)\n(box :b5 \"monitor 6 rms centroid chroma onset\" 40 180)\n(connect :b1 0 :b2 0)\n(connect :b1 0 :b3 0)\n(connect :b1 0 :b4 0)\n(connect :b2 0 :b5 0)\n(connect :b2 1 :b5 1)\n(connect :b3 0 :b5 2)\n(connect :b4 0 :b5 3)\n```\n\nSee also: `features~`, `chroma~`, `onset~`, `print`\n\n### msg\n\n`msg :stop · msg 0 8 4 · msg inc`\n\nMessage: when pressed it sends its content, read as in Clojure: numbers, keywords with their colon (:stop, :rec 4), names (any other word: inc, e4, 6/5, https://…), true false nil, text between quotes (\"two words\") as a string and EDN forms ([0 4 7], {:freq 440}); several make a list. A word without its colon is a name, not a keyword: msg stop does not stop a metro, msg :stop does.\n\n**Inlets** \n\n0. anything (or a click): sends its content\n\n**Outlets** \n\n0. its content, read as in Clojure: a number, a keyword with its colon (:stop), a name (inc, e4, https://…), true false nil, a string between quotes (\"two words\"), an EDN form ([0 4 7], {:freq 440}), or a list of them; empty, a bang\n\n**Messages and gestures**\n\n- `msg :stop`: a keyword: what boxes understand as an order (:stop, :rec 4, :clear)\n- `msg inc`: a name: a function where a box takes one (map inc), or free text (e4, 6/5, a URL)\n- `msg [0 4 7] {:freq 440}`: EDN forms, read whole\n\n**Try:** Start the engine and click the two messages: two MIDI pitches become two frequencies.\n\n```clojure\n(box :b1 \"msg 60\" 40 30)\n(box :b2 \"msg 67\" 110 30)\n(box :b3 \"mtof\" 40 90)\n(box :b4 \"osc~ 261.63\" 40 140)\n(box :b5 \"gain~ 0.3\" 40 190)\n(box :b6 \"dac~\" 40 240)\n(connect :b1 0 :b3 0)\n(connect :b2 0 :b3 0)\n(connect :b3 0 :b4 0)\n(connect :b4 0 :b5 0)\n(connect :b5 0 :b6 0)\n(connect :b5 0 :b6 1)\n```\n\nSee also: `number`, `bang`\n\nReference: [EDN](https://github.com/edn-format/edn) · [Keywords and symbols](https://clojure.org/reference/data_structures#Keywords)\n\n### mt\n\n`mt <operation> [arguments]`\n\nOperations on musical trees: a tree on the left comes out transformed. transpose n (semitones, or an interval: M3, -P5, A4) · invert [pivot] · retrograde · augment f · rotate k · canon delay [interval], or with the words of a reader on a ring: canon d 2 k P5 speed 0.5 inversion (the comes d beats later, k away, at a speed — 0.5 twice as slow, −1 backwards —, upside down) · thin amount (keeps the notes on the strongest positions of each measure: a share, 0.5, or how many, 3) · seq / par (joins the left tree with the one on the right) · events · pitches · duration · play [loop] [speed s] (a bang plays the last tree: Hz and voice ids for synth~, parameters and marks; at a speed, 0.5 twice as slow, −1 the tree backwards — msg :speed −1 —: the reader of a tree on its own clock, as a reader on a ring follows its head).\n\n**Inlets** 1: a tree: it comes out transformed (for play: a tree to play, then bang, :stop) · for transpose, invert, augment, rotate, canon, thin: the amount · for seq, par: the tree to join\n\n**Outlets** \n\n0. the result (for play: the Hz of the notes sounding, a list)\n\n**Messages and gestures**\n\n- `mt transpose 7`: seven semitones up\n- `mt invert c4`: mirrored around c4\n- `mt retrograde`: backwards\n- `mt augment 2`: twice as long\n- `mt rotate 1`: the first element goes to the end\n- `mt canon 2 7`: against itself, 2 beats later, a fifth up\n- `mt canon d 2 k P5 speed 0.5`: the same with the words of a reader on a ring: d beats later, k away (semitones or an interval), the comes at a speed — 0.5 twice as slow (an augmentation canon), −1 backwards (a crab) —, and inversion upside down\n- `mt thin 0.5`: keeps half the notes of each measure, the ones on its strongest positions (metric weight)\n- `mt seq · mt par`: the left tree followed by (or with) the right one\n- `mt events · mt pitches · mt duration`: the tree as data\n- `mt play [loop]`: plays it: Hz (0) and voice ids (1) for synth~, parameters (2), dynamics and texts (3)\n- `mt play speed 0.5 · msg :speed -1`: at a speed: twice as slow, or the tree backwards — the reader of a tree on its own clock (a reader moved by positions reads the tree box instead: what sounds where it is)\n\n**Try:** Change the box text to mt retrograde, mt invert c4 or mt augment 2: the score follows. (The number on the right inlet takes effect with the next tree: click the bang.)\n\n```clojure\n(box :b1 \"bang\" 40 20)\n(box :b2 \"tree\" 40 60)\n(code :b2 \"\\\"c4/1 d4/.5 e4 g4/1 e4 f4/.5 e4 d4/2\\\"\")\n(box :b4 \"number 7\" 220 170)\n(box :b3 \"mt transpose 7\" 40 170)\n(box :b5 \"tree\" 40 220)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n(connect :b4 0 :b3 1)\n(connect :b3 0 :b5 0)\n```\n\n**Two voices: a canon** — mt canon d i puts the tree against itself, d beats later and i semitones away: two voices that the score shows as two staves.\n\n*Try:* Click the bang. Change it to mt canon 1 -12 (an octave below, one beat later) or mt canon 4 0.\n\n```clojure\n(text! :b3 \"mt canon 2 7\")\n(delete :b4)\n```\n\n**Playing it** — mt play reads a tree in time: the Hz of the notes that sound (left) and their voice ids (second) go to a synth~, which gives each voice its own note.\n\n*Try:* Press ▶, click the first bang (the tree goes to mt play) and then msg :bang: the canon sounds in a loop; :stop ends it.\n\n```clojure\n(box :b6 \"msg :bang\" 500 170)\n(box :b7 \"msg :stop\" 570 170)\n(box :b8 \"mt play loop\" 500 220)\n(box :b9 \"synth~\" 500 270)\n(box :b10 \"gain~ 0.3\" 500 320)\n(box :b11 \"dac~\" 500 370)\n(connect :b3 0 :b8 0)\n(connect :b6 0 :b8 0)\n(connect :b7 0 :b8 0)\n(connect :b8 0 :b9 0)\n(connect :b8 1 :b9 1)\n(connect :b9 0 :b10 0)\n(connect :b10 0 :b11 0)\n(connect :b10 0 :b11 1)\n```\n\nSee also: `tree`, `freqt`, `synth~`\n\n### mtof\n\nMIDI pitch → Hz (lists too).\n\n**Inlets** \n\n0. a MIDI pitch (60 = middle C) or a list of them\n\n**Outlets** \n\n0. the frequency in Hz (or the list)\n\n**Try:** Drag the number: 69 is A4, 440 Hz; every 12 steps the frequency doubles.\n\n```clojure\n(box :b1 \"number 69\" 40 30)\n(box :b2 \"mtof\" 40 90)\n(box :b3 \"print\" 40 150)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n```\n\nSee also: `ftom`, `osc~`\n\n### number\n\n`number [initial]`\n\nA draggable number; sends it when it changes or on receiving a bang. Let go (or typed), its value stays in its text, as a knob's does: it travels with the work, and going back in the history brings back the number it had.\n\n**Inlets** \n\n0. a number sets it and sends it on; a bang sends it again\n\n**Outlets** \n\n0. the number\n\n**Messages and gestures**\n\n- `drag`: up and down changes it (and sends it); let go, the number stays in its text, as a knob's does\n- `double-click`: type a number (Enter sends it, Esc closes); so too knobs and the sliders of faust~\n\n**Try:** Start the engine and drag the number: the oscillator follows. Let it go: its text keeps the new number (back in the history, it goes back).\n\n```clojure\n(box :b1 \"number 440\" 40 30)\n(box :b2 \"osc~ 440\" 40 90)\n(box :b3 \"gain~ 0.3\" 40 140)\n(box :b4 \"dac~\" 40 190)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n(connect :b3 0 :b4 0)\n(connect :b3 0 :b4 1)\n```\n\nSee also: `msg`, `knob`\n\n### onset~ · `@kairotic/analysis`\n\n`onset~ [threshold] [ms]`\n\nA bang at the beginning of each sound (a note, a stroke, a syllable), and its strength.\n\n**Inlets** \n\n0. the signal; [:threshold x] and [:ms y] change them while it listens; a [:segment …] from form~ forgets the usual change of the section before\n\n**Outlets** \n\n0. a bang for each onset\n1. its strength (the growth of the spectrum, 0…1)\n2. the growth of every frame (the onset strength envelope)\n\n**Try:** Press ▶ and clap: the counter counts the claps. Raise the threshold if it counts too much.\n\n```clojure\n(box :b1 \"adc~ 1\" 40 30)\n(box :b2 \"onset~\" 40 90)\n(box :b3 \"counter 1\" 40 150)\n(box :b4 \"number\" 40 200)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n(connect :b3 0 :b4 0)\n```\n\nSee also: `pitch~`, `sample`, `counter`, `form~`\n\n### osc~\n\n`osc~ [hz]`\n\nSine oscillator. A number on the left changes its frequency; a signal on the left (from reader~, sig~…) is its frequency in Hz.\n\n**Inlets** \n\n0. a number: the frequency in Hz · a signal: the frequency itself\n1. —\n\n**Outlets** \n\n0. a sine signal (quiet: 0.15)\n\n**Try:** Start the engine and drag the number. Then put a phasor~ through a * into the left inlet: a signal instead of numbers.\n\n```clojure\n(box :b1 \"number 440\" 40 30)\n(box :b2 \"osc~ 440\" 40 90)\n(box :b3 \"gain~ 0.3\" 40 140)\n(box :b4 \"dac~\" 40 190)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n(connect :b3 0 :b4 0)\n(connect :b3 0 :b4 1)\n```\n\nSee also: `gain~`, `dac~`, `phasor~`, `mtof`\n\n### outlet\n\nAn outlet of the sub-patch it is in (numbered left to right). Sends out of the sub-patch what arrives at it.\n\n**Inlets** \n\n0. what leaves the sub-patch by this outlet\n\nSee also: `patch`, `inlet`, `outlet~`\n\n### outlet~\n\nAn audio outlet of the sub-patch it is in (numbered left to right, together with the message outlets).\n\n**Inlets** \n\n0. the signal that leaves the sub-patch by this outlet\n\nSee also: `patch`, `inlet~`\n\n### pan~ · `@kairotic/spatial`\n\n`pan~ [position]`\n\nStereo panning with equal power.\n\n**Inlets** \n\n0. the signal\n1. the position: −1 left … 1 right\n\n**Outlets** \n\n0. left\n1. right\n\nSee also: `space~`, `dac~`\n\n### patch\n\n`patch [label] · patch @line`\n\nAn embedded sub-patch: double-click to open it. Its inlet / outlet boxes (numbered left to right) are its ports. patch @name uses the line called name instead (its newest point, or the point it is pinned to): double-click opens its tab.\n\n**Messages and gestures**\n\n- `double-click`: opens it (patch @name: opens its line, in its tab)\n- `patch @name`: uses the line called name (spaces as -): its newest point, so it changes as the line advances; inside it, adc~ and dac~ are quiet (they play when the line plays alone): sound goes in and out through inlet~ / outlet~\n- `(pin-ref :bN)`: pins a patch @name to the point of its line it reads now · (follow-ref :bN) follows the line again\n- `(abstract :bN \"name\")`: turns it into a class (an abstraction)\n\nSee also: `inlet`, `outlet`\n\n### pattern · `@kairotic/patterns`\n\n`pattern [seed] [repeat] [loop]`\n\nA pattern as Clojure code: an expression that returns event maps (or one map, read as a pbind), with seeded randomness and pbind, pseq, pwhite, pchoose, pshuffle, pseries, pwalk at hand. In a shared room it runs only after (trust-scripts true).\n\n**Inlets** \n\n0. bang: sends its pattern again\n\n**Outlets** \n\n0. its pattern (a factory of streams), for a player\n\n**Messages and gestures**\n\n- `(pbind {:degree (pwhite 0 7) :dur 0.25} :inf)`: a pbind whose values are lazy sequences\n- `(concat (pbind m1) (pbind m2))`: phrases one after another\n- `(for [d (range 8)] {:degree d :dur (if (even? d) 0.5 0.25)})`: any Clojure that gives event maps\n- `rand · rand-int · rand-nth · shuffle`: seeded by the box: the same for everyone\n\n**Try:** Press ▶ and start. Edit the code (double-click the box) and apply: the player follows the new pattern from the beat it is on.\n\n```clojure\n(box :b1 \"pattern 3\" 40 30)\n(code :b1 \"(pbind {:degree (pwhite 0 7)\\n :dur (pchoose [0.25 0.25 0.5])\\n :octave [5 5 6]}\\n :inf)\")\n(box :b2 \"msg :start\" 40 130)\n(box :b3 \"msg :stop\" 110 130)\n(box :b4 \"player 120\" 40 180)\n(box :b5 \"synth~\" 40 240)\n(box :b6 \"dac~\" 40 290)\n(connect :b2 0 :b4 0)\n(connect :b3 0 :b4 0)\n(connect :b1 0 :b4 1)\n(connect :b4 0 :b5 0)\n(connect :b4 1 :b5 1)\n(connect :b5 0 :b6 0)\n(connect :b5 0 :b6 1)\n```\n\nSee also: `pbind`, `player`, `script`\n\n### pbind · `@kairotic/patterns`\n\n`pbind [seed] [repeat] [loop]`\n\nA pattern as EDN data: a map of constants, sequences and #pat/… generators, with its randomness seeded. It sends its pattern whenever it changes, for a player.\n\n**Inlets** \n\n0. bang: sends its pattern again · a map: replaces it (one event of the history) · [:set :dur [1 0.5]]: one key · [:unset :amp]\n\n**Outlets** \n\n0. its pattern (a factory of streams), for a player\n\n**Messages and gestures**\n\n- `{:degree [0 2 4] :dur 0.5}`: a key with a vector is a sequence; the shorter ones start again until the longest ends\n- `#pat/choose [0.25 0.5] · #pat/white [0 7] · #pat/walk [0 2 -7 7]`: endless random values (the same for everyone: the seed)\n- `#pat/shuffle [0 2 4] · #pat/series [0 2 8]`: every pass in a new order · an arithmetic series\n- `#pat/hold [4 [:c :g :d]]`: one value every 4 beats (following time, not events)\n- `#pat/chord [0 4 7]`: a vector as one value: a chord\n- `{:degree [0 2 :rest 4]} · [0 nil 4]`: a silence: :rest (:_ :- :r) or nil as the degree, note or freq\n- `:amp #pat/white [0.2 0.6]`: the loudness of each note (0…1), for synth~ and a polyphonic faust~\n- `pbind 7 · pbind 7 4 · pbind 7 loop`: the seed · four passes · for ever\n\n**Try:** Press ▶ and start: four notes in a new order every pass. Change :dur in the pbind (double-click it) and apply: the player goes on with it from the same beat. Change the seed (pbind 8 loop): other orders, but the same for everyone in a room.\n\n```clojure\n(box :b1 \"pbind 7 loop\" 40 30)\n(code :b1 \"{:degree #pat/shuffle [0 2 4 7]\\n :dur [0.5 0.5 1]\\n :amp #pat/white [0.1 0.3]}\")\n(box :b2 \"msg :start\" 40 130)\n(box :b3 \"msg :stop\" 110 130)\n(box :b4 \"player 110\" 40 180)\n(box :b5 \"synth~\" 40 240)\n(box :b6 \"dac~\" 40 290)\n(connect :b2 0 :b4 0)\n(connect :b3 0 :b4 0)\n(connect :b1 0 :b4 1)\n(connect :b4 0 :b5 0)\n(connect :b4 1 :b5 1)\n(connect :b5 0 :b6 0)\n(connect :b5 0 :b6 1)\n```\n\n**One value per bar** — #pat/hold follows time: the root changes every 4 beats whatever the rhythm, as Overtone's ^{:dur 4} does.\n\n*Try:* Press start: the same figure, moving through four harmonies.\n\n```clojure\n(code :b1 \"{:degree #pat/shuffle [0 2 4 7]\\n :dur [0.5 0.5 1]\\n :root #pat/hold [4 [:c :f :g :c]]}\")\n```\n\n**Random, but the same** — Every key has a seed of its own (the box's seed and its name): changing one key leaves the randomness of the others as it was.\n\n*Try:* Start, stop and start again: the same walk. Change :scale to :lydian: the same rhythm and contour, other notes.\n\n```clojure\n(code :b1 \"{:degree #pat/walk [0 1 -4 9]\\n :dur #pat/choose [0.25 0.25 0.5]\\n :scale :dorian}\")\n```\n\nSee also: `pattern`, `player`, `tree`\n\n### pcclock · `@kairotic/theory`\n\n`pcclock [notes]`\n\nA pitch-class set on the clock face: its polygon, the sets before it, its axes of symmetry; its prime form and interval vector go out.\n\n**Inlets** \n\n0. a list of pitches (Hz, as a keyboard or midiin sends them; MIDI or 0…11 with midi), a list of 12 weights (a chroma), or a number: a note, the last n notes (4) being the set; :clear\n\n**Outlets** \n\n0. the prime form, when the set changes\n1. the interval vector\n2. the pitch class pressed\n\n**Try:** Click the major triad, then the diminished seventh: (0 3 7) has no axis, (0 3 6 9) has four. (The messages are MIDI notes, hence midi; a keyboard sends Hz, as pitches go between boxes, so a pcclock written without midi takes it directly.) Press a pitch class on the clock: it comes out on the right.\n\n```clojure\n(box :b1 \"msg 60 64 67\" 40 30)\n(box :b2 \"msg 60 63 66 69\" 140 30)\n(box :b3 \"pcclock midi\" 40 80)\n(box :b4 \"print\" 40 330)\n(connect :b1 0 :b3 0)\n(connect :b2 0 :b3 0)\n(connect :b3 0 :b4 0)\n```\n\nSee also: `fourier`, `tonnetz`, `chroma~`\n\n### phasor~\n\n`phasor~ [hz]`\n\nA ramp signal from 0 to 1, repeated hz times per second (0.25 = once every 4 seconds). A number on the left changes hz.\n\n**Inlets** \n\n0. a number: the frequency in Hz (0.25 = once every 4 seconds)\n\n**Outlets** \n\n0. a ramp signal from 0 to 1\n\nSee also: `reader~`, `sig~`\n\n### pitch~ · `@kairotic/analysis`\n\n`pitch~ [lo hi] [threshold]`\n\nThe pitch of a signal by YIN: Hz on the left (0 once when it stops hearing one), how clearly periodic on the right.\n\n**Inlets** \n\n0. the signal\n\n**Outlets** \n\n0. the frequency in Hz, only when it changes; 0 once when it no longer finds one\n1. the clarity, 0…1\n\n**Try:** Press ▶ and sing: the box shows the note and its cents, the number the MIDI pitch.\n\n```clojure\n(box :b1 \"adc~ 1\" 40 30)\n(box :b2 \"pitch~ 80 1000\" 40 90)\n(box :b3 \"ftom\" 40 150)\n(box :b4 \"number\" 40 200)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n(connect :b3 0 :b4 0)\n```\n\nSee also: `onset~`, `ftom`, `freqt`\n\n### player · `@kairotic/patterns`\n\n`player [bpm] [quant] [jump] [limit] [edges] [spread]`\n\nPlays a pattern by its own clock (start/stop), one step at a time (bang) or at a position in beats (a number): the Hz and voice ids of the notes sounding, the whole event and the beat.\n\n**Inlets** \n\n0. :start · :stop: its own clock · bang: one step, now · a number: a position in beats · :seek p · :reset · [:bpm 90]\n1. a pattern (from a pbind or a pattern box): a new one goes on from the same beat\n\n**Outlets** \n\n0. the Hz of the notes sounding (a list), after [:gain amp] when the event has :amp\n1. their voice ids, sent first (for synth~ or a polyphonic faust~)\n2. the whole event, with :beat, :hz and :ids (and :dir :back when entered from its end)\n3. the beat\n\n**Messages and gestures**\n\n- `:start · :stop`: its own clock: every event lasts its :dur in beats at its bpm\n- `player 120 4`: start on a multiple of 4 beats: players with the same tempo meet\n- `[:bpm 90]`: another tempo, without a jump\n- `bang`: the next event now (and the ones of :dur 0 right after it)\n- `a number`: a position in beats: every event is a span, from its onset to its end, that sounds while the position is inside it — entered at its onset going forwards, at its end going backwards (:dir :back); what a step passes over sounds within it\n- `:seek 8 · [:seek 8]`: there at once, nothing in between: what still sounds there goes on, what starts to contain that position starts\n- `player 120 0 8 8`: a step more than 8 (jump) times the one before it, or longer than 8 (limit) beats, is a seek: the wrap of a ramp\n- `player 120 0 8 8 edges`: a seek sounds only what starts exactly there\n- `player 120 0 8 8 spread`: what a step passes keeps its rhythm, one step later (with ▶)\n- `:reset`: back to the beginning, silently\n\n**Try:** Press ▶ and start: the six notes, three durations cycling. The third outlet is the whole event: print writes the beat of each.\n\n```clojure\n(box :b1 \"pbind 1 loop\" 40 30)\n(code :b1 \"{:note [:c4 :e4 :g4 :b4 :a4 :f4]\\n :dur [0.5 0.5 1]}\")\n(box :b2 \"msg :start\" 40 130)\n(box :b3 \"msg :stop\" 110 130)\n(box :b4 \"player 100\" 40 180)\n(box :b5 \"synth~\" 40 240)\n(box :b6 \"dac~\" 40 290)\n(box :b7 \"get % :beat\" 260 240)\n(box :b8 \"print\" 260 290)\n(connect :b2 0 :b4 0)\n(connect :b3 0 :b4 0)\n(connect :b1 0 :b4 1)\n(connect :b4 0 :b5 0)\n(connect :b4 1 :b5 1)\n(connect :b5 0 :b6 0)\n(connect :b5 0 :b6 1)\n(connect :b4 2 :b7 0)\n(connect :b7 0 :b8 0)\n```\n\n**Step by step** — A bang plays the next event now: the pattern follows whatever moves it — a metro, an onset~ of what someone plays, a key.\n\n*Try:* Stop the clock and click 1: one note every 300 ms, whatever its :dur. Connect an onset~ from an adc~ instead: one note each time you play.\n\n```clojure\n(box :b9 \"metro 300\" 180 130)\n(box :b10 \"msg 1\" 180 100)\n(box :b11 \"msg 0\" 230 100)\n(connect :b10 0 :b9 0)\n(connect :b11 0 :b9 0)\n(connect :b9 0 :b4 0)\n```\n\n**At a position** — A number is a position in beats, as a reader reads a buffer: every event is a span that sounds while the position is inside it. Forwards it starts at its onset; backwards at its end. The wrap of a ramp (a step far larger than the ones before) is a seek: there at once.\n\n*Try:* Stop the clock and click bang: six beats in three seconds, again and again. Change the ramp to ramp 6 0 3 loop: the phrase backwards, each note from its end. Drag a number box into it instead: you are the clock, either way.\n\n```clojure\n(box :b12 \"ramp 0 6 3 loop\" 330 130)\n(box :b13 \"msg :bang\" 330 100)\n(connect :b13 0 :b12 0)\n(connect :b12 0 :b4 0)\n```\n\nSee also: `pbind`, `pattern`, `metro`, `ramp`, `reader`, `synth~`\n\n### presets\n\n`presets [label or number …]`\n\nPresets from the keyframes of the history (◆ snapshots, takes kept): a number or a label recalls one, a position on the right morphs between two, a bang makes a new one from what changes and what remains.\n\n**Inlets** \n\n0. a keyframe to recall: its number (1 = the first) or its label · bang: a new preset · [:generate seed] · [:morph a b t] · keep\n1. a position between keyframes: 1.5 morphs halfway from the first to the second\n\n**Outlets** \n\n0. the values of the controls it set: {:b3 0.5 :b5 880}\n\n**Messages and gestures**\n\n- `2 · intro`: recalls that keyframe: every box takes its text of then, as one event of the history\n- `1.5 (right)`: moves the controls (knobs, envelopes…) between two keyframes, as messages, as a drag does\n- `:keep`: writes the last morph into the texts of the controls, as one event\n- `bang · [:generate 42]`: a new preset: what is the same in every keyframe stays, what changes takes a value within its range\n- `(keyframes) · (recall 2) · (morph 1 2 0.5) · (morph :keep) · (generate 42)`: the same from the REPL, with every keyframe of the work\n- `(store-presets! :bN) · (presets! :bN […])`: keeps its keyframes in the box (only what changes): then it uses them, and they travel with the patch in its code, links and embeds\n\n**Try:** Press ◆ Snapshot, turn the lower knob and press ◆ again: two keyframes. Start the engine: 1 and 2 recall them, the knob on the right morphs between them, and the bang makes a new preset in between.\n\n```clojure\n(box :b1 \"msg 1\" 40 30)\n(box :b2 \"msg 2\" 100 30)\n(box :b3 \"bang\" 160 30)\n(box :b4 \"knob 1 2 1\" 230 20)\n(box :b5 \"presets\" 40 120)\n(box :b6 \"knob 100 1000 220 log\" 40 180)\n(box :b7 \"osc~ 220\" 40 280)\n(box :b8 \"gain~ 0.2\" 40 330)\n(box :b9 \"dac~\" 40 380)\n(connect :b1 0 :b5 0)\n(connect :b2 0 :b5 0)\n(connect :b3 0 :b5 0)\n(connect :b4 0 :b5 1)\n(connect :b6 0 :b7 0)\n(connect :b7 0 :b8 0)\n(connect :b8 0 :b9 0)\n(connect :b8 0 :b9 1)\n```\n\nSee also: `knob`, `patch`\n\n### print\n\n`print [label]`\n\nWrites to the REPL whatever it receives, after its label: print out0 writes out0: 60 (without one, print: 60). A string is written as it is, anything else as EDN; to shape what it writes, a format or str before it (format \"%.1f Hz\").\n\n**Inlets** \n\n0. anything: it is written in the REPL, after the label (print out0 → out0: 60)\n\n**Try:** Click the msg: the REPL writes freq: 440.1234 and print: 440.1 Hz.\n\n```clojure\n(box :b1 \"msg 440.1234\" 40 30)\n(box :b2 \"print freq\" 40 90)\n(box :b3 \"format \\\"%.1f Hz\\\"\" 180 90)\n(box :b4 \"print\" 180 150)\n(connect :b1 0 :b2 0)\n(connect :b1 0 :b3 0)\n(connect :b3 0 :b4 0)\n```\n\nSee also: `msg`, `format`, `str`\n\n### quantize\n\n`quantize [track]`\n\n**Free time written in measures, when you ask.** What `transcribe` or a drawing left in a `freqt` — notes placed anywhere in time — becomes a measured tree: measures, tuplets, ties, grace notes, voices, ready for a `tree` box, `mt` and the rest.\n\n**Only a bang sends.** The options can be tried first, one message at a time, and nothing goes out until you bang it: a tree written into a tree box is an event of the work's history.\n\n**Two ways in.** A `freqt` on the right inlet (its second outlet: the buffer), or a tree on the left — in free time, or measured (it is made free first, to be written again another way). Two `quantize` boxes can write the same take two ways.\n\nFree time written in measures, when you ask: what transcribe or a drawing left in a freqt (connect the freqt's second outlet to its right inlet), or a tree in free time that comes on the left (a measured one is made free first), becomes a measured tree — measures, tuplets, ties, grace notes, voices —, for a tree box. Only a bang quantizes and sends it, so its options can be tried first: [:meter \"6/8\"], [:meter \"7/8[2+2+3]\"], [:meters [\"3/4\" \"5/8\"]], [:divs [1 2 3 4]] (the divisions a beat may take), [:merge []] (no beats joined into a tuplet), [:legato 0.25] (the largest gap that is not a rest, in beats), [:chord 0.04] (starts that close are one chord), [:voices 1], [:grace false], [:key \"eb\"], [:tempo 72], [:time :track] (find the beats of what was played freely, as track), or a map of them; [:meter nil] forgets one, :reset all of them. With the word track it finds the beats from the start. It is the quantization a freqt shown as a score uses (that is a preview); here it is a step of the patch, with its options in view, and two quantize boxes can write the same take two ways.\n\n**Inlets** \n\n0. a bang: quantize and send · a tree (free or measured): the material, until the next one · [:meter \"6/8\"] and the other options, or a map of them · [:meter nil] forgets one · :reset forgets all · :clear forgets the tree\n1. a freqt (from its second outlet): the material, read at the bang\n\n**Outlets** \n\n0. the measured tree, for a tree box\n1. what it found: {:bars :meter :tempo :notes :voices}\n\n**Messages and gestures**\n\n- `:bang`: quantize the material and send the tree\n- `[:meter \"3/4\"]`: the meter (\"6/8\", \"7/8[2+2+3]\" for its groups); without one, the freqt's bar grid, or 4/4\n- `[:meters [\"3/4\" \"5/8\"]]`: a meter for each bar, the last one going on\n- `[:divs [1 2 3 4]]`: the divisions a beat may take (1 to 8 by default: 3, 5, 7 are tuplets)\n- `[:merge []]`: no two beats joined into one tuplet ([3 5 6] by default)\n- `[:legato 0.25]`: the largest gap before the next note that is not a rest, in beats (0: every gap is a rest)\n- `[:chord 0.04]`: starts this close (beats) are one chord\n- `[:voices 1]`: how many voices overlapping notes may take (2 by default)\n- `[:grace false]`: no grace notes: a note too short for any point is dropped\n- `[:key \"eb\"]`: the key it is written in: its signature and its spelling\n- `[:tempo 72]`: the tempo written in the tree\n- `[:time :track]`: what was played freely (with rubato, at any tempo): its beats are found first (also: quantize track)\n- `{:meter \"6/8\" :divs [1 2 3]}`: several options at once\n- `:reset`: the options forgotten (the defaults again)\n\n**Try:** The freqt holds a phrase played freely — the durations are not quite 1, ½ or ⅓. Click :bang: quantize writes it in measures of 4/4 and the tree box shows the score. Click :meter \"3/4\" and :bang again: the same notes, in 3/4. Change a stroke in the freqt (drag it) and bang: the score follows only when you ask.\n\n```clojure\n(box :b1 \"freqt\" 40 60)\n(resize :b1 420 200)\n(melody :b1 \"c4/1.06 e4/.47 d4/.55 g4/.94 e4/1.03 f4/.32 e4/.36 d4/.3 c4/2.1\" 0)\n(box :b2 \"msg :bang\" 520 30)\n(box :b6 \"msg :meter \\\"3/4\\\"\" 600 30)\n(box :b7 \"msg :meter nil\" 740 30)\n(box :b3 \"quantize\" 520 90)\n(box :b4 \"tree\" 520 160)\n(resize :b4 460 160)\n(box :b5 \"print\" 760 90)\n(connect :b1 1 :b3 1)\n(connect :b2 0 :b3 0)\n(connect :b6 0 :b3 0)\n(connect :b7 0 :b3 0)\n(connect :b3 0 :b4 0)\n(connect :b3 1 :b5 0)\n```\n\n**From your voice** — transcribe writes what pitch~ hears into the freqt, as strokes in free time; quantize writes them in measures. With :time :track (or quantize track) it first finds the beats of what you sang freely.\n\n*Try:* Press ▶, click :rec, sing a phrase, click :stop: the freqt holds it. Click :time :track, then :bang: your phrase, in measures.\n\n```clojure\n(box :b8 \"adc~ 1\" 40 330)\n(box :b9 \"pitch~ 80 1000\" 40 390)\n(box :b10 \"onset~\" 200 390)\n(box :b11 \"msg :rec\" 300 330)\n(box :b12 \"msg :stop\" 380 330)\n(box :b13 \"transcribe 60\" 40 450)\n(box :b14 \"msg :time :track\" 880 30)\n(connect :b8 0 :b9 0)\n(connect :b8 0 :b10 0)\n(connect :b9 0 :b13 0)\n(connect :b10 0 :b13 1)\n(connect :b11 0 :b13 0)\n(connect :b12 0 :b13 0)\n(connect :b13 0 :b1 0)\n(connect :b14 0 :b3 0)\n```\n\nSee also: `transcribe`, `freqt`, `tree`, `mt`\n\n### ramp\n\n`ramp a b s [loop]`\n\nLinear motion: a bang (or [a b s]) goes from a to b in s seconds; a number jumps there.\n\n**Inlets** \n\n0. bang: goes from a to b in s seconds · [a b s]: that motion · a number: jumps there · :stop\n1. 1 / 0: loop on or off\n\n**Outlets** \n\n0. the moving value\n\n**Try:** Press ▶: a glissando of two octaves in four seconds, again and again.\n\n```clojure\n(box :b1 \"loadbang\" 40 30)\n(box :b2 \"ramp 220 880 4 loop\" 40 90)\n(box :b3 \"osc~ 220\" 40 150)\n(box :b4 \"gain~ 0.3\" 40 200)\n(box :b5 \"dac~\" 40 250)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n(connect :b3 0 :b4 0)\n(connect :b4 0 :b5 0)\n(connect :b4 0 :b5 1)\n```\n\nSee also: `metro`, `reader`, `phasor~`\n\n### reader\n\n`reader [x|y|path [stroke]] [norm] [d s] [speed x] [jump s]`\n\nReads the buffer connected to its right inlet (canvas, freqt, ring) at the position that comes in on the left, in the buffer's own units — the X axis of a canvas (Y with `reader y`), the time of a freqt, the seconds of a ring — or, with `norm`, from 0 to 1, as reader~ does at audio rate. On a canvas or freqt: ids on the right and the values on the left (every crossing); with `reader path [stroke]` a position from 0 to 1 travels along a stroke in the order it was drawn and gives [x y]. On a ring: what it crosses, each value as it was written, either way (a move larger than its jump is a seek); or, without positions, it follows the ring's head d behind, then a speed (reader d 1 speed 0.5; msg :d, :speed, :jump, :stop).\n\n**Inlets** \n\n0. a position in the units of the buffer (along X, or Y with reader y; 0…1 with reader norm, or with reader path) · on a ring: in seconds (0…1 with norm), or :d, :speed, :stop\n1. the buffer of a canvas, freqt or ring (a ring's right outlet)\n\n**Outlets** \n\n0. the values where the position crosses something (a list) · from a ring, each value as it was written\n1. their ids (sent first), for voices\n\n**Messages and gestures**\n\n- `reader d 1 · msg :d 1`: on a ring: it follows the ring's head 1 s behind, on its own — a canon, a delay; it starts when the ring's time does\n- `reader d 1 speed 0.5 · msg :speed 0.5`: first the distance, then the speed: at 0.5 it falls behind (an augmentation), at −1 it goes back over what was written\n- `a number (a ramp, a counter)`: on a ring: moves it there; it sends what it crosses, either way, and a move larger than its jump (0.5 s; jump 1, msg :jump 1) is a seek\n- `:stop`: it stops following\n\n**Try:** Press ▶ and click the three messages: each comes back a second later, and from the second reader two seconds later, twice as slow. A ramp into a reader on the ring moves it by hand.\n\n```clojure\n(box :b1 \"msg 60\" 40 30)\n(box :b2 \"msg 64\" 100 30)\n(box :b3 \"msg 67\" 160 30)\n(box :b4 \"ring 8\" 40 90)\n(box :b5 \"reader d 1\" 40 150)\n(box :b6 \"reader d 2 speed 0.5\" 180 150)\n(box :b7 \"print canon\" 40 210)\n(box :b8 \"print slower\" 180 210)\n(connect :b1 0 :b4 0)\n(connect :b2 0 :b4 0)\n(connect :b3 0 :b4 0)\n(connect :b4 1 :b5 1)\n(connect :b4 1 :b6 1)\n(connect :b5 0 :b7 0)\n(connect :b6 0 :b8 0)\n```\n\nSee also: `ring`, `writer`, `canvas`, `reader~`\n\n### reader~\n\n`reader~ [x|y|path [stroke]] [voices] [gate] [norm] [d s] [speed x] [jump s]`\n\nReads a buffer at audio rate, as reader does once per message: a position signal on the left, the buffer on the right. The position is in the buffer's own units — the X axis of a canvas (Y with `reader~ y`), the time of a freqt, the seconds of a sample or a ring~ — or, with `norm`, from 0 to 1 (a phasor~ straight in); along a stroke (`reader~ path`) it is always 0…1. On a canvas or freqt: one signal outlet per voice, or x and y with path; where nothing passes a voice keeps its last value; with `gate`, one more outlet per voice, 1 where it has something. A sample: it plays it. A ring~: it reads there, or, with nothing on its left, follows the ring's head d behind, then a speed (reader~ d 1 speed 0.5; msg :d, :speed, :jump, :gain).\n\n**Inlets** \n\n0. the position signal, in the buffer's units (the X axis of a canvas, the time of a freqt, the seconds of a sample) or 0…1 with reader~ norm (a phasor~ straight in); along a stroke (path) always 0…1 · on a ring~: a position in seconds (0…1 with norm), or nothing (then it follows the ring's head); :d, :speed, :jump, :gain\n1. the buffer of a canvas or freqt, the sound of a sample (then it plays it, 0 its start and 1 its end), or a ring~ (its right outlet)\n\n**Outlets** 1: one signal per voice (the values it crosses) · from a ring~, the sound it reads · with gate: one more per voice, 1 where it sounds and 0 where not\n\n**Messages and gestures**\n\n- `reader~ d 1 · msg :d 1`: on a ring~, without a position: 1 s behind the ring's head — a canon, a delay; a new d glides (the pitch bends) or, larger than its jump (0.25 s), seeks with a crossfade\n- `reader~ d 1 speed 0.5 · msg :speed -1`: first the distance, then the speed: at 0.5 an octave down and falling behind, at −1 backwards\n- `a position signal on a ring~`: it reads there (seconds; norm: 0…1, a phasor~), at any speed, either way\n\n**Try:** Press ▶: the drawing plays every four seconds, and is silent where nothing is drawn (the gate).\n\n```clojure\n(box :b1 \"freqt\" 40 60)\n(box :b2 \"phasor~ 0.25\" 40 15)\n(box :b3 \"reader~ norm 1 gate\" 40 290)\n(box :b4 \"osc~\" 40 340)\n(box :b5 \"gain~\" 40 390)\n(box :b6 \"dac~\" 40 440)\n(connect :b2 0 :b3 0)\n(connect :b1 1 :b3 1)\n(connect :b3 0 :b4 0)\n(connect :b3 1 :b5 1)\n(connect :b4 0 :b5 0)\n(connect :b5 0 :b6 0)\n(connect :b5 0 :b6 1)\n(stroke :b1 [[0 220] [1 330] [1.5 293.66]])\n(stroke :b1 [[2.5 440] [4 220]])\n```\n\nSee also: `phasor~`, `adsr~`, `freqt`, `reader`, `sample`\n\n### realize~ · `@kairotic/analysis`\n\n`realize~ [settings] [midi]`\n\nPlays a faust~ from descriptors written as a score — loudness, brightness, noisiness, pitch — or from what features~ and pitch~ hear in another sound: its pitch (or freq) and gain sliders follow them, and its other sliders take the settings of that faust~ that sound nearest (Study 37).\n\n**Inlets** \n\n0. loudness: dB, or a level 0…1 (features~ rms)\n1. brightness: Hz (features~ centroid)\n2. noisiness: 0…1 (features~ flatness)\n3. pitch: Hz (pitch~; 0 for none), MIDI with realize~ midi\n4. loudness heard in what it plays (features~ of the faust~: rms)\n5. brightness heard (centroid)\n6. noisiness heard (flatness): with these three it corrects itself\n\n**Outlets** \n\n0. [:slider value] for the faust~ it plays: connect it to the faust~'s left inlet\n1. how far the nearest setting is from what is written (above 1: the faust~ cannot sound like that)\n\n**Messages and gestures**\n\n- `:learn`: plays steady settings of the faust~ offline and listens to them (300, or the number written): after changing its code\n\n**Try:** Press ▶ and allow the microphone (headphones): sing, whisper, hum — the synth follows your loudness, brightness, noisiness and pitch with its own sound. Then let it listen: a features~ 20 on the faust~, its three outlets into the last three inlets of realize~ — it corrects what it asks where it falls short. Draw instead: four canvases read by reader~ and snapshot~ are a score for it.\n\n```clojure\n(box :b1 \"adc~ 1\" 40 30)\n(box :b2 \"features~ 20\" 40 90)\n(box :b3 \"pitch~\" 260 90)\n(box :b4 \"realize~\" 40 160)\n(box :b5 \"faust~\" 40 240)\n(box :b6 \"dac~\" 40 430)\n(box :b7 \"msg :learn\" 300 160)\n(connect :b1 0 :b2 0)\n(connect :b1 0 :b3 0)\n(connect :b2 0 :b4 0)\n(connect :b2 1 :b4 1)\n(connect :b2 2 :b4 2)\n(connect :b3 0 :b4 3)\n(connect :b7 0 :b4 0)\n(connect :b4 0 :b5 0)\n(connect :b5 0 :b6 0)\n(connect :b5 0 :b6 1)\n(code :b5 \"import(\\\"stdfaust.lib\\\");\\npitch = hslider(\\\"pitch\\\", 60, 36, 84, 0.01) : si.smoo;\\ngain = hslider(\\\"gain [unit:dB]\\\", -12, -80, 6, 0.1) : ba.db2linear : si.smoo;\\nwave = hslider(\\\"wave\\\", 0.5, 0, 1, 0.001) : si.smoo;\\nnoise = hslider(\\\"noise\\\", 0.1, 0, 1, 0.001) : si.smoo;\\ncutoff = hslider(\\\"cutoff [scale:log]\\\", 1000, 60, 14000, 1) : si.smoo;\\nresonance = hslider(\\\"resonance [scale:log]\\\", 1, 0.5, 8, 0.01) : si.smoo;\\nf0 = ba.midikey2hz(pitch);\\nosc = os.sawtooth(f0) * (1 - wave) + os.square(f0) * wave;\\nprocess = osc * (1 - noise) + no.noise * noise : fi.svf.lp(min(cutoff, 0.45 * ma.SR), resonance) * gain;\")\n```\n\nSee also: `features~`, `pitch~`, `faust~`, `monitor`\n\n### record\n\n`record [lo hi] [log] [tolerance]`\n\nWrites any stream of numbers into a canvas (or a freqt) as strokes over time: an envelope (snapshot~ 50 rms), a descriptor (features~), a knob, a position. :rec starts a take from 0 (its first write clears the buffer); :rec t (msg :rec 4) records from t seconds on, keeping what is before t and replacing what is after (punch-in); :ovr t (msg :ovr 4) overwrites only what the take covers, from t to where it stops, keeping what comes after (punch-in/out); :stop ends it; a bang on the right ends a stroke, and the next number begins another. A value holds until the next one (snapshot~ sends only what changed), simplified within tolerance (1% of the range without it). Time in seconds from rec. With lo hi the Y axis of a canvas is set to them (log with log); without them it follows the values. It writes at most every 2 seconds, each write one event of the history; then reader~ reads it back as an automation.\n\n**Inlets** \n\n0. numbers (a knob, snapshot~, features~…); :rec starts a take from 0, :stop ends it\n1. a bang: the stroke being drawn ends, the next number begins another\n\n**Outlets** \n\n0. edits for a canvas or freqt (its inlet): [:batch …], at most every 2 seconds\n\n**Messages and gestures**\n\n- `:rec`: starts from 0; its first write clears the buffer\n- `:rec t (msg :rec 4)`: from t seconds: what is before t stays, what is after is replaced\n- `:ovr t (msg :ovr 4)`: from t seconds, over only what the take covers: what comes after it stays\n- `:stop`: writes what is left and stops\n\n**Try:** Press ▶, click rec, move the knob for a few seconds, click stop: the canvas holds the gesture. A phasor~ into a reader~ with the canvas on its right plays it back as an automation.\n\n```clojure\n(box :b1 \"knob 0 1 0.5\" 40 30)\n(box :b2 \"msg :rec\" 140 30)\n(box :b3 \"msg :stop\" 200 30)\n(box :b4 \"record 0 1\" 40 120)\n(box :b5 \"canvas\" 40 170)\n(connect :b1 0 :b4 0)\n(connect :b2 0 :b4 0)\n(connect :b3 0 :b4 0)\n(connect :b4 0 :b5 0)\n```\n\nSee also: `canvas`, `snapshot~`, `reader~`, `transcribe`\n\n### ring\n\n`ring [seconds]`\n\nA span of time for messages: it keeps what reached it in the last seconds (8 by default), each at its time. Its time starts at its first message; its write head goes round as a tape head, so what is older than one turn is gone. Its right outlet is the buffer for a reader (d behind, then a speed: a canon, a delay; or at a position from any source) and for a writer (several heads, anywhere, at any speed). :clear empties it, and its time starts again.\n\n**Inlets** \n\n0. any value: written where the ring's time is (from its first message) · a writer's edits · :clear\n\n**Outlets** \n\n0. what it is asked ([:data])\n1. the buffer, for a reader or a writer (on their right or middle inlet); :start when its time starts\n\n**Messages and gestures**\n\n- `ring 8`: keeps the last 8 seconds: its write head goes round as a tape head, so what is older than one turn is gone\n- `:clear`: empties it; its time starts again at the next message\n- `[:data]`: what it keeps, as {:dur :events [[position value] …]}\n\n**Try:** Press ▶ and click the messages: a canon in three voices, 0.5 s and 1.5 s behind. After 4 seconds what you played is gone.\n\n```clojure\n(box :b1 \"msg 60\" 40 30)\n(box :b2 \"msg 67\" 100 30)\n(box :b3 \"ring 4\" 40 90)\n(box :b4 \"reader d 0.5\" 40 150)\n(box :b5 \"reader d 1.5\" 160 150)\n(box :b6 \"print\" 40 210)\n(connect :b1 0 :b3 0)\n(connect :b2 0 :b3 0)\n(connect :b3 1 :b4 1)\n(connect :b3 1 :b5 1)\n(connect :b4 0 :b6 0)\n(connect :b5 0 :b6 0)\n```\n\nSee also: `reader`, `writer`, `record`\n\n### ring~\n\n`ring~ [seconds]`\n\nA span of sound: it keeps the last seconds (8 by default) of what reaches its left inlet, written where its time is, going round as a tape head. Its right outlet is the buffer for reader~ (d behind its head, then a speed: a canon, a delay, an octave down at 0.5, backwards at −1; or at a position signal) and for writer~ (more heads, anywhere, from any signal). Up to 8 heads share one node, so a feedback inside the ring is exact. :clear silences it.\n\n**Inlets** \n\n0. the sound, written where the ring's time is (its write head goes round as a tape head) · :clear silences it\n\n**Outlets** \n\n0. —\n1. the buffer, for reader~ and writer~ (on their right / middle inlet)\n\n**Messages and gestures**\n\n- `ring~ 8`: keeps the last 8 seconds (up to 60)\n- `:clear`: silence, the heads where they are\n- `up to 8 heads`: the reader~ and writer~ on it share one node: a feedback inside the ring is exact, through other boxes it costs a block (128 samples)\n- `reader~ → faust~ → writer~`: a faust~ in a loop of the ring runs inside the ring's node, one sample at a time: exact at any d (a string whose d is its period, a comb, a tape echo that darkens); its parameters follow it there (not a polyphonic one)\n\n**Try:** With headphones, press ▶ and sing: you come back a second later, and from the second reader~ an octave down, ever later. msg :d 0.25 into a reader~ glides it nearer.\n\n```clojure\n(box :b1 \"adc~\" 40 30)\n(box :b2 \"ring~ 8\" 40 90)\n(box :b3 \"reader~ d 1\" 40 150)\n(box :b4 \"reader~ d 1 speed 0.5\" 200 150)\n(box :b5 \"gain~ 0.4\" 40 210)\n(box :b6 \"dac~\" 40 270)\n(connect :b1 0 :b2 0)\n(connect :b2 1 :b3 1)\n(connect :b2 1 :b4 1)\n(connect :b3 0 :b5 0)\n(connect :b4 0 :b5 0)\n(connect :b5 0 :b6 0)\n(connect :b5 0 :b6 1)\n```\n\nSee also: `reader~`, `writer~`, `ring`, `sample`\n\n### sample\n\n`sample [seconds]`\n\nA buffer of sound. What reaches its left inlet is recorded on `:rec` until `:stop` (or until it has seconds, 60 by default), replacing what it had; :rec t (msg :rec 2.5) keeps its first t seconds and records from there (punch-in); :ovr t (msg :ovr 2.5) replaces only what the take covers and keeps what comes after (punch-in/out); `:clear` empties it. Its right outlet is the buffer for a reader~, which plays it at the position on its left, in seconds (or with reader~ norm from 0 to 1: a phasor~); a bang sends its length in seconds on the left, and so does every new recording. The sound stays in this browser; the work keeps its picture. A URL (a string on the left, or (load-sound! :bN \"https://…\")) loads a sound that every browser opening the work fetches by itself. (load-sound! :bN) brings in a file, (save-sound :bN) saves it as WAV.\n\n**Inlets** \n\n0. the signal to record; :rec starts, :stop ends (or its length in seconds), :clear empties it, a bang asks its length\n\n**Outlets** \n\n0. its length in seconds (after each recording, and on a bang)\n1. the sound, for a reader~ (on its right inlet)\n\n**Messages and gestures**\n\n- `:rec`: records what reaches it, from the beginning\n- `:rec t (msg :rec 2.5)`: keeps its first t seconds and records from there\n- `:ovr t (msg :ovr 2.5)`: replaces only what the take covers, keeping what comes after (:ovr: from 0)\n- `:stop`: keeps what was heard\n- `:clear`: empties it\n- `a URL (msg https://… · msg :url github:… · a string)`: loads the sound there; every browser that opens the work fetches it\n- `(load-sound! :bN)`: brings in a sound file\n- `(load-sound! :bN \"https://…\")`: loads it from a URL\n- `(sample! :bN {:url \"…\"})`: a sample that is only a URL, as a link or a shared session writes it\n- `github:owner/repo@ref/path.wav`: a file of a public GitHub repository (through jsDelivr: no CORS problem)\n- `freesound:12345`: a sound of Freesound, with your API key: (freesound-key! \"…\"); (sounds \"kick\") searches; (credits) lists who made them\n- `(save-sound :bN)`: saves it as WAV\n\n**Try:** Press ▶, click rec, sing a phrase, click stop: its length becomes the speed of the phasor~ (!/ 1: one over the seconds), and the reader~ plays it in a loop. Use headphones. Change the phasor~ to play it faster, slower or backwards.\n\n```clojure\n(box :b1 \"adc~ 1\" 40 30)\n(box :b2 \"msg :rec\" 140 30)\n(box :b3 \"msg :stop\" 200 30)\n(box :b4 \"sample 10\" 40 90)\n(box :b5 \"!/ 1\" 40 190)\n(box :b6 \"phasor~\" 40 240)\n(box :b7 \"reader~ norm\" 40 290)\n(box :b8 \"gain~ 0.5\" 40 340)\n(box :b9 \"dac~\" 40 390)\n(connect :b1 0 :b4 0)\n(connect :b2 0 :b4 0)\n(connect :b3 0 :b4 0)\n(connect :b4 0 :b5 0)\n(connect :b5 0 :b6 0)\n(connect :b6 0 :b7 0)\n(connect :b4 1 :b7 1)\n(connect :b7 0 :b8 0)\n(connect :b8 0 :b9 0)\n(connect :b8 0 :b9 1)\n```\n\nSee also: `reader~`, `adc~`, `phasor~`\n\n### scope~\n\n`scope~ [ms] [zoom]`\n\nAn oscilloscope in the patch: the last ms (20 by default) of the signal on its left, drawn from a rising zero crossing so a periodic wave stands still. zoom makes it taller. Drag up or down over it to zoom (⇧ finer) and sideways to change the time; on release both stay in the box text. A number on the left changes ms.\n\n**Inlets** \n\n0. the signal; a number changes the time shown (ms)\n\n**Messages and gestures**\n\n- `drag up/down`: zoom (⇧ finer)\n- `drag sideways`: the time shown\n\n**Try:** Press ▶: a sine wave stands still. Drag over it to zoom; connect an adc~ instead of the osc~.\n\n```clojure\n(box :b1 \"osc~ 220\" 40 30)\n(box :b2 \"scope~ 20\" 40 80)\n(connect :b1 0 :b2 0)\n```\n\nSee also: `adc~`, `snapshot~`\n\n### script\n\n`script [inlets] [outlets]`\n\nClojureScript code box: its source is a function (fn [m] …) that receives and returns messages like any component.\n\n**Inlets** \n\n0. what its function receives, by inlet (as many as the first number)\n\n**Outlets** \n\n0. what its function returns in :out (as many as the second number)\n\n**Messages and gestures**\n\n- `source`: (fn [m] {:out [[0 (* 2 (:value m))]]})\n\nSee also: `component`\n\n### sig~\n\n`sig~ [value]`\n\nA constant signal (a frequency for osc~, a factor for gain~, a position for reader~). A number on the left changes it.\n\n**Inlets** \n\n0. a number: the new constant value\n\n**Outlets** \n\n0. a constant signal\n\nSee also: `phasor~`, `osc~`\n\n### snapshot~\n\n`snapshot~ [ms] [rms|peak|db]`\n\nA signal as numbers: every ms (50 by default) its last value, or with a word its level over that time — rms, peak, or db (the rms in decibels). It sends only what changed, so a constant signal sends once. A number on the left changes ms; a bang sends the last value again. With adc~ it is a level meter; with phasor~, an envelope or faust~ it brings a signal back into the messages.\n\n**Inlets** \n\n0. the signal; a number changes ms, a bang sends the last value again\n\n**Outlets** \n\n0. its value (or its level with rms, peak or db) every ms, only when it changed\n\n**Messages and gestures**\n\n- `rms · peak · db`: written in the box: its level over each ms instead of its value\n\n**Try:** Press ▶: the ramp of the phasor~ arrives as numbers ten times a second. Write snapshot~ 100 peak and connect an adc~ instead.\n\n```clojure\n(box :b1 \"phasor~ 0.5\" 40 30)\n(box :b2 \"snapshot~ 100\" 40 80)\n(box :b3 \"print\" 40 130)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n```\n\nSee also: `adc~`, `scope~`, `phasor~`\n\n### space~ · `@kairotic/spatial`\n\n`space~ [x y]`\n\nA sound placed around the listener (binaural): drag the dot, or send [x y]. For headphones.\n\n**Inlets** \n\n0. the signal; [x y] moves it (−1…1, y = 1 in front)\n\n**Outlets** \n\n0. left\n1. right\n\nSee also: `pan~`, `reader`\n\n### spectrum~ · `@kairotic/analysis`\n\n`spectrum~ [lo hi]`\n\nThe spectrum of a signal drawn in the patch, on a log scale of frequency (dB from -90 to 0).\n\n**Inlets** \n\n0. the signal\n\n**Try:** Press ▶: one peak at 220 Hz. Connect an adc~ instead and sing a vowel: its partials and formants.\n\n```clojure\n(box :b1 \"osc~ 220\" 40 30)\n(box :b2 \"spectrum~\" 40 90)\n(connect :b1 0 :b2 0)\n```\n\nSee also: `scope~`, `features~`\n\n### synth~ · `@kairotic/synth`\n\n`synth~`\n\nPolyphonic triangle-wave synthesizer, one voice per id.\n\n**Inlets** \n\n0. frequencies (a number or a list) · :stop\n1. voice ids (from a reader)\n\n**Outlets** \n\n0. the sound\n\nSee also: `reader`, `adsr~`\n\n### tonnetz · `@kairotic/theory`\n\n`tonnetz [notes]`\n\nTriads on the Tonnetz (fifths across, thirds up) and the path of the harmony: each triad found joined to the ones before.\n\n**Inlets** \n\n0. a list of pitches (Hz, as a keyboard or midiin sends them; MIDI or 0…11 with midi), a list of 12 weights (a chroma, above 0.5), or a number: a note (the last n count: 3); :clear forgets the path\n\n**Outlets** \n\n0. the triad, when it changes (:C, :am, :Ebm…)\n1. the pitch class pressed\n\n**Try:** Click the four messages in order: C, c, A♭, g♯ — P, L, P: each step crosses one edge of the lattice. Press a node to hear which class it is (its number comes out on the right).\n\n```clojure\n(box :b1 \"msg 60 64 67\" 40 30)\n(box :b2 \"msg 60 63 67\" 130 30)\n(box :b3 \"msg 60 63 68\" 220 30)\n(box :b4 \"msg 59 63 68\" 310 30)\n(box :b5 \"tonnetz midi\" 40 80)\n(box :b6 \"print\" 40 340)\n(connect :b1 0 :b5 0)\n(connect :b2 0 :b5 0)\n(connect :b3 0 :b5 0)\n(connect :b4 0 :b5 0)\n(connect :b5 0 :b6 0)\n```\n\nSee also: `pcclock`, `fourier`, `mt`\n\n### transcribe · `@kairotic/analysis`\n\n`transcribe [bpm] [notes|glide] [ms]`\n\nWrites what pitch~ hears into a freqt, as strokes: notes where the contour settles on another pitch (slides, vibrato and ornaments do not start notes), or contours (glide).\n\n**Inlets** \n\n0. Hz from pitch~ (0: silence); :rec starts from 0, :stop ends\n1. a bang (from onset~): a new note, even on the same pitch\n\n**Outlets** \n\n0. edits for a freqt: [:batch [[:stroke …] …]], at most every 2 seconds (one event of the history each)\n\n**Messages and gestures**\n\n- `:rec`: starts a take from 0 (its first write clears the freqt)\n- `:rec t (msg :rec 8)`: from beat t: what is before t stays, what is after is replaced\n- `:ovr t (msg :ovr 8)`: from beat t, over only what the take covers: what comes after it stays\n- `:stop`: writes what is left and stops\n\n**Try:** Press ▶, click :rec, sing a phrase, click :stop: the freqt holds it (⇄ previews it as a score). To write it in measures, as a tree, connect the freqt's second outlet to a quantize box and bang it. Write transcribe 60 glide to keep the slides.\n\n```clojure\n(box :b1 \"adc~ 1\" 40 30)\n(box :b2 \"pitch~ 80 1000\" 40 90)\n(box :b3 \"onset~\" 200 90)\n(box :b4 \"msg :rec\" 330 90)\n(box :b5 \"msg :stop\" 400 90)\n(box :b6 \"transcribe 60\" 40 160)\n(box :b7 \"freqt\" 40 220)\n(connect :b1 0 :b2 0)\n(connect :b1 0 :b3 0)\n(connect :b2 0 :b6 0)\n(connect :b3 0 :b6 1)\n(connect :b4 0 :b6 0)\n(connect :b5 0 :b6 0)\n(connect :b6 0 :b7 0)\n```\n\nSee also: `pitch~`, `onset~`, `freqt`, `quantize`\n\n### tree\n\n`tree`\n\nA musical tree written in EDN (hiccup style: [:voice [:measure {:meter [4 4]} \"c4/1 e4 g4/2\"]]), seen as a score or as a roll of frequency over time (⇄ in its header), its text in the code window ({ } in its header) — one tree, two views (discussion #92): drawing on its roll writes notes into the tree (free time without measures, quantized bars with them). It sends its tree, expanded, whenever it changes (and again on a bang); `tree manual` only on a bang. Its second outlet is its notes as a buffer, for a reader~. On its inlet it takes edits [:edit [[:attrs path {…}] …]] (from a score's edits outlet) and whole trees, which change it.\n\n**Inlets** \n\n0. a bang: sends the tree again · [:edit …] (from the edits outlet of a freqt shown as a score): changes it · a tree: replaces it\n\n**Outlets** \n\n0. the tree, expanded (melody strings become notes, [:use …] the fragments it names), whenever it changes\n1. its notes as a buffer (strokes of frequency over time), for the right inlet of a reader~\n\n**Messages and gestures**\n\n- `{ } in the header (or a double-click on its right) · (source :bN)`: its text, in the code window (Ctrl+Enter applies): only the nodes that changed go into the history\n- `(tree! :bN [:voice …])`: writes a tree into it, as edits of the nodes that change\n- `(tree-edit! :bN [:attrs [0 1 2] {…}])`: edits nodes by their path: [:set p x] [:attrs p {…}] [:insert p x] [:remove p]\n- `(node-at :bN [0 1])`: the node at a path\n- `score: how it is shown at first · (view :bN :score)`: the tree drawn as a score, in this box (⇄ roll shows its roll)\n- `in a score: click a note`: ↑ ↓ pitch (⇧ octave) · a…g the nearest note of that name · # another name (c#4 → db4) · + − duration · ← → next · Delete → rest\n- `{:key \"eb\"} on the tree, a voice or a measure`: the score's key: its signature, accidentals that last the bar; :none writes every accidental\n- `in a score: click a rest`: Enter → a note (the pitch of the one before) · ↑ ↓ a step above or below it · a…g that note\n- `(as-tree :bN)`: reads it back as data\n- `⇄ roll · (view :bN :roll)`: a piano roll: its notes as strokes of frequency over time: drawing, dragging, stretching or erasing there edits the tree (free time; with measures, the bars it touches are quantized again; ⌥ to a free voice)\n- `(quantize! :bN) · (unquantize! :bN)`: its free time written in measures, and back (one event each)\n- `(track! :bN)`: its free time played (in seconds, at any tempo): the beats are found and kept in its :quant, so that its score and quantize! write it on them\n\n**Try:** The tree box is its own score: click a note and press ↑ (or a…g, + −, Delete), or press { } in its header, change a note in its text and apply it (Ctrl+Enter). It sends its tree whenever it changes: through mt transpose 7 it reaches the second tree box, a fifth higher, which follows. Press ⇄ roll on the tree box to draw notes into it. (A tree that comes into a tree box is written into it, as one event of the history.)\n\n```clojure\n(box :b1 \"bang\" 40 20)\n(box :b2 \"tree\" 40 60)\n(code :b2 \"[:voice\\n [:measure {:meter [3 4]} \\\"e5/1\\\" [:tuplet {:ratio [3 2]} \\\"d5/.5 c5 b4\\\"] [:note {:pitch \\\"a4\\\" :dur 1 :dyn \\\"p\\\"}]]\\n [:measure \\\"g4/3\\\"]]\")\n(box :b3 \"mt transpose 7\" 40 190)\n(box :b4 \"tree\" 40 230)\n(connect :b1 0 :b2 0)\n(connect :b2 0 :b3 0)\n(connect :b3 0 :b4 0)\n```\n\nSee also: `mt`, `quantize`, `freqt`\n\n### writer\n\n`writer [ovr|mix] [jump s] [norm]`\n\nA write head on a buffer (a ring): what reaches its left inlet is written where it is. Its position comes in on the right, from any source (a ramp, a counter, a phasor~ through snapshot~), in seconds of the span (0…1 with norm); without one it writes where the ring's head is. Moving, it replaces what it passes, as a tape head — silence too (ovr, the default) — or leaves it (mix); a move larger than its jump is a seek. :rec t / :ovr t send it to t, moving on at speed 1. Its outlet goes to the ring's left inlet; the ring's right outlet to its middle inlet.\n\n**Inlets** \n\n0. what is written where the writer is · :rec t / :ovr t · :stop\n1. the buffer (a ring's right outlet)\n2. a position in seconds of the span (0…1 with norm), from any source\n\n**Outlets** \n\n0. edits for the ring (its left inlet)\n\n**Messages and gestures**\n\n- `writer · writer mix`: ovr (the default) replaces what it passes, silence too, as a tape head; mix leaves it (an overdub)\n- `a position on the right`: it goes there: moving, with ovr it erases what it passes; a move larger than its jump (0.5 s; writer jump 1) is a seek\n- `:ovr t (msg :ovr 2)`: to t, then on at speed 1, replacing what it passes\n- `:rec t (msg :rec 2)`: the same, and on a ring everything else is erased first\n- `:stop`: it stays where it is\n\n**Try:** Press ▶ and click the notes: without a position the writer writes where the ring's head is, and the reader plays them a second later. Click :ovr 0: now the writer goes round from the ring's position 0 at speed 1, wherever the ring's head is, replacing what it passes, and the reader meets the notes when it gets there. A ramp on its right inlet moves it by hand.\n\n```clojure\n(box :b1 \"msg 60\" 40 30)\n(box :b2 \"msg 67\" 100 30)\n(box :b3 \"msg :ovr 0\" 160 30)\n(box :b4 \"writer\" 40 90)\n(box :b5 \"ring 4\" 40 150)\n(box :b6 \"reader d 1\" 40 210)\n(box :b7 \"print\" 40 270)\n(connect :b1 0 :b4 0)\n(connect :b2 0 :b4 0)\n(connect :b3 0 :b4 0)\n(connect :b4 0 :b5 0)\n(connect :b5 1 :b4 1)\n(connect :b5 1 :b6 1)\n(connect :b6 0 :b7 0)\n```\n\nSee also: `ring`, `reader`, `record`\n\n### writer~\n\n`writer~ [ovr|mix [keep]] [jump s] [norm]`\n\nA write head on a ring~: the sound on its left is written where it is, as a tape head — ovr (the default) replaces what is there, silence too; mix adds to it (mix 0.8: what was there fades a little at each pass). Its position: a signal on the right (seconds, or 0…1 with norm: a phasor~), any speed, either way — a jump larger than its jump is a seek; or, without one, the ring's head. :rec t / :ovr t send it to t, moving on at speed 1 (rec erases the ring first); :stop holds it. The ring~'s right outlet goes to its middle inlet.\n\n**Inlets** \n\n0. the sound it writes · :rec t / :ovr t · :stop · :keep x\n1. the ring~'s buffer (its right outlet)\n2. a position signal (seconds, or 0…1 with norm: a phasor~); without one, where the ring's head is\n\n**Messages and gestures**\n\n- `writer~ · writer~ mix · writer~ mix 0.8`: ovr (the default) replaces what is there, silence too, as a tape head; mix adds to it, keeping what was there times 0.8\n- `a position signal`: it writes there as it goes, at any speed, either way; a jump larger than its jump (0.25 s) is a seek\n- `:ovr t (msg :ovr 2) · :rec t`: to t, then on at speed 1, replacing; rec erases the ring first\n- `:stop`: it stays where it is\n\n**Try:** With headphones, press ▶ and sing: the writer~ goes round the ring backwards (a phasor~ at −0.25 Hz), so the reader~, which goes forwards, plays you reversed, in chunks.\n\n```clojure\n(box :b1 \"adc~\" 40 30)\n(box :b2 \"phasor~ -0.25\" 200 30)\n(box :b3 \"writer~ norm\" 40 90)\n(box :b4 \"ring~ 4\" 200 90)\n(box :b5 \"reader~ d 0.5\" 200 150)\n(box :b6 \"gain~ 0.4\" 200 210)\n(box :b7 \"dac~\" 200 270)\n(connect :b1 0 :b3 0)\n(connect :b2 0 :b3 2)\n(connect :b4 1 :b3 1)\n(connect :b4 1 :b5 1)\n(connect :b5 0 :b6 0)\n(connect :b6 0 :b7 0)\n(connect :b6 0 :b7 1)\n```\n\nSee also: `ring~`, `reader~`, `phasor~`\n\n"}}};
|