Skip to content

Art and animation, written as code. Illustrations, loops, interactive web art, launch-videos and scored films in dozens of styles, identical on every render.

chore: resync Codex mirror

Alex Greenshpun54df17bb13e9
diff --git a/plugins/anidoodle/skills/anidoodle/SKILL.md b/plugins/anidoodle/skills/anidoodle/SKILL.md
index 5e5c665..0536d4a 100644
--- a/plugins/anidoodle/skills/anidoodle/SKILL.md
+++ b/plugins/anidoodle/skills/anidoodle/SKILL.md
@@ -42,7 +42,7 @@ say why in one line. Write the answers into a short brief before drawing.
| A style matched from their image | `references/workflows/adapt-a-style.md` |
| A score or soundtrack | `references/music/README.md` |
-- Music: pick a style vocabulary and mood, compose your own harmony, motif and form (references/music/compose.md), then node tools/music.mjs check <score.ts#export> must PASS before a human listens. Styles give sound, never notes.
+- Music: pick a style vocabulary and mood, sketch the tension arc and motif, compose your own harmony, motif and form (references/music/compose.md, craft in references/music/theory/), revise until node tools/music.mjs craft shows only findings you chose, then check must PASS before a human listens. Styles give sound, never notes.
- Sound effects: references/music/sound-design.md. 14 layered, seeded effects cued by film frame (filmSfx); the score ducks, and every cue must be within 6 dB of it. Effects only on real direction changes, one riser + one impact per film.
- Launch films: `launchTemplate.ts` renders a product's launch from data: prompts, plates drawn for it, a score composed for it, words, install lines; habits that save tokens are in `references/working-method.md`.
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/craft.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/craft.ts
new file mode 100644
index 0000000..566e41c
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/craft.ts
@@ -0,0 +1,326 @@
+// CRAFT: measures how a composed piece is WRITTEN (not how it sounds): melody, harmony, rhythm,
+// tension and mood fit, straight from the notes, in milliseconds, no render. Advisory by design:
+// every finding names what it saw, where, and a fix; thresholds are genre-aware (craftTables.ts).
+// Only real errors (a note an acoustic instrument cannot play) are level "error". The composer
+// revises with it (references/music/compose.md, step 8); the theory is references/music/theory/.
+import { beatsPerBar, isCompound, sectionSpans, type Piece, type Note, type Role } from "./plan";
+import { MODES, pcOf, nameOf, type ModeId } from "./theory";
+import { MOODS, type MoodId } from "./tables";
+import { LOW_INTERVAL_LIMIT, INST_RANGE, IC_DISSONANCE, ROOT_TENSION, CRAFT_PROFILE, type CraftProfile } from "./craftTables";
+
+export type Finding = { level: "error" | "warn" | "info"; area: "melody" | "harmony" | "rhythm" | "tension" | "mood" | "range"; msg: string; fix?: string };
+const E = 1e-6;
+const mean = (a: number[]) => (a.length ? a.reduce((x, y) => x + y, 0) / a.length : 0);
+const pct = (x: number) => `${Math.round(x * 100)} %`;
+const mod12 = (x: number) => ((x % 12) + 12) % 12;
+
+/** The low-interval chart is loose by about 2 semitones (instrument-dependent), so craft flags a close interval 3+ semitones under its limit. */
+export const MUD_SLACK = 2;
+// ------------------------------------------------------------------ piece context
+type Span = { id: string; kind: string; a: number; b: number };
+type Ctx = { p: Piece; bpb: number; compound: boolean; spans: Span[]; notes: Note[]; mel: Note[]; profile: CraftProfile; keyAt: (t: number) => { tonic: number; mode: ModeId }; end: number };
+/** One voice: the top note of each onset (bass: the bottom). */
+export const topVoice = (ns: Note[], low = false) => { const by = new Map<number, Note>(); for (const n of ns) { const k = Math.round(n.t * 96), o = by.get(k); if (!o || (low ? n.p < o.p : n.p > o.p)) by.set(k, n); } return [...by.values()].sort((a, b) => a.t - b.t); };
+
+const context = (p: Piece): Ctx => {
+ const bpb = beatsPerBar(p.plan.meter), plan = sectionSpans(p.plan);
+ const spans: Span[] = p.arrangement?.length ? p.arrangement.map((x) => ({ id: x.id, kind: x.kind, a: x.from * bpb, b: (x.from + x.bars) * bpb })) : plan.map((x) => ({ id: x.s.id, kind: x.s.id, a: x.a, b: x.b }));
+ const notes = p.parts.flatMap((pt) => pt.notes.map((n) => ({ ...n, inst: pt.inst, part: pt.id }))) as (Note & { inst: string; part: string })[];
+ const keyAt = (t: number) => { const s = plan.find((x) => t >= x.a - E && t < x.b - E) ?? plan[plan.length - 1]; return { tonic: pcOf(s.s.key.replace(/m$/, "")), mode: s.s.mode }; };
+ const end = Math.max(spans[spans.length - 1]?.b ?? 0, ...notes.map((n) => n.t + n.d));
+ return { p, bpb, compound: isCompound(p.plan.meter), spans, notes, mel: topVoice(notes.filter((n) => n.role === "melody")), profile: CRAFT_PROFILE[p.plan.style] ?? CRAFT_PROFILE.folk, keyAt, end };
+};
+const where = (c: Ctx, t: number) => { const bar = Math.floor(t / c.bpb + E); return `bar ${bar + 1} beat ${+((t - bar * c.bpb) + 1).toFixed(2)}`; };
+const sectionOf = (c: Ctx, t: number) => c.spans.find((s) => t >= s.a - E && t < s.b - E);
+
+/** Metric weight of a position (GTTM-style hierarchy, Lerdahl & Jackendoff 1983): downbeat 4, mid-bar 3 (4/4, 12/8), beat 2, eighth 1, sixteenth 0, finer -1. */
+export const metricWeight = (t: number, bpb: number, compound: boolean) => {
+ const pos = (((t % bpb) + bpb) % bpb), on = (step: number) => Math.abs(pos / step - Math.round(pos / step)) < 1e-4;
+ if (on(bpb) || Math.abs(pos - bpb) < 1e-4) return 4;
+ if ((bpb === 4) && on(2)) return 3;
+ if (on(1)) return 2;
+ if (compound ? on(1 / 3) : on(0.5)) return 1;
+ if (compound ? on(1 / 6) : on(0.25)) return 0;
+ return -1;
+};
+
+/** Longuet-Higgins & Lee (1984) style syncopation: an onset on a weak position followed by silence (a rest or its own tie) over a stronger one. Returns mean syncopation per onset and the syncopated share. */
+export const syncopation = (onsets: number[], bpb: number, compound: boolean) => {
+ const ts = [...new Set(onsets.map((t) => Math.round(t * 96) / 96))].sort((a, b) => a - b), g = compound ? 1 / 6 : 0.25;
+ let sum = 0, n = 0;
+ for (let i = 0; i < ts.length - 1; i++) {
+ const t = ts[i], nx = ts[i + 1], w = metricWeight(t, bpb, compound); let mx = -2;
+ for (let k = Math.floor(t / g + E) + 1; k * g < nx - E && k * g < t + bpb; k++) mx = Math.max(mx, metricWeight(k * g, bpb, compound));
+ if (mx > w) { sum += mx - w; n++; }
+ }
+ return { index: ts.length > 1 ? sum / (ts.length - 1) : 0, share: ts.length > 1 ? n / (ts.length - 1) : 0 };
+};
+
+// ------------------------------------------------------------------ harmony helpers
+const sounding = (c: Ctx, t: number, roles: Role[]) => c.notes.filter((n) => roles.includes(n.role) && n.t <= t + E && n.t + n.d > t + E);
+/** The harmony's pitch classes at t: every accompaniment and bass note of the current harmony span (so broken chords and arpeggios count whole), else what sounds. */
+const chordPcs = (c: Ctx, t: number) => {
+ const hs = c.p.harmony, i = hs.reduce((k, h, j) => (h.t <= t + E ? j : k), -1);
+ if (i < 0) return new Set(sounding(c, t, ["accomp", "inner", "bass"]).map((n) => mod12(n.p)));
+ const a = hs[i].t, b = hs.slice(i + 1).find((h) => h.t > a + E)?.t ?? Infinity;
+ return new Set(c.notes.filter((n) => (n.role === "accomp" || n.role === "inner" || n.role === "bass") && ((n.t >= a - E && n.t < b - E) || (n.t < a && n.t + n.d > a + E))).map((n) => mod12(n.p)));
+};
+/** The root of the harmony at t: the lowest bass note sounding (or starting within the first beat), else the lowest chord note. */
+const rootAt = (c: Ctx, t: number) => {
+ const b = sounding(c, t + 0.01, ["bass"]); const bs = b.length ? b : c.notes.filter((n) => n.role === "bass" && n.t >= t - E && n.t < t + 1);
+ const pool = bs.length ? bs : sounding(c, t + 0.01, ["accomp", "inner"]);
+ return pool.length ? mod12(Math.min(...pool.map((n) => n.p))) : -1;
+};
+const changes = (c: Ctx) => { const hs = c.p.harmony.slice().sort((a, b) => a.t - b.t), out: { t: number; name: string }[] = []; for (const h of hs) if (!out.length || out[out.length - 1].name !== h.name) out.push(h); return out; };
+const DEG = ["1", "b2", "2", "b3", "3", "4", "#4", "5", "b6", "6", "b7", "7"];
+
+export const classifyCadence = (prev: number, last: number): string => {
+ if (last === 0) return prev === 7 || prev === 11 ? "authentic" : prev === 5 ? "plagal" : prev === 10 || prev === 8 || prev === 1 || prev === 2 ? "modal" : prev === 0 ? "held" : "arrival";
+ if (last === 7) return "half"; if (prev === 7 && (last === 9 || last === 8)) return "deceptive"; return "open";
+};
+
+// ------------------------------------------------------------------ melody
+const phrasesOf = (c: Ctx) => {
+ const out: Note[][] = []; let cur: Note[] = [];
+ c.mel.forEach((n, i) => { const nx = c.mel[i + 1]; cur.push(n);
+ const gap = nx ? nx.t - (n.t + n.d) : Infinity, cross = nx && sectionOf(c, nx.t) !== sectionOf(c, n.t);
+ if (!nx || gap >= 0.75 - E || cross || (n.d >= 2 && nx)) { if (cur.length >= 2) out.push(cur); cur = []; } });
+ return out;
+};
+/** Huron (1996) contour class: first, mean of the middle, last. */
+export const contourClass = (ph: Note[]) => {
+ const f = ph[0].p, l = ph[ph.length - 1].p, mid = ph.length > 2 ? mean(ph.slice(1, -1).map((n) => n.p)) : (f + l) / 2, s = (x: number) => (x > 1 ? 1 : x < -1 ? -1 : 0);
+ const a = s(mid - f), b = s(l - mid);
+ return a > 0 && b < 0 ? "arch" : a < 0 && b > 0 ? "bowl" : a >= 0 && b >= 0 && (a || b) ? "ascending" : a <= 0 && b <= 0 && (a || b) ? "descending" : "level";
+};
+export type Development = "exact" | "sequence" | "varied" | "new";
+/** How a phrase relates to the phrases before it (Schoenberg, Fundamentals of Musical Composition, 1967: repetition, sequence, variation): its opening rhythm and intervals compared to each earlier phrase's. */
+export const development = (ph: Note[], earlier: Note[][]): Development => {
+ const ioi = (x: Note[]) => x.slice(1).map((n, i) => Math.round((n.t - x[i].t) * 12)), iv = (x: Note[]) => x.slice(1).map((n, i) => n.p - x[i].p);
+ const rank: Record<Development, number> = { exact: 3, sequence: 2, varied: 1, new: 0 }; let best: Development = "new";
+ for (const q of earlier) { const L = Math.min(ph.length, q.length) - 1; if (L < 2) continue; // a two-note fragment matches anything: compare cells of 3+ notes
+ const r1 = ioi(ph), r2 = ioi(q), i1 = iv(ph), i2 = iv(q); let rs = 0, is = 0, cs = 0;
+ for (let k = 0; k < L; k++) { if (r1[k] === r2[k]) rs++; if (i1[k] === i2[k]) is++; if (Math.sign(i1[k]) === Math.sign(i2[k])) cs++; }
+ rs /= L; is /= L; cs /= L; const same = ph.length === q.length;
+ const d: Development = rs === 1 && is === 1 && same ? (ph[0].p === q[0].p ? "exact" : "sequence") : rs >= 0.6 || is >= 0.6 || (cs >= 0.75 && rs >= 0.4) ? "varied" : "new";
+ if (rank[d] > rank[best]) best = d; }
+ return best;
+};
+/** Motif repetition: the share of phrases that bring back an earlier one (exact, as a sequence, or varied), and the share of bars that are exact copies of an earlier bar. */
+export const repetition = (mel: Note[], bpb: number, phrases: Note[][] = [mel]) => {
+ // two segmentations: phrases (split at rests) and bar-length cells (a motif often lives in a bar inside a long phrase); the one that hears more returns wins
+ const profile = (segs: Note[][]) => { const dev: Record<Development, number> = { exact: 0, sequence: 0, varied: 0, new: 0 }; segs.forEach((x, i) => { if (i) dev[development(x, segs.slice(0, i))]++; }); const k = Math.max(1, segs.length - 1); return { dev, k, index: segs.length > 1 ? (dev.exact + dev.sequence + dev.varied) / k : 0 }; };
+ const byBar = new Map<number, Note[]>(); for (const x of mel) { const b = Math.floor(x.t / bpb + E); (byBar.get(b) ?? byBar.set(b, []).get(b)!).push(x); }
+ const A = profile(phrases), B = profile([...byBar].sort((a, b) => a[0] - b[0]).map(([, v]) => v).filter((v) => v.length >= 3)), win = B.index > A.index ? B : A, dev = win.dev, n = win.k;
+ const bars = new Map<number, string>(); for (const n of mel) { const b = Math.floor(n.t / bpb + E); bars.set(b, `${bars.get(b) ?? ""}${Math.round((n.t - b * bpb) * 12)}:${n.p}:${Math.round(n.d * 12)} `); }
+ const seen = new Set<string>(); let copies = 0; for (const [, s] of [...bars].sort((a, b) => a[0] - b[0])) { if (seen.has(s)) copies++; seen.add(s); }
+ return { index: win.index, exact: dev.exact / n, dev, exactBarCopies: bars.size ? copies / bars.size : 0 };
+};
+
+type NCT = "passing" | "neighbour" | "appoggiatura" | "suspension" | "escape" | "other";
+/** Non-chord tones by approach and departure (Aldwell & Schachter, Harmony and Voice Leading, ch. 9-10 terms). */
+const classifyNct = (prev: Note | undefined, n: Note, next: Note | undefined): NCT => {
+ const a = prev ? n.p - prev.p : NaN, b = next ? next.p - n.p : NaN, step = (x: number) => Math.abs(x) >= 1 && Math.abs(x) <= 2;
+ if (prev && prev.p === n.p && step(b) && b < 0) return "suspension";
+ if (step(a) && step(b)) return Math.sign(a) === Math.sign(b) ? "passing" : "neighbour";
+ if (Math.abs(a) > 2 && step(b) && Math.sign(a) !== Math.sign(b)) return "appoggiatura";
+ if (step(a) && Math.abs(b) > 2) return "escape";
+ return "other";
+};
+
+// ------------------------------------------------------------------ the report
+export type CraftReport = {
+ melody: { phrases: number; contours: Record<string, number>; leaps: number; leapsRecovered: number; stepShare: number; range: [string, string] | null; repetition: number; development: Record<Development, number>; exactBarCopies: number; stableEnds: number; lastNote: string | null; climax: { note: string; at: number; times: number } | null; strongBeatChordTones: number; ncts: Record<NCT, number> };
+ harmony: { cadences: { id: string; type: string; motion: string }[]; parallels: number; octaveDoublings: number; innerJumps: number; meanMotion: number; leadUnderChords: number; mud: { at: string; notes: string }[] };
+ rhythm: { syncopation: { melody: number; bass: number; drums: number }; density: { id: string; perBeat: number; layers: number }[]; grooveConsistency: number | null; chordChangesOnBeats: number; repeatedSections: string[] };
+ tension: { sections: { id: string; value: number }[]; peakAt: number; bars: number[] };
+ mood: { mood: MoodId; checks: { what: string; value: string; want: string; ok: boolean }[] };
+ scores: { melody: number; harmony: number; rhythm: number; tension: number; mood: number };
+ findings: Finding[];
+};
+
+export const craftReport = (p: Piece, o: { centroidHz?: number } = {}): CraftReport => {
+ const c = context(p), F: Finding[] = [], add = (f: Finding) => F.push(f), { bpb, compound, mel, profile } = c;
+ const loop = Boolean(p.plan.loop), moodId = (Array.isArray(p.plan.sections[0].mood) ? p.plan.sections[0].mood[0] : p.plan.sections[0].mood) as MoodId;
+ const openOk = profile.openEnding || ["tension", "dread", "eerie", "curious"].includes(moodId);
+
+ // ---------------- melody
+ const phrases = phrasesOf(c), contours: Record<string, number> = {};
+ for (const ph of phrases) { const k = contourClass(ph); contours[k] = (contours[k] ?? 0) + 1; }
+ let leaps = 0, rec = 0, steps = 0, moves = 0; const unrecovered: number[] = [];
+ for (const ph of phrases) for (let i = 1; i < ph.length; i++) {
+ const iv = ph[i].p - ph[i - 1].p; if (iv) { moves++; if (Math.abs(iv) <= 2) steps++; }
+ if (Math.abs(iv) >= 5) { leaps++; const nx = ph[i + 1], pcs = chordPcs(c, ph[i].t);
+ // turned back, or arpeggiating the harmony (the next leap outlines the same chord: a consonant skip, e.g. a fanfare)
+ const arp = nx && Math.abs(nx.p - ph[i].p) >= 3 && Math.sign(nx.p - ph[i].p) === Math.sign(iv) && [ph[i - 1], ph[i], nx].every((n) => pcs.has(mod12(n.p)));
+ if (!nx || Math.sign(nx.p - ph[i].p) === -Math.sign(iv) || nx.p === ph[i].p || arp) rec++; else unrecovered.push(ph[i].t); }
+ }
+ const stepShare = moves ? steps / moves : 1, recShare = leaps ? rec / leaps : 1;
+ if (leaps >= 3 && recShare < 0.6) add({ level: profile.arpeggioMelody ? "info" : "warn", area: "melody", msg: `${leaps - rec} of ${leaps} leaps (a 4th or more) keep going the same way (first at ${where(c, unrecovered[0])})`, fix: "after a leap, turn back by step: the ear expects the gap filled (von Hippel & Huron 2000). Arpeggio idioms are exempt" });
+ if (moves >= 8 && stepShare < 0.35 && !profile.arpeggioMelody) add({ level: "warn", area: "melody", msg: `only ${pct(stepShare)} of melodic moves are steps`, fix: "a singable line is mostly steps (60-80 % in folk and song corpora) with a few leaps for shape; fill leaps in with steps" });
+ if (phrases.length >= 3) { const top = Object.entries(contours).sort((a, b) => b[1] - a[1])[0]; if (top[0] === "level" && top[1] / phrases.length > 0.5) add({ level: "warn", area: "melody", msg: `${top[1]} of ${phrases.length} phrases are level (no rise and fall)`, fix: "give phrases a shape: an arch (rise to a high point, fall home) is the commonest and most satisfying (Huron 1996)" }); }
+ const rep = repetition(mel, bpb, phrases);
+ if (phrases.length >= 4 && rep.index < 0.25) add({ level: "warn", area: "melody", msg: `only ${pct(rep.index)} of phrases (or bars) bring back an earlier one (exact ${rep.dev.exact}, sequence ${rep.dev.sequence}, varied ${rep.dev.varied}, new ${rep.dev.new})`, fix: "state a 2-5 note motif, then bring it back developed (same rhythm new pitches, a sequence a step up, inverted, fragmented): a tune the ear can hold returns to its idea" });
+ // loop idioms (lo-fi, hip-hop, house) repeat on purpose: repetition is the groove's pleasure there, so only near-total copying is flagged
+ if (phrases.length >= 4 && rep.exact > (profile.groove ? 0.85 : 0.6)) add({ level: "warn", area: "melody", msg: `${pct(rep.exact)} of phrases (or bars) are exact copies of an earlier one`, fix: "repeat the motif, but vary it: change the last interval, displace it by an eighth, sequence it a step up, answer it in another register" });
+ // phrase ends and strong beats vs the harmony
+ /** a chord tone; outside common-practice idioms the added 6th and 9th count too (Levine, The Jazz Theory Book, 1995: 6 and 9 are colour tones, not dissonances to resolve) */
+ const isCt = (n: Note) => { const pcs = chordPcs(c, n.t), pc = mod12(n.p); if (pcs.has(pc)) return true; if (profile.parallels === "forbid") return false; const r = rootAt(c, n.t); return r >= 0 && [2, 9].includes(mod12(pc - r)); };
+ let stable = 0; for (const ph of phrases) { const n = ph[ph.length - 1]; if (isCt(n)) stable++; }
+ if (phrases.length >= 3 && stable / phrases.length < 0.6) add({ level: "warn", area: "melody", msg: `only ${stable} of ${phrases.length} phrases end on a chord tone`, fix: "end phrases on chord tones (answers on 1, 3 or 5 of the key); save the unresolved end for a question phrase" });
+ const last = mel[mel.length - 1]; let lastNote: string | null = null;
+ if (last) { const k = c.keyAt(last.t), deg = mod12(last.p - k.tonic), iv = MODES[k.mode].intervals, triad = [0, iv[2], iv[4]].filter((x) => x !== undefined);
+ lastNote = `${nameOf(last.p)} (${DEG[deg]})`;
+ if (!loop && !triad.includes(deg)) add({ level: openOk ? "info" : "warn", area: "melody", msg: `the melody's last note is ${lastNote}, off the home triad`, fix: openOk ? "an open ending suits this mood; keep it if you meant it" : "end on 1 (or 3/5) of the key, or make the unresolved ending a choice the picture asks for" }); }
+ let strong = 0, strongCt = 0; const ncts: Record<NCT, number> = { passing: 0, neighbour: 0, appoggiatura: 0, suspension: 0, escape: 0, other: 0 };
+ mel.forEach((n, i) => { const pcs = chordPcs(c, n.t); if (!pcs.size) return; const ct = isCt(n);
+ if (metricWeight(n.t, bpb, compound) >= 2) { strong++; if (ct) strongCt++; }
+ if (!ct && n.d >= (compound ? 1 / 3 : 0.25) - E) ncts[classifyNct(mel[i - 1], n, mel[i + 1])]++; });
+ const sbct = strong ? strongCt / strong : 1;
+ if (strong >= 8 && sbct < 0.5) add({ level: "warn", area: "melody", msg: `only ${pct(sbct)} of the melody's strong-beat notes are chord tones`, fix: "put chord tones on the beats; keep dissonance for passing and neighbour tones, or as an appoggiatura/suspension that resolves down by step" });
+ if (ncts.other >= 4 && ncts.other > (ncts.passing + ncts.neighbour + ncts.appoggiatura + ncts.suspension)) add({ level: "info", area: "melody", msg: `${ncts.other} non-chord tones are neither approached nor left by step`, fix: "a dissonance reads as intended when a step leads into or out of it" });
+ // range and climax
+ let climax: CraftReport["melody"]["climax"] = null;
+ if (mel.length) { const hi = Math.max(...mel.map((n) => n.p)), first = mel.find((n) => n.p === hi)!, times = mel.filter((n) => n.p === hi).length, at = (first.t - (c.spans[0]?.a ?? 0)) / Math.max(1, c.end - (c.spans[0]?.a ?? 0));
+ climax = { note: nameOf(hi), at, times };
+ if (mel.length >= 16 && !loop && at < 0.3) add({ level: "warn", area: "melody", msg: `the melody peaks (${nameOf(hi)}) at ${pct(at)} of the piece`, fix: "save the highest note for the second half (often around two thirds in): the climax is where the piece arrives" });
+ if (mel.length >= 16 && times > Math.max(3, mel.length / 12)) add({ level: "info", area: "melody", msg: `the top note ${nameOf(hi)} is heard ${times} times`, fix: "one high point per phrase group: a climax heard often stops being one" }); }
+
+ // ---------------- range per part
+ for (const pt of p.parts) { const r = INST_RANGE[pt.inst]; const ns = pt.notes.filter((n) => n.role !== "drum"); if (!r || !ns.length || pt.role === "drum") continue;
+ const lo = Math.min(...ns.map((n) => n.p)), hi = Math.max(...ns.map((n) => n.p));
+ const sweet: [number, number] = pt.role === "bass" && r.play ? [r.play[0], r.sweet[1]] : r.sweet, over = r.play ? Math.max(r.play[0] - lo, hi - r.play[1]) : 0;
+ if (r.play && over > 0) add({ level: over >= 3 ? "error" : "warn", area: "range", msg: `${pt.id} (${pt.inst}) plays ${nameOf(lo)}-${nameOf(hi)}, outside what a ${pt.inst} can play (${nameOf(r.play[0])}-${nameOf(r.play[1])})`, fix: over >= 3 ? "move the part by an octave or give it to an instrument that owns that register" : "a semitone or two past the standard range: extended-range models exist, but moving those notes an octave is safer" });
+ else { const out = ns.filter((n) => n.p < sweet[0] || n.p > sweet[1]).length / ns.length; if (out > 0.25) add({ level: "warn", area: "range", msg: `${pct(out)} of ${pt.id} (${pt.inst}) sits outside its sweet range ${nameOf(sweet[0])}-${nameOf(sweet[1])}`, fix: "move it toward the sweet range (an octave), or pick a voice that lives there" }); } }
+
+ // ---------------- harmony: cadences
+ const ch = changes(c), cadences: CraftReport["harmony"]["cadences"] = [];
+ for (const s of c.spans) { const inS = ch.filter((h) => h.t < s.b - E), lastH = inS[inS.length - 1]; if (!lastH) continue;
+ const k = c.keyAt(s.b - 0.01), lr = rootAt(c, Math.max(lastH.t, s.a)); let pr = -1;
+ for (let i = inS.length - 2; i >= 0; i--) { const r = rootAt(c, inS[i].t); if (r !== lr) { pr = r; break; } }
+ if (lr < 0) continue; const l = mod12(lr - k.tonic), pv = pr < 0 ? l : mod12(pr - k.tonic);
+ cadences.push({ id: s.id, type: classifyCadence(pv, l), motion: `${DEG[pv]}-${DEG[l]}` }); }
+ const lastCad = cadences[cadences.length - 1];
+ if (!loop && lastCad && !["authentic", "plagal", "modal", "held", "arrival"].includes(lastCad.type)) add({ level: openOk ? "info" : "warn", area: "harmony", msg: `the piece ends ${lastCad.type} (${lastCad.motion}), away from home`, fix: openOk ? "an open ending suits this idiom; keep it if you meant it" : "land the last section on the tonic (V-I, IV-I, bVII-I), or the ending sounds cut off" });
+ if (loop && lastCad && ["authentic", "plagal"].includes(lastCad.type)) add({ level: "info", area: "harmony", msg: `the loop's last section cadences home (${lastCad.motion})`, fix: "a loop should lean back into bar 1 (end on V, IV or a turnaround), not close" });
+ if (cadences.length >= 4 && !cadences.slice(0, -1).some((x) => x.type !== "open" && x.type !== "held")) add({ level: "warn", area: "harmony", msg: "no section before the last ends on a cadence (half, authentic, plagal, deceptive)", fix: "let phrases breathe: end the first sections on V (a question) or a deceptive vi, keep the full close for the end" });
+
+ // ---------------- harmony: voice leading of the chord part (+ the bass and the melody as outer voices)
+ // the chord part: the accompaniment part with the most block chords (3+ notes on one onset; arpeggios and single lines are not voicings)
+ const groups = (pt: (typeof p.parts)[number]) => { const by = new Map<number, number[]>(); for (const n of pt.notes) { const k = Math.round(n.t * 96); by.set(k, [...(by.get(k) ?? []), n.p]); } return [...by].filter(([, ps]) => ps.length >= 2).sort((a, b) => a[0] - b[0]).map(([k, ps]) => ({ t: k / 96, ps: [...new Set(ps)].sort((a, b) => a - b) })); };
+ const cands = p.parts.filter((pt) => pt.role === "accomp" || pt.role === "inner").map((pt) => ({ pt, ev: groups(pt) })), big = (x: (typeof cands)[number]) => x.ev.filter((e) => e.ps.length >= 3).length;
+ const main = cands.sort((a, b) => big(b) - big(a) || b.ev.length - a.ev.length)[0], events = main?.ev ?? [];
+ const blockTop = (t: number) => { let top = -1; for (const x of cands) for (const n of x.pt.notes) if (n.t <= t + E && n.t + n.d > t + E && x.ev.some((e) => Math.abs(e.t - n.t) < 1e-3)) top = Math.max(top, n.p); return top; };
+ // parallel 5ths between any two voices, and parallel octaves between the OUTER voices (bass and melody); octaves inside one
+ // chord part are doubling, which orchestration uses on purpose (Adler 2016), except in a choir, whose voices are independent
+ let parallels = 0, inner = 0, doublings = 0, motions: number[] = []; const parEx: string[] = [], choir = main?.pt.inst === "choir";
+ const par = (a1: number, b1: number, a2: number, b2: number, octaves = true) => { const i1 = mod12(b1 - a1), i2 = mod12(b2 - a2); return (i1 === 7 || (octaves && i1 === 0)) && i1 === i2 && a1 !== a2 && Math.sign(a2 - a1) === Math.sign(b2 - b1); };
+ for (let i = 1; i < events.length; i++) { const A = events[i - 1].ps, B = events[i].ps; if (A.join() === B.join()) continue;
+ if (A.length !== B.length) for (const b of B) motions.push(Math.min(...A.map((a) => Math.abs(b - a))));
+ if (A.length === B.length) { for (let v = 0; v < A.length; v++) { const mv = Math.abs(B[v] - A[v]); motions.push(mv); if (v > 0 && v < A.length - 1 && mv > 7) inner++; }
+ for (let x = 0; x < A.length; x++) for (let y = x + 1; y < A.length; y++) { if (par(A[x], A[y], B[x], B[y], choir)) { parallels++; if (parEx.length < 2) parEx.push(where(c, events[i].t)); } else if (par(A[x], A[y], B[x], B[y])) doublings++; } }
+ const bA = sounding(c, events[i - 1].t + 0.01, ["bass"]), bB = sounding(c, events[i].t + 0.01, ["bass"]), mA = sounding(c, events[i - 1].t + 0.01, ["melody"]), mB = sounding(c, events[i].t + 0.01, ["melody"]);
+ if (bA.length && bB.length && mA.length && mB.length) { const lo1 = Math.min(...bA.map((n) => n.p)), lo2 = Math.min(...bB.map((n) => n.p)), hi1 = Math.max(...mA.map((n) => n.p)), hi2 = Math.max(...mB.map((n) => n.p)); if (par(lo1, hi1, lo2, hi2)) { parallels++; if (parEx.length < 2) parEx.push(`${where(c, events[i].t)} (bass-melody)`); } } }
+ const meanMotion = mean(motions);
+ if (parallels) add({ level: profile.parallels === "forbid" ? "warn" : "info", area: "harmony", msg: `${parallels} parallel 5th/octave move(s) (${parEx.join(", ")})`, fix: profile.parallels === "forbid" ? "in this idiom move the voices in contrary or oblique motion, or hold a common tone" : "fine in this idiom (planing, power chords); keep it if it is the sound you want" });
+ if (inner >= 2) add({ level: profile.parallels === "forbid" ? "warn" : "info", area: "harmony", msg: `${inner} inner-voice jump(s) larger than a 5th between chords`, fix: "revoice: keep common tones, move each inner voice to the nearest chord tone" });
+ if (motions.length >= 8 && meanMotion > 4) add({ level: "info", area: "harmony", msg: `the chord voices move ${meanMotion.toFixed(1)} semitones each on average per change`, fix: "smooth voice leading averages 1-3: invert chords so voices move by step" });
+ // lead under the chords
+ let under = 0; for (const n of mel) { const top = blockTop(n.t + 0.01); if (top >= 0 && n.p < top) under++; }
+ const leadUnder = mel.length ? under / mel.length : 0;
+ if (mel.length >= 8 && leadUnder > 0.3) add({ level: "warn", area: "harmony", msg: `the melody sits under the chord voicing's top note ${pct(leadUnder)} of the time`, fix: "crossed voices mask the tune: voice the chords lower or move the melody up (a tenor-register theme works only in a distinct, louder timbre: see the masking guard)" });
+ // mud: low close intervals (low interval limits)
+ const mud = new Map<string, number>(); const pitched = c.notes.filter((n) => n.role !== "drum");
+ for (const t of [...new Set(pitched.map((n) => Math.round(n.t * 96) / 96))]) { const ps = [...new Set(pitched.filter((n) => n.t <= t + E && n.t + n.d > t + E).map((n) => n.p))].sort((a, b) => a - b);
+ for (let i = 1; i < ps.length; i++) { const lim = LOW_INTERVAL_LIMIT[ps[i] - ps[i - 1]]; if (lim !== undefined && ps[i - 1] < lim - MUD_SLACK) { const k = `${nameOf(ps[i - 1])}+${nameOf(ps[i])}`; if (!mud.has(k)) mud.set(k, t); } } }
+ const mudList = [...mud].map(([notes, t]) => ({ at: where(c, t), notes }));
+ if (mudList.length) add({ level: "warn", area: "harmony", msg: `${mudList.length} close interval(s) below their low limit: ${mudList.slice(0, 3).map((m) => `${m.notes} at ${m.at}`).join("; ")}`, fix: "low down keep only octaves and 5ths (thirds from about C3 up, seconds from about E3 up): spread the voicing or lift the upper note an octave" });
+
+ // ---------------- rhythm
+ const onsetsOf = (f: (n: Note & { inst?: string }) => boolean) => c.notes.filter(f).map((n) => n.t);
+ const syn = { melody: syncopation(mel.map((n) => n.t), bpb, compound).index, bass: syncopation(onsetsOf((n) => n.role === "bass"), bpb, compound).index, drums: syncopation(onsetsOf((n) => n.role === "drum" && /kick|snare/.test((n as { inst?: string }).inst ?? "")), bpb, compound).index };
+ const hasDrums = c.notes.some((n) => n.role === "drum");
+ if (profile.groove && hasDrums && syn.bass + syn.drums < 0.02 && syn.melody < 0.05) add({ level: "warn", area: "rhythm", msg: "no syncopation in the melody, bass or kick/snare", fix: "a groove idiom wants some: push a bass note or a melody note an eighth early (an anticipation) or tie it over the beat; medium syncopation grooves most (Witek et al. 2014)" });
+ if (syn.melody > 1.2) add({ level: "info", area: "rhythm", msg: `the melody is heavily syncopated (${syn.melody.toFixed(2)})`, fix: "if the tune stops sounding anchored, land the motif's first or last note on a beat" });
+ const density = c.spans.map((s) => { const ns = c.notes.filter((n) => n.t >= s.a - E && n.t < s.b - E), ts = new Set(ns.map((n) => Math.round(n.t * 48))); return { id: s.id, perBeat: ts.size / Math.max(E, s.b - s.a), layers: new Set(ns.map((n) => (n as { part?: string }).part)).size }; });
+ if (density.length >= 3) { const d = density.map((x) => x.perBeat), m = mean(d); if (d.every((x) => Math.abs(x - m) <= 0.15 * m) && new Set(density.map((x) => x.layers)).size === 1) add({ level: "warn", area: "rhythm", msg: "every section has the same density and the same layers", fix: "contrast sections: thin one (drums out, one line), build another (more onsets, a new layer); a section that only repeats is dead air" }); }
+ // groove consistency: kick+snare pattern per bar vs the section's commonest bar
+ const gc: number[] = [];
+ for (const s of c.spans) { const bars = new Map<number, Set<number>>();
+ for (const n of c.notes) if (n.role === "drum" && /kick|snare/.test((n as { inst?: string }).inst ?? "") && n.t >= s.a - E && n.t < s.b - E) { const b = Math.floor(n.t / bpb + E); (bars.get(b) ?? bars.set(b, new Set()).get(b)!).add(Math.round((n.t - b * bpb) * 12)); }
+ if (bars.size < 2) continue; const keys = [...bars.values()].map((x) => [...x].sort((a, b) => a - b).join()), cnt = new Map<string, number>(); for (const k of keys) cnt.set(k, (cnt.get(k) ?? 0) + 1);
+ const modeK = [...cnt].sort((a, b) => b[1] - a[1])[0][0], ref = new Set(modeK.split(",").filter(Boolean).map(Number));
+ for (const x of bars.values()) { const inter = [...x].filter((v) => ref.has(v)).length; gc.push(inter / (x.size + ref.size - inter || 1)); } }
+ const grooveConsistency = gc.length ? mean(gc) : null;
+ if (grooveConsistency !== null && grooveConsistency < 0.45) add({ level: "warn", area: "rhythm", msg: `the kick/snare pattern changes almost every bar (consistency ${grooveConsistency.toFixed(2)})`, fix: "a groove is a repeated pattern with small variations: keep the kick and backbeat stable, vary the hats and the fill bar" });
+ const chg = ch.filter((h) => h.t > E), onBeat = chg.filter((h) => metricWeight(h.t, bpb, compound) >= 2).length, cob = chg.length ? onBeat / chg.length : 1;
+ if (chg.length >= 4 && cob < 0.75) add({ level: "warn", area: "rhythm", msg: `${pct(1 - cob)} of chord changes fall between beats`, fix: "change chords on strong beats (an eighth-note anticipation is fine); off-beat changes blur the metre" });
+ // dead air: a section that repeats the previous one note for note in every pitched part
+ const repeated: string[] = [], sig = (s: Span) => c.notes.filter((n) => n.role !== "drum" && n.t >= s.a - E && n.t < s.b - E).map((n) => `${(n as { part?: string }).part}:${Math.round((n.t - s.a) * 48)}:${n.p}:${Math.round(n.d * 48)}`).sort().join("|");
+ for (let i = 1; i < c.spans.length; i++) { const A = c.spans[i - 1], B = c.spans[i]; if (B.b - B.a >= 4 * bpb - E && Math.abs((A.b - A.a) - (B.b - B.a)) < E && sig(A) && sig(A) === sig(B)) repeated.push(B.id); }
+ if (repeated.length) add({ level: "warn", area: "rhythm", msg: `section(s) ${repeated.join(", ")} repeat the previous section note for note`, fix: "vary the repeat: the motif an octave up, a counter line, thinner or fuller layers, a new last bar" });
+
+ // ---------------- tension curve (per bar)
+ const nBars = Math.max(1, Math.ceil(c.end / bpb - E)), melRange = mel.length ? [Math.min(...mel.map((n) => n.p)), Math.max(...mel.map((n) => n.p))] : [60, 72];
+ const raw = Array.from({ length: nBars }, (_, b) => { const a = b * bpb, z = a + bpb, ns = c.notes.filter((n) => n.t >= a - E && n.t < z - E);
+ const h = ch.filter((x) => x.t <= a + E).pop(), k = c.keyAt(a), r = rootAt(c, h ? Math.max(h.t, a) : a), fn = r < 0 ? 0 : ROOT_TENSION[mod12(r - k.tonic)];
+ const pcs = [...new Set(sounding(c, a + 0.01, ["accomp", "inner", "bass", "melody", "color"]).map((n) => mod12(n.p)))]; let ds = 0, pr = 0; for (let i = 0; i < pcs.length; i++) for (let j = i + 1; j < pcs.length; j++) { const ic = Math.min(mod12(pcs[j] - pcs[i]), 12 - mod12(pcs[j] - pcs[i])); ds += IC_DISSONANCE[ic]; pr++; }
+ const mb = mel.filter((n) => n.t >= a - E && n.t < z - E), reg = mb.length ? (mean(mb.map((n) => n.p)) - melRange[0]) / Math.max(1, melRange[1] - melRange[0]) : 0;
+ return { fn, diss: pr ? ds / pr : 0, dens: new Set(ns.map((n) => Math.round(n.t * 48))).size / bpb, reg, loud: ns.length ? mean(ns.map((n) => n.v)) * Math.min(1, new Set(ns.map((n) => (n as { part?: string }).part)).size / 6) : 0 }; });
+ const mx = (f: (x: (typeof raw)[number]) => number) => Math.max(E, ...raw.map(f));
+ const md = mx((x) => x.dens), ml = mx((x) => x.loud);
+ const bars = raw.map((x) => +(0.25 * x.fn + 0.2 * x.diss + 0.25 * (x.dens / md) + 0.15 * x.reg + 0.15 * (x.loud / ml)).toFixed(3));
+ const tsec = c.spans.map((s) => ({ id: s.id, value: +mean(bars.slice(Math.max(0, Math.floor(s.a / bpb + E)), Math.ceil(s.b / bpb - E))).toFixed(2) }));
+ const peakBar = bars.indexOf(Math.max(...bars)), peakAt = (peakBar + 0.5) / nBars;
+ if (tsec.length >= 3) { const vs = tsec.map((x) => x.value), rng = Math.max(...vs) - Math.min(...vs);
+ if (rng < 0.1) add({ level: "warn", area: "tension", msg: `the tension curve is flat (sections span ${rng.toFixed(2)})`, fix: "plan the arc before the notes: rise (denser, higher, leaning chords), a dip before the peak, then release" });
+ const peakS = vs.indexOf(Math.max(...vs));
+ if (!loop && peakS === 0) add({ level: "warn", area: "tension", msg: `the first section (${tsec[0].id}) is the most intense`, fix: "start below the peak so the piece has somewhere to go" });
+ if (!loop && !openOk && vs[vs.length - 1] >= Math.max(...vs) - 1e-9) add({ level: "warn", area: "tension", msg: `the last section (${tsec[tsec.length - 1].id}) is the most intense: no release`, fix: "after the peak, release: fewer layers, home chord, the motif's last word" }); }
+
+ // ---------------- mood fit (MOODS: tables.ts, grounded in Gabrielsson & Lindström 2010)
+ const M = MOODS[moodId], checks: CraftReport["mood"]["checks"] = [];
+ if (M) { const tempo = p.plan.tempo, inR = (x: number, r: [number, number], slack = 0) => x >= r[0] * (1 - slack) && x <= r[1] * (1 + slack);
+ checks.push({ what: "tempo", value: `${tempo}`, want: `${M.tempo[0]}-${M.tempo[1]}`, ok: inR(tempo, M.tempo, 0.1) });
+ const modes = [...new Set(p.plan.sections.map((s) => s.mode))], fam = (m: ModeId) => (MODES[m].intervals.includes(4) ? "major" : MODES[m].intervals.includes(3) ? "minor" : "other");
+ // the major/minor family is the emotion cue (Hevner 1935; Gabrielsson & Lindström 2010); the exact mode is colour, so a mode of the right family passes
+ checks.push({ what: "mode", value: modes.join("/"), want: M.modes.join("/"), ok: modes.some((m) => M.modes.includes(m) || M.modes.some((w) => fam(w) === fam(m) && fam(m) !== "other")) });
+ if (mel.length) { const med = mel.map((n) => n.p).sort((a, b) => a - b)[Math.floor(mel.length / 2)]; checks.push({ what: "melody register", value: nameOf(med), want: `${nameOf(M.register[0])}-${nameOf(M.register[1])}`, ok: med >= M.register[0] - 3 && med <= M.register[1] + 3 }); }
+ // pitched onsets: a hat's 16ths are groove, not the mood's pace of events
+ const allOn = new Set(c.notes.filter((n) => n.role !== "drum").map((n) => Math.round(n.t * 48))).size / Math.max(E, c.end); checks.push({ what: "note onsets/beat", value: allOn.toFixed(2), want: `${M.onsetsPerBeat[0]}-${M.onsetsPerBeat[1]}`, ok: inR(allOn, M.onsetsPerBeat, 0.25) });
+ if (chg.length >= 2) { const hr = (c.end / bpb) / (chg.length + 1); checks.push({ what: "bars per chord", value: hr.toFixed(2), want: `${M.harmonicRhythmBars[0]}-${M.harmonicRhythmBars[1]}`, ok: hr >= M.harmonicRhythmBars[0] / 2 && hr <= M.harmonicRhythmBars[1] * 2 }); }
+ if (o.centroidHz !== undefined && M.centroidHz) checks.push({ what: "brightness (centroid Hz)", value: `${Math.round(o.centroidHz)}`, want: `${M.centroidHz[0]}-${M.centroidHz[1]}`, ok: inR(o.centroidHz, M.centroidHz, 0.2) });
+ const bad = checks.filter((x) => !x.ok);
+ if (bad.length) add({ level: "warn", area: "mood", msg: `for "${moodId}": ${bad.map((x) => `${x.what} ${x.value} (typical ${x.want})`).join(", ")}`, fix: "either change these toward the mood (tempo, mode, register, density are the strongest emotion cues: Gabrielsson & Lindström 2010), or declare the mood you are actually writing" }); }
+
+ const s01 = (xs: number[]) => +Math.max(0, Math.min(1, mean(xs))).toFixed(2);
+ const scores = {
+ melody: s01([recShare, Math.min(1, stepShare / 0.6), Math.min(1, rep.index / 0.5), 1 - Math.max(0, rep.exact - 0.4), phrases.length ? stable / phrases.length : 1, sbct]),
+ harmony: s01([mudList.length ? Math.max(0, 1 - mudList.length / 6) : 1, profile.parallels === "forbid" ? Math.max(0, 1 - parallels / 4) : 1, 1 - leadUnder, meanMotion ? Math.min(1, 3 / meanMotion) : 1]),
+ rhythm: s01([cob, grooveConsistency ?? 1, repeated.length ? 0.5 : 1, profile.groove && hasDrums ? Math.min(1, (syn.bass + syn.drums + syn.melody) / 0.15) : 1]),
+ tension: s01([tsec.length >= 3 ? Math.min(1, (Math.max(...tsec.map((x) => x.value)) - Math.min(...tsec.map((x) => x.value))) / 0.2) : 1, loop || peakAt >= 0.3 ? 1 : 0.5]),
+ mood: checks.length ? +(checks.filter((x) => x.ok).length / checks.length).toFixed(2) : 1,
+ };
+ return {
+ melody: { phrases: phrases.length, contours, leaps, leapsRecovered: rec, stepShare, range: mel.length ? [nameOf(Math.min(...mel.map((n) => n.p))), nameOf(Math.max(...mel.map((n) => n.p)))] : null, repetition: rep.index, development: rep.dev, exactBarCopies: rep.exactBarCopies, stableEnds: phrases.length ? stable / phrases.length : 1, lastNote, climax, strongBeatChordTones: sbct, ncts },
+ harmony: { cadences, parallels, octaveDoublings: doublings, innerJumps: inner, meanMotion, leadUnderChords: leadUnder, mud: mudList },
+ rhythm: { syncopation: syn, density, grooveConsistency, chordChangesOnBeats: cob, repeatedSections: repeated },
+ tension: { sections: tsec, peakAt, bars }, mood: { mood: moodId, checks }, scores, findings: F,
+ };
+};
+
+/** The report as text for tools/music.mjs (check and craft). */
+export const craftText = (r: CraftReport) => {
+ const f2 = (x: number) => x.toFixed(2), spark = "▁▂▃▄▅▆▇█", m = r.melody, h = r.harmony, y = r.rhythm;
+ const o = [`craft melody ${f2(r.scores.melody)} | harmony ${f2(r.scores.harmony)} | rhythm ${f2(r.scores.rhythm)} | tension ${f2(r.scores.tension)} | mood ${f2(r.scores.mood)} (advisory: scores guide revision; only errors fail)`,
+ ` melody ${m.phrases} phrases (${Object.entries(m.contours).map(([k, v]) => `${k} ${v}`).join(", ") || "-"}) | steps ${pct(m.stepShare)} | leaps ${m.leaps}, turned back ${m.leapsRecovered} | range ${m.range ? m.range.join("-") : "-"} | motif returns ${pct(m.repetition)} (exact ${m.development.exact}, sequence ${m.development.sequence}, varied ${m.development.varied}, new ${m.development.new}) | phrase ends on chord tones ${pct(m.stableEnds)} | strong beats on chord tones ${pct(m.strongBeatChordTones)}`,
+ ` climax ${m.climax ? `${m.climax.note} at ${pct(m.climax.at)} (x${m.climax.times})` : "-"} | last note ${m.lastNote ?? "-"} | non-chord tones: ${Object.entries(m.ncts).filter(([, v]) => v).map(([k, v]) => `${k} ${v}`).join(", ") || "none"}`,
+ ` harmony cadences ${h.cadences.map((x) => `${x.id} ${x.type} (${x.motion})`).join(", ") || "-"}`,
+ ` voice motion ${h.meanMotion.toFixed(1)} st/voice | parallel 5ths/8ves ${h.parallels} (octave doublings ${h.octaveDoublings}) | inner jumps ${h.innerJumps} | melody under chords ${pct(h.leadUnderChords)} | mud ${h.mud.length}`,
+ ` rhythm syncopation melody ${f2(y.syncopation.melody)} bass ${f2(y.syncopation.bass)} kick/snare ${f2(y.syncopation.drums)} | groove consistency ${y.grooveConsistency === null ? "-" : f2(y.grooveConsistency)} | chord changes on beats ${pct(y.chordChangesOnBeats)}`,
+ ` density (onsets/beat, layers) ${y.density.map((d) => `${d.id} ${d.perBeat.toFixed(1)}/${d.layers}`).join(" ")}`,
+ ` tension ${r.tension.sections.map((s) => `${s.id} ${spark[Math.min(7, Math.floor(s.value * 8))]}${f2(s.value)}`).join(" ")} | bars ${r.tension.bars.map((v) => spark[Math.min(7, Math.floor(v * 8))]).join("")} | peak at ${pct(r.tension.peakAt)}`,
+ ` mood ${r.mood.mood}: ${r.mood.checks.map((c) => `${c.what} ${c.value} ${c.ok ? "ok" : `(typical ${c.want})`}`).join(" | ")}`];
+ for (const f of r.findings) o.push(`${f.level === "error" ? "ERROR " : f.level === "warn" ? "CRAFT " : "note "} ${f.area}: ${f.msg}${f.fix ? `\n fix: ${f.fix}` : ""}`);
+ return o.join("\n");
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/craftTables.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/craftTables.ts
new file mode 100644
index 0000000..aa90c18
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/craftTables.ts
@@ -0,0 +1,84 @@
+// CRAFT TABLES: the data behind craft.ts, with where each number comes from. Guides, not laws:
+// every threshold is a starting point that craft.ts turns into an advisory, never a silent rewrite.
+// Theory pages: references/music/theory/*.md.
+import type { InstId } from "./plan";
+import type { StyleId } from "./tables";
+
+/**
+ * Low interval limits: the lowest BOTTOM note (MIDI, C4 = 60) at which an interval of n semitones
+ * still sounds clear rather than muddy. The chart circulated in Berklee arranging teaching (e.g.
+ * Pease & Pullig, Modern Jazz Voicings, 2001); the physics is Plomp & Levelt (1965): two partials
+ * inside one critical band (about 100 Hz wide below 500 Hz) roughen, so close intervals low down beat.
+ * Unisons and octaves have no limit. Loose by +-2 semitones: a concert grand gets away with more.
+ */
+export const LOW_INTERVAL_LIMIT: Record<number, number> = {
+ 1: 52 /* m2 E3 */, 2: 51 /* M2 Eb3 */, 3: 48 /* m3 C3 */, 4: 46 /* M3 Bb2 */, 5: 46 /* P4 Bb2 */, 6: 47 /* tritone B2 */,
+ 7: 34 /* P5 Bb1 */, 8: 41 /* m6 F2 */, 9: 41 /* M6 F2 */, 10: 41 /* m7 F2 */, 11: 41 /* M7 F2 */, 13: 40 /* m9 E2 */, 14: 39 /* M9 Eb2 */,
+};
+
+/**
+ * Instrument ranges (MIDI, sounding pitch). `play`: what the instrument can physically play (a note
+ * outside is a real error for an acoustic instrument); `sweet`: where it sounds its best (outside is
+ * a warning). Sources: Adler, The Study of Orchestration (4th ed., 2016); Rimsky-Korsakov, Principles
+ * of Orchestration (1913); maker specs for Rhodes/Wurlitzer/marimba. Synth voices have no physical
+ * limit (`play` null): only the sweet spot is advised.
+ */
+export const INST_RANGE: Partial<Record<InstId, { play: [number, number] | null; sweet: [number, number] }>> = {
+ piano: { play: [21, 108], sweet: [36, 96] },
+ musicBox: { play: null /* combs vary from 18 to 144 teeth */, sweet: [60, 96] },
+ bell: { play: [48, 108], sweet: [60, 98] },
+ celesta: { play: [60, 108], sweet: [72, 103] },
+ marimba: { play: [36, 96], sweet: [45, 88] },
+ vibes: { play: [53, 89], sweet: [53, 86] },
+ glockenspiel: { play: [79, 108], sweet: [79, 103] },
+ harp: { play: [23, 104], sweet: [36, 91] },
+ guitar: { play: [38, 88], sweet: [40, 81] },
+ strings: { play: [28, 103], sweet: [36, 93] },
+ bowedSolo: { play: [36, 103], sweet: [43, 91] },
+ brass: { play: [28, 86], sweet: [40, 79] },
+ woodwind: { play: [50, 98], sweet: [55, 91] },
+ choir: { play: [36, 86], sweet: [43, 79] },
+ organ: { play: [24, 108], sweet: [36, 96] },
+ pipeOrgan: { play: [12, 108], sweet: [24, 96] },
+ timpani: { play: [36, 60], sweet: [38, 57] },
+ bass: { play: [23, 72], sweet: [28, 55] },
+ ePiano: { play: [28, 100], sweet: [40, 91] },
+ wurlitzer: { play: [33, 96], sweet: [40, 88] },
+ sub: { play: null, sweet: [24, 52] },
+ warmPad: { play: null, sweet: [43, 91] },
+ softPluck: { play: null, sweet: [48, 96] },
+ leadSynth: { play: null, sweet: [52, 96] },
+ pulse: { play: null, sweet: [48, 96] },
+ triangle: { play: null, sweet: [28, 76] },
+ fmBell: { play: null, sweet: [55, 103] },
+};
+
+/**
+ * Interval-class dissonance 0..1 from Huron (1994), "Interval-class content of equally tempered
+ * pitch-class sets", Music Perception 11(3): consonance ratings ic1 -1.428, ic2 -0.582, ic3 0.594,
+ * ic4 0.386, ic5 1.240, ic6 -0.453, rescaled so ic5 (fourth/fifth) = 0 and ic1 (semitone) = 1.
+ */
+export const IC_DISSONANCE = [0, 1, 0.683, 0.242, 0.32, 0, 0.635];
+
+/** Harmonic-function tension of a chord root, by semitones above the key's tonic (Lerdahl, Tonal Pitch Space, 2001, simplified: home 0, dominant high, borrowed and chromatic roots in between). */
+export const ROOT_TENSION = [0, 0.7, 0.55, 0.45, 0.35, 0.5, 0.8, 0.8, 0.45, 0.3, 0.5, 0.85];
+
+/** What a style allows. Genre-aware so the checks advise, never impose one idiom on another. */
+export type CraftProfile = {
+ /** parallel 5ths/8ves between voices: "forbid" in common-practice idioms (warn), "allow" where planing and power chords are the idiom (info) */
+ parallels: "forbid" | "allow";
+ /** melodies built from arpeggios and ostinatos: unrecovered leaps are the idiom, not a fault */
+ arpeggioMelody: boolean;
+ /** a groove idiom: expects some syncopation in the bass and drums (Witek et al. 2014: medium syncopation grooves most) */
+ groove: boolean;
+ /** an ending away from home is idiomatic (drones, suspense, ambient washes) */
+ openEnding: boolean;
+};
+const P = (parallels: "forbid" | "allow", arpeggioMelody = false, groove = false, openEnding = false): CraftProfile => ({ parallels, arpeggioMelody, groove, openEnding });
+export const CRAFT_PROFILE: Record<StyleId, CraftProfile> = {
+ musicBox: P("forbid", true), nocturne: P("forbid"), lullaby: P("forbid"), choral: P("forbid"), orchestral: P("forbid"), cinematic: P("forbid"),
+ folk: P("allow"), minimalist: P("allow", true, false, true), ambient: P("allow", false, false, true), suspense: P("allow", false, false, true),
+ jazz: P("allow", false, true), lofi: P("allow", false, true), lofiElectronic: P("allow", false, true), hipHop: P("allow", false, true),
+ house: P("allow", true, true), drive: P("allow", true, true), synthwave: P("allow", true, true), rock: P("allow", false, true),
+ playful: P("allow", false, true), world: P("allow", false, true), chiptune: P("allow", true, true),
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts
index 33e3f37..fe96de7 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts
@@ -13,6 +13,8 @@ export * from "./vocab";
export * from "./vocabTrim";
export * from "./compose";
export * from "./novelty";
+export * from "./craft";
+export * from "./craftTables";
export * from "./calibration";
export * as instruments from "./instruments";
export * from "./sfx";
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/craft.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/craft.test.ts
new file mode 100644
index 0000000..8c13848
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/test/craft.test.ts
@@ -0,0 +1,133 @@
+// CRAFT TESTS (music/craft.ts): every metric on a small good example and a small bad one, so a
+// threshold that drifts or a metric that stops seeing is caught with no render and no human.
+import { craftReport, contourClass, classifyCadence, syncopation, metricWeight, development, type Finding } from "../src/canvas-core/music/craft";
+import { line, type Piece, type Part, type Role, type InstId, type Meter, type Note } from "../src/canvas-core/music/plan";
+import type { StyleId, MoodId } from "../src/canvas-core/music/tables";
+import type { ModeId } from "../src/canvas-core/music/theory";
+
+type P = { id: string; inst: InstId; role: Role; src: string };
+const piece = (o: { style?: StyleId; mood?: MoodId; key?: string; mode?: ModeId; meter?: Meter; tempo?: number; bars: number; parts: P[]; harmony?: [number, string][]; sections?: [string, number][]; loop?: boolean }): Piece => {
+ const meter = o.meter ?? "4/4", bpb = meter === "3/4" ? 3 : meter === "6/8" ? 2 : 4;
+ const parts: Part[] = o.parts.map((x) => ({ id: x.id, inst: x.inst, role: x.role, notes: line(0, x.src, { role: x.role, bpb }) }));
+ let from = 0; const arrangement = (o.sections ?? [["a", o.bars]]).map(([id, bars]) => { const a = { id, kind: id, from, bars }; from += bars; return a; });
+ return { title: "t", seed: 1, tail: 1, parts, harmony: (o.harmony ?? [[0, "I"]]).map(([t, name]) => ({ t, name })), arrangement,
+ plan: { style: o.style ?? "folk", tempo: o.tempo ?? 90, meter, loop: o.loop, sections: [{ id: "a", bars: o.bars, mood: o.mood ?? "calm", key: o.key ?? "C", mode: o.mode ?? "major", melody: ["stepwise"], dyn: [0.6, 0.6] }] } };
+};
+const has = (fs: Finding[], area: string, re: RegExp, level?: Finding["level"]) => fs.some((f) => f.area === area && re.test(f.msg) && (!level || f.level === level));
+const n = (p: number, t: number): Note => ({ p, t, d: 1, v: 0.7, role: "melody" });
+
+export const name = "craft (melody, harmony, rhythm, tension, mood metrics)";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const C = "[C3 E3 G3]:4", G = "[B2 D3 G3]:4", F = "[A2 C3 F3]:4";
+ const bassC = "C2:4", bassG = "G1:4", bassF = "F1:4";
+
+ // ---------------- melody: contour classes (Huron 1996)
+ ok(contourClass([n(60, 0), n(64, 1), n(67, 2), n(64, 3), n(60, 4)]) === "arch", "contour: C E G E C is an arch");
+ ok(contourClass([n(67, 0), n(65, 1), n(64, 2), n(62, 3), n(60, 4)]) === "descending", "contour: G F E D C descends");
+ ok(contourClass([n(60, 0), n(60, 1), n(61, 2), n(60, 3)]) === "level", "contour: a line within a semitone is level");
+
+ // ---------------- melody: leap recovery
+ const leapy = piece({ bars: 4, harmony: [[0, "C"], [4, "G"], [8, "C"], [12, "G"]], parts: [
+ { id: "lead", inst: "piano", role: "melody", src: "C4:1 A4:1 D5:1 G5:1 | C4:1 A4:1 D5:1 G5:1 | C4:1 A4:1 D5:1 G5:1 | C4:1 A4:1 D5:1 G5:1" },
+ { id: "chords", inst: "piano", role: "accomp", src: [C, G, C, G].join(" | ") }, { id: "bass", inst: "bass", role: "bass", src: [bassC, bassG, bassC, bassG].join(" | ") }] });
+ const recovered = piece({ bars: 4, harmony: [[0, "C"], [4, "G"], [8, "C"], [12, "G"]], parts: [
+ { id: "lead", inst: "piano", role: "melody", src: "C4:1 A4:1 G4:1 F4:1 | E4:1 C5:1 B4:1 A4:1 | G4:1 E5:1 D5:1 C5:1 | B4:2 G4:2" },
+ { id: "chords", inst: "piano", role: "accomp", src: [C, G, C, G].join(" | ") }, { id: "bass", inst: "bass", role: "bass", src: [bassC, bassG, bassC, bassG].join(" | ") }] });
+ const rl = craftReport(leapy), rr = craftReport(recovered);
+ ok(has(rl.findings, "melody", /leaps/, "warn"), `leaps that keep climbing warn (${rl.melody.leaps} leaps, ${rl.melody.leapsRecovered} turned back)`);
+ ok(!has(rr.findings, "melody", /leaps/) && rr.melody.leapsRecovered === rr.melody.leaps, "leaps filled in by step pass");
+ ok(rr.melody.stepShare > rl.melody.stepShare, `step share: stepwise line ${rr.melody.stepShare.toFixed(2)} > leapy line ${rl.melody.stepShare.toFixed(2)}`);
+ // arpeggio idiom exemption: the same climb is a note, not a warning, in chiptune
+ ok(has(craftReport({ ...leapy, plan: { ...leapy.plan, style: "chiptune" } }).findings, "melody", /leaps/, "info"), "arpeggio idioms (chiptune) get a note, not a warning");
+
+ // ---------------- melody: motif development (Schoenberg: repetition, sequence, variation)
+ ok(development([n(60, 0), n(62, 1), n(64, 2)], [[n(60, 0), n(62, 1), n(64, 2)]]) === "exact", "development: the same cell is exact");
+ ok(development([n(62, 0), n(64, 1), n(66, 2)], [[n(60, 0), n(62, 1), n(64, 2)]]) === "sequence", "development: the cell a step up is a sequence");
+ ok(development([n(62, 0), n(59, 1), n(64, 2)], [[n(60, 0), n(62, 1), n(64, 2)]]) === "varied", "development: same rhythm, new intervals is varied");
+ ok(development([n(62, 0), n(59, 0.5), n(71, 2.5)], [[n(60, 0), n(62, 1), n(64, 2)]]) === "new", "development: new rhythm and intervals is new");
+ const motif = "E4:.5 G4:.5 A4:1 r:2", seqd = piece({ bars: 4, parts: [{ id: "lead", inst: "piano", role: "melody", src: [motif, "F4:.5 A4:.5 B4:1 r:2", "G4:.5 B4:.5 C5:1 r:2", "E4:.5 G4:.5 C5:1 r:2"].join(" | ") }] });
+ const random = piece({ bars: 4, parts: [{ id: "lead", inst: "piano", role: "melody", src: ["E4:1.5 D5:.5 r:2", "B3:.25 G4:.25 F4:2.5 r:1", "C5:1 A3:1 r:2", "F4:.75 E5:.25 G5:.5 r:2.5"].join(" | ") }] });
+ const same = piece({ bars: 5, parts: [{ id: "lead", inst: "piano", role: "melody", src: Array(5).fill(motif).join(" | ") }] });
+ ok(craftReport(seqd).melody.repetition >= 0.66 && !has(craftReport(seqd).findings, "melody", /bring back|exact copies/), `a developed motif returns (${craftReport(seqd).melody.repetition.toFixed(2)}) without a warning`);
+ ok(has(craftReport(random).findings, "melody", /bring back/), "a line where nothing returns warns");
+ ok(has(craftReport(same).findings, "melody", /exact copies/), "a photocopied motif warns");
+
+ // ---------------- melody: phrase endings, strong beats, climax
+ const ends = (last: string) => piece({ bars: 4, harmony: [[0, "C"], [4, "G"], [8, "F"], [12, "C"]], parts: [
+ { id: "lead", inst: "piano", role: "melody", src: `E4:1 F4:1 G4:1 r:1 | D4:1 C4:1 B3:1 r:1 | C4:1 A3:1 ${last}:1 r:1 | ${last}:1 D4:1 ${last}:1 r:1` },
+ { id: "chords", inst: "piano", role: "accomp", src: [C, G, F, C].join(" | ") }, { id: "bass", inst: "bass", role: "bass", src: [bassC, bassG, bassF, bassC].join(" | ") }] });
+ ok(craftReport(ends("C4")).melody.stableEnds === 1, "phrases ending on chord tones: 100 %");
+ ok(craftReport(ends("B3")).melody.stableEnds < 0.6 && has(craftReport(ends("B3")).findings, "melody", /end on a chord tone/), "phrases ending off the chord warn");
+ ok(has(craftReport(ends("B3")).findings, "melody", /last note/), "a last note off the home triad is named");
+ const peak = (early: boolean) => piece({ bars: 8, parts: [{ id: "lead", inst: "piano", role: "melody", src: Array.from({ length: 8 }, (_, i) => (i === (early ? 0 : 5) ? "C4:.5 D4:.5 E4:.5 A5:.5 G4:1 F4:1" : "C4:.5 D4:.5 E4:.5 F4:.5 E4:1 D4:1")).join(" | ") }] });
+ ok(has(craftReport(peak(true)).findings, "melody", /peaks/), "the climax in the first bar warns");
+ ok(!has(craftReport(peak(false)).findings, "melody", /peaks/) && Math.abs(craftReport(peak(false)).melody.climax!.at - 0.72) < 0.1, `the climax at ${Math.round(craftReport(peak(false)).melody.climax!.at * 100)} % passes`);
+
+ // ---------------- range per instrument
+ const vib = (src: string) => craftReport(piece({ bars: 1, parts: [{ id: "chords", inst: "vibes", role: "accomp", src }] })).findings;
+ ok(has(vib("[C3 E3 G3]:4"), "range", /outside what/, "error"), "vibes at C3 (5 st below F3) is an error");
+ ok(has(vib("[E3 A3 C4]:4"), "range", /outside what/, "warn"), "vibes at E3 (1 st below) is a warning: extended models exist");
+ ok(!vib("[A3 C4 E4]:4").some((f) => f.area === "range"), "vibes in range: no range finding");
+ ok(!craftReport(piece({ bars: 1, parts: [{ id: "bass", inst: "bass", role: "bass", src: "E1:4" }] })).findings.some((f) => f.area === "range"), "a bass on E1 is its home, not out of range");
+
+ // ---------------- harmony: cadences
+ ok(classifyCadence(7, 0) === "authentic" && classifyCadence(5, 0) === "plagal" && classifyCadence(10, 0) === "modal", "cadences: V-I authentic, IV-I plagal, bVII-I modal");
+ ok(classifyCadence(0, 7) === "half" && classifyCadence(7, 9) === "deceptive", "cadences: ending on V is half, V-vi deceptive");
+ const endOn = (fin: [string, string]) => piece({ bars: 4, sections: [["a", 2], ["b", 2]], harmony: [[0, "C"], [4, "F"], [8, "G"], [12, fin[0]]], parts: [
+ { id: "chords", inst: "piano", role: "accomp", src: [C, F, G, fin[1]].join(" | ") }, { id: "bass", inst: "bass", role: "bass", src: [bassC, bassF, bassG, fin[0] === "C" ? bassC : bassG].join(" | ") },
+ { id: "lead", inst: "piano", role: "melody", src: "E4:4 | F4:4 | D4:4 | C4:4" }] });
+ const home = craftReport(endOn(["C", C])), away = craftReport(endOn(["G", G]));
+ ok(home.harmony.cadences.at(-1)!.type === "authentic" && !has(home.findings, "harmony", /ends/), "a piece ending V-I is home");
+ ok(has(away.findings, "harmony", /ends half/, "warn"), "a piece ending on V warns (away from home)");
+ ok(has(craftReport({ ...endOn(["G", G]), plan: { ...endOn(["G", G]).plan, style: "suspense" } }).findings, "harmony", /ends/, "info"), "suspense may end open (a note, not a warning)");
+
+ // ---------------- harmony: voice leading (parallels, doublings, style-aware)
+ const pv = (style: StyleId, b: string) => craftReport(piece({ style, bars: 2, harmony: [[0, "C"], [4, "D"]], parts: [{ id: "chords", inst: "choir", role: "accomp", src: `[C4 G4 E5]:4 | ${b}:4` }] })).findings;
+ ok(has(pv("choral", "[D4 A4 F5]"), "harmony", /parallel/, "warn"), "choral: parallel 5ths C-G to D-A warn");
+ ok(!has(pv("choral", "[B3 G4 D5]"), "harmony", /parallel/), "choral: contrary/oblique motion passes");
+ ok(has(pv("rock", "[D4 A4 F5]"), "harmony", /parallel/, "info"), "rock: the same fifths are the idiom (a note)");
+ const dbl = craftReport(piece({ style: "orchestral", bars: 2, parts: [{ id: "chords", inst: "strings", role: "accomp", src: "[E3 G3 C4 E4]:4 | [F3 A3 C4 F4]:4" }] }));
+ ok(dbl.harmony.parallels === 0 && dbl.harmony.octaveDoublings === 1, "orchestral: an octave-doubled voice moving is doubling, not a parallel");
+ ok(craftReport(piece({ bars: 2, parts: [{ id: "chords", inst: "piano", role: "accomp", src: "[C4 E4 G4]:4 | [C5 E5 G5]:4" }] })).harmony.meanMotion > craftReport(piece({ bars: 2, parts: [{ id: "chords", inst: "piano", role: "accomp", src: "[C4 E4 G4]:4 | [C4 F4 A4]:4" }] })).harmony.meanMotion, "voice motion: a leap of the whole chord moves more than an inversion");
+
+ // ---------------- harmony: mud (low interval limits)
+ const mud = (src: string) => craftReport(piece({ bars: 1, parts: [{ id: "chords", inst: "piano", role: "accomp", src }] })).harmony.mud.length;
+ ok(mud("[C2 E2 G2]:4") > 0, "a close C2-E2 third is mud");
+ ok(mud("[C2 G2 E3]:4") === 0, "the same chord spread (C2 G2 E3) is clear");
+ ok(mud("[C2 C3]:4") === 0, "octaves are never mud");
+
+ // ---------------- harmony: the melody under the chords
+ ok(has(craftReport(piece({ bars: 2, parts: [{ id: "chords", inst: "piano", role: "accomp", src: "[C4 E4 G4 C5]:4 | [C4 E4 G4 C5]:4" }, { id: "lead", inst: "piano", role: "melody", src: "E4:1 F4:1 G4:1 A4:1 | G4:1 F4:1 E4:1 D4:1" }] })).findings, "harmony", /under/), "a melody buried under the chord voicing warns");
+
+ // ---------------- rhythm: metric weights, syncopation
+ ok(metricWeight(0, 4, false) === 4 && metricWeight(2, 4, false) === 3 && metricWeight(1, 4, false) === 2 && metricWeight(0.5, 4, false) === 1 && metricWeight(0.25, 4, false) === 0, "metric weights 4/4: downbeat 4, mid-bar 3, beat 2, 8th 1, 16th 0");
+ ok(metricWeight(1 / 3, 2, true) === 1 && metricWeight(1, 2, true) === 2, "metric weights 6/8: dotted-quarter beats 2, eighths 1");
+ ok(syncopation([0, 1, 2, 3, 4], 4, false).index === 0, "syncopation: quarter notes on the beat = 0");
+ ok(syncopation([0, 1.5, 3, 4], 4, false).index > 0 && syncopation([0, 1.5, 3, 4], 4, false).share > 0.3, "syncopation: an 'and of 2' held over beat 3 counts");
+ const groove = (kick: string) => craftReport(piece({ style: "hipHop", bars: 4, parts: [{ id: "kick", inst: "kick", role: "drum", src: kick }, { id: "bass", inst: "bass", role: "bass", src: "C2:4 | C2:4 | C2:4 | C2:4" }, { id: "lead", inst: "piano", role: "melody", src: "C4:4 | D4:4 | E4:4 | C4:4" }] }));
+ ok(has(groove("C4:1 C4:1 C4:1 C4:1 | C4:1 C4:1 C4:1 C4:1 | C4:1 C4:1 C4:1 C4:1 | C4:1 C4:1 C4:1 C4:1").findings, "rhythm", /no syncopation/), "hip-hop with every hit on the beat: no syncopation warns");
+ ok(!has(groove("C4:1.5 C4:.5 r:2 | C4:1.5 C4:1 C4:1.5 | C4:1.5 C4:.5 r:2 | C4:1.5 C4:1 C4:1.5").findings, "rhythm", /no syncopation/), "an anticipated kick grooves");
+ ok(has(groove("C4:4 | r:.75 C4:.25 C4:3 | C4:.5 C4:.5 C4:.5 C4:2.5 | r:3.5 C4:.5").findings, "rhythm", /changes almost every bar/), "a kick pattern that never repeats warns (groove consistency)");
+ ok(has(craftReport(piece({ bars: 2, harmony: [[0.5, "C"], [2.5, "F"], [4.5, "G"], [6.5, "C"]], parts: [{ id: "chords", inst: "piano", role: "accomp", src: "r:.5 [C3 E3 G3]:2 [A2 C3 F3]:1.5 | r:.5 [B2 D3 G3]:2 [C3 E3 G3]:1.5" }] })).findings, "rhythm", /between beats/), "chord changes on off-beats warn");
+ const rep = craftReport(piece({ bars: 8, sections: [["a", 4], ["b", 4]], parts: [{ id: "lead", inst: "piano", role: "melody", src: Array(8).fill("C4:1 E4:1 G4:1 E4:1").join(" | ") }] }));
+ ok(rep.rhythm.repeatedSections.includes("b") && has(rep.findings, "rhythm", /note for note/), "a section repeating the previous note for note is dead air");
+
+ // ---------------- tension: flat vs shaped
+ const sec = (x: string) => Array(2).fill(x).join(" | ");
+ const flat = craftReport(piece({ bars: 6, sections: [["a", 2], ["b", 2], ["c", 2]], parts: [{ id: "lead", inst: "piano", role: "melody", src: [sec("C4:1 D4:1 E4:1 D4:1"), sec("C4:1 E4:1 D4:1 E4:1"), sec("D4:1 C4:1 E4:1 C4:1")].join(" | ") }, { id: "chords", inst: "piano", role: "accomp", src: Array(6).fill(C).join(" | ") }] }));
+ ok(has(flat.findings, "tension", /flat/), `a piece with no arc warns (sections ${flat.tension.sections.map((s) => s.value).join(", ")})`);
+ const arc = craftReport(piece({ bars: 6, sections: [["a", 2], ["b", 2], ["c", 2]], harmony: [[0, "C"], [8, "G"], [16, "C"]], parts: [
+ { id: "lead", inst: "piano", role: "melody", src: [sec("C4:2 D4:2"), sec("G4:.5 A4:.5 B4:.5 C5:.5 D5:.5 E5:.5 F5:.5 G5:.5"), sec("E4:4")].join(" | ") },
+ { id: "chords", inst: "piano", role: "accomp", src: [C, C, "[B2 D3 F3 G3]:4", "[B2 D3 F3 G3]:4", C, C].join(" | ") }, { id: "bass", inst: "bass", role: "bass", src: [bassC, bassC, "G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5", "G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5 G1:.5", bassC, bassC].join(" | ") }] }));
+ ok(!arc.findings.some((f) => f.area === "tension") && arc.tension.sections[1].value > arc.tension.sections[0].value && arc.tension.sections[1].value > arc.tension.sections[2].value, `rise, peak, release (${arc.tension.sections.map((s) => s.value).join(" < > ")}) passes`);
+
+ // ---------------- mood fit
+ const moody = (tempo: number, mode: ModeId) => craftReport(piece({ mood: "calm", tempo, mode, bars: 2, parts: [{ id: "lead", inst: "piano", role: "melody", src: "E5:1 D5:.5 C5:.5 D5:1 E5:1 | D5:1 C5:.5 D5:.5 E5:1 C5:1" }, { id: "chords", inst: "piano", role: "accomp", src: `${C} | ${C}` }, { id: "bass", inst: "bass", role: "bass", src: "C2:4 | C2:4" }] }));
+ ok(!has(moody(72, "major").findings, "mood", /./), "calm at 72 bpm in major fits");
+ ok(has(moody(150, "major").findings, "mood", /tempo 150/), "calm at 150 bpm warns on tempo");
+ ok(has(moody(72, "phrygian").findings, "mood", /mode phrygian/), "calm in phrygian (minor family) warns on mode");
+ ok(!has(moody(72, "lydian").findings, "mood", /mode/), "calm in lydian (major family) passes: the family is the cue");
+
+ // ---------------- only real errors are errors
+ ok(craftReport(leapy).findings.every((f) => f.level !== "error"), "craft never errors on taste: only impossible ranges are errors");
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs
index d8d316d..5002272 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs
@@ -7,7 +7,8 @@
// returning either); or the name of a shipped demo (listening references, never a film's score).
//
// node tools/music.mjs vocab [style] # the style vocabularies: palette, grooves, harmony, melody, arrangement
-// node tools/music.mjs check <piece> [--fit --seconds N] # everything: key/mode, warnings, master, ghost/reverb/masking guards, stems, novelty
+// node tools/music.mjs check <piece> [--fit --seconds N] # everything: key/mode, warnings, master, ghost/reverb/masking guards, stems, craft, novelty
+// node tools/music.mjs craft <piece> [more ...] [--json] # how it is WRITTEN: melody, harmony, rhythm, tension, mood fit (no render, advisory; errors fail)
// node tools/music.mjs novelty <piece> [more ...] # vs every shipped piece (and pairwise when several); FAILS above the threshold or on a reused fragment
// node tools/music.mjs list # shipped demos and fixtures
// node tools/music.mjs render <piece> <out.wav|out.mp3> [--seconds 45] [--flat] [--tempo 66] [--fit] [--loop] [--stems]
@@ -129,11 +130,19 @@ const main = async () => {
}
if (fail) process.exitCode = 1; return;
}
+ if (cmd === "craft") {
+ let fail = false;
+ for (const ref of args.filter((a) => !a.startsWith("--"))) { const piece = (await getPiece(M, ref)).make(), r = M.craftReport(piece);
+ if (flag("--json")) console.log(JSON.stringify({ piece: ref, ...r }, null, 1)); else console.log(`${ref}\n${M.craftText(r)}`);
+ fail = fail || r.findings.some((f) => f.level === "error"); }
+ if (fail) process.exitCode = 1; return;
+ }
if (cmd === "check") {
const pc = await getPiece(M, args[0]); let piece = pc.make(), tempo = piece.plan.tempo, seconds = val("--seconds", undefined);
if (flag("--fit")) { const f = M.fitScore(piece, seconds); piece = f.piece; tempo = f.tempo; }
const r = piece.plan.loop ? M.renderLoop(piece, SR) : M.renderPiece(piece, SR, { seconds, tempo });
const ok = [report(M, r, piece), printStems(M, piece, tempo, seconds)?.ok !== false];
+ { const cr = M.craftReport(piece, { centroidHz: M.centroid([r.L, r.R], SR).mean }); console.log(M.craftText(cr)); ok.push(!cr.findings.some((f) => f.level === "error")); }
if (!pc.demo) { const fam = [args[0]]; ok.push(printNovelty(M, args[0], M.novelty(piece, M.DEMOS, fam), "shipped pieces")); }
console.log(ok.every(Boolean) ? "CHECK PASS: now a human listens (an mp3 or wav on a page)" : "CHECK FAIL: fix the items above, then run check again");
if (!ok.every(Boolean)) process.exitCode = 1; return;
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/README.md b/plugins/anidoodle/skills/anidoodle/references/music/README.md
index 1bd22ab..0445045 100644
--- a/plugins/anidoodle/skills/anidoodle/references/music/README.md
+++ b/plugins/anidoodle/skills/anidoodle/references/music/README.md
@@ -13,6 +13,9 @@ notes. You compose every note, and nothing is filled in for you. There is no def
Pages:
- [`compose.md`](compose.md): the workflow, the material format, craft, and the never-reuse rule.
+- [`theory/`](theory/README.md): the craft behind it: melody, harmony, rhythm, mood mapping, form and
+ orchestration, sound (psychoacoustics for voicing and mixing). Cited, and measured by
+ `node tools/music.mjs craft`.
- [`styles/vocabularies.md`](styles/vocabularies.md): all 21 style vocabularies, the 15 groove
families and the section kinds. It is generated from the code.
- [`styles/lofi-electronic.md`](styles/lofi-electronic.md): the lo-fi electronic vocabulary in
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/compose.md b/plugins/anidoodle/skills/anidoodle/references/music/compose.md
index 454e570..c3c4656 100644
--- a/plugins/anidoodle/skills/anidoodle/references/music/compose.md
+++ b/plugins/anidoodle/skills/anidoodle/references/music/compose.md
@@ -53,8 +53,18 @@ what to compose. The engine then performs, synthesizes, mixes and masters, deter
| `tension` | pad detune wider, string attacks shorter, lead decays shorter |
| `space` | reverb sends, delay mix, pad release |
- Controls change the sound only. Harmonic tension is yours to write (step 3).
-3. **Compose the harmony.** Work inside the style's harmony language: its modes, chord qualities,
+ Controls change the sound only. Harmonic tension is yours to write (step 4). To choose the tempo,
+ mode, register and density that make a feeling read, see [theory/mood.md](theory/mood.md): tempo
+ and mode are the strongest cues, and several cues pointing the same way make the mood unmistakable.
+3. **Sketch the arc and the motif before any chord.** Write three things down:
+ - **The tension curve.** One number 0..1 per section: it rises, dips just before the peak (a breath
+ or breakdown), peaks on the picture's key frame, then releases. This becomes each section's
+ `energy`, its layers and its harmony (leaning chords before home).
+ - **The climax.** The bar, the highest note of the piece, and the chord under it (home, full layers).
+ - **The motif.** Its rhythm (which beats it avoids, where the long note sits), its contour (one leap,
+ then steps back), and how it will develop across the form: stated, sequenced, fragmented in the
+ build, augmented at the climax, last word at the end ([theory/melody.md](theory/melody.md)).
+4. **Compose the harmony.** Work inside the style's harmony language: its modes, chord qualities,
tendencies and voicing rule. Decide the key and mode from the mood, not from habit.
- Write a progression **for this brief**. Choose its length (2, 3, 4, 5, 6 or 8 bars) and its
harmonic rhythm (one chord per bar, two per bar, or one per two bars) on purpose.
@@ -63,8 +73,11 @@ what to compose. The engine then performs, synthesizes, mixes and masters, deter
- Write each chord's bass line (one bar) in the style's bass idiom: held root, root and fifth,
walking, offbeat 8ths, a syncopated 808 figure. Make the rhythm YOURS.
- **Tension and release as a curve.** Stable (tonic), moving away (subdominant, relative,
- borrowed), leaning (dominant, suspension, pedal), home. Put home on the picture's key beat.
-4. **Compose the motif(s).** A motif is 2-5 notes with its own rhythm. Invent the rhythm first:
+ borrowed), leaning (dominant, suspension, pedal), home. Put home on the picture's key beat. End
+ inner sections on half or deceptive cadences, and save the full close for the end
+ ([theory/harmony.md](theory/harmony.md)).
+ - **Spread low, close high.** No close intervals below about C3 ([theory/sound.md](theory/sound.md)).
+5. **Compose the motif(s).** A motif is 2-5 notes with its own rhythm. Invent the rhythm first:
- Which beats does it avoid?
- Does it start on an upbeat?
- Where is the long note?
@@ -80,13 +93,15 @@ what to compose. The engine then performs, synthesizes, mixes and masters, deter
- put it in the bass for menace, or high and quiet at the close.
The phrase's high point goes in its second half. A phrase is 2 or 4 bars; a period is two phrases
- (question, answer). The line must respect the style's range and density.
-5. **Choose or write the groove.** Pick a family from the style's list (`bounce`, `trap`,
+ (question, answer). The line must respect the style's range and density. Put chord tones on strong
+ beats, and put the feeling in appoggiaturas and suspensions that resolve by step.
+6. **Choose or write the groove.** Pick a family from the style's list (`bounce`, `trap`,
`brushes`, `hand`, ...). Set `density` 0..1, `variation` 0..1 and `fill` (a fill on a section's
last bar). The seed varies every bar, so no two pieces share a loop. You can also write the drum
bars yourself as notation, one or more bars per lane: `kick`, `snare`, `ghost`, `hat`, `perc`.
- Use a second groove for contrast (`half`, `build`).
-6. **Write the form.** Sections are `{ kind, bars, harmony, lead, counter, arp, groove, bass,
+ Use a second groove for contrast (`half`, `build`). Keep the kick and backbeat stable, and syncopate on
+ top of them ([theory/rhythm.md](theory/rhythm.md)).
+7. **Write the form.** Sections are `{ kind, bars, harmony, lead, counter, arp, groove, bass,
chordVel, energy, repeat, stretch }`.
- The **kind** sets which layers may sound: intro, verse, groove, hook, build, half, breakdown,
drop, bridge, swell, breath, outro. See the arrangement grammar in vocabularies.md.
@@ -95,7 +110,33 @@ what to compose. The engine then performs, synthesizes, mixes and masters, deter
seconds, and at 30 fps a beat is `1800 / bpm` frames.
- Mark one section `stretch: true`: a film fit repeats or drops it to reach the exact length and
still end on your outro.
-7. **Check, render, listen:**
+ - Song and cue forms, builds, and orchestration slots: [theory/form.md](theory/form.md).
+8. **Revise with craft, before you render.** `craft` reads the notes in milliseconds:
+ ```
+ node tools/music.mjs craft <file>.ts#<export>
+ ```
+ - It prints scores (0..1) for melody, harmony, rhythm, tension and mood, the tension curve per
+ section and per bar, and each section's cadence.
+ - Each `CRAFT` line names what it saw, where (bar and beat), and a fix.
+ - Loop: read the findings, revise the notes, run `craft` again. Stop when every remaining
+ finding is one you chose on purpose (an open ending for suspense, parallel fifths in rock). Say
+ which ones in your note to the person.
+ - Compare the printed tension curve with your sketch from step 3. If the peak is not where you
+ planned it, the arrangement is wrong, not the sketch.
+
+ | `craft` says | Usual fix |
+ |---|---|
+ | leaps keep going the same way | turn back by step after a leap |
+ | nothing comes back / exact copies | develop one motif: sequence, vary the last interval, fragment |
+ | phrases don't end on chord tones | land answers on 1, 3 or 5; keep one open question |
+ | the melody peaks early | move the highest note to the second half, on the key frame |
+ | parallel 5ths (common-practice idiom) | contrary motion; hold the common tone |
+ | close intervals below their low limit | spread the voicing: 1-5-3', or lift the upper note an octave |
+ | melody under the chords | voice the chords lower, or the melody higher |
+ | no syncopation (groove idiom) | anticipate a bass or melody note by an eighth |
+ | flat tension curve / no release | change layers, register and harmony by section; release after the peak |
+ | mood cues (tempo, mode, register, density) | move the cue toward the mood, or declare the mood you wrote |
+9. **Check, render, listen:**
```
node tools/music.mjs check <file>.ts#<export> [--fit --seconds 62] # EVERYTHING, must PASS (below)
node tools/music.mjs render <file>.ts#<export> out.mp3 --stems # the file, plus the same report
@@ -108,6 +149,7 @@ what to compose. The engine then performs, synthesizes, mixes and masters, deter
gain short;
- the **ghost, reverb and masking guards**;
- the stems;
+ - craft (the step-8 report, with brightness measured from the render; only an unplayable range fails);
- novelty.
It exits non-zero on any failure. `render` prints the same report (stems with `--stems`), except
@@ -197,30 +239,29 @@ mid-bar writes its rest, `C2:3 r:1`, never a silent gap):
- `@VEL` scales the line's velocity (0..1).
- In a hand-written piece, a one-bar sting on any beat says so: `line(t, "G6:1", { ..., hit: true })`.
-## Craft notes (what makes it good, not just valid)
-
-- **One idea, developed.** Most memorable scores have one motif, heard 6-12 times, never the same
- way twice. Two motifs at most; the second answers or contrasts the first.
-- **Contrast by section:**
- - change the density (layers in and out);
- - change the register (the motif up an octave);
- - change the harmonic rhythm (twice as fast into a cadence);
- - change the groove (half-time).
-
- A section that only repeats the previous one is dead air.
-- **Cadences on picture beats.** The strongest arrival (home chord, full layers, the motif's peak)
- goes on the most important frame. The claim, the reveal and the logo each get a structural
- downbeat. Use a breakdown or a breath (drums out, one bar of silence) right before it.
-- **Tension curve.** Plan energy 0..1 per section before writing notes: rise, a dip before the peak,
- then release. Match it with density, register and harmony (leaning chords before home).
-- **Endings.** End on a phrase, never on the last frame by accident:
- - a held home chord with the motif's last word;
- - a button (a short tutti hit);
- - an unresolved hold (suspense only).
-- **Mood fit.** Match the mode, tempo and brightness to the words. If the listener names a different
- emotion from the one you declared, the choice was wrong, not the listener.
-- **Breadth.** Across projects, vary the meter, the harmonic rhythm, the groove family and the form
- length. Two scores for two products should not be siblings.
+## What makes it beautiful (check before you call it done)
+
+- [ ] **One idea, developed.** One motif, heard 6-12 times, never the same way twice. A second idea
+ answers or contrasts it.
+- [ ] **A line you could sing.** Mostly steps, leaps that turn back, arches, and one high point per
+ phrase group in its second half.
+- [ ] **Questions and answers.** Phrases in 2s and 4s. Questions end open, answers end home.
+- [ ] **Feeling in the dissonance.** Chord tones on the beats. An appoggiatura or suspension where
+ the picture needs an ache, resolved down by step.
+- [ ] **Harmony that moves smoothly.** Common tones held, voices by step, the bass contrary to the
+ tune, the low end spread.
+- [ ] **A groove that breathes.** An anchored kick and backbeat, syncopation on top, rests in the
+ melody, a fill only at section ends.
+- [ ] **An arc.** Contrast by section in density, register, harmonic rhythm and groove. A dip
+ before the peak, the peak on the key frame, then release.
+- [ ] **Cadences on picture beats.** The claim, the reveal and the logo each get a structural
+ downbeat.
+- [ ] **An ending on a phrase:** a held home chord with the motif's last word, a button, or (suspense
+ only) an unresolved hold.
+- [ ] **Mood cues aligned.** Tempo, mode, register, density, articulation and brightness all point
+ at the words. If a listener names a different emotion, the choice was wrong, not the listener.
+- [ ] **Breadth.** Across projects, vary the meter, harmonic rhythm, groove family and form length.
+ Two scores for two products should not be siblings.
## What checks what
@@ -233,6 +274,7 @@ mid-bar writes its rest, `C2:3 r:1`, never a silent gap):
| reverb guard | `check`, `render` | the late tail sits within 10 dB of the dry sound |
| masking guard | `check`, `render` | the melody doesn't clear the other parts in 500 Hz-4 kHz |
| stems | `check`, `render --stems`, `stems` | a part is more than 3 dB off target (lead: up to +6 dB allowed); advisory for uncalibrated styles |
+| craft | `craft`, `check` | (advisory scores and fixes) melody, harmony, rhythm, tension, mood fit; fails only on a note an acoustic instrument cannot play |
| novelty | `check`, `novelty` | similarity above 0.5 to a shipped piece (or to each other), or a reused 6-note melody fragment |
`tools/music-unit.mjs` keeps the engine honest: determinism, no defaults, every vocabulary renders.
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/theory/README.md b/plugins/anidoodle/skills/anidoodle/references/music/theory/README.md
new file mode 100644
index 0000000..ac0ce12
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/references/music/theory/README.md
@@ -0,0 +1,19 @@
+# Music theory for the composer
+
+These pages are the craft behind [../compose.md](../compose.md): what makes a line beautiful, a
+progression move, a groove feel good and a mood read true. Each page cites its sources and ends in
+rules you can apply. Examples use scale degrees and shapes, never tunes to copy.
+
+| Page | Read it when |
+|---|---|
+| [melody.md](melody.md) | writing the motif and phrases: development, contour, climax, leaps, non-chord tones |
+| [harmony.md](harmony.md) | writing chords and bass: function, cadences, voice leading, modal colour, tension |
+| [rhythm.md](rhythm.md) | writing grooves and lines: metre, syncopation, swing, fills, density |
+| [mood.md](mood.md) | choosing tempo, mode, register and density for a feeling (the research, and the 21-mood table) |
+| [form.md](form.md) | laying out sections: song and cue forms, builds, orchestration slots, counterpoint |
+| [sound.md](sound.md) | voicing and arranging for a clear mix: critical bands, masking, low limits, space |
+
+`node tools/music.mjs craft <score.ts#export>` measures these rules in milliseconds, with no render,
+and `check` prints the same report. Scores run from 0 to 1 and are advisory. Each `CRAFT` line names what
+it saw, where, and a fix. Only a note an acoustic instrument cannot play is an error. The rest is
+yours to judge: a rule broken on purpose is style, and one broken by accident is a fault.
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/theory/form.md b/plugins/anidoodle/skills/anidoodle/references/music/theory/form.md
new file mode 100644
index 0000000..3fdd779
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/references/music/theory/form.md
@@ -0,0 +1,111 @@
+# Form, arrangement, orchestration, counterpoint
+
+## 1. Song forms (and the engine's section kinds)
+
+| Form | Shape | Engine kinds |
+|---|---|---|
+| Verse-chorus | intro, verse, chorus, verse, chorus, bridge, chorus x2, outro | intro, verse, hook, bridge, drop, outro |
+| AABA (32-bar) | A (the tune), A (varied end), B (contrast: new key area), A | verse, verse, bridge, hook |
+| Loop / beat | 4-8 bar loop; layers in and out every 4-8 bars | groove, hook, half, breakdown, drop |
+| Build-drop (EDM, trailer) | intro, build (riser), breath, drop, outro | intro, build, breath, drop, outro |
+| Through-composed cue | motif stated, developed, climax, coda | intro, verse, swell, hook, outro |
+
+- The chorus (hook) holds the **motif's clearest statement**, the fullest layers and the most home
+ harmony.
+- The verse is lighter and leaves room.
+- The bridge goes somewhere new: a borrowed or relative key area, a new rhythm, a thinner texture.
+ Then it **returns**.
+- Return is what makes form. A-B-A satisfies because B made A new (Huron 2006: expectation built,
+ then fulfilled).
+
+## 2. Film cue structure (scoring to picture)
+
+Working film composers structure a cue around **hit points**: the frames where something happens
+(Karlin & Wright 2004; Davis 2010).
+
+1. **Spot the cue.** List the beats with times: the reveal, the claim, the cut, the logo.
+2. **Pick 1-3 sync points** that get a structural downbeat: an arrival, a hit, or a change of layer.
+ Don't hit everything. Hitting every cut is "mickey-mousing", fine for comedy and tiring elsewhere.
+3. **Tempo from the picture.** Choose a bpm so the key hits land on downbeats (the engine's `fitScore`
+ and `stretch` help). A bar lasts `beatsPerBar x 60 / bpm` seconds.
+4. **Shape:**
+ - establish (the motif, low density);
+ - develop (sequence, rising harmony);
+ - a breath (one bar of near-silence);
+ - the peak on the key frame (the climax note, full layers, home chord);
+ - release;
+ - a button or tail.
+5. **Stingers:** a one-bar hit on a sudden picture event, placed off the grid (`hit: true`).
+6. **Leave dialogue space.** Under a voice, thin the 1-4 kHz band. Keep the lead low or tacet and let the
+ chords carry the harmony.
+
+## 3. Builds and releases
+
+- **Build** with 4-8 bars of rising density, rising register and rising harmonic rhythm (twice as fast
+ into the cadence). Use a dominant pedal or a sus chord, fragments of the motif, and a crescendo. End
+ on a lean (V, sus4, a breath), never on home.
+- **Release:** land on home, on the downbeat, with the most layers, the motif augmented or in full, and
+ the climax note.
+- **Before the peak, a dip:** a breakdown, a breath or a drum drop-out. Contrast makes the landing
+ (the tension curve in [harmony.md](harmony.md), and `craft`'s tension line).
+- **Endings:**
+ - a held home chord with the motif's last word;
+ - a button (a short tutti hit on 1);
+ - a fade only for loops;
+ - an open hold only for suspense.
+
+## 4. Orchestration: registers and frequency slots
+
+Every instrument owns a register. Two parts in the same register fight (masking, see
+[sound.md](sound.md)). Arrange by giving each part its slot:
+
+| Slot | Range (fundamentals) | Who owns it | Rule |
+|---|---|---|---|
+| Sub | 30-60 Hz (B0-B1) | kick body, 808/sub bass | one owner at a time; mono |
+| Bass | 60-250 Hz (B1-B3) | bass, cello/contrabass, piano left hand, tuba | the root; open 5ths and octaves only |
+| Low-mid | 250-500 Hz (B3-B4) | chords, pads, guitar body, low brass, male voice | the mud zone: thin it, don't stack it |
+| Mid | 500 Hz-2 kHz (B4-B6) | melody, lead, violins, trumpet, flute, female voice | the lead's home; one lead at a time |
+| Presence | 2-5 kHz (harmonics) | attacks, consonants, snare crack, pick | what makes parts audible; not everything bright |
+| Air | 5-16 kHz | hats, shakers, cymbals, breath, sparkle (celesta, glock) | light touches |
+
+Guidelines:
+
+- **Spacing follows the harmonic series:** wide intervals low, close intervals high (Rimsky-Korsakov
+ 1913; Adler 2016).
+- **Doubling:**
+ - an octave doubling adds weight and brightness;
+ - a unison doubling adds body and chorus;
+ - a melody doubled in the 3rd or 6th sounds sweet (pop, folk);
+ - don't double the leading tone or a chord 7th in classical idioms.
+- **At most 3-4 families at once** outside the climax, each in its slot. Five simultaneous functions
+ is a useful ceiling:
+ 1. foundation (bass and drums);
+ 2. pad (sustained harmony);
+ 3. rhythm (a moving accompaniment);
+ 4. lead;
+ 5. fills and counter.
+
+ (Owsinski 2017, the arrangement elements.)
+- **Timbre as contrast:** move the motif to a new instrument for the second statement. It is new
+ without changing a note.
+
+## 5. Counterpoint basics (a second line that helps)
+
+A counter-melody is a second voice that stays independent (Fux 1725, *Gradus ad Parnassum*; Jeppesen
+1939):
+
+- **Move when the melody holds, hold when it moves** (complementary rhythm). The `counterMelody` guard
+ asks for at most 50 % shared onsets.
+- **Prefer contrary and oblique motion** to the melody. Similar motion into a 5th or octave hides the
+ counter.
+- **Consonances on strong beats** (3rds, 6ths, 5ths, octaves). Dissonances pass by step on weak beats,
+ or are suspensions that resolve down.
+- **Its own register**, a 3rd to a 10th away from the tune, and ideally a different timbre.
+- **Call and response:** the counter answers in the melody's rests. This is the easiest, most
+ idiomatic counterpoint for pop and film.
+
+Sources: Caplin, *Classical Form* (1998); Everett, *The Foundations of Rock* (2009); Karlin & Wright,
+*On the Track* (2nd ed., 2004); Davis, *Complete Guide to Film Scoring* (2nd ed., 2010);
+Rimsky-Korsakov, *Principles of Orchestration* (1913); Adler, *The Study of Orchestration* (4th ed.,
+2016); Owsinski, *The Mixing Engineer's Handbook* (4th ed., 2017); Fux, *Gradus ad Parnassum* (1725);
+Jeppesen, *Counterpoint* (1939); Huron, *Sweet Anticipation* (2006).
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/theory/harmony.md b/plugins/anidoodle/skills/anidoodle/references/music/theory/harmony.md
new file mode 100644
index 0000000..63e645a
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/references/music/theory/harmony.md
@@ -0,0 +1,123 @@
+# Harmony: function, voice leading, colour, tension
+
+Roman numerals are relative to the key (`I ii iii IV V vi vii°` in major, `i ii° III iv v VI VII` in
+minor, `b` = borrowed or lowered). These are idioms, which are vocabulary. A multi-bar progression
+together with its rhythm and groove is a piece, and novelty checks for that. `craft` measures this page
+on the **harmony** line.
+
+## 1. Function: home, away, leaning, home
+
+| Function | Chords (major) | Feels like | Use |
+|---|---|---|---|
+| Tonic (T) | I, vi, iii | home, rest | starts, arrivals, the end |
+| Subdominant / predominant (S) | IV, ii, (bVI, iv borrowed) | moving away, opening | verses, bridges, before the lean |
+| Dominant (D) | V, V7, vii°, (bVII in rock/modal) | leaning, wanting home | the bar before an arrival |
+
+The standard motion is T -> S -> D -> T. Film and pop often skip D (`I bVII IV I`, a plagal or modal
+world) for warmth without the classical "push".
+
+## 2. Cadences: where a phrase breathes
+
+| Cadence | Motion | Effect | `craft` label |
+|---|---|---|---|
+| Authentic | V(7) -> I | full stop, arrival | `authentic` |
+| Plagal | IV -> I (or iv -> I) | "amen", gentle, hymn-like | `plagal` |
+| Modal / backdoor | bVII -> I, bVI -> I, bII -> I | rock, film, epic warmth | `modal` |
+| Half | ... -> V | a question, a comma | `half` |
+| Deceptive | V -> vi (or bVI) | surprise, "not yet", extends a phrase | `deceptive` |
+
+Put half and deceptive cadences inside the piece and the full one at the end. `craft` lists each
+section's ending. It warns when nothing before the last section breathes, and when a non-loop piece ends
+away from home (except where the idiom allows an open ending). **A loop should not cadence home** at its
+end. Lean back into bar 1 instead (end on V, IV or a turnaround).
+
+## 3. Voice leading
+
+Chords are voices moving, not blocks (Aldwell & Schachter 2011; Tymoczko 2011):
+
+- **Hold common tones.** Move every other voice to the **nearest** tone of the next chord. Efficient
+ voice leading averages 1-3 semitones per voice per change (`craft`: "voice motion").
+- **Contrary motion** between the bass and the melody gives independence and strength.
+- **No parallel 5ths or octaves** between independent voices in common-practice idioms: chorale,
+ choir, orchestral, nocturne, lullaby, music box, cinematic. They fuse two voices into one. `craft`
+ warns in these styles and only notes them elsewhere. Parallel 5ths are the **sound** of rock power
+ chords, of planing in jazz, house and lo-fi, and of folk drones. Doubling a line in octaves is
+ orchestration, not a fault (`craft` counts it separately), except in a choir.
+- **Inner voices** move by step or stay. A jump bigger than a 5th in an inner voice is a revoicing
+ mistake.
+- **Tendency tones:** the leading tone (7) rises to 1. The chord 7th falls by step. The suspended 4th
+ falls to 3.
+
+## 4. Voicing and the low end
+
+- **Spread low, close high.** Below about C3, use only octaves and 5ths. Put thirds from about C3 up,
+ and seconds from about E3 up. `craft` flags close intervals under the **low interval limits**
+ (the chart in [sound.md](sound.md) and `craftTables.ts`), because they turn to mud.
+- **The bass owns the root** (or a chosen inversion). The chord part sits above it in its own octave.
+- **Voicings by genre:**
+
+| Idiom | Voicing |
+|---|---|
+| Classical / choral | 4 parts SATB, root doubled, close or open position, 3rd never doubled in V |
+| Jazz, lo-fi, neo-soul | rootless 3-7-9 or 7-3-13 shells between E3 and E4; the bass has the root (Levine 1995) |
+| Pop / piano ballad | root-5-8 in the left hand, triad or add9 in the right |
+| Rock | power chords (1-5-8) in the low guitar; keys add the 3rd higher up |
+| Film / orchestral | open 5ths in the low strings, triads in the violas and violins, octave doublings for weight |
+| Ambient / pad | add9, sus2 and maj7#11 clusters, placed high and wide |
+
+## 5. Colour: modes, borrowed chords, extensions
+
+| Colour | How | Feeling |
+|---|---|---|
+| Lydian `#4` | I -> II (major) | wonder, flight, magic (film "flying" music) |
+| Mixolydian `b7` | I -> bVII -> IV | sunny, rock, easygoing |
+| Dorian `6` | i -> IV (major) | bittersweet, moving forward |
+| Phrygian `b2` | i -> bII | menace, heat |
+| Borrowed iv | I -> iv -> I | a sudden ache, nostalgia (the "minor iv") |
+| bVI and bVII | I -> bVI -> bVII -> I | epic, heroic lift |
+| Chromatic mediants | I -> III or I -> bVI (major triads) | awe, a scene turning, the film "magic" shift (Lehman 2018) |
+| Extensions | maj7, 9, 11, 13 | warmth and sophistication (jazz, lo-fi); triads sound plainer and bolder |
+| Sus chords | sus4 -> 3, sus2 | openness; a lean that resolves |
+
+## 6. Secondary dominants, pedals, modulation
+
+- **Secondary dominant:** V/x before any chord x (`V/vi -> vi`, `V/V -> V`). It adds a leading tone and
+ energy for one chord without leaving the key.
+- **Pedal point:** hold the bass (1 or 5) while the chords change above it. A tonic pedal gives calm or
+ a drone. A dominant pedal gives the build before an arrival.
+- **Modulation:**
+ - pivot chord (smooth, a new chapter);
+ - direct lift up a step or a half step for the last chorus (energy; declare it on the section);
+ - chromatic mediant (cinematic);
+ - relative major and minor (mood change, same notes).
+
+## 7. Harmonic rhythm: pacing
+
+How often the chord changes sets the pace as much as the tempo does.
+
+- 1 chord per 2 bars: calm, spacious, ambient, awe.
+- 1 per bar: song default.
+- 2 per bar: urgency, jazz, a cadence approach.
+
+**Speed the harmonic rhythm up into a cadence** (the sentence's continuation) and slow it down after
+an arrival. Change chords on strong beats. An eighth-note anticipation is fine; changes between beats
+blur the metre (`craft`: "chord changes on beats").
+
+## 8. Tension curve
+
+`craft` draws a per-bar tension curve. It blends:
+
+- the chord's distance from home (Lerdahl 2001, simplified);
+- the sonority's dissonance (Huron 1994 interval-class ratings);
+- density;
+- the melody's register;
+- loudness.
+
+Plan the curve **before** the notes: rise, a dip just before the peak (a breath or breakdown), the
+peak on the key picture moment, then release. It warns on a flat curve, on a first section that is the
+most intense, and on a last section with no release.
+
+Sources: Aldwell & Schachter, *Harmony and Voice Leading* (2011); Kostka & Payne, *Tonal Harmony*
+(8th ed., 2018); Piston, *Harmony* (1941/1987); Tymoczko, *A Geometry of Music* (2011); Levine, *The
+Jazz Theory Book* (1995); Lehman, *Hollywood Harmony* (2018); Lerdahl, *Tonal Pitch Space* (2001);
+Huron, "Interval-class content of equally tempered pitch-class sets", *Music Perception* 11 (1994).
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/theory/melody.md b/plugins/anidoodle/skills/anidoodle/references/music/theory/melody.md
new file mode 100644
index 0000000..55012e3
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/references/music/theory/melody.md
@@ -0,0 +1,122 @@
+# Melody: motif, contour, phrase
+
+Notation on this page: scale degrees (`1 2 3 ... 7`, `b3`, `#4`; `5,` = the octave below, `1'` = the octave
+above), durations in beats after a colon (`3:.5`). These are shapes to apply, never tunes to copy.
+`node tools/music.mjs craft <score>` measures every rule below (the **melody** line and `CRAFT melody:` findings).
+
+## 1. Start from a motif, then develop it
+
+A motif is 2-5 notes with **its own rhythm**. The rhythm is its identity: listeners recognise a
+motif by its rhythm and contour long before its exact intervals (Schoenberg 1967, ch. 2-3; Dowling 1978).
+Write the rhythm first, then the pitches.
+
+| Technique | What changes | Example (from a cell `1:.5 2:.5 3:1`) | Effect |
+|---|---|---|---|
+| Repetition | nothing | the cell again | anchors: the ear learns it |
+| Varied repetition | the last interval or note | `1 2 5` | keeps identity, adds interest |
+| Sequence | the start pitch (same shape) | `2 3 4`, then `3 4 5` | motion, rising energy; max 3 links, then break |
+| Inversion | the direction of each interval | `3 2 1` | an answer, a turn of mood |
+| Retrograde | the order | `3 2 1` with the rhythm reversed | rare, a hidden echo |
+| Augmentation | durations x2 | `1:1 2:1 3:2` | weight, arrival, the climax or the end |
+| Diminution | durations /2 | `1:.25 2:.25 3:.5` | urgency, a build |
+| Fragmentation | keep 2-3 notes, repeat them | `2 3, 2 3, 2 3` | the build before a peak |
+| Displacement | start an eighth later | `r:.5 1 2 3` | syncopation, groove, surprise |
+| Reharmonisation | the chord under it | same notes over vi instead of I | new colour, same tune |
+
+A score that works usually has **one** idea heard 6-12 times, never the same way twice, and at most a
+second idea that answers or contrasts it. `craft` reports how each phrase (or bar) relates to earlier
+ones: `exact`, `sequence`, `varied`, `new`. Aim for most phrases to return (`motif returns` >= 50 %) and
+few to be exact copies (<= 60 %; loop idioms like lo-fi and house may repeat more).
+
+## 2. Phrase and period
+
+- A **phrase** is 2 or 4 bars and ends with a cadence, a long note or a rest (Caplin 1998).
+- A **period** is two phrases: the antecedent (question) ends open, on 2, 5 or 7 over V; the
+ consequent (answer) starts the same way and ends closed, on 1 over I.
+- A **sentence** is 2 + 2 + 4: the idea, the idea again (varied or sequenced), then a continuation that
+ fragments it and speeds up the harmony into the cadence (Schoenberg 1967; Caplin 1998).
+- Question/answer between instruments is the same device: the lead asks, the counter answers
+ within one bar.
+
+## 3. Contour and climax
+
+- **Arch.** Across thousands of folk songs, the commonest phrase shape rises then falls (Huron 1996).
+ Descending phrases come second; phrases also drift down at their ends ("late-phrase declination",
+ Huron 2006).
+- **One high point per phrase group**, in the second half, often about two thirds in. The highest
+ note of the whole piece is its climax: put it on the picture's key moment, and don't reuse it
+ casually. `craft` warns when the piece peaks in its first 30 % or repeats the top note often.
+- Vary contours between phrases: a question that rises, an answer that falls.
+- In minor-key themes, lines sit lower and move in smaller intervals than in major ones (Huron 2008).
+ That is part of why they sound sad, so use it on purpose.
+
+## 4. Steps, leaps and recovery
+
+- **Mostly steps.** Small intervals dominate melodies across cultures (Vos & Troost 1989; Huron
+ 2006, "pitch proximity"). Singable tunes are roughly 60-80 % steps.
+- **A leap is an event.** Use a 4th or more to mark the motif's head or to reach the high point.
+- **Recover from leaps.** After a leap, change direction, preferably by step, to fill the gap. This
+ is statistically real ("post-skip reversal") and partly regression to the middle of the range
+ (von Hippel & Huron 2000). `craft` counts leaps that keep going the same way.
+- **Exemptions:** arpeggiating the current chord (a fanfare `1 3 5 1'`), and arpeggio or ostinato
+ idioms (music box, chiptune, synthwave, house).
+- **Avoid:** two leaps the same way that don't outline a chord; augmented 2nds and tritone leaps
+ (except as a deliberate colour); leaps over an octave in anything meant to sound sung.
+
+## 5. Range and tessitura
+
+- Keep one phrase within about an octave. Keep the whole tune within a 10th to a 12th unless the
+ instrument is built for more (piano, harp, synth).
+- Keep each part in its instrument's sweet range. `craft` checks the table in `craftTables.ts`
+ (after Adler 2016): a note outside what the instrument can physically play is the one craft error.
+- The melody sits **above** the chord voicing. A melody under the chords' top note is masked unless it
+ is louder and a different timbre (a tenor-register theme).
+
+## 6. Rhythm and melody together
+
+- Put the motif's long note where the meaning is: on the downbeat for arrival, or on a weak beat
+ (syncopated) for lift.
+- Start motifs off the downbeat (an upbeat or pickup) for forward motion. Start on it for weight.
+- Leave rests. A melody that never breathes can't phrase, and echo effects need the gaps.
+- Rhythmic contrast between phrases matters as much as pitch contrast. Change one, keep the other.
+
+## 7. Non-chord tones: where the feeling is
+
+On strong beats, use chord tones (`craft`: "strong beats on chord tones"; below 50 % the tune fights the
+harmony). Dissonance belongs in these shapes, each with its own effect (Aldwell & Schachter 2011, ch.
+9-10; Huron 2006 on tension and resolution):
+
+| Type | Shape | Effect |
+|---|---|---|
+| Passing | step, step, same direction, weak beat | flow, smoothness |
+| Neighbour | step away and back | ornament, gentle motion |
+| Appoggiatura | leap INTO the dissonance on a strong beat, resolve by step the other way | longing, the "sigh": strongest emotional pull |
+| Suspension | a note held from the previous chord, resolving down by step (4-3, 9-8, 7-6) | ache, tenderness, delayed release |
+| Anticipation | the next chord's note arrives early | eagerness, pop and jazz lift |
+| Escape | step in, leap out | a flick, playfulness |
+
+Outside common-practice idioms the added 6th and 9th count as colour tones, not dissonances (Levine 1995).
+
+## 8. Phrase endings
+
+- Answers end on 1, 3 or 5 over a stable chord. Questions end on 2, 5 or 7 (over V) or on a colour tone.
+- `craft` reports the share of phrases ending on chord tones and names a last note off the home triad.
+ An open ending is allowed where the mood asks for it (suspense, ambient, curious), and craft says so.
+
+## Checklist
+
+- [ ] One motif, rhythm first, heard 6-12 times, developed (sequence, inversion, fragmentation, augmentation).
+- [ ] Phrases in 2s and 4s. Questions end open, answers end home.
+- [ ] Arches. One climax, in the second half, on the key picture beat.
+- [ ] Mostly steps. Leaps turn back.
+- [ ] Chord tones on the beats. Appoggiaturas and suspensions where you want feeling.
+- [ ] Every part in its sweet range. The tune sits above the chords.
+
+Sources: Schoenberg, *Fundamentals of Musical Composition* (1967); Caplin, *Classical Form* (1998);
+Huron, "The Melodic Arch in Western Folksongs", *Computing in Musicology* 10 (1996); Huron, *Sweet
+Anticipation* (2006); Huron, "A comparison of average pitch height and interval size in major- and
+minor-key themes", *Empirical Musicology Review* 3 (2008); von Hippel & Huron, "Why do skips precede
+reversals?", *Music Perception* 18 (2000); Vos & Troost, "Ascending and descending melodic intervals",
+*Music Perception* 6 (1989); Dowling, "Scale and contour", *Psychological Review* 85 (1978);
+Aldwell & Schachter, *Harmony and Voice Leading* (4th ed., 2011); Levine, *The Jazz Theory Book*
+(1995); Adler, *The Study of Orchestration* (4th ed., 2016).
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/theory/mood.md b/plugins/anidoodle/skills/anidoodle/references/music/theory/mood.md
new file mode 100644
index 0000000..3f8a14c
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/references/music/theory/mood.md
@@ -0,0 +1,88 @@
+# Mood mapping: from a feeling to numbers
+
+Listeners agree on the emotion a piece *expresses* well above chance, and they agree because of a
+small set of structural cues. Those cues combine additively and redundantly: no single cue decides,
+and several pointing the same way make the emotion unmistakable (Juslin 2001, the lens model;
+Gabrielsson & Lindström 2010; Juslin & Laukka 2003). Composing a mood means aligning the cues.
+`craft`'s **mood** line checks tempo, mode family, melody register, note density, harmonic rhythm and
+(in `check`) brightness against the row for your declared mood (`tables.ts` `MOODS`).
+
+## 1. The cues, strongest first (Gabrielsson & Lindström 2010, summary of ~100 studies)
+
+| Cue | Toward happy / energetic | Toward sad / calm | Toward fear / anger |
+|---|---|---|---|
+| Tempo | fast | slow | fast (anger) or irregular (fear) |
+| Mode | major | minor | minor, chromatic, atonal |
+| Loudness | loud-moderate | soft | loud (anger), soft with big swings (fear) |
+| Register (pitch height) | high | low | low rumble or extreme high |
+| Harmony | simple, consonant | consonant or mildly dissonant | dissonant, clusters, tritones |
+| Articulation | staccato, detached | legato | sharp attacks (anger), tremolo (fear) |
+| Rhythm | regular, flowing, dotted and bouncy | regular, slow, sparse | complex, irregular, ostinato |
+| Timbre | bright, few low partials | dark, soft attacks | sharp, harsh, rough |
+| Intervals and contour | large, rising | small, falling | large jumps, chromatic steps |
+
+Also useful:
+
+- Mode and tempo alone swing happy/sad judgments strongly, with tempo usually the stronger
+ (Hevner 1935, 1937; Gagnon & Peretz 2003).
+- Arousal (calm to excited) follows tempo, loudness and density. Valence (negative to positive)
+ follows mode and consonance (Russell 1980; Schubert 2004; Eerola & Vuoskoski 2011, on film music).
+- Minor-key themes also use lower pitch and smaller intervals, like sad speech (Huron 2008).
+
+## 2. Mood table (the engine's 21 moods)
+
+Tempo, mode and register (the melody's median, MIDI note name) are the rows `craft` measures. The
+other columns are the craft to apply. "Density" is pitched note onsets per beat.
+
+| Mood | Tempo | Mode / harmony | Register | Density | Articulation | Orchestration | Dynamics |
+|---|---|---|---|---|---|---|---|
+| joy | 110-150 | major, mixolydian, pentatonic; triads, I-IV-V, bright 6ths | C5-C7 | 2-4 | staccato, bouncy dotted rhythms | mallets, plucks, music box, piano high | mf-f, steady |
+| playful | 120-160 | major, blues; quick chord changes, chromatic passing | C4-F#6 | 2-4 | staccato, rests, stops | pizzicato, mallets, woodwinds, bass hops | mf, sudden p/f |
+| tender | 60-80 | major, lydian; add9, suspensions resolving | E4-C6 | 1-2 | legato, soft attacks | piano, harp, strings, warm pad | p-mp, small swells |
+| wistful | 70-95 | dorian, major with borrowed iv | E4-D6 | 1.5-3 | legato, sighing appoggiaturas | piano, strings, music box | p-mf |
+| melancholy | 50-72 | aeolian, harmonic minor; descending bass, iv, VI | G3-G#5 | 0.75-1.5 | legato, long notes | piano low-mid, cello, strings | p-mp, long swells |
+| hopeful | 80-110 | major, melodic minor; rising sequences, IV-V-vi-I lift | C4-E6 | 1.5-3 | legato to detached | piano, strings, bells | mp rising to f |
+| curious | 80-110 | dorian, lydian, whole-tone colour | C4-C6 | 1-2 | light staccato, pizzicato | plucks, celesta, bells | p-mp |
+| tension | 90-130 | harmonic minor, phrygian; pedals, clusters, b2 | C3-C5 | 2-4 | ostinato, short, tremolo | low strings, pulse, drums | build p to f |
+| dread | 50-80 | phrygian, aeolian, locrian colour; drones, tritones | C2-C4 | 0.5-1.5 | long, slow attacks | low bowed, sub, dark piano | pp-mp, sudden f |
+| awe | 60-90 | lydian, major; chromatic mediants, open 5ths | C5-E7 | 1-3 | long, legato, swells | strings high, choir, bells, harp | p to ff over 4-8 bars |
+| triumph | 100-140 | major (or minor turning major); bVI-bVII-I | C4-F#6 | 3-6 | marcato, accents | brass, strings, drums, organ | f-ff |
+| drive | 110-140 | aeolian, dorian, mixolydian; riff harmony, pedal | C4-D6 | 4-8 | short, tight, 16ths | drums, bass, plucks, arps | f, compressed |
+| calm | 60-90 | mixolydian, pentatonic, major; slow harmonic rhythm | C4-C6 | 1-2 | legato, soft | guitar, pad, bells | p-mp, flat |
+| nostalgic | 70-95 | major with maj7 and borrowed iv | C4-C6 | 1.5-3 | relaxed, swung | e-piano, soft drums, bass | mp |
+| romantic | 60-85 | major, aeolian; suspensions, secondary dominants | C4-E6 | 1-2.5 | legato, rubato | piano, strings | p-f waves |
+| anger | 120-170 | phrygian, aeolian; power chords, dissonance | E2-C5 | 3-8 | hard accents | drums, distorted bass, brass | ff |
+| eerie | 50-90 | whole-tone, locrian, phrygian; clusters, no cadence | C3-C7 | 0.25-1 | tremolo, harmonics, glissandi | bowed, choir, celesta | pp, sudden |
+| mischief | 100-150 | blues, dorian, whole-tone; chromatic neighbours | G3-F#6 | 1.5-3 | staccato, rests, slides | woodwinds, pizzicato, mallets | p-mf, sneaky |
+| heroic | 90-130 | major, mixolydian, dorian; I-bVII-IV, rising 4ths and 5ths | G3-C6 | 1-3 | marcato, dotted | brass, strings, timpani, choir | f |
+| sensual | 65-95 | dorian, aeolian; 9ths and 11ths | G3-G#5 | 0.75-2 | legato, laid back | e-piano, bass, sax-like woodwind | mp |
+| grief | 40-62 | aeolian, harmonic minor; slow descending lines, suspensions | C3-E5 | 0.5-1 | long, legato | solo bowed, strings, piano, choir | pp-mf |
+
+Tempo and register numbers are the engine's starting rows, set from the research above and from
+listening. Where you disagree with a row for a brief, **write the brief's mood** and say why. `craft`
+only advises. The mode check passes any mode of the right family (major-third or minor-third modes),
+because the family is the emotional cue and the exact mode is colour.
+
+## 3. Use cases
+
+| Use | Length | Form | Notes |
+|---|---|---|---|
+| Product launch film | 30-60 s | intro, build, drop on the reveal, button | one motif, the climax on the logo or claim, a clean ending |
+| Explainer | 60-120 s | a steady groove bed, low melody density | leave the voice's band free (1-4 kHz): lead sparse and low-mid |
+| Site / app loop | 20-60 s | 4 or 8 bar loop, no cadence home at the end | low arousal, no sharp accents, seamless |
+| Game menu / trailer | 15-60 s | ostinato + motif, stingers on hits | heroic or playful, strong hook in 2 bars |
+| Ad (15-30 s) | 15-30 s | hook in the first 2-4 s, button ending | high arousal, bright, the brand beat on the last downbeat |
+| Meditation / sleep | 45 s+ | drone + sparse motif, slow harmonic rhythm | 50-70 bpm, legato, no percussion, open ending allowed |
+| Suspense cue | any | drone + pulse, stingers, withheld resolution | irregular accents, low register, an open end |
+
+Sources: Juslin & Sloboda (eds.), *Handbook of Music and Emotion* (2010), especially Gabrielsson &
+Lindström, "The role of structure in the musical expression of emotions", pp. 367-400; Juslin & Laukka,
+"Communication of emotions in vocal expression and music performance", *Psychological Bulletin* 129
+(2003); Juslin, "Communicating emotion in music performance" (the lens model), in Juslin & Sloboda
+(eds.), *Music and Emotion* (2001); Hevner, "The affective character of the major and minor modes",
+*American Journal of Psychology* 47 (1935), and "The affective value of pitch and tempo" 49 (1937);
+Gagnon & Peretz, "Mode and tempo relative contributions to happy-sad judgements", *Cognition and
+Emotion* 17 (2003); Russell, "A circumplex model of affect", *JPSP* 39 (1980); Schubert, "Modeling
+perceived emotion with continuous musical features", *Music Perception* 21 (2004); Eerola & Vuoskoski,
+"A comparison of the discrete and dimensional models of emotion in music", *Psychology of Music* 39
+(2011); Huron, *Empirical Musicology Review* 3 (2008).
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/theory/rhythm.md b/plugins/anidoodle/skills/anidoodle/references/music/theory/rhythm.md
new file mode 100644
index 0000000..d0bd286
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/references/music/theory/rhythm.md
@@ -0,0 +1,124 @@
+# Rhythm and groove
+
+Positions are beats in the bar (`1`, `1&` = the eighth after it, `1e&a` = sixteenths). In 6/8 and 12/8 a
+beat is a dotted quarter. `craft` measures this page on the **rhythm** line.
+
+## 1. Metric hierarchy
+
+Beats nest into levels, and a stronger level is heard as more important (Lerdahl & Jackendoff 1983;
+London 2012). `craft` weights positions this way:
+
+| Position | 4/4 | 3/4 | 6/8, 12/8 | weight |
+|---|---|---|---|---|
+| downbeat | 1 | 1 | 1 | 4 |
+| mid-bar | 3 | - | 7 (12/8) | 3 |
+| beats | 2, 4 | 2, 3 | the dotted quarters | 2 |
+| eighths | the `&`s | the `&`s | each eighth | 1 |
+| sixteenths | `e`, `a` | `e`, `a` | the sixteenths | 0 |
+
+Rules that follow from it:
+
+- Arrivals (cadences, section starts, the climax) go on downbeats.
+- Chord changes go on strong beats.
+- What sits on weak positions is motion.
+
+## 2. Syncopation
+
+A syncopation is an onset on a weak position followed by silence or a tie over a stronger one: the
+expected accent is displaced (Longuet-Higgins & Lee 1984). `craft` reports a syncopation index per
+layer: melody, bass, and kick+snare.
+
+- **The inverted U.** Medium syncopation makes people most want to move and enjoy it most. Too
+ little is stiff, too much loses the beat (Witek et al. 2014).
+- In groove idioms (lo-fi, hip-hop, house, funk, pop, jazz), `craft` warns when nothing is syncopated.
+ Anticipate the bass or a melody note by an eighth, or tie over beat 3.
+- Keep the **kick and backbeat anchored**, and syncopate on top of them. If everything is
+ syncopated, nothing is.
+
+## 3. The backbeat and core patterns
+
+| Idiom | Kick | Snare / clap | Hats |
+|---|---|---|---|
+| Rock / pop | 1, 3 (plus pushes on `2&` or `3&`) | 2, 4 | eighths |
+| Four on the floor (house, disco) | every beat | 2, 4 | off-beat `&` open hat |
+| Hip-hop / boom bap | 1, `2&`, `3&` (varies) | 2, 4, lazy (late) | swung eighths or sixteenths |
+| Half-time (trap, cinematic) | 1, `3a` | 3 | fast sixteenths and triplet rolls |
+| Lo-fi | loose 1 and `3&` | 2, 4, soft and late | swung, quiet |
+| Waltz 3/4 | 1 | 2, 3 (or brushes) | - |
+| 6/8 gallop | 1, 4 | 4 (or 2 and 5) | eighths |
+
+Write your own, and let the family be the idiom rather than the notes. `craft`'s **groove consistency**
+compares each bar's kick and snare with the section's commonest bar. Below 0.45 the groove never
+settles. Hold the kick and backbeat, and vary the hats and the fill bar.
+
+## 4. Swing and feel
+
+- **Swing ratio** = long:short eighth. 1:1 is straight, 2:1 is triplet, 3:1 is dotted.
+- Jazz drummers swing **harder at slow tempos and straighter at fast ones**: up to about 3.5:1 slow,
+ down to about 1:1 fast. The short note stays near 100 ms (Friberg & Sundström 2002).
+- The engine's `swing` is the long note's share: 0.5 straight, 0.58 is about 1.4:1, 0.67 is triplet.
+ Typical settings:
+ - lo-fi and hip-hop 0.54-0.62 (sixteenth swing);
+ - jazz 0.6-0.67 (eighths, less at fast tempos);
+ - house 0.5-0.56;
+ - rock and orchestral 0.5.
+- **Push and lay back:** hats slightly early drive, a snare 10-25 ms late relaxes (the "lazy"
+ hip-hop and lo-fi backbeat), and the kick stays on the grid. The engine's `perform` applies per-lane
+ feel. You choose the style and swing.
+
+## 5. Polyrhythm and hemiola
+
+- **Hemiola:** 3 against 2. Two bars of 3/4 regrouped as three bars of 2/4 is the classic cadence
+ approach, and it drives any ending.
+- **3 over 4:** a three-note cell in running sixteenths realigns every 3 beats. It gives motion
+ without changing the tempo, as in minimalism and tension cues.
+- **Odd meters:** 7/8 = 2+2+3, 5/4 = 3+2. Accent the group starts so the ear can count.
+
+## 6. Fills and transitions
+
+- A fill goes on the **last bar (or half bar) of a section**, never in the middle of a phrase. It ends
+ **on the next downbeat** with a crash or an arrival.
+- Build to a landing:
+ 1. density rises (eighths to sixteenths);
+ 2. the snare rolls up;
+ 3. a beat or a bar of silence (the breath) comes just before the drop.
+
+ The silence makes the landing bigger (Huron 2006, the tension-contrast effect).
+- One fill per 4-8 bars. More turns into noise.
+
+## 7. Density arcs
+
+- Section contrast is mostly density: layers in and out, and onsets per beat. `craft` prints each
+ section's onsets per beat and layer count. It warns when every section is the same, and when a
+ section repeats the previous one note for note (dead air).
+- A good arc:
+ 1. sparse intro;
+ 2. medium verse;
+ 3. the hook adds a layer;
+ 4. the breakdown thins to one or two;
+ 5. the drop brings everything;
+ 6. the outro thins again.
+
+## 8. Rhythm in the melody
+
+A line with **one repeated rhythm and a few changes** is memorable. The same pitches with a new rhythm
+are a new tune (this is why the novelty fingerprint weighs rhythm most). Vary one axis at a time.
+
+## 9. Humanize or quantize
+
+- Machines are perfectly on grid. Players deviate in **correlated** ways (drifting ahead or behind for
+ several notes, 1/f-like), and listeners prefer that to random jitter (Hennig et al. 2011).
+- Random jitter is not feel: listeners do not rate randomly microtimed grooves above quantized ones
+ (Frühauf, Kopiez & Platz 2013; Senn et al. 2016).
+- The engine: `perform` adds correlated micro-timing and per-lane feel. Grid parts (music box,
+ chiptune, drive) stay mechanical on purpose. Velocity (`@0.6`) carries accents: write strong-weak
+ patterns (ghost notes at 0.3-0.5) instead of hoping the performer invents them.
+
+Sources: Lerdahl & Jackendoff, *A Generative Theory of Tonal Music* (1983); London, *Hearing in Time*
+(2nd ed., 2012); Longuet-Higgins & Lee, "The rhythmic interpretation of monophonic music", *Music
+Perception* 1 (1984); Witek et al., "Syncopation, body-movement and pleasure in groove music", *PLoS
+ONE* 9 (2014); Friberg & Sundström, "Swing ratios and ensemble timing in jazz performance", *Music
+Perception* 19 (2002); Hennig et al., "The nature and perception of fluctuations in human musical
+rhythms", *PLoS ONE* 6 (2011); Frühauf, Kopiez & Platz, "Music on the timing grid", *Musicae
+Scientiae* 17 (2013); Senn et al., "The effect of expert performance microtiming on listeners'
+experience of groove in swing or funk music", *Frontiers in Psychology* 7 (2016); Huron, *Sweet Anticipation* (2006).
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/theory/sound.md b/plugins/anidoodle/skills/anidoodle/references/music/theory/sound.md
new file mode 100644
index 0000000..635af1d
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/references/music/theory/sound.md
@@ -0,0 +1,115 @@
+# Sound theory: psychoacoustics for composing and mixing
+
+You write notes, and the engine mixes. Most "muddy", "thin" or "buried" results are decided by the
+notes: register, spacing, density and which parts overlap. This page is the physics behind those
+choices. The engine's guards and `craft` check the parts you can control from the score. The mix
+chain itself is in `render.ts` and `mixProfiles.ts` ([../sound-design.md](../sound-design.md) covers
+effects).
+
+## 1. Critical bands and roughness
+
+- The ear analyses sound in overlapping **critical bands**, about 100 Hz wide below 500 Hz and about
+ 20 % of the centre frequency above that (Zwicker 1961; the ERB is 24.7 x (4.37 f/kHz + 1) Hz,
+ Glasberg & Moore 1990).
+- Two partials inside one band **beat and roughen**. Roughness peaks near a quarter of a critical band
+ apart (Plomp & Levelt 1965).
+- Low down, a band spans many semitones, so **a third at C2 is rough while the same third at C4 is
+ sweet.**
+
+That is the physics of the **low interval limits** (the chart taught in Berklee arranging; e.g. Pease &
+Pullig 2001), the lowest bottom note for each interval before it muddies:
+
+| Interval | m2 | M2 | m3 | M3 | P4 | tritone | P5 | m6-M7 | m9 | M9 |
+|---|---|---|---|---|---|---|---|---|---|---|
+| Lowest bottom note | E3 | Eb3 | C3 | Bb2 | Bb2 | B2 | Bb1 | F2 | E2 | Eb2 |
+
+- Octaves have no limit. The chart is loose by about ±2 semitones (a concert grand gets away with
+ more), so `craft` flags intervals 3 or more semitones under their limit.
+- Fix: spread the voicing (`1-5-3'` instead of `1-3-5` in the bass), or lift the upper note an octave.
+
+## 2. Masking: why the tune gets buried
+
+- A louder sound hides a quieter one in the same critical band. Masking spreads **upward**: a loud low
+ sound masks higher sounds more than the reverse (Zwicker & Fastl 2007; Moore 2012).
+- A pad or chord stack in the melody's octave masks the melody even at a lower level. The engine's
+ masking guard requires the melody to beat every other part by 3 dB in 500 Hz-4 kHz.
+- **Composing fixes come before level fixes:**
+ - voice the chords below the tune (`craft`: "melody under chords");
+ - thin the accompaniment when the melody moves;
+ - give the lead a distinct timbre and its own octave;
+ - let counter lines answer in the rests instead of overlapping.
+- **Frequency slots** ([form.md](form.md) section 4): one owner per register at a time.
+
+## 3. Equal loudness (Fletcher-Munson / ISO 226)
+
+- Hearing is least sensitive at the extremes and most sensitive at 2-5 kHz. At low listening levels
+ the lows and highs drop away (Fletcher & Munson 1933; ISO 226:2003).
+- A bass line that is "loud enough" on studio monitors disappears on a phone speaker (the small
+ speaker rolls off below about 150-200 Hz). **Phone rule:** every low part needs harmonics above
+ 500 Hz: a bass with some drive or a pick attack, and an 808 with saturation. Octave-doubling the bass
+ line an octave up at a low level also works.
+- A quiet passage sounds thinner, not just quieter. Soft sections can take slightly more low-mid warmth.
+
+## 4. Tonal balance by genre (long-term spectrum)
+
+- Commercial mixes cluster around a smooth downward slope, about -5 dB per octave from 100 Hz to
+ 4 kHz, steeper above (Pestana et al. 2013). The shape has held across decades and genres.
+ The genres differ at the ends:
+
+| Genre | Low end | Mids | Top |
+|---|---|---|---|
+| EDM, hip-hop, trap | +3-6 dB sub (40-80 Hz), the kick and 808 dominate | scooped slightly around 300-500 Hz | bright hats |
+| Pop, rock | full, the kick and bass balanced | vocal and guitar forward at 1-4 kHz | bright |
+| Lo-fi | warm, head bump 60-90 Hz | forward low-mids | rolled off above 8-10 kHz |
+| Orchestral, acoustic | natural, less sub | wide | natural roll-off from distance and hall |
+| Ambient | soft lows, long tails | recessed | airy but gentle |
+
+- The engine's mix profiles implement these, and `check` measures the centroid for the mood. For
+ composing: **a dark mood wants lower registers and fewer bright attacks, not just a darker filter.**
+
+## 5. Stereo and depth
+
+- **Mono lows:** keep the kick, bass and anything below about 120 Hz in the centre. Low frequencies
+ carry little direction and eat headroom when spread.
+- **Width comes from difference**: different parts (or the same part voiced differently) on each side,
+ and two players with slight timing and tuning differences. One part copied to both sides is still
+ mono.
+- **The precedence (Haas) effect:** the same sound 1-30 ms later is heard as one sound from the
+ earlier side (Haas 1951; Blauert 1997). It is useful for width on doubles, and dangerous for mono
+ playback (comb filtering).
+- **Depth cues:** a far sound is quieter, darker (the air absorbs highs), wetter (a higher
+ reverb-to-direct ratio) and has softer attacks. Put the lead near and the pads far.
+
+## 6. Reverb and delay timing
+
+- **Tempo-synced delay:** a quarter note = 60,000 / bpm ms (at 90 bpm, 667 ms). A dotted eighth = 0.75 x
+ that. An eighth = 0.5 x.
+- **Pre-delay** (the gap before the reverb starts) keeps the attack dry and the part clear. 10-30 ms
+ is typical. Longer (up to a 1/32 or 1/64 note) keeps the vocal and lead forward (Izhaki 2017).
+- **Decay time to the tempo:** let the tail die before the next strong beat (a quarter to a half
+ note). Longer tails blur harmony changes. The engine's reverb guard fails a tail within 10 dB of the
+ dry sound.
+- **Slow and sparse = more space. Fast and dense = less.** Many notes plus a long hall is the "ghost"
+ wash that the ghost guard exists for.
+
+## 7. Loudness and dynamics
+
+- The engine masters to -16 LUFS (gentle) or -14 LUFS (dense), -1 dBTP, the streaming norms (AES TD1004,
+ 2015).
+- **Real dynamics are written, not mastered:** section `energy`, `dyn` and velocities. A peak is a
+ composing problem: stagger the bass under the loudest downbeat, roll the big chord, and don't double
+ the climax note in every part.
+- Perceived loudness follows density and brightness as well as level. A build can feel louder with more
+ onsets and a higher register at the same meter reading.
+
+Sources: Zwicker, "Subdivision of the audible frequency range into critical bands", *JASA* 33 (1961);
+Glasberg & Moore, "Derivation of auditory filter shapes from notched-noise data", *Hearing Research*
+47 (1990); Plomp & Levelt, "Tonal consonance and critical bandwidth", *JASA* 38 (1965); Zwicker &
+Fastl, *Psychoacoustics: Facts and Models* (3rd ed., 2007); Moore, *An Introduction to the Psychology
+of Hearing* (6th ed., 2012); Fletcher & Munson, "Loudness, its definition, measurement and
+calculation", *JASA* 5 (1933); ISO 226:2003; Pestana, Ma, Reiss, Barbosa & Black, "Spectral
+characteristics of popular commercial recordings 1950-2010", AES 135th Convention (2013); Haas, "Über
+den Einfluss eines Einfachechos auf die Hörsamkeit von Sprache", *Acustica* 1 (1951); Blauert,
+*Spatial Hearing* (1997); Izhaki, *Mixing Audio* (3rd ed., 2017); Owsinski, *The Mixing Engineer's
+Handbook* (4th ed., 2017); Katz, *Mastering Audio* (3rd ed., 2015); Pease & Pullig, *Modern Jazz
+Voicings* (2001); AES TD1004.1.15-10, "Recommendation for loudness of audio streaming and network file playback" (2015).