Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
ship a drum arrangement of House of the Rising Sun with the SongBook seeds
[._.]/ Adam Eivy27db1c248a6f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 42851a4281..6a4b20c385 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,6 +6,7 @@## Added+- **The SongBook's sample song now ships a drum part.** "House of the Rising Sun" has always seeded with guitar, piano, and ukulele arrangements, but a drummer opening it had nothing to read — only the invented "Example Rock Beat" that exists to demonstrate the grid format. A fourth arrangement now ships alongside the other three: 32 bars of 6/8 (one grid cell per eighth, four times through the 8-bar progression), with the drums sitting out the intro on a hi-hat foot pulse, entering on a pickup fill, moving from hats to the ride for the organ break, and ending on a flam into the crash. It plays back against the other three seeds at the same tempo, and the written 228 counts *eighths* — so the practice-tempo buttons take it down to a workable speed. Existing installs receive it on upgrade without ever overwriting a copy you've edited or deleted.- **Malware scans now leave a durable, reviewable report trail.** Git-link scans save an owned markdown artifact, surface it from the completed agent summary and Review Hub, and mark repositories with an explicit `DANGEROUS` verdict using a skull danger treatment on the Git links card.- **Slashdo-free TUI agent PRs now complete their lifecycle.** Codex, Antigravity, OpenCode, and lean Claude agents hand committed work back to PortOS so it can generate a non-empty PR description, run configured reviewers, and merge after the selected gates pass instead of leaving an ownerless PR open.- **Music Video projects now save their scene-video renderer and model.** Directors can choose local or Grok generation per project, pick an image-to-video-capable local model, see cut-pacing warnings, selectively continue clips on native LTX runtimes, generate all missing media from the board, and play or download the audio-backed final render in place.diff --git a/data.reference/brain/songs.json b/data.reference/brain/songs.jsonindex 3b1661d06c..b7dbb1557f 100644--- a/data.reference/brain/songs.json+++ b/data.reference/brain/songs.json@@ -72,6 +72,31 @@"updatedAt": "2026-07-15T00:00:00.000Z","originInstanceId": "seed"},+ "song-seed-hotrs-drums": {+ "title": "House of the Rising Sun",+ "artist": "Traditional",+ "instrument": "drums",+ "stage": "new",+ "tags": [+ "folk",+ "traditional",+ "public-domain",+ "drums"+ ],+ "key": "Am",+ "capo": 0,+ "tuning": "",+ "sourceUrl": "",+ "content": {+ "format": "drum",+ "text": "time: 6/8\ntempo: 228\nsubdivision: 1\n\n# Intro - guitar alone; keep the 6/8 pulse with the hi-hat foot x7\nHF: x - - x - -\n\n# Pickup fill - drums enter on the last intro bar\nT1: - - - o - -\nT2: - - - - o -\nS: - - - - - o\nK: o - - - - -\n\n# Verse groove - hats on every eighth, kick on 1, snare on 4 x7\nHH: x x x x x x\nS: - - - o - -\nK: o - - - - -\n\n# Verse turnaround - an extra kick pushes into the next section\nHH: x x x x x x\nS: - - - o - g\nK: o - - - o -\n\n# Organ break - move to the ride, kick on both pulses x7\nRD: x x x x x x\nS: - - - o - -\nK: o - - o - -\n\n# Break fill - walk down the toms\nS: o - o - - -\nT1: - - - o - -\nT2: - - - - o -\nFT: - - - - - o\nK: o - - - - -\n\n# Last verse - crash in and accent the backbeat\nCR: X - - - - -\nRD: x x x x x x\nS: - - - X - -\nK: o - - o - o\n\n# ...and hold that groove x6\nRD: x x x x x x\nS: - - - X - -\nK: o - - o - o\n\n# Ending - flam the last backbeat and let the crash ring\nCR: X - - - - -\nS: - - - f - -\nK: o - - - - -"+ },+ "notes": "Drum part for the SongBook's canonical song, so the guitar/piano/ukulele seeds have something to play against. 6/8 throughout — one cell per eighth, counted 1-2-3 4-5-6, with the kick on 1 and the snare on 4. The written 228 is the EIGHTH note (dotted quarter ~76), so start at 50-75% with the BPM control and work up. Drums sit out the 8-bar intro (hi-hat foot keeps the pulse), enter on the pickup fill, then verse groove on hats, organ break on the ride, and a flam into the final crash. 32 bars = four times through the 8-bar Am-C-D-F-Am-C-E-E progression. Traditional song, public domain.",+ "attachments": [],+ "createdAt": "2026-07-29T00:00:00.000Z",+ "updatedAt": "2026-07-29T00:00:00.000Z",+ "originInstanceId": "seed"+ },"song-seed-example-rock-beat": {"title": "Example Rock Beat","artist": "The Placeholders",diff --git a/scripts/migrations/190-seed-songbook-songs.test.js b/scripts/migrations/190-seed-songbook-songs.test.jsindex 9789563b30..f40d3d78d1 100644--- a/scripts/migrations/190-seed-songbook-songs.test.js+++ b/scripts/migrations/190-seed-songbook-songs.test.js@@ -112,12 +112,13 @@ describe('migration 190 — seed songbook songs', () => {it('seeds the SHIPPED reference records against a real repo layout shape', async () => {// Sanity-pin the seeds THIS migration ships: three instrument variants of the// same public-domain song, stable ids, and a FIXED originInstanceId sentinel.- // Later migrations add their own seed records to the same file (e.g. 209's- // drum example), so this scopes to its own ids rather than the whole file —- // and each new seed pins its own shape in its own migration's test.+ // Later migrations add their own seed records to the same file (209's drum+ // example, 213's drum arrangement of this same song), so this scopes to its+ // own ids rather than the whole file or the `song-seed-hotrs-` prefix — and+ // each new seed pins its own shape in its own migration's test.const shipped = JSON.parse(readFileSync(new URL('../../data.reference/brain/songs.json', import.meta.url), 'utf-8'));- const ids = Object.keys(shipped.records).filter((id) => id.startsWith('song-seed-hotrs-')).sort();- expect(ids).toEqual(['song-seed-hotrs-guitar', 'song-seed-hotrs-piano', 'song-seed-hotrs-ukulele']);+ const ids = ['song-seed-hotrs-guitar', 'song-seed-hotrs-piano', 'song-seed-hotrs-ukulele'];+ for (const id of ids) expect(shipped.records[id]).toBeDefined();for (const id of ids) {const rec = shipped.records[id];expect(rec.title).toBe('House of the Rising Sun');diff --git a/scripts/migrations/209-seed-drum-example-song.js b/scripts/migrations/209-seed-drum-example-song.jsindex a3b2c8530a..7d675feeb8 100644--- a/scripts/migrations/209-seed-drum-example-song.js+++ b/scripts/migrations/209-seed-drum-example-song.js@@ -5,117 +5,26 @@* example chart ("Example Rock Beat" by The Placeholders) in* data.reference/brain/songs.json — it doubles as the format's worked example,* so a drummer opening `/songbook` on an upgraded install has something to read,- * play along with, and copy from. Fresh installs get it because- * scripts/setup-data.js copies data.reference wholesale, but setup-data only- * copies MISSING files, so every existing install would never receive it.+ * play along with, and copy from.*- * Since migration 200, brain stores live per-record at- * `data/brain/<type>/<id>/index.json` (collectionStore layout) rather than in a- * monolithic `data/brain/<type>.json` — so unlike migration 190 (the pre-split- * SongBook seed), this writes one record directory. The legacy monolithic file is- * ALSO topped up when it's still present, so an install that hasn't run 200 yet- * (migrations apply in filename order, but a repaired/pending 200 can lag) still- * picks the seed up when its split finally runs.- *- * Idempotent and non-destructive: an id already present — a user-edited copy, a- * peer-synced copy, or a tombstone from a deliberate delete — is NEVER- * overwritten, so a deleted seed stays deleted. Nothing is written when the- * existing record (or the legacy file) is unreadable: possibly-recoverable user- * data beats a cosmetic starter chart. The seed carries a fixed- * originInstanceId ('seed') so every install holds a byte-identical record and- * the brain reconcile checksum still converges across peers.+ * Idempotency, tombstone/edit preservation, the legacy-monolith top-up, and the+ * never-write-over-unreadable-data rule all live in `makeBrainSeedMigration`+ * (`_lib.js`). The seed carries a fixed originInstanceId ('seed') so every+ * install holds a byte-identical record and the brain reconcile checksum still+ * converges across peers.*/-import { readFile, writeFile, mkdir, access } from 'fs/promises';-import { join, dirname } from 'path';--// Only THIS seed id — a later seed addition gets its own migration rather than-// silently riding along on a re-run of this one.-const SEED_IDS = ['song-seed-example-rock-beat'];--// Tagged read: 'missing' (ENOENT — nothing there, safe to create) is NOT the-// same as 'invalid' (exists but won't parse — user data a write would destroy).-// The migration runner executes before the service layer is wired, so no-// server/lib imports here.-async function readJsonTagged(path) {- let raw;- try {- raw = await readFile(path, 'utf-8');- } catch (err) {- return err?.code === 'ENOENT' ? { state: 'missing' } : { state: 'invalid', error: err?.message };- }- try {- return { state: 'ok', doc: JSON.parse(raw) };- } catch (err) {- return { state: 'invalid', error: err?.message };- }-}--const exists = async (path) => access(path).then(() => true, () => false);--export async function up({ rootDir }) {- const seedPath = join(rootDir, 'data.reference', 'brain', 'songs.json');- const perRecordDir = join(rootDir, 'data', 'brain', 'songs');- const legacyPath = join(rootDir, 'data', 'brain', 'songs.json');-- const seedRead = await readJsonTagged(seedPath);- const seedRecords = seedRead.state === 'ok' && seedRead.doc?.records && typeof seedRead.doc.records === 'object'- ? seedRead.doc.records- : {};- const present = SEED_IDS.filter((id) => seedRecords[id] !== undefined);- if (present.length === 0) {- console.log('🥁 drum-seed: no drum seed record in data.reference — no-op.');- return { ok: true, reason: 'no-seeds' };- }-- // --- Per-record store (the post-migration-200 layout) ---------------------- let added = 0;- let skipped = 0;- for (const id of present) {- const recordPath = join(perRecordDir, id, 'index.json');- const read = await readJsonTagged(recordPath);- if (read.state !== 'missing') {- // Present (a user-edited copy / peer copy / tombstone) or unreadable —- // either way, leave it alone.- if (read.state === 'invalid') {- console.error(`❌ drum-seed: ${id}/index.json is unreadable (${read.error}) — leaving it untouched.`);- }- skipped += 1;- continue;- }- await mkdir(dirname(recordPath), { recursive: true });- await writeFile(recordPath, JSON.stringify(seedRecords[id], null, 2) + '\n');- added += 1;- }-- // --- Legacy monolithic file (only when it still exists) -------------------- // An install whose migration-200 split hasn't run yet still reads- // data/brain/songs.json, so top that up too. We never CREATE the legacy file —- // doing so on a split install would resurrect a shape nothing reads.- let legacyAdded = 0;- if (await exists(legacyPath)) {- const legacyRead = await readJsonTagged(legacyPath);- if (legacyRead.state === 'invalid') {- console.error(`❌ drum-seed: data/brain/songs.json exists but is unreadable (${legacyRead.error}) — leaving it untouched.`);- } else {- const live = legacyRead.doc && typeof legacyRead.doc === 'object' ? legacyRead.doc : {};- if (!live.records || typeof live.records !== 'object') live.records = {};- for (const id of present) {- if (live.records[id] !== undefined) continue;- live.records[id] = seedRecords[id];- legacyAdded += 1;- }- if (legacyAdded > 0) await writeFile(legacyPath, JSON.stringify(live, null, 2) + '\n');- }- }-- if (added === 0 && legacyAdded === 0) {- console.log('🥁 drum-seed: drum example already present — no-op.');- return { ok: true, reason: 'already-present', added: 0, legacyAdded: 0, skipped };- }+import { makeBrainSeedMigration } from './_lib.js';- console.log(`🥁 drum-seed: added the drum example groove (${added} per-record, ${legacyAdded} legacy) to the SongBook.`);- return { ok: true, reason: 'seeded', added, legacyAdded, skipped };-}+const migration = makeBrainSeedMigration({+ logTag: '🥁 drum-seed',+ entityType: 'songs',+ // Only THIS seed id — a later seed addition gets its own migration rather+ // than silently riding along on a re-run of this one.+ seedIds: ['song-seed-example-rock-beat'],+ seedLabel: 'the drum example groove',+ storeLabel: 'the SongBook',+});-export default { up };+export const { up } = migration;+export default migration;diff --git a/scripts/migrations/209-seed-drum-example-song.test.js b/scripts/migrations/209-seed-drum-example-song.test.jsindex 7d6503eaa9..101acc809a 100644--- a/scripts/migrations/209-seed-drum-example-song.test.js+++ b/scripts/migrations/209-seed-drum-example-song.test.js@@ -1,34 +1,22 @@-import { describe, it, expect, beforeEach, afterEach } from 'vitest';-import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';-import { tmpdir } from 'os';-import { join } from 'path';+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'fs';import migration from './209-seed-drum-example-song.js';+import { runBrainSeedMigrationTests } from './_brainSeedTestHelpers.js';import { parseDrumChart } from '../../client/src/lib/drumNotation.js';const SEED_ID = 'song-seed-example-rock-beat';-let rootDir;-let seedDir;-let perRecordDir;-let legacyPath;--beforeEach(() => {- rootDir = mkdtempSync(join(tmpdir(), 'migration-209-'));- seedDir = join(rootDir, 'data.reference', 'brain');- perRecordDir = join(rootDir, 'data', 'brain', 'songs');- legacyPath = join(rootDir, 'data', 'brain', 'songs.json');- mkdirSync(seedDir, { recursive: true });-});--afterEach(() => {- rmSync(rootDir, { recursive: true, force: true });-});--// Invented seed fixture (privacy convention) — mirrors the shipped shape.-const SEEDS = {- records: {- [SEED_ID]: {+describe('migration 209 — seed the drum example song', () => {+ // The shared brain-seed contract (split-install write, never-overwrite,+ // tombstone-safe, idempotent, legacy top-up, unreadable-data safety).+ runBrainSeedMigrationTests({+ migration,+ number: 209,+ entityType: 'songs',+ seedId: SEED_ID,+ // Invented fixture (privacy convention) — mirrors the shipped shape.+ record: {title: 'Example Rock Beat',artist: 'The Placeholders',instrument: 'drums',@@ -38,106 +26,10 @@ const SEEDS = {updatedAt: '2026-07-26T00:00:00.000Z',originInstanceId: 'seed',},- // An unrelated seed the migration must NOT touch (it owns one id only).- 'song-seed-other': { title: 'Other Seed', attachments: [] },- },-};--const writeSeed = (obj = SEEDS) => writeFileSync(join(seedDir, 'songs.json'), JSON.stringify(obj, null, 2));-const recordPath = (id = SEED_ID) => join(perRecordDir, id, 'index.json');-const writeRecord = (obj, id = SEED_ID) => {- mkdirSync(join(perRecordDir, id), { recursive: true });- writeFileSync(recordPath(id), JSON.stringify(obj, null, 2));-};-const readRecord = (id = SEED_ID) => JSON.parse(readFileSync(recordPath(id), 'utf-8'));-const writeLegacy = (obj) => {- mkdirSync(join(rootDir, 'data', 'brain'), { recursive: true });- writeFileSync(legacyPath, JSON.stringify(obj, null, 2));-};-const readLegacy = () => JSON.parse(readFileSync(legacyPath, 'utf-8'));--describe('migration 209 — seed the drum example song', () => {- it('writes the per-record file (with parent dirs) on a split install', async () => {- writeSeed();- const result = await migration.up({ rootDir });- expect(result).toMatchObject({ ok: true, reason: 'seeded', added: 1, legacyAdded: 0 });- expect(readRecord().title).toBe('Example Rock Beat');- expect(readRecord().instrument).toBe('drums');- // It owns exactly one id — the other seed is another migration's business.- expect(existsSync(recordPath('song-seed-other'))).toBe(false);- });-- it('never overwrites an existing id — an edited copy survives', async () => {- writeSeed();- writeRecord({ title: 'My Customized Groove', updatedAt: '2026-08-01T00:00:00.000Z' });- const result = await migration.up({ rootDir });- expect(result.reason).toBe('already-present');- expect(readRecord().title).toBe('My Customized Groove');- });-- it('never resurrects a tombstoned (deliberately deleted) seed', async () => {- writeSeed();- writeRecord({ _deleted: true, updatedAt: '2026-08-01T00:00:00.000Z', deletedAt: '2026-08-01T00:00:00.000Z', originInstanceId: 'x' });- const result = await migration.up({ rootDir });- expect(result.reason).toBe('already-present');- expect(readRecord()._deleted).toBe(true);- });-- it('is idempotent — a second run adds nothing', async () => {- writeSeed();- await migration.up({ rootDir });- const second = await migration.up({ rootDir });- expect(second).toMatchObject({ reason: 'already-present', added: 0 });- });-- it('tops up a still-present legacy monolithic file too', async () => {- writeSeed();- writeLegacy({ records: { 'user-song-1': { title: 'User Song' } } });- const result = await migration.up({ rootDir });- expect(result).toMatchObject({ added: 1, legacyAdded: 1 });- const live = readLegacy();- expect(live.records[SEED_ID].title).toBe('Example Rock Beat');- expect(live.records['user-song-1'].title).toBe('User Song');- expect(live.records['song-seed-other']).toBeUndefined();- });-- it('never CREATES a legacy file on a split install', async () => {- writeSeed();- await migration.up({ rootDir });- expect(existsSync(legacyPath)).toBe(false);- });-- it('leaves an existing legacy id alone', async () => {- writeSeed();- writeLegacy({ records: { [SEED_ID]: { title: 'Kept' } } });- const result = await migration.up({ rootDir });- expect(result.legacyAdded).toBe(0);- expect(readLegacy().records[SEED_ID].title).toBe('Kept');- });-- it('NEVER writes over an unreadable record or legacy file', async () => {- writeSeed();- mkdirSync(join(perRecordDir, SEED_ID), { recursive: true });- writeFileSync(recordPath(), '{not json');- writeLegacy({ records: {} });- writeFileSync(legacyPath, '{also not json');- const result = await migration.up({ rootDir });- expect(result.reason).toBe('already-present');- // Both corrupt files are byte-for-byte untouched (recoverable by the user).- expect(readFileSync(recordPath(), 'utf-8')).toBe('{not json');- expect(readFileSync(legacyPath, 'utf-8')).toBe('{also not json');- });-- it('no-ops when the seed file is missing or lacks the drum record', async () => {- const missing = await migration.up({ rootDir });- expect(missing).toMatchObject({ ok: true, reason: 'no-seeds' });- expect(existsSync(recordPath())).toBe(false);-- writeSeed({ records: { 'song-seed-other': { title: 'Other' } } });- expect(await migration.up({ rootDir })).toMatchObject({ reason: 'no-seeds' });+ otherId: 'song-seed-other',});- it('ships a parseable drum chart in the real reference file', async () => {+ it('ships a parseable drum chart in the real reference file', () => {const shipped = JSON.parse(readFileSync(new URL('../../data.reference/brain/songs.json', import.meta.url), 'utf-8'));const rec = shipped.records[SEED_ID];expect(rec).toBeDefined();diff --git a/scripts/migrations/213-seed-hotrs-drums-song.js b/scripts/migrations/213-seed-hotrs-drums-song.jsnew file mode 100644index 0000000000..f39bac63a8--- /dev/null+++ b/scripts/migrations/213-seed-hotrs-drums-song.js@@ -0,0 +1,31 @@+/**+ * Migration 213 — seed the House of the Rising Sun drum part into existing installs.+ *+ * "House of the Rising Sun" is the SongBook's canonical sample song: migration+ * 190 shipped guitar/piano/ukulele arrangements of it, and #3115 added the+ * `drums` instrument + `drum` grid format. This adds the missing fourth+ * arrangement (`song-seed-hotrs-drums`) so a drummer has the canonical song to+ * play against the other three seeds, rather than only the invented "Example+ * Rock Beat" that exists to demonstrate the format (migration 209).+ *+ * Idempotency, tombstone/edit preservation, the legacy-monolith top-up, and the+ * never-write-over-unreadable-data rule all live in `makeBrainSeedMigration`+ * (`_lib.js`). The seed carries a fixed originInstanceId ('seed') so every+ * install holds a byte-identical record and the brain reconcile checksum still+ * converges across peers.+ */++import { makeBrainSeedMigration } from './_lib.js';++const migration = makeBrainSeedMigration({+ logTag: '🥁 hotrs-drums',+ entityType: 'songs',+ // Only THIS seed id — a later seed addition gets its own migration rather+ // than silently riding along on a re-run of this one.+ seedIds: ['song-seed-hotrs-drums'],+ seedLabel: 'the House of the Rising Sun drum part',+ storeLabel: 'the SongBook',+});++export const { up } = migration;+export default migration;diff --git a/scripts/migrations/213-seed-hotrs-drums-song.test.js b/scripts/migrations/213-seed-hotrs-drums-song.test.jsnew file mode 100644index 0000000000..b18d59ef12--- /dev/null+++ b/scripts/migrations/213-seed-hotrs-drums-song.test.js@@ -0,0 +1,67 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'fs';++import migration from './213-seed-hotrs-drums-song.js';+import { runBrainSeedMigrationTests } from './_brainSeedTestHelpers.js';+import { parseDrumChart } from '../../client/src/lib/drumNotation.js';++const SEED_ID = 'song-seed-hotrs-drums';++describe('migration 213 — seed the House of the Rising Sun drum part', () => {+ // The shared brain-seed contract (split-install write, never-overwrite,+ // tombstone-safe, idempotent, legacy top-up, unreadable-data safety).+ runBrainSeedMigrationTests({+ migration,+ number: 213,+ entityType: 'songs',+ seedId: SEED_ID,+ // Invented fixture (privacy convention) — mirrors the shipped shape.+ record: {+ title: 'House of the Rising Sun',+ artist: 'Traditional',+ instrument: 'drums',+ content: { format: 'drum', text: 'time: 6/8\nsubdivision: 1\n\nHH: xxxxxx\nK: o-----' },+ attachments: [],+ createdAt: '2026-07-29T00:00:00.000Z',+ updatedAt: '2026-07-29T00:00:00.000Z',+ originInstanceId: 'seed',+ },+ otherId: 'song-seed-other',+ });++ it('ships a parseable 6/8 drum chart in the real reference file', () => {+ const shipped = JSON.parse(readFileSync(new URL('../../data.reference/brain/songs.json', import.meta.url), 'utf-8'));+ const rec = shipped.records[SEED_ID];+ expect(rec).toBeDefined();+ expect(rec.title).toBe('House of the Rising Sun');+ expect(rec.artist).toBe('Traditional');+ expect(rec.instrument).toBe('drums');+ expect(rec.content.format).toBe('drum');+ expect(rec.attachments).toEqual([]);+ // Same key as the guitar/piano/ukulele arrangements, so the four seeds read+ // as one song across the SongBook index rather than four unrelated entries.+ expect(rec.key).toBe('Am');+ // Seed records MUST ship a fixed originInstanceId — see migration 190's test+ // for why (boot backfill would otherwise hash the same seed differently on+ // every peer and defeat the brain reconcile checksum).+ expect(rec.originInstanceId).toBe('seed');+ // The chart must parse clean — a seed with errors would teach the format wrong.+ const chart = parseDrumChart(rec.content.text);+ expect(chart.errors).toEqual([]);+ // 6/8 with one cell per eighth: the meter is the whole point of this+ // arrangement (the other seeds are the same song's arpeggiated 6/8), and the+ // renderer/playback both read `beatValue` as "the tempo counts eighths".+ expect(chart.time).toEqual({ beats: 6, beatValue: 8 });+ expect(chart.subdivision).toBe(1);+ expect(chart.stepsPerBar).toBe(6);+ // Four times through the 8-bar Am-C-D-F-Am-C-E-E progression.+ expect(chart.bars.length).toBe(32);+ expect(chart.bars.some((b) => b.repeat > 1)).toBe(true);+ for (const piece of ['K', 'S', 'HH', 'RD', 'CR']) expect(chart.pieces).toContain(piece);+ // The written tempo counts EIGHTHS, so it is deliberately high — guard the+ // band the practice-tempo control can actually reach (metronome 20–320, and+ // the transport's 110% button multiplies it).+ expect(chart.tempo).toBeGreaterThanOrEqual(180);+ expect(Math.round(chart.tempo * 1.1)).toBeLessThanOrEqual(320);+ });+});diff --git a/scripts/migrations/_brainSeedTestHelpers.js b/scripts/migrations/_brainSeedTestHelpers.jsnew file mode 100644index 0000000000..f4f1572369--- /dev/null+++ b/scripts/migrations/_brainSeedTestHelpers.js@@ -0,0 +1,145 @@+/**+ * Shared test scaffolding for `makeBrainSeedMigration`-based seed migrations.+ * Companion to `./_lib.js`'s brain seed-record family, and the sibling of+ * `./_seedStageTestHelpers.js` (the prompt-stage seed family). The runner skips+ * `_`-prefixed files, so this is never imported as a migration.+ *+ * Every member of the family shares the same contract — write the per-record+ * file on a split install, never overwrite an existing id (edited copy, peer+ * copy, or tombstone), stay idempotent, top up a still-present legacy monolith+ * without ever creating one, and never write over unreadable data. Asserting+ * that once per migration is what makes a config typo (wrong `entityType`, wrong+ * `seedIds`) fail loudly, so the shared cases live here and each migration's+ * `*.test.js` collapses to a `describe` + one `runBrainSeedMigrationTests(…)`+ * call plus its own assertions about the record it actually ships.+ *+ * Fixtures are built in an `mkdtempSync` sandbox with an INVENTED seed record+ * (privacy convention) — the install's real `data/` tree is never touched.+ */++import { it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++/**+ * Run the shared contract for one brain seed migration.+ *+ * - `migration` — the module's default export (`{ up }`)+ * - `number` — migration number, for the sandbox dir name+ * - `entityType` — brain entity type the migration seeds (e.g. `'songs'`)+ * - `seedId` — the id it owns+ * - `record` — an invented stand-in for the shipped record+ * - `otherId` — an unrelated seed id it must NOT touch+ */+export function runBrainSeedMigrationTests({ migration, number, entityType, seedId, record, otherId }) {+ let rootDir;+ let seedDir;+ let perRecordDir;+ let legacyPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), `migration-${number}-`));+ seedDir = join(rootDir, 'data.reference', 'brain');+ perRecordDir = join(rootDir, 'data', 'brain', entityType);+ legacyPath = join(rootDir, 'data', 'brain', `${entityType}.json`);+ mkdirSync(seedDir, { recursive: true });+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ const seeds = { records: { [seedId]: record, [otherId]: { title: 'Other Seed', attachments: [] } } };+ const writeSeed = (obj = seeds) => writeFileSync(join(seedDir, `${entityType}.json`), JSON.stringify(obj, null, 2));+ const recordPath = (id = seedId) => join(perRecordDir, id, 'index.json');+ const writeRecord = (obj, id = seedId) => {+ mkdirSync(join(perRecordDir, id), { recursive: true });+ writeFileSync(recordPath(id), JSON.stringify(obj, null, 2));+ };+ const readRecord = (id = seedId) => JSON.parse(readFileSync(recordPath(id), 'utf-8'));+ const writeLegacy = (obj) => {+ mkdirSync(join(rootDir, 'data', 'brain'), { recursive: true });+ writeFileSync(legacyPath, JSON.stringify(obj, null, 2));+ };+ const readLegacy = () => JSON.parse(readFileSync(legacyPath, 'utf-8'));++ it('writes the per-record file (with parent dirs) on a split install', async () => {+ writeSeed();+ const result = await migration.up({ rootDir });+ expect(result).toMatchObject({ ok: true, reason: 'seeded', added: 1, legacyAdded: 0 });+ expect(readRecord()).toEqual(record);+ // It owns exactly its own id — the other seed is another migration's business.+ expect(existsSync(recordPath(otherId))).toBe(false);+ });++ it('never overwrites an existing id — an edited copy survives', async () => {+ writeSeed();+ writeRecord({ title: 'My Customized Copy', updatedAt: '2026-08-01T00:00:00.000Z' });+ const result = await migration.up({ rootDir });+ expect(result.reason).toBe('already-present');+ expect(readRecord().title).toBe('My Customized Copy');+ });++ it('never resurrects a tombstoned (deliberately deleted) seed', async () => {+ writeSeed();+ writeRecord({ _deleted: true, updatedAt: '2026-08-01T00:00:00.000Z', deletedAt: '2026-08-01T00:00:00.000Z', originInstanceId: 'x' });+ const result = await migration.up({ rootDir });+ expect(result.reason).toBe('already-present');+ expect(readRecord()._deleted).toBe(true);+ });++ it('is idempotent — a second run adds nothing', async () => {+ writeSeed();+ await migration.up({ rootDir });+ const second = await migration.up({ rootDir });+ expect(second).toMatchObject({ reason: 'already-present', added: 0 });+ });++ it('tops up a still-present legacy monolithic file too', async () => {+ writeSeed();+ writeLegacy({ records: { 'user-record-1': { title: 'User Record' } } });+ const result = await migration.up({ rootDir });+ expect(result).toMatchObject({ added: 1, legacyAdded: 1 });+ const live = readLegacy();+ expect(live.records[seedId]).toEqual(record);+ expect(live.records['user-record-1'].title).toBe('User Record');+ expect(live.records[otherId]).toBeUndefined();+ });++ it('never CREATES a legacy file on a split install', async () => {+ writeSeed();+ await migration.up({ rootDir });+ expect(existsSync(legacyPath)).toBe(false);+ });++ it('leaves an existing legacy id alone', async () => {+ writeSeed();+ writeLegacy({ records: { [seedId]: { title: 'Kept' } } });+ const result = await migration.up({ rootDir });+ expect(result.legacyAdded).toBe(0);+ expect(readLegacy().records[seedId].title).toBe('Kept');+ });++ it('NEVER writes over an unreadable record or legacy file', async () => {+ writeSeed();+ mkdirSync(join(perRecordDir, seedId), { recursive: true });+ writeFileSync(recordPath(), '{not json');+ writeLegacy({ records: {} });+ writeFileSync(legacyPath, '{also not json');+ const result = await migration.up({ rootDir });+ expect(result.reason).toBe('already-present');+ // Both corrupt files are byte-for-byte untouched (recoverable by the user).+ expect(readFileSync(recordPath(), 'utf-8')).toBe('{not json');+ expect(readFileSync(legacyPath, 'utf-8')).toBe('{also not json');+ });++ it('no-ops when the seed file is missing or lacks this migration’s id', async () => {+ const missing = await migration.up({ rootDir });+ expect(missing).toMatchObject({ ok: true, reason: 'no-seeds' });+ expect(existsSync(recordPath())).toBe(false);++ writeSeed({ records: { [otherId]: { title: 'Other' } } });+ expect(await migration.up({ rootDir })).toMatchObject({ reason: 'no-seeds' });+ });+}diff --git a/scripts/migrations/_lib.js b/scripts/migrations/_lib.jsindex 5f5e35064e..84a890cbee 100644--- a/scripts/migrations/_lib.js+++ b/scripts/migrations/_lib.js@@ -513,6 +513,132 @@ export async function writeLayoutsDoc(path, doc) {await writeFile(path, JSON.stringify(doc, null, 2));}+// ---- brain seed-record migration family ----+//+// `scripts/setup-data.js` copies `data.reference/` wholesale, so a FRESH install+// picks up every seed record in `data.reference/brain/<type>.json` for free. But+// setup-data only copies MISSING files — an install whose `data/brain/<type>.json`+// already exists (even empty, from the feature's first boot) never receives a+// seed added later. Each such addition therefore ships a migration that merges+// its own ids in; 209 (the drum-format worked example) and 213 (the House of the+// Rising Sun drum arrangement) are the current members.+//+// They all want the same skeleton, so it lives here once:+// - Since migration 200, brain stores live per-record at+// `data/brain/<type>/<id>/index.json` (collectionStore layout) — that's the+// primary write target.+// - The legacy monolithic `data/brain/<type>.json` is ALSO topped up when it's+// still present, so an install whose 200 split hasn't run yet still picks the+// seed up when it finally does. It is never CREATED — doing so on a split+// install would resurrect a shape nothing reads.+// - An id already present — a user-edited copy, a peer-synced copy, or a+// tombstone from a deliberate delete — is NEVER overwritten, so a deleted+// seed stays deleted, and a second run is a no-op.+// - Nothing is written when the existing record (or the legacy file) is+// unreadable: possibly-recoverable user data beats a cosmetic starter record.+//+// Each migration owns an explicit `seedIds` list rather than "everything in the+// reference file", so a later seed addition gets its own migration instead of+// silently riding along on a re-run of an older one.++// Tagged read: 'missing' (ENOENT — nothing there, safe to create) is NOT the+// same as 'invalid' (exists but won't parse — user data a write would destroy).+// The migration runner executes before the service layer is wired, so this can't+// reach for server/lib helpers.+async function seedReadJsonTagged(path) {+ let raw;+ try {+ raw = await readFile(path, 'utf-8');+ } catch (err) {+ return err?.code === 'ENOENT' ? { state: 'missing' } : { state: 'invalid', error: err?.message };+ }+ try {+ return { state: 'ok', doc: JSON.parse(raw) };+ } catch (err) {+ return { state: 'invalid', error: err?.message };+ }+}++const seedFileExists = (path) => stat(path).then(() => true, () => false);++/**+ * Build a brain seed-record migration's `up()`. Returns `{ up }`.+ *+ * - `logTag` — emoji-prefixed log tag, e.g. `'🥁 drum-seed'`+ * - `entityType` — brain entity type, e.g. `'songs'` (names all three paths)+ * - `seedIds` — the record ids THIS migration owns+ * - `seedLabel` — human phrase for the log lines ("the drum example groove")+ * - `storeLabel` — where it lands, for the success line ("the SongBook")+ *+ * Resolves to `{ ok: true, reason: 'no-seeds' | 'already-present' | 'seeded',+ * added, legacyAdded, skipped }`.+ */+export function makeBrainSeedMigration({ logTag, entityType, seedIds, seedLabel, storeLabel }) {+ async function up({ rootDir }) {+ const seedPath = join(rootDir, 'data.reference', 'brain', `${entityType}.json`);+ const perRecordDir = join(rootDir, 'data', 'brain', entityType);+ const legacyPath = join(rootDir, 'data', 'brain', `${entityType}.json`);++ const seedRead = await seedReadJsonTagged(seedPath);+ const seedRecords = seedRead.state === 'ok' && seedRead.doc?.records && typeof seedRead.doc.records === 'object'+ ? seedRead.doc.records+ : {};+ const present = seedIds.filter((id) => seedRecords[id] !== undefined);+ if (present.length === 0) {+ console.log(`${logTag}: no ${seedLabel} in data.reference — no-op.`);+ return { ok: true, reason: 'no-seeds' };+ }++ // --- Per-record store (the post-migration-200 layout) -------------------+ let added = 0;+ let skipped = 0;+ for (const id of present) {+ const recordPath = join(perRecordDir, id, 'index.json');+ const read = await seedReadJsonTagged(recordPath);+ if (read.state !== 'missing') {+ // Present (a user-edited copy / peer copy / tombstone) or unreadable —+ // either way, leave it alone.+ if (read.state === 'invalid') {+ console.error(`❌ ${logTag}: ${id}/index.json is unreadable (${read.error}) — leaving it untouched.`);+ }+ skipped += 1;+ continue;+ }+ await mkdir(join(perRecordDir, id), { recursive: true });+ await writeFile(recordPath, JSON.stringify(seedRecords[id], null, 2) + '\n');+ added += 1;+ }++ // --- Legacy monolithic file (only when it still exists) -----------------+ let legacyAdded = 0;+ if (await seedFileExists(legacyPath)) {+ const legacyRead = await seedReadJsonTagged(legacyPath);+ if (legacyRead.state === 'invalid') {+ console.error(`❌ ${logTag}: data/brain/${entityType}.json exists but is unreadable (${legacyRead.error}) — leaving it untouched.`);+ } else {+ const live = legacyRead.doc && typeof legacyRead.doc === 'object' ? legacyRead.doc : {};+ if (!live.records || typeof live.records !== 'object') live.records = {};+ for (const id of present) {+ if (live.records[id] !== undefined) continue;+ live.records[id] = seedRecords[id];+ legacyAdded += 1;+ }+ if (legacyAdded > 0) await writeFile(legacyPath, JSON.stringify(live, null, 2) + '\n');+ }+ }++ if (added === 0 && legacyAdded === 0) {+ console.log(`${logTag}: ${seedLabel} already present — no-op.`);+ return { ok: true, reason: 'already-present', added: 0, legacyAdded: 0, skipped };+ }++ console.log(`${logTag}: added ${seedLabel} (${added} per-record, ${legacyAdded} legacy) to ${storeLabel}.`);+ return { ok: true, reason: 'seeded', added, legacyAdded, skipped };+ }++ return { up };+}+/*** Build the per-subdir prompt-drift tables that `scripts/setup-data.js` uses* for its "pending migration" warning by sweeping every numbered migration's