Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Rebuild unlisted Art and Music as project authoring tools (#128)

Deea940c824b450
diff --git a/.github/workflows/experience-checks.yml b/.github/workflows/experience-checks.yml
index 233f3ae1c..803eac0f5 100644
--- a/.github/workflows/experience-checks.yml
+++ b/.github/workflows/experience-checks.yml
@@ -33,3 +33,26 @@ jobs:
run: node store/tools/catalog.mjs
- name: Check FreeCAD contracts and delivery (native suite is opt-in)
run: node --test store/agents/freecad/test/*.test.mjs
+
+ authoring-browser:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
+ with:
+ node-version: '22.23.2'
+ - name: Install pinned browser tools
+ run: |
+ npm ci --prefix store/tools/experience-tests --ignore-scripts --no-audit --no-fund
+ node store/tools/experience-tests/node_modules/playwright-core/cli.js install --with-deps chromium
+ node -e 'require("fs").appendFileSync(process.env.GITHUB_ENV, "BROWSER_EXECUTABLE=" + require("./store/tools/experience-tests/node_modules/playwright-core").chromium.executablePath() + "\n")'
+ - name: Edit real projects and reopen their exports
+ env:
+ EXPERIENCE_IDS: generative-art,music-studio
+ run: node store/tools/experience-tests/browser.mjs
+ - name: Verify MIDI and aligned audio with independent readers
+ run: |
+ python3 -m venv /tmp/music-delivery-reader
+ /tmp/music-delivery-reader/bin/pip install mido==1.3.3
+ /tmp/music-delivery-reader/bin/python store/tools/experience-tests/verify-music-delivery.py work/experience-evidence/afterhours-production.zip
diff --git a/HANDOFF.md b/HANDOFF.md
index a841b4b0a..5f7e23709 100644
--- a/HANDOFF.md
+++ b/HANDOFF.md
@@ -3,6 +3,14 @@
Work in `/private/tmp/harness-store-voxel`, branch `codex/harness-store-voxel`.
The main checkout is shared with other sessions; leave it alone.
+**Current authoring rebuild:** read [AUTHORING-REBUILD.md](work/AUTHORING-REBUILD.md). Art and Music
+now use source under their own `template/studio/` directories, with real editable projects and
+production exports. `build-experiences.mjs` delegates to their builders. Their original preset
+sources remain under `store/tools/experiences/` for history; they no longer generate these two
+packages. Setup now installs pinned package-local browser tools. Both listings remain withdrawn;
+musical listening and real-user/installed-engine authoring trials are outstanding. The earlier
+seven-starter description below is historical and must not be presented as the new product bar.
+
**Product reset, 2026-09-20:** the user rejected preset and spectator experiences as the wrong
product. All seven below are withdrawn from discovery with `listed:false`. Read
[the new review and return-to-Store gates](work/SUPERPOWERS.md) before continuing. Focus only on
diff --git a/desktop/lib/widgets/engine_identity.dart b/desktop/lib/widgets/engine_identity.dart
index 58acb072a..11488d186 100644
--- a/desktop/lib/widgets/engine_identity.dart
+++ b/desktop/lib/widgets/engine_identity.dart
@@ -236,7 +236,7 @@ const _harnesses = <String, EngineIdentity>{
id: 'autonomous/generative-art',
label: 'Generative Art',
category: 'Original art',
- tagline: 'Design reproducible generative editions',
+ tagline: 'Turn a visual brief into editable artwork and complete asset sets',
creator: 'Autonomous',
color: Color(0xffce7645),
asset: 'assets/engine-icons/generative-art.png',
@@ -245,7 +245,7 @@ const _harnesses = <String, EngineIdentity>{
id: 'autonomous/music-studio',
label: 'Music Studio',
category: 'Audio',
- tagline: 'Compose a seeded eight-bar track, edit five instrument patterns, shape swing and',
+ tagline: 'Compose original music with editable notes, audio and stems for your DAW',
creator: 'Autonomous',
color: Color(0xffd6c7e9),
asset: 'assets/engine-icons/music-studio.png',
diff --git a/store/agents/generative-art/.gitignore b/store/agents/generative-art/.gitignore
new file mode 100644
index 000000000..00758e57d
--- /dev/null
+++ b/store/agents/generative-art/.gitignore
@@ -0,0 +1,4 @@
+toolchain/node_modules/
+toolchain/browsers/
+template/.harness/
+template/delivery/
diff --git a/store/agents/generative-art/AGENTS.md b/store/agents/generative-art/AGENTS.md
index 83527fecb..0948bc298 100644
--- a/store/agents/generative-art/AGENTS.md
+++ b/store/agents/generative-art/AGENTS.md
@@ -1,67 +1,56 @@
-# Generative Art harness
-
-You turn a plain-English description into a **deterministic, seedable generative artwork** in a
-single self-contained `sketch/index.html`. The pane loads it live, so the user sees the piece —
-and a re-seed — as you work.
-
-## What a good piece is
-
-- **One file, offline.** All rendering inline (canvas 2D, p5-style loops, or WebGL/WebGPU
- shaders) — no CDN at runtime. A `?seed=` query param selects the version: the same seed always
- renders the same frame on this machine.
-- **Determinism is the product.** The whole point is that a piece is *reproducible*: seed a PRNG,
- name sub-streams (per shape, per color), and render the same composition at 400px and 4000px.
- If a sketch cannot render the same seed twice, it is not finished.
-- **Be honest about what verification can and cannot prove.** Same-machine reproducibility and
- perceptual stability across sizes are checkable. Cross-machine determinism in WebGL/JS is *not*
- guaranteed (shader compilers, float precision, rasterizers differ). Say so in the verdict rather
- than overclaiming.
-- **Specific briefs beat vibes.** "sand dunes with a low sun, four compositions in a series, seed
- ranges 0–99" beats "something cool and generative."
-
-## How to work so the pane moves
-
-1. **Save within a minute.** Materialize `sketch/index.html` rendering a trivial seeded frame
- (a gradient plus one seeded shape), so the header has a state and the pane can load it.
-2. **Build the system, then the piece.** First get the seeded-PRNG + render-at-any-size plumbing
- right; only then tune the composition, palette, and motion.
-3. **Verify like a visitor:** load the file with a few seeds, screenshot from the actual output
- (not the editor), look, adjust, re-render. The camera/output is the referee.
-4. **Update `.harness/verdict.json` at every check and phase change** — `ready`, one-line
- `summary`, `phases`, `findings`, and a reproducibility note. Write it as a feed.
-
-## Rules
-
-- An edition is only "ready to mint/print" when the rarity table and the census agree — sample a
- grid of seeds and confirm no degenerate seed (blank, blown-out, same-as-everything) hides in the
- range you claim to support.
-- Tag every crafted decision USER vs AI in `sketch/DESIGN.md`
- (`YYYY-MM-DD | USER|AI | topic | decision | still in build?`).
-- The `summary` says plainly what is reproducible now and what is not. Never claim "done" on a
- piece you haven't re-rendered seed-for-seed.
-
-## Shipped experience and operating standard
-
-The workspace starts with **Fieldwork**, a working experience, not an empty placeholder.
-Three techniques, named random streams, palette selection, density/tension controls, nearby seed previews, high-resolution PNG export.
-
-- Read the existing artifact before replacing it. The useful model boundaries are artModel, artPaths, drawArt, logical print coordinates.
-- Preserve working interactions and exports when extending the artifact. Match the user's brief;
- the starter's genre and visual style are examples, not a ceiling.
-- Expose meaningful domain controls and outputs. Every control must change real state; every
- displayed metric must be computed from that state. Never invent model activity or test results.
-- Use named random streams and a fixed simulation/score clock. Sample seeds, repeat the same
- seed, inspect exported data, and verify keyboard/touch controls in the actual viewer.
-- This HTML runs with same-origin APIs in the shared viewer. Sibling fetches, localStorage,
- downloads and pointer lock are available. Keep files portable and support direct opening.
-- Do not equate an existing HTML file, a successful reload, or a source-string test with a usable
- result. `seed-verdict.sh` deliberately keeps `ready:false`; write `ready:true` only after your
- checks establish it. Record exact commands, sampled seeds, observations and limitations.
-- Never claim a test coverage percentage for browser code based on Node subprocess tests.
-
-## Check your actual edited model
-
-Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from
-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and
-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are
-followed by browser interaction, exported-output inspection, and visual or listening review.
+# Generative Art — an authoring tool, not a style picker
+
+Turn the person's idea into original visual work they can use. They should not need to draw,
+program, or accept the look of our example. The workspace is a small production studio whose
+**drawing program, controls, assets and deliverables belong to the brief**.
+
+Read `skills/gen-art/SKILL.md`. Start by reading `sketch/project.json` and `sketch/artwork.js`.
+The Night Garden festival is an example output, not the product or a default style to preserve.
+Replace its drawing system for a different brief. Do not simply recolor or reseed it.
+
+## Work from the real task
+
+1. Identify the thing the person will actually use: a print edition, packaging graphic, identity
+ assets, an illustration, a visual explanation, a pattern or a set of social assets. Use their
+ actual words, data and images. Ask only for material that is necessary and missing.
+2. Create a visual system appropriate to that task. Write new geometry in `sketch/artwork.js`;
+ it is arbitrary JavaScript producing SVG, not an enum of techniques. Expose the meaningful
+ decisions in `sketch/project.json`: text, colors, dimensions, ranges, toggles and image slots.
+3. Compose each requested format. A wide banner needs a different layout from a portrait, not
+ a stretched poster. Keep important text editable, allow safe margins and respect long titles.
+4. Run `node tools/build.mjs`. The pane reloads with the user's project and its own controls.
+5. Run `node tools/export.mjs --seeds 3`. It exports every named format as real SVG and PNG,
+ an editable project and a portable studio into `delivery/`, plus a verification report.
+6. **Inspect those files.** Open the actual exported images, look at every format, check their
+ text and composition against the request, fix defects, then export again. A deterministic
+ program can produce bad art. A successful build is never a ready verdict.
+7. Deliver the files and explain one useful next revision. Record user decisions and unresolved
+ limitations in `sketch/DESIGN.md`. Update `.harness/verdict.json` honestly.
+
+## Revisions and continuity
+
+Preserve user-approved text, uploaded assets, dimensions and choices when revising. A new creative
+request may justify a new program; a request to move a logo does not justify replacing everything.
+The studio autosaves controls locally, has undo/redo, and can save a complete `.fieldwork.json`.
+Browser drafts are not automatically written into source files. To incorporate a saved project,
+run `node tools/import-project.mjs path/to/project.fieldwork.json` before editing. This keeps a
+source backup in `.harness/history/`. Do not pretend to have read edits you cannot access.
+
+When source changes and a browser draft exists, the studio offers the new version or the saved
+draft. The old draft must not silently overwrite a new agent revision or disappear during reload.
+
+## What this tool can and cannot deliver
+
+- Arbitrary static SVG illustration and procedural geometry; real text, embedded images, named
+ formats, editable vectors, PNGs, project source, portable HTML and reproducible SVG editions.
+- The agent writes code; the person uses the studio and speaks in the Harness chat. Do not make
+ them use a code editor. There is no fake AI prompt box or hidden remote generation service.
+- SVG is RGB artwork, not a print shop's CMYK, bleed, font-outline or color-profile guarantee.
+ Use the user's print specification or explain the remaining production step.
+- System-font text can change on another computer. Use compatible installed fonts and verify on
+ the target system, or explicitly arrange an outlined/embedded-font delivery when needed.
+- Do not call this photo generation, a video editor, or a complete branding service. For a task
+ that needs other real tools, integrate and verify those tools; don't simulate their output.
+
+The Store listing remains withdrawn during this rebuild. Product acceptance and the evidence
+required for relisting are in `work/SUPERPOWERS.md` in the source repository.
diff --git a/store/agents/generative-art/README.md b/store/agents/generative-art/README.md
index 2b6f3fc3e..710572a82 100644
--- a/store/agents/generative-art/README.md
+++ b/store/agents/generative-art/README.md
@@ -1,60 +1,50 @@
# Generative Art — Fieldwork
-> Withdrawn from Store discovery on 2026-09-20: the current starter does not meet our
-> standard for an open-ended tool that completes real user work. Existing projects and
-> source remain available. See [the product review](../../../work/SUPERPOWERS.md).
+> Unlisted while the authoring rebuild is validated. Code and existing projects remain available.
+> See [the product review](../../../work/SUPERPOWERS.md).
![Generative Art logo](brand/logo.svg)
-Design reproducible generative editions. Explore contour fields, dunes and orbital studies, tune their geometry and palettes, and export prints up to 3200 × 4000.
+Describe original visual work in the Harness chat. The agent creates its drawing system, controls
+and delivery formats. The studio lets you revise the result and export real files. You are not
+limited to a menu of drawing styles.
-## Try it
+For example: “Create packaging illustrations for my coffee roastery using my logo. I need a
+portrait bag label, a square announcement and a wide shop banner. Make it feel like a woodcut.”
-> Create an edition of 12 tidal contour prints in indigo and burnt orange. Keep the paper quiet and make each seed feel related but distinct.
+## Workflow
-The starter already works before the first prompt. Change it with the agent, interact with the
-result in the pane, and keep the output. Everything needed at runtime is in `sketch/index.html`.
-It works offline and can be opened outside Harness.
+The agent writes `sketch/project.json` and `sketch/artwork.js`, then builds `sketch/index.html`.
+You can change the controls created for your project, import your own images, undo/redo, change
+artboards and explore seeds. Browser drafts survive reload and are kept separate from new agent
+revisions. Save a `.fieldwork.json` to move your edits between sessions or attach them to the agent.
-## What you can do
+Export SVG for vector editors, PNG for publishing, all named formats as a ZIP, a seeded vector
+edition, or a complete studio you can open without Harness. The editable project includes the
+program and embedded images. There is no remote generation service or additional AI subscription.
+The agent uses the coding-engine account already configured in Harness.
-Three techniques, named random streams, palette selection, density/tension controls, nearby seed previews, high-resolution PNG export.
+## Authoring and verification
-## Build on the starter
+```sh
+node tools/build.mjs
+node tools/check.mjs
+node tools/export.mjs --seeds 3
+node tools/import-project.mjs path/to/saved.fieldwork.json
+```
-The model functions `artModel` and `artPaths` are the starting points for substantive changes. Preserve seed
-reproducibility and user controls while changing the domain behavior. A different brief can replace
-this starter's entire visual language. Keep the artifact self-contained and test the actual result.
+Setup installs pinned Playwright in the package for the agent's production exports. It uses local
+Chrome when available; otherwise it installs Chromium locally. Node.js 20+ and npm are required.
+The resulting HTML studio itself works offline without those tools.
-The source checkout builds these starters with `node store/tools/build-experiences.mjs`. Installed
-workspaces are editable HTML; no build tool, network dependency or paid service is required.
-
-## Verification
-
-Model census: `node --test store/tools/experience-tests/models.test.mjs` from the source checkout.
-Browser interactions, exports, same-origin APIs and manifest routing: see
-[`store/tools/experience-tests`](../../tools/experience-tests/README.md).
-
-`seed-verdict.sh` establishes only artifact presence and keeps `ready:false`. The agent must run
-and record real domain and browser checks before writing a ready verdict. No cross-device pixel or
-audio equality is promised. The research is inspiration; this is original code, not a wrapper of
-any cited third-party engine.
-
-## Check your actual edited model
-
-Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from
-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and
-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are
-followed by browser interaction, exported-output inspection, and visual or listening review.
-
-## Logo and icon
-
-The original identity ships in `brand/`: [vector icon](brand/icon.svg),
-[256px PNG](brand/icon.png), [light logo](brand/logo.svg) and
-[dark logo](brand/logo-dark.svg). The same mark appears in the starter header,
-its offline favicon and the desktop Store/picker/tabs. MIT, by OpenHarness contributors.
+The exporter repeats the actual drawing program, checks PNG dimensions and preserves source and
+verification reports. Visual review and matching the brief remain required; a build never marks
+an artifact ready. SVG uses editable system-font text, whose appearance may differ on another
+machine. Output is RGB, not certified press-ready CMYK. This is a static vector authoring tool,
+not photo or video generation.
## Credit and stewardship
-Original implementation and visual identity by OpenHarness contributors, maintained by
-Autonomous under the [MIT license](LICENSE). Report issues in the OpenHarness repository.
+Original implementation and identity by OpenHarness contributors, maintained by Autonomous under
+the [MIT license](LICENSE). Playwright is a separate Apache-2.0 dependency by Microsoft. Branding
+sources remain in `brand/`. Report issues in the OpenHarness repository.
diff --git a/store/agents/generative-art/examples/README.md b/store/agents/generative-art/examples/README.md
new file mode 100644
index 000000000..b25285865
--- /dev/null
+++ b/store/agents/generative-art/examples/README.md
@@ -0,0 +1,13 @@
+# Original visual systems
+
+Night Garden in the template, Canopy Coffee here and A Year of Rain here each have a separately
+authored drawing program. They demonstrate changing the visual language, controls, inputs and
+output composition for a brief. They are acceptance fixtures, not a menu limiting future projects.
+
+In a fresh workspace, copy an example's `project.json`, `artwork.js` and assets into `sketch/`, then
+build/export with the workspace tools. Preserve existing work before replacing its source.
+
+Canopy embeds an original logo fixture and editable product details. It is artwork, not a compliant
+packaging dieline. The data atlas consumes pasted `label,value` rows and labels its ring scale and
+order; its sample observations are explicitly invented. Use the person's actual data in real work.
+All three examples have separately composed portrait, square and wide formats.
diff --git a/store/agents/generative-art/examples/coffee/artwork.js b/store/agents/generative-art/examples/coffee/artwork.js
new file mode 100644
index 000000000..6d281f1e7
--- /dev/null
+++ b/store/agents/generative-art/examples/coffee/artwork.js
@@ -0,0 +1,33 @@
+const {el, text}=svg, w=width,h=height,wide=w/h>1.6,square=!wide&&w/h>.85,base=Math.min(w,h),pad=base*.065,r=rng('engraving');
+const out=[el('rect',{width:w,height:h,fill:values.paper})];
+const ink={fill:values.ink,'font-family':'Georgia, serif'};
+out.push(el('rect',{x:pad*.6,y:pad*.6,width:w-pad*1.2,height:h-pad*1.2,fill:'none',stroke:values.ink,'stroke-width':base*.002}));
+function leaf(x,y,size,angle){
+ const leaf=[];
+ leaf.push(el('path',{d:`M0 0 C${-size*.8} ${-size*.4},${-size*.35} ${-size*1.15},0 ${-size*1.6} C${size*.65} ${-size*.9},${size*.65} ${-size*.2},0 0Z`,fill:values.ink}));
+ leaf.push(el('path',{d:`M0 0Q${size*.04} ${-size*.7},0 ${-size*1.48}`,fill:'none',stroke:values.paper,'stroke-width':size*.022}));
+ for(let i=1;i<values.detail;i++){
+ const t=i/values.detail,yy=-size*1.48*t,extent=Math.sin(t*Math.PI)*size*.33;
+ leaf.push(el('path',{d:`M0 ${yy} Q${-extent*.5} ${yy+size*.12},${-extent} ${yy+size*.20} M0 ${yy} Q${extent*.5} ${yy+size*.08},${extent} ${yy+size*.16}`,fill:'none',stroke:values.paper,'stroke-width':size*.009}));
+ }
+ return el('g',{transform:`translate(${x} ${y}) rotate(${angle})`},leaf);
+}
+const cx=wide?w*.73:w*.51,cy=wide?h*.70:square?h*.66:h*.62,size=base*(square?.14:.20);
+let branch=el('path',{d:`M${cx} ${cy} Q${cx-size*.5} ${cy-size*.6},${cx+size*.2} ${cy-size*2}`,fill:'none',stroke:values.ink,'stroke-width':size*.028});
+for(let i=0;i<5;i++){
+ const y=cy-i*size*.36,x=cx+Math.sin(i)*size*.10;
+ branch+=leaf(x,y,size*(.63+r()*.2),(i%2?-1:1)*(45+r()*22));
+ if(i<4){branch+=el('circle',{cx:x+size*.16,cy:y-size*.10,r:size*.09,fill:values.accent});branch+=el('circle',{cx:x+size*.27,cy:y-size*.17,r:size*.075,fill:values.accent});}
+}
+out.push(branch);
+const textX=wide?w*.09:w/2,anchor=wide?'start':'middle',font=Math.min(base*(square?.12:.14),(wide?w*.48:w*.82)/Math.max(values.brand.length,1)*1.4);
+out.push(text('SMALL LOT / SLOW ROASTED',{...ink,x:textX,y:h*(wide?.25:square?.09:.10),'text-anchor':anchor,'font-family':'Arial, sans-serif','font-size':base*.014,'letter-spacing':base*.003}));
+out.push(text(values.brand,{...ink,x:textX,y:h*(wide?.41:square?.23:.20),'text-anchor':anchor,'font-size':font,'letter-spacing':-font*.06}));
+out.push(text('COFFEE ROASTERS',{...ink,x:textX,y:h*(wide?.47:square?.28:.235),'text-anchor':anchor,'font-family':'Arial, sans-serif','font-size':base*.017,'letter-spacing':base*.004}));
+const y=h*(wide?.65:square?.79:.76);
+out.push(text(values.origin,{...ink,x:textX,y,'text-anchor':anchor,'font-family':'Arial, sans-serif','font-size':base*.025,'font-weight':700}));
+out.push(text(values.lot,{...ink,x:textX,y:y+base*.048,'text-anchor':anchor,'font-family':'Arial, sans-serif','font-size':base*.017}));
+out.push(text(values.tasting,{...ink,x:textX,y:y+base*.093,'text-anchor':anchor,'font-family':'Arial, sans-serif','font-size':base*.012,'letter-spacing':base*.0007}));
+out.push(text(values.weight,{...ink,x:w-pad,y:h-pad,'text-anchor':'end','font-size':base*.023}));
+if(assets.logo)out.push(el('image',{href:assets.logo,x:pad,y:h-pad-base*.07,width:base*.07,height:base*.07}));
+return out.join('');
diff --git a/store/agents/generative-art/examples/coffee/logo.svg b/store/agents/generative-art/examples/coffee/logo.svg
new file mode 100644
index 000000000..160cb798a
--- /dev/null
+++ b/store/agents/generative-art/examples/coffee/logo.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><path d="M50 8 90 84H10Z" fill="none" stroke="#273c35" stroke-width="4"/><path d="M50 66V35m0 17C28 53 27 28 27 28c23 0 23 24 23 24Zm0 7c24-1 25-24 25-24-24 0-25 24-25 24Z" fill="#273c35"/></svg>
diff --git a/store/agents/generative-art/examples/coffee/project.json b/store/agents/generative-art/examples/coffee/project.json
new file mode 100644
index 000000000..cce568cba
--- /dev/null
+++ b/store/agents/generative-art/examples/coffee/project.json
@@ -0,0 +1,19 @@
+{
+ "spec": "fieldwork/1", "id": "canopy-coffee", "title": "Canopy Coffee",
+ "brief": "Create a woodcut-inspired packaging identity for Canopy Coffee, using our own logo. Deliver a portrait bag label, a square launch card and a wide shop banner. Preserve editable product details and embed the logo in every deliverable.",
+ "notes": "Acceptance brief authored for this rebuild. The botanical illustration is original procedural vector geometry; this is not a label-compliance or dieline guarantee.",
+ "seed": "canopy-01",
+ "formats": [{ "name": "Bag label", "width": 1000, "height": 1500 }, { "name": "Launch card", "width": 1200, "height": 1200 }, { "name": "Shop banner", "width": 2000, "height": 800 }],
+ "controls": [
+ { "key": "brand", "type": "text", "label": "Roastery", "value": "CANOPY" },
+ { "key": "origin", "type": "text", "label": "Origin", "value": "SIERRA NEVADA · COLOMBIA" },
+ { "key": "lot", "type": "text", "label": "Coffee", "value": "LOT 042 / WASHED CATURRA" },
+ { "key": "tasting", "type": "text", "label": "Tasting notes", "value": "COCOA · ORANGE BLOSSOM · HONEY" },
+ { "key": "weight", "type": "text", "label": "Net weight", "value": "250 g" },
+ { "key": "paper", "type": "color", "label": "Stock", "value": "#e9e1c7" },
+ { "key": "ink", "type": "color", "label": "Print ink", "value": "#273c35" },
+ { "key": "accent", "type": "color", "label": "Lot mark", "value": "#b3432d" },
+ { "key": "detail", "type": "range", "label": "Engraving detail", "min": 6, "max": 28, "value": 18 }
+ ],
+ "assets": [{ "key": "logo", "label": "Roastery logo", "file": "logo.svg" }]
+}
diff --git a/store/agents/generative-art/examples/data-atlas/artwork.js b/store/agents/generative-art/examples/data-atlas/artwork.js
new file mode 100644
index 000000000..c798211c4
--- /dev/null
+++ b/store/agents/generative-art/examples/data-atlas/artwork.js
@@ -0,0 +1,27 @@
+const {el,text}=svg,w=width,h=height,wide=w/h>1.5,square=!wide&&w/h>.85,base=Math.min(w,h),pad=base*.075;
+const rows=values.csv.trim().split(/\r?\n/).filter(Boolean).map(line=>{const cells=line.split(',');return {label:cells[0]?.trim(),value:cells.length===2&&cells[1].trim()?Number(cells[1]):NaN};});
+if(rows.length<2||rows.length>24||rows.some(r=>!r.label||!Number.isFinite(r.value)||r.value<0))throw new Error('Use 2–24 CSV rows: month, non-negative rainfall in mm.');
+const max=Math.max(...rows.map(r=>r.value),1),scale=Math.ceil(max/50)*50,total=rows.reduce((n,r)=>n+r.value,0),cx=wide?w*.35:w*.5,cy=wide?h*.52:square?h*.40:h*.44;
+const columns=wide?3:Math.min(6,rows.length),numberY=wide?h*.61:h-pad*.5-(Math.ceil(rows.length/columns)-1)*base*.026;
+const tx=wide?w*.67:pad,ty=wide?h*.40:numberY-base*.188,legendY=wide?ty+base*.16:numberY-base*.03;
+const radius=Math.min(base*(wide?.35:square?.29:.36),wide?Infinity:ty-base*.1-cy),gap=radius/(rows.length+2),parts=[el('rect',{width:w,height:h,fill:values.paper})];
+const type={fill:values.ink,'font-family':'Arial, Helvetica, sans-serif'};
+parts.push(text('OBSERVATION / 001',{...type,x:pad,y:pad,'font-size':base*.014,'letter-spacing':base*.003}));
+parts.push(text(values.place,{...type,x:w-pad,y:pad,'text-anchor':'end','font-size':base*.013,'letter-spacing':base*.001}));
+for(let i=0;i<rows.length;i++){
+ const row=rows[i],r=(i+2)*gap,fraction=row.value/scale,start=-Math.PI/2,end=start+fraction*Math.PI*2;
+ const x=cx+Math.cos(end)*r,y=cy+Math.sin(end)*r,stroke=gap*values.ring/100;
+ parts.push(el('circle',{cx,cy,r,fill:'none',stroke:values.ink,'stroke-opacity':.09,'stroke-width':stroke}));
+ const style={fill:'none',stroke:values.accent,'stroke-width':stroke,'stroke-linecap':'round',opacity:.35+.65*i/Math.max(rows.length-1,1)};
+ if(fraction===1)parts.push(el('circle',{cx,cy,r,...style}));
+ else if(row.value>0)parts.push(el('path',{d:`M${cx} ${cy-r} A${r} ${r} 0 ${fraction>.5?1:0} 1 ${x} ${y}`,...style}));
+}
+parts.push(text('A YEAR',{...type,x:tx,y:ty,'font-size':base*.077,'font-weight':500,'letter-spacing':-base*.004}));
+parts.push(text('OF RAIN.',{...type,x:tx,y:ty+base*.078,'font-size':base*.077,'font-weight':500,'letter-spacing':-base*.004}));
+parts.push(text(`${total.toFixed(0)} MM / ${rows.length} OBSERVATIONS`,{...type,x:tx,y:ty+base*.123,'font-size':base*.016,'letter-spacing':base*.001}));
+parts.push(text(`INNER TO OUTER: CSV ORDER / FULL RING = ${scale} MM`,{...type,x:tx,y:legendY,'font-size':base*.009,'letter-spacing':base*.0002}));
+if(values.numbers){
+ const startX=wide?tx:pad,startY=numberY,colW=wide?base*.13:(w-pad*2)/columns;
+ rows.forEach((row,i)=>parts.push(text(`${row.label.toUpperCase()} ${row.value}`,{...type,x:startX+i%columns*colW,y:startY+Math.floor(i/columns)*base*.026,'font-size':base*.011,'font-family':'monospace'})));
+}
+return parts.join('');
diff --git a/store/agents/generative-art/examples/data-atlas/project.json b/store/agents/generative-art/examples/data-atlas/project.json
new file mode 100644
index 000000000..315829ae3
--- /dev/null
+++ b/store/agents/generative-art/examples/data-atlas/project.json
@@ -0,0 +1,17 @@
+{
+ "spec": "fieldwork/1", "id": "rain-atlas", "title": "A Year of Rain",
+ "brief": "Turn my monthly observations into a restrained data-art print: twelve concentric calendar rings, with rainfall controlling each arc. Include the actual values and the place. Deliver a wall print, a square card and a landscape legend, using my pasted CSV rather than synthetic numbers.",
+ "notes": "The example CSV is an explicitly invented acceptance fixture. Replace it with your observations. The artwork shows the supplied values without claiming these are historical measurements.",
+ "seed": "atlas-1", "variations": false,
+ "formats": [{ "name": "Wall print", "width": 1400, "height": 1800 }, { "name": "Square card", "width": 1200, "height": 1200 }, { "name": "Landscape", "width": 2000, "height": 1000 }],
+ "controls": [
+ { "key": "place", "type": "text", "label": "Place and year", "value": "FIELD STATION / 2026" },
+ { "key": "csv", "type": "text", "label": "Your observations (month, mm)", "multiline": true, "value": "Jan,42\nFeb,65\nMar,81\nApr,124\nMay,201\nJun,175\nJul,142\nAug,98\nSep,131\nOct,192\nNov,86\nDec,51" },
+ { "key": "paper", "type": "color", "label": "Background", "value": "#102333" },
+ { "key": "ink", "type": "color", "label": "Ink", "value": "#e8e4d6" },
+ { "key": "accent", "type": "color", "label": "Water", "value": "#7ad2d0" },
+ { "key": "ring", "type": "range", "label": "Ring thickness", "min": 20, "max": 85, "value": 55 },
+ { "key": "numbers", "type": "toggle", "label": "Show observations", "value": true }
+ ],
+ "assets": []
+}
diff --git a/store/agents/generative-art/harness.json b/store/agents/generative-art/harness.json
index 5ac15753d..6cf996dc2 100644
--- a/store/agents/generative-art/harness.json
+++ b/store/agents/generative-art/harness.json
@@ -4,7 +4,7 @@
"name": "Generative Art",
"category": "Original art",
"author": "Autonomous",
- "description": "Design reproducible generative editions. Explore contour fields, dunes and orbital studies, tune their geometry and palettes, and export prints up to 3200 \u00d7 4000.",
+ "description": "Turn your brief into original vector artwork with its own drawing program and controls. Use your text, images and data; revise multiple layouts; export SVG, PNG, editions and complete editable projects.",
"engine": "claude",
"workspace": {
"template": "template",
diff --git a/store/agents/generative-art/skills/gen-art/SKILL.md b/store/agents/generative-art/skills/gen-art/SKILL.md
index 5ace724d9..85b596801 100644
--- a/store/agents/generative-art/skills/gen-art/SKILL.md
+++ b/store/agents/generative-art/skills/gen-art/SKILL.md
@@ -1,72 +1,77 @@
---
name: gen-art
-description: Build a deterministic, seedable generative artwork in one HTML file from a plain-English description. Use whenever the user asks for a generative piece, an edition, a flow field, a shader, a seedable series, or prompt-to-art.
+description: Create original vector artwork and complete visual asset sets from a person's brief, with custom drawing programs, user-editable controls and real SVG/PNG/source delivery.
---
-# gen-art
+# Original work from a brief
-Take the user's description and produce a **single self-contained `sketch/index.html`** that renders
-a **deterministic, seedable** generative artwork, loading the seed from a `?seed=` query param so
-the web-viewer can preview the current seed and re-seed live.
+The studio is infrastructure. The program is the art. Never restrict a new brief to the example's
+flowers, palette or layout. Build the new system in these files:
-## The floor (in order)
+- `sketch/project.json`: `spec: "fieldwork/1"`, a stable lowercase `id`, title, brief, seed,
+ named `formats` with width/height in pixels, `controls`, and optional image `assets`.
+- `sketch/artwork.js`: JavaScript function body returning SVG children as a string.
+- `sketch/DESIGN.md`: the brief, decisions, requested deliverables, revisions and evidence.
+- `studio/`: reusable UI and runtime. Change it only when the task needs a new authoring capability.
-1. **Seeded PRNG.** A small seeded PRNG (mulberry32 / sfc32) derived from the hash of the seed
- string. Nothing may call a non-seeded random — the sketch must be reproducible.
-2. **Render-at-any-size.** The composition is defined in logical units and scaled; the same seed
- renders at 400px preview and 4000px print. High-DPI (devicePixelRatio) aware.
-3. **`?seed=` plumbing.** Reading the param, plus a tiny UI (input + "re-seed" button) so the user
- can browse seeds in the pane.
-4. **Named sub-streams.** One PRNG sub-stream per concern (composition, palette, detail) so tuning
- one doesn't reshuffle the other.
+## Renderer contract
-## The gold checklist
+The function receives `width`, `height`, `seed`, `values`, `assets`, `rng` and `svg`.
+`rng('named-stream')` returns a stable random-number function. Never use time or `Math.random()`
+for the geometry. `values` contains the current control values; `assets.name` is an embedded image
+URL or an empty string. `svg.el(tag, attributes, children)` and `svg.text(text, attributes)` escape
+attributes and text. The latter is essential for the person's real text (including `&` and `<`).
-- **Trait + rarity tables that survive an edition**: a deterministic mapping from seed → traits
- (palette, layout, density), and a census that proves no hidden degenerate seed.
-- **Palette discipline**: OKLCH/OKLab ramps or a seeded palette-from-image; grain/dither as taste.
-- **Style range**: flow fields, packing, reaction-diffusion, attractors, raymarched shaders,
- Islamic/polar patterns — matched to the brief, not all at once.
-- **Export routes**: a `?seed=X&size=4000` render for print, a video-loop-friendly static repaint.
-- Motion (if the brief wants it) should be seed-stable and respect `prefers-reduced-motion`.
-
-## Verify like a visitor, not a compiler
-
-Render a grid of seeds, screenshot the actual output, and look. Two hard checks before "ready":
-- **Re-render same-seed** and diff — it must be byte-perceptually stable on this machine.
-- **Census the seed range you promise** (e.g. 0–99); reject any blank/blown-out/duplicate frame.
-
-Be explicit in the verdict about the reproducibility guarantee: same-machine yes; *cross*-machine
-for WebGL you cannot prove — say so.
-
-## Verdict feed
-
-Write `.harness/verdict.json` at every change:
-
-```json
-{ "spec": 1, "ready": false, "summary": "seeded flow field · re-seed live · census 0–99 clean",
- "findings": [{ "severity": "info", "kind": "reproducibility", "message": "same-machine verification pending; cross-machine WebGL not provable" }],
- "artifact": "sketch/index.html",
- "phases": [{ "id": "seed", "name": "Seeded core", "state": "done" },
- { "id": "piece", "name": "The piece", "state": "active" },
- { "id": "edition", "name": "Edition", "state": "pending" }],
- "updatedAt": "2026-09-18T00:00:00Z" }
+```js
+const r = rng('constellation');
+const marks = Array.from({length: values.stars}, () => svg.el('circle', {
+ cx: r() * width, cy: r() * height, r: 1 + r() * 4, fill: values.ink
+}));
+return svg.el('rect', {width, height, fill: values.paper}) + marks.join('');
```
-## Starting from Fieldwork
-
-The template is functional: Three techniques, named random streams, palette selection, density/tension controls, nearby seed previews, high-resolution PNG export.
+That tiny example illustrates the contract, not an acceptable finished commission. Use original
+composition and domain-appropriate detail. The full SVG vocabulary is available, including paths,
+gradients, masks, clipping, patterns, groups, transforms, typography and embedded images.
+Rendering runs in a worker with a five-second limit; keep it responsive. A render error preserves
+what was visible and disables stale exports until the drawing works again.
+
+## Project controls and assets
+
+A control has `key`, `label`, `type`, `value`. Types:
+- `text`, optionally `multiline: true`; can also hold user-pasted CSV/JSON interpreted by the program.
+- `color`: six-digit hex.
+- `range`: `min`, `max`, optional positive `step`.
+- `select`: string `options`.
+- `toggle`: boolean.
+
+Use at most 40 meaningful controls, not a wall of arbitrary knobs. Formats are 64–8192 pixels per
+side. PNGs are bounded to 32 megapixels. Every control must visibly affect the intended part.
+An asset has `key`, `label`, optional `file` relative to `sketch/`. The builder embeds PNG/JPEG/WebP/SVG
+bytes; it refuses a path outside that folder. The user can replace images in the pane. All exports
+must stay portable: no external image/font URLs, script tags or active SVG content.
+
+## Build, deliver, revise
+
+```sh
+node tools/build.mjs
+node tools/check.mjs
+node tools/export.mjs --seeds 3 --scale 1
+```
-Keep its useful controls and exports when making a user's creation. Test the behavioral core
-(artModel, artPaths, drawArt, logical print coordinates) as well as the visible result. A self-contained HTML file can still have well-separated
-model, rendering, input and export functions. Do not turn a finished starter into a waiting screen.
+`GENART_DSH_DIR` points to the installed package. Setup installs pinned Playwright locally and uses
+an installed Chrome or downloads a local Chromium. Export tooling supports `BROWSER_EXECUTABLE`
+and `PLAYWRIGHT_MODULE` for testing. Nothing sends art or prompts to a paid service.
-Presence-only helpers do not prove correctness or reproducibility. Record actual evidence before
-marking the result ready. Export and reopen the result as part of the handoff to the user.
+The browser exports individual SVG/PNG, an all-format ZIP, a seeded edition ZIP, an editable
+project and a portable studio. Inspect their actual bytes and reopen the project. For revisions
+from a user-saved project, run `node tools/import-project.mjs FILE` first; it preserves a backup.
+Do not overwrite a browser user's choices with old source defaults without acknowledging the conflict.
-## Check your actual edited model
+The exporter checks same-seed geometry and PNG dimensions, but leaves `ready:false`. Inspect
+all formats and their text, image placement, clipping, margins, color and scale. If randomness
+is promised, test distinct seeds as well as repeated seeds. If a print edition promises a bounded
+range, sample that range. Document font differences and any remaining production work.
-Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from
-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and
-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are
-followed by browser interaction, exported-output inspection, and visual or listening review.
+Only mark ready after the user's deliverables exist and pass both technical and visual review.
+Never label a starter, a thumbnail, a screenshot of a tool, or a successful reload as the finished work.
diff --git a/store/agents/generative-art/store.json b/store/agents/generative-art/store.json
index d2c2591ee..0f2e1315d 100644
--- a/store/agents/generative-art/store.json
+++ b/store/agents/generative-art/store.json
@@ -2,15 +2,25 @@
"listed": false,
"homepage": "https://github.com/autonomous-ai/openharness/tree/main/store/agents/generative-art",
"license": "MIT",
- "tagline": "Design reproducible generative editions",
+ "tagline": "Turn a visual brief into editable artwork and complete asset sets",
"screenshots": [
"https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/generative-art/starter.jpg"
],
"examples": [
{
- "prompt": "Create an edition of 12 tidal contour prints in indigo and burnt orange. Keep the paper quiet and make each seed feel related but distinct.",
- "caption": "Fieldwork · interactive offline starter",
- "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/generative-art/starter.jpg"
+ "prompt": "Create a botanical festival identity: a poster, square announcement and wide banner. Use bold cut-paper flowers and editable event details.",
+ "caption": "Night Garden \u00b7 original festival artwork",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/generative-art/night-garden.png"
+ },
+ {
+ "prompt": "Create woodcut-inspired coffee packaging using my logo. Deliver a bag label, launch card and shop banner with editable product details.",
+ "caption": "Canopy Coffee \u00b7 original packaging artwork",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/generative-art/canopy.png"
+ },
+ {
+ "prompt": "Turn my monthly rainfall CSV into an editable data-art print, square card and landscape graphic. Retain the actual observations.",
+ "caption": "A Year of Rain \u00b7 data-art fixture with editable CSV",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/generative-art/rain-atlas.png"
}
]
}
diff --git a/store/agents/generative-art/template/sketch/DESIGN.md b/store/agents/generative-art/template/sketch/DESIGN.md
new file mode 100644
index 000000000..484632634
--- /dev/null
+++ b/store/agents/generative-art/template/sketch/DESIGN.md
@@ -0,0 +1,16 @@
+# Night Garden · example brief
+
+Create an independent festival identity with oversized type and original cut-paper flowers.
+The festival, artists and dates are fictional input fixtures. This is one authored project, not
+a restriction on the studio's visual vocabulary. A different brief should receive its own program.
+
+Deliverables: 1200×1600 poster, 1080×1080 announcement, 1920×800 banner; SVG and PNG, editable
+project and portable studio. Text, palette, geometry and an optional logo are editable.
+
+The three layouts were exported and visually reviewed during the rebuild. Square flowers and
+foliage were reduced to leave space above the title; wide artwork clears the footer. Typography
+uses system fonts. Fonts, production color and any print shop's bleed requirements still need
+checking for a real commission. A build does not automatically set a ready verdict.
+
+The revision fixture changes dates/venue while retaining the approved geometry and other controls.
+See the repository's `store/tools/experience-tests/revisions.mjs` and `work/AUTHORING-REBUILD.md`.
diff --git a/store/agents/generative-art/template/sketch/artwork.js b/store/agents/generative-art/template/sketch/artwork.js
new file mode 100644
index 000000000..45ee6b217
--- /dev/null
+++ b/store/agents/generative-art/template/sketch/artwork.js
@@ -0,0 +1,44 @@
+// This program belongs to this brief. Replace it entirely for a different idea.
+// Return SVG children. width/height are the current artboard; values are user edits.
+const { el, text } = svg, r = rng('flowers'), w = width, h = height;
+const wide = w / h > 1.7, square = !wide && w / h > .85;
+const pad = w * .065, base = Math.min(w, h);
+const parts = [el('rect', { width: w, height: h, fill: values.paper })];
+const flower = (x, y, radius, petals, rotation, color) => {
+ let path = '';
+ const steps = petals * 24, jitter = values.wildness / 100;
+ const phase = r() * 6.283;
+ for (let i = 0; i <= steps; i++) {
+ const angle = i / steps * Math.PI * 2;
+ const lobes = .57 + .43 * (.5 + .5 * Math.cos(angle * petals));
+ const rad = radius * lobes * (1 + Math.sin(angle * 3 + phase) * .13 * jitter);
+ path += `${i ? 'L' : 'M'}${(Math.cos(angle) * rad).toFixed(2)},${(Math.sin(angle) * rad).toFixed(2)} `;
+ }
+ return el('g', { transform: `translate(${x} ${y}) rotate(${rotation})` }, [
+ el('path', { d: path + 'Z', fill: color }),
+ el('circle', { r: radius * .24, fill: values.accent }),
+ ...Array.from({ length: 32 }, () => { const a = r() * Math.PI * 2, d = Math.sqrt(r()) * radius * .18; return el('circle', { cx: Math.cos(a) * d, cy: Math.sin(a) * d, r: radius * .012, fill: values.ink }); }),
+ ]);
+};
+const type = { fill: values.ink, 'font-family': 'Arial, Helvetica, sans-serif' };
+parts.push(text('INDEPENDENT SOUND / AFTER DARK', { ...type, x: pad, y: h * .066, 'font-size': base * .015, 'letter-spacing': base * .002 }));
+if (wide) {
+ parts.push(flower(w * .77, h * .45, h * .35, values.petals, -20, values.flower));
+ parts.push(flower(w * .94, h * .20, h * .15, 6, 0, values.ink));
+} else {
+ parts.push(el('path', { d: `M ${w * .50} ${h * (square ? .55 : .59)} Q ${w * .25} ${h * .45} ${w * .65} ${h * .27}`, fill: 'none', stroke: values.ink, 'stroke-width': w * .026 }));
+ parts.push(flower(w * .66, h * (square ? .27 : .28), w * (square ? .215 : .30), values.petals, -18, values.flower));
+ parts.push(flower(w * .25, h * (square ? .37 : .40), w * (square ? .15 : .17), Math.max(5, values.petals - 2), 20, values.ink));
+ const leafY = h * (square ? .44 : .50);
+ parts.push(el('ellipse', { cx: w * .53, cy: leafY, rx: w * (square ? .07 : .085), ry: w * (square ? .135 : .19), fill: values.ink, transform: `rotate(57 ${w * .53} ${leafY})` }));
+}
+const words = values.headline.trim().split(/\s+/), midpoint = Math.ceil(words.length / 2);
+const lines = words.length > 1 ? [words.slice(0, midpoint).join(' '), words.slice(midpoint).join(' ')] : [words[0] || 'UNTITLED'];
+const maxWidth = w * (wide ? .52 : .88), font = Math.min(base * (wide ? .195 : square ? .17 : .18), maxWidth / Math.max(...lines.map(s => s.length)) * 1.48);
+const baseline = h * (wide ? .39 : square ? .70 : .72);
+lines.forEach((line, i) => parts.push(text(line, { ...type, x: pad, y: baseline + i * font * .90, 'font-size': font, 'font-weight': '900', 'letter-spacing': -font * .05 })));
+parts.push(el('line', { x1: pad, x2: w - pad, y1: h * .89, y2: h * .89, stroke: values.ink, 'stroke-width': Math.max(1, base * .0014) }));
+parts.push(text(values.details, { ...type, x: pad, y: h * .925, 'font-size': Math.min(base * .017, (w - pad * 2) / Math.max(values.details.length, 1) * 1.6), 'font-weight': 700, 'letter-spacing': base * .001 }));
+parts.push(text(values.lineup, { ...type, x: pad, y: h * .96, 'font-size': Math.min(base * .013, (w - pad * 2) / Math.max(values.lineup.length, 1) * 1.6) }));
+if (assets.logo) parts.push(el('image', { href: assets.logo, x: w - pad - base * .08, y: h * .036, width: base * .08, height: base * .055, preserveAspectRatio: 'xMidYMid meet' }));
+return parts.join('');
diff --git a/store/agents/generative-art/template/sketch/index.html b/store/agents/generative-art/template/sketch/index.html
index 216133f1f..07128c5dd 100644
--- a/store/agents/generative-art/template/sketch/index.html
+++ b/store/agents/generative-art/template/sketch/index.html
@@ -1,521 +1,9 @@
<!doctype html>
-<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
-<meta name="color-scheme" content="dark light"><title>FIELDWORK — Generative Art</title>
-<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22256%22%20height%3D%22256%22%20viewBox%3D%220%200%2096%2096%22%3E%0A%20%20%3Ctitle%3EGenerative%20Art%20%E2%80%94%20contour%20edition%3C%2Ftitle%3E%0A%20%20%3Crect%20x%3D%224%22%20y%3D%224%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2223%22%20fill%3D%22%23eee7d5%22%2F%3E%0A%20%20%3Cg%20fill%3D%22none%22%20stroke%3D%22%232d5449%22%20stroke-width%3D%225%22%20stroke-linecap%3D%22round%22%3E%0A%20%20%20%20%3Cpath%20d%3D%22M21%2027c31-20%2023%2045%2054%2025%22%2F%3E%0A%20%20%20%20%3Cpath%20d%3D%22M21%2039c31-20%2023%2045%2054%2025%22%2F%3E%0A%20%20%20%20%3Cpath%20d%3D%22M21%2051c31-20%2023%2045%2054%2025%22%2F%3E%0A%20%20%20%20%3Cpath%20d%3D%22M21%2063c21-14%2024%2014%2037%2014%22%2F%3E%0A%20%20%3C%2Fg%3E%0A%20%20%3Ccircle%20cx%3D%2271%22%20cy%3D%2224%22%20r%3D%227%22%20fill%3D%22%23ce7645%22%2F%3E%0A%3C%2Fsvg%3E">
-<!-- Built by store/tools/build-experiences.mjs. Edit this file freely in your workspace. -->
-<style>:root {
- color-scheme: dark;
- --bg: #111414;
- --panel: #191e1c;
- --line: #ffffff1c;
- --ink: #f4f2e9;
- --muted: #a1aaa4;
- --accent: #d0f28a;
- font:
- 14px/1.5 -apple-system,
- BlinkMacSystemFont,
- "Segoe UI",
- sans-serif;
-}
-* {
- box-sizing: border-box;
-}
-body {
- margin: 0;
- background: var(--bg);
- color: var(--ink);
-}
-button,
-input,
-select {
- font: inherit;
-}
-button,
-a,
-input,
-select {
- -webkit-tap-highlight-color: transparent;
-}
-button,
-a {
- touch-action: manipulation;
-}
-button {
- cursor: pointer;
-}
-button:disabled {
- opacity: 0.45;
- cursor: wait;
-}
-button:focus-visible,
-input:focus-visible,
-select:focus-visible,
-a:focus-visible {
- outline: 2px solid var(--accent);
- outline-offset: 4px;
-}
-button,
-input,
-select {
- color: inherit;
- background: transparent;
- border: 1px solid var(--line);
- border-radius: 5px;
- padding: 9px 13px;
-}
-button:hover {
- background: #ffffff0c;
- border-color: var(--muted);
-}
-button.primary {
- background: var(--accent);
- color: #142015;
- border-color: transparent;
- font-weight: 650;
-}
-button[aria-pressed="true"] {
- border-color: var(--accent);
- color: var(--accent);
-}
-input[type="range"] {
- accent-color: var(--accent);
- padding: 0;
- min-width: 0;
-}
-input[type="number"] {
- width: 80px;
-}
-select {
- background: var(--panel);
-}
-label {
- cursor: pointer;
-}
-a {
- color: inherit;
-}
-h1,
-h2,
-h3,
-p {
- margin: 0;
-}
-h1 {
- font-size: clamp(32px, 5vw, 64px);
- line-height: 1.02;
- letter-spacing: -0.055em;
- font-weight: 550;
-}
-h2 {
- font-weight: 550;
- letter-spacing: -0.03em;
-}
-h3 {
- font-size: 14px;
- font-weight: 550;
-}
-.mono,
-.eyebrow {
- font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
-}
-.eyebrow {
- font-size: 10px;
- letter-spacing: 0.16em;
- text-transform: uppercase;
- color: var(--muted);
-}
-.muted {
- color: var(--muted);
-}
-.small {
- font-size: 12px;
-}
-.masthead {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 20px;
- padding: 19px 28px;
- border-bottom: 1px solid var(--line);
-}
-.identity {
- display: flex;
- gap: 12px;
- align-items: center;
- white-space: nowrap;
- font-size: 12px;
- font-weight: 600;
- letter-spacing: 0.04em;
-}
-.mark {
- width: 28px;
- height: 28px;
- flex: 0 0 28px;
- display: grid;
- place-items: center;
-}
-.mark svg {
- display: block;
- width: 100%;
- height: 100%;
-}
-.seed-form {
- display: flex;
- align-items: center;
- gap: 6px;
-}
-.seed-form label {
- font:
- 10px ui-monospace,
- monospace;
- text-transform: uppercase;
- letter-spacing: 0.12em;
- color: var(--muted);
- margin-right: 4px;
-}
-.seed-form input {
- width: 74px;
- padding: 6px 8px;
- font:
- 12px ui-monospace,
- monospace;
-}
-.seed-form button {
- padding: 6px 10px;
- font-size: 12px;
-}
-.intro {
- padding: 32px 28px;
- display: flex;
- align-items: flex-end;
- justify-content: space-between;
- gap: 20px;
-}
-.intro p {
- max-width: 440px;
- color: var(--muted);
- margin-top: 14px;
-}
-.intro .eyebrow {
- margin-bottom: 12px;
-}
-.actions {
- display: flex;
- align-items: center;
- gap: 8px;
- flex-wrap: wrap;
-}
-.workspace {
- display: grid;
- grid-template-columns: minmax(0, 1fr) 270px;
- gap: 22px;
- padding: 0 28px 28px;
-}
-.panel {
- background: var(--panel);
- border: 1px solid var(--line);
- border-radius: 8px;
- overflow: hidden;
-}
-.panel-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 16px 20px;
- border-bottom: 1px solid var(--line);
- gap: 10px;
-}
-.side {
- display: flex;
- flex-direction: column;
- gap: 20px;
-}
-.section {
- border-top: 1px solid var(--line);
- padding-top: 18px;
-}
-.section h3 {
- margin-bottom: 15px;
-}
-.field {
- display: grid;
- gap: 7px;
- margin: 14px 0;
-}
-.field > span {
- display: flex;
- justify-content: space-between;
- font-size: 12px;
- color: var(--muted);
-}
-.metrics {
- display: grid;
- grid-template-columns: repeat(3, 1fr);
- gap: 1px;
- background: var(--line);
- border: 1px solid var(--line);
- border-radius: 6px;
- overflow: hidden;
-}
-.metric {
- background: var(--bg);
- padding: 13px 15px;
-}
-.metric strong {
- display: block;
- font:
- 24px ui-monospace,
- monospace;
- letter-spacing: -0.06em;
-}
-.metric span {
- font-size: 10px;
- color: var(--muted);
- text-transform: uppercase;
- letter-spacing: 0.09em;
-}
-canvas {
- display: block;
- max-width: 100%;
-}
-.status-line {
- display: flex;
- justify-content: space-between;
- gap: 20px;
- padding: 14px 28px;
- border-top: 1px solid var(--line);
- font:
- 10px ui-monospace,
- monospace;
- color: var(--muted);
-}
-.dot {
- width: 6px;
- height: 6px;
- display: inline-block;
- background: var(--accent);
- border-radius: 50%;
- margin-right: 6px;
-}
-.toast {
- position: fixed;
- z-index: 99;
- left: 50%;
- bottom: 22px;
- transform: translateX(-50%);
- max-width: 90vw;
- background: var(--ink);
- color: var(--bg);
- padding: 11px 18px;
- border-radius: 6px;
- box-shadow: 0 3px 30px #0004;
- font-size: 12px;
-}
-.toast:empty {
- display: none;
-}
-[hidden] {
- display: none !important;
-}
-.sr-only {
- position: absolute;
- width: 1px;
- height: 1px;
- padding: 0;
- margin: -1px;
- overflow: hidden;
- clip-path: inset(50%);
- white-space: nowrap;
- border: 0;
-}
-@media (max-width: 800px) {
- .workspace {
- grid-template-columns: 1fr;
- }
- .side {
- display: grid;
- grid-template-columns: repeat(2, minmax(0, 1fr));
- }
- .intro {
- align-items: flex-start;
- flex-direction: column;
- }
- .intro h1 {
- font-size: 44px;
- }
-}
-@media (max-width: 480px) {
- .masthead {
- padding: 13px 16px;
- gap: 8px;
- flex-wrap: wrap;
- }
- .intro {
- padding: 26px 16px;
- }
- .intro h1 {
- font-size: 38px;
- }
- .workspace {
- padding: 0 16px 20px;
- gap: 18px;
- }
- .side {
- grid-template-columns: 1fr;
- }
- .seed-form label {
- display: none;
- }
- .status-line {
- padding: 12px 16px;
- }
- .status-line span:last-child {
- display: none;
- }
- .metrics .metric {
- padding: 12px 10px;
- }
- .panel-head {
- padding: 12px;
- }
- .actions {
- gap: 6px;
- }
-}
-@media (prefers-reduced-motion: reduce) {
- *,
- *::before,
- *::after {
- scroll-behavior: auto !important;
- animation: none !important;
- transition: none !important;
- }
-}
-
-:root {
- color-scheme: light;
- --bg: #e9e8e1;
- --panel: #f5f3eb;
- --line: #242d292a;
- --ink: #26342d;
- --muted: #646d62;
- --accent: #314b3a;
-}
-button.primary {
- color: #f4f1e7;
-}
-.intro h1 {
- font-weight: 450;
-}
-.intro em {
- font-family: Georgia, serif;
- font-weight: 400;
-}
-.workspace {
- grid-template-columns: minmax(0, 1fr) 230px;
- max-width: 1320px;
- margin: auto;
- gap: 40px;
-}
-.intro {
- max-width: 1320px;
- margin: auto;
-}
-.paper-stage {
- background: #dbdcd4;
- padding: 30px 50px 18px;
- display: flex;
- align-items: center;
- flex-direction: column;
- min-width: 0;
-}
-.paper-stage > canvas {
- width: min(100%, 620px);
- aspect-ratio: 4/5;
- height: auto;
- box-shadow: 0 13px 28px #28302620;
-}
-.caption {
- font:
- 9px ui-monospace,
- monospace;
- letter-spacing: 0.08em;
- width: 100%;
- display: flex;
- justify-content: space-between;
- margin-top: 18px;
- gap: 8px;
-}
-.palettes {
- display: flex;
- gap: 8px;
- margin-top: 20px;
-}
-.palettes button {
- border-radius: 50%;
- width: 32px;
- height: 32px;
- padding: 0;
- border: 3px solid var(--bg);
- outline: 1px solid var(--line);
-}
-.palettes button[aria-pressed="true"] {
- outline: 2px solid var(--ink);
-}
-.editions {
- display: grid;
- grid-template-columns: repeat(3, 1fr);
- gap: 8px;
-}
-.editions button {
- padding: 0;
- border: 0;
- border-radius: 0;
-}
-.editions canvas {
- width: 100%;
-}
-.editions span {
- font:
- 9px ui-monospace,
- monospace;
- display: block;
- margin-top: 6px;
-}
-.side h2 {
- font:
- 27px/1.15 Georgia,
- serif;
-}
-.seed-form button:hover {
- background: #0000000b;
-}
-.actions select {
- background: #e9e8e1;
- font-size: 12px;
-}
-@media (max-width: 800px) {
- .workspace {
- grid-template-columns: 1fr;
- gap: 24px;
- }
- .paper-stage {
- padding: 24px 32px 16px;
- }
-}
-@media (max-width: 480px) {
- .paper-stage {
- padding: 18px;
- }
- .intro {
- padding-top: 22px;
- }
- .intro h1 {
- font-size: 42px;
- }
-}
-</style></head><body>
-<header class="masthead"><div class="identity"><span class="mark" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">
+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Fieldwork · Your visual studio</title><link rel="icon" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22256%22%20height%3D%22256%22%20viewBox%3D%220%200%2096%2096%22%3E%0A%20%20%3Ctitle%3EGenerative%20Art%20%E2%80%94%20contour%20edition%3C%2Ftitle%3E%0A%20%20%3Crect%20x%3D%224%22%20y%3D%224%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2223%22%20fill%3D%22%23eee7d5%22%2F%3E%0A%20%20%3Cg%20fill%3D%22none%22%20stroke%3D%22%232d5449%22%20stroke-width%3D%225%22%20stroke-linecap%3D%22round%22%3E%0A%20%20%20%20%3Cpath%20d%3D%22M21%2027c31-20%2023%2045%2054%2025%22%2F%3E%0A%20%20%20%20%3Cpath%20d%3D%22M21%2039c31-20%2023%2045%2054%2025%22%2F%3E%0A%20%20%20%20%3Cpath%20d%3D%22M21%2051c31-20%2023%2045%2054%2025%22%2F%3E%0A%20%20%20%20%3Cpath%20d%3D%22M21%2063c21-14%2024%2014%2037%2014%22%2F%3E%0A%20%20%3C%2Fg%3E%0A%20%20%3Ccircle%20cx%3D%2271%22%20cy%3D%2224%22%20r%3D%227%22%20fill%3D%22%23ce7645%22%2F%3E%0A%3C%2Fsvg%3E%0A"><style>:root{color-scheme:dark;--bg:#111513;--panel:#171c19;--line:#ffffff17;--ink:#f0f2e9;--muted:#99a59b;--accent:#d6fa8b;font:13px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink)}button,input,select,textarea{font:inherit;color:inherit;border:1px solid var(--line);border-radius:6px;background:var(--panel);padding:9px 11px;min-width:0}button{cursor:pointer;touch-action:manipulation}button:hover{border-color:#879280;background:#253022}button:disabled{opacity:.4;cursor:default}button.primary{background:var(--accent);color:#182319;border-color:transparent;font-weight:650}button:focus-visible,input:focus-visible,summary:focus-visible{outline:2px solid var(--accent);outline-offset:3px}button[aria-pressed=true]{color:var(--accent);border-color:#d6fa8b55;background:#253022}button.quiet{color:var(--muted);width:100%}input[type=range]{padding:0;accent-color:var(--accent);width:100%}input[type=color]{height:38px;width:100%;padding:3px}input[type=checkbox]{accent-color:var(--accent)}textarea{resize:vertical;min-height:64px;width:100%}header{min-height:73px;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;padding:16px 25px;gap:16px}.wordmark{display:flex;align-items:center;gap:10px;font-size:12px;letter-spacing:.08em;font-weight:700}.wordmark span{font-size:9px;border-left:1px solid var(--line);padding-left:13px;color:var(--muted);font-weight:400}.file-actions{display:flex;gap:8px}main{display:grid;grid-template-columns:270px minmax(300px,1fr) 205px;min-height:calc(100vh - 73px)}aside{padding:28px 22px}.project-panel{border-right:1px solid var(--line)}.production-panel{border-left:1px solid var(--line)}h1,h2,p{margin:0}h1{font-size:29px;line-height:1.1;letter-spacing:-.04em;margin:12px 0 16px;font-weight:560}h2{font-size:14px;font-weight:550}.eyebrow{font-size:9px;letter-spacing:.17em;color:var(--muted);font-family:ui-monospace,monospace}.brief{color:#b9c2b9;font-size:12px;line-height:1.6}.help{margin-top:16px;padding:12px;background:#d6fa8b08;border:1px solid #d6fa8b20;border-radius:7px;font-size:11px}.help summary{color:var(--accent);cursor:pointer}.help p{margin-top:10px;color:var(--muted)}.section-heading{display:flex;justify-content:space-between;align-items:center;margin:27px 0 10px;padding-top:22px;border-top:1px solid var(--line)}.section-heading button{padding:3px 8px;font-size:18px}.field,label{display:flex;flex-direction:column;gap:7px;margin:16px 0;color:#cbd2ca;font-size:11px}.field-top{display:flex;justify-content:space-between;align-items:center;gap:8px}.field output{color:var(--muted);font-variant-numeric:tabular-nums}.asset-preview{max-height:60px;max-width:100%;object-fit:contain}.asset-row{display:flex;gap:7px}.asset-row button{font-size:11px}.hint{font-size:10px;color:var(--muted);line-height:1.65}.brief-details{margin-top:24px;font-size:11px;color:var(--muted)}.brief-details summary{cursor:pointer}.brief-details p{margin-top:10px}.stage-column{min-width:0;background:#0c100e;display:flex;flex-direction:column}.stage-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:15px 22px;min-height:65px;border-bottom:1px solid var(--line)}#formats{display:flex;gap:5px;flex-wrap:wrap}#formats button{font-size:10px;padding:6px 10px;background:transparent}#dimensions{font-size:10px;white-space:nowrap;color:var(--muted);font-family:ui-monospace,monospace}.art-stage{position:relative;min-height:520px;flex:1;display:flex;justify-content:center;align-items:center;padding:34px 44px;background:radial-gradient(ellipse at 50% 35%,#27312955,transparent 65%)}#art{max-width:100%;width:auto;height:auto;max-height:calc(100vh - 320px);min-height:180px;object-fit:contain;box-shadow:0 15px 50px #0008}.canvas-footer{display:flex;justify-content:space-between;padding:10px 23px;border-top:1px solid var(--line);gap:15px;font-size:9px;letter-spacing:.02em;color:var(--muted)}.status-dot{display:inline-block;width:5px;height:5px;border-radius:50%;background:var(--accent);margin-right:7px}.output-panel{padding:23px;display:flex;align-items:center;justify-content:space-between;gap:20px;border-top:1px solid var(--line)}.output-panel h2{font-size:18px;letter-spacing:-.025em;margin:6px 0}.output-panel p:not(.eyebrow){font-size:10px;color:var(--muted)}.output-actions{display:flex;flex-direction:column;gap:6px;min-width:137px}.output-actions button{font-size:10px}.rule{height:1px;background:var(--line);margin:25px 0}.seed-row{display:flex;gap:5px}.seed-row input{width:100%}#next-seed,#export-edition{font-size:11px;width:100%;margin:5px 0 10px}#toast{position:fixed;bottom:24px;left:50%;transform:translate(-50%,15px);max-width:min(600px,90vw);padding:11px 18px;background:#e8f0df;color:#172115;border-radius:7px;opacity:0;pointer-events:none;z-index:10;box-shadow:0 10px 40px #0007;transition:.15s}#toast.visible{opacity:1;transform:translate(-50%,0)}.render-error{position:absolute;inset:auto 25px 25px;background:#47251f;color:#ffddd0;padding:18px;border:1px solid #a45e4a;border-radius:7px;white-space:pre-wrap}.notice{padding:12px 25px;display:flex;gap:12px;align-items:center;background:#39341d;font-size:11px}.notice button{font-size:11px}.notice[hidden], [hidden]{display:none!important}@media(min-width:1600px){main{grid-template-columns:300px minmax(300px,1fr) 230px}.art-stage{min-height:650px}.project-panel{padding:34px 28px}}@media(max-width:1100px){main{grid-template-columns:245px minmax(240px,1fr)}.production-panel{grid-column:1/-1;display:grid;grid-template-columns:repeat(3,1fr);gap:0 22px;border-top:1px solid var(--line)}.production-panel>.rule{display:none}.production-panel>.eyebrow{grid-column:1/-1;margin-top:12px}.output-panel{align-items:flex-start;flex-direction:column}.output-actions{flex-direction:row;flex-wrap:wrap}.art-stage{padding:25px;min-height:460px}.wordmark span{display:none}}@media(max-width:650px){header{padding:14px;align-items:flex-start;flex-wrap:wrap}.file-actions{width:100%}.file-actions button{flex:1;font-size:11px}main{display:flex;flex-direction:column}.stage-column{order:0}.project-panel{order:1;border-top:1px solid var(--line);border-right:none}.production-panel{order:2;display:block;border-left:none}.art-stage{min-height:360px;padding:25px 20px}#art{max-height:60vh}.stage-toolbar{padding:12px;flex-wrap:wrap}.output-panel{padding:18px}.canvas-footer{padding:10px 14px;font-size:8px}.notice{flex-wrap:wrap}aside{padding:24px}h1{font-size:30px}}@media(prefers-reduced-motion:reduce){*{transition:none!important}}
+.wordmark .brand-icon{display:block;width:27px;height:27px;padding:0;border:0}.brand-icon svg{display:block;width:100%;height:100%}
+</style></head>
+<body>
+<header><div class="wordmark"><span class="brand-icon" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">
<title>Generative Art — contour edition</title>
<rect x="4" y="4" width="88" height="88" rx="23" fill="#eee7d5"/>
<g fill="none" stroke="#2d5449" stroke-width="5" stroke-linecap="round">
@@ -525,377 +13,340 @@ button.primary {
<path d="M21 63c21-14 24 14 37 14"/>
</g>
<circle cx="71" cy="24" r="7" fill="#ce7645"/>
-</svg></span>FIELDWORK</div>
-<form class="seed-form" id="seed-form"><label for="seed">Seed</label><input id="seed" aria-label="Seed" maxlength="128" autocomplete="off" spellcheck="false"><button type="submit">Apply</button><button id="next-seed" type="button" title="Next seed">↗ Next</button></form></header>
-<section class="intro">
- <div>
- <p class="eyebrow">A study in controlled disorder · 001</p>
- <h1>Follow the<br /><em>unexpected.</em></h1>
- <p>
- A field of lines. A small set of rules. An edition that belongs to you.
- </p>
- </div>
- <div class="actions">
- <select id="export-size" aria-label="Export resolution">
- <option value="1600">1600 × 2000</option>
- <option value="3200">3200 × 4000</option></select
- ><button class="primary" id="export">Export print ↗</button>
- </div>
+</svg>
+</span>FIELDWORK<span>VISUAL STUDIO</span></div><div class="file-actions"><button id="open-project">Open project</button><button id="save-project">Save project</button><button class="primary" id="export-kit">Export kit ↗</button></div></header>
+<div id="revision-notice" class="notice" hidden><span>The agent has made a new version. Your previous draft is saved on this device.</span><button id="use-revision">Use new version</button><button id="keep-draft">Keep my draft</button></div>
+<main>
+<aside class="project-panel">
+<p class="eyebrow">YOUR PROJECT</p><h1 id="project-title"></h1><p id="brief" class="brief"></p>
+<details class="help"><summary>Make something entirely different</summary><p>Describe it in the Harness chat beside this studio. Ask for a new composition, illustration, pattern or visual identity. The agent creates the artwork and the controls for your idea. You never need to write code.</p><p>Try: “Use my café’s name and logo. Create an illustrated coffee bag, a square announcement and a landscape banner. Use woodcut botanical forms.”</p></details>
+<div class="section-heading"><h2>Make it yours</h2><div><button id="undo" title="Undo" aria-label="Undo">↶</button><button id="redo" title="Redo" aria-label="Redo">↷</button></div></div>
+<div id="controls"></div><div id="assets"></div>
+<details class="brief-details"><summary>Project notes</summary><p id="notes"></p><p>Save project includes the drawing program, your adjustments and embedded images. Keep this file to reopen or attach to a new Harness conversation.</p></details>
+</aside>
+<section class="stage-column">
+<div class="stage-toolbar"><div id="formats" role="group" aria-label="Output format"></div><span id="dimensions"></span></div>
+<div class="art-stage" id="art-stage"><img id="art" alt="Your original artwork"><div class="render-error" id="render-error" role="alert" hidden></div></div>
+<div class="canvas-footer"><span><i class="status-dot"></i><span id="render-status">Preparing your artwork</span></span><span id="draft-status">Saved in this browser</span></div>
+<section class="output-panel"><div><p class="eyebrow">DELIVER SOMETHING REAL</p><h2>From your idea. Into the world.</h2><p>Editable SVG for design tools. PNG for publishing. A complete project to keep creating.</p></div><div class="output-actions"><button id="export-svg">Editable SVG ↗</button><button id="export-png">PNG image ↗</button><button id="export-html">Portable studio ↗</button></div></section>
</section>
-<main class="workspace">
- <section class="paper-stage">
- <canvas id="art" aria-label="Seeded generative artwork"></canvas>
- <div class="caption">
- <span>FIELD NOTES / <span id="edition"></span></span
- ><span id="palette-name"></span>
- </div>
- </section>
- <aside class="side">
- <div>
- <p class="eyebrow">The system</p>
- <h2 style="margin-top: 10px">Make a little<br />room for chance.</h2>
- <label class="field"
- ><span>Technique</span
- ><select id="mode">
- <option value="contours">01 / Contour field</option>
- <option value="dunes">02 / Dune study</option>
- <option value="orbits">03 / Orbital motion</option>
- </select></label
- ><label class="field"
- ><span>Line density <output id="density-value">120</output></span
- ><input
- id="density"
- type="range"
- min="40"
- max="200"
- value="120" /></label
- ><label class="field"
- ><span>Field tension <output id="curl-value">55</output></span
- ><input id="curl" type="range" min="0" max="100" value="55"
- /></label>
- <div
- id="palettes"
- class="palettes"
- role="group"
- aria-label="Palette"
- ></div>
- </div>
- <div class="section">
- <h3>Nearby possibilities</h3>
- <div class="editions" id="editions"></div>
- <p class="small muted" style="margin-top: 12px">
- Every seed is a composition. Return to a seed to find it exactly as you
- left it.
- </p>
- </div>
- <div class="section small muted">
- Prints use the same geometry at every size. Color and rasterization can
- vary between devices.
- </div>
- </aside>
-</main>
-<footer class="status-line">
- <span><i class="dot"></i>DETERMINISTIC BY DESIGN</span
- ><span>CANVAS / NO EXTERNAL ASSETS</span>
-</footer>
-<div class="toast" id="toast" role="status"></div>
-<script id="harness-model">
-'use strict';
-// Shared deterministic primitives. Domain models use named streams so unrelated edits stay stable.
-function hash(value) {
- let h = 2166136261;
- for (const c of String(value)) h = Math.imul(h ^ c.charCodeAt(0), 16777619);
- return h >>> 0;
-}
-function random(seed, stream = "main") {
- let a = hash(`${seed}:${stream}`);
- return () => {
- a = (a + 0x6d2b79f5) | 0;
- let t = Math.imul(a ^ (a >>> 15), 1 | a);
- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
- };
-}
-const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));
-const lerp = (a, b, t) => a + (b - a) * t;
-const pick = (items, rng) => items[Math.floor(rng() * items.length)];
-function normal(rng) {
- return (
- Math.sqrt(-2 * Math.log(Math.max(1e-9, rng()))) *
- Math.cos(2 * Math.PI * rng())
- );
-}
-
-const artPalettes = [
- {
- name: "Estuary",
- paper: "#f1ecdf",
- colors: ["#203c36", "#527863", "#9cab86", "#d87746", "#e2b65f"],
- },
- {
- name: "Ultramarine",
- paper: "#efebe2",
- colors: ["#132d6c", "#355bb5", "#6e99b3", "#e24f32", "#d59b75"],
- },
- {
- name: "After the rain",
- paper: "#e9e6ee",
- colors: ["#332852", "#79658d", "#ac8992", "#cf805c", "#354d52"],
- },
- {
- name: "Ember",
- paper: "#201e23",
- colors: ["#edbe7f", "#e67a53", "#ad4248", "#69787b", "#ad9a83"],
+<aside class="production-panel"><p class="eyebrow">ARTBOARD</p><label>Width<input type="number" min="64" max="8192" id="width"></label><label>Height<input type="number" min="64" max="8192" id="height"></label><p class="hint">Pixels. The SVG stays sharp at any size. Ask the agent to adapt the layout to a new proportion.</p>
+<div id="variation-panel"><div class="rule"></div><p class="eyebrow">VARIATION</p><form id="seed-form"><label for="seed">Composition seed</label><div class="seed-row"><input id="seed" maxlength="128"><button type="submit">Apply</button></div><button id="next-seed" type="button">Explore another ↗</button></form><p class="hint">The same project and seed recreate the same vector geometry.</p></div>
+<div class="rule"></div><p class="eyebrow">EXPORT</p><label>PNG scale<select id="png-scale"><option value="1">1× · artboard size</option><option value="2">2× · double size</option><option value="4">4× · print detail</option></select></label><div id="edition-panel"><label>Edition count<input id="edition-count" type="number" min="1" max="24" value="1"></label><button id="export-edition">Export SVG edition ↗</button><p class="hint">Edition ZIP includes the exact seeds and your editable source. Export kit includes every named format as SVG and PNG.</p></div>
+<div class="rule"></div><button id="reset-project" class="quiet">Restore agent version</button></aside>
+</main><div id="toast" role="status"></div><input type="file" id="project-file" accept=".json,application/json" hidden>
+<script id="fieldwork-data" type="application/json">{"spec":"fieldwork/1","id":"night-garden","title":"Night Garden","brief":"A nocturnal botanical identity for an independent music festival. Build a poster, square announcement and wide banner with oversized typography and original cut-paper flowers.","notes":"Example project. Ask the agent for your own visual system; none of these shapes or controls are requirements. The three formats are composed separately from the same design language.","seed":"42","formats":[{"name":"Poster","width":1200,"height":1600},{"name":"Social","width":1080,"height":1080},{"name":"Banner","width":1920,"height":800}],"controls":[{"key":"headline","type":"text","label":"Festival name","value":"NIGHT GARDEN"},{"key":"details","type":"text","label":"Date and place","value":"SEPTEMBER 26—28 · BOTANICAL GROUNDS"},{"key":"lineup","type":"text","label":"Lineup","value":"MIRA / SOFT SIGNAL / LUNAR ASSEMBLY"},{"key":"paper","type":"color","label":"Paper","value":"#f4ead9"},{"key":"ink","type":"color","label":"Ink","value":"#142a24"},{"key":"flower","type":"color","label":"Petals","value":"#f26842"},{"key":"accent","type":"color","label":"Center","value":"#dcf476"},{"key":"petals","type":"range","label":"Flower geometry","min":5,"max":14,"step":1,"value":8},{"key":"wildness","type":"range","label":"Organic variation","min":0,"max":100,"step":1,"value":55}],"assets":[{"key":"logo","label":"Your logo (optional)"}],"code":"// This program belongs to this brief. Replace it entirely for a different idea.\n// Return SVG children. width/height are the current artboard; values are user edits.\nconst { el, text } = svg, r = rng('flowers'), w = width, h = height;\nconst wide = w / h > 1.7, square = !wide && w / h > .85;\nconst pad = w * .065, base = Math.min(w, h);\nconst parts = [el('rect', { width: w, height: h, fill: values.paper })];\nconst flower = (x, y, radius, petals, rotation, color) => {\n let path = '';\n const steps = petals * 24, jitter = values.wildness / 100;\n const phase = r() * 6.283;\n for (let i = 0; i \u003c= steps; i++) {\n const angle = i / steps * Math.PI * 2;\n const lobes = .57 + .43 * (.5 + .5 * Math.cos(angle * petals));\n const rad = radius * lobes * (1 + Math.sin(angle * 3 + phase) * .13 * jitter);\n path += `${i ? 'L' : 'M'}${(Math.cos(angle) * rad).toFixed(2)},${(Math.sin(angle) * rad).toFixed(2)} `;\n }\n return el('g', { transform: `translate(${x} ${y}) rotate(${rotation})` }, [\n el('path', { d: path + 'Z', fill: color }),\n el('circle', { r: radius * .24, fill: values.accent }),\n ...Array.from({ length: 32 }, () => { const a = r() * Math.PI * 2, d = Math.sqrt(r()) * radius * .18; return el('circle', { cx: Math.cos(a) * d, cy: Math.sin(a) * d, r: radius * .012, fill: values.ink }); }),\n ]);\n};\nconst type = { fill: values.ink, 'font-family': 'Arial, Helvetica, sans-serif' };\nparts.push(text('INDEPENDENT SOUND / AFTER DARK', { ...type, x: pad, y: h * .066, 'font-size': base * .015, 'letter-spacing': base * .002 }));\nif (wide) {\n parts.push(flower(w * .77, h * .45, h * .35, values.petals, -20, values.flower));\n parts.push(flower(w * .94, h * .20, h * .15, 6, 0, values.ink));\n} else {\n parts.push(el('path', { d: `M ${w * .50} ${h * (square ? .55 : .59)} Q ${w * .25} ${h * .45} ${w * .65} ${h * .27}`, fill: 'none', stroke: values.ink, 'stroke-width': w * .026 }));\n parts.push(flower(w * .66, h * (square ? .27 : .28), w * (square ? .215 : .30), values.petals, -18, values.flower));\n parts.push(flower(w * .25, h * (square ? .37 : .40), w * (square ? .15 : .17), Math.max(5, values.petals - 2), 20, values.ink));\n const leafY = h * (square ? .44 : .50);\n parts.push(el('ellipse', { cx: w * .53, cy: leafY, rx: w * (square ? .07 : .085), ry: w * (square ? .135 : .19), fill: values.ink, transform: `rotate(57 ${w * .53} ${leafY})` }));\n}\nconst words = values.headline.trim().split(/\\s+/), midpoint = Math.ceil(words.length / 2);\nconst lines = words.length > 1 ? [words.slice(0, midpoint).join(' '), words.slice(midpoint).join(' ')] : [words[0] || 'UNTITLED'];\nconst maxWidth = w * (wide ? .52 : .88), font = Math.min(base * (wide ? .195 : square ? .17 : .18), maxWidth / Math.max(...lines.map(s => s.length)) * 1.48);\nconst baseline = h * (wide ? .39 : square ? .70 : .72);\nlines.forEach((line, i) => parts.push(text(line, { ...type, x: pad, y: baseline + i * font * .90, 'font-size': font, 'font-weight': '900', 'letter-spacing': -font * .05 })));\nparts.push(el('line', { x1: pad, x2: w - pad, y1: h * .89, y2: h * .89, stroke: values.ink, 'stroke-width': Math.max(1, base * .0014) }));\nparts.push(text(values.details, { ...type, x: pad, y: h * .925, 'font-size': Math.min(base * .017, (w - pad * 2) / Math.max(values.details.length, 1) * 1.6), 'font-weight': 700, 'letter-spacing': base * .001 }));\nparts.push(text(values.lineup, { ...type, x: pad, y: h * .96, 'font-size': Math.min(base * .013, (w - pad * 2) / Math.max(values.lineup.length, 1) * 1.6) }));\nif (assets.logo) parts.push(el('image', { href: assets.logo, x: w - pad - base * .08, y: h * .036, width: base * .08, height: base * .055, preserveAspectRatio: 'xMidYMid meet' }));\nreturn parts.join('');\n","revision":"34377e73e93d35f3709b29bea94b74df60560a809351500020f388f3067bfe25"}</script><script id="fieldwork-model">// Shared by the authoring tools, preview worker and exported projects.
+const ART_SPEC = 'fieldwork/1';
+const kinds = new Set(['text', 'color', 'range', 'select', 'toggle']);
+const keyPattern = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;
+function validateProject(input) {
+ const p = structuredClone(input);
+ if (!p || p.spec !== ART_SPEC) throw new Error('This is not a Fieldwork project.');
+ if (typeof p.id !== 'string' || !/^[a-z0-9-]{1,80}$/.test(p.id)) throw new Error('Project needs a stable id.');
+ for (const name of ['title', 'brief']) if (typeof p[name] !== 'string' || !p[name].trim() || p[name].length > 6000) throw new Error(`Invalid ${name}.`);
+ if (typeof p.code !== 'string' || !p.code.trim() || p.code.length > 500000) throw new Error('The project needs an artwork.js renderer.');
+ // Compile only. Actual rendering happens in a terminable browser worker.
+ new Function('width', 'height', 'seed', 'values', 'assets', 'rng', 'svg', '"use strict";\n' + p.code);
+ if (!Array.isArray(p.formats) || !p.formats.length || p.formats.length > 12) throw new Error('Provide 1–12 output formats.');
+ for (const f of p.formats) {
+ if (typeof f.name !== 'string' || !f.name.trim() || f.name.length > 80) throw new Error('Name each format.');
+ for (const k of ['width', 'height']) if (!Number.isInteger(f[k]) || f[k] < 64 || f[k] > 8192) throw new Error('Artboards must be 64–8192 pixels per side.');
+ }
+ if (!Array.isArray(p.controls) || p.controls.length > 40) throw new Error('Provide at most 40 editable controls.');
+ const ids = new Set();
+ for (const c of p.controls) {
+ if (!keyPattern.test(c.key) || ids.has(c.key) || !kinds.has(c.type) || typeof c.label !== 'string') throw new Error('Invalid or duplicate project control.');
+ ids.add(c.key);
+ if (c.type === 'range' && (![c.min, c.max, c.step ?? 1].every(Number.isFinite) || c.max <= c.min || (c.step ?? 1) <= 0)) throw new Error(`Invalid range: ${c.key}.`);
+ if (c.type === 'select' && (!Array.isArray(c.options) || !c.options.length || c.options.length > 50 || c.options.some(x => typeof x !== 'string'))) throw new Error(`Invalid choices: ${c.key}.`);
+ checkedValue(c, c.value);
+ }
+ p.assets ??= [];
+ if (!Array.isArray(p.assets) || p.assets.length > 12) throw new Error('Provide at most 12 image assets.');
+ ids.clear();
+ for (const a of p.assets) {
+ if (!keyPattern.test(a.key) || ids.has(a.key) || typeof a.label !== 'string') throw new Error('Invalid asset slot.');
+ ids.add(a.key);
+ if (a.data && (typeof a.data !== 'string' || !/^data:image\/(png|jpeg|webp|svg\+xml);base64,[a-zA-Z0-9+/=]+$/.test(a.data) || a.data.length > 16000000)) throw new Error(`Embed ${a.label} as a PNG, JPEG, WebP or SVG image.`);
+ }
+ p.seed = String(p.seed ?? '1').slice(0, 128);
+ if (p.variations !== undefined && typeof p.variations !== 'boolean') throw new Error('variations must be a boolean.');
+ if (JSON.stringify(p).length > 28000000) throw new Error('Keep the editable project under 28 MB. Use smaller embedded images.');
+ return p;
+}
+function checkedValue(c, value) {
+ if (c.type === 'range' && (!Number.isFinite(value) || value < c.min || value > c.max)) throw new Error(`${c.label} is out of range.`);
+ if (c.type === 'color' && (typeof value !== 'string' || !/^#[0-9a-f]{6}$/i.test(value))) throw new Error(`Invalid ${c.label} color.`);
+ if (c.type === 'text' && (typeof value !== 'string' || value.length > 4000)) throw new Error(`${c.label} must be text under 4000 characters.`);
+ if (c.type === 'select' && !c.options.includes(value)) throw new Error(`Invalid ${c.label} choice.`);
+ if (c.type === 'toggle' && typeof value !== 'boolean') throw new Error(`Invalid ${c.label} toggle.`);
+ return value;
+}
+function artRandom(seed, namespace = '') {
+ let n = 2166136261;
+ for (const c of String(seed) + ':' + namespace) n = Math.imul(n ^ c.charCodeAt(0), 16777619);
+ return () => { n += 0x6D2B79F5; let t = Math.imul(n ^ n >>> 15, n | 1); t ^= t + Math.imul(t ^ t >>> 7, t | 61); return ((t ^ t >>> 14) >>> 0) / 4294967296; };
+}
+function xml(value) { return String(value).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' })[c]); }
+const svg = {
+ escape: xml,
+ el(tag, attrs = {}, children = '') {
+ if (!/^[a-zA-Z][a-zA-Z0-9:-]*$/.test(tag)) throw new Error('Invalid SVG element.');
+ return `<${tag}${Object.entries(attrs).filter(([, v]) => v !== undefined && v !== null).map(([k, v]) => ` ${k}="${xml(v)}"`).join('')}>${Array.isArray(children) ? children.join('') : children}</${tag}>`;
},
-];
-function artModel(
- seed,
- { density = 120, curl = 55, mode = "contours", palette } = {},
-) {
- const rnd = random(seed, "composition");
- return {
- seed: String(seed),
- density,
- curl,
- mode,
- palette:
- palette ?? Math.floor(random(seed, "palette")() * artPalettes.length),
- phases: Array.from({ length: 5 }, () => rnd() * Math.PI * 2),
- frequency: 1.4 + rnd() * 1.8,
- tilt: (rnd() - 0.5) * 0.22,
- };
-}
-function artPaths(model) {
- const { density, curl, phases: p, frequency: f, mode } = model;
- const paths = [];
- for (let i = 0; i < density; i++) {
- const u = i / (density - 1),
- path = [];
- for (let j = 0; j <= 140; j++) {
- const v = j / 140;
- if (mode === "orbits") {
- const theta = v * Math.PI * 2;
- const radius =
- 50 + u * 385 + Math.sin(theta * 3 + p[0]) * (curl * 0.6) * u;
- path.push([
- 500 + Math.cos(theta) * radius,
- 580 + Math.sin(theta) * radius * 1.25,
- ]);
- } else {
- const wave =
- Math.sin(v * f * Math.PI + p[0] + u * 2.6) * Math.sin(u * Math.PI);
- const wave2 =
- Math.cos(v * Math.PI * 3 + p[1]) * Math.sin(u * Math.PI) * 0.27;
- if (mode === "dunes")
- path.push([
- 70 + v * 860,
- 170 + u * 890 + (wave + wave2) * curl * 2.1,
- ]);
- else
- path.push([
- 80 + u * 840 + (wave + wave2) * curl * 2.2,
- 80 + v * 1070 + (u - 0.5) * model.tilt * 400,
- ]);
- }
+ text(value, attrs = {}) { return svg.el('text', attrs, xml(value)); },
+};
+function renderProject(project, { format = 0, width, height, seed = project.seed, values = {} } = {}) {
+ const f = project.formats[format];
+ if (!f) throw new Error('Choose a valid format.');
+ width ??= f.width; height ??= f.height;
+ if (![width, height].every(n => Number.isInteger(n) && n >= 64 && n <= 8192)) throw new Error('Invalid artboard size.');
+ const resolved = Object.fromEntries(project.controls.map(c => [c.key, checkedValue(c, values[c.key] ?? c.value)]));
+ const assets = Object.fromEntries(project.assets.map(a => [a.key, a.data || '']));
+ const body = new Function('width', 'height', 'seed', 'values', 'assets', 'rng', 'svg', '"use strict";\n' + project.code)(width, height, String(seed), resolved, assets, name => artRandom(seed, name), svg);
+ if (typeof body !== 'string' || !body.trim() || body.length > 24000000) throw new Error('The renderer must return SVG artwork under 24 MB.');
+ return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}"><title>${xml(project.title)}</title>${body}</svg>`;
+}
+function filename(name) { return String(name).normalize('NFKD').replace(/[^a-zA-Z0-9_.-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 100) || 'artwork'; }
+// ZIP STORE: portable editable delivery without a runtime dependency or a cloud service.
+function zipFiles(files) {
+ const enc = new TextEncoder(), chunks = [], central = []; let offset = 0;
+ for (const [name, body] of files) {
+ const path = enc.encode(name), bytes = typeof body === 'string' ? enc.encode(body) : new Uint8Array(body);
+ let crc = 0xffffffff;
+ for (const b of bytes) { crc ^= b; for (let i = 0; i < 8; i++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); }
+ crc = (crc ^ 0xffffffff) >>> 0;
+ const header = new Uint8Array(30 + path.length), v = new DataView(header.buffer);
+ v.setUint32(0, 0x04034b50, true); v.setUint16(4, 20, true); v.setUint16(6, 0x800, true); v.setUint16(12, 33, true);
+ v.setUint32(14, crc, true); v.setUint32(18, bytes.length, true); v.setUint32(22, bytes.length, true); v.setUint16(26, path.length, true); header.set(path, 30);
+ const row = new Uint8Array(46 + path.length), c = new DataView(row.buffer);
+ c.setUint32(0, 0x02014b50, true); c.setUint16(4, 20, true); c.setUint16(6, 20, true); c.setUint16(8, 0x800, true); c.setUint16(14, 33, true);
+ c.setUint32(16, crc, true); c.setUint32(20, bytes.length, true); c.setUint32(24, bytes.length, true); c.setUint16(28, path.length, true); c.setUint32(42, offset, true); row.set(path, 46);
+ chunks.push(header, bytes); central.push(row); offset += header.length + bytes.length;
+ }
+ const length = central.reduce((n, row) => n + row.length, 0), end = new Uint8Array(22), e = new DataView(end.buffer);
+ e.setUint32(0, 0x06054b50, true); e.setUint16(8, files.length, true); e.setUint16(10, files.length, true); e.setUint32(12, length, true); e.setUint32(16, offset, true);
+ return new Blob([...chunks, ...central, end], { type: 'application/zip' });
+}
+</script><script>const $ = selector => document.querySelector(selector);
+const original = validateProject(JSON.parse($('#fieldwork-data').textContent));
+const modelSource = $('#fieldwork-model').textContent;
+const storageKey = `fieldwork:${original.id}`;
+let project = structuredClone(original), format = 0, svgText = '', artURL, worker, renderSequence = 0;
+let undoStack = [], redoStack = [], pendingDraft, preserveDraft = false, toastTimer, renderTimer;
+const exportButtons = ['export-svg', 'export-png', 'export-kit', 'export-edition'];
+const snapshot = () => ({ project: structuredClone(project), format });
+function toast(message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 4500); }
+function signal(type, extra = {}) { if (parent !== window) parent.postMessage({ type, seed: project.seed, ...extra }, '*'); }
+function persist() {
+ if (preserveDraft) return;
+ try { localStorage.setItem(storageKey, JSON.stringify({ baseRevision: original.revision, ...snapshot() })); $('#draft-status').textContent = 'Draft saved on this device'; }
+ catch { $('#draft-status').textContent = 'Save project to keep your changes'; }
+}
+function changed(mutate, { rebuild = false } = {}) {
+ undoStack.push(snapshot()); if (undoStack.length > 24) undoStack.shift(); redoStack = [];
+ mutate(); if (rebuild) buildUI(); else syncFields();
+ persist(); scheduleRender();
+}
+function restore(state) { project = validateProject(state.project); format = Math.max(0, Math.min(project.formats.length - 1, state.format || 0)); buildUI(); persist(); scheduleRender(); }
+function saveFile(name, content, type) {
+ const blob = content instanceof Blob ? content : new Blob([content], { type: type || 'application/octet-stream' });
+ const url = URL.createObjectURL(blob), a = document.createElement('a'); a.href = url; a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(url), 30000);
+}
+function baseName(suffix = '') { return `${filename(project.title)}-${filename(project.formats[format].name)}-${filename(project.seed)}${suffix}`; }
+function portableProject() { return { ...structuredClone(project), view: { format } }; }
+function syncFields() {
+ $('#width').value = project.formats[format].width; $('#height').value = project.formats[format].height;
+ $('#dimensions').textContent = `${$('#width').value} × ${$('#height').value}`;
+ $('#seed').value = project.seed;
+ $('#undo').disabled = !undoStack.length; $('#redo').disabled = !redoStack.length;
+ for (const b of $('#formats').children) b.setAttribute('aria-pressed', Number(b.dataset.format) === format);
+ const url = new URL(location.href); url.searchParams.set('seed', project.seed); history.replaceState(null, '', url);
+ signal('harness:state');
+}
+function buildUI() {
+ document.title = `${project.title} · Fieldwork`;
+ $('#project-title').textContent = project.title; $('#brief').textContent = project.brief;
+ $('#notes').textContent = project.notes || 'Your drawing program is original to this project. Ask the agent to change its visual language, composition or outputs.';
+ $('#variation-panel').hidden = project.variations === false;
+ $('#edition-panel').hidden = project.variations === false;
+ $('#formats').replaceChildren();
+ project.formats.forEach((f, i) => { const b = document.createElement('button'); b.textContent = f.name; b.dataset.format = i; b.onclick = () => changed(() => { format = i; }); $('#formats').append(b); });
+ $('#controls').replaceChildren();
+ for (const c of project.controls) {
+ const label = document.createElement('label'), top = document.createElement('span'), title = document.createElement('span'), out = document.createElement('output');
+ label.className = 'field'; top.className = 'field-top'; title.textContent = c.label; top.append(title);
+ let input;
+ if (c.type === 'select') { input = document.createElement('select'); for (const option of c.options) { const el = document.createElement('option'); el.textContent = option; input.append(el); } }
+ else if (c.type === 'text' && c.multiline) input = document.createElement('textarea');
+ else { input = document.createElement('input'); input.type = c.type === 'toggle' ? 'checkbox' : c.type === 'text' ? 'text' : c.type; }
+ input.id = 'control-' + c.key;
+ if (c.type === 'range') { input.min = c.min; input.max = c.max; input.step = c.step ?? 1; out.value = c.value; top.append(out); }
+ if (c.type === 'toggle') input.checked = c.value; else input.value = c.value;
+ if (c.type === 'text') input.maxLength = 4000;
+ input.addEventListener(c.type === 'color' || c.type === 'range' || c.type === 'text' ? 'input' : 'change', () => changed(() => {
+ c.value = c.type === 'toggle' ? input.checked : c.type === 'range' ? Number(input.value) : input.value; out.value = c.value;
+ }));
+ label.append(top, input); $('#controls').append(label);
+ }
+ $('#assets').replaceChildren();
+ for (const asset of project.assets) {
+ const block = document.createElement('div'), name = document.createElement('p'), row = document.createElement('div'), choose = document.createElement('button'), remove = document.createElement('button'), input = document.createElement('input');
+ block.className = 'field'; name.textContent = asset.label; row.className = 'asset-row'; choose.textContent = asset.data ? 'Replace image' : 'Use your image'; remove.textContent = 'Remove'; remove.disabled = !asset.data;
+ input.type = 'file'; input.accept = 'image/png,image/jpeg,image/webp,image/svg+xml'; input.hidden = true; input.setAttribute('aria-label', asset.label);
+ choose.onclick = () => input.click();
+ input.onchange = async () => {
+ try {
+ const file = input.files[0]; if (!file) return;
+ if (file.size > 12000000) throw new Error('Choose an image under 12 MB.');
+ const data = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(file); });
+ const candidate = structuredClone(project); candidate.assets.find(a => a.key === asset.key).data = data; validateProject(candidate);
+ changed(() => { asset.data = data; }, { rebuild: true });
+ } catch (error) { toast(error.message || 'Could not read that image.'); }
+ };
+ remove.onclick = () => changed(() => { delete asset.data; }, { rebuild: true });
+ row.append(choose, remove); block.append(name, row, input); $('#assets').append(block);
+ }
+ syncFields();
+}
+function checkSVG(text) {
+ const externalURL = value => [...value.matchAll(/url\(\s*([^)]*)\)/gi)].some(([, url]) => !/^(#|data:)/i.test(url.trim().replace(/^['"]|['"]$/g, '')));
+ const doc = new DOMParser().parseFromString(text, 'image/svg+xml');
+ if (doc.querySelector('parsererror')) throw new Error('Artwork returned invalid SVG. Ask the agent to fix the drawing program.');
+ for (const node of doc.querySelectorAll('*')) {
+ if (['script', 'foreignobject', 'iframe', 'object', 'embed', 'audio', 'video', 'animate', 'animatetransform', 'set'].includes(node.localName.toLowerCase())) throw new Error('This studio exports static vector artwork. Remove active SVG elements.');
+ for (const attr of node.attributes) {
+ if (/^on/i.test(attr.name) || (/(^|:)href$/.test(attr.name) && !/^(#|data:image\/)/.test(attr.value))) throw new Error('Embed artwork assets so exports work offline.');
+ if (externalURL(attr.value)) throw new Error('External resources are not portable. Embed them in the project.');
}
- paths.push(path);
+ if (node.localName === 'style' && (/@import/i.test(node.textContent) || externalURL(node.textContent))) throw new Error('Embed fonts and images; external stylesheets cannot be exported.');
}
- return paths;
-}
-
-</script>
-<script>
-'use strict';
-const $ = (s) => document.querySelector(s);
-const $$ = (s) => [...document.querySelectorAll(s)];
-const params = new URLSearchParams(location.search);
-let seed = (params.get("seed") || "42").slice(0, 128);
-const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
-const parentMessage = (message) => {
- if (parent !== window) parent.postMessage(message, "*");
-};
-function toast(message) {
- $("#toast").textContent = message;
- clearTimeout(toast.timer);
- toast.timer = setTimeout(() => {
- $("#toast").textContent = "";
- }, 3500);
-}
-function saveFile(name, content, type = "application/json") {
- const blob =
- content instanceof Blob ? content : new Blob([content], { type });
- const url = URL.createObjectURL(blob),
- a = document.createElement("a");
- a.href = url;
- a.download = name;
- document.body.append(a);
- a.click();
- a.remove();
- setTimeout(() => URL.revokeObjectURL(url), 30000);
-}
-function canvasPNG(canvas, name) {
- canvas.toBlob((blob) => {
- if (blob) saveFile(name, blob);
- else toast("Image export failed. Please try again.");
+ return text;
+}
+function renderInWorker(candidate, options = {}) {
+ return new Promise((resolve, reject) => {
+ const script = modelSource + '\nonmessage = e => { try { postMessage({ svg: renderProject(e.data.project, e.data.options) }); } catch (error) { postMessage({ error: error.message }); } };';
+ const url = URL.createObjectURL(new Blob([script], { type: 'text/javascript' }));
+ const task = new Worker(url); URL.revokeObjectURL(url);
+ const timer = setTimeout(() => { task.terminate(); reject(new Error('This drawing took longer than 5 seconds. Ask the agent to simplify it.')); }, 5000);
+ const done = fn => value => { clearTimeout(timer); task.terminate(); fn(value); };
+ task.onmessage = event => done(event.data.error ? reject : resolve)(event.data.error ? new Error(event.data.error) : event.data.svg);
+ task.onerror = event => done(reject)(new Error(event.message));
+ task.postMessage({ project: candidate, options });
});
}
-function setSeed(value) {
- seed = String(value).trim().slice(0, 128) || "42";
- $("#seed").value = seed;
- const url = new URL(location.href);
- url.searchParams.set("seed", seed);
+function scheduleRender() { ++renderSequence; for (const id of exportButtons) $('#' + id).disabled = true; clearTimeout(renderTimer); renderTimer = setTimeout(render, 80); }
+async function render() {
+ const sequence = ++renderSequence;
+ for (const id of exportButtons) $('#' + id).disabled = true;
+ $('#render-status').textContent = 'Drawing your project…';
try {
- history.replaceState(null, "", url);
- } catch {
- /* Opaque-origin iframe: the shell owns its URL. */
+ const text = checkSVG(await renderInWorker(project, { format }));
+ if (sequence !== renderSequence) return;
+ const image = $('#art'), nextURL = URL.createObjectURL(new Blob([text], { type: 'image/svg+xml' }));
+ await new Promise((resolve, reject) => { image.onload = resolve; image.onerror = () => reject(new Error('The vector image could not be displayed.')); image.src = nextURL; });
+ if (artURL) URL.revokeObjectURL(artURL); artURL = nextURL;
+ if (sequence !== renderSequence) return;
+ svgText = text; $('#render-error').hidden = true;
+ $('#render-status').textContent = 'Original vector artwork · ready to export';
+ for (const id of exportButtons) $('#' + id).disabled = false;
+ document.body.dataset.ready = 'true'; signal('harness:ready');
+ } catch (error) {
+ if (sequence !== renderSequence) return;
+ $('#render-error').textContent = error.message; $('#render-error').hidden = false;
+ $('#render-status').textContent = 'Drawing needs a fix · exports paused'; signal('harness:error', { message: error.message });
}
- parentMessage({ type: "harness:state", seed });
- dispatchEvent(new CustomEvent("seedchange", { detail: seed }));
}
-$("#seed").value = seed;
-$("#seed-form").addEventListener("submit", (e) => {
- e.preventDefault();
- setSeed($("#seed").value);
+async function raster(text, width, height, scale = Number($('#png-scale').value)) {
+ const w = Math.round(width * scale), h = Math.round(height * scale);
+ if (w > 8192 || h > 8192 || w * h > 32000000) throw new Error('PNG is too large. Choose a smaller scale or artboard (maximum 32 megapixels).');
+ const url = URL.createObjectURL(new Blob([text], { type: 'image/svg+xml' }));
+ try {
+ const img = new Image(); img.src = url; await img.decode();
+ const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h;
+ canvas.getContext('2d').drawImage(img, 0, 0, w, h);
+ const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
+ if (!blob) throw new Error('PNG export failed.');
+ return blob;
+ } finally { URL.revokeObjectURL(url); }
+}
+function guard(task) { return async () => { try { await task(); } catch (error) { toast(error.message); } }; }
+$('#export-svg').onclick = () => saveFile(baseName('.svg'), svgText, 'image/svg+xml');
+$('#export-png').onclick = guard(async () => { const f = project.formats[format]; saveFile(baseName('.png'), await raster(svgText, f.width, f.height)); toast('PNG exported at your chosen size.'); });
+$('#save-project').onclick = () => { saveFile(`${filename(project.title)}.fieldwork.json`, JSON.stringify(portableProject(), null, 2), 'application/json'); toast('Editable project saved, including your images and drawing program.'); };
+$('#open-project').onclick = () => $('#project-file').click();
+$('#project-file').onchange = guard(async () => {
+ const file = $('#project-file').files[0]; if (!file) return;
+ if (file.size > 64000000) throw new Error('Project is too large (maximum 64 MB).');
+ const next = validateProject(JSON.parse(await file.text()));
+ changed(() => { project = next; format = Math.min(next.view?.format || 0, next.formats.length - 1); }, { rebuild: true });
+ $('#project-file').value = ''; toast('Project opened.');
});
-$("#next-seed").addEventListener("click", () =>
- setSeed(/^\d{1,9}$/.test(seed) ? Number(seed) + 1 : hash(seed)),
-);
-function fitCanvas(canvas, draw, maxDpr = 2) {
- const observer = new ResizeObserver(() => {
- const box = canvas.getBoundingClientRect(),
- dpr = Math.min(devicePixelRatio || 1, maxDpr);
- canvas.width = Math.max(1, Math.round(box.width * dpr));
- canvas.height = Math.max(1, Math.round(box.height * dpr));
- draw?.();
- });
- observer.observe(canvas);
- return observer;
-}
-const editable = (target) =>
- target instanceof Element &&
- !!target.closest("input,textarea,select,[contenteditable=true]");
-addEventListener("error", (e) =>
- parentMessage({ type: "harness:error", message: e.message }),
-);
-addEventListener("unhandledrejection", (e) =>
- parentMessage({
- type: "harness:error",
- message: String(e.reason?.message || e.reason),
- }),
-);
-function ready() {
- document.body.dataset.ready = "true";
- parentMessage({ type: "harness:ready", title: document.title, seed });
-}
-
-let artwork, paletteOverride;
-function drawArt(canvas, model) {
- const ctx = canvas.getContext("2d"),
- p = artPalettes[model.palette];
- ctx.setTransform(canvas.width / 1000, 0, 0, canvas.height / 1250, 0, 0);
- ctx.fillStyle = p.paper;
- ctx.fillRect(0, 0, 1000, 1250);
- const paths = artPaths(model),
- colors = random(model.seed, "line-colors");
- // Batch by ink color. Hundreds of tiny GPU submissions otherwise dominate the redraw.
- const inks = p.colors.map(() => new Path2D());
- paths.forEach((points, i) => {
- const index = Math.floor(
- (((i / paths.length) * 3 + colors() * 0.45) % 1) * p.colors.length,
- );
- points.forEach(([x, y], j) =>
- j ? inks[index].lineTo(x, y) : inks[index].moveTo(x, y),
- );
- });
- ctx.lineWidth = model.mode === "dunes" ? 2.6 : 2.1;
- ctx.globalAlpha = 0.83;
- inks.forEach((path, i) => {
- ctx.strokeStyle = p.colors[i];
- ctx.stroke(path);
- });
- ctx.globalAlpha = 1;
- // Seeded paper texture in one draw, in logical coordinates at every export resolution.
- const grain = random(model.seed, "paper");
- const texture = document.createElement("canvas");
- texture.width = texture.height = 128;
- const textureContext = texture.getContext("2d");
- const pixels = textureContext.createImageData(128, 128);
- for (let i = 0; i < pixels.data.length; i += 4) {
- pixels.data[i] = model.palette === 3 ? 255 : 65;
- pixels.data[i + 1] = model.palette === 3 ? 255 : 55;
- pixels.data[i + 2] = model.palette === 3 ? 255 : 46;
- pixels.data[i + 3] = grain() > 0.91 ? 16 : 0;
- }
- textureContext.putImageData(pixels, 0, 0);
- ctx.fillStyle = ctx.createPattern(texture, "repeat");
- ctx.fillRect(0, 0, 1000, 1250);
- ctx.fillStyle = p.colors[0];
- ctx.font = "9px monospace";
- ctx.fillText(
- `FIELDWORK / ${model.seed.slice(0, 26)} / ${model.mode.toUpperCase()}`,
- 70,
- 1208,
- );
-}
-function controls() {
- return {
- density: +$("#density").value,
- curl: +$("#curl").value,
- mode: $("#mode").value,
- palette: paletteOverride,
- };
+$('#export-html').onclick = () => {
+ const doc = document.documentElement.cloneNode(true);
+ doc.querySelector('#fieldwork-data').textContent = JSON.stringify(portableProject()).replace(/</g, '\\u003c');
+ doc.querySelector('#revision-notice').hidden = true; doc.querySelector('#art').removeAttribute('src');
+ doc.querySelector('#toast').className = ''; doc.querySelector('body').removeAttribute('data-ready');
+ saveFile(`${filename(project.title)}-studio.html`, '<!doctype html>\n' + doc.outerHTML, 'text/html');
+ toast('Portable studio saved. Open it directly in a browser.');
+};
+function sourceFiles() {
+ const p = portableProject(), manifest = structuredClone(p); delete manifest.code; delete manifest.revision; delete manifest.view;
+ return [['project.fieldwork.json', JSON.stringify(p, null, 2)], ['source/project.json', JSON.stringify(manifest, null, 2)], ['source/artwork.js', p.code], ['README.txt', `${p.title}\n\n${p.brief}\n\nOpen SVG in a vector editor. PNGs are ready for publishing. Open project.fieldwork.json in Fieldwork to revise the project; it contains your renderer and embedded images. The source folder contains editable project settings and drawing code. System fonts can vary between machines.\n`]];
}
-function renderArt() {
- artwork = artModel(seed, controls());
- $("#density-value").value = artwork.density;
- $("#curl-value").value = artwork.curl;
- $("#edition").textContent = seed;
- $("#palette-name").textContent = artPalettes[artwork.palette].name;
- drawArt($("#art"), artwork);
- $$("#palettes button").forEach((b, i) =>
- b.setAttribute("aria-pressed", i === artwork.palette),
- );
- $("#editions").replaceChildren();
- for (let i = 1; i <= 3; i++) {
- const next = /^\d{1,9}$/.test(seed) ? String(+seed + i) : `${seed}.${i}`;
- const button = document.createElement("button"),
- c = document.createElement("canvas"),
- label = document.createElement("span");
- c.width = 160;
- c.height = 200;
- label.textContent = next.slice(0, 9);
- button.setAttribute("aria-label", `Explore seed ${next}`);
- button.append(c, label);
- button.onclick = () => setSeed(next);
- $("#editions").append(button);
- drawArt(c, artModel(next, controls()));
+$('#export-kit').onclick = guard(async () => {
+ const candidate = structuredClone(project), files = sourceFiles(), scale = Number($('#png-scale').value);
+ $('#export-kit').disabled = true;
+ try {
+ for (let i = 0; i < candidate.formats.length; i++) {
+ const f = candidate.formats[i], name = `${String(i + 1).padStart(2, '0')}-${filename(f.name)}`, text = checkSVG(await renderInWorker(candidate, { format: i }));
+ files.push([`${name}.svg`, text], [`${name}.png`, await (await raster(text, f.width, f.height, scale)).arrayBuffer()]);
+ }
+ saveFile(`${filename(candidate.title)}-delivery.zip`, zipFiles(files)); toast(`${candidate.formats.length} formats exported as SVG and PNG, with editable source.`);
+ } finally { $('#export-kit').disabled = false; }
+});
+$('#export-edition').onclick = guard(async () => {
+ const count = Number($('#edition-count').value);
+ if (!Number.isInteger(count) || count < 1 || count > 24) throw new Error('Choose an edition of 1–24.');
+ const candidate = structuredClone(project), chosenFormat = format, files = sourceFiles(), seeds = [];
+ for (let i = 0; i < count; i++) {
+ const seed = i === 0 ? candidate.seed : /^\d{1,9}$/.test(candidate.seed) ? String(Number(candidate.seed) + i) : `${candidate.seed}.${i}`;
+ seeds.push(seed); files.push([`edition/${String(i + 1).padStart(2, '0')}-${filename(seed)}.svg`, checkSVG(await renderInWorker(candidate, { format: chosenFormat, seed }))]);
}
-}
-artPalettes.forEach((p, i) => {
- const b = document.createElement("button");
- b.title = p.name;
- b.setAttribute("aria-label", p.name);
- b.style.background = `conic-gradient(${p.colors.map((c, j) => `${c} ${j * 20}% ${(j + 1) * 20}%`).join(",")})`;
- b.onclick = () => {
- paletteOverride = i;
- renderArt();
- };
- $("#palettes").append(b);
+ files.push(['edition.json', JSON.stringify({ seeds, format: candidate.formats[chosenFormat], project: candidate.id }, null, 2)]);
+ saveFile(`${filename(candidate.title)}-edition.zip`, zipFiles(files)); toast(`${count} reproducible vectors exported.`);
});
-$("#art").width = 1000;
-$("#art").height = 1250;
-for (const id of ["density", "curl", "mode"])
- $("#" + id).addEventListener("input", renderArt);
-$("#export").onclick = () => {
- const c = document.createElement("canvas");
- c.width = +$("#export-size").value;
- c.height = c.width * 1.25;
- drawArt(c, artwork);
- canvasPNG(c, `fieldwork-${hash(seed)}-${artwork.mode}.png`);
- toast("Your print is ready.");
+$('#seed-form').onsubmit = event => { event.preventDefault(); changed(() => { project.seed = $('#seed').value.trim().slice(0, 128) || '1'; }); };
+$('#next-seed').onclick = () => changed(() => { project.seed = /^\d{1,9}$/.test(project.seed) ? String(Number(project.seed) + 1) : `${project.seed.slice(0, 115)}.${Math.floor(artRandom(project.seed, 'next')() * 1000000)}`; });
+for (const dimension of ['width', 'height']) $('#' + dimension).onchange = () => {
+ const value = Number($('#' + dimension).value);
+ if (!Number.isInteger(value) || value < 64 || value > 8192) { toast('Use a size from 64 to 8192 pixels.'); syncFields(); return; }
+ changed(() => { project.formats[format][dimension] = value; });
+};
+$('#undo').onclick = () => { if (!undoStack.length) return; redoStack.push(snapshot()); restore(undoStack.pop()); };
+$('#redo').onclick = () => { if (!redoStack.length) return; undoStack.push(snapshot()); restore(redoStack.pop()); };
+$('#reset-project').onclick = () => changed(() => { project = structuredClone(original); format = 0; }, { rebuild: true });
+$('#use-revision').onclick = () => { preserveDraft = false; $('#revision-notice').hidden = true; persist(); };
+$('#keep-draft').onclick = () => { preserveDraft = false; $('#revision-notice').hidden = true; restore(pendingDraft); };
+try {
+ const saved = JSON.parse(localStorage.getItem(storageKey));
+ if (saved) {
+ saved.project = validateProject(saved.project);
+ if (saved.baseRevision === original.revision) { project = saved.project; format = Math.min(saved.format || 0, project.formats.length - 1); }
+ else { pendingDraft = saved; preserveDraft = true; $('#revision-notice').hidden = false; }
+ }
+} catch { /* A blocked store or an old draft never prevents opening the project. */ }
+const querySeed = new URLSearchParams(location.search).get('seed'); if (querySeed) project.seed = querySeed.slice(0, 128);
+addEventListener('keydown', e => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z' && !e.target.closest('input,textarea,select')) { e.preventDefault(); $('#' + (e.shiftKey ? 'redo' : 'undo')).click(); } });
+window.fieldwork = {
+ getProject: () => portableProject(), getSVG: () => svgText, validateProject,
+ render: async (options = {}) => checkSVG(await renderInWorker(project, { format, ...options })),
+ async deliver(options, scale = 1) {
+ const f = project.formats[options.format || 0], text = checkSVG(await renderInWorker(project, options));
+ const blob = await raster(text, f.width, f.height, scale);
+ const png = await new Promise(resolve => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.readAsDataURL(blob); });
+ return { svg: text, png, width: f.width * scale, height: f.height * scale };
+ },
};
-addEventListener("seedchange", renderArt);
-renderArt();
-ready();
-
+buildUI(); render();
</script></body></html>
diff --git a/store/agents/generative-art/template/sketch/project.json b/store/agents/generative-art/template/sketch/project.json
new file mode 100644
index 000000000..09b37146f
--- /dev/null
+++ b/store/agents/generative-art/template/sketch/project.json
@@ -0,0 +1,25 @@
+{
+ "spec": "fieldwork/1",
+ "id": "night-garden",
+ "title": "Night Garden",
+ "brief": "A nocturnal botanical identity for an independent music festival. Build a poster, square announcement and wide banner with oversized typography and original cut-paper flowers.",
+ "notes": "Example project. Ask the agent for your own visual system; none of these shapes or controls are requirements. The three formats are composed separately from the same design language.",
+ "seed": "42",
+ "formats": [
+ { "name": "Poster", "width": 1200, "height": 1600 },
+ { "name": "Social", "width": 1080, "height": 1080 },
+ { "name": "Banner", "width": 1920, "height": 800 }
+ ],
+ "controls": [
+ { "key": "headline", "type": "text", "label": "Festival name", "value": "NIGHT GARDEN" },
+ { "key": "details", "type": "text", "label": "Date and place", "value": "SEPTEMBER 26—28 · BOTANICAL GROUNDS" },
+ { "key": "lineup", "type": "text", "label": "Lineup", "value": "MIRA / SOFT SIGNAL / LUNAR ASSEMBLY" },
+ { "key": "paper", "type": "color", "label": "Paper", "value": "#f4ead9" },
+ { "key": "ink", "type": "color", "label": "Ink", "value": "#142a24" },
+ { "key": "flower", "type": "color", "label": "Petals", "value": "#f26842" },
+ { "key": "accent", "type": "color", "label": "Center", "value": "#dcf476" },
+ { "key": "petals", "type": "range", "label": "Flower geometry", "min": 5, "max": 14, "step": 1, "value": 8 },
+ { "key": "wildness", "type": "range", "label": "Organic variation", "min": 0, "max": 100, "step": 1, "value": 55 }
+ ],
+ "assets": [{ "key": "logo", "label": "Your logo (optional)" }]
+}
diff --git a/store/agents/generative-art/template/studio/app.js b/store/agents/generative-art/template/studio/app.js
new file mode 100644
index 000000000..2f3ce6be2
--- /dev/null
+++ b/store/agents/generative-art/template/studio/app.js
@@ -0,0 +1,221 @@
+const $ = selector => document.querySelector(selector);
+const original = validateProject(JSON.parse($('#fieldwork-data').textContent));
+const modelSource = $('#fieldwork-model').textContent;
+const storageKey = `fieldwork:${original.id}`;
+let project = structuredClone(original), format = 0, svgText = '', artURL, worker, renderSequence = 0;
+let undoStack = [], redoStack = [], pendingDraft, preserveDraft = false, toastTimer, renderTimer;
+const exportButtons = ['export-svg', 'export-png', 'export-kit', 'export-edition'];
+const snapshot = () => ({ project: structuredClone(project), format });
+function toast(message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 4500); }
+function signal(type, extra = {}) { if (parent !== window) parent.postMessage({ type, seed: project.seed, ...extra }, '*'); }
+function persist() {
+ if (preserveDraft) return;
+ try { localStorage.setItem(storageKey, JSON.stringify({ baseRevision: original.revision, ...snapshot() })); $('#draft-status').textContent = 'Draft saved on this device'; }
+ catch { $('#draft-status').textContent = 'Save project to keep your changes'; }
+}
+function changed(mutate, { rebuild = false } = {}) {
+ undoStack.push(snapshot()); if (undoStack.length > 24) undoStack.shift(); redoStack = [];
+ mutate(); if (rebuild) buildUI(); else syncFields();
+ persist(); scheduleRender();
+}
+function restore(state) { project = validateProject(state.project); format = Math.max(0, Math.min(project.formats.length - 1, state.format || 0)); buildUI(); persist(); scheduleRender(); }
+function saveFile(name, content, type) {
+ const blob = content instanceof Blob ? content : new Blob([content], { type: type || 'application/octet-stream' });
+ const url = URL.createObjectURL(blob), a = document.createElement('a'); a.href = url; a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(url), 30000);
+}
+function baseName(suffix = '') { return `${filename(project.title)}-${filename(project.formats[format].name)}-${filename(project.seed)}${suffix}`; }
+function portableProject() { return { ...structuredClone(project), view: { format } }; }
+function syncFields() {
+ $('#width').value = project.formats[format].width; $('#height').value = project.formats[format].height;
+ $('#dimensions').textContent = `${$('#width').value} × ${$('#height').value}`;
+ $('#seed').value = project.seed;
+ $('#undo').disabled = !undoStack.length; $('#redo').disabled = !redoStack.length;
+ for (const b of $('#formats').children) b.setAttribute('aria-pressed', Number(b.dataset.format) === format);
+ const url = new URL(location.href); url.searchParams.set('seed', project.seed); history.replaceState(null, '', url);
+ signal('harness:state');
+}
+function buildUI() {
+ document.title = `${project.title} · Fieldwork`;
+ $('#project-title').textContent = project.title; $('#brief').textContent = project.brief;
+ $('#notes').textContent = project.notes || 'Your drawing program is original to this project. Ask the agent to change its visual language, composition or outputs.';
+ $('#variation-panel').hidden = project.variations === false;
+ $('#edition-panel').hidden = project.variations === false;
+ $('#formats').replaceChildren();
+ project.formats.forEach((f, i) => { const b = document.createElement('button'); b.textContent = f.name; b.dataset.format = i; b.onclick = () => changed(() => { format = i; }); $('#formats').append(b); });
+ $('#controls').replaceChildren();
+ for (const c of project.controls) {
+ const label = document.createElement('label'), top = document.createElement('span'), title = document.createElement('span'), out = document.createElement('output');
+ label.className = 'field'; top.className = 'field-top'; title.textContent = c.label; top.append(title);
+ let input;
+ if (c.type === 'select') { input = document.createElement('select'); for (const option of c.options) { const el = document.createElement('option'); el.textContent = option; input.append(el); } }
+ else if (c.type === 'text' && c.multiline) input = document.createElement('textarea');
+ else { input = document.createElement('input'); input.type = c.type === 'toggle' ? 'checkbox' : c.type === 'text' ? 'text' : c.type; }
+ input.id = 'control-' + c.key;
+ if (c.type === 'range') { input.min = c.min; input.max = c.max; input.step = c.step ?? 1; out.value = c.value; top.append(out); }
+ if (c.type === 'toggle') input.checked = c.value; else input.value = c.value;
+ if (c.type === 'text') input.maxLength = 4000;
+ input.addEventListener(c.type === 'color' || c.type === 'range' || c.type === 'text' ? 'input' : 'change', () => changed(() => {
+ c.value = c.type === 'toggle' ? input.checked : c.type === 'range' ? Number(input.value) : input.value; out.value = c.value;
+ }));
+ label.append(top, input); $('#controls').append(label);
+ }
+ $('#assets').replaceChildren();
+ for (const asset of project.assets) {
+ const block = document.createElement('div'), name = document.createElement('p'), row = document.createElement('div'), choose = document.createElement('button'), remove = document.createElement('button'), input = document.createElement('input');
+ block.className = 'field'; name.textContent = asset.label; row.className = 'asset-row'; choose.textContent = asset.data ? 'Replace image' : 'Use your image'; remove.textContent = 'Remove'; remove.disabled = !asset.data;
+ input.type = 'file'; input.accept = 'image/png,image/jpeg,image/webp,image/svg+xml'; input.hidden = true; input.setAttribute('aria-label', asset.label);
+ choose.onclick = () => input.click();
+ input.onchange = async () => {
+ try {
+ const file = input.files[0]; if (!file) return;
+ if (file.size > 12000000) throw new Error('Choose an image under 12 MB.');
+ const data = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(file); });
+ const candidate = structuredClone(project); candidate.assets.find(a => a.key === asset.key).data = data; validateProject(candidate);
+ changed(() => { asset.data = data; }, { rebuild: true });
+ } catch (error) { toast(error.message || 'Could not read that image.'); }
+ };
+ remove.onclick = () => changed(() => { delete asset.data; }, { rebuild: true });
+ row.append(choose, remove); block.append(name, row, input); $('#assets').append(block);
+ }
+ syncFields();
+}
+function checkSVG(text) {
+ const externalURL = value => [...value.matchAll(/url\(\s*([^)]*)\)/gi)].some(([, url]) => !/^(#|data:)/i.test(url.trim().replace(/^['"]|['"]$/g, '')));
+ const doc = new DOMParser().parseFromString(text, 'image/svg+xml');
+ if (doc.querySelector('parsererror')) throw new Error('Artwork returned invalid SVG. Ask the agent to fix the drawing program.');
+ for (const node of doc.querySelectorAll('*')) {
+ if (['script', 'foreignobject', 'iframe', 'object', 'embed', 'audio', 'video', 'animate', 'animatetransform', 'set'].includes(node.localName.toLowerCase())) throw new Error('This studio exports static vector artwork. Remove active SVG elements.');
+ for (const attr of node.attributes) {
+ if (/^on/i.test(attr.name) || (/(^|:)href$/.test(attr.name) && !/^(#|data:image\/)/.test(attr.value))) throw new Error('Embed artwork assets so exports work offline.');
+ if (externalURL(attr.value)) throw new Error('External resources are not portable. Embed them in the project.');
+ }
+ if (node.localName === 'style' && (/@import/i.test(node.textContent) || externalURL(node.textContent))) throw new Error('Embed fonts and images; external stylesheets cannot be exported.');
+ }
+ return text;
+}
+function renderInWorker(candidate, options = {}) {
+ return new Promise((resolve, reject) => {
+ const script = modelSource + '\nonmessage = e => { try { postMessage({ svg: renderProject(e.data.project, e.data.options) }); } catch (error) { postMessage({ error: error.message }); } };';
+ const url = URL.createObjectURL(new Blob([script], { type: 'text/javascript' }));
+ const task = new Worker(url); URL.revokeObjectURL(url);
+ const timer = setTimeout(() => { task.terminate(); reject(new Error('This drawing took longer than 5 seconds. Ask the agent to simplify it.')); }, 5000);
+ const done = fn => value => { clearTimeout(timer); task.terminate(); fn(value); };
+ task.onmessage = event => done(event.data.error ? reject : resolve)(event.data.error ? new Error(event.data.error) : event.data.svg);
+ task.onerror = event => done(reject)(new Error(event.message));
+ task.postMessage({ project: candidate, options });
+ });
+}
+function scheduleRender() { ++renderSequence; for (const id of exportButtons) $('#' + id).disabled = true; clearTimeout(renderTimer); renderTimer = setTimeout(render, 80); }
+async function render() {
+ const sequence = ++renderSequence;
+ for (const id of exportButtons) $('#' + id).disabled = true;
+ $('#render-status').textContent = 'Drawing your project…';
+ try {
+ const text = checkSVG(await renderInWorker(project, { format }));
+ if (sequence !== renderSequence) return;
+ const image = $('#art'), nextURL = URL.createObjectURL(new Blob([text], { type: 'image/svg+xml' }));
+ await new Promise((resolve, reject) => { image.onload = resolve; image.onerror = () => reject(new Error('The vector image could not be displayed.')); image.src = nextURL; });
+ if (artURL) URL.revokeObjectURL(artURL); artURL = nextURL;
+ if (sequence !== renderSequence) return;
+ svgText = text; $('#render-error').hidden = true;
+ $('#render-status').textContent = 'Original vector artwork · ready to export';
+ for (const id of exportButtons) $('#' + id).disabled = false;
+ document.body.dataset.ready = 'true'; signal('harness:ready');
+ } catch (error) {
+ if (sequence !== renderSequence) return;
+ $('#render-error').textContent = error.message; $('#render-error').hidden = false;
+ $('#render-status').textContent = 'Drawing needs a fix · exports paused'; signal('harness:error', { message: error.message });
+ }
+}
+async function raster(text, width, height, scale = Number($('#png-scale').value)) {
+ const w = Math.round(width * scale), h = Math.round(height * scale);
+ if (w > 8192 || h > 8192 || w * h > 32000000) throw new Error('PNG is too large. Choose a smaller scale or artboard (maximum 32 megapixels).');
+ const url = URL.createObjectURL(new Blob([text], { type: 'image/svg+xml' }));
+ try {
+ const img = new Image(); img.src = url; await img.decode();
+ const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h;
+ canvas.getContext('2d').drawImage(img, 0, 0, w, h);
+ const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
+ if (!blob) throw new Error('PNG export failed.');
+ return blob;
+ } finally { URL.revokeObjectURL(url); }
+}
+function guard(task) { return async () => { try { await task(); } catch (error) { toast(error.message); } }; }
+$('#export-svg').onclick = () => saveFile(baseName('.svg'), svgText, 'image/svg+xml');
+$('#export-png').onclick = guard(async () => { const f = project.formats[format]; saveFile(baseName('.png'), await raster(svgText, f.width, f.height)); toast('PNG exported at your chosen size.'); });
+$('#save-project').onclick = () => { saveFile(`${filename(project.title)}.fieldwork.json`, JSON.stringify(portableProject(), null, 2), 'application/json'); toast('Editable project saved, including your images and drawing program.'); };
+$('#open-project').onclick = () => $('#project-file').click();
+$('#project-file').onchange = guard(async () => {
+ const file = $('#project-file').files[0]; if (!file) return;
+ if (file.size > 64000000) throw new Error('Project is too large (maximum 64 MB).');
+ const next = validateProject(JSON.parse(await file.text()));
+ changed(() => { project = next; format = Math.min(next.view?.format || 0, next.formats.length - 1); }, { rebuild: true });
+ $('#project-file').value = ''; toast('Project opened.');
+});
+$('#export-html').onclick = () => {
+ const doc = document.documentElement.cloneNode(true);
+ doc.querySelector('#fieldwork-data').textContent = JSON.stringify(portableProject()).replace(/</g, '\\u003c');
+ doc.querySelector('#revision-notice').hidden = true; doc.querySelector('#art').removeAttribute('src');
+ doc.querySelector('#toast').className = ''; doc.querySelector('body').removeAttribute('data-ready');
+ saveFile(`${filename(project.title)}-studio.html`, '<!doctype html>\n' + doc.outerHTML, 'text/html');
+ toast('Portable studio saved. Open it directly in a browser.');
+};
+function sourceFiles() {
+ const p = portableProject(), manifest = structuredClone(p); delete manifest.code; delete manifest.revision; delete manifest.view;
+ return [['project.fieldwork.json', JSON.stringify(p, null, 2)], ['source/project.json', JSON.stringify(manifest, null, 2)], ['source/artwork.js', p.code], ['README.txt', `${p.title}\n\n${p.brief}\n\nOpen SVG in a vector editor. PNGs are ready for publishing. Open project.fieldwork.json in Fieldwork to revise the project; it contains your renderer and embedded images. The source folder contains editable project settings and drawing code. System fonts can vary between machines.\n`]];
+}
+$('#export-kit').onclick = guard(async () => {
+ const candidate = structuredClone(project), files = sourceFiles(), scale = Number($('#png-scale').value);
+ $('#export-kit').disabled = true;
+ try {
+ for (let i = 0; i < candidate.formats.length; i++) {
+ const f = candidate.formats[i], name = `${String(i + 1).padStart(2, '0')}-${filename(f.name)}`, text = checkSVG(await renderInWorker(candidate, { format: i }));
+ files.push([`${name}.svg`, text], [`${name}.png`, await (await raster(text, f.width, f.height, scale)).arrayBuffer()]);
+ }
+ saveFile(`${filename(candidate.title)}-delivery.zip`, zipFiles(files)); toast(`${candidate.formats.length} formats exported as SVG and PNG, with editable source.`);
+ } finally { $('#export-kit').disabled = false; }
+});
+$('#export-edition').onclick = guard(async () => {
+ const count = Number($('#edition-count').value);
+ if (!Number.isInteger(count) || count < 1 || count > 24) throw new Error('Choose an edition of 1–24.');
+ const candidate = structuredClone(project), chosenFormat = format, files = sourceFiles(), seeds = [];
+ for (let i = 0; i < count; i++) {
+ const seed = i === 0 ? candidate.seed : /^\d{1,9}$/.test(candidate.seed) ? String(Number(candidate.seed) + i) : `${candidate.seed}.${i}`;
+ seeds.push(seed); files.push([`edition/${String(i + 1).padStart(2, '0')}-${filename(seed)}.svg`, checkSVG(await renderInWorker(candidate, { format: chosenFormat, seed }))]);
+ }
+ files.push(['edition.json', JSON.stringify({ seeds, format: candidate.formats[chosenFormat], project: candidate.id }, null, 2)]);
+ saveFile(`${filename(candidate.title)}-edition.zip`, zipFiles(files)); toast(`${count} reproducible vectors exported.`);
+});
+$('#seed-form').onsubmit = event => { event.preventDefault(); changed(() => { project.seed = $('#seed').value.trim().slice(0, 128) || '1'; }); };
+$('#next-seed').onclick = () => changed(() => { project.seed = /^\d{1,9}$/.test(project.seed) ? String(Number(project.seed) + 1) : `${project.seed.slice(0, 115)}.${Math.floor(artRandom(project.seed, 'next')() * 1000000)}`; });
+for (const dimension of ['width', 'height']) $('#' + dimension).onchange = () => {
+ const value = Number($('#' + dimension).value);
+ if (!Number.isInteger(value) || value < 64 || value > 8192) { toast('Use a size from 64 to 8192 pixels.'); syncFields(); return; }
+ changed(() => { project.formats[format][dimension] = value; });
+};
+$('#undo').onclick = () => { if (!undoStack.length) return; redoStack.push(snapshot()); restore(undoStack.pop()); };
+$('#redo').onclick = () => { if (!redoStack.length) return; undoStack.push(snapshot()); restore(redoStack.pop()); };
+$('#reset-project').onclick = () => changed(() => { project = structuredClone(original); format = 0; }, { rebuild: true });
+$('#use-revision').onclick = () => { preserveDraft = false; $('#revision-notice').hidden = true; persist(); };
+$('#keep-draft').onclick = () => { preserveDraft = false; $('#revision-notice').hidden = true; restore(pendingDraft); };
+try {
+ const saved = JSON.parse(localStorage.getItem(storageKey));
+ if (saved) {
+ saved.project = validateProject(saved.project);
+ if (saved.baseRevision === original.revision) { project = saved.project; format = Math.min(saved.format || 0, project.formats.length - 1); }
+ else { pendingDraft = saved; preserveDraft = true; $('#revision-notice').hidden = false; }
+ }
+} catch { /* A blocked store or an old draft never prevents opening the project. */ }
+const querySeed = new URLSearchParams(location.search).get('seed'); if (querySeed) project.seed = querySeed.slice(0, 128);
+addEventListener('keydown', e => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z' && !e.target.closest('input,textarea,select')) { e.preventDefault(); $('#' + (e.shiftKey ? 'redo' : 'undo')).click(); } });
+window.fieldwork = {
+ getProject: () => portableProject(), getSVG: () => svgText, validateProject,
+ render: async (options = {}) => checkSVG(await renderInWorker(project, { format, ...options })),
+ async deliver(options, scale = 1) {
+ const f = project.formats[options.format || 0], text = checkSVG(await renderInWorker(project, options));
+ const blob = await raster(text, f.width, f.height, scale);
+ const png = await new Promise(resolve => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.readAsDataURL(blob); });
+ return { svg: text, png, width: f.width * scale, height: f.height * scale };
+ },
+};
+buildUI(); render();
diff --git a/store/agents/generative-art/template/studio/icon.svg b/store/agents/generative-art/template/studio/icon.svg
new file mode 100644
index 000000000..a325c4b1e
--- /dev/null
+++ b/store/agents/generative-art/template/studio/icon.svg
@@ -0,0 +1,11 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">
+ <title>Generative Art — contour edition</title>
+ <rect x="4" y="4" width="88" height="88" rx="23" fill="#eee7d5"/>
+ <g fill="none" stroke="#2d5449" stroke-width="5" stroke-linecap="round">
+ <path d="M21 27c31-20 23 45 54 25"/>
+ <path d="M21 39c31-20 23 45 54 25"/>
+ <path d="M21 51c31-20 23 45 54 25"/>
+ <path d="M21 63c21-14 24 14 37 14"/>
+ </g>
+ <circle cx="71" cy="24" r="7" fill="#ce7645"/>
+</svg>
diff --git a/store/agents/generative-art/template/studio/project.mjs b/store/agents/generative-art/template/studio/project.mjs
new file mode 100644
index 000000000..59afe50ae
--- /dev/null
+++ b/store/agents/generative-art/template/studio/project.mjs
@@ -0,0 +1,93 @@
+// Shared by the authoring tools, preview worker and exported projects.
+export const ART_SPEC = 'fieldwork/1';
+const kinds = new Set(['text', 'color', 'range', 'select', 'toggle']);
+const keyPattern = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;
+export function validateProject(input) {
+ const p = structuredClone(input);
+ if (!p || p.spec !== ART_SPEC) throw new Error('This is not a Fieldwork project.');
+ if (typeof p.id !== 'string' || !/^[a-z0-9-]{1,80}$/.test(p.id)) throw new Error('Project needs a stable id.');
+ for (const name of ['title', 'brief']) if (typeof p[name] !== 'string' || !p[name].trim() || p[name].length > 6000) throw new Error(`Invalid ${name}.`);
+ if (typeof p.code !== 'string' || !p.code.trim() || p.code.length > 500000) throw new Error('The project needs an artwork.js renderer.');
+ // Compile only. Actual rendering happens in a terminable browser worker.
+ new Function('width', 'height', 'seed', 'values', 'assets', 'rng', 'svg', '"use strict";\n' + p.code);
+ if (!Array.isArray(p.formats) || !p.formats.length || p.formats.length > 12) throw new Error('Provide 1–12 output formats.');
+ for (const f of p.formats) {
+ if (typeof f.name !== 'string' || !f.name.trim() || f.name.length > 80) throw new Error('Name each format.');
+ for (const k of ['width', 'height']) if (!Number.isInteger(f[k]) || f[k] < 64 || f[k] > 8192) throw new Error('Artboards must be 64–8192 pixels per side.');
+ }
+ if (!Array.isArray(p.controls) || p.controls.length > 40) throw new Error('Provide at most 40 editable controls.');
+ const ids = new Set();
+ for (const c of p.controls) {
+ if (!keyPattern.test(c.key) || ids.has(c.key) || !kinds.has(c.type) || typeof c.label !== 'string') throw new Error('Invalid or duplicate project control.');
+ ids.add(c.key);
+ if (c.type === 'range' && (![c.min, c.max, c.step ?? 1].every(Number.isFinite) || c.max <= c.min || (c.step ?? 1) <= 0)) throw new Error(`Invalid range: ${c.key}.`);
+ if (c.type === 'select' && (!Array.isArray(c.options) || !c.options.length || c.options.length > 50 || c.options.some(x => typeof x !== 'string'))) throw new Error(`Invalid choices: ${c.key}.`);
+ checkedValue(c, c.value);
+ }
+ p.assets ??= [];
+ if (!Array.isArray(p.assets) || p.assets.length > 12) throw new Error('Provide at most 12 image assets.');
+ ids.clear();
+ for (const a of p.assets) {
+ if (!keyPattern.test(a.key) || ids.has(a.key) || typeof a.label !== 'string') throw new Error('Invalid asset slot.');
+ ids.add(a.key);
+ if (a.data && (typeof a.data !== 'string' || !/^data:image\/(png|jpeg|webp|svg\+xml);base64,[a-zA-Z0-9+/=]+$/.test(a.data) || a.data.length > 16000000)) throw new Error(`Embed ${a.label} as a PNG, JPEG, WebP or SVG image.`);
+ }
+ p.seed = String(p.seed ?? '1').slice(0, 128);
+ if (p.variations !== undefined && typeof p.variations !== 'boolean') throw new Error('variations must be a boolean.');
+ if (JSON.stringify(p).length > 28000000) throw new Error('Keep the editable project under 28 MB. Use smaller embedded images.');
+ return p;
+}
+export function checkedValue(c, value) {
+ if (c.type === 'range' && (!Number.isFinite(value) || value < c.min || value > c.max)) throw new Error(`${c.label} is out of range.`);
+ if (c.type === 'color' && (typeof value !== 'string' || !/^#[0-9a-f]{6}$/i.test(value))) throw new Error(`Invalid ${c.label} color.`);
+ if (c.type === 'text' && (typeof value !== 'string' || value.length > 4000)) throw new Error(`${c.label} must be text under 4000 characters.`);
+ if (c.type === 'select' && !c.options.includes(value)) throw new Error(`Invalid ${c.label} choice.`);
+ if (c.type === 'toggle' && typeof value !== 'boolean') throw new Error(`Invalid ${c.label} toggle.`);
+ return value;
+}
+export function artRandom(seed, namespace = '') {
+ let n = 2166136261;
+ for (const c of String(seed) + ':' + namespace) n = Math.imul(n ^ c.charCodeAt(0), 16777619);
+ return () => { n += 0x6D2B79F5; let t = Math.imul(n ^ n >>> 15, n | 1); t ^= t + Math.imul(t ^ t >>> 7, t | 61); return ((t ^ t >>> 14) >>> 0) / 4294967296; };
+}
+export function xml(value) { return String(value).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' })[c]); }
+export const svg = {
+ escape: xml,
+ el(tag, attrs = {}, children = '') {
+ if (!/^[a-zA-Z][a-zA-Z0-9:-]*$/.test(tag)) throw new Error('Invalid SVG element.');
+ return `<${tag}${Object.entries(attrs).filter(([, v]) => v !== undefined && v !== null).map(([k, v]) => ` ${k}="${xml(v)}"`).join('')}>${Array.isArray(children) ? children.join('') : children}</${tag}>`;
+ },
+ text(value, attrs = {}) { return svg.el('text', attrs, xml(value)); },
+};
+export function renderProject(project, { format = 0, width, height, seed = project.seed, values = {} } = {}) {
+ const f = project.formats[format];
+ if (!f) throw new Error('Choose a valid format.');
+ width ??= f.width; height ??= f.height;
+ if (![width, height].every(n => Number.isInteger(n) && n >= 64 && n <= 8192)) throw new Error('Invalid artboard size.');
+ const resolved = Object.fromEntries(project.controls.map(c => [c.key, checkedValue(c, values[c.key] ?? c.value)]));
+ const assets = Object.fromEntries(project.assets.map(a => [a.key, a.data || '']));
+ const body = new Function('width', 'height', 'seed', 'values', 'assets', 'rng', 'svg', '"use strict";\n' + project.code)(width, height, String(seed), resolved, assets, name => artRandom(seed, name), svg);
+ if (typeof body !== 'string' || !body.trim() || body.length > 24000000) throw new Error('The renderer must return SVG artwork under 24 MB.');
+ return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}"><title>${xml(project.title)}</title>${body}</svg>`;
+}
+export function filename(name) { return String(name).normalize('NFKD').replace(/[^a-zA-Z0-9_.-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 100) || 'artwork'; }
+// ZIP STORE: portable editable delivery without a runtime dependency or a cloud service.
+export function zipFiles(files) {
+ const enc = new TextEncoder(), chunks = [], central = []; let offset = 0;
+ for (const [name, body] of files) {
+ const path = enc.encode(name), bytes = typeof body === 'string' ? enc.encode(body) : new Uint8Array(body);
+ let crc = 0xffffffff;
+ for (const b of bytes) { crc ^= b; for (let i = 0; i < 8; i++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); }
+ crc = (crc ^ 0xffffffff) >>> 0;
+ const header = new Uint8Array(30 + path.length), v = new DataView(header.buffer);
+ v.setUint32(0, 0x04034b50, true); v.setUint16(4, 20, true); v.setUint16(6, 0x800, true); v.setUint16(12, 33, true);
+ v.setUint32(14, crc, true); v.setUint32(18, bytes.length, true); v.setUint32(22, bytes.length, true); v.setUint16(26, path.length, true); header.set(path, 30);
+ const row = new Uint8Array(46 + path.length), c = new DataView(row.buffer);
+ c.setUint32(0, 0x02014b50, true); c.setUint16(4, 20, true); c.setUint16(6, 20, true); c.setUint16(8, 0x800, true); c.setUint16(14, 33, true);
+ c.setUint32(16, crc, true); c.setUint32(20, bytes.length, true); c.setUint32(24, bytes.length, true); c.setUint16(28, path.length, true); c.setUint32(42, offset, true); row.set(path, 46);
+ chunks.push(header, bytes); central.push(row); offset += header.length + bytes.length;
+ }
+ const length = central.reduce((n, row) => n + row.length, 0), end = new Uint8Array(22), e = new DataView(end.buffer);
+ e.setUint32(0, 0x06054b50, true); e.setUint16(8, files.length, true); e.setUint16(10, files.length, true); e.setUint32(12, length, true); e.setUint32(16, offset, true);
+ return new Blob([...chunks, ...central, end], { type: 'application/zip' });
+}
diff --git a/store/agents/generative-art/template/studio/shell.html b/store/agents/generative-art/template/studio/shell.html
new file mode 100644
index 000000000..42afa5f44
--- /dev/null
+++ b/store/agents/generative-art/template/studio/shell.html
@@ -0,0 +1,25 @@
+<!doctype html>
+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Fieldwork · Your visual studio</title><!-- FAVICON --><style>/* STUDIO_CSS */</style></head>
+<body>
+<header><div class="wordmark"><span class="brand-icon" aria-hidden="true"><!-- PROJECT_ICON --></span>FIELDWORK<span>VISUAL STUDIO</span></div><div class="file-actions"><button id="open-project">Open project</button><button id="save-project">Save project</button><button class="primary" id="export-kit">Export kit ↗</button></div></header>
+<div id="revision-notice" class="notice" hidden><span>The agent has made a new version. Your previous draft is saved on this device.</span><button id="use-revision">Use new version</button><button id="keep-draft">Keep my draft</button></div>
+<main>
+<aside class="project-panel">
+<p class="eyebrow">YOUR PROJECT</p><h1 id="project-title"></h1><p id="brief" class="brief"></p>
+<details class="help"><summary>Make something entirely different</summary><p>Describe it in the Harness chat beside this studio. Ask for a new composition, illustration, pattern or visual identity. The agent creates the artwork and the controls for your idea. You never need to write code.</p><p>Try: “Use my café’s name and logo. Create an illustrated coffee bag, a square announcement and a landscape banner. Use woodcut botanical forms.”</p></details>
+<div class="section-heading"><h2>Make it yours</h2><div><button id="undo" title="Undo" aria-label="Undo">↶</button><button id="redo" title="Redo" aria-label="Redo">↷</button></div></div>
+<div id="controls"></div><div id="assets"></div>
+<details class="brief-details"><summary>Project notes</summary><p id="notes"></p><p>Save project includes the drawing program, your adjustments and embedded images. Keep this file to reopen or attach to a new Harness conversation.</p></details>
+</aside>
+<section class="stage-column">
+<div class="stage-toolbar"><div id="formats" role="group" aria-label="Output format"></div><span id="dimensions"></span></div>
+<div class="art-stage" id="art-stage"><img id="art" alt="Your original artwork"><div class="render-error" id="render-error" role="alert" hidden></div></div>
+<div class="canvas-footer"><span><i class="status-dot"></i><span id="render-status">Preparing your artwork</span></span><span id="draft-status">Saved in this browser</span></div>
+<section class="output-panel"><div><p class="eyebrow">DELIVER SOMETHING REAL</p><h2>From your idea. Into the world.</h2><p>Editable SVG for design tools. PNG for publishing. A complete project to keep creating.</p></div><div class="output-actions"><button id="export-svg">Editable SVG ↗</button><button id="export-png">PNG image ↗</button><button id="export-html">Portable studio ↗</button></div></section>
+</section>
+<aside class="production-panel"><p class="eyebrow">ARTBOARD</p><label>Width<input type="number" min="64" max="8192" id="width"></label><label>Height<input type="number" min="64" max="8192" id="height"></label><p class="hint">Pixels. The SVG stays sharp at any size. Ask the agent to adapt the layout to a new proportion.</p>
+<div id="variation-panel"><div class="rule"></div><p class="eyebrow">VARIATION</p><form id="seed-form"><label for="seed">Composition seed</label><div class="seed-row"><input id="seed" maxlength="128"><button type="submit">Apply</button></div><button id="next-seed" type="button">Explore another ↗</button></form><p class="hint">The same project and seed recreate the same vector geometry.</p></div>
+<div class="rule"></div><p class="eyebrow">EXPORT</p><label>PNG scale<select id="png-scale"><option value="1">1× · artboard size</option><option value="2">2× · double size</option><option value="4">4× · print detail</option></select></label><div id="edition-panel"><label>Edition count<input id="edition-count" type="number" min="1" max="24" value="1"></label><button id="export-edition">Export SVG edition ↗</button><p class="hint">Edition ZIP includes the exact seeds and your editable source. Export kit includes every named format as SVG and PNG.</p></div>
+<div class="rule"></div><button id="reset-project" class="quiet">Restore agent version</button></aside>
+</main><div id="toast" role="status"></div><input type="file" id="project-file" accept=".json,application/json" hidden>
+<script id="fieldwork-data" type="application/json">"PROJECT_DATA"</script><script id="fieldwork-model">/* PROJECT_MODEL */</script><script>/* STUDIO_APP */</script></body></html>
diff --git a/store/agents/generative-art/template/studio/style.css b/store/agents/generative-art/template/studio/style.css
new file mode 100644
index 000000000..a0efbe76d
--- /dev/null
+++ b/store/agents/generative-art/template/studio/style.css
@@ -0,0 +1,2 @@
+:root{color-scheme:dark;--bg:#111513;--panel:#171c19;--line:#ffffff17;--ink:#f0f2e9;--muted:#99a59b;--accent:#d6fa8b;font:13px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink)}button,input,select,textarea{font:inherit;color:inherit;border:1px solid var(--line);border-radius:6px;background:var(--panel);padding:9px 11px;min-width:0}button{cursor:pointer;touch-action:manipulation}button:hover{border-color:#879280;background:#253022}button:disabled{opacity:.4;cursor:default}button.primary{background:var(--accent);color:#182319;border-color:transparent;font-weight:650}button:focus-visible,input:focus-visible,summary:focus-visible{outline:2px solid var(--accent);outline-offset:3px}button[aria-pressed=true]{color:var(--accent);border-color:#d6fa8b55;background:#253022}button.quiet{color:var(--muted);width:100%}input[type=range]{padding:0;accent-color:var(--accent);width:100%}input[type=color]{height:38px;width:100%;padding:3px}input[type=checkbox]{accent-color:var(--accent)}textarea{resize:vertical;min-height:64px;width:100%}header{min-height:73px;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;padding:16px 25px;gap:16px}.wordmark{display:flex;align-items:center;gap:10px;font-size:12px;letter-spacing:.08em;font-weight:700}.wordmark span{font-size:9px;border-left:1px solid var(--line);padding-left:13px;color:var(--muted);font-weight:400}.file-actions{display:flex;gap:8px}main{display:grid;grid-template-columns:270px minmax(300px,1fr) 205px;min-height:calc(100vh - 73px)}aside{padding:28px 22px}.project-panel{border-right:1px solid var(--line)}.production-panel{border-left:1px solid var(--line)}h1,h2,p{margin:0}h1{font-size:29px;line-height:1.1;letter-spacing:-.04em;margin:12px 0 16px;font-weight:560}h2{font-size:14px;font-weight:550}.eyebrow{font-size:9px;letter-spacing:.17em;color:var(--muted);font-family:ui-monospace,monospace}.brief{color:#b9c2b9;font-size:12px;line-height:1.6}.help{margin-top:16px;padding:12px;background:#d6fa8b08;border:1px solid #d6fa8b20;border-radius:7px;font-size:11px}.help summary{color:var(--accent);cursor:pointer}.help p{margin-top:10px;color:var(--muted)}.section-heading{display:flex;justify-content:space-between;align-items:center;margin:27px 0 10px;padding-top:22px;border-top:1px solid var(--line)}.section-heading button{padding:3px 8px;font-size:18px}.field,label{display:flex;flex-direction:column;gap:7px;margin:16px 0;color:#cbd2ca;font-size:11px}.field-top{display:flex;justify-content:space-between;align-items:center;gap:8px}.field output{color:var(--muted);font-variant-numeric:tabular-nums}.asset-preview{max-height:60px;max-width:100%;object-fit:contain}.asset-row{display:flex;gap:7px}.asset-row button{font-size:11px}.hint{font-size:10px;color:var(--muted);line-height:1.65}.brief-details{margin-top:24px;font-size:11px;color:var(--muted)}.brief-details summary{cursor:pointer}.brief-details p{margin-top:10px}.stage-column{min-width:0;background:#0c100e;display:flex;flex-direction:column}.stage-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:15px 22px;min-height:65px;border-bottom:1px solid var(--line)}#formats{display:flex;gap:5px;flex-wrap:wrap}#formats button{font-size:10px;padding:6px 10px;background:transparent}#dimensions{font-size:10px;white-space:nowrap;color:var(--muted);font-family:ui-monospace,monospace}.art-stage{position:relative;min-height:520px;flex:1;display:flex;justify-content:center;align-items:center;padding:34px 44px;background:radial-gradient(ellipse at 50% 35%,#27312955,transparent 65%)}#art{max-width:100%;width:auto;height:auto;max-height:calc(100vh - 320px);min-height:180px;object-fit:contain;box-shadow:0 15px 50px #0008}.canvas-footer{display:flex;justify-content:space-between;padding:10px 23px;border-top:1px solid var(--line);gap:15px;font-size:9px;letter-spacing:.02em;color:var(--muted)}.status-dot{display:inline-block;width:5px;height:5px;border-radius:50%;background:var(--accent);margin-right:7px}.output-panel{padding:23px;display:flex;align-items:center;justify-content:space-between;gap:20px;border-top:1px solid var(--line)}.output-panel h2{font-size:18px;letter-spacing:-.025em;margin:6px 0}.output-panel p:not(.eyebrow){font-size:10px;color:var(--muted)}.output-actions{display:flex;flex-direction:column;gap:6px;min-width:137px}.output-actions button{font-size:10px}.rule{height:1px;background:var(--line);margin:25px 0}.seed-row{display:flex;gap:5px}.seed-row input{width:100%}#next-seed,#export-edition{font-size:11px;width:100%;margin:5px 0 10px}#toast{position:fixed;bottom:24px;left:50%;transform:translate(-50%,15px);max-width:min(600px,90vw);padding:11px 18px;background:#e8f0df;color:#172115;border-radius:7px;opacity:0;pointer-events:none;z-index:10;box-shadow:0 10px 40px #0007;transition:.15s}#toast.visible{opacity:1;transform:translate(-50%,0)}.render-error{position:absolute;inset:auto 25px 25px;background:#47251f;color:#ffddd0;padding:18px;border:1px solid #a45e4a;border-radius:7px;white-space:pre-wrap}.notice{padding:12px 25px;display:flex;gap:12px;align-items:center;background:#39341d;font-size:11px}.notice button{font-size:11px}.notice[hidden], [hidden]{display:none!important}@media(min-width:1600px){main{grid-template-columns:300px minmax(300px,1fr) 230px}.art-stage{min-height:650px}.project-panel{padding:34px 28px}}@media(max-width:1100px){main{grid-template-columns:245px minmax(240px,1fr)}.production-panel{grid-column:1/-1;display:grid;grid-template-columns:repeat(3,1fr);gap:0 22px;border-top:1px solid var(--line)}.production-panel>.rule{display:none}.production-panel>.eyebrow{grid-column:1/-1;margin-top:12px}.output-panel{align-items:flex-start;flex-direction:column}.output-actions{flex-direction:row;flex-wrap:wrap}.art-stage{padding:25px;min-height:460px}.wordmark span{display:none}}@media(max-width:650px){header{padding:14px;align-items:flex-start;flex-wrap:wrap}.file-actions{width:100%}.file-actions button{flex:1;font-size:11px}main{display:flex;flex-direction:column}.stage-column{order:0}.project-panel{order:1;border-top:1px solid var(--line);border-right:none}.production-panel{order:2;display:block;border-left:none}.art-stage{min-height:360px;padding:25px 20px}#art{max-height:60vh}.stage-toolbar{padding:12px;flex-wrap:wrap}.output-panel{padding:18px}.canvas-footer{padding:10px 14px;font-size:8px}.notice{flex-wrap:wrap}aside{padding:24px}h1{font-size:30px}}@media(prefers-reduced-motion:reduce){*{transition:none!important}}
+.wordmark .brand-icon{display:block;width:27px;height:27px;padding:0;border:0}.brand-icon svg{display:block;width:100%;height:100%}
diff --git a/store/agents/generative-art/template/tools/build.mjs b/store/agents/generative-art/template/tools/build.mjs
new file mode 100644
index 000000000..69e5bec1c
--- /dev/null
+++ b/store/agents/generative-art/template/tools/build.mjs
@@ -0,0 +1,48 @@
+#!/usr/bin/env node
+import { readFile, writeFile, mkdir, realpath } from 'node:fs/promises';
+import { resolve, dirname, extname, sep } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createHash } from 'node:crypto';
+import { validateProject } from '../studio/project.mjs';
+
+export async function buildArt(workspace, { check = false } = {}) {
+ const root = resolve(workspace), source = resolve(root, 'sketch');
+ if (!check) {
+ await mkdir(resolve(root, '.harness'), { recursive: true });
+ await writeFile(resolve(root, '.harness/verdict.json'), JSON.stringify({ spec: 1, ready: false, artifact: 'sketch/index.html', summary: 'Building artwork · verification pending' }));
+ }
+ const read = name => readFile(resolve(root, name), 'utf8');
+ const project = JSON.parse(await read('sketch/project.json'));
+ project.code = await read('sketch/artwork.js');
+ for (const asset of project.assets || []) {
+ if (!asset.file) continue;
+ const actual = await realpath(resolve(source, asset.file));
+ const base = await realpath(source);
+ if (!actual.startsWith(base + sep)) throw new Error(`Asset must live inside sketch/: ${asset.file}`);
+ const mime = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.svg': 'image/svg+xml' }[extname(actual).toLowerCase()];
+ if (!mime) throw new Error(`Unsupported asset: ${asset.file}`);
+ const bytes = await readFile(actual);
+ if (bytes.length > 12000000) throw new Error(`Asset is over 12 MB: ${asset.file}`);
+ asset.data = `data:${mime};base64,${bytes.toString('base64')}`;
+ delete asset.file;
+ }
+ validateProject(project);
+ const revision = createHash('sha256').update(JSON.stringify(project)).digest('hex');
+ const [shell, css, model, app, icon] = await Promise.all(['studio/shell.html', 'studio/style.css', 'studio/project.mjs', 'studio/app.js', 'studio/icon.svg'].map(read));
+ const js = text => text.replace(/<\/script/gi, '<\\/script');
+ const data = JSON.stringify({ ...project, revision }).replace(/</g, '\\u003c');
+ const html = shell.replace('/* STUDIO_CSS */', () => css).replace('/* PROJECT_MODEL */', () => js(model.replace(/^export /gm, ''))).replace('/* STUDIO_APP */', () => js(app)).replace('"PROJECT_DATA"', () => data).replace('<!-- PROJECT_ICON -->', () => icon).replace('<!-- FAVICON -->', () => `<link rel="icon" href="data:image/svg+xml,${encodeURIComponent(icon)}">`);
+ const out = resolve(source, 'index.html');
+ if (check) {
+ if (await readFile(out, 'utf8') !== html) throw new Error('Preview is out of date. Run node tools/build.mjs.');
+ } else {
+ await writeFile(out, html);
+ await mkdir(resolve(root, '.harness'), { recursive: true });
+ await writeFile(resolve(root, '.harness/verdict.json'), JSON.stringify({ spec: 1, ready: false, artifact: 'sketch/index.html', summary: `${project.title} built · export and visual review pending`, findings: [{ severity: 'info', kind: 'review_pending', message: 'A successful build does not establish visual quality or match to the brief.' }] }, null, 2) + '\n');
+ }
+ return { title: project.title, revision, formats: project.formats.length, htmlBytes: Buffer.byteLength(html) };
+}
+if (process.argv[1] && await realpath(process.argv[1]).catch(() => '') === fileURLToPath(import.meta.url)) {
+ try { console.log(JSON.stringify(await buildArt(resolve(dirname(fileURLToPath(import.meta.url)), '..'), { check: process.argv.includes('--check') }))); }
+ catch (error) { console.error(error.message); process.exitCode = 1; }
+}
diff --git a/store/agents/generative-art/template/tools/check.mjs b/store/agents/generative-art/template/tools/check.mjs
index 19413fa14..b1cc0b418 100644
--- a/store/agents/generative-art/template/tools/check.mjs
+++ b/store/agents/generative-art/template/tools/check.mjs
@@ -1,75 +1,6 @@
-const CONFIG = {"id":"generative-art","artifact":"sketch/index.html"};
-// Compiled into each workspace's tools/check.mjs. Tests the model in the ACTUAL edited HTML.
-import { readFile, mkdir, writeFile } from "node:fs/promises";
-import { createHash } from "node:crypto";
-import vm from "node:vm";
-import { resolve, dirname } from "node:path";
-
-const args = process.argv.slice(2),
- i = args.indexOf("--seeds");
-const count = i === -1 ? 32 : Number(args[i + 1]);
-if (!Number.isInteger(count) || count < 1 || count > 1000)
- throw new Error("--seeds must be an integer from 1 to 1000");
-const artifact = resolve(CONFIG.artifact);
-const html = await readFile(artifact, "utf8");
-const script = html.match(
- /<script id="harness-model">([\s\S]*?)<\/script>/,
-)?.[1];
-if (!script)
- throw new Error(
- 'Keep the pure model in <script id="harness-model"> so this checker can exercise the actual artifact.',
- );
-const expressions = {
- "generative-art": `const m=artModel(SEED);const p=artPaths(m);({state:m,valid:p.length>0&&p.flat().every(([x,y])=>Number.isFinite(x)&&Number.isFinite(y)),metrics:{paths:p.length,palette:m.palette}})`,
- "creative-direction": `const m=directionModel(SEED);const ratio=contrast(m.colors[0],m.colors[1]);({state:m,valid:ratio>=4.5,metrics:{direction:m.name,contrast:ratio}})`,
- "lab-bench": `const p=experiment(SEED),e=treatmentEffect(p);({state:p,valid:p.length>1&&p.every(p=>Number.isFinite(p.x)&&Number.isFinite(p.y))&&Number.isFinite(e.low)&&e.low<=e.high,metrics:{samples:p.length,effect:e.difference,interval:[e.low,e.high]}})`,
- "music-studio": `const s=musicScore(SEED),r=renderMusic(s);({state:Array.from(r.samples),valid:r.peak>.001&&r.peak<=.95&&r.samples.every(Number.isFinite),metrics:{seconds:r.duration,peak:r.peak,rms:r.rms}})`,
- "game-master": `const m=arenaMatch(SEED),s=m.history.at(-1);({state:m,valid:m.history.length>1&&m.history.length<=10000&&s.units.every(u=>u.hp>=0&&u.x>=0&&u.x<m.map.w&&u.y>=0&&u.y<m.map.h),metrics:{turns:s.turn,score:s.score,winner:m.winner}})`,
- "drone-pilot": `const s=flyAutopilot(SEED);({state:s,valid:s.finished&&!s.crashed&&s.passed===flightCourse(SEED).length,metrics:{seconds:s.time,passed:s.passed,missed:s.missed}})`,
- "voxel-worlds": `const w=voxelWorld(SEED);let p={...w.spawn,vy:0,grounded:true};const clear=playerFits(w,p.x,p.y,p.z);for(let t=0;t<120;t++)p=movePlayer(w,p,{forward:1});({state:Array.from(w.blocks),valid:clear&&playerFits(w,p.x,p.y,p.z),metrics:{blocks:w.blocks.filter(Boolean).length,walkDistance:Math.hypot(p.x-w.spawn.x,p.z-w.spawn.z)}})`,
-};
-const expression = expressions[CONFIG.id];
-const digest = (value) =>
- createHash("sha256").update(JSON.stringify(value)).digest("hex");
-const results = [];
-for (let seed = 0; seed < count; seed++) {
- const run = () =>
- vm.runInNewContext(
- `${script}\n${expression}`,
- { SEED: String(seed) },
- { timeout: 10000 },
- );
- try {
- const first = run(),
- second = run(),
- signature = digest(first.state),
- repeat = digest(second.state);
- results.push({
- seed,
- ok: first.valid && signature === repeat,
- signature,
- metrics: first.metrics,
- });
- } catch (error) {
- results.push({ seed, ok: false, error: error.message });
- }
-}
-const passed = results.filter((r) => r.ok).length;
-const report = {
- spec: 1,
- harness: CONFIG.id,
- artifact: CONFIG.artifact,
- checkedAt: new Date().toISOString(),
- modelChecks: { passed, total: count },
- scope:
- "Pure model invariants and same-process repeatability. Browser interaction, layout, listening and export review still required.",
- results,
-};
-const out = resolve(".harness/model-check.json");
-await mkdir(dirname(out), { recursive: true });
-await writeFile(out, JSON.stringify(report, null, 2) + "\n");
-console.log(
- `${CONFIG.id}: ${passed}/${count} model checks passed. Report: ${out}`,
-);
-console.log(report.scope);
-if (passed !== count) process.exitCode = 1;
+import { buildArt } from './build.mjs';
+import { fileURLToPath } from 'node:url';
+try {
+ const result = await buildArt(fileURLToPath(new URL('..', import.meta.url)), { check: true });
+ console.log(JSON.stringify({ ...result, ready: false, next: 'Run node tools/export.mjs, inspect the exported artwork, and compare it to the brief.' }));
+} catch (error) { console.error(error.message); process.exitCode = 1; }
diff --git a/store/agents/generative-art/template/tools/export.mjs b/store/agents/generative-art/template/tools/export.mjs
new file mode 100644
index 000000000..28a3d6e7a
--- /dev/null
+++ b/store/agents/generative-art/template/tools/export.mjs
@@ -0,0 +1,51 @@
+#!/usr/bin/env node
+// Production export and repeatability checks on the user's actual program, not a preset model.
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { resolve, join } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { createHash } from 'node:crypto';
+import { buildArt } from './build.mjs';
+import { filename } from '../studio/project.mjs';
+const root = fileURLToPath(new URL('..', import.meta.url));
+const args = process.argv.slice(2), arg = (name, fallback) => args.includes(name) ? args[args.indexOf(name) + 1] : fallback;
+const count = Number(arg('--seeds', 3)), scale = Number(arg('--scale', 1));
+if (!Number.isInteger(count) || count < 1 || count > 100 || ![1, 2, 4].includes(scale)) throw new Error('Use --seeds 1–100 and --scale 1, 2 or 4.');
+const output = resolve(root, arg('--out', 'delivery'));
+await buildArt(root);
+const toolchain = process.env.GENART_DSH_DIR ? pathToFileURL(join(process.env.GENART_DSH_DIR, 'toolchain/')).href : new URL('../../toolchain/', import.meta.url).href;
+const modulePath = process.env.PLAYWRIGHT_MODULE || new URL('node_modules/playwright-core/index.mjs', toolchain).href;
+let chromium;
+try { ({ chromium } = await import(modulePath)); }
+catch { throw new Error('Run the Generative Art toolchain setup first (Playwright is required for real exports).'); }
+const executablePath = process.env.BROWSER_EXECUTABLE || await (await import(new URL('browser.mjs', toolchain).href)).browserPath();
+const browser = await chromium.launch({ executablePath, headless: true });
+try {
+ await mkdir(output, { recursive: true });
+ const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
+ const errors = []; page.on('pageerror', e => errors.push(e.message));
+ await page.goto(pathToFileURL(join(root, 'sketch/index.html')).href);
+ await page.locator('body[data-ready=true]').waitFor({ timeout: 15000 });
+ const project = await page.evaluate(() => fieldwork.getProject());
+ const hash = data => createHash('sha256').update(data).digest('hex');
+ const results = [];
+ for (let i = 0; i < count; i++) {
+ const seed = i === 0 ? project.seed : /^\d{1,9}$/.test(project.seed) ? String(Number(project.seed) + i) : `${project.seed}.${i}`;
+ for (let format = 0; format < project.formats.length; format++) {
+ const first = await page.evaluate(({ options, scale }) => fieldwork.deliver(options, scale), { options: { seed, format }, scale });
+ const repeated = await page.evaluate(options => fieldwork.render(options), { seed, format });
+ if (first.svg !== repeated) throw new Error(`Non-deterministic vector: seed ${seed}, ${project.formats[format].name}.`);
+ const prefix = `${String(format + 1).padStart(2, '0')}-${filename(project.formats[format].name)}-${filename(seed)}`;
+ const png = Buffer.from(first.png.split(',')[1], 'base64');
+ if (png.readUInt32BE(16) !== first.width || png.readUInt32BE(20) !== first.height) throw new Error('PNG dimensions do not match the requested output.');
+ await writeFile(join(output, prefix + '.svg'), first.svg); await writeFile(join(output, prefix + '.png'), png);
+ results.push({ seed, format: project.formats[format].name, width: first.width, height: first.height, svg: prefix + '.svg', png: prefix + '.png', sha256: hash(first.svg), pngSha256: hash(png), sameSeedVector: true });
+ }
+ }
+ if (errors.length) throw new Error(errors.join('\n'));
+ await page.screenshot({ path: join(output, 'studio.png'), fullPage: true });
+ await writeFile(join(output, 'project.fieldwork.json'), JSON.stringify(project, null, 2));
+ await writeFile(join(output, 'studio.html'), await readFile(join(root, 'sketch/index.html')));
+ const report = { title: project.title, brief: project.brief, sourceRevision: project.revision, ready: false, exports: results, limitation: 'Geometry repeated exactly in this browser. Visual match to the brief requires review. SVG text uses system fonts, which can differ on another machine.' };
+ await writeFile(join(output, 'verification.json'), JSON.stringify(report, null, 2));
+ console.log(JSON.stringify({ output, formats: project.formats.length, seeds: count, exports: results.length, ready: false, next: 'Inspect the real exported SVGs and PNGs against the brief before marking ready.' }));
+} finally { await browser.close(); }
diff --git a/store/agents/generative-art/template/tools/import-project.mjs b/store/agents/generative-art/template/tools/import-project.mjs
new file mode 100644
index 000000000..cc6da7f1a
--- /dev/null
+++ b/store/agents/generative-art/template/tools/import-project.mjs
@@ -0,0 +1,18 @@
+#!/usr/bin/env node
+import { readFile, writeFile, mkdir } from 'node:fs/promises';
+import { resolve, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { validateProject } from '../studio/project.mjs';
+import { buildArt } from './build.mjs';
+const root = fileURLToPath(new URL('..', import.meta.url));
+if (!process.argv[2]) throw new Error('Usage: node tools/import-project.mjs path/to/project.fieldwork.json');
+const bytes = await readFile(resolve(process.argv[2]), 'utf8');
+if (bytes.length > 64000000) throw new Error('Project exceeds 64 MB.');
+const project = validateProject(JSON.parse(bytes));
+const backup = join(root, '.harness/history', new Date().toISOString().replace(/[:.]/g, '-'));
+await mkdir(backup, { recursive: true });
+for (const name of ['project.json', 'artwork.js']) await writeFile(join(backup, name), await readFile(join(root, 'sketch', name)));
+const manifest = structuredClone(project); delete manifest.code; delete manifest.revision; delete manifest.view;
+await writeFile(join(root, 'sketch/project.json'), JSON.stringify(manifest, null, 2) + '\n');
+await writeFile(join(root, 'sketch/artwork.js'), project.code);
+console.log(JSON.stringify({ ...await buildArt(root), backup }));
diff --git a/store/agents/generative-art/test/projects.test.mjs b/store/agents/generative-art/test/projects.test.mjs
new file mode 100644
index 000000000..99bf5ab05
--- /dev/null
+++ b/store/agents/generative-art/test/projects.test.mjs
@@ -0,0 +1,60 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { readFile, mkdtemp, cp, writeFile, rm, mkdir } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { fileURLToPath } from 'node:url';
+import { validateProject, renderProject } from '../template/studio/project.mjs';
+import { buildArt } from '../template/tools/build.mjs';
+const root = fileURLToPath(new URL('..', import.meta.url));
+async function load(dir) {
+ const p = JSON.parse(await readFile(join(dir, 'project.json'), 'utf8'));
+ p.code = await readFile(join(dir, 'artwork.js'), 'utf8');
+ for (const a of p.assets) if (a.file) { a.data = 'data:image/svg+xml;base64,' + (await readFile(join(dir, a.file))).toString('base64'); delete a.file; }
+ return validateProject(p);
+}
+for (const dir of ['template/sketch', 'examples/coffee', 'examples/data-atlas']) test(`${dir}: a different original program, all formats repeat and escape user text`, async () => {
+ const p = await load(join(root, dir));
+ for (let i = 0; i < p.formats.length; i++) {
+ const a = renderProject(p, { format: i });
+ assert.equal(a, renderProject(p, { format: i }));
+ assert.match(a, new RegExp(`width="${p.formats[i].width}" height="${p.formats[i].height}"`));
+ assert.ok(a.length > 500);
+ }
+ const text = p.controls.find(c => c.type === 'text');
+ const output = renderProject(p, { values: { [text.key]: 'A & B <new>' } });
+ assert.match(output, /&amp;/); assert.match(output, /&lt;new&gt;/);
+ if (p.variations !== false) assert.notEqual(renderProject(p, { seed: '1' }), renderProject(p, { seed: '2' }));
+});
+test('the renderer is not restricted to the shipped visual vocabulary', async () => {
+ const p = await load(join(root, 'template/sketch'));
+ p.code = 'return svg.el("path", {d: `M0 0 L${width} ${height} L0 ${height} Z`, fill: values.ink})';
+ assert.match(renderProject(validateProject(p)), /M0 0 L1200 1600 L0 1600 Z/);
+ assert.doesNotMatch(renderProject(p), /NIGHT GARDEN/);
+});
+test('rejects broken controls, invalid dimensions and missing drawing programs', async () => {
+ const p = await load(join(root, 'template/sketch'));
+ for (const mutate of [x => { x.code = ''; }, x => { x.code = 'return {'; }, x => { x.formats[0].width = 0; }, x => { x.controls[0].key = '__proto__'; }, x => { x.controls[0].value = 4; }, x => { x.assets[0].data = 'https://remote.example/image.png'; }]) {
+ const broken = structuredClone(p); mutate(broken); assert.throws(() => validateProject(broken));
+ }
+});
+test('a fresh project builds, embeds local material and detects stale preview/source drift', async () => {
+ const ws = await mkdtemp(join(tmpdir(), 'fieldwork-build-'));
+ try {
+ await cp(join(root, 'template'), ws, { recursive: true });
+ await cp(join(root, 'examples/coffee'), join(ws, 'sketch'), { recursive: true });
+ await buildArt(ws); await buildArt(ws, { check: true });
+ const html = await readFile(join(ws, 'sketch/index.html'), 'utf8');
+ assert.match(html, /data:image\/svg\+xml;base64/);
+ const manifest = JSON.parse(await readFile(join(ws, 'sketch/project.json'), 'utf8'));
+ manifest.controls[0].value = 'USER REVISION $& </script> & <tag>';
+ await writeFile(join(ws, 'sketch/project.json'), JSON.stringify(manifest));
+ await assert.rejects(buildArt(ws, { check: true }), /out of date/);
+ await buildArt(ws);
+ assert.match(await readFile(join(ws, 'sketch/index.html'), 'utf8'), /USER REVISION/);
+ const rebuilt = await readFile(join(ws, 'sketch/index.html'), 'utf8');
+ const data = JSON.parse(rebuilt.match(/<script id="fieldwork-data" type="application\/json">([\s\S]*?)<\/script>/)[1]);
+ assert.equal(data.controls[0].value, manifest.controls[0].value);
+ assert.equal(JSON.parse(await readFile(join(ws, '.harness/verdict.json'), 'utf8')).ready, false);
+ } finally { await rm(ws, { recursive: true, force: true }); }
+});
diff --git a/store/agents/generative-art/test/toolchain.test.mjs b/store/agents/generative-art/test/toolchain.test.mjs
index c228b1126..4ffd24fb1 100644
--- a/store/agents/generative-art/test/toolchain.test.mjs
+++ b/store/agents/generative-art/test/toolchain.test.mjs
@@ -28,11 +28,14 @@ test('every script the manifest names is in the folder and executable', () => {
}
})
-test('setup installs nothing and succeeds quietly', () => {
- assert.deepEqual(run(manifest.toolchain.setup), { code: 0, stdout: '', stderr: '' })
+test('setup installs package-local export tools and finds a browser', () => {
+ const result = run(manifest.toolchain.setup)
+ assert.equal(result.code, 0, result.stderr)
+ assert.match(result.stdout, /ok export browser:/)
+ assert.doesNotThrow(() => accessSync(join(here, 'toolchain/node_modules/playwright-core/index.mjs')))
})
-test('doctor says ok when sh is on PATH', () => {
+test('doctor verifies authoring and export tools', () => {
assert.equal(run(manifest.toolchain.doctor).code, 0)
})
diff --git a/store/agents/generative-art/toolchain/browser.mjs b/store/agents/generative-art/toolchain/browser.mjs
new file mode 100644
index 000000000..a2ca5d644
--- /dev/null
+++ b/store/agents/generative-art/toolchain/browser.mjs
@@ -0,0 +1,18 @@
+import { access, writeFile, readFile } from 'node:fs/promises';
+import { execFileSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { join } from 'node:path';
+const dir = fileURLToPath(new URL('.', import.meta.url));
+export async function browserPath({ install = false } = {}) {
+ const candidates = [process.env.BROWSER_EXECUTABLE, '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', process.env.PROGRAMFILES && join(process.env.PROGRAMFILES, 'Google/Chrome/Application/chrome.exe')].filter(Boolean);
+ for (const path of candidates) { try { await access(path); return path; } catch {} }
+ process.env.PLAYWRIGHT_BROWSERS_PATH = join(dir, 'browsers');
+ const { chromium } = await import('./node_modules/playwright-core/index.mjs');
+ const path = chromium.executablePath();
+ try { await access(path); return path; } catch {}
+ if (!install) throw new Error('Browser missing. Run the Generative Art setup script.');
+ execFileSync(process.execPath, [join(dir, 'node_modules/playwright-core/cli.js'), 'install', 'chromium'], { stdio: 'inherit', env: process.env });
+ await access(path); return path;
+}
+if (process.argv.includes('--install')) console.log(`ok export browser: ${await browserPath({ install: true })}`);
+if (process.argv.includes('--check')) console.log(`ok export browser: ${await browserPath()}`);
diff --git a/store/agents/generative-art/toolchain/doctor.sh b/store/agents/generative-art/toolchain/doctor.sh
index 66f5b1083..cf5f6c3c4 100755
--- a/store/agents/generative-art/toolchain/doctor.sh
+++ b/store/agents/generative-art/toolchain/doctor.sh
@@ -1,5 +1,5 @@
#!/bin/sh
-# Exit 0 when this machine can run the harness. Print one line per check; Harness shows them.
-command -v sh >/dev/null 2>&1 && echo "ok sh (art runtime)" || { echo "miss sh"; exit 1; }
-command -v node >/dev/null 2>&1 && echo "ok node (for seed-census verify)" || echo "note node optional: seed census needs node"
-exit 0
+set -eu
+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+node -e 'if(Number(process.versions.node.split(".")[0]) < 20) process.exit(1); console.log("ok Node.js (authoring tools)")'
+node "$here/browser.mjs" --check
diff --git a/store/agents/generative-art/toolchain/package-lock.json b/store/agents/generative-art/toolchain/package-lock.json
new file mode 100644
index 000000000..2dc0b60ff
--- /dev/null
+++ b/store/agents/generative-art/toolchain/package-lock.json
@@ -0,0 +1,25 @@
+{
+ "name": "fieldwork-exporter",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "fieldwork-exporter",
+ "dependencies": {
+ "playwright-core": "1.63.0"
+ }
+ },
+ "node_modules/playwright-core": {
+ "version": "1.63.0",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
+ "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ }
+ }
+}
diff --git a/store/agents/generative-art/toolchain/package.json b/store/agents/generative-art/toolchain/package.json
new file mode 100644
index 000000000..023d8413e
--- /dev/null
+++ b/store/agents/generative-art/toolchain/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "fieldwork-exporter",
+ "private": true,
+ "type": "module",
+ "dependencies": { "playwright-core": "1.63.0" }
+}
diff --git a/store/agents/generative-art/toolchain/setup.sh b/store/agents/generative-art/toolchain/setup.sh
index 4325cad0b..3c263d1fc 100755
--- a/store/agents/generative-art/toolchain/setup.sh
+++ b/store/agents/generative-art/toolchain/setup.sh
@@ -1,3 +1,8 @@
#!/bin/sh
-# Nothing to install: art renders in the built-in web-viewer. Kept so the shape matches a real one.
-exit 0
+# Browser exports use pinned tools installed in this package, never globally.
+set -eu
+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+node -e 'if(Number(process.versions.node.split(".")[0]) < 20) process.exit(1)'
+cd "$here"
+npm ci --ignore-scripts --no-audit --no-fund
+node browser.mjs --install
diff --git a/store/agents/music-studio/.gitignore b/store/agents/music-studio/.gitignore
new file mode 100644
index 000000000..00758e57d
--- /dev/null
+++ b/store/agents/music-studio/.gitignore
@@ -0,0 +1,4 @@
+toolchain/node_modules/
+toolchain/browsers/
+template/.harness/
+template/delivery/
diff --git a/store/agents/music-studio/AGENTS.md b/store/agents/music-studio/AGENTS.md
index 46ca363f5..3203b7759 100644
--- a/store/agents/music-studio/AGENTS.md
+++ b/store/agents/music-studio/AGENTS.md
@@ -1,67 +1,55 @@
-# Music Studio harness
-
-You turn a plain-English description into a **deterministic, seedable piece of
-music** rendered in one self-contained `piece/index.html`. The pane plays it
-live, so the person hears the piece — and a re-seed — as you work.
-
-## What a good piece is
-
-- **One file, offline.** All synthesis inline via the Web Audio API (oscillators,
- envelopes, buffers, a simple scheduler loop). No CDN at runtime. A `?seed=`
- query param selects the version: the same seed always plays the same track on
- this machine.
-- **Determinism is the product.** Seed a PRNG and name sub-streams (per chord,
- per rhythm, per melody) so tuning one doesn't reshuffle the rest. Same seed →
- same score, same sound, same length.
-- **Playable, not just loud.** Keep peak levels sane (no clipping), give the
- piece a beginning/middle/end, and expose a visible waveform or step grid so the
- pane is fun to watch while it plays.
-- **Be honest about verification.** Same-machine playback is checkable.
- Cross-machine audio is *not* bit-identical (implementations differ) — say so in
- the verdict rather than overclaiming.
-
-## How to work so the pane moves
-
-1. **Save within a minute.** Materialize `piece/index.html` that plays a trivial
- seeded loop (a few notes + a kick), so the header has a state and the pane can
- play it.
-2. **Build the system, then the piece.** Get the seeded score scheduler + sound
- right first; only then tune mood, arrangement, and mix.
-3. **Verify like a listener:** play a few seeds in the pane, look at the waveform,
- check it isn't clipping, re-play the same seed and confirm it is identical.
-4. **Update `.harness/verdict.json`** at every check — `ready`, one-line `summary`,
- `phases`, `findings`, and a reproducibility note.
-
-## Rules
-
-- A piece is only "ready" when every seed in the range you promise plays clean:
- no silence, no clipping, no stuck-forever track. Sample a grid of seeds.
-- Tag every crafted decision USER vs AI in `piece/DESIGN.md`
- (`YYYY-MM-DD | USER|AI | topic | decision | still in build?`).
-- The `summary` says plainly what is reproducible now and what is not.
-
-## Shipped experience and operating standard
-
-The workspace starts with **Afterhours**, a working experience, not an empty placeholder.
-Five editable tracks, finite arrangement, tempo/swing, per-track mute and level, waveform transport, reproducible PCM, WAV export.
-
-- Read the existing artifact before replacing it. The useful model boundaries are musicScore, scoreEvents, renderMusic, wavFile.
-- Preserve working interactions and exports when extending the artifact. Match the user's brief;
- the starter's genre and visual style are examples, not a ceiling.
-- Expose meaningful domain controls and outputs. Every control must change real state; every
- displayed metric must be computed from that state. Never invent model activity or test results.
-- Use named random streams and a fixed simulation/score clock. Sample seeds, repeat the same
- seed, inspect exported data, and verify keyboard/touch controls in the actual viewer.
-- This HTML runs with same-origin APIs in the shared viewer. Sibling fetches, localStorage,
- downloads and pointer lock are available. Keep files portable and support direct opening.
-- Do not equate an existing HTML file, a successful reload, or a source-string test with a usable
- result. `seed-verdict.sh` deliberately keeps `ready:false`; write `ready:true` only after your
- checks establish it. Record exact commands, sampled seeds, observations and limitations.
-- Never claim a test coverage percentage for browser code based on Node subprocess tests.
-
-## Check your actual edited model
-
-Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from
-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and
-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are
-followed by browser interaction, exported-output inspection, and visual or listening review.
+# Music Studio — compose work the person can use
+
+Turn the person's musical brief into a complete, editable composition. They should not need to
+write code, know notation, or accept the example's genre. The preview is an authoring studio,
+not a seed picker or a spectator visualizer. Read `skills/studio/SKILL.md`.
+
+Start by reading `piece/session.json`. It is the actual composition: arbitrary notes, tracks,
+tempo changes, sections, mix settings and embedded recordings. `piece/compose.mjs` is the example's
+original generator; running it overwrites the score. Do not rerun it over approved edits.
+
+## Complete the real task
+
+1. Establish the purpose, duration, mood, musical material and required outputs. Use supplied MIDI,
+ melody and recordings. If the request already gives enough information, start composing.
+2. Write an original beginning, development and ending. Compose the notes and arrangement in
+ `piece/session.json`, directly or with a new generator appropriate to the brief. Never merely
+ reseed Blue Hour or rename its instruments and present that as the requested music.
+3. Respect useful structure: a voiceover needs space, a loop needs a clean seam, a title cue needs
+ a timed ending. Use note velocities, register, voicing, silence and instrumentation deliberately.
+4. Run `node tools/build.mjs`. The pane exposes the actual arrangement, editable piano roll,
+ track mixer, instrument envelopes and audio-clip controls. The user can revise individual notes,
+ rearrange sections, import recordings and keep going without a code editor.
+5. Run `node tools/export.mjs`. The `delivery/` folder contains stereo WAV, aligned WAV stems,
+ standard MIDI, the editable project and a portable HTML studio. Open the real files with an
+ independent reader, check timing and note content, and listen through the complete piece.
+6. Revise what fails the brief. A playable buffer or technically valid MIDI is not musical quality.
+ Record exactly what you inspected and heard, then update `.harness/verdict.json` honestly.
+
+## Preserve the person's work
+
+Keep approved notes, timing, recordings, mix choices and sections when making a targeted revision.
+The browser saves drafts locally, supports undo/redo, and explicitly handles a conflict with a new
+agent revision. Those local edits are not automatically written into the source score. Import a
+saved `.afterhours.json` with `node tools/import-project.mjs FILE` before editing it. This keeps a
+backup. Never claim to have read a browser edit you cannot access.
+
+Use `node tools/import-project.mjs melody.mid` to start from a real MIDI composition. Notes, tempo
+changes, initial volume/pan and one meter are imported. Controller automation, sustain and pitch
+bends are not reproduced; the importer reports them. Preserve the original MIDI and use an audio
+render of it when that performance data matters. Never silently call it a lossless MIDI roundtrip.
+
+## Production truth
+
+- This is local instrumental synthesis, composition and sampling. It does not generate a singer
+ from lyrics or pretend that oscillators are an orchestral recording.
+- The person can supply audio, use it as a track or pitched instrument, and export real audio.
+- WAV is 48 kHz stereo 16-bit PCM. Stems share timeline, length and mix gain and follow mute/solo.
+ MIDI contains all notes and tempo, not audio clips or effects; another DAW's patches may differ.
+- Limits: four minutes, 16 tracks, 16,000 notes and 28 MB of embedded project data. For longer work,
+ compose movements or continue in a DAW. A larger stem bundle can be exported in soloed groups.
+- Do not promise a mastered commercial release from headroom measurements. Listening, musical
+ judgment and the intended use decide readiness. Keep `ready:false` until that review is real.
+
+The Store listing remains withdrawn during validation. The original simpler sequencer source is
+preserved under `store/tools/experiences/` in the repository, along with the other parked harnesses.
diff --git a/store/agents/music-studio/README.md b/store/agents/music-studio/README.md
index ed155b4b2..247ebfe97 100644
--- a/store/agents/music-studio/README.md
+++ b/store/agents/music-studio/README.md
@@ -1,60 +1,48 @@
# Music Studio — Afterhours
-> Withdrawn from Store discovery on 2026-09-20: the current starter does not meet our
-> standard for an open-ended tool that completes real user work. Existing projects and
-> source remain available. See [the product review](../../../work/SUPERPOWERS.md).
+> Unlisted while the authoring rebuild is validated. Code and existing projects remain available.
+> See [the product review](../../../work/SUPERPOWERS.md).
![Music Studio logo](brand/logo.svg)
-Compose a seeded eight-bar track, edit five instrument patterns, shape swing and the mix, listen locally, and export the result as a WAV file.
+Describe a piece you want to make. The agent composes an original arrangement, then you can edit
+notes, timing, sections, instruments and the mix. Bring your own MIDI or recordings. Deliver a
+stereo WAV, separate tracks for a DAW, editable MIDI and a complete project you can reopen.
-## Try it
-
-> Build a warm, unhurried eight-bar piece with a syncopated bass line and a sparse melody. Give it a distinct opening and ending.
-
-The starter already works before the first prompt. Change it with the agent, interact with the
-result in the pane, and keep the output. Everything needed at runtime is in `piece/index.html`.
-It works offline and can be opened outside Harness.
+The example is a 48-second documentary cue with five sections. It is a starting piece, not a
+limit on genre or a fixed loop. For a new brief the agent writes a new score.
## What you can do
-Five editable tracks, finite arrangement, tempo/swing, per-track mute and level, waveform transport, reproducible PCM, WAV export.
-
-## Build on the starter
-
-The model functions `musicScore`, `scoreEvents`, `renderMusic` and `wavFile` are the starting points for substantive changes. Preserve seed
-reproducibility and user controls while changing the domain behavior. A different brief can replace
-this starter's entire visual language. Keep the artifact self-contained and test the actual result.
-
-The source checkout builds these starters with `node store/tools/build-experiences.mjs`. Installed
-workspaces are editable HTML; no build tool, network dependency or paid service is required.
-
-## Verification
-
-Model census: `node --test store/tools/experience-tests/models.test.mjs` from the source checkout.
-Browser interactions, exports, same-origin APIs and manifest routing: see
-[`store/tools/experience-tests`](../../tools/experience-tests/README.md).
+- Edit pitches, note lengths, starts and velocities in the piano roll; drag notes and undo/redo.
+- Add instruments, repeat sections, transpose tracks, change tempo, mute/solo and shape the mix.
+- Open MIDI notes and tempo maps, add your own recordings, trim/place clips, or play a recording
+ as a pitched sample. MIDI automation and pitch bends are reported as unsupported on import.
+- Export 48 kHz stereo 16-bit WAV, aligned stems, MIDI, the editable project and portable HTML.
-`seed-verdict.sh` establishes only artifact presence and keeps `ready:false`. The agent must run
-and record real domain and browser checks before writing a ready verdict. No cross-device pixel or
-audio equality is promised. The research is inspiration; this is original code, not a wrapper of
-any cited third-party engine.
+Browser edits autosave locally and stay recoverable when the agent changes the source. Save the
+project to move it between sessions or attach it to the agent; local drafts do not write into the
+source score automatically. The production ZIP contains the exact notes, mix and embedded audio.
-## Check your actual edited model
+## Authoring and verification
-Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from
-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and
-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are
-followed by browser interaction, exported-output inspection, and visual or listening review.
+The source score is `piece/session.json`. Build with `node tools/build.mjs`; check source/preview
+agreement with `node tools/check.mjs`; export the actual files with `node tools/export.mjs`.
+`node tools/import-project.mjs FILE` imports a saved project or MIDI and keeps a source backup.
-## Logo and icon
+Setup installs pinned browser/MIDI tools locally. Node.js 20+ and npm are required for authoring;
+the exported studio needs only a browser. The harness uses the coding-engine account already
+configured in Harness and no additional remote music-generation service.
-The original identity ships in `brand/`: [vector icon](brand/icon.svg),
-[256px PNG](brand/icon.png), [light logo](brand/logo.svg) and
-[dark logo](brand/logo-dark.svg). The same mark appears in the starter header,
-its offline favicon and the desktop Store/picker/tabs. MIT, by OpenHarness contributors.
+The renderer measures headroom and timing; the exporter verifies playback and repeatability.
+These checks do not establish musical quality. The complete piece still needs a listening review.
+Synthesized voices are not recorded acoustic instruments or generated singing. MIDI patches may
+sound different in a DAW; use stems for the actual sound. Work is bounded to four minutes, 16
+tracks, 16,000 notes and 28 MB of embedded project data; longer projects can continue in a DAW.
## Credit and stewardship
-Original implementation and visual identity by OpenHarness contributors, maintained by
-Autonomous under the [MIT license](LICENSE). Report issues in the OpenHarness repository.
+Original studio and identity by OpenHarness contributors, maintained by Autonomous under the
+[MIT license](LICENSE). MIDI I/O uses [@tonejs/midi](https://github.com/Tonejs/Midi), midi-file and
+array-flatten; their MIT licenses are retained in `template/studio/vendor/`. Playwright is a
+separate Apache-2.0 dependency by Microsoft. Report issues in the OpenHarness repository.
diff --git a/store/agents/music-studio/examples/README.md b/store/agents/music-studio/examples/README.md
new file mode 100644
index 000000000..bc134bade
--- /dev/null
+++ b/store/agents/music-studio/examples/README.md
@@ -0,0 +1,14 @@
+# Different briefs, different scores
+
+These are original acceptance fixtures, not a style menu. `compose-examples.mjs` writes only this
+examples directory. It demonstrates score construction and actual MIDI input rather than preset
+selection. No recordings or melodies are attributed to a real customer.
+
+- `orbit-runner/session.json`: 30-second electronic game title, 128 BPM, 4/4, 312 notes.
+- `keepsake/input-melody.mid`: the original waltz input fixture, 3/4 with two tempos.
+- `keepsake/session.json`: a 33-second arrangement that retains that imported melody, 92 notes.
+
+In a fresh workspace, copy a chosen session to `piece/session.json`, then build/export it with
+the workspace tools. Preserve an existing user's source first. These files can also be opened as
+projects in the studio. The source repo's revision scenarios preserve approved parts while
+changing one requested part. Technical delivery checks passed; listening review remains pending.
diff --git a/store/agents/music-studio/examples/compose-examples.mjs b/store/agents/music-studio/examples/compose-examples.mjs
new file mode 100644
index 000000000..d2d2a7e4e
--- /dev/null
+++ b/store/agents/music-studio/examples/compose-examples.mjs
@@ -0,0 +1,60 @@
+// Original acceptance fixtures authored for two different briefs. No user recordings
+// or existing songs are represented here. Running this only updates examples/.
+import { mkdir, writeFile } from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { validateSession, writeSessionMidi, readSessionMidi } from '../template/studio/session.mjs';
+const { Midi } = createRequire(import.meta.url)('../template/studio/vendor/midi.cjs');
+const save = async (name, p) => { const dir = new URL(name + '/', import.meta.url); await mkdir(dir, { recursive: true }); await writeFile(new URL('session.json', dir), JSON.stringify(validateSession(p), null, 2) + '\n'); };
+const note = (p, track, beat, midi, duration, velocity) => p.tracks[track].notes.push({ beat, midi, duration, velocity });
+const orbit = {
+ spec: 'afterhours/1', id: 'orbit-runner', title: 'Orbit Runner',
+ brief: 'A 30-second instrumental title cue for a retro space puzzle game. Establish a distinctive syncopated hook, build momentum, break down briefly, then land on a clear final accent. Bright electronic voices and a dry rhythm section; no documentary pads.',
+ seed: 'orbit-original', tempo: 128, meter: [4, 4], beats: 64, tail: 0, master: .86,
+ sections: [{ name: 'Signal', beat: 0, length: 8 }, { name: 'Launch', beat: 8, length: 24 }, { name: 'Zero gravity', beat: 32, length: 16 }, { name: 'Arrival', beat: 48, length: 16 }],
+ tracks: [
+ { id: 'hook', name: 'Navigation hook', instrument: 'lead', gain: .63, tone: 5400, attack: .005, release: .07, delay: .11, space: .04, notes: [] },
+ { id: 'arp', name: 'Orbit fragments', instrument: 'bell', gain: .37, pan: .3, tone: 8800, release: .10, space: .08, notes: [] },
+ { id: 'bass', name: 'Engine', instrument: 'bass', gain: .68, tone: 1800, release: .09, space: 0, notes: [] },
+ { id: 'kit', name: 'Dry rhythm', instrument: 'drums', gain: .56, tone: 13000, space: 0, notes: [] },
+ ]
+};
+const roots = [45, 45, 53, 48, 50, 53, 52, 45], hook = [69, 76, 72, 71, 69, 64];
+for (let bar = 0; bar < 16; bar++) {
+ const b = bar * 4, root = roots[Math.floor(bar / 2)], sparse = bar >= 8 && bar < 10;
+ if (bar < 15) [0, .75, 1.5, 2.25, 3, 3.5].forEach((step, i) => { if (!sparse || i < 2) note(orbit, 0, b + step, hook[(i + (bar >= 12 ? 2 : 0)) % 6] + (bar >= 12 ? 12 : 0), i === 5 ? .3 : .35, i === 0 ? .8 : .58); });
+ if (bar >= 2 && bar < 15) for (let i = 0; i < (sparse ? 1 : 4); i++) note(orbit, 2, b + i + (i % 2 ? .25 : 0), root - 12, .48, i === 0 ? .8 : .65);
+ if (bar >= 4 && bar < 15 && !sparse) [0.5, 1.75, 2.5, 3.75].forEach((step, i) => note(orbit, 1, b + step, root + 24 + [0, 7, 12, 10][i], .18, .46));
+ if (bar >= 2 && bar < 15 && !sparse) {
+ [0, 1.75, 2.5].forEach(step => note(orbit, 3, b + step, 36, .12, .75));
+ [1, 3].forEach(step => note(orbit, 3, b + step, 38, .10, .56));
+ for (let i = 0; i < 8; i++) note(orbit, 3, b + i / 2, 42, .05, i % 2 ? .43 : .26);
+ }
+}
+[69, 72, 76].forEach((pitch, i) => note(orbit, 0, 60 + i * .25, pitch, 1.1 - i * .25, .68));
+note(orbit, 2, 60, 33, 1.6, .8); note(orbit, 3, 60, 36, .15, .8);
+await save('orbit-runner', orbit);
+
+const melody = {
+ spec: 'afterhours/1', id: 'keepsake-melody', title: 'Keepsake — supplied melody fixture', brief: 'Original MIDI input fixture: a small waltz theme with a slower second half.',
+ tempo: 72, tempos: [{ beat: 0, bpm: 72 }, { beat: 18, bpm: 60 }], meter: [3, 4], beats: 36, tail: 0,
+ tracks: [{ id: 'melody', name: 'Approved melody', instrument: 'felt', notes: [] }]
+};
+const phrase = [[0, 67, 1.5], [1.5, 69, .5], [2, 71, .75], [3, 74, 2.4], [6, 72, 1], [7, 71, 1], [8, 69, .8], [9, 67, 2.4], [12, 64, 1.4], [13.5, 67, .8], [15, 66, 2.6]];
+for (const [beat, pitch, length] of phrase) note(melody, 0, beat, pitch, length, beat % 3 === 0 ? .62 : .48);
+for (const [beat, pitch, length] of phrase) note(melody, 0, beat + 18, beat === 15 ? 67 : pitch, length, beat % 3 === 0 ? .56 : .43);
+const input = writeSessionMidi(validateSession(melody), Midi);
+const keepsake = readSessionMidi(input, Midi);
+Object.assign(keepsake, { id: 'keepsake', title: 'Keepsake', tail: 0, master: .9, seed: 'keepsake-original', brief: 'Arrange the supplied waltz melody for a 33-second family film interlude. Preserve every melody note and both tempos. Add an understated three-beat accompaniment, a low foundation and a small final answer; leave room for narration.', sections: [{ name: 'A memory', beat: 0, length: 18 }, { name: 'Coming home', beat: 18, length: 18 }] });
+Object.assign(keepsake.tracks[0], { gain: .8, pan: -.08, space: .22, release: .4, tone: 6500 });
+keepsake.tracks.push({ id: 'left-hand', name: 'Waltz accompaniment', instrument: 'felt', gain: .4, pan: -.23, space: .12, release: .3, notes: [] }, { id: 'cello-role', name: 'Low foundation', instrument: 'bass', gain: .24, tone: 800, release: .25, space: .06, notes: [] }, { id: 'answer', name: 'Final answer', instrument: 'bell', gain: .24, pan: .27, release: .45, space: .2, notes: [] });
+const harmony = [[43, 59, 62], [47, 59, 62], [48, 60, 64], [43, 59, 62], [40, 59, 64], [38, 57, 60]];
+for (let bar = 0; bar < 12; bar++) {
+ const b = bar * 3, chord = bar === 11 ? [43, 59, 62] : harmony[bar % 6];
+ note(keepsake, 1, b, chord[0] + 12, .8, .43);
+ for (const step of [1, 2]) for (const pitch of chord.slice(1)) note(keepsake, 1, b + step, pitch, .6, .32);
+ if (bar % 2 === 0 || bar === 11) note(keepsake, 2, b, chord[0], 2.5, .5);
+}
+[74, 71, 67].forEach((pitch, i) => note(keepsake, 3, 30 + i * 1.5, pitch, .9, .4));
+await save('keepsake', keepsake);
+await writeFile(new URL('keepsake/input-melody.mid', import.meta.url), input);
+console.log('Composed Orbit Runner (30s, 4/4) and Keepsake (33s, 3/4, imported MIDI + tempo changes).');
diff --git a/store/agents/music-studio/examples/keepsake/input-melody.mid b/store/agents/music-studio/examples/keepsake/input-melody.mid
new file mode 100644
index 000000000..4596c4d7b
Binary files /dev/null and b/store/agents/music-studio/examples/keepsake/input-melody.mid differ
diff --git a/store/agents/music-studio/examples/keepsake/session.json b/store/agents/music-studio/examples/keepsake/session.json
new file mode 100644
index 000000000..112afe0f2
--- /dev/null
+++ b/store/agents/music-studio/examples/keepsake/session.json
@@ -0,0 +1,666 @@
+{
+ "spec": "afterhours/1",
+ "id": "keepsake",
+ "title": "Keepsake",
+ "brief": "Arrange the supplied waltz melody for a 33-second family film interlude. Preserve every melody note and both tempos. Add an understated three-beat accompaniment, a low foundation and a small final answer; leave room for narration.",
+ "seed": "keepsake-original",
+ "tempo": 72.00002880001152,
+ "tempos": [
+ {
+ "beat": 0,
+ "bpm": 72.00002880001152
+ },
+ {
+ "beat": 18,
+ "bpm": 60
+ }
+ ],
+ "meter": [
+ 3,
+ 4
+ ],
+ "beats": 36,
+ "tracks": [
+ {
+ "id": "midi-0",
+ "name": "Approved melody",
+ "instrument": "felt",
+ "midiProgram": 0,
+ "gain": 0.8,
+ "pan": -0.08,
+ "notes": [
+ {
+ "beat": 0,
+ "duration": 1.5,
+ "midi": 67,
+ "velocity": 0.6141732283464567
+ },
+ {
+ "beat": 1.5,
+ "duration": 0.5,
+ "midi": 69,
+ "velocity": 0.47244094488188976
+ },
+ {
+ "beat": 2,
+ "duration": 0.75,
+ "midi": 71,
+ "velocity": 0.47244094488188976
+ },
+ {
+ "beat": 3,
+ "duration": 2.4,
+ "midi": 74,
+ "velocity": 0.6141732283464567
+ },
+ {
+ "beat": 6,
+ "duration": 1,
+ "midi": 72,
+ "velocity": 0.6141732283464567
+ },
+ {
+ "beat": 7,
+ "duration": 1,
+ "midi": 71,
+ "velocity": 0.47244094488188976
+ },
+ {
+ "beat": 8,
+ "duration": 0.8,
+ "midi": 69,
+ "velocity": 0.47244094488188976
+ },
+ {
+ "beat": 9,
+ "duration": 2.4,
+ "midi": 67,
+ "velocity": 0.6141732283464567
+ },
+ {
+ "beat": 12,
+ "duration": 1.4,
+ "midi": 64,
+ "velocity": 0.6141732283464567
+ },
+ {
+ "beat": 13.5,
+ "duration": 0.8,
+ "midi": 67,
+ "velocity": 0.47244094488188976
+ },
+ {
+ "beat": 15,
+ "duration": 2.6,
+ "midi": 66,
+ "velocity": 0.6141732283464567
+ },
+ {
+ "beat": 18,
+ "duration": 1.5,
+ "midi": 67,
+ "velocity": 0.5590551181102362
+ },
+ {
+ "beat": 19.5,
+ "duration": 0.5,
+ "midi": 69,
+ "velocity": 0.4251968503937008
+ },
+ {
+ "beat": 20,
+ "duration": 0.75,
+ "midi": 71,
+ "velocity": 0.4251968503937008
+ },
+ {
+ "beat": 21,
+ "duration": 2.4,
+ "midi": 74,
+ "velocity": 0.5590551181102362
+ },
+ {
+ "beat": 24,
+ "duration": 1,
+ "midi": 72,
+ "velocity": 0.5590551181102362
+ },
+ {
+ "beat": 25,
+ "duration": 1,
+ "midi": 71,
+ "velocity": 0.4251968503937008
+ },
+ {
+ "beat": 26,
+ "duration": 0.8,
+ "midi": 69,
+ "velocity": 0.4251968503937008
+ },
+ {
+ "beat": 27,
+ "duration": 2.4,
+ "midi": 67,
+ "velocity": 0.5590551181102362
+ },
+ {
+ "beat": 30,
+ "duration": 1.4,
+ "midi": 64,
+ "velocity": 0.5590551181102362
+ },
+ {
+ "beat": 31.5,
+ "duration": 0.8,
+ "midi": 67,
+ "velocity": 0.4251968503937008
+ },
+ {
+ "beat": 33,
+ "duration": 2.6,
+ "midi": 67,
+ "velocity": 0.5590551181102362
+ }
+ ],
+ "muted": false,
+ "solo": false,
+ "attack": 0.008,
+ "release": 0.4,
+ "tone": 6500,
+ "space": 0.22,
+ "delay": 0,
+ "sampleRoot": 60,
+ "clips": []
+ },
+ {
+ "id": "left-hand",
+ "name": "Waltz accompaniment",
+ "instrument": "felt",
+ "gain": 0.4,
+ "pan": -0.23,
+ "space": 0.12,
+ "release": 0.3,
+ "notes": [
+ {
+ "beat": 0,
+ "midi": 55,
+ "duration": 0.8,
+ "velocity": 0.43
+ },
+ {
+ "beat": 1,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 1,
+ "midi": 62,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 2,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 2,
+ "midi": 62,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 3,
+ "midi": 59,
+ "duration": 0.8,
+ "velocity": 0.43
+ },
+ {
+ "beat": 4,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 4,
+ "midi": 62,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 5,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 5,
+ "midi": 62,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 6,
+ "midi": 60,
+ "duration": 0.8,
+ "velocity": 0.43
+ },
+ {
+ "beat": 7,
+ "midi": 60,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 7,
+ "midi": 64,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 8,
+ "midi": 60,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 8,
+ "midi": 64,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 9,
+ "midi": 55,
+ "duration": 0.8,
+ "velocity": 0.43
+ },
+ {
+ "beat": 10,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 10,
+ "midi": 62,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 11,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 11,
+ "midi": 62,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 12,
+ "midi": 52,
+ "duration": 0.8,
+ "velocity": 0.43
+ },
+ {
+ "beat": 13,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 13,
+ "midi": 64,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 14,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 14,
+ "midi": 64,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 15,
+ "midi": 50,
+ "duration": 0.8,
+ "velocity": 0.43
+ },
+ {
+ "beat": 16,
+ "midi": 57,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 16,
+ "midi": 60,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 17,
+ "midi": 57,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 17,
+ "midi": 60,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 18,
+ "midi": 55,
+ "duration": 0.8,
+ "velocity": 0.43
+ },
+ {
+ "beat": 19,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 19,
+ "midi": 62,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 20,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 20,
+ "midi": 62,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 21,
+ "midi": 59,
+ "duration": 0.8,
+ "velocity": 0.43
+ },
+ {
+ "beat": 22,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 22,
+ "midi": 62,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 23,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 23,
+ "midi": 62,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 24,
+ "midi": 60,
+ "duration": 0.8,
+ "velocity": 0.43
+ },
+ {
+ "beat": 25,
+ "midi": 60,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 25,
+ "midi": 64,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 26,
+ "midi": 60,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 26,
+ "midi": 64,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 27,
+ "midi": 55,
+ "duration": 0.8,
+ "velocity": 0.43
+ },
+ {
+ "beat": 28,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 28,
+ "midi": 62,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 29,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 29,
+ "midi": 62,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 30,
+ "midi": 52,
+ "duration": 0.8,
+ "velocity": 0.43
+ },
+ {
+ "beat": 31,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 31,
+ "midi": 64,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 32,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 32,
+ "midi": 64,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 33,
+ "midi": 55,
+ "duration": 0.8,
+ "velocity": 0.43
+ },
+ {
+ "beat": 34,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 34,
+ "midi": 62,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 35,
+ "midi": 59,
+ "duration": 0.6,
+ "velocity": 0.32
+ },
+ {
+ "beat": 35,
+ "midi": 62,
+ "duration": 0.6,
+ "velocity": 0.32
+ }
+ ],
+ "muted": false,
+ "solo": false,
+ "attack": 0.008,
+ "tone": 8000,
+ "delay": 0,
+ "sampleRoot": 60,
+ "clips": []
+ },
+ {
+ "id": "cello-role",
+ "name": "Low foundation",
+ "instrument": "bass",
+ "gain": 0.24,
+ "tone": 800,
+ "release": 0.25,
+ "space": 0.06,
+ "notes": [
+ {
+ "beat": 0,
+ "midi": 43,
+ "duration": 2.5,
+ "velocity": 0.5
+ },
+ {
+ "beat": 6,
+ "midi": 48,
+ "duration": 2.5,
+ "velocity": 0.5
+ },
+ {
+ "beat": 12,
+ "midi": 40,
+ "duration": 2.5,
+ "velocity": 0.5
+ },
+ {
+ "beat": 18,
+ "midi": 43,
+ "duration": 2.5,
+ "velocity": 0.5
+ },
+ {
+ "beat": 24,
+ "midi": 48,
+ "duration": 2.5,
+ "velocity": 0.5
+ },
+ {
+ "beat": 30,
+ "midi": 40,
+ "duration": 2.5,
+ "velocity": 0.5
+ },
+ {
+ "beat": 33,
+ "midi": 43,
+ "duration": 2.5,
+ "velocity": 0.5
+ }
+ ],
+ "pan": 0,
+ "muted": false,
+ "solo": false,
+ "attack": 0.008,
+ "delay": 0,
+ "sampleRoot": 60,
+ "clips": []
+ },
+ {
+ "id": "answer",
+ "name": "Final answer",
+ "instrument": "bell",
+ "gain": 0.24,
+ "pan": 0.27,
+ "release": 0.45,
+ "space": 0.2,
+ "notes": [
+ {
+ "beat": 30,
+ "midi": 74,
+ "duration": 0.9,
+ "velocity": 0.4
+ },
+ {
+ "beat": 31.5,
+ "midi": 71,
+ "duration": 0.9,
+ "velocity": 0.4
+ },
+ {
+ "beat": 33,
+ "midi": 67,
+ "duration": 0.9,
+ "velocity": 0.4
+ }
+ ],
+ "muted": false,
+ "solo": false,
+ "attack": 0.008,
+ "tone": 8000,
+ "delay": 0,
+ "sampleRoot": 60,
+ "clips": []
+ }
+ ],
+ "importWarnings": [],
+ "master": 0.9,
+ "tail": 0,
+ "assets": [],
+ "sections": [
+ {
+ "name": "A memory",
+ "beat": 0,
+ "length": 18
+ },
+ {
+ "name": "Coming home",
+ "beat": 18,
+ "length": 18
+ }
+ ]
+}
diff --git a/store/agents/music-studio/examples/orbit-runner/session.json b/store/agents/music-studio/examples/orbit-runner/session.json
new file mode 100644
index 000000000..336e43373
--- /dev/null
+++ b/store/agents/music-studio/examples/orbit-runner/session.json
@@ -0,0 +1,1990 @@
+{
+ "spec": "afterhours/1",
+ "id": "orbit-runner",
+ "title": "Orbit Runner",
+ "brief": "A 30-second instrumental title cue for a retro space puzzle game. Establish a distinctive syncopated hook, build momentum, break down briefly, then land on a clear final accent. Bright electronic voices and a dry rhythm section; no documentary pads.",
+ "seed": "orbit-original",
+ "tempo": 128,
+ "meter": [
+ 4,
+ 4
+ ],
+ "beats": 64,
+ "tail": 0,
+ "master": 0.86,
+ "sections": [
+ {
+ "name": "Signal",
+ "beat": 0,
+ "length": 8
+ },
+ {
+ "name": "Launch",
+ "beat": 8,
+ "length": 24
+ },
+ {
+ "name": "Zero gravity",
+ "beat": 32,
+ "length": 16
+ },
+ {
+ "name": "Arrival",
+ "beat": 48,
+ "length": 16
+ }
+ ],
+ "tracks": [
+ {
+ "id": "hook",
+ "name": "Navigation hook",
+ "instrument": "lead",
+ "gain": 0.63,
+ "tone": 5400,
+ "attack": 0.005,
+ "release": 0.07,
+ "delay": 0.11,
+ "space": 0.04,
+ "notes": [
+ {
+ "beat": 0,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.8
+ },
+ {
+ "beat": 0.75,
+ "midi": 76,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 1.5,
+ "midi": 72,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 2.25,
+ "midi": 71,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 3,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 3.5,
+ "midi": 64,
+ "duration": 0.3,
+ "velocity": 0.58
+ },
+ {
+ "beat": 4,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.8
+ },
+ {
+ "beat": 4.75,
+ "midi": 76,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 5.5,
+ "midi": 72,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 6.25,
+ "midi": 71,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 7,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 7.5,
+ "midi": 64,
+ "duration": 0.3,
+ "velocity": 0.58
+ },
+ {
+ "beat": 8,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.8
+ },
+ {
+ "beat": 8.75,
+ "midi": 76,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 9.5,
+ "midi": 72,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 10.25,
+ "midi": 71,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 11,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 11.5,
+ "midi": 64,
+ "duration": 0.3,
+ "velocity": 0.58
+ },
+ {
+ "beat": 12,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.8
+ },
+ {
+ "beat": 12.75,
+ "midi": 76,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 13.5,
+ "midi": 72,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 14.25,
+ "midi": 71,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 15,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 15.5,
+ "midi": 64,
+ "duration": 0.3,
+ "velocity": 0.58
+ },
+ {
+ "beat": 16,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.8
+ },
+ {
+ "beat": 16.75,
+ "midi": 76,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 17.5,
+ "midi": 72,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 18.25,
+ "midi": 71,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 19,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 19.5,
+ "midi": 64,
+ "duration": 0.3,
+ "velocity": 0.58
+ },
+ {
+ "beat": 20,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.8
+ },
+ {
+ "beat": 20.75,
+ "midi": 76,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 21.5,
+ "midi": 72,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 22.25,
+ "midi": 71,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 23,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 23.5,
+ "midi": 64,
+ "duration": 0.3,
+ "velocity": 0.58
+ },
+ {
+ "beat": 24,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.8
+ },
+ {
+ "beat": 24.75,
+ "midi": 76,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 25.5,
+ "midi": 72,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 26.25,
+ "midi": 71,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 27,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 27.5,
+ "midi": 64,
+ "duration": 0.3,
+ "velocity": 0.58
+ },
+ {
+ "beat": 28,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.8
+ },
+ {
+ "beat": 28.75,
+ "midi": 76,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 29.5,
+ "midi": 72,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 30.25,
+ "midi": 71,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 31,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 31.5,
+ "midi": 64,
+ "duration": 0.3,
+ "velocity": 0.58
+ },
+ {
+ "beat": 32,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.8
+ },
+ {
+ "beat": 32.75,
+ "midi": 76,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 36,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.8
+ },
+ {
+ "beat": 36.75,
+ "midi": 76,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 40,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.8
+ },
+ {
+ "beat": 40.75,
+ "midi": 76,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 41.5,
+ "midi": 72,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 42.25,
+ "midi": 71,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 43,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 43.5,
+ "midi": 64,
+ "duration": 0.3,
+ "velocity": 0.58
+ },
+ {
+ "beat": 44,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.8
+ },
+ {
+ "beat": 44.75,
+ "midi": 76,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 45.5,
+ "midi": 72,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 46.25,
+ "midi": 71,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 47,
+ "midi": 69,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 47.5,
+ "midi": 64,
+ "duration": 0.3,
+ "velocity": 0.58
+ },
+ {
+ "beat": 48,
+ "midi": 84,
+ "duration": 0.35,
+ "velocity": 0.8
+ },
+ {
+ "beat": 48.75,
+ "midi": 83,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 49.5,
+ "midi": 81,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 50.25,
+ "midi": 76,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 51,
+ "midi": 81,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 51.5,
+ "midi": 88,
+ "duration": 0.3,
+ "velocity": 0.58
+ },
+ {
+ "beat": 52,
+ "midi": 84,
+ "duration": 0.35,
+ "velocity": 0.8
+ },
+ {
+ "beat": 52.75,
+ "midi": 83,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 53.5,
+ "midi": 81,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 54.25,
+ "midi": 76,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 55,
+ "midi": 81,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 55.5,
+ "midi": 88,
+ "duration": 0.3,
+ "velocity": 0.58
+ },
+ {
+ "beat": 56,
+ "midi": 84,
+ "duration": 0.35,
+ "velocity": 0.8
+ },
+ {
+ "beat": 56.75,
+ "midi": 83,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 57.5,
+ "midi": 81,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 58.25,
+ "midi": 76,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 59,
+ "midi": 81,
+ "duration": 0.35,
+ "velocity": 0.58
+ },
+ {
+ "beat": 59.5,
+ "midi": 88,
+ "duration": 0.3,
+ "velocity": 0.58
+ },
+ {
+ "beat": 60,
+ "midi": 69,
+ "duration": 1.1,
+ "velocity": 0.68
+ },
+ {
+ "beat": 60.25,
+ "midi": 72,
+ "duration": 0.8500000000000001,
+ "velocity": 0.68
+ },
+ {
+ "beat": 60.5,
+ "midi": 76,
+ "duration": 0.6000000000000001,
+ "velocity": 0.68
+ }
+ ],
+ "pan": 0,
+ "muted": false,
+ "solo": false,
+ "sampleRoot": 60,
+ "clips": []
+ },
+ {
+ "id": "arp",
+ "name": "Orbit fragments",
+ "instrument": "bell",
+ "gain": 0.37,
+ "pan": 0.3,
+ "tone": 8800,
+ "release": 0.1,
+ "space": 0.08,
+ "notes": [
+ {
+ "beat": 16.5,
+ "midi": 77,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 17.75,
+ "midi": 84,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 18.5,
+ "midi": 89,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 19.75,
+ "midi": 87,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 20.5,
+ "midi": 77,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 21.75,
+ "midi": 84,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 22.5,
+ "midi": 89,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 23.75,
+ "midi": 87,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 24.5,
+ "midi": 72,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 25.75,
+ "midi": 79,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 26.5,
+ "midi": 84,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 27.75,
+ "midi": 82,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 28.5,
+ "midi": 72,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 29.75,
+ "midi": 79,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 30.5,
+ "midi": 84,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 31.75,
+ "midi": 82,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 40.5,
+ "midi": 77,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 41.75,
+ "midi": 84,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 42.5,
+ "midi": 89,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 43.75,
+ "midi": 87,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 44.5,
+ "midi": 77,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 45.75,
+ "midi": 84,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 46.5,
+ "midi": 89,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 47.75,
+ "midi": 87,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 48.5,
+ "midi": 76,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 49.75,
+ "midi": 83,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 50.5,
+ "midi": 88,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 51.75,
+ "midi": 86,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 52.5,
+ "midi": 76,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 53.75,
+ "midi": 83,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 54.5,
+ "midi": 88,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 55.75,
+ "midi": 86,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 56.5,
+ "midi": 69,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 57.75,
+ "midi": 76,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 58.5,
+ "midi": 81,
+ "duration": 0.18,
+ "velocity": 0.46
+ },
+ {
+ "beat": 59.75,
+ "midi": 79,
+ "duration": 0.18,
+ "velocity": 0.46
+ }
+ ],
+ "muted": false,
+ "solo": false,
+ "attack": 0.008,
+ "delay": 0,
+ "sampleRoot": 60,
+ "clips": []
+ },
+ {
+ "id": "bass",
+ "name": "Engine",
+ "instrument": "bass",
+ "gain": 0.68,
+ "tone": 1800,
+ "release": 0.09,
+ "space": 0,
+ "notes": [
+ {
+ "beat": 8,
+ "midi": 33,
+ "duration": 0.48,
+ "velocity": 0.8
+ },
+ {
+ "beat": 9.25,
+ "midi": 33,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 10,
+ "midi": 33,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 11.25,
+ "midi": 33,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 12,
+ "midi": 33,
+ "duration": 0.48,
+ "velocity": 0.8
+ },
+ {
+ "beat": 13.25,
+ "midi": 33,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 14,
+ "midi": 33,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 15.25,
+ "midi": 33,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 16,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.8
+ },
+ {
+ "beat": 17.25,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 18,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 19.25,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 20,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.8
+ },
+ {
+ "beat": 21.25,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 22,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 23.25,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 24,
+ "midi": 36,
+ "duration": 0.48,
+ "velocity": 0.8
+ },
+ {
+ "beat": 25.25,
+ "midi": 36,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 26,
+ "midi": 36,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 27.25,
+ "midi": 36,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 28,
+ "midi": 36,
+ "duration": 0.48,
+ "velocity": 0.8
+ },
+ {
+ "beat": 29.25,
+ "midi": 36,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 30,
+ "midi": 36,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 31.25,
+ "midi": 36,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 32,
+ "midi": 38,
+ "duration": 0.48,
+ "velocity": 0.8
+ },
+ {
+ "beat": 36,
+ "midi": 38,
+ "duration": 0.48,
+ "velocity": 0.8
+ },
+ {
+ "beat": 40,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.8
+ },
+ {
+ "beat": 41.25,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 42,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 43.25,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 44,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.8
+ },
+ {
+ "beat": 45.25,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 46,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 47.25,
+ "midi": 41,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 48,
+ "midi": 40,
+ "duration": 0.48,
+ "velocity": 0.8
+ },
+ {
+ "beat": 49.25,
+ "midi": 40,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 50,
+ "midi": 40,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 51.25,
+ "midi": 40,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 52,
+ "midi": 40,
+ "duration": 0.48,
+ "velocity": 0.8
+ },
+ {
+ "beat": 53.25,
+ "midi": 40,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 54,
+ "midi": 40,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 55.25,
+ "midi": 40,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 56,
+ "midi": 33,
+ "duration": 0.48,
+ "velocity": 0.8
+ },
+ {
+ "beat": 57.25,
+ "midi": 33,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 58,
+ "midi": 33,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 59.25,
+ "midi": 33,
+ "duration": 0.48,
+ "velocity": 0.65
+ },
+ {
+ "beat": 60,
+ "midi": 33,
+ "duration": 1.6,
+ "velocity": 0.8
+ }
+ ],
+ "pan": 0,
+ "muted": false,
+ "solo": false,
+ "attack": 0.008,
+ "delay": 0,
+ "sampleRoot": 60,
+ "clips": []
+ },
+ {
+ "id": "kit",
+ "name": "Dry rhythm",
+ "instrument": "drums",
+ "gain": 0.56,
+ "tone": 13000,
+ "space": 0,
+ "notes": [
+ {
+ "beat": 8,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 9.75,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 10.5,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 9,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 11,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 8,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 8.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 9,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 9.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 10,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 10.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 11,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 11.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 12,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 13.75,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 14.5,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 13,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 15,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 12,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 12.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 13,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 13.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 14,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 14.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 15,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 15.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 16,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 17.75,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 18.5,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 17,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 19,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 16,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 16.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 17,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 17.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 18,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 18.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 19,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 19.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 20,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 21.75,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 22.5,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 21,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 23,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 20,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 20.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 21,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 21.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 22,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 22.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 23,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 23.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 24,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 25.75,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 26.5,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 25,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 27,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 24,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 24.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 25,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 25.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 26,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 26.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 27,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 27.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 28,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 29.75,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 30.5,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 29,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 31,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 28,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 28.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 29,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 29.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 30,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 30.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 31,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 31.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 40,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 41.75,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 42.5,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 41,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 43,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 40,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 40.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 41,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 41.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 42,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 42.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 43,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 43.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 44,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 45.75,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 46.5,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 45,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 47,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 44,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 44.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 45,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 45.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 46,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 46.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 47,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 47.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 48,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 49.75,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 50.5,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 49,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 51,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 48,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 48.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 49,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 49.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 50,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 50.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 51,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 51.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 52,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 53.75,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 54.5,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 53,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 55,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 52,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 52.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 53,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 53.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 54,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 54.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 55,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 55.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 56,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 57.75,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 58.5,
+ "midi": 36,
+ "duration": 0.12,
+ "velocity": 0.75
+ },
+ {
+ "beat": 57,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 59,
+ "midi": 38,
+ "duration": 0.1,
+ "velocity": 0.56
+ },
+ {
+ "beat": 56,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 56.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 57,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 57.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 58,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 58.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 59,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.26
+ },
+ {
+ "beat": 59.5,
+ "midi": 42,
+ "duration": 0.05,
+ "velocity": 0.43
+ },
+ {
+ "beat": 60,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.8
+ }
+ ],
+ "pan": 0,
+ "muted": false,
+ "solo": false,
+ "attack": 0.008,
+ "release": 0.25,
+ "delay": 0,
+ "sampleRoot": 60,
+ "clips": []
+ }
+ ],
+ "tempos": [
+ {
+ "beat": 0,
+ "bpm": 128
+ }
+ ],
+ "assets": []
+}
diff --git a/store/agents/music-studio/harness.json b/store/agents/music-studio/harness.json
index 878d1651c..707ba5b2b 100644
--- a/store/agents/music-studio/harness.json
+++ b/store/agents/music-studio/harness.json
@@ -4,7 +4,7 @@
"name": "Music Studio",
"category": "Audio",
"author": "Autonomous",
- "description": "Compose a seeded eight-bar track, edit five instrument patterns, shape swing and the mix, listen locally, and export the result as a WAV file.",
+ "description": "Compose and revise original music from your brief. Edit notes and arrangements, import MIDI and recordings, shape each instrument, and deliver stereo WAV, aligned stems, MIDI and an editable project.",
"engine": "claude",
"workspace": {
"template": "template",
@@ -15,7 +15,10 @@
"instructions": "AGENTS.md",
"skills": [
"skills"
- ]
+ ],
+ "env": {
+ "MUSIC_DSH_DIR": "${dsh}"
+ }
},
"toolchain": {
"setup": "toolchain/setup.sh",
diff --git a/store/agents/music-studio/skills/studio/SKILL.md b/store/agents/music-studio/skills/studio/SKILL.md
index a588cc90c..465d808a0 100644
--- a/store/agents/music-studio/skills/studio/SKILL.md
+++ b/store/agents/music-studio/skills/studio/SKILL.md
@@ -1,75 +1,86 @@
---
name: studio
-description: Build a deterministic, seedable piece of music in one HTML file from a plain-English description. Use whenever the user asks for a track, a beat, a generative song, a seedable sound series, or prompt-to-music.
+description: Compose and revise complete original music from a brief or the user's MIDI and recordings, with editable notes, arrangements and real WAV/stem/MIDI/project delivery.
---
-# studio
+# Make the composition, not another loop demo
-Take the user's description and produce a **single self-contained `piece/index.html`**
-that plays a **deterministic, seedable** track, loading the seed from a `?seed=`
-query param so the web-viewer can preview the current seed and re-seed live.
+Read the current `piece/session.json` and the person's brief. Blue Hour is an example of one
+48-second cue, not a template genre. Write a different score and structure for a different task.
+The agent does the programming and musical construction; the person speaks in Harness chat and
+uses a normal piano roll and mixer.
-## The floor (in order)
+## Score format
-1. **Seeded PRNG.** A small seeded PRNG derived from the hash of the seed string.
- Nothing may call a non-seeded random — the piece must be reproducible.
-2. **Score + synthesis.** A seeded score (chord progression, rhythm grid, melody)
- driving Web Audio synthesis (oscillators + envelopes, a clock-based scheduler).
-3. **`?seed=` plumbing.** Reading the param, plus a tiny UI (input + "re-seed"
- button, play/stop) so the person can browse seeds in the pane.
-4. **Named sub-streams.** One PRNG sub-stream per concern (harmony, rhythm, melody)
- so tuning one doesn't reshuffle the other.
+`spec: "afterhours/1"`, stable lowercase `id`, `title`, `brief`, `seed`, `tempo` (30–240),
+`meter: [numerator, denominator]`, `beats` (quarter-note units), `tail` (0–6 seconds), `master` (0–1).
+Optional `tempos` is an ordered array of `{beat,bpm}` beginning at zero. With no map, `tempo` is
+constant. The timeline must fit four minutes; `tail: 0` gives an exact cut when the brief requires it.
-## The gold checklist
-
-- **Trait tables that survive an edition**: seed → traits (key, tempo, arrangement),
- and a census that shows no silent/clipping/degenerate seed in the range you claim.
-- **Level discipline**: a ceiling (soft clipper or gain architecture) so nothing
- blows out; a visible meter or waveform.
-- **Style range**: generative techno, lo-fi chords, arpeggiated ambient, drum-grid
- patterns — matched to the brief, not all at once.
-- **Export route**: `?seed=X&size=…` style render is audio, so offer a "render
- once, loop forever" mode and a visible step grid.
-
-## Verify like a listener, not a compiler
-
-Play a grid of seeds — actually play them — and listen.
-Two hard checks before "ready":
-- **Re-play same-seed** — it must be identical on this machine.
-- **Census the seed range you promise** (e.g. 0–99); reject any silent, clipped,
- or stuck-forever frame.
-
-Be explicit in the verdict about the reproducibility guarantee: same-machine yes;
-cross-machine audio you cannot prove bit-identical — say so.
-
-## Verdict feed
-
-Write `.harness/verdict.json` at every change:
+Each of at most 16 tracks has `id`, `name`, `instrument`, `notes` and optional `clips`. Notes are:
```json
-{ "spec": 1, "ready": false, "summary": "seeded lo-fi loop · re-seed live · census 0–99 clean",
- "findings": [{ "severity": "info", "kind": "reproducibility", "message": "same-machine verification pending; cross-machine audio not provable bit-identical" }],
- "artifact": "piece/index.html",
- "phases": [{ "id": "seed", "name": "Seeded core", "state": "done" },
- { "id": "piece", "name": "The piece", "state": "active" },
- { "id": "edition", "name": "Edition", "state": "pending" }],
- "updatedAt": "2026-09-18T00:00:00Z" }
+{"beat": 4, "duration": 1.5, "midi": 66, "velocity": 0.72}
```
-## Starting from Afterhours
+A MIDI pitch of 60 is C4. Import `noteNumber`, `secondsAt` and `beatAt` from `studio/session.mjs`
+when writing a generator. These are scheduling utilities, not a restricted style vocabulary.
+Use arbitrary voicings, motifs, rhythms, tempo changes and forms. Separate the roles of melody,
+harmony, bass and rhythm. Use negative space and deliberate dynamics instead of filling every cell.
+
+Note velocity must be 1/127–1 so MIDI can represent it as a note-on. For silence, remove the note
+or mute its track. Section markers and the intended end are included in MIDI, preserving a quiet
+ending after the last note.
+
+Instruments: `felt`, `pluck`, `pad`, `bass`, `bell`, `lead`, `drums`, `sampler`, `audio`.
+They are synthesized voices or supplied recordings, not claims of sampled acoustic instruments.
+A track's `gain`, `pan`, `attack`, `release`, `tone` (filter Hz), `space` and `delay` shape its sound.
+The drum voice uses GM pitches (36 kick, 38 snare, 42 closed hat, 46 open hat). A sampler adds
+`sampleId` and `sampleRoot` (original MIDI pitch). A standard MIDI program number can be retained
+as `midiProgram` for the DAW handoff; a plugin's sound is not encoded in the MIDI file.
+
+Sections are `{name, beat, length}` and describe actual spans in the score. They are not a fixed
+verse/chorus template. The UI can repeat a selected eight-bar window, edit note start/pitch/length/
+velocity, move notes, transpose tracks, add instruments and edit the mix.
+
+## The user's own material
+
+Audio assets: `{id, name, file}` with `file` relative to `piece/`, or an embedded `data` audio URL.
+The build embeds WAV, MP3, M4A or OGG. Use WAV/MP3 for broad decoder support. A track's clips are
+`{assetId, beat, offset, duration, gain, fadeIn, fadeOut}`; offsets and durations are in seconds,
+position is in beats. Recording import in the pane creates a real audio track, not a visual proxy.
+
+`node tools/import-project.mjs FILE` opens an editable project or MIDI and backs up the source.
+MIDI import handles notes, tempo changes, one time signature and initial volume/pan. It reports
+unsupported controllers and pitch bends. A performance that depends on sustain, expression or
+pitch bends needs its original audio or further tool integration; do not discard that silently.
+Keep the supplied originals. Never invent that you heard, extracted or transcribed a melody.
+
+## Build and handoff
+
+```sh
+node tools/build.mjs
+node tools/check.mjs
+node tools/export.mjs
+```
-The template is functional: Five editable tracks, finite arrangement, tempo/swing, per-track mute and level, waveform transport, reproducible PCM, WAV export.
+`MUSIC_DSH_DIR` locates the installed tools. Setup pins Playwright and MIDI libraries locally and
+uses Chrome or installs local Chromium. The emitted studio works offline; it has no CDN or paid
+music-generation dependency. The engine account already configured in Harness does the authoring.
-Keep its useful controls and exports when making a user's creation. Test the behavioral core
-(musicScore, scoreEvents, renderMusic, wavFile) as well as the visible result. A self-contained HTML file can still have well-separated
-model, rendering, input and export functions. Do not turn a finished starter into a waiting screen.
+The production ZIP contains aligned WAV stems, the mix, MIDI and project. The stems use one common
+gain and include each audible track's effects, so align them all at time zero. MIDI does not carry
+recordings or effects, and preview patches are not the same as every DAW's instruments. Deliver
+both forms. Preserve the project so revision is possible without reverse engineering a WAV.
-Presence-only helpers do not prove correctness or reproducibility. Record actual evidence before
-marking the result ready. Export and reopen the result as part of the handoff to the user.
+## Review the actual music
-## Check your actual edited model
+The export command opens the browser, exercises playback and writes the real deliverables. It
+measures duration, peak, RMS and repeatability, and deliberately leaves `ready:false`.
-Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from
-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and
-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are
-followed by browser interaction, exported-output inspection, and visual or listening review.
+Inspect exported WAV with an independent decoder and exported MIDI with an independent reader.
+Verify the requested duration, notes, meter, tempo changes, audible tracks, recording positions
+and stem alignment. Then listen from start to finish: transitions, timing, voicing, loudness,
+tails, intended space, clicks and the ending. Revise and listen again when a change affects sound.
+Do not substitute a waveform screenshot or a green test for this judgment. Record exact evidence
+and limitations in `piece/DESIGN.md` and the verdict. Never invent listening evidence.
diff --git a/store/agents/music-studio/store.json b/store/agents/music-studio/store.json
index faa9381c5..3610c3e4f 100644
--- a/store/agents/music-studio/store.json
+++ b/store/agents/music-studio/store.json
@@ -2,15 +2,25 @@
"listed": false,
"homepage": "https://github.com/autonomous-ai/openharness/tree/main/store/agents/music-studio",
"license": "MIT",
- "tagline": "Compose a seeded eight-bar track, edit five instrument patterns, shape swing and",
+ "tagline": "Compose original music with editable notes, audio and stems for your DAW",
"screenshots": [
"https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/music-studio/starter.jpg"
],
"examples": [
{
- "prompt": "Build a warm, unhurried eight-bar piece with a syncopated bass line and a sparse melody. Give it a distinct opening and ending.",
- "caption": "Afterhours · interactive offline starter",
+ "prompt": "Compose a 48-second coastal documentary cue. Start with an intimate plucked motif, develop warm harmony and a restrained pulse, then resolve quietly. Leave room for voiceover.",
+ "caption": "Blue Hour \u00b7 original 48-second score",
"image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/music-studio/starter.jpg"
+ },
+ {
+ "prompt": "Write a 30-second title cue for a retro space puzzle game: syncopated hook, momentum, a brief breakdown and a clear final accent.",
+ "caption": "Orbit Runner \u00b7 original 30-second electronic score",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/music-studio/orbit-runner.png"
+ },
+ {
+ "prompt": "Arrange my waltz melody for a 33-second family film. Preserve every melody note and its two tempos, adding a restrained accompaniment and low foundation.",
+ "caption": "Keepsake \u00b7 imported MIDI, 3/4 and tempo changes",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/music-studio/keepsake.png"
}
]
}
diff --git a/store/agents/music-studio/template/piece/DESIGN.md b/store/agents/music-studio/template/piece/DESIGN.md
new file mode 100644
index 000000000..a9f15a01c
--- /dev/null
+++ b/store/agents/music-studio/template/piece/DESIGN.md
@@ -0,0 +1,17 @@
+# Blue Hour · example brief
+
+An original 48-second coastal-documentary title cue in five developing sections. A plucked motif
+introduces D-major/B-minor colors; felt keys respond, a warm pad and low pulse enter, and the ending
+returns to a quiet resolved voicing. The score leaves room for narration.
+
+The source contains 249 notes over 80 quarter-note beats at 100 BPM. The five tracks and actual
+beginning/development/ending are editable; a different brief requires a new score. The generator
+is source for this example only and should not be run over a person's approved revisions.
+
+Exports passed real playback, timing, MIDI and independent stem-summation checks. The full
+listening review has not happened. Do not claim that transitions, timbre, balance or fit to a
+real film were auditioned. Keep the verdict not-ready until the actual piece is reviewed.
+
+A revision fixture adds one quiet final motif echo and preserves the other tracks. Other original
+fixtures in the package cover a 30-second electronic cue and a 33-second waltz built from a supplied
+MIDI fixture with tempo changes. See `work/AUTHORING-REBUILD.md` in the repository.
diff --git a/store/agents/music-studio/template/piece/compose.mjs b/store/agents/music-studio/template/piece/compose.mjs
new file mode 100644
index 000000000..7e2fa609f
--- /dev/null
+++ b/store/agents/music-studio/template/piece/compose.mjs
@@ -0,0 +1,40 @@
+// Original acceptance brief: a 48-second documentary title cue. This is source,
+// not a style menu. Replace it with your own composition for a different brief.
+import { writeFile } from 'node:fs/promises';
+import { musicRandom } from '../studio/session.mjs';
+const rnd = musicRandom('blue-hour');
+const p = {
+ spec: 'afterhours/1', id: 'blue-hour', title: 'Blue Hour',
+ brief: 'A 48-second title cue for a coastal documentary. An intimate plucked motif opens into warm harmony and a restrained pulse, then resolves quietly. The arrangement leaves space for a voiceover.',
+ seed: 'blue-hour', tempo: 100, meter: [4, 4], beats: 80, tail: 0, master: .9,
+ sections: ['First light', 'Footsteps', 'Open water', 'The lift', 'Home'].map((name, i) => ({ name, beat: i * 16, length: 16 })),
+ tracks: [
+ { id: 'motif', name: 'Plucked motif', instrument: 'pluck', gain: .92, pan: -.22, tone: 7200, space: .18, delay: .12, release: .35, notes: [] },
+ { id: 'felt', name: 'Felt melody', instrument: 'felt', gain: .7, pan: .15, tone: 5200, space: .24, release: .75, notes: [] },
+ { id: 'pad', name: 'Warm horizon', instrument: 'pad', gain: .24, pan: 0, tone: 1600, attack: .55, space: .35, release: .9, notes: [] },
+ { id: 'bass', name: 'Low tide', instrument: 'bass', gain: .55, pan: 0, tone: 1100, space: .02, release: .20, notes: [] },
+ { id: 'pulse', name: 'Soft pulse', instrument: 'drums', gain: .4, pan: .04, tone: 12000, space: .06, release: .05, notes: [] }
+ ], assets: []
+};
+function note(track, beat, midi, duration, velocity) {
+ if (beat + duration > 79.1) return;
+ p.tracks[track].notes.push({ beat, midi, duration, velocity: Math.min(1, velocity * (.92 + rnd() * .12)) });
+}
+const chords = [[50, 57, 61, 66], [47, 54, 57, 62], [43, 50, 54, 59], [45, 52, 57, 61]];
+const melody = [[74, 73, 69, 66], [73, 69, 66, 62], [71, 69, 66, 62], [69, 73, 76, 73]];
+for (let bar = 0; bar < 20; bar++) {
+ const b = bar * 4, chord = chords[Math.floor(bar / 2) % 4], ending = bar >= 18, energy = ending ? .60 : bar >= 12 && bar < 16 ? 1 : .8;
+ const steps = bar < 4 ? [0, 1.5, 3] : ending ? [0, 2] : [0, .75, 1.5, 2, 2.75, 3.5];
+ steps.forEach((step, i) => note(0, b + step, chord[(i + bar % 2) % 4] + 12, .55 + (i % 3 === 0 ? .35 : 0), .7 * energy));
+ if (bar >= 4 && bar < 18 && bar % 2 === 0) chord.slice(1).forEach((pitch, i) => note(2, b + i * .045, pitch + 12, 7.5, .5 * energy));
+ if (bar >= 8 && bar < 18) { note(3, b, chord[0] - 12, 2.7, .75 * energy); if (bar % 2) note(3, b + 3, chord[0] - 12, .75, .42); }
+ if (bar >= 8 && bar < 16) {
+ note(4, b, 36, .15, .62); note(4, b + 2.5, 36, .15, .37); note(4, b + 2, 38, .12, .28);
+ for (let step = .5; step < 4; step += .5) note(4, b + step, 42, .08, (step % 1 ? .36 : .2) * energy);
+ }
+ if (bar >= 4 && bar % 2 === 0 && bar < 18) melody[Math.floor(bar / 2) % 4].forEach((pitch, i) => note(1, b + [0, 1.5, 3, 5.5][i], pitch, [1.1, .8, 1.7, 1.8][i], .5 + (i === 2 ? .12 : 0)));
+}
+[50, 57, 62, 66].forEach((pitch, i) => note(1, 76 + i * .09, pitch + 12, 2.7 - i * .1, .36));
+note(0, 77.5, 74, 1.4, .36);
+await writeFile(new URL('session.json', import.meta.url), JSON.stringify(p, null, 2) + '\n');
+console.log('Composed Blue Hour: 48 seconds, five parts, five editable tracks.');
diff --git a/store/agents/music-studio/template/piece/index.html b/store/agents/music-studio/template/piece/index.html
index 9eed67d9b..4bde028f1 100644
--- a/store/agents/music-studio/template/piece/index.html
+++ b/store/agents/music-studio/template/piece/index.html
@@ -1,602 +1,7 @@
-<!doctype html>
-<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
-<meta name="color-scheme" content="dark light"><title>AFTERHOURS — Music Studio</title>
-<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22256%22%20height%3D%22256%22%20viewBox%3D%220%200%2096%2096%22%3E%0A%20%20%3Ctitle%3EMusic%20Studio%20%E2%80%94%20five%20tracks%20after%20dark%3C%2Ftitle%3E%0A%20%20%3Crect%20x%3D%224%22%20y%3D%224%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2223%22%20fill%3D%22%23272537%22%2F%3E%0A%20%20%3Cpath%20d%3D%22M67%2017a15%2015%200%201%200%2012%2024%2016%2016%200%200%201-12-24Z%22%20fill%3D%22%23edbfa9%22%2F%3E%0A%20%20%3Cg%20fill%3D%22%23d6c7e9%22%3E%0A%20%20%20%20%3Crect%20x%3D%2219%22%20y%3D%2247%22%20width%3D%228%22%20height%3D%2221%22%20rx%3D%224%22%2F%3E%0A%20%20%20%20%3Crect%20x%3D%2232%22%20y%3D%2231%22%20width%3D%228%22%20height%3D%2245%22%20rx%3D%224%22%2F%3E%0A%20%20%20%20%3Crect%20x%3D%2245%22%20y%3D%2242%22%20width%3D%228%22%20height%3D%2226%22%20rx%3D%224%22%2F%3E%0A%20%20%20%20%3Crect%20x%3D%2258%22%20y%3D%2253%22%20width%3D%228%22%20height%3D%2223%22%20rx%3D%224%22%2F%3E%0A%20%20%20%20%3Crect%20x%3D%2271%22%20y%3D%2253%22%20width%3D%228%22%20height%3D%2215%22%20rx%3D%224%22%2F%3E%0A%20%20%3C%2Fg%3E%0A%3C%2Fsvg%3E">
-<!-- Built by store/tools/build-experiences.mjs. Edit this file freely in your workspace. -->
-<style>:root {
- color-scheme: dark;
- --bg: #111414;
- --panel: #191e1c;
- --line: #ffffff1c;
- --ink: #f4f2e9;
- --muted: #a1aaa4;
- --accent: #d0f28a;
- font:
- 14px/1.5 -apple-system,
- BlinkMacSystemFont,
- "Segoe UI",
- sans-serif;
-}
-* {
- box-sizing: border-box;
-}
-body {
- margin: 0;
- background: var(--bg);
- color: var(--ink);
-}
-button,
-input,
-select {
- font: inherit;
-}
-button,
-a,
-input,
-select {
- -webkit-tap-highlight-color: transparent;
-}
-button,
-a {
- touch-action: manipulation;
-}
-button {
- cursor: pointer;
-}
-button:disabled {
- opacity: 0.45;
- cursor: wait;
-}
-button:focus-visible,
-input:focus-visible,
-select:focus-visible,
-a:focus-visible {
- outline: 2px solid var(--accent);
- outline-offset: 4px;
-}
-button,
-input,
-select {
- color: inherit;
- background: transparent;
- border: 1px solid var(--line);
- border-radius: 5px;
- padding: 9px 13px;
-}
-button:hover {
- background: #ffffff0c;
- border-color: var(--muted);
-}
-button.primary {
- background: var(--accent);
- color: #142015;
- border-color: transparent;
- font-weight: 650;
-}
-button[aria-pressed="true"] {
- border-color: var(--accent);
- color: var(--accent);
-}
-input[type="range"] {
- accent-color: var(--accent);
- padding: 0;
- min-width: 0;
-}
-input[type="number"] {
- width: 80px;
-}
-select {
- background: var(--panel);
-}
-label {
- cursor: pointer;
-}
-a {
- color: inherit;
-}
-h1,
-h2,
-h3,
-p {
- margin: 0;
-}
-h1 {
- font-size: clamp(32px, 5vw, 64px);
- line-height: 1.02;
- letter-spacing: -0.055em;
- font-weight: 550;
-}
-h2 {
- font-weight: 550;
- letter-spacing: -0.03em;
-}
-h3 {
- font-size: 14px;
- font-weight: 550;
-}
-.mono,
-.eyebrow {
- font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
-}
-.eyebrow {
- font-size: 10px;
- letter-spacing: 0.16em;
- text-transform: uppercase;
- color: var(--muted);
-}
-.muted {
- color: var(--muted);
-}
-.small {
- font-size: 12px;
-}
-.masthead {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 20px;
- padding: 19px 28px;
- border-bottom: 1px solid var(--line);
-}
-.identity {
- display: flex;
- gap: 12px;
- align-items: center;
- white-space: nowrap;
- font-size: 12px;
- font-weight: 600;
- letter-spacing: 0.04em;
-}
-.mark {
- width: 28px;
- height: 28px;
- flex: 0 0 28px;
- display: grid;
- place-items: center;
-}
-.mark svg {
- display: block;
- width: 100%;
- height: 100%;
-}
-.seed-form {
- display: flex;
- align-items: center;
- gap: 6px;
-}
-.seed-form label {
- font:
- 10px ui-monospace,
- monospace;
- text-transform: uppercase;
- letter-spacing: 0.12em;
- color: var(--muted);
- margin-right: 4px;
-}
-.seed-form input {
- width: 74px;
- padding: 6px 8px;
- font:
- 12px ui-monospace,
- monospace;
-}
-.seed-form button {
- padding: 6px 10px;
- font-size: 12px;
-}
-.intro {
- padding: 32px 28px;
- display: flex;
- align-items: flex-end;
- justify-content: space-between;
- gap: 20px;
-}
-.intro p {
- max-width: 440px;
- color: var(--muted);
- margin-top: 14px;
-}
-.intro .eyebrow {
- margin-bottom: 12px;
-}
-.actions {
- display: flex;
- align-items: center;
- gap: 8px;
- flex-wrap: wrap;
-}
-.workspace {
- display: grid;
- grid-template-columns: minmax(0, 1fr) 270px;
- gap: 22px;
- padding: 0 28px 28px;
-}
-.panel {
- background: var(--panel);
- border: 1px solid var(--line);
- border-radius: 8px;
- overflow: hidden;
-}
-.panel-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 16px 20px;
- border-bottom: 1px solid var(--line);
- gap: 10px;
-}
-.side {
- display: flex;
- flex-direction: column;
- gap: 20px;
-}
-.section {
- border-top: 1px solid var(--line);
- padding-top: 18px;
-}
-.section h3 {
- margin-bottom: 15px;
-}
-.field {
- display: grid;
- gap: 7px;
- margin: 14px 0;
-}
-.field > span {
- display: flex;
- justify-content: space-between;
- font-size: 12px;
- color: var(--muted);
-}
-.metrics {
- display: grid;
- grid-template-columns: repeat(3, 1fr);
- gap: 1px;
- background: var(--line);
- border: 1px solid var(--line);
- border-radius: 6px;
- overflow: hidden;
-}
-.metric {
- background: var(--bg);
- padding: 13px 15px;
-}
-.metric strong {
- display: block;
- font:
- 24px ui-monospace,
- monospace;
- letter-spacing: -0.06em;
-}
-.metric span {
- font-size: 10px;
- color: var(--muted);
- text-transform: uppercase;
- letter-spacing: 0.09em;
-}
-canvas {
- display: block;
- max-width: 100%;
-}
-.status-line {
- display: flex;
- justify-content: space-between;
- gap: 20px;
- padding: 14px 28px;
- border-top: 1px solid var(--line);
- font:
- 10px ui-monospace,
- monospace;
- color: var(--muted);
-}
-.dot {
- width: 6px;
- height: 6px;
- display: inline-block;
- background: var(--accent);
- border-radius: 50%;
- margin-right: 6px;
-}
-.toast {
- position: fixed;
- z-index: 99;
- left: 50%;
- bottom: 22px;
- transform: translateX(-50%);
- max-width: 90vw;
- background: var(--ink);
- color: var(--bg);
- padding: 11px 18px;
- border-radius: 6px;
- box-shadow: 0 3px 30px #0004;
- font-size: 12px;
-}
-.toast:empty {
- display: none;
-}
-[hidden] {
- display: none !important;
-}
-.sr-only {
- position: absolute;
- width: 1px;
- height: 1px;
- padding: 0;
- margin: -1px;
- overflow: hidden;
- clip-path: inset(50%);
- white-space: nowrap;
- border: 0;
-}
-@media (max-width: 800px) {
- .workspace {
- grid-template-columns: 1fr;
- }
- .side {
- display: grid;
- grid-template-columns: repeat(2, minmax(0, 1fr));
- }
- .intro {
- align-items: flex-start;
- flex-direction: column;
- }
- .intro h1 {
- font-size: 44px;
- }
-}
-@media (max-width: 480px) {
- .masthead {
- padding: 13px 16px;
- gap: 8px;
- flex-wrap: wrap;
- }
- .intro {
- padding: 26px 16px;
- }
- .intro h1 {
- font-size: 38px;
- }
- .workspace {
- padding: 0 16px 20px;
- gap: 18px;
- }
- .side {
- grid-template-columns: 1fr;
- }
- .seed-form label {
- display: none;
- }
- .status-line {
- padding: 12px 16px;
- }
- .status-line span:last-child {
- display: none;
- }
- .metrics .metric {
- padding: 12px 10px;
- }
- .panel-head {
- padding: 12px;
- }
- .actions {
- gap: 6px;
- }
-}
-@media (prefers-reduced-motion: reduce) {
- *,
- *::before,
- *::after {
- scroll-behavior: auto !important;
- animation: none !important;
- transition: none !important;
- }
-}
-
-:root {
- --bg: #201c1b;
- --panel: #2b2522;
- --ink: #f0e6d7;
- --muted: #b5a496;
- --line: #af958332;
- --accent: #eda776;
-}
-.intro {
- padding-top: 34px;
- padding-bottom: 30px;
-}
-.intro h1 {
- font-size: clamp(48px, 7vw, 80px);
-}
-.intro h1 em {
- font-family: Georgia, serif;
- font-weight: 400;
-}
-.record {
- width: 166px;
- height: 166px;
- border-radius: 50%;
- background: repeating-radial-gradient(
- circle,
- #211f1f 0,
- #211f1f 2px,
- #393431 3px,
- #161515 4px
- );
- display: grid;
- place-items: center;
- margin-right: 10px;
- transform: rotate(-13deg);
- box-shadow: 5px 8px 20px #0005;
-}
-.record-label {
- width: 65px;
- height: 65px;
- border-radius: 50%;
- background: #c88860;
- color: #241c18;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- font-size: 10px;
- font-weight: 800;
- line-height: 1.1;
-}
-.record-label span {
- font: 7px monospace;
- margin-top: 5px;
-}
-.transport {
- display: flex;
- gap: 8px;
- align-items: center;
- flex-wrap: wrap;
- padding-bottom: 18px;
-}
-.transport .mono {
- font-size: 11px;
- margin: 0 4px;
-}
-#export-wav {
- margin-left: auto;
- font-size: 12px;
-}
-.wave-panel {
- background: #181615;
- border: 1px solid var(--line);
- padding: 16px 16px 10px;
- border-radius: 6px;
-}
-.wave-panel canvas {
- width: 100%;
- height: 126px;
-}
-.sections {
- display: flex;
- justify-content: space-between;
- font:
- 8px ui-monospace,
- monospace;
- letter-spacing: 0.07em;
- color: var(--muted);
- border-top: 1px solid var(--line);
- padding-top: 10px;
-}
-.sequencer {
- margin-top: 18px;
-}
-.sequencer .panel-head {
- padding: 12px 0;
- border: 0;
-}
-.step-grid {
- display: grid;
- grid-template-columns: 70px repeat(16, minmax(0, 1fr));
- gap: 5px;
- align-items: center;
-}
-.step-grid .track {
- font-size: 10px;
- text-align: left;
- border: 0;
- padding: 8px 0;
- color: var(--muted);
-}
-.step-grid .step {
- height: 30px;
- border-radius: 3px;
- padding: 0;
- background: #312a27;
- border: 1px solid #504138;
-}
-.step-grid .step.beat {
- background: #3a302b;
-}
-.step-grid .step[aria-pressed="true"] {
- background: #d59063;
- border-color: #e5a67e;
-}
-.step-grid .step.current {
- outline: 2px solid #f9e8c7;
- outline-offset: 0;
-}
-.step-grid .step-num {
- font: 8px monospace;
- text-align: center;
- color: #a99181;
-}
-.music-note {
- border-top: 1px solid var(--line);
- padding: 20px 0;
-}
-.music-note p {
- font:
- 17px Georgia,
- serif;
- margin-top: 8px;
-}
-.workspace {
- grid-template-columns: minmax(0, 1fr) 220px;
- gap: 30px;
-}
-#mixer .field {
- margin: 12px 0;
-}
-#mixer input {
- width: 100%;
-}
-@media (max-width: 800px) {
- .workspace {
- grid-template-columns: 1fr;
- }
- .intro {
- flex-direction: row;
- }
- .record {
- width: 125px;
- height: 125px;
- flex-shrink: 0;
- }
-}
-@media (max-width: 480px) {
- .record {
- width: 94px;
- height: 94px;
- margin: 10px 0;
- }
- .record-label {
- width: 46px;
- height: 46px;
- font-size: 8px;
- }
- .intro h1 {
- font-size: 42px;
- }
- .intro p {
- font-size: 12px;
- }
- .step-grid {
- grid-template-columns: 47px repeat(16, minmax(0, 1fr));
- gap: 3px;
- }
- .step-grid .step {
- height: 25px;
- }
- .step-grid .track {
- font-size: 8px;
- }
- .transport .mono {
- font-size: 10px;
- }
- #key {
- display: none;
- }
- .sections {
- font-size: 7px;
- }
-}
+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Afterhours · Music Studio</title><link rel="icon" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22256%22%20height%3D%22256%22%20viewBox%3D%220%200%2096%2096%22%3E%0A%20%20%3Ctitle%3EMusic%20Studio%20%E2%80%94%20five%20tracks%20after%20dark%3C%2Ftitle%3E%0A%20%20%3Crect%20x%3D%224%22%20y%3D%224%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2223%22%20fill%3D%22%23272537%22%2F%3E%0A%20%20%3Cpath%20d%3D%22M67%2017a15%2015%200%201%200%2012%2024%2016%2016%200%200%201-12-24Z%22%20fill%3D%22%23edbfa9%22%2F%3E%0A%20%20%3Cg%20fill%3D%22%23d6c7e9%22%3E%0A%20%20%20%20%3Crect%20x%3D%2219%22%20y%3D%2247%22%20width%3D%228%22%20height%3D%2221%22%20rx%3D%224%22%2F%3E%0A%20%20%20%20%3Crect%20x%3D%2232%22%20y%3D%2231%22%20width%3D%228%22%20height%3D%2245%22%20rx%3D%224%22%2F%3E%0A%20%20%20%20%3Crect%20x%3D%2245%22%20y%3D%2242%22%20width%3D%228%22%20height%3D%2226%22%20rx%3D%224%22%2F%3E%0A%20%20%20%20%3Crect%20x%3D%2258%22%20y%3D%2253%22%20width%3D%228%22%20height%3D%2223%22%20rx%3D%224%22%2F%3E%0A%20%20%20%20%3Crect%20x%3D%2271%22%20y%3D%2253%22%20width%3D%228%22%20height%3D%2215%22%20rx%3D%224%22%2F%3E%0A%20%20%3C%2Fg%3E%0A%3C%2Fsvg%3E%0A"><style>:root{color-scheme:dark;--bg:#10121a;--panel:#191d29;--line:#ffffff16;--ink:#f3ede8;--muted:#9299aa;--accent:#eabe90;--purple:#b9acf1;font:13px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink)}button,input,select{font:inherit;color:inherit;background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:8px 11px;min-width:0}button{cursor:pointer;touch-action:manipulation}button:hover{border-color:#8d819f}button:focus-visible,input:focus-visible,canvas:focus-visible,summary:focus-visible{outline:2px solid var(--accent);outline-offset:3px}button:disabled{opacity:.4;cursor:default}button.primary,.play{background:var(--accent);color:#1a1820;border:0;font-weight:650}button[aria-pressed=true]{border-color:var(--accent);color:var(--accent);background:#47352c}input[type=range]{padding:0;width:100%;accent-color:var(--accent)}input[type=number]{font-variant-numeric:tabular-nums}h1,h2,p{margin:0}h1{font-size:38px;font-weight:550;line-height:1.05;letter-spacing:-.045em;margin:9px 0 12px}h2{font-size:14px;font-weight:550}.eyebrow{font:9px/1.5 ui-monospace,monospace;letter-spacing:.18em;color:var(--muted)}header{display:flex;align-items:center;justify-content:space-between;gap:16px;min-height:72px;padding:16px 26px;border-bottom:1px solid var(--line)}.identity{display:flex;align-items:center;gap:11px;font-size:11px;letter-spacing:.08em;font-weight:650}.identity>span:last-child{border-left:1px solid var(--line);padding-left:12px;font-size:9px;color:var(--muted);font-weight:400}.brand-icon,.brand-icon svg{width:28px;height:28px;display:block}.file-actions,.small-actions,.exports,.transport-buttons{display:flex;align-items:center;gap:8px}main{display:grid;grid-template-columns:minmax(0,1fr) 248px;max-width:1900px;margin:auto}.main-panel{padding:30px;min-width:0}aside{padding:28px 22px;border-left:1px solid var(--line)}.project-heading{display:flex;align-items:center;justify-content:space-between;gap:32px}#brief{max-width:610px;font-size:12px;color:#aeb4c4;line-height:1.7}.project-controls{display:flex;align-items:end;gap:12px;flex-shrink:0}.project-controls label{width:67px}.project-controls input{width:100%}.project-controls #meter{font-size:11px;color:var(--muted);padding-bottom:25px}label{display:flex;flex-direction:column;gap:7px;font-size:11px;color:#c4c8d2;margin:15px 0}label output{font-size:10px;color:var(--muted)}.transport{display:flex;align-items:center;justify-content:space-between;margin:26px 0 16px;gap:14px}#time{font:11px ui-monospace,monospace;color:var(--muted);margin-left:10px;white-space:nowrap}.wave-stage{background:linear-gradient(120deg,#201e30,#191d2b);border:1px solid var(--line);border-radius:8px;overflow:hidden}.wave-stage canvas{width:100%;height:110px;display:block;cursor:pointer}.mix-stats{display:flex;justify-content:space-between;gap:10px;border-top:1px solid var(--line);padding:10px 15px;color:var(--muted);font:9px ui-monospace,monospace}.section-heading{display:flex;justify-content:space-between;align-items:center;gap:14px;margin:25px 0 13px}.small-actions button{font-size:10px;padding:6px 10px}.hint{color:var(--muted);font-size:10px;line-height:1.65;margin-top:5px}.sections{margin-left:156px;height:28px;position:relative;overflow:hidden}.section{position:absolute;top:0;height:24px;border-left:1px solid #b9acf166;color:#b9acf1;font:9px ui-monospace,monospace;white-space:nowrap;padding:4px 6px;background:#b9acf10a;overflow:hidden}.tracks{border:1px solid var(--line);border-radius:7px;overflow:hidden}.track{display:grid;grid-template-columns:155px minmax(0,1fr);border-bottom:1px solid var(--line);height:49px}.track:last-child{border-bottom:0}.track.selected{background:#b9acf110}.track-info{display:flex;align-items:center;gap:4px;padding:0 8px;border-right:1px solid var(--line);min-width:0}.track-info .track-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;text-align:left;border:0;background:transparent;padding:6px 2px;font-size:11px}.track-info .mini{font-size:8px;padding:3px 5px}.track canvas{width:100%;height:48px;display:block;cursor:pointer}.piano-stage{border:1px solid var(--line);border-radius:7px;overflow:hidden;background:#131722}#piano{height:250px;width:100%;display:block;touch-action:none;cursor:crosshair}.note-editor{display:grid;grid-template-columns:90px 90px 85px minmax(90px,1fr) auto;gap:12px;align-items:end}.note-editor button{margin-bottom:15px;font-size:10px}.note-editor input:not([type=range]){width:100%}.note-editor label{margin:12px 0 15px;font-size:10px}.edit-actions{display:flex;justify-content:space-between;align-items:center;gap:16px;margin-top:3px;padding:13px 0;border-bottom:1px solid var(--line)}.edit-actions button{font-size:10px}.edit-actions span{font-size:9px;color:var(--muted)}.handoff{display:grid;grid-template-columns:1fr 1fr;gap:30px;margin-top:27px}.handoff h2{font-size:19px;letter-spacing:-.025em;margin:5px 0 9px}.handoff p:not(.eyebrow),.handoff details{font-size:11px;line-height:1.7;color:var(--muted)}.handoff summary{color:var(--accent);cursor:pointer}.handoff details p{margin-top:12px}.rule{height:1px;background:var(--line);margin:23px 0}.mixer-buttons,.transpose{display:flex;gap:8px}.mixer-buttons button,.transpose button{flex:1;font-size:11px}.quiet{font-size:10px;width:100%;margin-top:10px;color:var(--muted)}#toast{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);max-width:90vw;border-radius:7px;background:#ede1d5;color:#17141d;padding:11px 18px;opacity:0;pointer-events:none;box-shadow:0 12px 35px #0007;z-index:20;font-size:12px}#toast.visible{opacity:1}.error{position:fixed;bottom:20px;left:20px;right:280px;background:#442628;border:1px solid #ad6160;border-radius:7px;padding:14px;color:#ffe0de;z-index:10}.notice{padding:12px 25px;background:#413623;display:flex;gap:12px;align-items:center;font-size:11px}.notice button{font-size:11px}[hidden]{display:none!important}@media(min-width:1500px){.main-panel{padding:35px 45px}main{grid-template-columns:minmax(0,1fr) 280px}#piano{height:285px}.track{height:57px}.track canvas{height:56px}}@media(max-width:1100px){.identity>span:last-child{display:none}main{grid-template-columns:minmax(0,1fr) 215px}.main-panel{padding:24px 20px}aside{padding:24px 16px}.project-heading{display:block}.project-controls{margin-top:8px}.project-controls label{margin-bottom:0}.project-controls #meter{padding-bottom:10px}.transport{flex-wrap:wrap}.note-editor{grid-template-columns:65px 70px 70px minmax(60px,1fr)}.note-editor button{grid-column:1/-1;margin-top:-10px}.handoff{grid-template-columns:1fr;gap:16px}}@media(max-width:700px){header{padding:14px;flex-wrap:wrap}.file-actions{width:100%}.file-actions button{flex:1;font-size:10px}main{display:block}.main-panel{padding:25px 14px}aside{border-top:1px solid var(--line);border-left:0;padding:24px;display:grid;grid-template-columns:1fr 1fr;gap:0 20px}aside>.eyebrow,aside>.rule,aside>.hint{grid-column:1/-1}.track{grid-template-columns:110px minmax(0,1fr)}.track-info{padding:0 5px}.track-info .track-name{font-size:9px}.track-info .mini{padding:2px 3px}.sections{margin-left:111px}.section-heading{flex-wrap:wrap}.small-actions{gap:5px;flex-wrap:wrap}.small-actions button{font-size:9px}.transport-buttons{gap:6px}#time{margin-left:0;font-size:10px}.transport button,.exports button{font-size:11px}.mix-stats{font-size:8px}.edit-actions{align-items:flex-start;flex-direction:column}.notice{flex-wrap:wrap}.error{right:20px}h1{font-size:34px}.note-editor{grid-template-columns:60px 70px 70px minmax(45px,1fr);gap:9px}.note-editor button{grid-column:auto;margin-top:0;grid-column:1/3}#piano{height:245px}}
+.transport{position:sticky;top:0;z-index:5;background:var(--bg);padding:10px 0}aside{position:sticky;top:0;height:100vh;overflow:auto}@media(max-width:700px){aside{position:static;height:auto;overflow:visible}}
</style></head><body>
-<header class="masthead"><div class="identity"><span class="mark" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">
+<header><div class="identity"><span class="brand-icon"><svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">
<title>Music Studio — five tracks after dark</title>
<rect x="4" y="4" width="88" height="88" rx="23" fill="#272537"/>
<path d="M67 17a15 15 0 1 0 12 24 16 16 0 0 1-12-24Z" fill="#edbfa9"/>
@@ -607,590 +12,552 @@ canvas {
<rect x="58" y="53" width="8" height="23" rx="4"/>
<rect x="71" y="53" width="8" height="15" rx="4"/>
</g>
-</svg></span>AFTERHOURS</div>
-<form class="seed-form" id="seed-form"><label for="seed">Seed</label><input id="seed" aria-label="Seed" maxlength="128" autocomplete="off" spellcheck="false"><button type="submit">Apply</button><button id="next-seed" type="button" title="Next seed">↗ Next</button></form></header>
-<section class="intro">
- <div>
- <p class="eyebrow">A small room for big ideas / Vol. 01</p>
- <h1>Stay a little<br /><em>longer.</em></h1>
- <p>
- Eight bars after midnight. Shape the rhythm, find the pocket, take the
- whole thing with you.
- </p>
- </div>
- <div class="record" aria-hidden="true">
- <div class="record-label">AFTER<br />HOURS<span>33 ⅓</span></div>
- </div>
-</section>
-<main class="workspace">
- <div>
- <section class="transport">
- <button id="play" class="primary">▶ Play</button
- ><button id="stop" aria-label="Stop playback">■</button
- ><span class="mono" id="time">0:00 / 0:00</span
- ><span id="key" class="muted mono"></span
- ><button id="export-wav">Export WAV ↗</button>
- </section>
- <section class="wave-panel">
- <canvas
- id="waveform"
- aria-label="Waveform of the full arrangement"
- ></canvas>
- <div class="sections">
- <span>01 / ARRIVE</span><span>02 / FIND THE POCKET</span
- ><span>03 / LET GO</span>
- </div>
- </section>
- <section class="sequencer">
- <div class="panel-head">
- <h3>The pattern</h3>
- <span class="eyebrow" id="bar">8 bars / 16 steps</span>
- </div>
- <div class="step-grid" id="steps"></div>
- <p class="small muted" style="padding: 12px 0">
- Tap a step to write the pattern. Tap a track name to mute it.
- </p>
- </section>
- <div class="music-note">
- <span class="eyebrow">Your arrangement</span>
- <p id="audio-status">Your score is ready. Press Play to hear it.</p>
- </div>
- </div>
- <aside class="side">
- <div>
- <p class="eyebrow">The pocket</p>
- <label class="field"
- ><span>Tempo <output id="tempo-value"></output></span
- ><input id="tempo" type="range" min="66" max="132" value="86" /></label
- ><label class="field"
- ><span>Swing <output id="swing-value">16%</output></span
- ><input id="swing" type="range" min="0" max="45" value="16" /></label
- ><label class="field"
- ><span>Listening level <output id="volume-value">70%</output></span
- ><input id="volume" type="range" min="0" max="100" value="70"
- /></label>
- </div>
- <div class="section">
- <h3>The mix</h3>
- <div id="mixer"></div>
- </div>
- <div class="section small muted">
- <p>
- Original, locally synthesized audio. No samples to download, no account,
- no network.
- </p>
- <p style="margin-top: 10px">
- The same score and settings produce the same PCM samples here. WAV
- exports are mono, 22.05 kHz.
- </p>
- </div>
- </aside>
-</main>
-<footer class="status-line">
- <span><i class="dot"></i>LISTEN FIRST. THEN MAKE IT YOURS.</span
- ><span id="peak"></span>
-</footer>
-<div class="toast" id="toast" role="status"></div>
-<script id="harness-model">
-'use strict';
-// Shared deterministic primitives. Domain models use named streams so unrelated edits stay stable.
-function hash(value) {
- let h = 2166136261;
- for (const c of String(value)) h = Math.imul(h ^ c.charCodeAt(0), 16777619);
- return h >>> 0;
-}
-function random(seed, stream = "main") {
- let a = hash(`${seed}:${stream}`);
- return () => {
- a = (a + 0x6d2b79f5) | 0;
- let t = Math.imul(a ^ (a >>> 15), 1 | a);
- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
- };
-}
-const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));
-const lerp = (a, b, t) => a + (b - a) * t;
-const pick = (items, rng) => items[Math.floor(rng() * items.length)];
-function normal(rng) {
- return (
- Math.sqrt(-2 * Math.log(Math.max(1e-9, rng()))) *
- Math.cos(2 * Math.PI * rng())
- );
-}
-
-const trackNames = ["Kick", "Snare", "Hi-hat", "Bass", "Keys"];
-function musicScore(seed) {
- const rhythm = random(seed, "rhythm"),
- melody = random(seed, "melody"),
- harmony = random(seed, "harmony");
- const root = pick([45, 48, 50, 52], harmony),
- scale = [0, 3, 5, 7, 10];
- const patterns = [
- Array.from(
- { length: 16 },
- (_, i) => i % 4 === 0 || (i === 14 && rhythm() > 0.5),
- ),
- Array.from({ length: 16 }, (_, i) => i === 4 || i === 12),
- Array.from({ length: 16 }, (_, i) => i % 2 === 0 || rhythm() > 0.64),
- Array.from({ length: 16 }, (_, i) => [0, 6, 8, 14].includes(i)),
- Array.from({ length: 16 }, (_, i) => i % 2 === 0 && melody() > 0.18),
- ];
- return {
- seed: String(seed),
- root,
- tempo: pick([82, 86, 90, 94], harmony),
- bars: 8,
- patterns,
- notes: Array.from({ length: 16 }, () => root + 24 + pick(scale, melody)),
- chords: [0, 0, 5, 5, 3, 3, 7, 0],
- };
-}
-function scoreEvents(
- score,
- {
- tempo = score.tempo,
- swing = 16,
- patterns = score.patterns,
- muted = [],
- } = {},
-) {
- const beat = 60 / tempo,
- step = beat / 4,
- events = [];
- for (let bar = 0; bar < score.bars; bar++)
- for (let tick = 0; tick < 16; tick++)
- for (let track = 0; track < 5; track++) {
- if (
- !patterns[track][tick] ||
- muted[track] ||
- (bar === 0 && track === 1) ||
- (bar === 7 && tick > 11 && track < 3)
- )
- continue;
- const time =
- (bar * 16 + tick) * step + (tick % 2 ? (step * swing) / 100 : 0);
- events.push({
- track,
- time,
- note:
- track === 3
- ? score.root - 12 + score.chords[bar]
- : score.notes[tick] + score.chords[bar],
- duration:
- track === 4 ? beat * 1.1 : track === 3 ? beat * 0.7 : beat * 0.35,
- bar,
- tick,
- });
- }
- return { events, duration: score.bars * 4 * beat + 1, beat };
-}
-function renderMusic(score, options = {}, sampleRate = 22050) {
- const { events, duration } = scoreEvents(score, options),
- samples = new Float32Array(Math.ceil(duration * sampleRate));
- const levels = options.levels ?? [0.85, 0.5, 0.32, 0.6, 0.5];
- for (const event of events) {
- const { track, time, note } = event,
- start = Math.round(time * sampleRate),
- length = Math.min(
- samples.length - start,
- Math.ceil((track < 3 ? 0.24 : event.duration + 0.3) * sampleRate),
- );
- const frequency = 440 * 2 ** ((note - 69) / 12),
- noise = random(score.seed, `hit:${track}:${event.bar}:${event.tick}`);
- let phase = 0;
- for (let i = 0; i < length; i++) {
- const t = i / sampleRate;
- let value = 0;
- if (track === 0) {
- phase += (2 * Math.PI * (48 + 125 * Math.exp(-t * 38))) / sampleRate;
- value = Math.sin(phase) * Math.exp(-t * 18) * 0.8;
- }
- if (track === 1)
- value =
- ((noise() * 2 - 1) * 0.66 + Math.sin(2 * Math.PI * 180 * t) * 0.34) *
- Math.exp(-t * 23) *
- 0.55;
- if (track === 2) value = (noise() * 2 - 1) * Math.exp(-t * 75) * 0.27;
- if (track === 3)
- value =
- (Math.sin(2 * Math.PI * frequency * t) +
- 0.18 * Math.sin(4 * Math.PI * frequency * t)) *
- Math.min(1, t * 90) *
- Math.exp(-t * 5) *
- 0.5;
- if (track === 4)
- value =
- (Math.sin(2 * Math.PI * frequency * t) * 0.6 +
- Math.sin(2 * Math.PI * frequency * 2.002 * t) * 0.15 +
- Math.sin(2 * Math.PI * frequency * 0.5 * t) * 0.25) *
- Math.min(1, t * 120) *
- Math.exp(-t * 3.8) *
- 0.4;
- samples[start + i] += value * levels[track];
+</svg>
+</span>AFTERHOURS<span>MUSIC STUDIO</span></div><div class="file-actions"><button id="open-project">Open project</button><button id="save-project">Save project</button><button id="export-stems" class="primary">Stems + project ↗</button></div></header>
+<div class="notice" id="revision-notice" hidden><span>A new agent revision is available. Your saved mix and notes are still here.</span><button id="use-revision">Use new version</button><button id="keep-draft">Keep my draft</button></div>
+<main><section class="main-panel"><div class="project-heading"><div><p class="eyebrow">YOUR COMPOSITION</p><h1 id="title"></h1><p id="brief"></p></div><div class="project-controls"><label>Tempo<input id="tempo" type="number" min="30" max="240" step="0.001"></label><label>Bars<input id="bars" type="number" min="1" max="256"></label><span id="meter"></span></div></div>
+<div class="transport"><div class="transport-buttons"><button id="play" class="play" aria-label="Play">▶ Play</button><button id="stop">■ Stop</button><span id="time">0:00 / 0:00</span></div><div class="exports"><button id="export-wav">Export WAV ↗</button><button id="export-midi">Export MIDI ↗</button></div></div>
+<div class="wave-stage"><canvas id="waveform" aria-label="Rendered stereo waveform"></canvas><div class="mix-stats"><span id="audio-status">Preparing your mix</span><span id="level">48 kHz / stereo</span></div></div>
+<div class="section-heading"><h2>Arrangement</h2><div class="small-actions"><button id="open-midi">Open MIDI</button><button id="import-audio">Add recording</button><button id="add-track">+ Instrument</button></div></div>
+<div id="sections" class="sections"></div><div id="tracks" class="tracks"></div>
+<div class="section-heading"><div><h2 id="piano-title">Notes</h2><p class="hint">Click to add. Drag to move. Select a note to change its pitch, length or touch.</p></div><div class="small-actions"><button id="previous-bars" aria-label="Previous bars">←</button><span id="bar-window"></span><button id="next-bars" aria-label="Next bars">→</button></div></div>
+<div class="piano-stage"><canvas id="piano" aria-label="Editable piano roll" tabindex="0"></canvas></div>
+<div class="note-editor"><label>Pitch<input id="note-pitch" value="C4" size="5"></label><label>Start beat<input id="note-start" type="number" min="0" step="0.25"></label><label>Length<input id="note-length" type="number" min="0.125" step="0.25" value="1"></label><label>Touch<input id="note-velocity" type="range" min="0.05" max="1" step="0.01" value="0.75"></label><button id="delete-note">Delete note</button></div>
+<div class="edit-actions"><div><button id="undo">↶ Undo</button><button id="redo">↷ Redo</button><button id="duplicate-section">Repeat these bars</button></div><span id="draft-status">Draft saved on this device</span></div>
+<div class="handoff"><div><p class="eyebrow">KEEP MAKING IT YOURS</p><h2>A piece you can take anywhere.</h2><p>Bring your own MIDI or recordings. Keep the notes editable. Export the mix and separate tracks to continue in your DAW.</p></div><details><summary>Make a completely different piece</summary><p>Describe it in the Harness chat. Give the purpose, mood, length and any melody or recording you want to use. The agent writes a complete arrangement for your brief. This example is not a genre restriction.</p><p>Try: “Make a 40-second title sequence for a coastal documentary. Start with an intimate plucked motif, open into warm harmony, then end on a quiet resolved chord. Leave room for my voiceover.”</p></details></div>
+</section><aside><p class="eyebrow">SELECTED TRACK</p><label>Track name<input id="track-name"></label><label>Sound<select id="instrument"></select></label><div id="sampler-controls" hidden><label>Sample<select id="sample-id"></select></label><label>Original pitch<input id="sample-root" value="C4"></label></div>
+<div class="mixer-buttons"><button id="mute">Mute</button><button id="solo">Solo</button></div>
+<label>Level <output id="gain-label"></output><input id="gain" type="range" min="0" max="1.5" step="0.01"></label><label>Position <output id="pan-label"></output><input id="pan" type="range" min="-1" max="1" step="0.01"></label>
+<div class="rule"></div><p class="eyebrow">SHAPE THE SOUND</p><label>Soft entrance<input id="attack" type="range" min="0.001" max="3" step="0.001"></label><label>Release<input id="release" type="range" min="0.01" max="3" step="0.01"></label><label>Brightness<input id="tone" type="range" min="100" max="20000" step="100"></label><label>Room<input id="space" type="range" min="0" max="0.8" step="0.01"></label><label>Echo<input id="delay" type="range" min="0" max="0.6" step="0.01"></label>
+<div id="clip-controls" hidden><div class="rule"></div><p class="eyebrow">RECORDING</p><label>Clip<select id="clip-select"></select></label><label>Start beat<input id="clip-beat" type="number" min="0" step="0.25"></label><label>Trim start (seconds)<input id="clip-offset" type="number" min="0" step="0.01"></label><label>Length (seconds)<input id="clip-duration" type="number" min="0.01" step="0.01"></label></div>
+<div class="rule"></div><div class="transpose"><button id="transpose-down">− Octave</button><button id="transpose-up">+ Octave</button></div><button id="remove-track" class="quiet">Remove track</button><div class="rule"></div><p class="eyebrow">MASTER</p><label>Output level<input id="master" type="range" min="0" max="1" step="0.01"></label><p class="hint">WAV: 48 kHz, stereo, 16-bit. Stems follow mute and solo. MIDI keeps all notes; recordings travel as audio.</p><button id="export-html" class="quiet">Portable studio ↗</button><button id="reset-project" class="quiet">Restore agent version</button></aside></main>
+<div id="error" class="error" role="alert" hidden></div><div id="toast" role="status"></div><input id="project-file" type="file" accept=".json" hidden><input id="midi-file" type="file" accept=".mid,.midi" hidden><input id="audio-file" type="file" accept="audio/wav,audio/mpeg,audio/mp3,audio/ogg,audio/mp4" hidden>
+<script id="afterhours-data" type="application/json">{"spec":"afterhours/1","id":"blue-hour","title":"Blue Hour","brief":"A 48-second title cue for a coastal documentary. An intimate plucked motif opens into warm harmony and a restrained pulse, then resolves quietly. The arrangement leaves space for a voiceover.","seed":"blue-hour","tempo":100,"meter":[4,4],"beats":80,"tail":0,"master":0.9,"sections":[{"name":"First light","beat":0,"length":16},{"name":"Footsteps","beat":16,"length":16},{"name":"Open water","beat":32,"length":16},{"name":"The lift","beat":48,"length":16},{"name":"Home","beat":64,"length":16}],"tracks":[{"id":"motif","name":"Plucked motif","instrument":"pluck","gain":0.92,"pan":-0.22,"tone":7200,"space":0.18,"delay":0.12,"release":0.35,"notes":[{"beat":0,"midi":62,"duration":0.9,"velocity":0.5645551978774368},{"beat":1.5,"midi":69,"duration":0.55,"velocity":0.5156839515805244},{"beat":3,"midi":73,"duration":0.55,"velocity":0.5337221220098436},{"beat":4,"midi":69,"duration":0.9,"velocity":0.5704508999161422},{"beat":5.5,"midi":73,"duration":0.55,"velocity":0.5553384073100984},{"beat":7,"midi":78,"duration":0.55,"velocity":0.5486000507526099},{"beat":8,"midi":59,"duration":0.9,"velocity":0.542434654519707},{"beat":9.5,"midi":66,"duration":0.55,"velocity":0.5555654297582805},{"beat":11,"midi":69,"duration":0.55,"velocity":0.5576091022111475},{"beat":12,"midi":66,"duration":0.9,"velocity":0.5498305642195046},{"beat":13.5,"midi":69,"duration":0.55,"velocity":0.5180191269449889},{"beat":15,"midi":74,"duration":0.55,"velocity":0.551269242669642},{"beat":16,"midi":55,"duration":0.9,"velocity":0.5297916078120469},{"beat":16.75,"midi":62,"duration":0.55,"velocity":0.531561849565804},{"beat":17.5,"midi":66,"duration":0.55,"velocity":0.5246851859532295},{"beat":18,"midi":71,"duration":0.9,"velocity":0.5459769469805061},{"beat":18.75,"midi":55,"duration":0.55,"velocity":0.5430110706716775},{"beat":19.5,"midi":62,"duration":0.55,"velocity":0.5556431808911263},{"beat":20,"midi":62,"duration":0.9,"velocity":0.5426485464416444},{"beat":20.75,"midi":66,"duration":0.55,"velocity":0.551458582278341},{"beat":21.5,"midi":71,"duration":0.55,"velocity":0.5649891081705689},{"beat":22,"midi":55,"duration":0.9,"velocity":0.5389283135816455},{"beat":22.75,"midi":62,"duration":0.55,"velocity":0.5602186762280762},{"beat":23.5,"midi":66,"duration":0.55,"velocity":0.5550721922561526},{"beat":24,"midi":57,"duration":0.9,"velocity":0.5556441643811761},{"beat":24.75,"midi":64,"duration":0.55,"velocity":0.5601637458100914},{"beat":25.5,"midi":69,"duration":0.55,"velocity":0.5181704859040677},{"beat":26,"midi":73,"duration":0.9,"velocity":0.5534745311327278},{"beat":26.75,"midi":57,"duration":0.55,"velocity":0.5393594153784215},{"beat":27.5,"midi":64,"duration":0.55,"velocity":0.580917686356604},{"beat":28,"midi":64,"duration":0.9,"velocity":0.5533817687354982},{"beat":28.75,"midi":69,"duration":0.55,"velocity":0.5587183390788734},{"beat":29.5,"midi":73,"duration":0.55,"velocity":0.5792586211293935},{"beat":30,"midi":57,"duration":0.9,"velocity":0.573284814916551},{"beat":30.75,"midi":64,"duration":0.55,"velocity":0.5703277547985315},{"beat":31.5,"midi":69,"duration":0.55,"velocity":0.5619088765397667},{"beat":32,"midi":62,"duration":0.9,"velocity":0.5153246533192694},{"beat":32.75,"midi":69,"duration":0.55,"velocity":0.5237792561523615},{"beat":33.5,"midi":73,"duration":0.55,"velocity":0.5725928144164383},{"beat":34,"midi":78,"duration":0.9,"velocity":0.5557868683211505},{"beat":34.75,"midi":62,"duration":0.55,"velocity":0.5406799630582332},{"beat":35.5,"midi":69,"duration":0.55,"velocity":0.5282267559967935},{"beat":36,"midi":69,"duration":0.9,"velocity":0.5165786395415664},{"beat":36.75,"midi":73,"duration":0.55,"velocity":0.5615075619526207},{"beat":37.5,"midi":78,"duration":0.55,"velocity":0.5189804663449525},{"beat":38,"midi":62,"duration":0.9,"velocity":0.5445952211908995},{"beat":38.75,"midi":69,"duration":0.55,"velocity":0.5558770329765975},{"beat":39.5,"midi":73,"duration":0.55,"velocity":0.5320751886576414},{"beat":40,"midi":59,"duration":0.9,"velocity":0.5198988145969808},{"beat":40.75,"midi":66,"duration":0.55,"velocity":0.5620267365992069},{"beat":41.5,"midi":69,"duration":0.55,"velocity":0.5809937621548772},{"beat":42,"midi":74,"duration":0.9,"velocity":0.5508571488857269},{"beat":42.75,"midi":59,"duration":0.55,"velocity":0.5699040935456753},{"beat":43.5,"midi":66,"duration":0.55,"velocity":0.578915261233598},{"beat":44,"midi":66,"duration":0.9,"velocity":0.5367697411932051},{"beat":44.75,"midi":69,"duration":0.55,"velocity":0.5672844250261783},{"beat":45.5,"midi":74,"duration":0.55,"velocity":0.5304293285422027},{"beat":46,"midi":59,"duration":0.9,"velocity":0.5438700043462216},{"beat":46.75,"midi":66,"duration":0.55,"velocity":0.5440233726710081},{"beat":47.5,"midi":69,"duration":0.55,"velocity":0.5674215055428445},{"beat":48,"midi":55,"duration":0.9,"velocity":0.672498374399729},{"beat":48.75,"midi":62,"duration":0.55,"velocity":0.7142857280028984},{"beat":49.5,"midi":66,"duration":0.55,"velocity":0.6693470929078758},{"beat":50,"midi":71,"duration":0.9,"velocity":0.6544555243700743},{"beat":50.75,"midi":55,"duration":0.55,"velocity":0.7016154746282844},{"beat":51.5,"midi":62,"duration":0.55,"velocity":0.7146699369736016},{"beat":52,"midi":62,"duration":0.9,"velocity":0.6642920906236396},{"beat":52.75,"midi":66,"duration":0.55,"velocity":0.7161841747676952},{"beat":53.5,"midi":71,"duration":0.55,"velocity":0.6836484735189006},{"beat":54,"midi":55,"duration":0.9,"velocity":0.670372108512558},{"beat":54.75,"midi":62,"duration":0.55,"velocity":0.693134555073455},{"beat":55.5,"midi":66,"duration":0.55,"velocity":0.6526450070301071},{"beat":56,"midi":57,"duration":0.9,"velocity":0.6671485533202067},{"beat":56.75,"midi":64,"duration":0.55,"velocity":0.7067000186173245},{"beat":57.5,"midi":69,"duration":0.55,"velocity":0.6841152801522985},{"beat":58,"midi":73,"duration":0.9,"velocity":0.6866803099540993},{"beat":58.75,"midi":57,"duration":0.55,"velocity":0.6533734201705083},{"beat":59.5,"midi":64,"duration":0.55,"velocity":0.6772519801398739},{"beat":60,"midi":64,"duration":0.9,"velocity":0.6657161834491416},{"beat":60.75,"midi":69,"duration":0.55,"velocity":0.6660698143094779},{"beat":61.5,"midi":73,"duration":0.55,"velocity":0.6567942600864917},{"beat":62,"midi":57,"duration":0.9,"velocity":0.6868582462500781},{"beat":62.75,"midi":64,"duration":0.55,"velocity":0.6881102317394688},{"beat":63.5,"midi":69,"duration":0.55,"velocity":0.6895300984820351},{"beat":64,"midi":62,"duration":0.9,"velocity":0.5748425221830606},{"beat":64.75,"midi":69,"duration":0.55,"velocity":0.5556503183364868},{"beat":65.5,"midi":73,"duration":0.55,"velocity":0.5547063233807682},{"beat":66,"midi":78,"duration":0.9,"velocity":0.5626272984817624},{"beat":66.75,"midi":62,"duration":0.55,"velocity":0.522831639175117},{"beat":67.5,"midi":69,"duration":0.55,"velocity":0.5546279738426209},{"beat":68,"midi":69,"duration":0.9,"velocity":0.5413805456191301},{"beat":68.75,"midi":73,"duration":0.55,"velocity":0.5201513358294964},{"beat":69.5,"midi":78,"duration":0.55,"velocity":0.5385957259826362},{"beat":70,"midi":62,"duration":0.9,"velocity":0.534280517487973},{"beat":70.75,"midi":69,"duration":0.55,"velocity":0.5577538215406239},{"beat":71.5,"midi":73,"duration":0.55,"velocity":0.5772834022156894},{"beat":72,"midi":59,"duration":0.9,"velocity":0.4230030191425234},{"beat":74,"midi":66,"duration":0.55,"velocity":0.38740793404039},{"beat":76,"midi":66,"duration":0.9,"velocity":0.3901720629170537},{"beat":78,"midi":69,"duration":0.55,"velocity":0.40686308683957906},{"beat":77.5,"midi":74,"duration":1.4,"velocity":0.343521455296129}],"muted":false,"solo":false,"attack":0.008,"sampleRoot":60,"clips":[]},{"id":"felt","name":"Felt melody","instrument":"felt","gain":0.7,"pan":0.15,"tone":5200,"space":0.24,"release":0.75,"notes":[{"beat":16,"midi":71,"duration":1.1,"velocity":0.4673883465398103},{"beat":17.5,"midi":69,"duration":0.8,"velocity":0.49379954020492733},{"beat":19,"midi":66,"duration":1.7,"velocity":0.6301682471336797},{"beat":21.5,"midi":62,"duration":1.8,"velocity":0.49152300154324624},{"beat":24,"midi":69,"duration":1.1,"velocity":0.4603718268405646},{"beat":25.5,"midi":73,"duration":0.8,"velocity":0.48717615934088826},{"beat":27,"midi":76,"duration":1.7,"velocity":0.6432531002314761},{"beat":29.5,"midi":73,"duration":1.8,"velocity":0.4998916279897094},{"beat":32,"midi":74,"duration":1.1,"velocity":0.501504489555955},{"beat":33.5,"midi":73,"duration":0.8,"velocity":0.48988275276497006},{"beat":35,"midi":69,"duration":1.7,"velocity":0.5941922905027867},{"beat":37.5,"midi":66,"duration":1.8,"velocity":0.48086906783282757},{"beat":40,"midi":73,"duration":1.1,"velocity":0.5025697763077915},{"beat":41.5,"midi":69,"duration":0.8,"velocity":0.48952602764125913},{"beat":43,"midi":66,"duration":1.7,"velocity":0.5855324333235622},{"beat":45.5,"midi":62,"duration":1.8,"velocity":0.5071403011493385},{"beat":48,"midi":71,"duration":1.1,"velocity":0.46563015357125553},{"beat":49.5,"midi":69,"duration":0.8,"velocity":0.49834976814221593},{"beat":51,"midi":66,"duration":1.7,"velocity":0.5926955807154999},{"beat":53.5,"midi":62,"duration":1.8,"velocity":0.4645159267447889},{"beat":56,"midi":69,"duration":1.1,"velocity":0.4845800973614678},{"beat":57.5,"midi":73,"duration":0.8,"velocity":0.5087262404616922},{"beat":59,"midi":76,"duration":1.7,"velocity":0.641343982924521},{"beat":61.5,"midi":73,"duration":1.8,"velocity":0.48929653075523677},{"beat":64,"midi":74,"duration":1.1,"velocity":0.46052718054037545},{"beat":65.5,"midi":73,"duration":0.8,"velocity":0.4692010128684342},{"beat":67,"midi":69,"duration":1.7,"velocity":0.6186143748374656},{"beat":69.5,"midi":66,"duration":1.8,"velocity":0.5143161941040307},{"beat":76,"midi":62,"duration":2.7,"velocity":0.3558878572102636},{"beat":76.09,"midi":69,"duration":2.6,"velocity":0.35292200230546295},{"beat":76.18,"midi":74,"duration":2.5,"velocity":0.34290987599417566},{"beat":76.27,"midi":78,"duration":2.4000000000000004,"velocity":0.3397677047353238}],"muted":false,"solo":false,"attack":0.008,"delay":0,"sampleRoot":60,"clips":[]},{"id":"pad","name":"Warm horizon","instrument":"pad","gain":0.24,"pan":0,"tone":1600,"attack":0.55,"space":0.35,"release":0.9,"notes":[{"beat":16,"midi":62,"duration":7.5,"velocity":0.37253679525852207},{"beat":16.045,"midi":66,"duration":7.5,"velocity":0.3803293997310102},{"beat":16.09,"midi":71,"duration":7.5,"velocity":0.4021729043647647},{"beat":24,"midi":64,"duration":7.5,"velocity":0.3783894086442888},{"beat":24.045,"midi":69,"duration":7.5,"velocity":0.3832112705297768},{"beat":24.09,"midi":73,"duration":7.5,"velocity":0.40341265460848813},{"beat":32,"midi":69,"duration":7.5,"velocity":0.40125959977880127},{"beat":32.045,"midi":73,"duration":7.5,"velocity":0.3932125707380474},{"beat":32.09,"midi":78,"duration":7.5,"velocity":0.3723255736678839},{"beat":40,"midi":66,"duration":7.5,"velocity":0.38505192853137854},{"beat":40.045,"midi":69,"duration":7.5,"velocity":0.39397476967051626},{"beat":40.09,"midi":74,"duration":7.5,"velocity":0.3787869536057115},{"beat":48,"midi":62,"duration":7.5,"velocity":0.5097104608826339},{"beat":48.045,"midi":66,"duration":7.5,"velocity":0.4887416532775387},{"beat":48.09,"midi":71,"duration":7.5,"velocity":0.4663905056659132},{"beat":56,"midi":64,"duration":7.5,"velocity":0.47987989383284},{"beat":56.045,"midi":69,"duration":7.5,"velocity":0.4905236521502957},{"beat":56.09,"midi":73,"duration":7.5,"velocity":0.5169125688262284},{"beat":64,"midi":69,"duration":7.5,"velocity":0.36891332033276564},{"beat":64.045,"midi":73,"duration":7.5,"velocity":0.38823245551437147},{"beat":64.09,"midi":78,"duration":7.5,"velocity":0.3705159105472267}],"muted":false,"solo":false,"delay":0,"sampleRoot":60,"clips":[]},{"id":"bass","name":"Low tide","instrument":"bass","gain":0.55,"pan":0,"tone":1100,"space":0.02,"release":0.2,"notes":[{"beat":32,"midi":38,"duration":2.7,"velocity":0.5659881625939162},{"beat":36,"midi":38,"duration":2.7,"velocity":0.57739312787354},{"beat":39,"midi":38,"duration":0.75,"velocity":0.4011168014382943},{"beat":40,"midi":35,"duration":2.7,"velocity":0.5901264471597971},{"beat":44,"midi":35,"duration":2.7,"velocity":0.5557340490985663},{"beat":47,"midi":35,"duration":0.75,"velocity":0.38950243089739234},{"beat":48,"midi":31,"duration":2.7,"velocity":0.7510273775272072},{"beat":52,"midi":31,"duration":2.7,"velocity":0.7463892952236347},{"beat":55,"midi":31,"duration":0.75,"velocity":0.4253533074991777},{"beat":56,"midi":33,"duration":2.7,"velocity":0.7061171898711472},{"beat":60,"midi":33,"duration":2.7,"velocity":0.7267716949526222},{"beat":63,"midi":33,"duration":0.75,"velocity":0.40719077550172805},{"beat":64,"midi":38,"duration":2.7,"velocity":0.5554849594887347},{"beat":68,"midi":38,"duration":2.7,"velocity":0.6220494564995172},{"beat":71,"midi":38,"duration":0.75,"velocity":0.39888761456049976}],"muted":false,"solo":false,"attack":0.008,"delay":0,"sampleRoot":60,"clips":[]},{"id":"pulse","name":"Soft pulse","instrument":"drums","gain":0.4,"pan":0.04,"tone":12000,"space":0.06,"release":0.05,"notes":[{"beat":32,"midi":36,"duration":0.15,"velocity":0.6424152635859326},{"beat":34.5,"midi":36,"duration":0.15,"velocity":0.38359787704553455},{"beat":34,"midi":38,"duration":0.12,"velocity":0.267568149670586},{"beat":32.5,"midi":42,"duration":0.08,"velocity":0.26824469596356154},{"beat":33,"midi":42,"duration":0.08,"velocity":0.15431948463171724},{"beat":33.5,"midi":42,"duration":0.08,"velocity":0.2763720994761586},{"beat":34,"midi":42,"duration":0.08,"velocity":0.16475707195252184},{"beat":34.5,"midi":42,"duration":0.08,"velocity":0.28171498903155323},{"beat":35,"midi":42,"duration":0.08,"velocity":0.14896126154810194},{"beat":35.5,"midi":42,"duration":0.08,"velocity":0.28008688166856766},{"beat":36,"midi":36,"duration":0.15,"velocity":0.6103359449379147},{"beat":38.5,"midi":36,"duration":0.15,"velocity":0.34600719700139015},{"beat":38,"midi":38,"duration":0.12,"velocity":0.2577655539680273},{"beat":36.5,"midi":42,"duration":0.08,"velocity":0.2911793159544468},{"beat":37,"midi":42,"duration":0.08,"velocity":0.16618706753551965},{"beat":37.5,"midi":42,"duration":0.08,"velocity":0.28155436441898346},{"beat":38,"midi":42,"duration":0.08,"velocity":0.14951299550086264},{"beat":38.5,"midi":42,"duration":0.08,"velocity":0.292978693215251},{"beat":39,"midi":42,"duration":0.08,"velocity":0.16493001419603828},{"beat":39.5,"midi":42,"duration":0.08,"velocity":0.29935998227208854},{"beat":40,"midi":36,"duration":0.15,"velocity":0.6227911817951128},{"beat":42.5,"midi":36,"duration":0.15,"velocity":0.36319101423379035},{"beat":42,"midi":38,"duration":0.12,"velocity":0.2674223409183324},{"beat":40.5,"midi":42,"duration":0.08,"velocity":0.26885269566714765},{"beat":41,"midi":42,"duration":0.08,"velocity":0.14842683670371776},{"beat":41.5,"midi":42,"duration":0.08,"velocity":0.2900981490164995},{"beat":42,"midi":42,"duration":0.08,"velocity":0.15013547391891482},{"beat":42.5,"midi":42,"duration":0.08,"velocity":0.2782903241148591},{"beat":43,"midi":42,"duration":0.08,"velocity":0.15549137902855878},{"beat":43.5,"midi":42,"duration":0.08,"velocity":0.2657426358997822},{"beat":44,"midi":36,"duration":0.15,"velocity":0.6385968701584264},{"beat":46.5,"midi":36,"duration":0.15,"velocity":0.36781779395164926},{"beat":46,"midi":38,"duration":0.12,"velocity":0.2688600487709046},{"beat":44.5,"midi":42,"duration":0.08,"velocity":0.2920743362617492},{"beat":45,"midi":42,"duration":0.08,"velocity":0.1564018059819937},{"beat":45.5,"midi":42,"duration":0.08,"velocity":0.29019289072751997},{"beat":46,"midi":42,"duration":0.08,"velocity":0.1639803674280644},{"beat":46.5,"midi":42,"duration":0.08,"velocity":0.2896591020476818},{"beat":47,"midi":42,"duration":0.08,"velocity":0.15562188003957275},{"beat":47.5,"midi":42,"duration":0.08,"velocity":0.26665342630863187},{"beat":48,"midi":36,"duration":0.15,"velocity":0.6012453261822462},{"beat":50.5,"midi":36,"duration":0.15,"velocity":0.38347316287420685},{"beat":50,"midi":38,"duration":0.12,"velocity":0.29083676083944743},{"beat":48.5,"midi":42,"duration":0.08,"velocity":0.362990914780274},{"beat":49,"midi":42,"duration":0.08,"velocity":0.20171330443397167},{"beat":49.5,"midi":42,"duration":0.08,"velocity":0.37419263635911043},{"beat":50,"midi":42,"duration":0.08,"velocity":0.19364401854574684},{"beat":50.5,"midi":42,"duration":0.08,"velocity":0.33881614779643715},{"beat":51,"midi":42,"duration":0.08,"velocity":0.20576345479860905},{"beat":51.5,"midi":42,"duration":0.08,"velocity":0.3669487734172493},{"beat":52,"midi":36,"duration":0.15,"velocity":0.6033834156412632},{"beat":54.5,"midi":36,"duration":0.15,"velocity":0.3822028408040293},{"beat":54,"midi":38,"duration":0.12,"velocity":0.28975858010537925},{"beat":52.5,"midi":42,"duration":0.08,"velocity":0.33262176410481337},{"beat":53,"midi":42,"duration":0.08,"velocity":0.18739120012894273},{"beat":53.5,"midi":42,"duration":0.08,"velocity":0.3531498343728483},{"beat":54,"midi":42,"duration":0.08,"velocity":0.18867628381773832},{"beat":54.5,"midi":42,"duration":0.08,"velocity":0.3518502222105861},{"beat":55,"midi":42,"duration":0.08,"velocity":0.18627944037877026},{"beat":55.5,"midi":42,"duration":0.08,"velocity":0.37059383017010983},{"beat":56,"midi":36,"duration":0.15,"velocity":0.5981210666202008},{"beat":58.5,"midi":36,"duration":0.15,"velocity":0.3652888320416212},{"beat":58,"midi":38,"duration":0.12,"velocity":0.2608478527460248},{"beat":56.5,"midi":42,"duration":0.08,"velocity":0.3562542293228209},{"beat":57,"midi":42,"duration":0.08,"velocity":0.2005892051476985},{"beat":57.5,"midi":42,"duration":0.08,"velocity":0.3535288679033518},{"beat":58,"midi":42,"duration":0.08,"velocity":0.195253765989095},{"beat":58.5,"midi":42,"duration":0.08,"velocity":0.373120148422569},{"beat":59,"midi":42,"duration":0.08,"velocity":0.18732341896370056},{"beat":59.5,"midi":42,"duration":0.08,"velocity":0.35690220285505053},{"beat":60,"midi":36,"duration":0.15,"velocity":0.6422965398216621},{"beat":62.5,"midi":36,"duration":0.15,"velocity":0.3682552629672923},{"beat":62,"midi":38,"duration":0.12,"velocity":0.28541103162653747},{"beat":60.5,"midi":42,"duration":0.08,"velocity":0.3713737545859069},{"beat":61,"midi":42,"duration":0.08,"velocity":0.19733027558587493},{"beat":61.5,"midi":42,"duration":0.08,"velocity":0.3499408989116549},{"beat":62,"midi":42,"duration":0.08,"velocity":0.20693535734713078},{"beat":62.5,"midi":42,"duration":0.08,"velocity":0.3483866785850376},{"beat":63,"midi":42,"duration":0.08,"velocity":0.20023711827024818},{"beat":63.5,"midi":42,"duration":0.08,"velocity":0.34467739011459053}],"muted":false,"solo":false,"attack":0.008,"delay":0,"sampleRoot":60,"clips":[]}],"assets":[],"tempos":[{"beat":0,"bpm":100}],"revision":"342d70c49ff80e2a1904012cc72620dd18cb6895f813abec2b44552a989ca57f"}</script><script>!function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var r=e();for(var n in r)("object"==typeof exports?exports:t)[n]=r[n]}}("undefined"!=typeof self?self:this,(function(){return(()=>{var t={507:(t,e,r)=>{"use strict";function n(t){var e=[];return i(t,e),e}function i(t,e){for(var r=0;r<t.length;r++){var n=t[r];Array.isArray(n)?i(n,e):e.push(n)}}r.r(e),r.d(e,{flatten:()=>n})},289:(t,e,r)=>{e.parseMidi=r(666),e.writeMidi=r(865)},666:t=>{function e(t){for(var e,n=new r(t),i=[];!n.eof();){var a=o();i.push(a)}return i;function o(){var t={};t.deltaTime=n.readVarInt();var r=n.readUInt8();if(240==(240&r)){if(255!==r){if(240==r)return t.type="sysEx",a=n.readVarInt(),t.data=n.readBytes(a),t;if(247==r)return t.type="endSysEx",a=n.readVarInt(),t.data=n.readBytes(a),t;throw"Unrecognised MIDI event type byte: "+r}t.meta=!0;var i=n.readUInt8(),a=n.readVarInt();switch(i){case 0:if(t.type="sequenceNumber",2!==a)throw"Expected length for sequenceNumber event is 2, got "+a;return t.number=n.readUInt16(),t;case 1:return t.type="text",t.text=n.readString(a),t;case 2:return t.type="copyrightNotice",t.text=n.readString(a),t;case 3:return t.type="trackName",t.text=n.readString(a),t;case 4:return t.type="instrumentName",t.text=n.readString(a),t;case 5:return t.type="lyrics",t.text=n.readString(a),t;case 6:return t.type="marker",t.text=n.readString(a),t;case 7:return t.type="cuePoint",t.text=n.readString(a),t;case 32:if(t.type="channelPrefix",1!=a)throw"Expected length for channelPrefix event is 1, got "+a;return t.channel=n.readUInt8(),t;case 33:if(t.type="portPrefix",1!=a)throw"Expected length for portPrefix event is 1, got "+a;return t.port=n.readUInt8(),t;case 47:if(t.type="endOfTrack",0!=a)throw"Expected length for endOfTrack event is 0, got "+a;return t;case 81:if(t.type="setTempo",3!=a)throw"Expected length for setTempo event is 3, got "+a;return t.microsecondsPerBeat=n.readUInt24(),t;case 84:if(t.type="smpteOffset",5!=a)throw"Expected length for smpteOffset event is 5, got "+a;var o=n.readUInt8();return t.frameRate={0:24,32:25,64:29,96:30}[96&o],t.hour=31&o,t.min=n.readUInt8(),t.sec=n.readUInt8(),t.frame=n.readUInt8(),t.subFrame=n.readUInt8(),t;case 88:if(t.type="timeSignature",4!=a)throw"Expected length for timeSignature event is 4, got "+a;return t.numerator=n.readUInt8(),t.denominator=1<<n.readUInt8(),t.metronome=n.readUInt8(),t.thirtyseconds=n.readUInt8(),t;case 89:if(t.type="keySignature",2!=a)throw"Expected length for keySignature event is 2, got "+a;return t.key=n.readInt8(),t.scale=n.readUInt8(),t;case 127:return t.type="sequencerSpecific",t.data=n.readBytes(a),t;default:return t.type="unknownMeta",t.data=n.readBytes(a),t.metatypeByte=i,t}}else{var s;if(0==(128&r)){if(null===e)throw"Running status byte encountered before status byte";s=r,r=e,t.running=!0}else s=n.readUInt8(),e=r;var c=r>>4;switch(t.channel=15&r,c){case 8:return t.type="noteOff",t.noteNumber=s,t.velocity=n.readUInt8(),t;case 9:var u=n.readUInt8();return t.type=0===u?"noteOff":"noteOn",t.noteNumber=s,t.velocity=u,0===u&&(t.byte9=!0),t;case 10:return t.type="noteAftertouch",t.noteNumber=s,t.amount=n.readUInt8(),t;case 11:return t.type="controller",t.controllerType=s,t.value=n.readUInt8(),t;case 12:return t.type="programChange",t.programNumber=s,t;case 13:return t.type="channelAftertouch",t.amount=s,t;case 14:return t.type="pitchBend",t.value=s+(n.readUInt8()<<7)-8192,t;default:throw"Unrecognised MIDI event type: "+c}}}}function r(t){this.buffer=t,this.bufferLen=this.buffer.length,this.pos=0}r.prototype.eof=function(){return this.pos>=this.bufferLen},r.prototype.readUInt8=function(){var t=this.buffer[this.pos];return this.pos+=1,t},r.prototype.readInt8=function(){var t=this.readUInt8();return 128&t?t-256:t},r.prototype.readUInt16=function(){return(this.readUInt8()<<8)+this.readUInt8()},r.prototype.readInt16=function(){var t=this.readUInt16();return 32768&t?t-65536:t},r.prototype.readUInt24=function(){return(this.readUInt8()<<16)+(this.readUInt8()<<8)+this.readUInt8()},r.prototype.readInt24=function(){var t=this.readUInt24();return 8388608&t?t-16777216:t},r.prototype.readUInt32=function(){return(this.readUInt8()<<24)+(this.readUInt8()<<16)+(this.readUInt8()<<8)+this.readUInt8()},r.prototype.readBytes=function(t){var e=this.buffer.slice(this.pos,this.pos+t);return this.pos+=t,e},r.prototype.readString=function(t){var e=this.readBytes(t);return String.fromCharCode.apply(null,e)},r.prototype.readVarInt=function(){for(var t=0;!this.eof();){var e=this.readUInt8();if(!(128&e))return t+e;t+=127&e,t<<=7}return t},r.prototype.readChunk=function(){var t=this.readString(4),e=this.readUInt32();return{id:t,length:e,data:this.readBytes(e)}},t.exports=function(t){var n=new r(t),i=n.readChunk();if("MThd"!=i.id)throw"Bad MIDI file. Expected 'MHdr', got: '"+i.id+"'";for(var a=function(t){var e=new r(t),n={format:e.readUInt16(),numTracks:e.readUInt16()},i=e.readUInt16();return 32768&i?(n.framesPerSecond=256-(i>>8),n.ticksPerFrame=255&i):n.ticksPerBeat=i,n}(i.data),o=[],s=0;!n.eof()&&s<a.numTracks;s++){var c=n.readChunk();if("MTrk"!=c.id)throw"Bad MIDI file. Expected 'MTrk', got: '"+c.id+"'";var u=e(c.data);o.push(u)}return{header:a,tracks:o}}},865:t=>{function e(t,e,i){var a,o=new n,s=e.length,c=null;for(a=0;a<s;a++)!1!==i.running&&(i.running||e[a].running)||(c=null),c=r(o,e[a],c,i.useByte9ForNoteOff);t.writeChunk("MTrk",o.buffer)}function r(t,e,r,n){var i=e.type,a=e.deltaTime,o=e.text||"",s=e.data||[],c=null;switch(t.writeVarInt(a),i){case"sequenceNumber":t.writeUInt8(255),t.writeUInt8(0),t.writeVarInt(2),t.writeUInt16(e.number);break;case"text":t.writeUInt8(255),t.writeUInt8(1),t.writeVarInt(o.length),t.writeString(o);break;case"copyrightNotice":t.writeUInt8(255),t.writeUInt8(2),t.writeVarInt(o.length),t.writeString(o);break;case"trackName":t.writeUInt8(255),t.writeUInt8(3),t.writeVarInt(o.length),t.writeString(o);break;case"instrumentName":t.writeUInt8(255),t.writeUInt8(4),t.writeVarInt(o.length),t.writeString(o);break;case"lyrics":t.writeUInt8(255),t.writeUInt8(5),t.writeVarInt(o.length),t.writeString(o);break;case"marker":t.writeUInt8(255),t.writeUInt8(6),t.writeVarInt(o.length),t.writeString(o);break;case"cuePoint":t.writeUInt8(255),t.writeUInt8(7),t.writeVarInt(o.length),t.writeString(o);break;case"channelPrefix":t.writeUInt8(255),t.writeUInt8(32),t.writeVarInt(1),t.writeUInt8(e.channel);break;case"portPrefix":t.writeUInt8(255),t.writeUInt8(33),t.writeVarInt(1),t.writeUInt8(e.port);break;case"endOfTrack":t.writeUInt8(255),t.writeUInt8(47),t.writeVarInt(0);break;case"setTempo":t.writeUInt8(255),t.writeUInt8(81),t.writeVarInt(3),t.writeUInt24(e.microsecondsPerBeat);break;case"smpteOffset":t.writeUInt8(255),t.writeUInt8(84),t.writeVarInt(5);var u=31&e.hour|{24:0,25:32,29:64,30:96}[e.frameRate];t.writeUInt8(u),t.writeUInt8(e.min),t.writeUInt8(e.sec),t.writeUInt8(e.frame),t.writeUInt8(e.subFrame);break;case"timeSignature":t.writeUInt8(255),t.writeUInt8(88),t.writeVarInt(4),t.writeUInt8(e.numerator);var h=255&Math.floor(Math.log(e.denominator)/Math.LN2);t.writeUInt8(h),t.writeUInt8(e.metronome),t.writeUInt8(e.thirtyseconds||8);break;case"keySignature":t.writeUInt8(255),t.writeUInt8(89),t.writeVarInt(2),t.writeInt8(e.key),t.writeUInt8(e.scale);break;case"sequencerSpecific":t.writeUInt8(255),t.writeUInt8(127),t.writeVarInt(s.length),t.writeBytes(s);break;case"unknownMeta":null!=e.metatypeByte&&(t.writeUInt8(255),t.writeUInt8(e.metatypeByte),t.writeVarInt(s.length),t.writeBytes(s));break;case"sysEx":t.writeUInt8(240),t.writeVarInt(s.length),t.writeBytes(s);break;case"endSysEx":t.writeUInt8(247),t.writeVarInt(s.length),t.writeBytes(s);break;case"noteOff":(c=(!1!==n&&e.byte9||n&&0==e.velocity?144:128)|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.noteNumber),t.writeUInt8(e.velocity);break;case"noteOn":(c=144|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.noteNumber),t.writeUInt8(e.velocity);break;case"noteAftertouch":(c=160|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.noteNumber),t.writeUInt8(e.amount);break;case"controller":(c=176|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.controllerType),t.writeUInt8(e.value);break;case"programChange":(c=192|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.programNumber);break;case"channelAftertouch":(c=208|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.amount);break;case"pitchBend":(c=224|e.channel)!==r&&t.writeUInt8(c);var f=8192+e.value,p=127&f,l=f>>7&127;t.writeUInt8(p),t.writeUInt8(l);break;default:throw"Unrecognized event type: "+i}return c}function n(){this.buffer=[]}n.prototype.writeUInt8=function(t){this.buffer.push(255&t)},n.prototype.writeInt8=n.prototype.writeUInt8,n.prototype.writeUInt16=function(t){var e=t>>8&255,r=255&t;this.writeUInt8(e),this.writeUInt8(r)},n.prototype.writeInt16=n.prototype.writeUInt16,n.prototype.writeUInt24=function(t){var e=t>>16&255,r=t>>8&255,n=255&t;this.writeUInt8(e),this.writeUInt8(r),this.writeUInt8(n)},n.prototype.writeInt24=n.prototype.writeUInt24,n.prototype.writeUInt32=function(t){var e=t>>24&255,r=t>>16&255,n=t>>8&255,i=255&t;this.writeUInt8(e),this.writeUInt8(r),this.writeUInt8(n),this.writeUInt8(i)},n.prototype.writeInt32=n.prototype.writeUInt32,n.prototype.writeBytes=function(t){this.buffer=this.buffer.concat(Array.prototype.slice.call(t,0))},n.prototype.writeString=function(t){var e,r=t.length,n=[];for(e=0;e<r;e++)n.push(t.codePointAt(e));this.writeBytes(n)},n.prototype.writeVarInt=function(t){if(t<0)throw"Cannot write negative variable-length integer";if(t<=127)this.writeUInt8(t);else{var e=t,r=[];for(r.push(127&e),e>>=7;e;){var n=127&e|128;r.push(n),e>>=7}this.writeBytes(r.reverse())}},n.prototype.writeChunk=function(t,e){this.writeString(t),this.writeUInt32(e.length),this.writeBytes(e)},t.exports=function(t,r){if("object"!=typeof t)throw"Invalid MIDI data";r=r||{};var i,a=t.header||{},o=t.tracks||[],s=o.length,c=new n;for(function(t,e,r){var i=null==e.format?1:e.format,a=128;e.timeDivision?a=e.timeDivision:e.ticksPerFrame&&e.framesPerSecond?a=-(255&e.framesPerSecond)<<8|255&e.ticksPerFrame:e.ticksPerBeat&&(a=32767&e.ticksPerBeat);var o=new n;o.writeUInt16(i),o.writeUInt16(r),o.writeUInt16(a),t.writeChunk("MThd",o.buffer)}(c,a,s),i=0;i<s;i++)e(c,o[i],r);return c.buffer}},805:(t,e)=>{"use strict";function r(t,e,r){void 0===r&&(r="ticks");var n=0,i=t.length,a=i;if(i>0&&t[i-1][r]<=e)return i-1;for(;n<a;){var o=Math.floor(n+(a-n)/2),s=t[o],c=t[o+1];if(s[r]===e){for(var u=o;u<t.length;u++)t[u][r]===e&&(o=u);return o}if(s[r]<e&&c[r]>e)return o;s[r]>e?a=o:s[r]<e&&(n=o+1)}return-1}Object.defineProperty(e,"__esModule",{value:!0}),e.insert=e.search=void 0,e.search=r,e.insert=function(t,e,n){if(void 0===n&&(n="ticks"),t.length){var i=r(t,e[n],n);t.splice(i+1,0,e)}else t.push(e)}},543:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ControlChange=e.controlChangeIds=e.controlChangeNames=void 0,e.controlChangeNames={1:"modulationWheel",2:"breath",4:"footController",5:"portamentoTime",7:"volume",8:"balance",10:"pan",64:"sustain",65:"portamentoTime",66:"sostenuto",67:"softPedal",68:"legatoFootswitch",84:"portamentoControl"},e.controlChangeIds=Object.keys(e.controlChangeNames).reduce((function(t,r){return t[e.controlChangeNames[r]]=r,t}),{});var r=new WeakMap,n=new WeakMap,i=function(){function t(t,e){r.set(this,e),n.set(this,t.controllerType),this.ticks=t.absoluteTime,this.value=t.value}return Object.defineProperty(t.prototype,"number",{get:function(){return n.get(this)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return e.controlChangeNames[this.number]?e.controlChangeNames[this.number]:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"time",{get:function(){return r.get(this).ticksToSeconds(this.ticks)},set:function(t){var e=r.get(this);this.ticks=e.secondsToTicks(t)},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return{number:this.number,ticks:this.ticks,time:this.time,value:this.value}},t}();e.ControlChange=i},906:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createControlChanges=void 0;var n=r(543);e.createControlChanges=function(){return new Proxy({},{get:function(t,e){return t[e]?t[e]:n.controlChangeIds.hasOwnProperty(e)?t[n.controlChangeIds[e]]:void 0},set:function(t,e,r){return n.controlChangeIds.hasOwnProperty(e)?t[n.controlChangeIds[e]]=r:t[e]=r,!0}})}},54:function(t,e,r){"use strict";var n=this&&this.__spreadArray||function(t,e,r){if(r||2===arguments.length)for(var n,i=0,a=e.length;i<a;i++)!n&&i in e||(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))};Object.defineProperty(e,"__esModule",{value:!0}),e.encode=void 0;var i=r(289),a=r(535),o=r(507);function s(t,e){return{absoluteTime:t.ticks,channel:e,controllerType:t.number,deltaTime:0,type:"controller",value:Math.floor(127*t.value)}}function c(t){return{absoluteTime:0,channel:t.channel,deltaTime:0,programNumber:t.instrument.number,type:"programChange"}}e.encode=function(t){var e={header:{format:1,numTracks:t.tracks.length+1,ticksPerBeat:t.header.ppq},tracks:n([n(n(n(n([{absoluteTime:0,deltaTime:0,meta:!0,text:t.header.name,type:"trackName"}],t.header.keySignatures.map((function(t){return function(t){var e=a.keySignatureKeys.indexOf(t.key);return{absoluteTime:t.ticks,deltaTime:0,key:e+7,meta:!0,scale:"major"===t.scale?0:1,type:"keySignature"}}(t)})),!0),t.header.meta.map((function(t){return{absoluteTime:(e=t).ticks,deltaTime:0,meta:!0,text:e.text,type:e.type};var e})),!0),t.header.tempos.map((function(t){return function(t){return{absoluteTime:t.ticks,deltaTime:0,meta:!0,microsecondsPerBeat:Math.floor(6e7/t.bpm),type:"setTempo"}}(t)})),!0),t.header.timeSignatures.map((function(t){return function(t){return{absoluteTime:t.ticks,deltaTime:0,denominator:t.timeSignature[1],meta:!0,metronome:24,numerator:t.timeSignature[0],thirtyseconds:8,type:"timeSignature"}}(t)})),!0)],t.tracks.map((function(t){return n(n(n([(e=t.name,{absoluteTime:0,deltaTime:0,meta:!0,text:e,type:"trackName"}),c(t)],function(t){return(0,o.flatten)(t.notes.map((function(e){return function(t,e){return[{absoluteTime:t.ticks,channel:e,deltaTime:0,noteNumber:t.midi,type:"noteOn",velocity:Math.floor(127*t.velocity)},{absoluteTime:t.ticks+t.durationTicks,channel:e,deltaTime:0,noteNumber:t.midi,type:"noteOff",velocity:Math.floor(127*t.noteOffVelocity)}]}(e,t.channel)})))}(t),!0),function(t){for(var e=[],r=0;r<127;r++)t.controlChanges.hasOwnProperty(r)&&t.controlChanges[r].forEach((function(r){e.push(s(r,t.channel))}));return e}(t),!0),function(t){var e=[];return t.pitchBends.forEach((function(r){e.push(function(t,e){return{absoluteTime:t.ticks,channel:e,deltaTime:0,type:"pitchBend",value:t.value}}(r,t.channel))})),e}(t),!0);var e})),!0)};return e.tracks=e.tracks.map((function(t){t=t.sort((function(t,e){return t.absoluteTime-e.absoluteTime}));var e=0;return t.forEach((function(t){t.deltaTime=t.absoluteTime-e,e=t.absoluteTime,delete t.absoluteTime})),t.push({deltaTime:0,meta:!0,type:"endOfTrack"}),t})),new Uint8Array((0,i.writeMidi)(e))}},535:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Header=e.keySignatureKeys=void 0;var n=r(805),i=new WeakMap;e.keySignatureKeys=["Cb","Gb","Db","Ab","Eb","Bb","F","C","G","D","A","E","B","F#","C#"];var a=function(){function t(t){var r=this;if(this.tempos=[],this.timeSignatures=[],this.keySignatures=[],this.meta=[],this.name="",i.set(this,480),t){i.set(this,t.header.ticksPerBeat),t.tracks.forEach((function(t){t.forEach((function(t){t.meta&&("timeSignature"===t.type?r.timeSignatures.push({ticks:t.absoluteTime,timeSignature:[t.numerator,t.denominator]}):"setTempo"===t.type?r.tempos.push({bpm:6e7/t.microsecondsPerBeat,ticks:t.absoluteTime}):"keySignature"===t.type&&r.keySignatures.push({key:e.keySignatureKeys[t.key+7],scale:0===t.scale?"major":"minor",ticks:t.absoluteTime}))}))}));var n=0;t.tracks[0].forEach((function(t){n+=t.deltaTime,t.meta&&("trackName"===t.type?r.name=t.text:"text"!==t.type&&"cuePoint"!==t.type&&"marker"!==t.type&&"lyrics"!==t.type||r.meta.push({text:t.text,ticks:n,type:t.type}))})),this.update()}}return t.prototype.update=function(){var t=this,e=0,r=0;this.tempos.sort((function(t,e){return t.ticks-e.ticks})),this.tempos.forEach((function(n,i){var a=i>0?t.tempos[i-1].bpm:t.tempos[0].bpm,o=n.ticks/t.ppq-r,s=60/a*o;n.time=s+e,e=n.time,r+=o})),this.timeSignatures.sort((function(t,e){return t.ticks-e.ticks})),this.timeSignatures.forEach((function(e,r){var n=r>0?t.timeSignatures[r-1]:t.timeSignatures[0],i=(e.ticks-n.ticks)/t.ppq/n.timeSignature[0]/(n.timeSignature[1]/4);n.measures=n.measures||0,e.measures=i+n.measures}))},t.prototype.ticksToSeconds=function(t){var e=(0,n.search)(this.tempos,t);if(-1!==e){var r=this.tempos[e],i=r.time,a=(t-r.ticks)/this.ppq;return i+60/r.bpm*a}return t/this.ppq*.5},t.prototype.ticksToMeasures=function(t){var e=(0,n.search)(this.timeSignatures,t);if(-1!==e){var r=this.timeSignatures[e],i=(t-r.ticks)/this.ppq;return r.measures+i/(r.timeSignature[0]/r.timeSignature[1])/4}return t/this.ppq/4},Object.defineProperty(t.prototype,"ppq",{get:function(){return i.get(this)},enumerable:!1,configurable:!0}),t.prototype.secondsToTicks=function(t){var e=(0,n.search)(this.tempos,t,"time");if(-1!==e){var r=this.tempos[e],i=(t-r.time)/(60/r.bpm);return Math.round(r.ticks+i*this.ppq)}var a=t/.5;return Math.round(a*this.ppq)},t.prototype.toJSON=function(){return{keySignatures:this.keySignatures,meta:this.meta,name:this.name,ppq:this.ppq,tempos:this.tempos.map((function(t){return{bpm:t.bpm,ticks:t.ticks}})),timeSignatures:this.timeSignatures}},t.prototype.fromJSON=function(t){this.name=t.name,this.tempos=t.tempos.map((function(t){return Object.assign({},t)})),this.timeSignatures=t.timeSignatures.map((function(t){return Object.assign({},t)})),this.keySignatures=t.keySignatures.map((function(t){return Object.assign({},t)})),this.meta=t.meta.map((function(t){return Object.assign({},t)})),i.set(this,t.ppq),this.update()},t.prototype.setTempo=function(t){this.tempos=[{bpm:t,ticks:0}],this.update()},t}();e.Header=a},362:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Instrument=void 0;var n=r(438),i=new WeakMap,a=function(){function t(t,e){if(this.number=0,i.set(this,e),this.number=0,t){var r=t.find((function(t){return"programChange"===t.type}));r&&(this.number=r.programNumber)}}return Object.defineProperty(t.prototype,"name",{get:function(){return this.percussion?n.DrumKitByPatchID[this.number]:n.instrumentByPatchID[this.number]},set:function(t){var e=n.instrumentByPatchID.indexOf(t);-1!==e&&(this.number=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"family",{get:function(){return this.percussion?"drums":n.InstrumentFamilyByID[Math.floor(this.number/8)]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"percussion",{get:function(){return 9===i.get(this).channel},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return{family:this.family,number:this.number,name:this.name}},t.prototype.fromJSON=function(t){this.number=t.number},t}();e.Instrument=a},438:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.DrumKitByPatchID=e.InstrumentFamilyByID=e.instrumentByPatchID=void 0,e.instrumentByPatchID=["acoustic grand piano","bright acoustic piano","electric grand piano","honky-tonk piano","electric piano 1","electric piano 2","harpsichord","clavi","celesta","glockenspiel","music box","vibraphone","marimba","xylophone","tubular bells","dulcimer","drawbar organ","percussive organ","rock organ","church organ","reed organ","accordion","harmonica","tango accordion","acoustic guitar (nylon)","acoustic guitar (steel)","electric guitar (jazz)","electric guitar (clean)","electric guitar (muted)","overdriven guitar","distortion guitar","guitar harmonics","acoustic bass","electric bass (finger)","electric bass (pick)","fretless bass","slap bass 1","slap bass 2","synth bass 1","synth bass 2","violin","viola","cello","contrabass","tremolo strings","pizzicato strings","orchestral harp","timpani","string ensemble 1","string ensemble 2","synthstrings 1","synthstrings 2","choir aahs","voice oohs","synth voice","orchestra hit","trumpet","trombone","tuba","muted trumpet","french horn","brass section","synthbrass 1","synthbrass 2","soprano sax","alto sax","tenor sax","baritone sax","oboe","english horn","bassoon","clarinet","piccolo","flute","recorder","pan flute","blown bottle","shakuhachi","whistle","ocarina","lead 1 (square)","lead 2 (sawtooth)","lead 3 (calliope)","lead 4 (chiff)","lead 5 (charang)","lead 6 (voice)","lead 7 (fifths)","lead 8 (bass + lead)","pad 1 (new age)","pad 2 (warm)","pad 3 (polysynth)","pad 4 (choir)","pad 5 (bowed)","pad 6 (metallic)","pad 7 (halo)","pad 8 (sweep)","fx 1 (rain)","fx 2 (soundtrack)","fx 3 (crystal)","fx 4 (atmosphere)","fx 5 (brightness)","fx 6 (goblins)","fx 7 (echoes)","fx 8 (sci-fi)","sitar","banjo","shamisen","koto","kalimba","bag pipe","fiddle","shanai","tinkle bell","agogo","steel drums","woodblock","taiko drum","melodic tom","synth drum","reverse cymbal","guitar fret noise","breath noise","seashore","bird tweet","telephone ring","helicopter","applause","gunshot"],e.InstrumentFamilyByID=["piano","chromatic percussion","organ","guitar","bass","strings","ensemble","brass","reed","pipe","synth lead","synth pad","synth effects","world","percussive","sound effects"],e.DrumKitByPatchID={0:"standard kit",8:"room kit",16:"power kit",24:"electronic kit",25:"tr-808 kit",32:"jazz kit",40:"brush kit",48:"orchestra kit",56:"sound fx kit"}},233:function(t,e,r){"use strict";var n=this&&this.__awaiter||function(t,e,r,n){return new(r||(r=Promise))((function(i,a){function o(t){try{c(n.next(t))}catch(t){a(t)}}function s(t){try{c(n.throw(t))}catch(t){a(t)}}function c(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(o,s)}c((n=n.apply(t,e||[])).next())}))},i=this&&this.__generator||function(t,e){var r,n,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=e.call(t,o)}catch(t){a=[6,t],n=0}finally{r=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}};Object.defineProperty(e,"__esModule",{value:!0}),e.Header=e.Track=e.Midi=void 0;var a=r(289),o=r(535),s=r(334),c=r(54),u=function(){function t(t){var e=this,r=null;if(t){var n=t instanceof ArrayBuffer?new Uint8Array(t):t;(r=(0,a.parseMidi)(n)).tracks.forEach((function(t){var e=0;t.forEach((function(t){e+=t.deltaTime,t.absoluteTime=e}))})),r.tracks=function(t){for(var e=[],r=0;r<t.length;r++)for(var n=e.length,i=new Map,a=Array(16).fill(0),o=0,s=t[r];o<s.length;o++){var c=s[o],u=n,h=c.channel;if(void 0!==h){"programChange"===c.type&&(a[h]=c.programNumber);var f=a[h],p="".concat(f," ").concat(h);i.has(p)?u=i.get(p):(u=n+i.size,i.set(p,u))}e[u]||e.push([]),e[u].push(c)}return e}(r.tracks)}this.header=new o.Header(r),this.tracks=[],t&&(this.tracks=r.tracks.map((function(t){return new s.Track(t,e.header)})),1===r.header.format&&0===this.tracks[0].duration&&this.tracks.shift())}return t.fromUrl=function(e){return n(this,void 0,void 0,(function(){var r;return i(this,(function(n){switch(n.label){case 0:return[4,fetch(e)];case 1:return(r=n.sent()).ok?[4,r.arrayBuffer()]:[3,3];case 2:return[2,new t(n.sent())];case 3:throw new Error("Could not load '".concat(e,"'"))}}))}))},Object.defineProperty(t.prototype,"name",{get:function(){return this.header.name},set:function(t){this.header.name=t},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"duration",{get:function(){var t=this.tracks.map((function(t){return t.duration}));return Math.max.apply(Math,t)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"durationTicks",{get:function(){var t=this.tracks.map((function(t){return t.durationTicks}));return Math.max.apply(Math,t)},enumerable:!1,configurable:!0}),t.prototype.addTrack=function(){var t=new s.Track(void 0,this.header);return this.tracks.push(t),t},t.prototype.toArray=function(){return(0,c.encode)(this)},t.prototype.toJSON=function(){return{header:this.header.toJSON(),tracks:this.tracks.map((function(t){return t.toJSON()}))}},t.prototype.fromJSON=function(t){var e=this;this.header=new o.Header,this.header.fromJSON(t.header),this.tracks=t.tracks.map((function(t){var r=new s.Track(void 0,e.header);return r.fromJSON(t),r}))},t.prototype.clone=function(){var e=new t;return e.fromJSON(this.toJSON()),e},t}();e.Midi=u;var h=r(334);Object.defineProperty(e,"Track",{enumerable:!0,get:function(){return h.Track}});var f=r(535);Object.defineProperty(e,"Header",{enumerable:!0,get:function(){return f.Header}})},518:(t,e)=>{"use strict";function r(t){return["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"][t%12]}Object.defineProperty(e,"__esModule",{value:!0}),e.Note=void 0;var n,i,a=(n=/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,i={cbb:-2,cb:-1,c:0,"c#":1,cx:2,dbb:0,db:1,d:2,"d#":3,dx:4,ebb:2,eb:3,e:4,"e#":5,ex:6,fbb:3,fb:4,f:5,"f#":6,fx:7,gbb:5,gb:6,g:7,"g#":8,gx:9,abb:7,ab:8,a:9,"a#":10,ax:11,bbb:9,bb:10,b:11,"b#":12,bx:13},function(t){var e=n.exec(t),r=e[1],a=e[2];return i[r.toLowerCase()]+12*(parseInt(a,10)+1)}),o=new WeakMap,s=function(){function t(t,e,r){o.set(this,r),this.midi=t.midi,this.velocity=t.velocity,this.noteOffVelocity=e.velocity,this.ticks=t.ticks,this.durationTicks=e.ticks-t.ticks}return Object.defineProperty(t.prototype,"name",{get:function(){return t=this.midi,e=Math.floor(t/12)-1,r(t)+e.toString();var t,e},set:function(t){this.midi=a(t)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"octave",{get:function(){return Math.floor(this.midi/12)-1},set:function(t){var e=t-this.octave;this.midi+=12*e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pitch",{get:function(){return r(this.midi)},set:function(t){this.midi=12*(this.octave+1)+["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"].indexOf(t)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"duration",{get:function(){var t=o.get(this);return t.ticksToSeconds(this.ticks+this.durationTicks)-t.ticksToSeconds(this.ticks)},set:function(t){var e=o.get(this).secondsToTicks(this.time+t);this.durationTicks=e-this.ticks},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"time",{get:function(){return o.get(this).ticksToSeconds(this.ticks)},set:function(t){var e=o.get(this);this.ticks=e.secondsToTicks(t)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bars",{get:function(){return o.get(this).ticksToMeasures(this.ticks)},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return{duration:this.duration,durationTicks:this.durationTicks,midi:this.midi,name:this.name,ticks:this.ticks,time:this.time,velocity:this.velocity}},t}();e.Note=s},882:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PitchBend=void 0;var r=new WeakMap,n=function(){function t(t,e){r.set(this,e),this.ticks=t.absoluteTime,this.value=t.value}return Object.defineProperty(t.prototype,"time",{get:function(){return r.get(this).ticksToSeconds(this.ticks)},set:function(t){var e=r.get(this);this.ticks=e.secondsToTicks(t)},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return{ticks:this.ticks,time:this.time,value:this.value}},t}();e.PitchBend=n},334:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Track=void 0;var n=r(805),i=r(543),a=r(906),o=r(882),s=r(362),c=r(518),u=new WeakMap,h=function(){function t(t,e){var r=this;if(this.name="",this.notes=[],this.controlChanges=(0,a.createControlChanges)(),this.pitchBends=[],u.set(this,e),t){var n=t.find((function(t){return"trackName"===t.type}));this.name=n?n.text:""}if(this.instrument=new s.Instrument(t,this),this.channel=0,t){for(var i=t.filter((function(t){return"noteOn"===t.type})),o=t.filter((function(t){return"noteOff"===t.type})),c=function(){var t=i.shift();h.channel=t.channel;var e=o.findIndex((function(e){return e.noteNumber===t.noteNumber&&e.absoluteTime>=t.absoluteTime}));if(-1!==e){var r=o.splice(e,1)[0];h.addNote({durationTicks:r.absoluteTime-t.absoluteTime,midi:t.noteNumber,noteOffVelocity:r.velocity/127,ticks:t.absoluteTime,velocity:t.velocity/127})}},h=this;i.length;)c();t.filter((function(t){return"controller"===t.type})).forEach((function(t){r.addCC({number:t.controllerType,ticks:t.absoluteTime,value:t.value/127})})),t.filter((function(t){return"pitchBend"===t.type})).forEach((function(t){r.addPitchBend({ticks:t.absoluteTime,value:t.value/Math.pow(2,13)})}));var f=t.find((function(t){return"endOfTrack"===t.type}));this.endOfTrackTicks=void 0!==f?f.absoluteTime:void 0}}return t.prototype.addNote=function(t){var e=u.get(this),r=new c.Note({midi:0,ticks:0,velocity:1},{ticks:0,velocity:0},e);return Object.assign(r,t),(0,n.insert)(this.notes,r,"ticks"),this},t.prototype.addCC=function(t){var e=u.get(this),r=new i.ControlChange({controllerType:t.number},e);return delete t.number,Object.assign(r,t),Array.isArray(this.controlChanges[r.number])||(this.controlChanges[r.number]=[]),(0,n.insert)(this.controlChanges[r.number],r,"ticks"),this},t.prototype.addPitchBend=function(t){var e=u.get(this),r=new o.PitchBend({},e);return Object.assign(r,t),(0,n.insert)(this.pitchBends,r,"ticks"),this},Object.defineProperty(t.prototype,"duration",{get:function(){if(!this.notes.length)return 0;for(var t=this.notes[this.notes.length-1].time+this.notes[this.notes.length-1].duration,e=0;e<this.notes.length-1;e++){var r=this.notes[e].time+this.notes[e].duration;t<r&&(t=r)}return t},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"durationTicks",{get:function(){if(!this.notes.length)return 0;for(var t=this.notes[this.notes.length-1].ticks+this.notes[this.notes.length-1].durationTicks,e=0;e<this.notes.length-1;e++){var r=this.notes[e].ticks+this.notes[e].durationTicks;t<r&&(t=r)}return t},enumerable:!1,configurable:!0}),t.prototype.fromJSON=function(t){var e=this;for(var r in this.name=t.name,this.channel=t.channel,this.instrument=new s.Instrument(void 0,this),this.instrument.fromJSON(t.instrument),void 0!==t.endOfTrackTicks&&(this.endOfTrackTicks=t.endOfTrackTicks),t.controlChanges)t.controlChanges[r]&&t.controlChanges[r].forEach((function(t){e.addCC({number:t.number,ticks:t.ticks,value:t.value})}));t.notes.forEach((function(t){e.addNote({durationTicks:t.durationTicks,midi:t.midi,ticks:t.ticks,velocity:t.velocity})}))},t.prototype.toJSON=function(){for(var t={},e=0;e<127;e++)this.controlChanges.hasOwnProperty(e)&&(t[e]=this.controlChanges[e].map((function(t){return t.toJSON()})));var r={channel:this.channel,controlChanges:t,pitchBends:this.pitchBends.map((function(t){return t.toJSON()})),instrument:this.instrument.toJSON(),name:this.name,notes:this.notes.map((function(t){return t.toJSON()}))};return void 0!==this.endOfTrackTicks&&(r.endOfTrackTicks=this.endOfTrackTicks),r},t}();e.Track=h}},e={};function r(n){var i=e[n];if(void 0!==i)return i.exports;var a=e[n]={exports:{}};return t[n].call(a.exports,a,a.exports,r),a.exports}return r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r(233)})()}));
+</script><script id="afterhours-model">const MUSIC_SPEC = 'afterhours/1';
+const instruments = { felt: 'Felt keys', pluck: 'Plucked strings', pad: 'Analog pad', bass: 'Round bass', bell: 'Glass bells', lead: 'Soft lead', drums: 'Drum kit', sampler: 'Your sample', audio: 'Audio recording' };
+const midiPrograms = { felt: 0, pluck: 24, pad: 89, bass: 33, bell: 11, lead: 80, drums: 0, sampler: 0, audio: 0 };
+const finite = (value, min, max) => Number.isFinite(value) && value >= min && value <= max;
+function validateSession(input) {
+ const p = structuredClone(input);
+ if (!p || p.spec !== MUSIC_SPEC) throw new Error('Open an Afterhours project.');
+ if (typeof p.id !== 'string' || !/^[a-z0-9-]{1,80}$/.test(p.id)) throw new Error('Project needs a stable id.');
+ if (typeof p.title !== 'string' || !p.title.trim() || p.title.length > 160 || typeof p.brief !== 'string' || p.brief.length > 6000) throw new Error('Name the piece and its brief.');
+ p.seed = String(p.seed ?? '1').slice(0, 128);
+ if (!finite(p.tempo, 30, 240)) throw new Error('Tempo must be 30–240 BPM.');
+ p.tempos ??= [{ beat: 0, bpm: p.tempo }];
+ if (!Array.isArray(p.tempos) || !p.tempos.length || p.tempos.length > 200 || p.tempos[0].beat !== 0) throw new Error('Tempo map must begin at beat zero.');
+ for (let i = 0; i < p.tempos.length; i++) if (!finite(p.tempos[i].beat, 0, 4096) || !finite(p.tempos[i].bpm, 30, 240) || i && p.tempos[i].beat <= p.tempos[i - 1].beat) throw new Error('Tempo changes must be ordered and valid.');
+ p.tempo = p.tempos[0].bpm;
+ p.meter ??= [4, 4];
+ if (!Array.isArray(p.meter) || !Number.isInteger(p.meter[0]) || !finite(p.meter[0], 1, 12) || ![2, 4, 8, 16].includes(p.meter[1])) throw new Error('Invalid time signature.');
+ if (!finite(p.beats, 1, 4096) || secondsAt(p, p.beats) > 240) throw new Error('Keep a piece within four minutes; split longer work into movements.');
+ p.master ??= .85; if (!finite(p.master, 0, 1)) throw new Error('Invalid master level.');
+ p.tail ??= 1.5; if (!finite(p.tail, 0, 6)) throw new Error('Use a tail of 0–6 seconds.');
+ p.assets ??= [];
+ const assets = new Set();
+ if (!Array.isArray(p.assets) || p.assets.length > 16) throw new Error('Use at most 16 audio assets.');
+ for (const a of p.assets) {
+ if (typeof a.id !== 'string' || assets.has(a.id) || typeof a.name !== 'string' || a.name.length > 200 || typeof a.data !== 'string' || !/^data:(audio\/[a-z0-9.+-]+|application\/octet-stream);base64,[a-zA-Z0-9+/=]+$/i.test(a.data)) throw new Error('Audio assets must be embedded recordings.');
+ assets.add(a.id);
+ }
+ if (!Array.isArray(p.tracks) || !p.tracks.length || p.tracks.length > 16) throw new Error('Use 1–16 tracks.');
+ const trackIds = new Set(); let noteCount = 0;
+ for (const t of p.tracks) {
+ if (typeof t.id !== 'string' || trackIds.has(t.id) || typeof t.name !== 'string' || t.name.length > 120 || !Object.hasOwn(instruments, t.instrument)) throw new Error('Invalid track.');
+ trackIds.add(t.id);
+ const defaults = { gain: .7, pan: 0, muted: false, solo: false, attack: .008, release: .25, tone: 8000, space: .12, delay: 0, sampleRoot: 60 };
+ for (const [key, value] of Object.entries(defaults)) t[key] ??= value;
+ for (const [key, low, high] of [['gain', 0, 1.5], ['pan', -1, 1], ['attack', .001, 3], ['release', .01, 3], ['tone', 100, 20000], ['space', 0, .8], ['delay', 0, .6], ['sampleRoot', 0, 127]]) if (!finite(t[key], low, high)) throw new Error(`Invalid ${t.name}: ${key}.`);
+ if (typeof t.muted !== 'boolean' || typeof t.solo !== 'boolean') throw new Error('Invalid mute/solo state.');
+ if (t.midiProgram !== undefined && (!Number.isInteger(t.midiProgram) || !finite(t.midiProgram, 0, 127))) throw new Error('Invalid MIDI program.');
+ t.notes ??= []; t.clips ??= [];
+ if (!Array.isArray(t.notes) || !Array.isArray(t.clips) || t.clips.length > 100) throw new Error('Invalid track events.');
+ noteCount += t.notes.length;
+ for (const n of t.notes) if (!finite(n.beat, 0, p.beats) || !finite(n.duration, 1 / 32767, p.beats) || n.beat + n.duration > p.beats + 1e-6 || !Number.isInteger(n.midi) || !finite(n.midi, 0, 127) || !finite(n.velocity, 1 / 127, 1)) throw new Error(`Invalid note in ${t.name}. Use a positive MIDI velocity (at least 1/127); mute the track for silence.`);
+ if (t.instrument === 'audio' && t.notes.length) throw new Error('Choose an instrument to play MIDI notes on this track.');
+ if (t.instrument === 'sampler' && !assets.has(t.sampleId)) throw new Error(`Choose a sample for ${t.name}.`);
+ for (const c of t.clips) {
+ c.gain ??= 1; c.fadeIn ??= .02; c.fadeOut ??= .05;
+ if (!assets.has(c.assetId) || !finite(c.beat, 0, p.beats) || !finite(c.offset, 0, 240) || !finite(c.duration, .01, 240) || !finite(c.gain, 0, 1.5) || !finite(c.fadeIn, 0, c.duration) || !finite(c.fadeOut, 0, c.duration)) throw new Error(`Invalid audio clip in ${t.name}.`);
+ if (secondsAt(p, c.beat) + c.duration > secondsAt(p, p.beats) + .001) throw new Error(`Extend the arrangement to fit ${t.name}'s recording.`);
}
}
- // Fixed soft ceiling, no seed-dependent normalization pumping. Leave headroom for playback.
- let peak = 0,
- energy = 0;
- for (let i = 0; i < samples.length; i++) {
- samples[i] = Math.tanh(samples[i] * 1.25) * 0.9;
- peak = Math.max(peak, Math.abs(samples[i]));
- energy += samples[i] ** 2;
- }
- return {
- samples,
- sampleRate,
- duration,
- peak,
- rms: Math.sqrt(energy / samples.length),
- };
-}
-function wavFile(samples, sampleRate) {
- const out = new ArrayBuffer(44 + samples.length * 2),
- v = new DataView(out);
- const text = (offset, s) => {
- for (let i = 0; i < s.length; i++) v.setUint8(offset + i, s.charCodeAt(i));
- };
- text(0, "RIFF");
- v.setUint32(4, 36 + samples.length * 2, true);
- text(8, "WAVE");
- text(12, "fmt ");
- v.setUint32(16, 16, true);
- v.setUint16(20, 1, true);
- v.setUint16(22, 1, true);
- v.setUint32(24, sampleRate, true);
- v.setUint32(28, sampleRate * 2, true);
- v.setUint16(32, 2, true);
- v.setUint16(34, 16, true);
- text(36, "data");
- v.setUint32(40, samples.length * 2, true);
- samples.forEach((s, i) =>
- v.setInt16(44 + i * 2, Math.round(clamp(s, -1, 1) * 32767), true),
- );
- return out;
-}
-
-</script>
-<script>
-'use strict';
-const $ = (s) => document.querySelector(s);
-const $$ = (s) => [...document.querySelectorAll(s)];
-const params = new URLSearchParams(location.search);
-let seed = (params.get("seed") || "42").slice(0, 128);
-const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
-const parentMessage = (message) => {
- if (parent !== window) parent.postMessage(message, "*");
-};
-function toast(message) {
- $("#toast").textContent = message;
- clearTimeout(toast.timer);
- toast.timer = setTimeout(() => {
- $("#toast").textContent = "";
- }, 3500);
-}
-function saveFile(name, content, type = "application/json") {
- const blob =
- content instanceof Blob ? content : new Blob([content], { type });
- const url = URL.createObjectURL(blob),
- a = document.createElement("a");
- a.href = url;
- a.download = name;
- document.body.append(a);
- a.click();
- a.remove();
- setTimeout(() => URL.revokeObjectURL(url), 30000);
-}
-function canvasPNG(canvas, name) {
- canvas.toBlob((blob) => {
- if (blob) saveFile(name, blob);
- else toast("Image export failed. Please try again.");
+ if (noteCount > 16000) throw new Error('Use at most 16,000 notes per piece.');
+ p.sections ??= [{ name: 'Piece', beat: 0, length: p.beats }];
+ if (!Array.isArray(p.sections) || p.sections.length > 64) throw new Error('Invalid arrangement sections.');
+ for (const s of p.sections) if (typeof s.name !== 'string' || s.name.length > 80 || !finite(s.beat, 0, p.beats) || !finite(s.length, .01, p.beats) || s.beat + s.length > p.beats + 1e-6) throw new Error('Sections must fit inside the piece.');
+ if (JSON.stringify(p).length > 28000000) throw new Error('Keep the project under 28 MB. For long recordings, import an MP3 or a shorter WAV.');
+ return p;
+}
+function beatsPerBar(p) { return p.meter[0] * 4 / p.meter[1]; }
+function secondsAt(p, beat) {
+ const map = p.tempos || [{ beat: 0, bpm: p.tempo }]; let seconds = 0;
+ for (let i = 0; i < map.length && map[i].beat < beat; i++) seconds += (Math.min(beat, map[i + 1]?.beat ?? beat) - map[i].beat) * 60 / map[i].bpm;
+ return seconds;
+}
+function beatAt(p, seconds) {
+ const map = p.tempos || [{ beat: 0, bpm: p.tempo }]; let elapsed = 0;
+ for (let i = 0; i < map.length; i++) {
+ const length = ((map[i + 1]?.beat ?? Infinity) - map[i].beat) * 60 / map[i].bpm;
+ if (elapsed + length >= seconds) return map[i].beat + (seconds - elapsed) * map[i].bpm / 60;
+ elapsed += length;
+ }
+ return 0;
+}
+function noteName(n) { return ['C', 'C♯', 'D', 'D♯', 'E', 'F', 'F♯', 'G', 'G♯', 'A', 'A♯', 'B'][n % 12] + (Math.floor(n / 12) - 1); }
+function noteNumber(name) {
+ if (typeof name === 'number') return name;
+ const m = /^([A-Ga-g])([#b♯♭]?)(-?\d+)$/.exec(name.trim());
+ if (!m) throw new Error('Use a pitch such as C4, F#3 or Bb5.');
+ return (Number(m[3]) + 1) * 12 + ({ C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 })[m[1].toUpperCase()] + (['#', '♯'].includes(m[2]) ? 1 : ['b', '♭'].includes(m[2]) ? -1 : 0);
+}
+function musicRandom(seed) {
+ let n = 2166136261; for (const c of String(seed)) n = Math.imul(n ^ c.charCodeAt(0), 16777619);
+ return () => { n += 0x6d2b79f5; let t = Math.imul(n ^ n >>> 15, n | 1); t ^= t + Math.imul(t ^ t >>> 7, t | 61); return ((t ^ t >>> 14) >>> 0) / 4294967296; };
+}
+function activeTracks(p) { const solo = p.tracks.some(t => t.solo); return p.tracks.filter(t => !t.muted && (!solo || t.solo)); }
+function duplicateSection(p, start, length) {
+ if (!finite(start, 0, p.beats) || !finite(length, .25, p.beats) || start + length > p.beats) throw new Error('Select a section within the piece.');
+ const next = structuredClone(p), destination = p.beats;
+ for (const t of next.tracks) {
+ const notes = t.notes.filter(n => n.beat >= start && n.beat < start + length).map(n => ({ ...n, beat: n.beat - start + destination, duration: Math.min(n.duration, start + length - n.beat) }));
+ const clips = t.clips.filter(c => c.beat >= start && c.beat < start + length).map(c => ({ ...c, beat: c.beat - start + destination, duration: Math.min(c.duration, secondsAt(p, start + length) - secondsAt(p, c.beat)) }));
+ t.notes.push(...notes); t.clips.push(...clips);
+ }
+ next.beats += length;
+ const initial = p.tempos.filter(t => t.beat <= start).at(-1).bpm;
+ if (next.tempos.at(-1).bpm !== initial) next.tempos.push({ beat: destination, bpm: initial });
+ next.tempos.push(...p.tempos.filter(t => t.beat > start && t.beat < start + length).map(t => ({ beat: destination + t.beat - start, bpm: t.bpm })));
+ next.sections.push({ name: 'New section', beat: destination, length });
+ return validateSession(next);
+}
+function writeSessionMidi(p, MidiClass) {
+ if (p.tracks.filter(t => t.notes.length && t.instrument !== 'drums').length > 15) throw new Error('MIDI has 15 melodic channels plus drums. Combine a melodic track or export WAV stems.');
+ const midi = new MidiClass(); midi.header.name = p.title;
+ midi.header.tempos = p.tempos.map(t => ({ ticks: Math.round(t.beat * midi.header.ppq), bpm: t.bpm }));
+ // Standard markers preserve section cues and intentional silence at the end.
+ // The encoder otherwise ends the file at the final note-off.
+ midi.header.meta = [...p.sections.map(s => ({ ticks: Math.round(s.beat * midi.header.ppq), type: 'marker', text: s.name })), { ticks: Math.round(p.beats * midi.header.ppq), type: 'marker', text: 'Afterhours: end' }];
+ midi.header.timeSignatures = [{ ticks: 0, timeSignature: p.meter }]; midi.header.update();
+ let channel = 0;
+ for (const t of p.tracks.filter(t => t.notes.length)) {
+ const track = midi.addTrack(); track.name = t.name;
+ if (channel === 9) channel++;
+ track.channel = t.instrument === 'drums' ? 9 : channel++ % 16;
+ track.instrument.number = t.midiProgram ?? midiPrograms[t.instrument];
+ track.addCC({ number: 7, ticks: 0, value: Math.min(1, t.gain) }); track.addCC({ number: 10, ticks: 0, value: (t.pan + 1) / 2 });
+ for (const n of t.notes) track.addNote({ midi: n.midi, ticks: Math.round(n.beat * midi.header.ppq), durationTicks: Math.max(1, Math.round(n.duration * midi.header.ppq)), velocity: n.velocity });
+ }
+ return midi.toArray();
+}
+function readSessionMidi(bytes, MidiClass) {
+ const midi = new MidiClass(bytes), warnings = [], ppq = midi.header.ppq;
+ const source = midi.tracks.filter(t => t.notes.length);
+ if (!source.length) throw new Error('That MIDI file contains no notes.');
+ if (midi.header.timeSignatures.length > 1) throw new Error('This studio supports one time signature per piece. Split meter changes into movements before importing.');
+ const tempos = midi.header.tempos.map(t => ({ beat: t.ticks / ppq, bpm: t.bpm }));
+ if (!tempos.length || tempos[0].beat !== 0) tempos.unshift({ beat: 0, bpm: 120 });
+ const meter = midi.header.timeSignatures[0]?.timeSignature || [4, 4], bar = meter[0] * 4 / meter[1];
+ const tracks = source.map((t, i) => {
+ if (Object.entries(t.controlChanges).some(([key, events]) => events?.some(e => !['7', '10'].includes(key) || e.ticks !== 0)) || t.pitchBends.length) warnings.push(`${t.name || 'Track ' + (i + 1)}: MIDI automation and pitch bends are not imported. Render audio in the source application if they are essential.`);
+ const program = t.instrument.number;
+ const instrument = t.instrument.percussion ? 'drums' : program >= 32 && program <= 39 ? 'bass' : program >= 24 && program <= 31 ? 'pluck' : program >= 88 && program <= 95 ? 'pad' : program >= 8 && program <= 15 ? 'bell' : 'felt';
+ return { id: 'midi-' + i, name: (t.name || t.instrument.name || 'Track ' + (i + 1)).slice(0, 120), instrument, midiProgram: program, gain: t.controlChanges[7]?.find(e => e.ticks === 0)?.value ?? .7, pan: (t.controlChanges[10]?.find(e => e.ticks === 0)?.value ?? .5) * 2 - 1, notes: t.notes.map(n => ({ beat: n.ticks / ppq, duration: Math.max(1, n.durationTicks) / ppq, midi: n.midi, velocity: n.velocity })) };
});
-}
-function setSeed(value) {
- seed = String(value).trim().slice(0, 128) || "42";
- $("#seed").value = seed;
- const url = new URL(location.href);
- url.searchParams.set("seed", seed);
- try {
- history.replaceState(null, "", url);
- } catch {
- /* Opaque-origin iframe: the shell owns its URL. */
+ const lastTick = Math.max(0, ...midi.header.meta.map(m => m.ticks), ...midi.tracks.map(t => t.endOfTrackTicks || 0));
+ const beats = Math.ceil(Math.max(lastTick / ppq, ...tracks.flatMap(t => t.notes.map(n => n.beat + n.duration))) / bar) * bar;
+ return validateSession({ spec: MUSIC_SPEC, id: 'imported-midi', title: (midi.name || 'Your composition').slice(0, 160), brief: 'Your MIDI notes and tempo map, ready to arrange and produce. Synthesized instruments are a preview; export MIDI or stems to continue in your DAW.', seed: 'midi', tempo: tempos[0].bpm, tempos, meter, beats, tracks, importWarnings: warnings });
+}
+function wavBytes(channels, sampleRate, gain = 1) {
+ const frames = channels[0].length, count = channels.length;
+ const bytes = new ArrayBuffer(44 + frames * count * 2), view = new DataView(bytes);
+ const text = (at, s) => [...s].forEach((c, i) => view.setUint8(at + i, c.charCodeAt(0)));
+ text(0, 'RIFF'); view.setUint32(4, bytes.byteLength - 8, true); text(8, 'WAVE'); text(12, 'fmt '); view.setUint32(16, 16, true);
+ view.setUint16(20, 1, true); view.setUint16(22, count, true); view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * count * 2, true); view.setUint16(32, count * 2, true); view.setUint16(34, 16, true); text(36, 'data'); view.setUint32(40, frames * count * 2, true);
+ for (let i = 0; i < frames; i++) for (let c = 0; c < count; c++) view.setInt16(44 + (i * count + c) * 2, Math.round(Math.max(-1, Math.min(1, channels[c][i] * gain)) * 32767), true);
+ return bytes;
+}
+</script><script>const decoded = new Map();
+async function audioAssets(project, context) {
+ const result = new Map();
+ for (const asset of project.assets) {
+ let buffer = decoded.get(asset.data);
+ if (!buffer) {
+ const binary = atob(asset.data.split(',')[1]), bytes = Uint8Array.from(binary, c => c.charCodeAt(0));
+ try { buffer = await context.decodeAudioData(bytes.buffer); }
+ catch { throw new Error(`Cannot decode ${asset.name}. Use a WAV or MP3 recording.`); }
+ if (buffer.duration > 240) throw new Error(`${asset.name} is longer than four minutes. Trim it before importing.`);
+ if (decoded.size >= 16) decoded.delete(decoded.keys().next().value);
+ decoded.set(asset.data, buffer);
+ }
+ result.set(asset.id, buffer);
+ }
+ return result;
+}
+function noiseBuffer(context, seed, seconds) {
+ const buffer = context.createBuffer(1, Math.ceil(context.sampleRate * seconds), context.sampleRate), data = buffer.getChannelData(0), r = musicRandom(seed);
+ for (let i = 0; i < data.length; i++) data[i] = r() * 2 - 1;
+ return buffer;
+}
+function impulse(context, seed) {
+ const length = Math.round(context.sampleRate * 1.4), buffer = context.createBuffer(2, length, context.sampleRate), r = musicRandom(seed);
+ for (let channel = 0; channel < 2; channel++) { const data = buffer.getChannelData(channel); for (let i = 0; i < length; i++) data[i] = (r() * 2 - 1) * Math.exp(-i / length * 8) * .65; }
+ return buffer;
+}
+function trackBus(context, track, seed) {
+ const filter = context.createBiquadFilter(); filter.type = 'lowpass'; filter.frequency.value = track.tone; filter.Q.value = .45;
+ const volume = context.createGain(); volume.gain.value = track.gain;
+ const pan = context.createStereoPanner(); pan.pan.value = track.pan;
+ filter.connect(volume); volume.connect(pan); pan.connect(context.destination);
+ if (track.space > 0) {
+ const reverb = context.createConvolver(), send = context.createGain(); reverb.buffer = impulse(context, seed + ':room'); send.gain.value = track.space;
+ volume.connect(send); send.connect(reverb); reverb.connect(pan);
+ }
+ if (track.delay > 0) {
+ const delay = context.createDelay(2), feedback = context.createGain(), send = context.createGain();
+ delay.delayTime.value = .31; feedback.gain.value = .28; send.gain.value = track.delay;
+ volume.connect(send); send.connect(delay); delay.connect(feedback); feedback.connect(delay); delay.connect(pan);
+ }
+ return filter;
+}
+function envelope(context, target, time, duration, velocity, attack, release, sustained = false) {
+ const gain = context.createGain(), level = Math.max(.00001, velocity * .32), hold = Math.max(time + attack + .002, time + duration);
+ gain.gain.setValueAtTime(.00001, time);
+ gain.gain.exponentialRampToValueAtTime(level, time + attack);
+ if (sustained) gain.gain.linearRampToValueAtTime(level * .75, hold);
+ else gain.gain.exponentialRampToValueAtTime(Math.max(.00001, level * .24), hold);
+ gain.gain.exponentialRampToValueAtTime(.00001, hold + release);
+ gain.connect(target); return { gain, end: hold + release + .01 };
+}
+function synthNote(context, target, track, note, time, duration, seed, assets) {
+ const f = 440 * 2 ** ((note.midi - 69) / 12), kind = track.instrument, key = `${seed}:${note.beat}:${note.midi}`;
+ if (note.velocity <= 0) return;
+ if (kind === 'drums') {
+ const gain = context.createGain(); gain.connect(target);
+ if ([35, 36].includes(note.midi)) {
+ const osc = context.createOscillator(); osc.frequency.setValueAtTime(150, time); osc.frequency.exponentialRampToValueAtTime(44, time + .16);
+ gain.gain.setValueAtTime(.00001, time); gain.gain.exponentialRampToValueAtTime(note.velocity * .8, time + .003); gain.gain.exponentialRampToValueAtTime(.00001, time + .36);
+ osc.connect(gain); osc.start(time); osc.stop(time + .37);
+ } else {
+ const hat = [42, 44, 46, 49, 51].includes(note.midi), length = note.midi === 46 ? .36 : hat ? .10 : .23;
+ const source = context.createBufferSource(), filter = context.createBiquadFilter();
+ source.buffer = noiseBuffer(context, key, length); filter.type = hat ? 'highpass' : 'bandpass'; filter.frequency.value = hat ? 7000 : 1700; filter.Q.value = hat ? .4 : .8;
+ source.connect(filter); filter.connect(gain);
+ gain.gain.setValueAtTime(Math.max(.00001, note.velocity * (hat ? .23 : .63)), time); gain.gain.exponentialRampToValueAtTime(.00001, time + length);
+ source.start(time); source.stop(time + length);
+ if (!hat) { const body = context.createOscillator(); body.type = 'triangle'; body.frequency.value = 185; const bodyGain = context.createGain(); bodyGain.gain.setValueAtTime(note.velocity * .13, time); bodyGain.gain.exponentialRampToValueAtTime(.00001, time + .14); body.connect(bodyGain); bodyGain.connect(target); body.start(time); body.stop(time + .15); }
+ }
+ return;
}
- parentMessage({ type: "harness:state", seed });
- dispatchEvent(new CustomEvent("seedchange", { detail: seed }));
-}
-$("#seed").value = seed;
-$("#seed-form").addEventListener("submit", (e) => {
- e.preventDefault();
- setSeed($("#seed").value);
-});
-$("#next-seed").addEventListener("click", () =>
- setSeed(/^\d{1,9}$/.test(seed) ? Number(seed) + 1 : hash(seed)),
-);
-function fitCanvas(canvas, draw, maxDpr = 2) {
- const observer = new ResizeObserver(() => {
- const box = canvas.getBoundingClientRect(),
- dpr = Math.min(devicePixelRatio || 1, maxDpr);
- canvas.width = Math.max(1, Math.round(box.width * dpr));
- canvas.height = Math.max(1, Math.round(box.height * dpr));
- draw?.();
- });
- observer.observe(canvas);
- return observer;
-}
-const editable = (target) =>
- target instanceof Element &&
- !!target.closest("input,textarea,select,[contenteditable=true]");
-addEventListener("error", (e) =>
- parentMessage({ type: "harness:error", message: e.message }),
-);
-addEventListener("unhandledrejection", (e) =>
- parentMessage({
- type: "harness:error",
- message: String(e.reason?.message || e.reason),
- }),
-);
-function ready() {
- document.body.dataset.ready = "true";
- parentMessage({ type: "harness:ready", title: document.title, seed });
-}
-
-let score,
- patterns,
- rendered,
- audioContext,
- source,
- master,
- started = 0,
- offset = 0,
- playing = false,
- muted = [false, false, false, false, false],
- levels = [0.85, 0.5, 0.32, 0.6, 0.5];
-const clockText = (s) =>
- `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`;
-const musicOptions = () => ({
- tempo: +$("#tempo").value,
- swing: +$("#swing").value,
- patterns,
- muted,
- levels,
-});
-function stopMusic(reset = true) {
- if (source) {
- source.onended = null;
- source.stop();
- source = null;
+ const env = envelope(context, target, time, duration, note.velocity, kind === 'pad' ? Math.max(.12, track.attack) : track.attack, track.release, kind === 'pad' || kind === 'lead');
+ if (kind === 'sampler') {
+ const source = context.createBufferSource(); source.buffer = assets.get(track.sampleId); source.playbackRate.value = 2 ** ((note.midi - track.sampleRoot) / 12); source.connect(env.gain); source.start(time); source.stop(env.end); return;
+ }
+ if (kind === 'pluck') {
+ const length = Math.ceil((duration + track.release + .02) * context.sampleRate), buffer = context.createBuffer(1, length, context.sampleRate), out = buffer.getChannelData(0);
+ const size = Math.max(2, Math.round(context.sampleRate / f)), line = new Float32Array(size), r = musicRandom(key);
+ for (let i = 0; i < size; i++) line[i] = r() * 2 - 1;
+ for (let i = 0; i < length; i++) { const pos = i % size, next = (pos + 1) % size; out[i] = line[pos]; line[pos] = (line[pos] + line[next]) * .4988; }
+ const source = context.createBufferSource(); source.buffer = buffer; source.connect(env.gain); source.start(time); source.stop(env.end); return;
+ }
+ const osc = context.createOscillator(); osc.frequency.value = f;
+ if (kind === 'felt' || kind === 'bell') {
+ const harmonics = kind === 'felt' ? [0, 1, .25, .1, .04, .008] : [0, 1, .01, .38, .04, .16, .04];
+ osc.setPeriodicWave(context.createPeriodicWave(new Float32Array(harmonics.length), new Float32Array(harmonics)));
+ } else osc.type = kind === 'pad' ? 'sawtooth' : kind === 'bass' ? 'triangle' : 'sine';
+ osc.connect(env.gain); osc.start(time); osc.stop(env.end);
+ if (kind === 'pad' || kind === 'bass') {
+ const second = context.createOscillator(), mix = context.createGain(); second.type = 'sine'; second.frequency.value = kind === 'bass' ? f / 2 : f; second.detune.value = kind === 'pad' ? 7 : 0; mix.gain.value = .32; second.connect(mix); mix.connect(env.gain); second.start(time); second.stop(env.end);
+ }
+}
+async function renderSession(project, { onlyTrack, sampleRate = 48000 } = {}) {
+ const duration = secondsAt(project, project.beats) + (project.tail ?? 1.5), context = new OfflineAudioContext(2, Math.ceil(duration * sampleRate), sampleRate);
+ const assets = await audioAssets(project, context);
+ const tracks = onlyTrack ? project.tracks.filter(t => t.id === onlyTrack) : activeTracks(project);
+ for (const track of tracks) {
+ const seed = project.seed + ':' + track.id, bus = trackBus(context, track, seed);
+ for (const note of track.notes) {
+ const time = secondsAt(project, note.beat), length = secondsAt(project, note.beat + note.duration) - time;
+ synthNote(context, bus, track, note, time, length, seed, assets);
+ }
+ for (const clip of track.clips) {
+ const buffer = assets.get(clip.assetId), start = secondsAt(project, clip.beat);
+ if (clip.offset + clip.duration > buffer.duration + .03) throw new Error(`${track.name}: the clip extends beyond its recording.`);
+ const source = context.createBufferSource(), gain = context.createGain(); source.buffer = buffer;
+ const fadeIn = Math.min(clip.fadeIn, clip.duration / 2), fadeOut = Math.min(clip.fadeOut, clip.duration / 2), level = clip.gain;
+ gain.gain.setValueAtTime(fadeIn ? 0 : level, start); if (fadeIn) gain.gain.linearRampToValueAtTime(level, start + fadeIn);
+ gain.gain.setValueAtTime(level, start + clip.duration - fadeOut); if (fadeOut) gain.gain.linearRampToValueAtTime(0, start + clip.duration);
+ source.connect(gain); gain.connect(bus); source.start(start, clip.offset, clip.duration);
+ }
}
- if (playing && audioContext) offset = audioContext.currentTime - started;
- playing = false;
- if (reset) offset = 0;
- $("#play").textContent = "▶ Play";
- drawWave();
-}
-function rebuildMusic() {
- stopMusic();
- rendered = renderMusic(score, musicOptions());
- $("#tempo-value").value = `${$("#tempo").value} BPM`;
- $("#swing-value").value = `${$("#swing").value}%`;
- $("#time").textContent = `0:00 / ${clockText(rendered.duration)}`;
- $("#peak").textContent =
- `PEAK ${rendered.peak ? (20 * Math.log10(rendered.peak)).toFixed(1) : "−∞"} dBFS`;
- $("#audio-status").textContent =
- "Your score is ready. Press Play to hear it.";
- drawWave();
+ const buffer = await context.startRendering(), channels = [buffer.getChannelData(0), buffer.getChannelData(1)];
+ let peak = 0, energy = 0;
+ for (const data of channels) for (let i = 0; i < data.length; i++) {
+ // The same linear ending fade is applied to each stem and the mix.
+ data[i] *= Math.min(1, (data.length - 1 - i) / (sampleRate * .015));
+ peak = Math.max(peak, Math.abs(data[i])); energy += data[i] ** 2;
+ }
+ const gain = project.master * Math.min(1, .95 / Math.max(peak, .000001));
+ return { buffer, channels, sampleRate, duration: buffer.duration, rawPeak: peak, gain, peak: peak * gain, rms: Math.sqrt(energy / (buffer.length * 2)) * gain };
+}
+</script><script>function filename(name) { return String(name).normalize('NFKD').replace(/[^a-zA-Z0-9_.-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 100) || 'artwork'; }
+// ZIP STORE: portable editable delivery without a runtime dependency or a cloud service.
+function zipFiles(files) {
+ const enc = new TextEncoder(), chunks = [], central = []; let offset = 0;
+ for (const [name, body] of files) {
+ const path = enc.encode(name), bytes = typeof body === 'string' ? enc.encode(body) : new Uint8Array(body);
+ let crc = 0xffffffff;
+ for (const b of bytes) { crc ^= b; for (let i = 0; i < 8; i++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); }
+ crc = (crc ^ 0xffffffff) >>> 0;
+ const header = new Uint8Array(30 + path.length), v = new DataView(header.buffer);
+ v.setUint32(0, 0x04034b50, true); v.setUint16(4, 20, true); v.setUint16(6, 0x800, true); v.setUint16(12, 33, true);
+ v.setUint32(14, crc, true); v.setUint32(18, bytes.length, true); v.setUint32(22, bytes.length, true); v.setUint16(26, path.length, true); header.set(path, 30);
+ const row = new Uint8Array(46 + path.length), c = new DataView(row.buffer);
+ c.setUint32(0, 0x02014b50, true); c.setUint16(4, 20, true); c.setUint16(6, 20, true); c.setUint16(8, 0x800, true); c.setUint16(14, 33, true);
+ c.setUint32(16, crc, true); c.setUint32(20, bytes.length, true); c.setUint32(24, bytes.length, true); c.setUint16(28, path.length, true); c.setUint32(42, offset, true); row.set(path, 46);
+ chunks.push(header, bytes); central.push(row); offset += header.length + bytes.length;
+ }
+ const length = central.reduce((n, row) => n + row.length, 0), end = new Uint8Array(22), e = new DataView(end.buffer);
+ e.setUint32(0, 0x06054b50, true); e.setUint16(8, files.length, true); e.setUint16(10, files.length, true); e.setUint32(12, length, true); e.setUint32(16, offset, true);
+ return new Blob([...chunks, ...central, end], { type: 'application/zip' });
+}
+</script><script>const $ = selector => document.querySelector(selector), colors = ['#eabe90', '#b9acf1', '#8bc9ba', '#98bce8', '#dc9caa', '#cad990'];
+const original = validateSession(JSON.parse($('#afterhours-data').textContent)), storageKey = 'afterhours:' + original.id;
+let project = structuredClone(original), selectedTrack = 0, selectedNote = -1, selectedClip = 0, windowBar = 0, undoStack = [], redoStack = [], pendingDraft, preserveDraft = false;
+let mix, mixRevision = -1, revision = 0, renderPromise, renderTimer, playback, audioContext, startedAt = 0, seekSeconds = 0, toastTimer, noteRects = [], pianoBounds;
+const state = () => ({ project: structuredClone(project), selectedTrack, windowBar });
+const track = () => project.tracks[selectedTrack];
+const duration = () => secondsAt(project, project.beats) + (project.tail ?? 1.5);
+const clock = value => { const seconds = Math.floor(Math.max(0, value) + .001); return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; };
+function toast(message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 6000); }
+function parentMessage(type, extra = {}) { if (parent !== window) parent.postMessage({ type, ...extra }, '*'); }
+function persist() {
+ if (preserveDraft) return;
+ try { localStorage.setItem(storageKey, JSON.stringify({ baseRevision: original.revision, ...state() })); $('#draft-status').textContent = 'Draft saved on this device'; }
+ catch { $('#draft-status').textContent = 'Save project to keep your recordings'; }
+}
+function stop() { if (playback) { playback.onended = null; playback.stop(); playback.disconnect(); playback = null; } $('#play').textContent = '▶ Play'; $('#play').setAttribute('aria-label', 'Play'); }
+function change(mutate, { rebuild = true } = {}) {
+ const previous = state();
+ try { mutate(); project = validateSession(project); }
+ catch (error) { project = previous.project; selectedTrack = previous.selectedTrack; toast(error.message); buildUI(); return; }
+ undoStack.push(previous); if (undoStack.length > 16) undoStack.shift(); redoStack = [];
+ stop(); revision++; mixRevision = -1; selectedNote = Math.min(selectedNote, track().notes.length - 1);
+ if (rebuild) buildUI(); else updateLabels(); persist(); scheduleMix();
+}
+function restore(saved) { stop(); project = validateSession(saved.project); selectedTrack = Math.min(saved.selectedTrack || 0, project.tracks.length - 1); windowBar = saved.windowBar || 0; selectedNote = -1; revision++; mixRevision = -1; buildUI(); persist(); scheduleMix(); }
+function saveFile(name, content, type = 'application/octet-stream') { const blob = content instanceof Blob ? content : new Blob([content], { type }), url = URL.createObjectURL(blob), a = document.createElement('a'); a.href = url; a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(url), 30000); }
+function canvasContext(canvas) {
+ const box = canvas.getBoundingClientRect(), ratio = Math.min(devicePixelRatio || 1, 2), w = Math.max(1, Math.round(box.width)), h = Math.max(1, Math.round(box.height));
+ if (canvas.width !== Math.round(w * ratio) || canvas.height !== Math.round(h * ratio)) { canvas.width = Math.round(w * ratio); canvas.height = Math.round(h * ratio); }
+ const ctx = canvas.getContext('2d'); ctx.setTransform(ratio, 0, 0, ratio, 0, 0); ctx.clearRect(0, 0, w, h); return { ctx, w, h };
+}
+function updateLabels() {
+ $('#title').textContent = project.title; document.title = project.title + ' · Afterhours'; $('#brief').textContent = project.brief;
+ $('#tempo').value = Number(project.tempo.toFixed(3)); $('#bars').value = Math.ceil(project.beats / beatsPerBar(project)); $('#meter').textContent = project.meter.join(' / ');
+ $('#gain-label').value = `${Math.round(track().gain * 100)}%`; $('#pan-label').value = track().pan === 0 ? 'Center' : `${Math.round(Math.abs(track().pan) * 100)}% ${track().pan < 0 ? 'left' : 'right'}`;
+ $('#undo').disabled = !undoStack.length; $('#redo').disabled = !redoStack.length;
+ $('#mute').setAttribute('aria-pressed', track().muted); $('#solo').setAttribute('aria-pressed', track().solo);
+}
+function buildUI() {
+ selectedTrack = Math.min(selectedTrack, project.tracks.length - 1);
+ windowBar = Math.max(0, Math.min(windowBar, Math.max(0, Math.ceil(project.beats / beatsPerBar(project)) - 1)));
+ updateLabels();
+ $('#tracks').replaceChildren(); $('#sections').replaceChildren();
+ project.sections.forEach((s, i) => { const div = document.createElement('div'); div.className = 'section'; div.textContent = s.name; div.style.left = `${s.beat / project.beats * 100}%`; div.style.width = `${s.length / project.beats * 100}%`; div.style.color = colors[i % colors.length]; $('#sections').append(div); });
+ project.tracks.forEach((t, i) => {
+ const row = document.createElement('div'), info = document.createElement('div'), name = document.createElement('button'), mute = document.createElement('button'), solo = document.createElement('button'), canvas = document.createElement('canvas');
+ row.className = 'track' + (selectedTrack === i ? ' selected' : ''); info.className = 'track-info'; name.className = 'track-name'; name.textContent = t.name; name.title = t.name; name.style.color = colors[i % colors.length];
+ name.onclick = () => { selectedTrack = i; selectedNote = -1; selectedClip = 0; buildUI(); };
+ mute.className = solo.className = 'mini'; mute.textContent = 'M'; solo.textContent = 'S'; mute.setAttribute('aria-label', `Mute ${t.name}`); solo.setAttribute('aria-label', `Solo ${t.name}`); mute.setAttribute('aria-pressed', t.muted); solo.setAttribute('aria-pressed', t.solo);
+ mute.onclick = () => change(() => { t.muted = !t.muted; }); solo.onclick = () => change(() => { t.solo = !t.solo; });
+ canvas.dataset.track = i; canvas.setAttribute('aria-label', t.name + ' arrangement'); canvas.onclick = event => { selectedTrack = i; selectedNote = -1; const box = canvas.getBoundingClientRect(); seekSeconds = secondsAt(project, Math.max(0, Math.min(project.beats, (event.clientX - box.left) / box.width * project.beats))); stop(); buildUI(); };
+ info.append(name, mute, solo); row.append(info, canvas); $('#tracks').append(row);
+ });
+ $('#track-name').value = track().name;
+ $('#instrument').replaceChildren();
+ for (const [key, label] of Object.entries(instruments)) { if (key === 'sampler' && !project.assets.length || key === 'audio' && track().instrument !== 'audio') continue; const option = document.createElement('option'); option.value = key; option.textContent = label; $('#instrument').append(option); }
+ $('#instrument').value = track().instrument;
+ for (const name of ['gain', 'pan', 'attack', 'release', 'tone', 'space', 'delay']) $('#' + name).value = track()[name];
+ $('#master').value = project.master; $('#sampler-controls').hidden = track().instrument !== 'sampler'; $('#sample-id').replaceChildren();
+ for (const asset of project.assets) { const option = document.createElement('option'); option.value = asset.id; option.textContent = asset.name; $('#sample-id').append(option); }
+ $('#sample-id').value = track().sampleId || project.assets[0]?.id || ''; $('#sample-root').value = noteName(track().sampleRoot);
+ $('#clip-controls').hidden = !track().clips.length;
+ selectedClip = Math.max(0, Math.min(selectedClip, track().clips.length - 1)); $('#clip-select').replaceChildren();
+ track().clips.forEach((c, i) => { const option = document.createElement('option'); option.value = i; option.textContent = `${i + 1}. ${project.assets.find(a => a.id === c.assetId)?.name || 'Recording'} · beat ${c.beat}`; $('#clip-select').append(option); });
+ $('#clip-select').value = selectedClip;
+ if (track().clips[selectedClip]) for (const [id, key] of [['clip-beat', 'beat'], ['clip-offset', 'offset'], ['clip-duration', 'duration']]) $('#' + id).value = track().clips[selectedClip][key];
+ $('#remove-track').disabled = project.tracks.length === 1;
+ updateNote(); requestAnimationFrame(drawAll);
+}
+function drawArrangement() {
+ const beat = beatAt(project, playback ? Math.max(0, audioContext.currentTime - startedAt) : seekSeconds);
+ for (const canvas of document.querySelectorAll('#tracks canvas')) {
+ const i = Number(canvas.dataset.track), t = project.tracks[i], { ctx, w, h } = canvasContext(canvas), unit = w / project.beats;
+ ctx.strokeStyle = '#ffffff09'; ctx.lineWidth = 1;
+ for (let b = 0; b <= project.beats; b += beatsPerBar(project)) { ctx.beginPath(); ctx.moveTo(b * unit + .5, 0); ctx.lineTo(b * unit + .5, h); ctx.stroke(); }
+ ctx.fillStyle = colors[i % colors.length]; ctx.globalAlpha = t.muted ? .18 : .75;
+ for (const n of t.notes) ctx.fillRect(n.beat * unit, 6 + (1 - (n.midi % 36) / 36) * (h - 15), Math.max(2, n.duration * unit - 1), 3);
+ for (const clip of t.clips) { const x = clip.beat * unit, width = (beatAt(project, secondsAt(project, clip.beat) + clip.duration) - clip.beat) * unit; ctx.globalAlpha = .24; ctx.fillRect(x, 6, width, h - 12); ctx.globalAlpha = .85; ctx.font = '9px sans-serif'; ctx.save(); ctx.beginPath(); ctx.rect(x + 4, 4, Math.max(0, width - 8), h - 8); ctx.clip(); ctx.fillText(project.assets.find(a => a.id === clip.assetId)?.name || 'Recording', x + 6, h / 2 + 3); ctx.restore(); }
+ ctx.globalAlpha = 1; ctx.fillStyle = '#f8e5ca'; ctx.fillRect(Math.min(w - 1, beat * unit), 0, 1, h);
+ }
+}
+function drawPiano() {
+ const { ctx, w, h } = canvasContext($('#piano')), bar = beatsPerBar(project), start = windowBar * bar, span = Math.min(8 * bar, project.beats - start), labelWidth = 37;
+ const notes = track().notes, lowest = Math.min(...notes.map(n => n.midi), 60), highest = Math.max(...notes.map(n => n.midi), 72);
+ const low = Math.max(0, Math.floor(lowest / 12) * 12 - 3), high = Math.min(127, Math.max(low + 24, highest + 4)), rows = high - low + 1, rowHeight = (h - 24) / rows, unit = (w - labelWidth) / Math.max(span, 1);
+ pianoBounds = { w, h, low, high, rows, rowHeight, unit, start, span, labelWidth }; noteRects = [];
+ for (let midi = low; midi <= high; midi++) {
+ const y = 24 + (high - midi) * rowHeight; ctx.fillStyle = [1, 3, 6, 8, 10].includes(midi % 12) ? '#ffffff02' : '#ffffff06'; ctx.fillRect(labelWidth, y, w - labelWidth, rowHeight - .5);
+ if (midi % 12 === 0) { ctx.fillStyle = '#737d94'; ctx.font = '9px monospace'; ctx.fillText(noteName(midi), 5, y + rowHeight); }
+ }
+ for (let beat = 0; beat <= span; beat += 4 / project.meter[1]) { const x = labelWidth + beat * unit, major = Math.abs(beat / bar - Math.round(beat / bar)) < .0001; ctx.strokeStyle = major ? '#ffffff24' : '#ffffff09'; ctx.beginPath(); ctx.moveTo(x + .5, 24); ctx.lineTo(x + .5, h); ctx.stroke(); if (major) { ctx.fillStyle = '#838da2'; ctx.font = '9px monospace'; ctx.fillText(String(Math.round((start + beat) / bar) + 1), x + 4, 15); } }
+ notes.forEach((n, i) => {
+ if (n.beat + n.duration <= start || n.beat >= start + span) return;
+ const x = labelWidth + Math.max(0, n.beat - start) * unit, y = 24 + (high - n.midi) * rowHeight + 1, width = Math.max(3, (Math.min(start + span, n.beat + n.duration) - Math.max(start, n.beat)) * unit - 1);
+ ctx.globalAlpha = .4 + n.velocity * .6; ctx.fillStyle = i === selectedNote ? '#fff4df' : colors[selectedTrack % colors.length]; ctx.fillRect(x, y, width, Math.max(2, rowHeight - 2)); ctx.globalAlpha = 1;
+ noteRects.push({ index: i, x, y, width, height: Math.max(3, rowHeight) });
+ });
+ $('#bar-window').textContent = `${windowBar + 1}–${Math.ceil((start + span) / bar)}`; $('#previous-bars').disabled = windowBar === 0; $('#next-bars').disabled = start + span >= project.beats;
+ $('#piano-title').textContent = track().name + (track().instrument === 'audio' ? ' · recording' : ' · notes');
}
function drawWave() {
- if (!rendered) return;
- const c = $("#waveform"),
- ctx = c.getContext("2d"),
- w = c.width,
- h = c.height;
- ctx.clearRect(0, 0, w, h);
- const pos = playing ? audioContext.currentTime - started : offset;
- const played = (pos / rendered.duration) * w;
- const stride = Math.max(1, Math.floor(rendered.samples.length / w));
- ctx.lineWidth = 1.4;
- for (let x = 0; x < w; x += 3) {
- let peak = 0;
- for (
- let i = x * stride;
- i < Math.min((x + 3) * stride, rendered.samples.length);
- i += 8
- )
- peak = Math.max(peak, Math.abs(rendered.samples[i]));
- ctx.strokeStyle = x < played ? "#efb082" : "#836650";
- ctx.beginPath();
- ctx.moveTo(x, h / 2 - peak * h * 0.7);
- ctx.lineTo(x, h / 2 + peak * h * 0.7);
- ctx.stroke();
- }
- if (playing) {
- ctx.strokeStyle = "#f7e7d0";
- ctx.beginPath();
- ctx.moveTo(played, 0);
- ctx.lineTo(played, h);
- ctx.stroke();
- }
-}
-function renderGrid() {
- const grid = $("#steps");
- grid.replaceChildren();
- grid.append(document.createElement("span"));
- for (let i = 0; i < 16; i++) {
- const s = document.createElement("span");
- s.className = "step-num";
- s.textContent = i + 1;
- grid.append(s);
+ const { ctx, w, h } = canvasContext($('#waveform'));
+ if (mix) {
+ for (let channel = 0; channel < 2; channel++) {
+ const samples = mix.channels[channel], stride = Math.max(1, Math.floor(samples.length / w)), center = h * (channel ? .75 : .25);
+ ctx.strokeStyle = channel ? '#b9acf1' : '#eabe90'; ctx.lineWidth = 1;
+ ctx.beginPath();
+ for (let x = 0; x < w; x++) { let peak = 0; for (let j = x * stride; j < Math.min(samples.length, (x + 1) * stride); j += Math.max(1, Math.floor(stride / 24))) peak = Math.max(peak, Math.abs(samples[j])); const length = peak * mix.gain * h * .24; ctx.moveTo(x, center - Math.max(.5, length)); ctx.lineTo(x, center + Math.max(.5, length)); }
+ ctx.stroke();
+ }
}
- trackNames.forEach((name, track) => {
- const b = document.createElement("button");
- b.className = "track";
- b.textContent = muted[track] ? `${name} ×` : name;
- b.setAttribute("aria-label", `${muted[track] ? "Unmute" : "Mute"} ${name}`);
- b.onclick = () => {
- muted[track] = !muted[track];
- renderGrid();
- rebuildMusic();
- };
- grid.append(b);
- patterns[track].forEach((on, tick) => {
- const s = document.createElement("button");
- s.className = `step ${tick % 4 === 0 ? "beat" : ""}`;
- s.dataset.tick = tick;
- s.setAttribute("aria-pressed", on);
- s.setAttribute("aria-label", `${name} step ${tick + 1}`);
- s.onclick = () => {
- patterns[track][tick] = !patterns[track][tick];
- renderGrid();
- rebuildMusic();
- };
- grid.append(s);
- });
+ const current = playback ? Math.min(duration(), Math.max(0, audioContext.currentTime - startedAt)) : Math.min(duration(), seekSeconds);
+ ctx.fillStyle = '#ffffffb3'; ctx.fillRect(current / duration() * w, 0, 1, h); $('#time').textContent = clock(current) + ' / ' + clock(duration());
+}
+function drawAll() { drawArrangement(); drawPiano(); drawWave(); }
+function updateNote() {
+ const n = track().notes[selectedNote];
+ for (const id of ['note-pitch', 'note-start', 'note-velocity']) $('#' + id).disabled = !n;
+ $('#delete-note').disabled = !n;
+ if (n) { $('#note-pitch').value = noteName(n.midi); $('#note-start').value = Number(n.beat.toFixed(4)); $('#note-length').value = Number(n.duration.toFixed(4)); $('#note-velocity').value = n.velocity; }
+}
+async function ensureMix() {
+ if (mixRevision === revision && mix) return mix;
+ if (renderPromise?.revision === revision) return renderPromise.promise;
+ const current = revision, candidate = structuredClone(project);
+ $('#audio-status').textContent = 'Rendering your arrangement…'; $('#error').hidden = true;
+ $('#play').disabled = $('#export-wav').disabled = $('#export-stems').disabled = true;
+ const promise = renderSession(candidate).then(result => {
+ if (current !== revision) return result;
+ mix = result; mixRevision = current;
+ $('#audio-status').textContent = activeTracks(project).length + ' tracks · ready to play';
+ $('#level').textContent = `PEAK ${result.peak > 0 ? (20 * Math.log10(result.peak)).toFixed(1) : '−∞'} dBFS / 48 kHz`;
+ $('#play').disabled = $('#export-wav').disabled = $('#export-stems').disabled = false;
+ document.body.dataset.ready = 'true'; parentMessage('harness:ready'); drawWave(); return result;
+ }).catch(error => {
+ if (current === revision) { $('#error').textContent = error.message; $('#error').hidden = false; $('#audio-status').textContent = 'A track needs attention'; parentMessage('harness:error', { message: error.message }); }
+ throw error;
});
-}
-async function playMusic() {
- if (playing) {
- stopMusic(false);
- return;
+ renderPromise = { revision: current, promise }; return promise;
+}
+function scheduleMix() { $('#play').disabled = $('#export-wav').disabled = $('#export-stems').disabled = true; clearTimeout(renderTimer); renderTimer = setTimeout(() => ensureMix().catch(() => {}), 240); }
+function guard(task) { return async (...args) => { try { await task(...args); } catch (error) { toast(error.message || String(error)); } }; }
+async function play() {
+ if (playback) { seekSeconds = audioContext.currentTime - startedAt; stop(); return; }
+ const current = revision, rendered = await ensureMix(); if (current !== revision) return;
+ audioContext ??= new AudioContext(); await audioContext.resume();
+ const source = audioContext.createBufferSource(), gain = audioContext.createGain(); source.buffer = rendered.buffer; gain.gain.value = rendered.gain; source.connect(gain); gain.connect(audioContext.destination);
+ if (seekSeconds >= rendered.duration - .05) seekSeconds = 0;
+ startedAt = audioContext.currentTime - seekSeconds; source.start(0, seekSeconds); playback = source;
+ $('#play').textContent = 'Ⅱ Pause'; $('#play').setAttribute('aria-label', 'Pause');
+ source.onended = () => { if (playback === source) { playback = null; seekSeconds = 0; $('#play').textContent = '▶ Play'; $('#play').setAttribute('aria-label', 'Play'); } };
+}
+$('#play').onclick = guard(play); $('#stop').onclick = () => { stop(); seekSeconds = 0; drawAll(); };
+$('#waveform').onclick = guard(async event => { const wasPlaying = !!playback, box = $('#waveform').getBoundingClientRect(); stop(); seekSeconds = Math.max(0, Math.min(duration() - .02, (event.clientX - box.left) / box.width * duration())); if (wasPlaying) await play(); drawAll(); });
+let drag;
+$('#piano').onpointerdown = event => {
+ if (!event.isPrimary || event.button !== 0) return;
+ if (track().instrument === 'audio') { toast('Use the recording controls to move or trim this clip.'); return; }
+ const box = $('#piano').getBoundingClientRect(), x = event.clientX - box.left, y = event.clientY - box.top, hit = noteRects.find(r => x >= r.x && x <= r.x + r.width && y >= r.y && y <= r.y + r.height);
+ if (hit) {
+ selectedNote = hit.index; drag = { x, y, previous: state(), note: { ...track().notes[selectedNote] }, moved: false }; $('#piano').setPointerCapture(event.pointerId); updateNote(); drawPiano();
+ } else if (x > pianoBounds.labelWidth && y > 24) {
+ const beat = Math.round((pianoBounds.start + (x - pianoBounds.labelWidth) / pianoBounds.unit) * 4) / 4, midi = Math.max(0, Math.min(127, pianoBounds.high - Math.floor((y - 24) / pianoBounds.rowHeight))), length = Math.max(.125, Number($('#note-length').value) || 1);
+ if (beat >= project.beats) return;
+ change(() => { track().notes.push({ beat, midi, duration: Math.min(length, project.beats - beat), velocity: Number($('#note-velocity').value) || .75 }); selectedNote = track().notes.length - 1; });
}
- try {
- audioContext ??= new (window.AudioContext || window.webkitAudioContext)();
- await audioContext.resume();
- master ??= audioContext.createGain();
- master.disconnect();
- master.connect(audioContext.destination);
- master.gain.value = +$("#volume").value / 100;
- const buffer = audioContext.createBuffer(
- 1,
- rendered.samples.length,
- rendered.sampleRate,
- );
- buffer.copyToChannel(rendered.samples, 0);
- source = audioContext.createBufferSource();
- source.buffer = buffer;
- source.connect(master);
- if (offset >= rendered.duration) offset = 0;
- started = audioContext.currentTime - offset;
- source.start(0, offset);
- source.onended = () => {
- playing = false;
- source = null;
- offset = 0;
- $("#play").textContent = "▶ Play";
- $("#audio-status").textContent =
- "That was your take. Play it again, or change a step.";
- };
- playing = true;
- $("#play").textContent = "Ⅱ Pause";
- $("#audio-status").textContent = "Playing your eight-bar arrangement.";
- } catch (e) {
- toast("Audio could not start: " + e.message);
- }
-}
-function newScore() {
- score = musicScore(seed);
- patterns = score.patterns.map((row) => [...row]);
- $("#tempo").value = score.tempo;
- $("#key").textContent =
- ["C", "C♯", "D", "E♭", "E", "F", "F♯", "G", "A♭", "A", "B♭", "B"][
- score.root % 12
- ] + " minor";
- renderGrid();
- rebuildMusic();
-}
-trackNames.forEach((name, i) => {
- const label = document.createElement("label");
- label.className = "field";
- const span = document.createElement("span");
- span.textContent = name;
- const input = document.createElement("input");
- input.type = "range";
- input.min = 0;
- input.max = 100;
- input.value = levels[i] * 100;
- input.setAttribute("aria-label", `${name} level`);
- input.onchange = () => {
- levels[i] = +input.value / 100;
- rebuildMusic();
- };
- label.append(span, input);
- $("#mixer").append(label);
-});
-$("#play").onclick = playMusic;
-$("#stop").onclick = () => {
- stopMusic();
- $("#time").textContent = `0:00 / ${clockText(rendered.duration)}`;
- $("#audio-status").textContent =
- "Stopped. Press Play to start at the beginning.";
-};
-for (const id of ["tempo", "swing"]) $("#" + id).onchange = rebuildMusic;
-$("#volume").oninput = () => {
- $("#volume-value").value = `${$("#volume").value}%`;
- if (master)
- master.gain.setTargetAtTime(
- +$("#volume").value / 100,
- audioContext.currentTime,
- 0.02,
- );
};
-$("#export-wav").onclick = () => {
- saveFile(
- `afterhours-${hash(seed)}.wav`,
- wavFile(rendered.samples, rendered.sampleRate),
- "audio/wav",
- );
- toast("WAV rendered from your current score and mix.");
+$('#piano').onpointermove = event => {
+ if (!drag) return;
+ const box = $('#piano').getBoundingClientRect(), dx = event.clientX - box.left - drag.x, dy = event.clientY - box.top - drag.y;
+ if (!drag.moved && Math.abs(dx) + Math.abs(dy) < 4) return;
+ drag.moved = true; stop(); const n = track().notes[selectedNote];
+ n.beat = Math.max(0, Math.min(project.beats - n.duration, Math.round((drag.note.beat + dx / pianoBounds.unit) * 4) / 4));
+ n.midi = Math.max(0, Math.min(127, drag.note.midi - Math.round(dy / pianoBounds.rowHeight))); updateNote(); drawPiano(); drawArrangement();
};
-let lastTick = -1;
-function musicFrame() {
- if (playing) {
- const t = Math.min(rendered.duration, audioContext.currentTime - started),
- tick = Math.floor(t / (60 / +$("#tempo").value / 4)) % 16;
- $("#time").textContent =
- `${clockText(t)} / ${clockText(rendered.duration)}`;
- $("#bar").textContent =
- `Bar ${Math.min(8, Math.floor(t / ((60 / +$("#tempo").value) * 4)) + 1)} / 8`;
- if (tick !== lastTick) {
- $$(".step").forEach((b) =>
- b.classList.toggle("current", +b.dataset.tick === tick),
- );
- lastTick = tick;
- }
- drawWave();
- } else if (lastTick !== -1) {
- $$(".step.current").forEach((b) => b.classList.remove("current"));
- lastTick = -1;
- }
- requestAnimationFrame(musicFrame);
-}
-fitCanvas($("#waveform"), drawWave);
-addEventListener("seedchange", newScore);
-addEventListener("pagehide", () => {
- stopMusic();
- audioContext?.close();
+function endDrag() { if (drag?.moved) { undoStack.push(drag.previous); if (undoStack.length > 16) undoStack.shift(); redoStack = []; revision++; mixRevision = -1; persist(); scheduleMix(); updateLabels(); } drag = null; }
+$('#piano').onpointerup = endDrag; $('#piano').onpointercancel = endDrag;
+for (const [id, key, parse] of [['note-pitch', 'midi', noteNumber], ['note-start', 'beat', Number], ['note-length', 'duration', Number], ['note-velocity', 'velocity', Number]]) $('#' + id).onchange = () => { if (selectedNote < 0) return; change(() => { track().notes[selectedNote][key] = parse($('#' + id).value); }); };
+$('#delete-note').onclick = () => { if (selectedNote >= 0) change(() => { track().notes.splice(selectedNote, 1); selectedNote = -1; }); };
+$('#previous-bars').onclick = () => { windowBar = Math.max(0, windowBar - 8); drawPiano(); }; $('#next-bars').onclick = () => { windowBar += 8; drawPiano(); };
+$('#duplicate-section').onclick = () => change(() => { const start = windowBar * beatsPerBar(project), length = Math.min(8 * beatsPerBar(project), project.beats - start); project = duplicateSection(project, start, length); windowBar = Math.floor((project.beats - length) / beatsPerBar(project)); });
+$('#track-name').onchange = () => change(() => { track().name = $('#track-name').value.trim() || 'Instrument'; });
+$('#instrument').onchange = () => change(() => { track().instrument = $('#instrument').value; delete track().midiProgram; if (track().instrument === 'sampler') track().sampleId = project.assets[0]?.id; });
+for (const key of ['gain', 'pan', 'attack', 'release', 'tone', 'space', 'delay']) $('#' + key).onchange = () => change(() => { track()[key] = Number($('#' + key).value); });
+$('#mute').onclick = () => change(() => { track().muted = !track().muted; }); $('#solo').onclick = () => change(() => { track().solo = !track().solo; });
+$('#master').onchange = () => change(() => { project.master = Number($('#master').value); });
+$('#tempo').onchange = () => change(() => { const ratio = Number($('#tempo').value) / project.tempo; project.tempos.forEach(t => { t.bpm *= ratio; }); project.tempo = project.tempos[0].bpm; });
+$('#bars').onchange = () => change(() => { const beats = Number($('#bars').value) * beatsPerBar(project); if (project.tracks.some(t => t.notes.some(n => n.beat + n.duration > beats) || t.clips.some(c => secondsAt(project, c.beat) + c.duration > secondsAt(project, beats)))) throw new Error('Move or shorten the ending notes and recordings before reducing the arrangement.'); project.beats = beats; project.sections = project.sections.filter(s => s.beat < beats).map(s => ({ ...s, length: Math.min(s.length, beats - s.beat) })); project.tempos = project.tempos.filter(t => t.beat < beats); });
+$('#sample-id').onchange = () => change(() => { track().sampleId = $('#sample-id').value; }); $('#sample-root').onchange = () => change(() => { track().sampleRoot = noteNumber($('#sample-root').value); });
+$('#clip-select').onchange = () => { selectedClip = Number($('#clip-select').value); buildUI(); };
+for (const [id, key] of [['clip-beat', 'beat'], ['clip-offset', 'offset'], ['clip-duration', 'duration']]) $('#' + id).onchange = () => change(() => { const clip = track().clips[selectedClip]; clip[key] = Number($('#' + id).value); const end = beatAt(project, secondsAt(project, clip.beat) + clip.duration); project.beats = Math.max(project.beats, Math.ceil(end / beatsPerBar(project)) * beatsPerBar(project)); });
+for (const [id, delta] of [['transpose-down', -12], ['transpose-up', 12]]) $('#' + id).onclick = () => change(() => { track().notes.forEach(n => { n.midi += delta; }); });
+$('#add-track').onclick = () => change(() => { project.tracks.push({ id: 'instrument-' + Date.now(), name: 'Your instrument', instrument: 'felt', notes: [], clips: [] }); selectedTrack = project.tracks.length - 1; selectedNote = -1; });
+$('#remove-track').onclick = () => { if (project.tracks.length > 1) change(() => { project.tracks.splice(selectedTrack, 1); selectedTrack = Math.min(selectedTrack, project.tracks.length - 1); selectedNote = -1; }); };
+$('#undo').onclick = () => { if (undoStack.length) { redoStack.push(state()); restore(undoStack.pop()); } }; $('#redo').onclick = () => { if (redoStack.length) { undoStack.push(state()); restore(redoStack.pop()); } };
+$('#reset-project').onclick = () => change(() => { project = structuredClone(original); selectedTrack = 0; selectedNote = -1; windowBar = 0; });
+$('#save-project').onclick = () => saveFile(filename(project.title) + '.afterhours.json', JSON.stringify(project, null, 2), 'application/json');
+$('#open-project').onclick = () => $('#project-file').click(); $('#open-midi').onclick = () => $('#midi-file').click(); $('#import-audio').onclick = () => $('#audio-file').click();
+$('#project-file').onchange = guard(async () => { const file = $('#project-file').files[0]; if (!file) return; if (file.size > 28000000) throw new Error('Project exceeds 28 MB.'); const p = validateSession(JSON.parse(await file.text())); change(() => { project = p; selectedTrack = 0; selectedNote = -1; windowBar = 0; }); $('#project-file').value = ''; });
+$('#midi-file').onchange = guard(async () => { const file = $('#midi-file').files[0]; if (!file) return; if (file.size > 4000000) throw new Error('MIDI file exceeds 4 MB.'); const p = readSessionMidi(new Uint8Array(await file.arrayBuffer()), Midi); change(() => { project = p; selectedTrack = 0; selectedNote = -1; windowBar = 0; }); $('#midi-file').value = ''; toast(p.importWarnings.length ? p.importWarnings[0] : 'Your notes and tempo changes are ready to arrange.'); });
+$('#audio-file').onchange = guard(async () => {
+ const file = $('#audio-file').files[0]; if (!file) return; if (file.size > 18000000) throw new Error('Use a recording under 18 MB. A longer recording can be imported as MP3.');
+ const context = new OfflineAudioContext(1, 1, 48000), buffer = await context.decodeAudioData(await file.arrayBuffer());
+ if (buffer.duration > 240) throw new Error('Trim the recording to four minutes or less.');
+ const data = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(file); });
+ change(() => {
+ const id = 'recording-' + Date.now(); project.assets.push({ id, name: file.name, data });
+ project.beats = Math.max(project.beats, Math.ceil(beatAt(project, buffer.duration) / beatsPerBar(project)) * beatsPerBar(project));
+ project.tracks.push({ id, name: file.name.slice(0, 120), instrument: 'audio', gain: 1, tone: 20000, space: 0, notes: [], clips: [{ assetId: id, beat: 0, offset: 0, duration: buffer.duration, gain: 1, fadeIn: .02, fadeOut: .05 }] });
+ selectedTrack = project.tracks.length - 1; selectedNote = -1;
+ }); $('#audio-file').value = ''; toast('Your recording is in the arrangement. Move or trim it in the track controls.');
});
-newScore();
-musicFrame();
-ready();
-
+$('#export-wav').onclick = guard(async () => { const current = revision, result = await ensureMix(); if (current !== revision) throw new Error('The piece changed during export. Export the new version when it is ready.'); saveFile(filename(project.title) + '.wav', wavBytes(result.channels, result.sampleRate, result.gain), 'audio/wav'); });
+$('#export-midi').onclick = guard(async () => { saveFile(filename(project.title) + '.mid', writeSessionMidi(project, Midi), 'audio/midi'); toast('Editable notes and tempo exported. Your recorded audio stays in the WAV stems and project.'); });
+async function stemFiles() {
+ const candidate = structuredClone(project), result = await renderSession(candidate), audible = activeTracks(candidate);
+ if (audible.length * result.buffer.length * 4 > 512000000) throw new Error('This stem bundle exceeds 512 MB. Solo a smaller group of tracks and export in groups.');
+ const files = [['mix.wav', wavBytes(result.channels, result.sampleRate, result.gain)], ['composition.mid', writeSessionMidi(candidate, Midi)], ['project.afterhours.json', JSON.stringify(candidate, null, 2)]];
+ const report = { title: candidate.title, sampleRate: result.sampleRate, channels: 2, bitDepth: 16, duration: result.duration, commonGain: result.gain, peak: result.peak, stems: [] };
+ for (let i = 0; i < audible.length; i++) {
+ const t = audible[i], rendered = await renderSession(candidate, { onlyTrack: t.id }), name = `${String(i + 1).padStart(2, '0')}-${filename(t.name)}.wav`;
+ files.push(['stems/' + name, wavBytes(rendered.channels, rendered.sampleRate, result.gain)]); report.stems.push({ file: name, track: t.id, name: t.name });
+ }
+ files.push(['delivery.json', JSON.stringify(report, null, 2)], ['README.txt', `${candidate.title}\n\n${candidate.brief}\n\nDrag every WAV stem to time zero in your DAW. All stems share length, sample rate and mix gain. They contain the audible tracks at export time, including per-track effects. MIDI carries all notes and the tempo map, not recordings or audio effects. Synth previews need not sound like your DAW's MIDI instruments. project.afterhours.json preserves your notes, mix and embedded recordings.\n`]);
+ return { files, report };
+}
+$('#export-stems').onclick = guard(async () => { const name = filename(project.title); $('#export-stems').disabled = true; $('#audio-status').textContent = 'Rendering separate tracks…'; try { const { files, report } = await stemFiles(); saveFile(name + '-production.zip', zipFiles(files)); toast(`${report.stems.length} aligned WAV stems, mix, MIDI and editable project exported.`); } finally { $('#export-stems').disabled = false; $('#audio-status').textContent = 'Ready to play'; } });
+$('#export-html').onclick = () => { const doc = document.documentElement.cloneNode(true); doc.querySelector('#afterhours-data').textContent = JSON.stringify(project).replace(/</g, '\\u003c'); doc.querySelector('#revision-notice').hidden = true; doc.querySelector('#error').hidden = true; doc.querySelector('#toast').className = ''; doc.querySelector('body').removeAttribute('data-ready'); saveFile(filename(project.title) + '-studio.html', '<!doctype html>\n' + doc.outerHTML, 'text/html'); };
+$('#use-revision').onclick = () => { preserveDraft = false; $('#revision-notice').hidden = true; persist(); }; $('#keep-draft').onclick = () => { preserveDraft = false; $('#revision-notice').hidden = true; restore(pendingDraft); };
+try { const saved = JSON.parse(localStorage.getItem(storageKey)); if (saved) { saved.project = validateSession(saved.project); if (saved.baseRevision === original.revision) { project = saved.project; selectedTrack = Math.min(saved.selectedTrack || 0, project.tracks.length - 1); windowBar = saved.windowBar || 0; } else { pendingDraft = saved; preserveDraft = true; $('#revision-notice').hidden = false; } } } catch {}
+addEventListener('keydown', event => { if (event.target.closest('input,select,textarea')) return; if (event.code === 'Space') { event.preventDefault(); guard(play)(); } else if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'z') { event.preventDefault(); $('#' + (event.shiftKey ? 'redo' : 'undo')).click(); } else if (['Backspace', 'Delete'].includes(event.key) && event.target === $('#piano')) { event.preventDefault(); $('#delete-note').click(); } });
+new ResizeObserver(drawAll).observe($('.main-panel'));
+function animate() { if (playback) { drawWave(); drawArrangement(); } requestAnimationFrame(animate); }
+window.afterhours = {
+ getProject: () => structuredClone(project), getState: () => ({ playing: !!playback, context: audioContext?.state, selectedTrack, selectedNote, peak: mix?.peak, rms: mix?.rms, duration: mix?.duration, revision, mixRevision }),
+ render: options => renderSession(project, options), midi: () => Array.from(writeSessionMidi(project, Midi)), stemFiles,
+ async deliver() { const result = await ensureMix(), bytes = new Blob([wavBytes(result.channels, result.sampleRate, result.gain)], { type: 'audio/wav' }); const wav = await new Promise(resolve => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.readAsDataURL(bytes); }); return { wav, duration: result.duration, peak: result.peak, rms: result.rms, sampleRate: result.sampleRate, gain: result.gain }; },
+};
+buildUI(); ensureMix().catch(() => {}); animate();
</script></body></html>
diff --git a/store/agents/music-studio/template/piece/session.json b/store/agents/music-studio/template/piece/session.json
new file mode 100644
index 000000000..53d1926ad
--- /dev/null
+++ b/store/agents/music-studio/template/piece/session.json
@@ -0,0 +1,1601 @@
+{
+ "spec": "afterhours/1",
+ "id": "blue-hour",
+ "title": "Blue Hour",
+ "brief": "A 48-second title cue for a coastal documentary. An intimate plucked motif opens into warm harmony and a restrained pulse, then resolves quietly. The arrangement leaves space for a voiceover.",
+ "seed": "blue-hour",
+ "tempo": 100,
+ "meter": [
+ 4,
+ 4
+ ],
+ "beats": 80,
+ "tail": 0,
+ "master": 0.9,
+ "sections": [
+ {
+ "name": "First light",
+ "beat": 0,
+ "length": 16
+ },
+ {
+ "name": "Footsteps",
+ "beat": 16,
+ "length": 16
+ },
+ {
+ "name": "Open water",
+ "beat": 32,
+ "length": 16
+ },
+ {
+ "name": "The lift",
+ "beat": 48,
+ "length": 16
+ },
+ {
+ "name": "Home",
+ "beat": 64,
+ "length": 16
+ }
+ ],
+ "tracks": [
+ {
+ "id": "motif",
+ "name": "Plucked motif",
+ "instrument": "pluck",
+ "gain": 0.92,
+ "pan": -0.22,
+ "tone": 7200,
+ "space": 0.18,
+ "delay": 0.12,
+ "release": 0.35,
+ "notes": [
+ {
+ "beat": 0,
+ "midi": 62,
+ "duration": 0.9,
+ "velocity": 0.5645551978774368
+ },
+ {
+ "beat": 1.5,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.5156839515805244
+ },
+ {
+ "beat": 3,
+ "midi": 73,
+ "duration": 0.55,
+ "velocity": 0.5337221220098436
+ },
+ {
+ "beat": 4,
+ "midi": 69,
+ "duration": 0.9,
+ "velocity": 0.5704508999161422
+ },
+ {
+ "beat": 5.5,
+ "midi": 73,
+ "duration": 0.55,
+ "velocity": 0.5553384073100984
+ },
+ {
+ "beat": 7,
+ "midi": 78,
+ "duration": 0.55,
+ "velocity": 0.5486000507526099
+ },
+ {
+ "beat": 8,
+ "midi": 59,
+ "duration": 0.9,
+ "velocity": 0.542434654519707
+ },
+ {
+ "beat": 9.5,
+ "midi": 66,
+ "duration": 0.55,
+ "velocity": 0.5555654297582805
+ },
+ {
+ "beat": 11,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.5576091022111475
+ },
+ {
+ "beat": 12,
+ "midi": 66,
+ "duration": 0.9,
+ "velocity": 0.5498305642195046
+ },
+ {
+ "beat": 13.5,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.5180191269449889
+ },
+ {
+ "beat": 15,
+ "midi": 74,
+ "duration": 0.55,
+ "velocity": 0.551269242669642
+ },
+ {
+ "beat": 16,
+ "midi": 55,
+ "duration": 0.9,
+ "velocity": 0.5297916078120469
+ },
+ {
+ "beat": 16.75,
+ "midi": 62,
+ "duration": 0.55,
+ "velocity": 0.531561849565804
+ },
+ {
+ "beat": 17.5,
+ "midi": 66,
+ "duration": 0.55,
+ "velocity": 0.5246851859532295
+ },
+ {
+ "beat": 18,
+ "midi": 71,
+ "duration": 0.9,
+ "velocity": 0.5459769469805061
+ },
+ {
+ "beat": 18.75,
+ "midi": 55,
+ "duration": 0.55,
+ "velocity": 0.5430110706716775
+ },
+ {
+ "beat": 19.5,
+ "midi": 62,
+ "duration": 0.55,
+ "velocity": 0.5556431808911263
+ },
+ {
+ "beat": 20,
+ "midi": 62,
+ "duration": 0.9,
+ "velocity": 0.5426485464416444
+ },
+ {
+ "beat": 20.75,
+ "midi": 66,
+ "duration": 0.55,
+ "velocity": 0.551458582278341
+ },
+ {
+ "beat": 21.5,
+ "midi": 71,
+ "duration": 0.55,
+ "velocity": 0.5649891081705689
+ },
+ {
+ "beat": 22,
+ "midi": 55,
+ "duration": 0.9,
+ "velocity": 0.5389283135816455
+ },
+ {
+ "beat": 22.75,
+ "midi": 62,
+ "duration": 0.55,
+ "velocity": 0.5602186762280762
+ },
+ {
+ "beat": 23.5,
+ "midi": 66,
+ "duration": 0.55,
+ "velocity": 0.5550721922561526
+ },
+ {
+ "beat": 24,
+ "midi": 57,
+ "duration": 0.9,
+ "velocity": 0.5556441643811761
+ },
+ {
+ "beat": 24.75,
+ "midi": 64,
+ "duration": 0.55,
+ "velocity": 0.5601637458100914
+ },
+ {
+ "beat": 25.5,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.5181704859040677
+ },
+ {
+ "beat": 26,
+ "midi": 73,
+ "duration": 0.9,
+ "velocity": 0.5534745311327278
+ },
+ {
+ "beat": 26.75,
+ "midi": 57,
+ "duration": 0.55,
+ "velocity": 0.5393594153784215
+ },
+ {
+ "beat": 27.5,
+ "midi": 64,
+ "duration": 0.55,
+ "velocity": 0.580917686356604
+ },
+ {
+ "beat": 28,
+ "midi": 64,
+ "duration": 0.9,
+ "velocity": 0.5533817687354982
+ },
+ {
+ "beat": 28.75,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.5587183390788734
+ },
+ {
+ "beat": 29.5,
+ "midi": 73,
+ "duration": 0.55,
+ "velocity": 0.5792586211293935
+ },
+ {
+ "beat": 30,
+ "midi": 57,
+ "duration": 0.9,
+ "velocity": 0.573284814916551
+ },
+ {
+ "beat": 30.75,
+ "midi": 64,
+ "duration": 0.55,
+ "velocity": 0.5703277547985315
+ },
+ {
+ "beat": 31.5,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.5619088765397667
+ },
+ {
+ "beat": 32,
+ "midi": 62,
+ "duration": 0.9,
+ "velocity": 0.5153246533192694
+ },
+ {
+ "beat": 32.75,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.5237792561523615
+ },
+ {
+ "beat": 33.5,
+ "midi": 73,
+ "duration": 0.55,
+ "velocity": 0.5725928144164383
+ },
+ {
+ "beat": 34,
+ "midi": 78,
+ "duration": 0.9,
+ "velocity": 0.5557868683211505
+ },
+ {
+ "beat": 34.75,
+ "midi": 62,
+ "duration": 0.55,
+ "velocity": 0.5406799630582332
+ },
+ {
+ "beat": 35.5,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.5282267559967935
+ },
+ {
+ "beat": 36,
+ "midi": 69,
+ "duration": 0.9,
+ "velocity": 0.5165786395415664
+ },
+ {
+ "beat": 36.75,
+ "midi": 73,
+ "duration": 0.55,
+ "velocity": 0.5615075619526207
+ },
+ {
+ "beat": 37.5,
+ "midi": 78,
+ "duration": 0.55,
+ "velocity": 0.5189804663449525
+ },
+ {
+ "beat": 38,
+ "midi": 62,
+ "duration": 0.9,
+ "velocity": 0.5445952211908995
+ },
+ {
+ "beat": 38.75,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.5558770329765975
+ },
+ {
+ "beat": 39.5,
+ "midi": 73,
+ "duration": 0.55,
+ "velocity": 0.5320751886576414
+ },
+ {
+ "beat": 40,
+ "midi": 59,
+ "duration": 0.9,
+ "velocity": 0.5198988145969808
+ },
+ {
+ "beat": 40.75,
+ "midi": 66,
+ "duration": 0.55,
+ "velocity": 0.5620267365992069
+ },
+ {
+ "beat": 41.5,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.5809937621548772
+ },
+ {
+ "beat": 42,
+ "midi": 74,
+ "duration": 0.9,
+ "velocity": 0.5508571488857269
+ },
+ {
+ "beat": 42.75,
+ "midi": 59,
+ "duration": 0.55,
+ "velocity": 0.5699040935456753
+ },
+ {
+ "beat": 43.5,
+ "midi": 66,
+ "duration": 0.55,
+ "velocity": 0.578915261233598
+ },
+ {
+ "beat": 44,
+ "midi": 66,
+ "duration": 0.9,
+ "velocity": 0.5367697411932051
+ },
+ {
+ "beat": 44.75,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.5672844250261783
+ },
+ {
+ "beat": 45.5,
+ "midi": 74,
+ "duration": 0.55,
+ "velocity": 0.5304293285422027
+ },
+ {
+ "beat": 46,
+ "midi": 59,
+ "duration": 0.9,
+ "velocity": 0.5438700043462216
+ },
+ {
+ "beat": 46.75,
+ "midi": 66,
+ "duration": 0.55,
+ "velocity": 0.5440233726710081
+ },
+ {
+ "beat": 47.5,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.5674215055428445
+ },
+ {
+ "beat": 48,
+ "midi": 55,
+ "duration": 0.9,
+ "velocity": 0.672498374399729
+ },
+ {
+ "beat": 48.75,
+ "midi": 62,
+ "duration": 0.55,
+ "velocity": 0.7142857280028984
+ },
+ {
+ "beat": 49.5,
+ "midi": 66,
+ "duration": 0.55,
+ "velocity": 0.6693470929078758
+ },
+ {
+ "beat": 50,
+ "midi": 71,
+ "duration": 0.9,
+ "velocity": 0.6544555243700743
+ },
+ {
+ "beat": 50.75,
+ "midi": 55,
+ "duration": 0.55,
+ "velocity": 0.7016154746282844
+ },
+ {
+ "beat": 51.5,
+ "midi": 62,
+ "duration": 0.55,
+ "velocity": 0.7146699369736016
+ },
+ {
+ "beat": 52,
+ "midi": 62,
+ "duration": 0.9,
+ "velocity": 0.6642920906236396
+ },
+ {
+ "beat": 52.75,
+ "midi": 66,
+ "duration": 0.55,
+ "velocity": 0.7161841747676952
+ },
+ {
+ "beat": 53.5,
+ "midi": 71,
+ "duration": 0.55,
+ "velocity": 0.6836484735189006
+ },
+ {
+ "beat": 54,
+ "midi": 55,
+ "duration": 0.9,
+ "velocity": 0.670372108512558
+ },
+ {
+ "beat": 54.75,
+ "midi": 62,
+ "duration": 0.55,
+ "velocity": 0.693134555073455
+ },
+ {
+ "beat": 55.5,
+ "midi": 66,
+ "duration": 0.55,
+ "velocity": 0.6526450070301071
+ },
+ {
+ "beat": 56,
+ "midi": 57,
+ "duration": 0.9,
+ "velocity": 0.6671485533202067
+ },
+ {
+ "beat": 56.75,
+ "midi": 64,
+ "duration": 0.55,
+ "velocity": 0.7067000186173245
+ },
+ {
+ "beat": 57.5,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.6841152801522985
+ },
+ {
+ "beat": 58,
+ "midi": 73,
+ "duration": 0.9,
+ "velocity": 0.6866803099540993
+ },
+ {
+ "beat": 58.75,
+ "midi": 57,
+ "duration": 0.55,
+ "velocity": 0.6533734201705083
+ },
+ {
+ "beat": 59.5,
+ "midi": 64,
+ "duration": 0.55,
+ "velocity": 0.6772519801398739
+ },
+ {
+ "beat": 60,
+ "midi": 64,
+ "duration": 0.9,
+ "velocity": 0.6657161834491416
+ },
+ {
+ "beat": 60.75,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.6660698143094779
+ },
+ {
+ "beat": 61.5,
+ "midi": 73,
+ "duration": 0.55,
+ "velocity": 0.6567942600864917
+ },
+ {
+ "beat": 62,
+ "midi": 57,
+ "duration": 0.9,
+ "velocity": 0.6868582462500781
+ },
+ {
+ "beat": 62.75,
+ "midi": 64,
+ "duration": 0.55,
+ "velocity": 0.6881102317394688
+ },
+ {
+ "beat": 63.5,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.6895300984820351
+ },
+ {
+ "beat": 64,
+ "midi": 62,
+ "duration": 0.9,
+ "velocity": 0.5748425221830606
+ },
+ {
+ "beat": 64.75,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.5556503183364868
+ },
+ {
+ "beat": 65.5,
+ "midi": 73,
+ "duration": 0.55,
+ "velocity": 0.5547063233807682
+ },
+ {
+ "beat": 66,
+ "midi": 78,
+ "duration": 0.9,
+ "velocity": 0.5626272984817624
+ },
+ {
+ "beat": 66.75,
+ "midi": 62,
+ "duration": 0.55,
+ "velocity": 0.522831639175117
+ },
+ {
+ "beat": 67.5,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.5546279738426209
+ },
+ {
+ "beat": 68,
+ "midi": 69,
+ "duration": 0.9,
+ "velocity": 0.5413805456191301
+ },
+ {
+ "beat": 68.75,
+ "midi": 73,
+ "duration": 0.55,
+ "velocity": 0.5201513358294964
+ },
+ {
+ "beat": 69.5,
+ "midi": 78,
+ "duration": 0.55,
+ "velocity": 0.5385957259826362
+ },
+ {
+ "beat": 70,
+ "midi": 62,
+ "duration": 0.9,
+ "velocity": 0.534280517487973
+ },
+ {
+ "beat": 70.75,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.5577538215406239
+ },
+ {
+ "beat": 71.5,
+ "midi": 73,
+ "duration": 0.55,
+ "velocity": 0.5772834022156894
+ },
+ {
+ "beat": 72,
+ "midi": 59,
+ "duration": 0.9,
+ "velocity": 0.4230030191425234
+ },
+ {
+ "beat": 74,
+ "midi": 66,
+ "duration": 0.55,
+ "velocity": 0.38740793404039
+ },
+ {
+ "beat": 76,
+ "midi": 66,
+ "duration": 0.9,
+ "velocity": 0.3901720629170537
+ },
+ {
+ "beat": 78,
+ "midi": 69,
+ "duration": 0.55,
+ "velocity": 0.40686308683957906
+ },
+ {
+ "beat": 77.5,
+ "midi": 74,
+ "duration": 1.4,
+ "velocity": 0.343521455296129
+ }
+ ]
+ },
+ {
+ "id": "felt",
+ "name": "Felt melody",
+ "instrument": "felt",
+ "gain": 0.7,
+ "pan": 0.15,
+ "tone": 5200,
+ "space": 0.24,
+ "release": 0.75,
+ "notes": [
+ {
+ "beat": 16,
+ "midi": 71,
+ "duration": 1.1,
+ "velocity": 0.4673883465398103
+ },
+ {
+ "beat": 17.5,
+ "midi": 69,
+ "duration": 0.8,
+ "velocity": 0.49379954020492733
+ },
+ {
+ "beat": 19,
+ "midi": 66,
+ "duration": 1.7,
+ "velocity": 0.6301682471336797
+ },
+ {
+ "beat": 21.5,
+ "midi": 62,
+ "duration": 1.8,
+ "velocity": 0.49152300154324624
+ },
+ {
+ "beat": 24,
+ "midi": 69,
+ "duration": 1.1,
+ "velocity": 0.4603718268405646
+ },
+ {
+ "beat": 25.5,
+ "midi": 73,
+ "duration": 0.8,
+ "velocity": 0.48717615934088826
+ },
+ {
+ "beat": 27,
+ "midi": 76,
+ "duration": 1.7,
+ "velocity": 0.6432531002314761
+ },
+ {
+ "beat": 29.5,
+ "midi": 73,
+ "duration": 1.8,
+ "velocity": 0.4998916279897094
+ },
+ {
+ "beat": 32,
+ "midi": 74,
+ "duration": 1.1,
+ "velocity": 0.501504489555955
+ },
+ {
+ "beat": 33.5,
+ "midi": 73,
+ "duration": 0.8,
+ "velocity": 0.48988275276497006
+ },
+ {
+ "beat": 35,
+ "midi": 69,
+ "duration": 1.7,
+ "velocity": 0.5941922905027867
+ },
+ {
+ "beat": 37.5,
+ "midi": 66,
+ "duration": 1.8,
+ "velocity": 0.48086906783282757
+ },
+ {
+ "beat": 40,
+ "midi": 73,
+ "duration": 1.1,
+ "velocity": 0.5025697763077915
+ },
+ {
+ "beat": 41.5,
+ "midi": 69,
+ "duration": 0.8,
+ "velocity": 0.48952602764125913
+ },
+ {
+ "beat": 43,
+ "midi": 66,
+ "duration": 1.7,
+ "velocity": 0.5855324333235622
+ },
+ {
+ "beat": 45.5,
+ "midi": 62,
+ "duration": 1.8,
+ "velocity": 0.5071403011493385
+ },
+ {
+ "beat": 48,
+ "midi": 71,
+ "duration": 1.1,
+ "velocity": 0.46563015357125553
+ },
+ {
+ "beat": 49.5,
+ "midi": 69,
+ "duration": 0.8,
+ "velocity": 0.49834976814221593
+ },
+ {
+ "beat": 51,
+ "midi": 66,
+ "duration": 1.7,
+ "velocity": 0.5926955807154999
+ },
+ {
+ "beat": 53.5,
+ "midi": 62,
+ "duration": 1.8,
+ "velocity": 0.4645159267447889
+ },
+ {
+ "beat": 56,
+ "midi": 69,
+ "duration": 1.1,
+ "velocity": 0.4845800973614678
+ },
+ {
+ "beat": 57.5,
+ "midi": 73,
+ "duration": 0.8,
+ "velocity": 0.5087262404616922
+ },
+ {
+ "beat": 59,
+ "midi": 76,
+ "duration": 1.7,
+ "velocity": 0.641343982924521
+ },
+ {
+ "beat": 61.5,
+ "midi": 73,
+ "duration": 1.8,
+ "velocity": 0.48929653075523677
+ },
+ {
+ "beat": 64,
+ "midi": 74,
+ "duration": 1.1,
+ "velocity": 0.46052718054037545
+ },
+ {
+ "beat": 65.5,
+ "midi": 73,
+ "duration": 0.8,
+ "velocity": 0.4692010128684342
+ },
+ {
+ "beat": 67,
+ "midi": 69,
+ "duration": 1.7,
+ "velocity": 0.6186143748374656
+ },
+ {
+ "beat": 69.5,
+ "midi": 66,
+ "duration": 1.8,
+ "velocity": 0.5143161941040307
+ },
+ {
+ "beat": 76,
+ "midi": 62,
+ "duration": 2.7,
+ "velocity": 0.3558878572102636
+ },
+ {
+ "beat": 76.09,
+ "midi": 69,
+ "duration": 2.6,
+ "velocity": 0.35292200230546295
+ },
+ {
+ "beat": 76.18,
+ "midi": 74,
+ "duration": 2.5,
+ "velocity": 0.34290987599417566
+ },
+ {
+ "beat": 76.27,
+ "midi": 78,
+ "duration": 2.4000000000000004,
+ "velocity": 0.3397677047353238
+ }
+ ]
+ },
+ {
+ "id": "pad",
+ "name": "Warm horizon",
+ "instrument": "pad",
+ "gain": 0.24,
+ "pan": 0,
+ "tone": 1600,
+ "attack": 0.55,
+ "space": 0.35,
+ "release": 0.9,
+ "notes": [
+ {
+ "beat": 16,
+ "midi": 62,
+ "duration": 7.5,
+ "velocity": 0.37253679525852207
+ },
+ {
+ "beat": 16.045,
+ "midi": 66,
+ "duration": 7.5,
+ "velocity": 0.3803293997310102
+ },
+ {
+ "beat": 16.09,
+ "midi": 71,
+ "duration": 7.5,
+ "velocity": 0.4021729043647647
+ },
+ {
+ "beat": 24,
+ "midi": 64,
+ "duration": 7.5,
+ "velocity": 0.3783894086442888
+ },
+ {
+ "beat": 24.045,
+ "midi": 69,
+ "duration": 7.5,
+ "velocity": 0.3832112705297768
+ },
+ {
+ "beat": 24.09,
+ "midi": 73,
+ "duration": 7.5,
+ "velocity": 0.40341265460848813
+ },
+ {
+ "beat": 32,
+ "midi": 69,
+ "duration": 7.5,
+ "velocity": 0.40125959977880127
+ },
+ {
+ "beat": 32.045,
+ "midi": 73,
+ "duration": 7.5,
+ "velocity": 0.3932125707380474
+ },
+ {
+ "beat": 32.09,
+ "midi": 78,
+ "duration": 7.5,
+ "velocity": 0.3723255736678839
+ },
+ {
+ "beat": 40,
+ "midi": 66,
+ "duration": 7.5,
+ "velocity": 0.38505192853137854
+ },
+ {
+ "beat": 40.045,
+ "midi": 69,
+ "duration": 7.5,
+ "velocity": 0.39397476967051626
+ },
+ {
+ "beat": 40.09,
+ "midi": 74,
+ "duration": 7.5,
+ "velocity": 0.3787869536057115
+ },
+ {
+ "beat": 48,
+ "midi": 62,
+ "duration": 7.5,
+ "velocity": 0.5097104608826339
+ },
+ {
+ "beat": 48.045,
+ "midi": 66,
+ "duration": 7.5,
+ "velocity": 0.4887416532775387
+ },
+ {
+ "beat": 48.09,
+ "midi": 71,
+ "duration": 7.5,
+ "velocity": 0.4663905056659132
+ },
+ {
+ "beat": 56,
+ "midi": 64,
+ "duration": 7.5,
+ "velocity": 0.47987989383284
+ },
+ {
+ "beat": 56.045,
+ "midi": 69,
+ "duration": 7.5,
+ "velocity": 0.4905236521502957
+ },
+ {
+ "beat": 56.09,
+ "midi": 73,
+ "duration": 7.5,
+ "velocity": 0.5169125688262284
+ },
+ {
+ "beat": 64,
+ "midi": 69,
+ "duration": 7.5,
+ "velocity": 0.36891332033276564
+ },
+ {
+ "beat": 64.045,
+ "midi": 73,
+ "duration": 7.5,
+ "velocity": 0.38823245551437147
+ },
+ {
+ "beat": 64.09,
+ "midi": 78,
+ "duration": 7.5,
+ "velocity": 0.3705159105472267
+ }
+ ]
+ },
+ {
+ "id": "bass",
+ "name": "Low tide",
+ "instrument": "bass",
+ "gain": 0.55,
+ "pan": 0,
+ "tone": 1100,
+ "space": 0.02,
+ "release": 0.2,
+ "notes": [
+ {
+ "beat": 32,
+ "midi": 38,
+ "duration": 2.7,
+ "velocity": 0.5659881625939162
+ },
+ {
+ "beat": 36,
+ "midi": 38,
+ "duration": 2.7,
+ "velocity": 0.57739312787354
+ },
+ {
+ "beat": 39,
+ "midi": 38,
+ "duration": 0.75,
+ "velocity": 0.4011168014382943
+ },
+ {
+ "beat": 40,
+ "midi": 35,
+ "duration": 2.7,
+ "velocity": 0.5901264471597971
+ },
+ {
+ "beat": 44,
+ "midi": 35,
+ "duration": 2.7,
+ "velocity": 0.5557340490985663
+ },
+ {
+ "beat": 47,
+ "midi": 35,
+ "duration": 0.75,
+ "velocity": 0.38950243089739234
+ },
+ {
+ "beat": 48,
+ "midi": 31,
+ "duration": 2.7,
+ "velocity": 0.7510273775272072
+ },
+ {
+ "beat": 52,
+ "midi": 31,
+ "duration": 2.7,
+ "velocity": 0.7463892952236347
+ },
+ {
+ "beat": 55,
+ "midi": 31,
+ "duration": 0.75,
+ "velocity": 0.4253533074991777
+ },
+ {
+ "beat": 56,
+ "midi": 33,
+ "duration": 2.7,
+ "velocity": 0.7061171898711472
+ },
+ {
+ "beat": 60,
+ "midi": 33,
+ "duration": 2.7,
+ "velocity": 0.7267716949526222
+ },
+ {
+ "beat": 63,
+ "midi": 33,
+ "duration": 0.75,
+ "velocity": 0.40719077550172805
+ },
+ {
+ "beat": 64,
+ "midi": 38,
+ "duration": 2.7,
+ "velocity": 0.5554849594887347
+ },
+ {
+ "beat": 68,
+ "midi": 38,
+ "duration": 2.7,
+ "velocity": 0.6220494564995172
+ },
+ {
+ "beat": 71,
+ "midi": 38,
+ "duration": 0.75,
+ "velocity": 0.39888761456049976
+ }
+ ]
+ },
+ {
+ "id": "pulse",
+ "name": "Soft pulse",
+ "instrument": "drums",
+ "gain": 0.4,
+ "pan": 0.04,
+ "tone": 12000,
+ "space": 0.06,
+ "release": 0.05,
+ "notes": [
+ {
+ "beat": 32,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.6424152635859326
+ },
+ {
+ "beat": 34.5,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.38359787704553455
+ },
+ {
+ "beat": 34,
+ "midi": 38,
+ "duration": 0.12,
+ "velocity": 0.267568149670586
+ },
+ {
+ "beat": 32.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.26824469596356154
+ },
+ {
+ "beat": 33,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.15431948463171724
+ },
+ {
+ "beat": 33.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.2763720994761586
+ },
+ {
+ "beat": 34,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.16475707195252184
+ },
+ {
+ "beat": 34.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.28171498903155323
+ },
+ {
+ "beat": 35,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.14896126154810194
+ },
+ {
+ "beat": 35.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.28008688166856766
+ },
+ {
+ "beat": 36,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.6103359449379147
+ },
+ {
+ "beat": 38.5,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.34600719700139015
+ },
+ {
+ "beat": 38,
+ "midi": 38,
+ "duration": 0.12,
+ "velocity": 0.2577655539680273
+ },
+ {
+ "beat": 36.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.2911793159544468
+ },
+ {
+ "beat": 37,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.16618706753551965
+ },
+ {
+ "beat": 37.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.28155436441898346
+ },
+ {
+ "beat": 38,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.14951299550086264
+ },
+ {
+ "beat": 38.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.292978693215251
+ },
+ {
+ "beat": 39,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.16493001419603828
+ },
+ {
+ "beat": 39.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.29935998227208854
+ },
+ {
+ "beat": 40,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.6227911817951128
+ },
+ {
+ "beat": 42.5,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.36319101423379035
+ },
+ {
+ "beat": 42,
+ "midi": 38,
+ "duration": 0.12,
+ "velocity": 0.2674223409183324
+ },
+ {
+ "beat": 40.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.26885269566714765
+ },
+ {
+ "beat": 41,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.14842683670371776
+ },
+ {
+ "beat": 41.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.2900981490164995
+ },
+ {
+ "beat": 42,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.15013547391891482
+ },
+ {
+ "beat": 42.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.2782903241148591
+ },
+ {
+ "beat": 43,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.15549137902855878
+ },
+ {
+ "beat": 43.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.2657426358997822
+ },
+ {
+ "beat": 44,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.6385968701584264
+ },
+ {
+ "beat": 46.5,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.36781779395164926
+ },
+ {
+ "beat": 46,
+ "midi": 38,
+ "duration": 0.12,
+ "velocity": 0.2688600487709046
+ },
+ {
+ "beat": 44.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.2920743362617492
+ },
+ {
+ "beat": 45,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.1564018059819937
+ },
+ {
+ "beat": 45.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.29019289072751997
+ },
+ {
+ "beat": 46,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.1639803674280644
+ },
+ {
+ "beat": 46.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.2896591020476818
+ },
+ {
+ "beat": 47,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.15562188003957275
+ },
+ {
+ "beat": 47.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.26665342630863187
+ },
+ {
+ "beat": 48,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.6012453261822462
+ },
+ {
+ "beat": 50.5,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.38347316287420685
+ },
+ {
+ "beat": 50,
+ "midi": 38,
+ "duration": 0.12,
+ "velocity": 0.29083676083944743
+ },
+ {
+ "beat": 48.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.362990914780274
+ },
+ {
+ "beat": 49,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.20171330443397167
+ },
+ {
+ "beat": 49.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.37419263635911043
+ },
+ {
+ "beat": 50,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.19364401854574684
+ },
+ {
+ "beat": 50.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.33881614779643715
+ },
+ {
+ "beat": 51,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.20576345479860905
+ },
+ {
+ "beat": 51.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.3669487734172493
+ },
+ {
+ "beat": 52,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.6033834156412632
+ },
+ {
+ "beat": 54.5,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.3822028408040293
+ },
+ {
+ "beat": 54,
+ "midi": 38,
+ "duration": 0.12,
+ "velocity": 0.28975858010537925
+ },
+ {
+ "beat": 52.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.33262176410481337
+ },
+ {
+ "beat": 53,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.18739120012894273
+ },
+ {
+ "beat": 53.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.3531498343728483
+ },
+ {
+ "beat": 54,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.18867628381773832
+ },
+ {
+ "beat": 54.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.3518502222105861
+ },
+ {
+ "beat": 55,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.18627944037877026
+ },
+ {
+ "beat": 55.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.37059383017010983
+ },
+ {
+ "beat": 56,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.5981210666202008
+ },
+ {
+ "beat": 58.5,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.3652888320416212
+ },
+ {
+ "beat": 58,
+ "midi": 38,
+ "duration": 0.12,
+ "velocity": 0.2608478527460248
+ },
+ {
+ "beat": 56.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.3562542293228209
+ },
+ {
+ "beat": 57,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.2005892051476985
+ },
+ {
+ "beat": 57.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.3535288679033518
+ },
+ {
+ "beat": 58,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.195253765989095
+ },
+ {
+ "beat": 58.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.373120148422569
+ },
+ {
+ "beat": 59,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.18732341896370056
+ },
+ {
+ "beat": 59.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.35690220285505053
+ },
+ {
+ "beat": 60,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.6422965398216621
+ },
+ {
+ "beat": 62.5,
+ "midi": 36,
+ "duration": 0.15,
+ "velocity": 0.3682552629672923
+ },
+ {
+ "beat": 62,
+ "midi": 38,
+ "duration": 0.12,
+ "velocity": 0.28541103162653747
+ },
+ {
+ "beat": 60.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.3713737545859069
+ },
+ {
+ "beat": 61,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.19733027558587493
+ },
+ {
+ "beat": 61.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.3499408989116549
+ },
+ {
+ "beat": 62,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.20693535734713078
+ },
+ {
+ "beat": 62.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.3483866785850376
+ },
+ {
+ "beat": 63,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.20023711827024818
+ },
+ {
+ "beat": 63.5,
+ "midi": 42,
+ "duration": 0.08,
+ "velocity": 0.34467739011459053
+ }
+ ]
+ }
+ ],
+ "assets": []
+}
diff --git a/store/agents/music-studio/template/studio/app.js b/store/agents/music-studio/template/studio/app.js
new file mode 100644
index 000000000..db3c59144
--- /dev/null
+++ b/store/agents/music-studio/template/studio/app.js
@@ -0,0 +1,239 @@
+const $ = selector => document.querySelector(selector), colors = ['#eabe90', '#b9acf1', '#8bc9ba', '#98bce8', '#dc9caa', '#cad990'];
+const original = validateSession(JSON.parse($('#afterhours-data').textContent)), storageKey = 'afterhours:' + original.id;
+let project = structuredClone(original), selectedTrack = 0, selectedNote = -1, selectedClip = 0, windowBar = 0, undoStack = [], redoStack = [], pendingDraft, preserveDraft = false;
+let mix, mixRevision = -1, revision = 0, renderPromise, renderTimer, playback, audioContext, startedAt = 0, seekSeconds = 0, toastTimer, noteRects = [], pianoBounds;
+const state = () => ({ project: structuredClone(project), selectedTrack, windowBar });
+const track = () => project.tracks[selectedTrack];
+const duration = () => secondsAt(project, project.beats) + (project.tail ?? 1.5);
+const clock = value => { const seconds = Math.floor(Math.max(0, value) + .001); return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; };
+function toast(message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 6000); }
+function parentMessage(type, extra = {}) { if (parent !== window) parent.postMessage({ type, ...extra }, '*'); }
+function persist() {
+ if (preserveDraft) return;
+ try { localStorage.setItem(storageKey, JSON.stringify({ baseRevision: original.revision, ...state() })); $('#draft-status').textContent = 'Draft saved on this device'; }
+ catch { $('#draft-status').textContent = 'Save project to keep your recordings'; }
+}
+function stop() { if (playback) { playback.onended = null; playback.stop(); playback.disconnect(); playback = null; } $('#play').textContent = '▶ Play'; $('#play').setAttribute('aria-label', 'Play'); }
+function change(mutate, { rebuild = true } = {}) {
+ const previous = state();
+ try { mutate(); project = validateSession(project); }
+ catch (error) { project = previous.project; selectedTrack = previous.selectedTrack; toast(error.message); buildUI(); return; }
+ undoStack.push(previous); if (undoStack.length > 16) undoStack.shift(); redoStack = [];
+ stop(); revision++; mixRevision = -1; selectedNote = Math.min(selectedNote, track().notes.length - 1);
+ if (rebuild) buildUI(); else updateLabels(); persist(); scheduleMix();
+}
+function restore(saved) { stop(); project = validateSession(saved.project); selectedTrack = Math.min(saved.selectedTrack || 0, project.tracks.length - 1); windowBar = saved.windowBar || 0; selectedNote = -1; revision++; mixRevision = -1; buildUI(); persist(); scheduleMix(); }
+function saveFile(name, content, type = 'application/octet-stream') { const blob = content instanceof Blob ? content : new Blob([content], { type }), url = URL.createObjectURL(blob), a = document.createElement('a'); a.href = url; a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(url), 30000); }
+function canvasContext(canvas) {
+ const box = canvas.getBoundingClientRect(), ratio = Math.min(devicePixelRatio || 1, 2), w = Math.max(1, Math.round(box.width)), h = Math.max(1, Math.round(box.height));
+ if (canvas.width !== Math.round(w * ratio) || canvas.height !== Math.round(h * ratio)) { canvas.width = Math.round(w * ratio); canvas.height = Math.round(h * ratio); }
+ const ctx = canvas.getContext('2d'); ctx.setTransform(ratio, 0, 0, ratio, 0, 0); ctx.clearRect(0, 0, w, h); return { ctx, w, h };
+}
+function updateLabels() {
+ $('#title').textContent = project.title; document.title = project.title + ' · Afterhours'; $('#brief').textContent = project.brief;
+ $('#tempo').value = Number(project.tempo.toFixed(3)); $('#bars').value = Math.ceil(project.beats / beatsPerBar(project)); $('#meter').textContent = project.meter.join(' / ');
+ $('#gain-label').value = `${Math.round(track().gain * 100)}%`; $('#pan-label').value = track().pan === 0 ? 'Center' : `${Math.round(Math.abs(track().pan) * 100)}% ${track().pan < 0 ? 'left' : 'right'}`;
+ $('#undo').disabled = !undoStack.length; $('#redo').disabled = !redoStack.length;
+ $('#mute').setAttribute('aria-pressed', track().muted); $('#solo').setAttribute('aria-pressed', track().solo);
+}
+function buildUI() {
+ selectedTrack = Math.min(selectedTrack, project.tracks.length - 1);
+ windowBar = Math.max(0, Math.min(windowBar, Math.max(0, Math.ceil(project.beats / beatsPerBar(project)) - 1)));
+ updateLabels();
+ $('#tracks').replaceChildren(); $('#sections').replaceChildren();
+ project.sections.forEach((s, i) => { const div = document.createElement('div'); div.className = 'section'; div.textContent = s.name; div.style.left = `${s.beat / project.beats * 100}%`; div.style.width = `${s.length / project.beats * 100}%`; div.style.color = colors[i % colors.length]; $('#sections').append(div); });
+ project.tracks.forEach((t, i) => {
+ const row = document.createElement('div'), info = document.createElement('div'), name = document.createElement('button'), mute = document.createElement('button'), solo = document.createElement('button'), canvas = document.createElement('canvas');
+ row.className = 'track' + (selectedTrack === i ? ' selected' : ''); info.className = 'track-info'; name.className = 'track-name'; name.textContent = t.name; name.title = t.name; name.style.color = colors[i % colors.length];
+ name.onclick = () => { selectedTrack = i; selectedNote = -1; selectedClip = 0; buildUI(); };
+ mute.className = solo.className = 'mini'; mute.textContent = 'M'; solo.textContent = 'S'; mute.setAttribute('aria-label', `Mute ${t.name}`); solo.setAttribute('aria-label', `Solo ${t.name}`); mute.setAttribute('aria-pressed', t.muted); solo.setAttribute('aria-pressed', t.solo);
+ mute.onclick = () => change(() => { t.muted = !t.muted; }); solo.onclick = () => change(() => { t.solo = !t.solo; });
+ canvas.dataset.track = i; canvas.setAttribute('aria-label', t.name + ' arrangement'); canvas.onclick = event => { selectedTrack = i; selectedNote = -1; const box = canvas.getBoundingClientRect(); seekSeconds = secondsAt(project, Math.max(0, Math.min(project.beats, (event.clientX - box.left) / box.width * project.beats))); stop(); buildUI(); };
+ info.append(name, mute, solo); row.append(info, canvas); $('#tracks').append(row);
+ });
+ $('#track-name').value = track().name;
+ $('#instrument').replaceChildren();
+ for (const [key, label] of Object.entries(instruments)) { if (key === 'sampler' && !project.assets.length || key === 'audio' && track().instrument !== 'audio') continue; const option = document.createElement('option'); option.value = key; option.textContent = label; $('#instrument').append(option); }
+ $('#instrument').value = track().instrument;
+ for (const name of ['gain', 'pan', 'attack', 'release', 'tone', 'space', 'delay']) $('#' + name).value = track()[name];
+ $('#master').value = project.master; $('#sampler-controls').hidden = track().instrument !== 'sampler'; $('#sample-id').replaceChildren();
+ for (const asset of project.assets) { const option = document.createElement('option'); option.value = asset.id; option.textContent = asset.name; $('#sample-id').append(option); }
+ $('#sample-id').value = track().sampleId || project.assets[0]?.id || ''; $('#sample-root').value = noteName(track().sampleRoot);
+ $('#clip-controls').hidden = !track().clips.length;
+ selectedClip = Math.max(0, Math.min(selectedClip, track().clips.length - 1)); $('#clip-select').replaceChildren();
+ track().clips.forEach((c, i) => { const option = document.createElement('option'); option.value = i; option.textContent = `${i + 1}. ${project.assets.find(a => a.id === c.assetId)?.name || 'Recording'} · beat ${c.beat}`; $('#clip-select').append(option); });
+ $('#clip-select').value = selectedClip;
+ if (track().clips[selectedClip]) for (const [id, key] of [['clip-beat', 'beat'], ['clip-offset', 'offset'], ['clip-duration', 'duration']]) $('#' + id).value = track().clips[selectedClip][key];
+ $('#remove-track').disabled = project.tracks.length === 1;
+ updateNote(); requestAnimationFrame(drawAll);
+}
+function drawArrangement() {
+ const beat = beatAt(project, playback ? Math.max(0, audioContext.currentTime - startedAt) : seekSeconds);
+ for (const canvas of document.querySelectorAll('#tracks canvas')) {
+ const i = Number(canvas.dataset.track), t = project.tracks[i], { ctx, w, h } = canvasContext(canvas), unit = w / project.beats;
+ ctx.strokeStyle = '#ffffff09'; ctx.lineWidth = 1;
+ for (let b = 0; b <= project.beats; b += beatsPerBar(project)) { ctx.beginPath(); ctx.moveTo(b * unit + .5, 0); ctx.lineTo(b * unit + .5, h); ctx.stroke(); }
+ ctx.fillStyle = colors[i % colors.length]; ctx.globalAlpha = t.muted ? .18 : .75;
+ for (const n of t.notes) ctx.fillRect(n.beat * unit, 6 + (1 - (n.midi % 36) / 36) * (h - 15), Math.max(2, n.duration * unit - 1), 3);
+ for (const clip of t.clips) { const x = clip.beat * unit, width = (beatAt(project, secondsAt(project, clip.beat) + clip.duration) - clip.beat) * unit; ctx.globalAlpha = .24; ctx.fillRect(x, 6, width, h - 12); ctx.globalAlpha = .85; ctx.font = '9px sans-serif'; ctx.save(); ctx.beginPath(); ctx.rect(x + 4, 4, Math.max(0, width - 8), h - 8); ctx.clip(); ctx.fillText(project.assets.find(a => a.id === clip.assetId)?.name || 'Recording', x + 6, h / 2 + 3); ctx.restore(); }
+ ctx.globalAlpha = 1; ctx.fillStyle = '#f8e5ca'; ctx.fillRect(Math.min(w - 1, beat * unit), 0, 1, h);
+ }
+}
+function drawPiano() {
+ const { ctx, w, h } = canvasContext($('#piano')), bar = beatsPerBar(project), start = windowBar * bar, span = Math.min(8 * bar, project.beats - start), labelWidth = 37;
+ const notes = track().notes, lowest = Math.min(...notes.map(n => n.midi), 60), highest = Math.max(...notes.map(n => n.midi), 72);
+ const low = Math.max(0, Math.floor(lowest / 12) * 12 - 3), high = Math.min(127, Math.max(low + 24, highest + 4)), rows = high - low + 1, rowHeight = (h - 24) / rows, unit = (w - labelWidth) / Math.max(span, 1);
+ pianoBounds = { w, h, low, high, rows, rowHeight, unit, start, span, labelWidth }; noteRects = [];
+ for (let midi = low; midi <= high; midi++) {
+ const y = 24 + (high - midi) * rowHeight; ctx.fillStyle = [1, 3, 6, 8, 10].includes(midi % 12) ? '#ffffff02' : '#ffffff06'; ctx.fillRect(labelWidth, y, w - labelWidth, rowHeight - .5);
+ if (midi % 12 === 0) { ctx.fillStyle = '#737d94'; ctx.font = '9px monospace'; ctx.fillText(noteName(midi), 5, y + rowHeight); }
+ }
+ for (let beat = 0; beat <= span; beat += 4 / project.meter[1]) { const x = labelWidth + beat * unit, major = Math.abs(beat / bar - Math.round(beat / bar)) < .0001; ctx.strokeStyle = major ? '#ffffff24' : '#ffffff09'; ctx.beginPath(); ctx.moveTo(x + .5, 24); ctx.lineTo(x + .5, h); ctx.stroke(); if (major) { ctx.fillStyle = '#838da2'; ctx.font = '9px monospace'; ctx.fillText(String(Math.round((start + beat) / bar) + 1), x + 4, 15); } }
+ notes.forEach((n, i) => {
+ if (n.beat + n.duration <= start || n.beat >= start + span) return;
+ const x = labelWidth + Math.max(0, n.beat - start) * unit, y = 24 + (high - n.midi) * rowHeight + 1, width = Math.max(3, (Math.min(start + span, n.beat + n.duration) - Math.max(start, n.beat)) * unit - 1);
+ ctx.globalAlpha = .4 + n.velocity * .6; ctx.fillStyle = i === selectedNote ? '#fff4df' : colors[selectedTrack % colors.length]; ctx.fillRect(x, y, width, Math.max(2, rowHeight - 2)); ctx.globalAlpha = 1;
+ noteRects.push({ index: i, x, y, width, height: Math.max(3, rowHeight) });
+ });
+ $('#bar-window').textContent = `${windowBar + 1}–${Math.ceil((start + span) / bar)}`; $('#previous-bars').disabled = windowBar === 0; $('#next-bars').disabled = start + span >= project.beats;
+ $('#piano-title').textContent = track().name + (track().instrument === 'audio' ? ' · recording' : ' · notes');
+}
+function drawWave() {
+ const { ctx, w, h } = canvasContext($('#waveform'));
+ if (mix) {
+ for (let channel = 0; channel < 2; channel++) {
+ const samples = mix.channels[channel], stride = Math.max(1, Math.floor(samples.length / w)), center = h * (channel ? .75 : .25);
+ ctx.strokeStyle = channel ? '#b9acf1' : '#eabe90'; ctx.lineWidth = 1;
+ ctx.beginPath();
+ for (let x = 0; x < w; x++) { let peak = 0; for (let j = x * stride; j < Math.min(samples.length, (x + 1) * stride); j += Math.max(1, Math.floor(stride / 24))) peak = Math.max(peak, Math.abs(samples[j])); const length = peak * mix.gain * h * .24; ctx.moveTo(x, center - Math.max(.5, length)); ctx.lineTo(x, center + Math.max(.5, length)); }
+ ctx.stroke();
+ }
+ }
+ const current = playback ? Math.min(duration(), Math.max(0, audioContext.currentTime - startedAt)) : Math.min(duration(), seekSeconds);
+ ctx.fillStyle = '#ffffffb3'; ctx.fillRect(current / duration() * w, 0, 1, h); $('#time').textContent = clock(current) + ' / ' + clock(duration());
+}
+function drawAll() { drawArrangement(); drawPiano(); drawWave(); }
+function updateNote() {
+ const n = track().notes[selectedNote];
+ for (const id of ['note-pitch', 'note-start', 'note-velocity']) $('#' + id).disabled = !n;
+ $('#delete-note').disabled = !n;
+ if (n) { $('#note-pitch').value = noteName(n.midi); $('#note-start').value = Number(n.beat.toFixed(4)); $('#note-length').value = Number(n.duration.toFixed(4)); $('#note-velocity').value = n.velocity; }
+}
+async function ensureMix() {
+ if (mixRevision === revision && mix) return mix;
+ if (renderPromise?.revision === revision) return renderPromise.promise;
+ const current = revision, candidate = structuredClone(project);
+ $('#audio-status').textContent = 'Rendering your arrangement…'; $('#error').hidden = true;
+ $('#play').disabled = $('#export-wav').disabled = $('#export-stems').disabled = true;
+ const promise = renderSession(candidate).then(result => {
+ if (current !== revision) return result;
+ mix = result; mixRevision = current;
+ $('#audio-status').textContent = activeTracks(project).length + ' tracks · ready to play';
+ $('#level').textContent = `PEAK ${result.peak > 0 ? (20 * Math.log10(result.peak)).toFixed(1) : '−∞'} dBFS / 48 kHz`;
+ $('#play').disabled = $('#export-wav').disabled = $('#export-stems').disabled = false;
+ document.body.dataset.ready = 'true'; parentMessage('harness:ready'); drawWave(); return result;
+ }).catch(error => {
+ if (current === revision) { $('#error').textContent = error.message; $('#error').hidden = false; $('#audio-status').textContent = 'A track needs attention'; parentMessage('harness:error', { message: error.message }); }
+ throw error;
+ });
+ renderPromise = { revision: current, promise }; return promise;
+}
+function scheduleMix() { $('#play').disabled = $('#export-wav').disabled = $('#export-stems').disabled = true; clearTimeout(renderTimer); renderTimer = setTimeout(() => ensureMix().catch(() => {}), 240); }
+function guard(task) { return async (...args) => { try { await task(...args); } catch (error) { toast(error.message || String(error)); } }; }
+async function play() {
+ if (playback) { seekSeconds = audioContext.currentTime - startedAt; stop(); return; }
+ const current = revision, rendered = await ensureMix(); if (current !== revision) return;
+ audioContext ??= new AudioContext(); await audioContext.resume();
+ const source = audioContext.createBufferSource(), gain = audioContext.createGain(); source.buffer = rendered.buffer; gain.gain.value = rendered.gain; source.connect(gain); gain.connect(audioContext.destination);
+ if (seekSeconds >= rendered.duration - .05) seekSeconds = 0;
+ startedAt = audioContext.currentTime - seekSeconds; source.start(0, seekSeconds); playback = source;
+ $('#play').textContent = 'Ⅱ Pause'; $('#play').setAttribute('aria-label', 'Pause');
+ source.onended = () => { if (playback === source) { playback = null; seekSeconds = 0; $('#play').textContent = '▶ Play'; $('#play').setAttribute('aria-label', 'Play'); } };
+}
+$('#play').onclick = guard(play); $('#stop').onclick = () => { stop(); seekSeconds = 0; drawAll(); };
+$('#waveform').onclick = guard(async event => { const wasPlaying = !!playback, box = $('#waveform').getBoundingClientRect(); stop(); seekSeconds = Math.max(0, Math.min(duration() - .02, (event.clientX - box.left) / box.width * duration())); if (wasPlaying) await play(); drawAll(); });
+let drag;
+$('#piano').onpointerdown = event => {
+ if (!event.isPrimary || event.button !== 0) return;
+ if (track().instrument === 'audio') { toast('Use the recording controls to move or trim this clip.'); return; }
+ const box = $('#piano').getBoundingClientRect(), x = event.clientX - box.left, y = event.clientY - box.top, hit = noteRects.find(r => x >= r.x && x <= r.x + r.width && y >= r.y && y <= r.y + r.height);
+ if (hit) {
+ selectedNote = hit.index; drag = { x, y, previous: state(), note: { ...track().notes[selectedNote] }, moved: false }; $('#piano').setPointerCapture(event.pointerId); updateNote(); drawPiano();
+ } else if (x > pianoBounds.labelWidth && y > 24) {
+ const beat = Math.round((pianoBounds.start + (x - pianoBounds.labelWidth) / pianoBounds.unit) * 4) / 4, midi = Math.max(0, Math.min(127, pianoBounds.high - Math.floor((y - 24) / pianoBounds.rowHeight))), length = Math.max(.125, Number($('#note-length').value) || 1);
+ if (beat >= project.beats) return;
+ change(() => { track().notes.push({ beat, midi, duration: Math.min(length, project.beats - beat), velocity: Number($('#note-velocity').value) || .75 }); selectedNote = track().notes.length - 1; });
+ }
+};
+$('#piano').onpointermove = event => {
+ if (!drag) return;
+ const box = $('#piano').getBoundingClientRect(), dx = event.clientX - box.left - drag.x, dy = event.clientY - box.top - drag.y;
+ if (!drag.moved && Math.abs(dx) + Math.abs(dy) < 4) return;
+ drag.moved = true; stop(); const n = track().notes[selectedNote];
+ n.beat = Math.max(0, Math.min(project.beats - n.duration, Math.round((drag.note.beat + dx / pianoBounds.unit) * 4) / 4));
+ n.midi = Math.max(0, Math.min(127, drag.note.midi - Math.round(dy / pianoBounds.rowHeight))); updateNote(); drawPiano(); drawArrangement();
+};
+function endDrag() { if (drag?.moved) { undoStack.push(drag.previous); if (undoStack.length > 16) undoStack.shift(); redoStack = []; revision++; mixRevision = -1; persist(); scheduleMix(); updateLabels(); } drag = null; }
+$('#piano').onpointerup = endDrag; $('#piano').onpointercancel = endDrag;
+for (const [id, key, parse] of [['note-pitch', 'midi', noteNumber], ['note-start', 'beat', Number], ['note-length', 'duration', Number], ['note-velocity', 'velocity', Number]]) $('#' + id).onchange = () => { if (selectedNote < 0) return; change(() => { track().notes[selectedNote][key] = parse($('#' + id).value); }); };
+$('#delete-note').onclick = () => { if (selectedNote >= 0) change(() => { track().notes.splice(selectedNote, 1); selectedNote = -1; }); };
+$('#previous-bars').onclick = () => { windowBar = Math.max(0, windowBar - 8); drawPiano(); }; $('#next-bars').onclick = () => { windowBar += 8; drawPiano(); };
+$('#duplicate-section').onclick = () => change(() => { const start = windowBar * beatsPerBar(project), length = Math.min(8 * beatsPerBar(project), project.beats - start); project = duplicateSection(project, start, length); windowBar = Math.floor((project.beats - length) / beatsPerBar(project)); });
+$('#track-name').onchange = () => change(() => { track().name = $('#track-name').value.trim() || 'Instrument'; });
+$('#instrument').onchange = () => change(() => { track().instrument = $('#instrument').value; delete track().midiProgram; if (track().instrument === 'sampler') track().sampleId = project.assets[0]?.id; });
+for (const key of ['gain', 'pan', 'attack', 'release', 'tone', 'space', 'delay']) $('#' + key).onchange = () => change(() => { track()[key] = Number($('#' + key).value); });
+$('#mute').onclick = () => change(() => { track().muted = !track().muted; }); $('#solo').onclick = () => change(() => { track().solo = !track().solo; });
+$('#master').onchange = () => change(() => { project.master = Number($('#master').value); });
+$('#tempo').onchange = () => change(() => { const ratio = Number($('#tempo').value) / project.tempo; project.tempos.forEach(t => { t.bpm *= ratio; }); project.tempo = project.tempos[0].bpm; });
+$('#bars').onchange = () => change(() => { const beats = Number($('#bars').value) * beatsPerBar(project); if (project.tracks.some(t => t.notes.some(n => n.beat + n.duration > beats) || t.clips.some(c => secondsAt(project, c.beat) + c.duration > secondsAt(project, beats)))) throw new Error('Move or shorten the ending notes and recordings before reducing the arrangement.'); project.beats = beats; project.sections = project.sections.filter(s => s.beat < beats).map(s => ({ ...s, length: Math.min(s.length, beats - s.beat) })); project.tempos = project.tempos.filter(t => t.beat < beats); });
+$('#sample-id').onchange = () => change(() => { track().sampleId = $('#sample-id').value; }); $('#sample-root').onchange = () => change(() => { track().sampleRoot = noteNumber($('#sample-root').value); });
+$('#clip-select').onchange = () => { selectedClip = Number($('#clip-select').value); buildUI(); };
+for (const [id, key] of [['clip-beat', 'beat'], ['clip-offset', 'offset'], ['clip-duration', 'duration']]) $('#' + id).onchange = () => change(() => { const clip = track().clips[selectedClip]; clip[key] = Number($('#' + id).value); const end = beatAt(project, secondsAt(project, clip.beat) + clip.duration); project.beats = Math.max(project.beats, Math.ceil(end / beatsPerBar(project)) * beatsPerBar(project)); });
+for (const [id, delta] of [['transpose-down', -12], ['transpose-up', 12]]) $('#' + id).onclick = () => change(() => { track().notes.forEach(n => { n.midi += delta; }); });
+$('#add-track').onclick = () => change(() => { project.tracks.push({ id: 'instrument-' + Date.now(), name: 'Your instrument', instrument: 'felt', notes: [], clips: [] }); selectedTrack = project.tracks.length - 1; selectedNote = -1; });
+$('#remove-track').onclick = () => { if (project.tracks.length > 1) change(() => { project.tracks.splice(selectedTrack, 1); selectedTrack = Math.min(selectedTrack, project.tracks.length - 1); selectedNote = -1; }); };
+$('#undo').onclick = () => { if (undoStack.length) { redoStack.push(state()); restore(undoStack.pop()); } }; $('#redo').onclick = () => { if (redoStack.length) { undoStack.push(state()); restore(redoStack.pop()); } };
+$('#reset-project').onclick = () => change(() => { project = structuredClone(original); selectedTrack = 0; selectedNote = -1; windowBar = 0; });
+$('#save-project').onclick = () => saveFile(filename(project.title) + '.afterhours.json', JSON.stringify(project, null, 2), 'application/json');
+$('#open-project').onclick = () => $('#project-file').click(); $('#open-midi').onclick = () => $('#midi-file').click(); $('#import-audio').onclick = () => $('#audio-file').click();
+$('#project-file').onchange = guard(async () => { const file = $('#project-file').files[0]; if (!file) return; if (file.size > 28000000) throw new Error('Project exceeds 28 MB.'); const p = validateSession(JSON.parse(await file.text())); change(() => { project = p; selectedTrack = 0; selectedNote = -1; windowBar = 0; }); $('#project-file').value = ''; });
+$('#midi-file').onchange = guard(async () => { const file = $('#midi-file').files[0]; if (!file) return; if (file.size > 4000000) throw new Error('MIDI file exceeds 4 MB.'); const p = readSessionMidi(new Uint8Array(await file.arrayBuffer()), Midi); change(() => { project = p; selectedTrack = 0; selectedNote = -1; windowBar = 0; }); $('#midi-file').value = ''; toast(p.importWarnings.length ? p.importWarnings[0] : 'Your notes and tempo changes are ready to arrange.'); });
+$('#audio-file').onchange = guard(async () => {
+ const file = $('#audio-file').files[0]; if (!file) return; if (file.size > 18000000) throw new Error('Use a recording under 18 MB. A longer recording can be imported as MP3.');
+ const context = new OfflineAudioContext(1, 1, 48000), buffer = await context.decodeAudioData(await file.arrayBuffer());
+ if (buffer.duration > 240) throw new Error('Trim the recording to four minutes or less.');
+ const data = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(file); });
+ change(() => {
+ const id = 'recording-' + Date.now(); project.assets.push({ id, name: file.name, data });
+ project.beats = Math.max(project.beats, Math.ceil(beatAt(project, buffer.duration) / beatsPerBar(project)) * beatsPerBar(project));
+ project.tracks.push({ id, name: file.name.slice(0, 120), instrument: 'audio', gain: 1, tone: 20000, space: 0, notes: [], clips: [{ assetId: id, beat: 0, offset: 0, duration: buffer.duration, gain: 1, fadeIn: .02, fadeOut: .05 }] });
+ selectedTrack = project.tracks.length - 1; selectedNote = -1;
+ }); $('#audio-file').value = ''; toast('Your recording is in the arrangement. Move or trim it in the track controls.');
+});
+$('#export-wav').onclick = guard(async () => { const current = revision, result = await ensureMix(); if (current !== revision) throw new Error('The piece changed during export. Export the new version when it is ready.'); saveFile(filename(project.title) + '.wav', wavBytes(result.channels, result.sampleRate, result.gain), 'audio/wav'); });
+$('#export-midi').onclick = guard(async () => { saveFile(filename(project.title) + '.mid', writeSessionMidi(project, Midi), 'audio/midi'); toast('Editable notes and tempo exported. Your recorded audio stays in the WAV stems and project.'); });
+async function stemFiles() {
+ const candidate = structuredClone(project), result = await renderSession(candidate), audible = activeTracks(candidate);
+ if (audible.length * result.buffer.length * 4 > 512000000) throw new Error('This stem bundle exceeds 512 MB. Solo a smaller group of tracks and export in groups.');
+ const files = [['mix.wav', wavBytes(result.channels, result.sampleRate, result.gain)], ['composition.mid', writeSessionMidi(candidate, Midi)], ['project.afterhours.json', JSON.stringify(candidate, null, 2)]];
+ const report = { title: candidate.title, sampleRate: result.sampleRate, channels: 2, bitDepth: 16, duration: result.duration, commonGain: result.gain, peak: result.peak, stems: [] };
+ for (let i = 0; i < audible.length; i++) {
+ const t = audible[i], rendered = await renderSession(candidate, { onlyTrack: t.id }), name = `${String(i + 1).padStart(2, '0')}-${filename(t.name)}.wav`;
+ files.push(['stems/' + name, wavBytes(rendered.channels, rendered.sampleRate, result.gain)]); report.stems.push({ file: name, track: t.id, name: t.name });
+ }
+ files.push(['delivery.json', JSON.stringify(report, null, 2)], ['README.txt', `${candidate.title}\n\n${candidate.brief}\n\nDrag every WAV stem to time zero in your DAW. All stems share length, sample rate and mix gain. They contain the audible tracks at export time, including per-track effects. MIDI carries all notes and the tempo map, not recordings or audio effects. Synth previews need not sound like your DAW's MIDI instruments. project.afterhours.json preserves your notes, mix and embedded recordings.\n`]);
+ return { files, report };
+}
+$('#export-stems').onclick = guard(async () => { const name = filename(project.title); $('#export-stems').disabled = true; $('#audio-status').textContent = 'Rendering separate tracks…'; try { const { files, report } = await stemFiles(); saveFile(name + '-production.zip', zipFiles(files)); toast(`${report.stems.length} aligned WAV stems, mix, MIDI and editable project exported.`); } finally { $('#export-stems').disabled = false; $('#audio-status').textContent = 'Ready to play'; } });
+$('#export-html').onclick = () => { const doc = document.documentElement.cloneNode(true); doc.querySelector('#afterhours-data').textContent = JSON.stringify(project).replace(/</g, '\\u003c'); doc.querySelector('#revision-notice').hidden = true; doc.querySelector('#error').hidden = true; doc.querySelector('#toast').className = ''; doc.querySelector('body').removeAttribute('data-ready'); saveFile(filename(project.title) + '-studio.html', '<!doctype html>\n' + doc.outerHTML, 'text/html'); };
+$('#use-revision').onclick = () => { preserveDraft = false; $('#revision-notice').hidden = true; persist(); }; $('#keep-draft').onclick = () => { preserveDraft = false; $('#revision-notice').hidden = true; restore(pendingDraft); };
+try { const saved = JSON.parse(localStorage.getItem(storageKey)); if (saved) { saved.project = validateSession(saved.project); if (saved.baseRevision === original.revision) { project = saved.project; selectedTrack = Math.min(saved.selectedTrack || 0, project.tracks.length - 1); windowBar = saved.windowBar || 0; } else { pendingDraft = saved; preserveDraft = true; $('#revision-notice').hidden = false; } } } catch {}
+addEventListener('keydown', event => { if (event.target.closest('input,select,textarea')) return; if (event.code === 'Space') { event.preventDefault(); guard(play)(); } else if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'z') { event.preventDefault(); $('#' + (event.shiftKey ? 'redo' : 'undo')).click(); } else if (['Backspace', 'Delete'].includes(event.key) && event.target === $('#piano')) { event.preventDefault(); $('#delete-note').click(); } });
+new ResizeObserver(drawAll).observe($('.main-panel'));
+function animate() { if (playback) { drawWave(); drawArrangement(); } requestAnimationFrame(animate); }
+window.afterhours = {
+ getProject: () => structuredClone(project), getState: () => ({ playing: !!playback, context: audioContext?.state, selectedTrack, selectedNote, peak: mix?.peak, rms: mix?.rms, duration: mix?.duration, revision, mixRevision }),
+ render: options => renderSession(project, options), midi: () => Array.from(writeSessionMidi(project, Midi)), stemFiles,
+ async deliver() { const result = await ensureMix(), bytes = new Blob([wavBytes(result.channels, result.sampleRate, result.gain)], { type: 'audio/wav' }); const wav = await new Promise(resolve => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.readAsDataURL(bytes); }); return { wav, duration: result.duration, peak: result.peak, rms: result.rms, sampleRate: result.sampleRate, gain: result.gain }; },
+};
+buildUI(); ensureMix().catch(() => {}); animate();
diff --git a/store/agents/music-studio/template/studio/audio.mjs b/store/agents/music-studio/template/studio/audio.mjs
new file mode 100644
index 000000000..616feb43d
--- /dev/null
+++ b/store/agents/music-studio/template/studio/audio.mjs
@@ -0,0 +1,124 @@
+import { secondsAt, musicRandom, activeTracks } from './session.mjs';
+const decoded = new Map();
+async function audioAssets(project, context) {
+ const result = new Map();
+ for (const asset of project.assets) {
+ let buffer = decoded.get(asset.data);
+ if (!buffer) {
+ const binary = atob(asset.data.split(',')[1]), bytes = Uint8Array.from(binary, c => c.charCodeAt(0));
+ try { buffer = await context.decodeAudioData(bytes.buffer); }
+ catch { throw new Error(`Cannot decode ${asset.name}. Use a WAV or MP3 recording.`); }
+ if (buffer.duration > 240) throw new Error(`${asset.name} is longer than four minutes. Trim it before importing.`);
+ if (decoded.size >= 16) decoded.delete(decoded.keys().next().value);
+ decoded.set(asset.data, buffer);
+ }
+ result.set(asset.id, buffer);
+ }
+ return result;
+}
+function noiseBuffer(context, seed, seconds) {
+ const buffer = context.createBuffer(1, Math.ceil(context.sampleRate * seconds), context.sampleRate), data = buffer.getChannelData(0), r = musicRandom(seed);
+ for (let i = 0; i < data.length; i++) data[i] = r() * 2 - 1;
+ return buffer;
+}
+function impulse(context, seed) {
+ const length = Math.round(context.sampleRate * 1.4), buffer = context.createBuffer(2, length, context.sampleRate), r = musicRandom(seed);
+ for (let channel = 0; channel < 2; channel++) { const data = buffer.getChannelData(channel); for (let i = 0; i < length; i++) data[i] = (r() * 2 - 1) * Math.exp(-i / length * 8) * .65; }
+ return buffer;
+}
+function trackBus(context, track, seed) {
+ const filter = context.createBiquadFilter(); filter.type = 'lowpass'; filter.frequency.value = track.tone; filter.Q.value = .45;
+ const volume = context.createGain(); volume.gain.value = track.gain;
+ const pan = context.createStereoPanner(); pan.pan.value = track.pan;
+ filter.connect(volume); volume.connect(pan); pan.connect(context.destination);
+ if (track.space > 0) {
+ const reverb = context.createConvolver(), send = context.createGain(); reverb.buffer = impulse(context, seed + ':room'); send.gain.value = track.space;
+ volume.connect(send); send.connect(reverb); reverb.connect(pan);
+ }
+ if (track.delay > 0) {
+ const delay = context.createDelay(2), feedback = context.createGain(), send = context.createGain();
+ delay.delayTime.value = .31; feedback.gain.value = .28; send.gain.value = track.delay;
+ volume.connect(send); send.connect(delay); delay.connect(feedback); feedback.connect(delay); delay.connect(pan);
+ }
+ return filter;
+}
+function envelope(context, target, time, duration, velocity, attack, release, sustained = false) {
+ const gain = context.createGain(), level = Math.max(.00001, velocity * .32), hold = Math.max(time + attack + .002, time + duration);
+ gain.gain.setValueAtTime(.00001, time);
+ gain.gain.exponentialRampToValueAtTime(level, time + attack);
+ if (sustained) gain.gain.linearRampToValueAtTime(level * .75, hold);
+ else gain.gain.exponentialRampToValueAtTime(Math.max(.00001, level * .24), hold);
+ gain.gain.exponentialRampToValueAtTime(.00001, hold + release);
+ gain.connect(target); return { gain, end: hold + release + .01 };
+}
+function synthNote(context, target, track, note, time, duration, seed, assets) {
+ const f = 440 * 2 ** ((note.midi - 69) / 12), kind = track.instrument, key = `${seed}:${note.beat}:${note.midi}`;
+ if (note.velocity <= 0) return;
+ if (kind === 'drums') {
+ const gain = context.createGain(); gain.connect(target);
+ if ([35, 36].includes(note.midi)) {
+ const osc = context.createOscillator(); osc.frequency.setValueAtTime(150, time); osc.frequency.exponentialRampToValueAtTime(44, time + .16);
+ gain.gain.setValueAtTime(.00001, time); gain.gain.exponentialRampToValueAtTime(note.velocity * .8, time + .003); gain.gain.exponentialRampToValueAtTime(.00001, time + .36);
+ osc.connect(gain); osc.start(time); osc.stop(time + .37);
+ } else {
+ const hat = [42, 44, 46, 49, 51].includes(note.midi), length = note.midi === 46 ? .36 : hat ? .10 : .23;
+ const source = context.createBufferSource(), filter = context.createBiquadFilter();
+ source.buffer = noiseBuffer(context, key, length); filter.type = hat ? 'highpass' : 'bandpass'; filter.frequency.value = hat ? 7000 : 1700; filter.Q.value = hat ? .4 : .8;
+ source.connect(filter); filter.connect(gain);
+ gain.gain.setValueAtTime(Math.max(.00001, note.velocity * (hat ? .23 : .63)), time); gain.gain.exponentialRampToValueAtTime(.00001, time + length);
+ source.start(time); source.stop(time + length);
+ if (!hat) { const body = context.createOscillator(); body.type = 'triangle'; body.frequency.value = 185; const bodyGain = context.createGain(); bodyGain.gain.setValueAtTime(note.velocity * .13, time); bodyGain.gain.exponentialRampToValueAtTime(.00001, time + .14); body.connect(bodyGain); bodyGain.connect(target); body.start(time); body.stop(time + .15); }
+ }
+ return;
+ }
+ const env = envelope(context, target, time, duration, note.velocity, kind === 'pad' ? Math.max(.12, track.attack) : track.attack, track.release, kind === 'pad' || kind === 'lead');
+ if (kind === 'sampler') {
+ const source = context.createBufferSource(); source.buffer = assets.get(track.sampleId); source.playbackRate.value = 2 ** ((note.midi - track.sampleRoot) / 12); source.connect(env.gain); source.start(time); source.stop(env.end); return;
+ }
+ if (kind === 'pluck') {
+ const length = Math.ceil((duration + track.release + .02) * context.sampleRate), buffer = context.createBuffer(1, length, context.sampleRate), out = buffer.getChannelData(0);
+ const size = Math.max(2, Math.round(context.sampleRate / f)), line = new Float32Array(size), r = musicRandom(key);
+ for (let i = 0; i < size; i++) line[i] = r() * 2 - 1;
+ for (let i = 0; i < length; i++) { const pos = i % size, next = (pos + 1) % size; out[i] = line[pos]; line[pos] = (line[pos] + line[next]) * .4988; }
+ const source = context.createBufferSource(); source.buffer = buffer; source.connect(env.gain); source.start(time); source.stop(env.end); return;
+ }
+ const osc = context.createOscillator(); osc.frequency.value = f;
+ if (kind === 'felt' || kind === 'bell') {
+ const harmonics = kind === 'felt' ? [0, 1, .25, .1, .04, .008] : [0, 1, .01, .38, .04, .16, .04];
+ osc.setPeriodicWave(context.createPeriodicWave(new Float32Array(harmonics.length), new Float32Array(harmonics)));
+ } else osc.type = kind === 'pad' ? 'sawtooth' : kind === 'bass' ? 'triangle' : 'sine';
+ osc.connect(env.gain); osc.start(time); osc.stop(env.end);
+ if (kind === 'pad' || kind === 'bass') {
+ const second = context.createOscillator(), mix = context.createGain(); second.type = 'sine'; second.frequency.value = kind === 'bass' ? f / 2 : f; second.detune.value = kind === 'pad' ? 7 : 0; mix.gain.value = .32; second.connect(mix); mix.connect(env.gain); second.start(time); second.stop(env.end);
+ }
+}
+export async function renderSession(project, { onlyTrack, sampleRate = 48000 } = {}) {
+ const duration = secondsAt(project, project.beats) + (project.tail ?? 1.5), context = new OfflineAudioContext(2, Math.ceil(duration * sampleRate), sampleRate);
+ const assets = await audioAssets(project, context);
+ const tracks = onlyTrack ? project.tracks.filter(t => t.id === onlyTrack) : activeTracks(project);
+ for (const track of tracks) {
+ const seed = project.seed + ':' + track.id, bus = trackBus(context, track, seed);
+ for (const note of track.notes) {
+ const time = secondsAt(project, note.beat), length = secondsAt(project, note.beat + note.duration) - time;
+ synthNote(context, bus, track, note, time, length, seed, assets);
+ }
+ for (const clip of track.clips) {
+ const buffer = assets.get(clip.assetId), start = secondsAt(project, clip.beat);
+ if (clip.offset + clip.duration > buffer.duration + .03) throw new Error(`${track.name}: the clip extends beyond its recording.`);
+ const source = context.createBufferSource(), gain = context.createGain(); source.buffer = buffer;
+ const fadeIn = Math.min(clip.fadeIn, clip.duration / 2), fadeOut = Math.min(clip.fadeOut, clip.duration / 2), level = clip.gain;
+ gain.gain.setValueAtTime(fadeIn ? 0 : level, start); if (fadeIn) gain.gain.linearRampToValueAtTime(level, start + fadeIn);
+ gain.gain.setValueAtTime(level, start + clip.duration - fadeOut); if (fadeOut) gain.gain.linearRampToValueAtTime(0, start + clip.duration);
+ source.connect(gain); gain.connect(bus); source.start(start, clip.offset, clip.duration);
+ }
+ }
+ const buffer = await context.startRendering(), channels = [buffer.getChannelData(0), buffer.getChannelData(1)];
+ let peak = 0, energy = 0;
+ for (const data of channels) for (let i = 0; i < data.length; i++) {
+ // The same linear ending fade is applied to each stem and the mix.
+ data[i] *= Math.min(1, (data.length - 1 - i) / (sampleRate * .015));
+ peak = Math.max(peak, Math.abs(data[i])); energy += data[i] ** 2;
+ }
+ const gain = project.master * Math.min(1, .95 / Math.max(peak, .000001));
+ return { buffer, channels, sampleRate, duration: buffer.duration, rawPeak: peak, gain, peak: peak * gain, rms: Math.sqrt(energy / (buffer.length * 2)) * gain };
+}
diff --git a/store/agents/music-studio/template/studio/files.mjs b/store/agents/music-studio/template/studio/files.mjs
new file mode 100644
index 000000000..1aec1e4f9
--- /dev/null
+++ b/store/agents/music-studio/template/studio/files.mjs
@@ -0,0 +1,21 @@
+export function filename(name) { return String(name).normalize('NFKD').replace(/[^a-zA-Z0-9_.-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 100) || 'artwork'; }
+// ZIP STORE: portable editable delivery without a runtime dependency or a cloud service.
+export function zipFiles(files) {
+ const enc = new TextEncoder(), chunks = [], central = []; let offset = 0;
+ for (const [name, body] of files) {
+ const path = enc.encode(name), bytes = typeof body === 'string' ? enc.encode(body) : new Uint8Array(body);
+ let crc = 0xffffffff;
+ for (const b of bytes) { crc ^= b; for (let i = 0; i < 8; i++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); }
+ crc = (crc ^ 0xffffffff) >>> 0;
+ const header = new Uint8Array(30 + path.length), v = new DataView(header.buffer);
+ v.setUint32(0, 0x04034b50, true); v.setUint16(4, 20, true); v.setUint16(6, 0x800, true); v.setUint16(12, 33, true);
+ v.setUint32(14, crc, true); v.setUint32(18, bytes.length, true); v.setUint32(22, bytes.length, true); v.setUint16(26, path.length, true); header.set(path, 30);
+ const row = new Uint8Array(46 + path.length), c = new DataView(row.buffer);
+ c.setUint32(0, 0x02014b50, true); c.setUint16(4, 20, true); c.setUint16(6, 20, true); c.setUint16(8, 0x800, true); c.setUint16(14, 33, true);
+ c.setUint32(16, crc, true); c.setUint32(20, bytes.length, true); c.setUint32(24, bytes.length, true); c.setUint16(28, path.length, true); c.setUint32(42, offset, true); row.set(path, 46);
+ chunks.push(header, bytes); central.push(row); offset += header.length + bytes.length;
+ }
+ const length = central.reduce((n, row) => n + row.length, 0), end = new Uint8Array(22), e = new DataView(end.buffer);
+ e.setUint32(0, 0x06054b50, true); e.setUint16(8, files.length, true); e.setUint16(10, files.length, true); e.setUint32(12, length, true); e.setUint32(16, offset, true);
+ return new Blob([...chunks, ...central, end], { type: 'application/zip' });
+}
diff --git a/store/agents/music-studio/template/studio/icon.svg b/store/agents/music-studio/template/studio/icon.svg
new file mode 100644
index 000000000..126ef18c4
--- /dev/null
+++ b/store/agents/music-studio/template/studio/icon.svg
@@ -0,0 +1,12 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">
+ <title>Music Studio — five tracks after dark</title>
+ <rect x="4" y="4" width="88" height="88" rx="23" fill="#272537"/>
+ <path d="M67 17a15 15 0 1 0 12 24 16 16 0 0 1-12-24Z" fill="#edbfa9"/>
+ <g fill="#d6c7e9">
+ <rect x="19" y="47" width="8" height="21" rx="4"/>
+ <rect x="32" y="31" width="8" height="45" rx="4"/>
+ <rect x="45" y="42" width="8" height="26" rx="4"/>
+ <rect x="58" y="53" width="8" height="23" rx="4"/>
+ <rect x="71" y="53" width="8" height="15" rx="4"/>
+ </g>
+</svg>
diff --git a/store/agents/music-studio/template/studio/session.mjs b/store/agents/music-studio/template/studio/session.mjs
new file mode 100644
index 000000000..7a89fc12a
--- /dev/null
+++ b/store/agents/music-studio/template/studio/session.mjs
@@ -0,0 +1,144 @@
+export const MUSIC_SPEC = 'afterhours/1';
+export const instruments = { felt: 'Felt keys', pluck: 'Plucked strings', pad: 'Analog pad', bass: 'Round bass', bell: 'Glass bells', lead: 'Soft lead', drums: 'Drum kit', sampler: 'Your sample', audio: 'Audio recording' };
+export const midiPrograms = { felt: 0, pluck: 24, pad: 89, bass: 33, bell: 11, lead: 80, drums: 0, sampler: 0, audio: 0 };
+const finite = (value, min, max) => Number.isFinite(value) && value >= min && value <= max;
+export function validateSession(input) {
+ const p = structuredClone(input);
+ if (!p || p.spec !== MUSIC_SPEC) throw new Error('Open an Afterhours project.');
+ if (typeof p.id !== 'string' || !/^[a-z0-9-]{1,80}$/.test(p.id)) throw new Error('Project needs a stable id.');
+ if (typeof p.title !== 'string' || !p.title.trim() || p.title.length > 160 || typeof p.brief !== 'string' || p.brief.length > 6000) throw new Error('Name the piece and its brief.');
+ p.seed = String(p.seed ?? '1').slice(0, 128);
+ if (!finite(p.tempo, 30, 240)) throw new Error('Tempo must be 30–240 BPM.');
+ p.tempos ??= [{ beat: 0, bpm: p.tempo }];
+ if (!Array.isArray(p.tempos) || !p.tempos.length || p.tempos.length > 200 || p.tempos[0].beat !== 0) throw new Error('Tempo map must begin at beat zero.');
+ for (let i = 0; i < p.tempos.length; i++) if (!finite(p.tempos[i].beat, 0, 4096) || !finite(p.tempos[i].bpm, 30, 240) || i && p.tempos[i].beat <= p.tempos[i - 1].beat) throw new Error('Tempo changes must be ordered and valid.');
+ p.tempo = p.tempos[0].bpm;
+ p.meter ??= [4, 4];
+ if (!Array.isArray(p.meter) || !Number.isInteger(p.meter[0]) || !finite(p.meter[0], 1, 12) || ![2, 4, 8, 16].includes(p.meter[1])) throw new Error('Invalid time signature.');
+ if (!finite(p.beats, 1, 4096) || secondsAt(p, p.beats) > 240) throw new Error('Keep a piece within four minutes; split longer work into movements.');
+ p.master ??= .85; if (!finite(p.master, 0, 1)) throw new Error('Invalid master level.');
+ p.tail ??= 1.5; if (!finite(p.tail, 0, 6)) throw new Error('Use a tail of 0–6 seconds.');
+ p.assets ??= [];
+ const assets = new Set();
+ if (!Array.isArray(p.assets) || p.assets.length > 16) throw new Error('Use at most 16 audio assets.');
+ for (const a of p.assets) {
+ if (typeof a.id !== 'string' || assets.has(a.id) || typeof a.name !== 'string' || a.name.length > 200 || typeof a.data !== 'string' || !/^data:(audio\/[a-z0-9.+-]+|application\/octet-stream);base64,[a-zA-Z0-9+/=]+$/i.test(a.data)) throw new Error('Audio assets must be embedded recordings.');
+ assets.add(a.id);
+ }
+ if (!Array.isArray(p.tracks) || !p.tracks.length || p.tracks.length > 16) throw new Error('Use 1–16 tracks.');
+ const trackIds = new Set(); let noteCount = 0;
+ for (const t of p.tracks) {
+ if (typeof t.id !== 'string' || trackIds.has(t.id) || typeof t.name !== 'string' || t.name.length > 120 || !Object.hasOwn(instruments, t.instrument)) throw new Error('Invalid track.');
+ trackIds.add(t.id);
+ const defaults = { gain: .7, pan: 0, muted: false, solo: false, attack: .008, release: .25, tone: 8000, space: .12, delay: 0, sampleRoot: 60 };
+ for (const [key, value] of Object.entries(defaults)) t[key] ??= value;
+ for (const [key, low, high] of [['gain', 0, 1.5], ['pan', -1, 1], ['attack', .001, 3], ['release', .01, 3], ['tone', 100, 20000], ['space', 0, .8], ['delay', 0, .6], ['sampleRoot', 0, 127]]) if (!finite(t[key], low, high)) throw new Error(`Invalid ${t.name}: ${key}.`);
+ if (typeof t.muted !== 'boolean' || typeof t.solo !== 'boolean') throw new Error('Invalid mute/solo state.');
+ if (t.midiProgram !== undefined && (!Number.isInteger(t.midiProgram) || !finite(t.midiProgram, 0, 127))) throw new Error('Invalid MIDI program.');
+ t.notes ??= []; t.clips ??= [];
+ if (!Array.isArray(t.notes) || !Array.isArray(t.clips) || t.clips.length > 100) throw new Error('Invalid track events.');
+ noteCount += t.notes.length;
+ for (const n of t.notes) if (!finite(n.beat, 0, p.beats) || !finite(n.duration, 1 / 32767, p.beats) || n.beat + n.duration > p.beats + 1e-6 || !Number.isInteger(n.midi) || !finite(n.midi, 0, 127) || !finite(n.velocity, 1 / 127, 1)) throw new Error(`Invalid note in ${t.name}. Use a positive MIDI velocity (at least 1/127); mute the track for silence.`);
+ if (t.instrument === 'audio' && t.notes.length) throw new Error('Choose an instrument to play MIDI notes on this track.');
+ if (t.instrument === 'sampler' && !assets.has(t.sampleId)) throw new Error(`Choose a sample for ${t.name}.`);
+ for (const c of t.clips) {
+ c.gain ??= 1; c.fadeIn ??= .02; c.fadeOut ??= .05;
+ if (!assets.has(c.assetId) || !finite(c.beat, 0, p.beats) || !finite(c.offset, 0, 240) || !finite(c.duration, .01, 240) || !finite(c.gain, 0, 1.5) || !finite(c.fadeIn, 0, c.duration) || !finite(c.fadeOut, 0, c.duration)) throw new Error(`Invalid audio clip in ${t.name}.`);
+ if (secondsAt(p, c.beat) + c.duration > secondsAt(p, p.beats) + .001) throw new Error(`Extend the arrangement to fit ${t.name}'s recording.`);
+ }
+ }
+ if (noteCount > 16000) throw new Error('Use at most 16,000 notes per piece.');
+ p.sections ??= [{ name: 'Piece', beat: 0, length: p.beats }];
+ if (!Array.isArray(p.sections) || p.sections.length > 64) throw new Error('Invalid arrangement sections.');
+ for (const s of p.sections) if (typeof s.name !== 'string' || s.name.length > 80 || !finite(s.beat, 0, p.beats) || !finite(s.length, .01, p.beats) || s.beat + s.length > p.beats + 1e-6) throw new Error('Sections must fit inside the piece.');
+ if (JSON.stringify(p).length > 28000000) throw new Error('Keep the project under 28 MB. For long recordings, import an MP3 or a shorter WAV.');
+ return p;
+}
+export function beatsPerBar(p) { return p.meter[0] * 4 / p.meter[1]; }
+export function secondsAt(p, beat) {
+ const map = p.tempos || [{ beat: 0, bpm: p.tempo }]; let seconds = 0;
+ for (let i = 0; i < map.length && map[i].beat < beat; i++) seconds += (Math.min(beat, map[i + 1]?.beat ?? beat) - map[i].beat) * 60 / map[i].bpm;
+ return seconds;
+}
+export function beatAt(p, seconds) {
+ const map = p.tempos || [{ beat: 0, bpm: p.tempo }]; let elapsed = 0;
+ for (let i = 0; i < map.length; i++) {
+ const length = ((map[i + 1]?.beat ?? Infinity) - map[i].beat) * 60 / map[i].bpm;
+ if (elapsed + length >= seconds) return map[i].beat + (seconds - elapsed) * map[i].bpm / 60;
+ elapsed += length;
+ }
+ return 0;
+}
+export function noteName(n) { return ['C', 'C♯', 'D', 'D♯', 'E', 'F', 'F♯', 'G', 'G♯', 'A', 'A♯', 'B'][n % 12] + (Math.floor(n / 12) - 1); }
+export function noteNumber(name) {
+ if (typeof name === 'number') return name;
+ const m = /^([A-Ga-g])([#b♯♭]?)(-?\d+)$/.exec(name.trim());
+ if (!m) throw new Error('Use a pitch such as C4, F#3 or Bb5.');
+ return (Number(m[3]) + 1) * 12 + ({ C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 })[m[1].toUpperCase()] + (['#', '♯'].includes(m[2]) ? 1 : ['b', '♭'].includes(m[2]) ? -1 : 0);
+}
+export function musicRandom(seed) {
+ let n = 2166136261; for (const c of String(seed)) n = Math.imul(n ^ c.charCodeAt(0), 16777619);
+ return () => { n += 0x6d2b79f5; let t = Math.imul(n ^ n >>> 15, n | 1); t ^= t + Math.imul(t ^ t >>> 7, t | 61); return ((t ^ t >>> 14) >>> 0) / 4294967296; };
+}
+export function activeTracks(p) { const solo = p.tracks.some(t => t.solo); return p.tracks.filter(t => !t.muted && (!solo || t.solo)); }
+export function duplicateSection(p, start, length) {
+ if (!finite(start, 0, p.beats) || !finite(length, .25, p.beats) || start + length > p.beats) throw new Error('Select a section within the piece.');
+ const next = structuredClone(p), destination = p.beats;
+ for (const t of next.tracks) {
+ const notes = t.notes.filter(n => n.beat >= start && n.beat < start + length).map(n => ({ ...n, beat: n.beat - start + destination, duration: Math.min(n.duration, start + length - n.beat) }));
+ const clips = t.clips.filter(c => c.beat >= start && c.beat < start + length).map(c => ({ ...c, beat: c.beat - start + destination, duration: Math.min(c.duration, secondsAt(p, start + length) - secondsAt(p, c.beat)) }));
+ t.notes.push(...notes); t.clips.push(...clips);
+ }
+ next.beats += length;
+ const initial = p.tempos.filter(t => t.beat <= start).at(-1).bpm;
+ if (next.tempos.at(-1).bpm !== initial) next.tempos.push({ beat: destination, bpm: initial });
+ next.tempos.push(...p.tempos.filter(t => t.beat > start && t.beat < start + length).map(t => ({ beat: destination + t.beat - start, bpm: t.bpm })));
+ next.sections.push({ name: 'New section', beat: destination, length });
+ return validateSession(next);
+}
+export function writeSessionMidi(p, MidiClass) {
+ if (p.tracks.filter(t => t.notes.length && t.instrument !== 'drums').length > 15) throw new Error('MIDI has 15 melodic channels plus drums. Combine a melodic track or export WAV stems.');
+ const midi = new MidiClass(); midi.header.name = p.title;
+ midi.header.tempos = p.tempos.map(t => ({ ticks: Math.round(t.beat * midi.header.ppq), bpm: t.bpm }));
+ // Standard markers preserve section cues and intentional silence at the end.
+ // The encoder otherwise ends the file at the final note-off.
+ midi.header.meta = [...p.sections.map(s => ({ ticks: Math.round(s.beat * midi.header.ppq), type: 'marker', text: s.name })), { ticks: Math.round(p.beats * midi.header.ppq), type: 'marker', text: 'Afterhours: end' }];
+ midi.header.timeSignatures = [{ ticks: 0, timeSignature: p.meter }]; midi.header.update();
+ let channel = 0;
+ for (const t of p.tracks.filter(t => t.notes.length)) {
+ const track = midi.addTrack(); track.name = t.name;
+ if (channel === 9) channel++;
+ track.channel = t.instrument === 'drums' ? 9 : channel++ % 16;
+ track.instrument.number = t.midiProgram ?? midiPrograms[t.instrument];
+ track.addCC({ number: 7, ticks: 0, value: Math.min(1, t.gain) }); track.addCC({ number: 10, ticks: 0, value: (t.pan + 1) / 2 });
+ for (const n of t.notes) track.addNote({ midi: n.midi, ticks: Math.round(n.beat * midi.header.ppq), durationTicks: Math.max(1, Math.round(n.duration * midi.header.ppq)), velocity: n.velocity });
+ }
+ return midi.toArray();
+}
+export function readSessionMidi(bytes, MidiClass) {
+ const midi = new MidiClass(bytes), warnings = [], ppq = midi.header.ppq;
+ const source = midi.tracks.filter(t => t.notes.length);
+ if (!source.length) throw new Error('That MIDI file contains no notes.');
+ if (midi.header.timeSignatures.length > 1) throw new Error('This studio supports one time signature per piece. Split meter changes into movements before importing.');
+ const tempos = midi.header.tempos.map(t => ({ beat: t.ticks / ppq, bpm: t.bpm }));
+ if (!tempos.length || tempos[0].beat !== 0) tempos.unshift({ beat: 0, bpm: 120 });
+ const meter = midi.header.timeSignatures[0]?.timeSignature || [4, 4], bar = meter[0] * 4 / meter[1];
+ const tracks = source.map((t, i) => {
+ if (Object.entries(t.controlChanges).some(([key, events]) => events?.some(e => !['7', '10'].includes(key) || e.ticks !== 0)) || t.pitchBends.length) warnings.push(`${t.name || 'Track ' + (i + 1)}: MIDI automation and pitch bends are not imported. Render audio in the source application if they are essential.`);
+ const program = t.instrument.number;
+ const instrument = t.instrument.percussion ? 'drums' : program >= 32 && program <= 39 ? 'bass' : program >= 24 && program <= 31 ? 'pluck' : program >= 88 && program <= 95 ? 'pad' : program >= 8 && program <= 15 ? 'bell' : 'felt';
+ return { id: 'midi-' + i, name: (t.name || t.instrument.name || 'Track ' + (i + 1)).slice(0, 120), instrument, midiProgram: program, gain: t.controlChanges[7]?.find(e => e.ticks === 0)?.value ?? .7, pan: (t.controlChanges[10]?.find(e => e.ticks === 0)?.value ?? .5) * 2 - 1, notes: t.notes.map(n => ({ beat: n.ticks / ppq, duration: Math.max(1, n.durationTicks) / ppq, midi: n.midi, velocity: n.velocity })) };
+ });
+ const lastTick = Math.max(0, ...midi.header.meta.map(m => m.ticks), ...midi.tracks.map(t => t.endOfTrackTicks || 0));
+ const beats = Math.ceil(Math.max(lastTick / ppq, ...tracks.flatMap(t => t.notes.map(n => n.beat + n.duration))) / bar) * bar;
+ return validateSession({ spec: MUSIC_SPEC, id: 'imported-midi', title: (midi.name || 'Your composition').slice(0, 160), brief: 'Your MIDI notes and tempo map, ready to arrange and produce. Synthesized instruments are a preview; export MIDI or stems to continue in your DAW.', seed: 'midi', tempo: tempos[0].bpm, tempos, meter, beats, tracks, importWarnings: warnings });
+}
+export function wavBytes(channels, sampleRate, gain = 1) {
+ const frames = channels[0].length, count = channels.length;
+ const bytes = new ArrayBuffer(44 + frames * count * 2), view = new DataView(bytes);
+ const text = (at, s) => [...s].forEach((c, i) => view.setUint8(at + i, c.charCodeAt(0)));
+ text(0, 'RIFF'); view.setUint32(4, bytes.byteLength - 8, true); text(8, 'WAVE'); text(12, 'fmt '); view.setUint32(16, 16, true);
+ view.setUint16(20, 1, true); view.setUint16(22, count, true); view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * count * 2, true); view.setUint16(32, count * 2, true); view.setUint16(34, 16, true); text(36, 'data'); view.setUint32(40, frames * count * 2, true);
+ for (let i = 0; i < frames; i++) for (let c = 0; c < count; c++) view.setInt16(44 + (i * count + c) * 2, Math.round(Math.max(-1, Math.min(1, channels[c][i] * gain)) * 32767), true);
+ return bytes;
+}
diff --git a/store/agents/music-studio/template/studio/shell.html b/store/agents/music-studio/template/studio/shell.html
new file mode 100644
index 000000000..0c020c9b2
--- /dev/null
+++ b/store/agents/music-studio/template/studio/shell.html
@@ -0,0 +1,21 @@
+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Afterhours · Music Studio</title><!-- FAVICON --><style>/* STUDIO_CSS */</style></head><body>
+<header><div class="identity"><span class="brand-icon"><!-- PROJECT_ICON --></span>AFTERHOURS<span>MUSIC STUDIO</span></div><div class="file-actions"><button id="open-project">Open project</button><button id="save-project">Save project</button><button id="export-stems" class="primary">Stems + project ↗</button></div></header>
+<div class="notice" id="revision-notice" hidden><span>A new agent revision is available. Your saved mix and notes are still here.</span><button id="use-revision">Use new version</button><button id="keep-draft">Keep my draft</button></div>
+<main><section class="main-panel"><div class="project-heading"><div><p class="eyebrow">YOUR COMPOSITION</p><h1 id="title"></h1><p id="brief"></p></div><div class="project-controls"><label>Tempo<input id="tempo" type="number" min="30" max="240" step="0.001"></label><label>Bars<input id="bars" type="number" min="1" max="256"></label><span id="meter"></span></div></div>
+<div class="transport"><div class="transport-buttons"><button id="play" class="play" aria-label="Play">▶ Play</button><button id="stop">■ Stop</button><span id="time">0:00 / 0:00</span></div><div class="exports"><button id="export-wav">Export WAV ↗</button><button id="export-midi">Export MIDI ↗</button></div></div>
+<div class="wave-stage"><canvas id="waveform" aria-label="Rendered stereo waveform"></canvas><div class="mix-stats"><span id="audio-status">Preparing your mix</span><span id="level">48 kHz / stereo</span></div></div>
+<div class="section-heading"><h2>Arrangement</h2><div class="small-actions"><button id="open-midi">Open MIDI</button><button id="import-audio">Add recording</button><button id="add-track">+ Instrument</button></div></div>
+<div id="sections" class="sections"></div><div id="tracks" class="tracks"></div>
+<div class="section-heading"><div><h2 id="piano-title">Notes</h2><p class="hint">Click to add. Drag to move. Select a note to change its pitch, length or touch.</p></div><div class="small-actions"><button id="previous-bars" aria-label="Previous bars">←</button><span id="bar-window"></span><button id="next-bars" aria-label="Next bars">→</button></div></div>
+<div class="piano-stage"><canvas id="piano" aria-label="Editable piano roll" tabindex="0"></canvas></div>
+<div class="note-editor"><label>Pitch<input id="note-pitch" value="C4" size="5"></label><label>Start beat<input id="note-start" type="number" min="0" step="0.25"></label><label>Length<input id="note-length" type="number" min="0.125" step="0.25" value="1"></label><label>Touch<input id="note-velocity" type="range" min="0.05" max="1" step="0.01" value="0.75"></label><button id="delete-note">Delete note</button></div>
+<div class="edit-actions"><div><button id="undo">↶ Undo</button><button id="redo">↷ Redo</button><button id="duplicate-section">Repeat these bars</button></div><span id="draft-status">Draft saved on this device</span></div>
+<div class="handoff"><div><p class="eyebrow">KEEP MAKING IT YOURS</p><h2>A piece you can take anywhere.</h2><p>Bring your own MIDI or recordings. Keep the notes editable. Export the mix and separate tracks to continue in your DAW.</p></div><details><summary>Make a completely different piece</summary><p>Describe it in the Harness chat. Give the purpose, mood, length and any melody or recording you want to use. The agent writes a complete arrangement for your brief. This example is not a genre restriction.</p><p>Try: “Make a 40-second title sequence for a coastal documentary. Start with an intimate plucked motif, open into warm harmony, then end on a quiet resolved chord. Leave room for my voiceover.”</p></details></div>
+</section><aside><p class="eyebrow">SELECTED TRACK</p><label>Track name<input id="track-name"></label><label>Sound<select id="instrument"></select></label><div id="sampler-controls" hidden><label>Sample<select id="sample-id"></select></label><label>Original pitch<input id="sample-root" value="C4"></label></div>
+<div class="mixer-buttons"><button id="mute">Mute</button><button id="solo">Solo</button></div>
+<label>Level <output id="gain-label"></output><input id="gain" type="range" min="0" max="1.5" step="0.01"></label><label>Position <output id="pan-label"></output><input id="pan" type="range" min="-1" max="1" step="0.01"></label>
+<div class="rule"></div><p class="eyebrow">SHAPE THE SOUND</p><label>Soft entrance<input id="attack" type="range" min="0.001" max="3" step="0.001"></label><label>Release<input id="release" type="range" min="0.01" max="3" step="0.01"></label><label>Brightness<input id="tone" type="range" min="100" max="20000" step="100"></label><label>Room<input id="space" type="range" min="0" max="0.8" step="0.01"></label><label>Echo<input id="delay" type="range" min="0" max="0.6" step="0.01"></label>
+<div id="clip-controls" hidden><div class="rule"></div><p class="eyebrow">RECORDING</p><label>Clip<select id="clip-select"></select></label><label>Start beat<input id="clip-beat" type="number" min="0" step="0.25"></label><label>Trim start (seconds)<input id="clip-offset" type="number" min="0" step="0.01"></label><label>Length (seconds)<input id="clip-duration" type="number" min="0.01" step="0.01"></label></div>
+<div class="rule"></div><div class="transpose"><button id="transpose-down">− Octave</button><button id="transpose-up">+ Octave</button></div><button id="remove-track" class="quiet">Remove track</button><div class="rule"></div><p class="eyebrow">MASTER</p><label>Output level<input id="master" type="range" min="0" max="1" step="0.01"></label><p class="hint">WAV: 48 kHz, stereo, 16-bit. Stems follow mute and solo. MIDI keeps all notes; recordings travel as audio.</p><button id="export-html" class="quiet">Portable studio ↗</button><button id="reset-project" class="quiet">Restore agent version</button></aside></main>
+<div id="error" class="error" role="alert" hidden></div><div id="toast" role="status"></div><input id="project-file" type="file" accept=".json" hidden><input id="midi-file" type="file" accept=".mid,.midi" hidden><input id="audio-file" type="file" accept="audio/wav,audio/mpeg,audio/mp3,audio/ogg,audio/mp4" hidden>
+<script id="afterhours-data" type="application/json">"PROJECT_DATA"</script><script>/* MIDI_LIBRARY */</script><script id="afterhours-model">/* SESSION_MODEL */</script><script>/* AUDIO_ENGINE */</script><script>/* FILE_TOOLS */</script><script>/* STUDIO_APP */</script></body></html>
diff --git a/store/agents/music-studio/template/studio/style.css b/store/agents/music-studio/template/studio/style.css
new file mode 100644
index 000000000..06c6fe790
--- /dev/null
+++ b/store/agents/music-studio/template/studio/style.css
@@ -0,0 +1,2 @@
+:root{color-scheme:dark;--bg:#10121a;--panel:#191d29;--line:#ffffff16;--ink:#f3ede8;--muted:#9299aa;--accent:#eabe90;--purple:#b9acf1;font:13px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink)}button,input,select{font:inherit;color:inherit;background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:8px 11px;min-width:0}button{cursor:pointer;touch-action:manipulation}button:hover{border-color:#8d819f}button:focus-visible,input:focus-visible,canvas:focus-visible,summary:focus-visible{outline:2px solid var(--accent);outline-offset:3px}button:disabled{opacity:.4;cursor:default}button.primary,.play{background:var(--accent);color:#1a1820;border:0;font-weight:650}button[aria-pressed=true]{border-color:var(--accent);color:var(--accent);background:#47352c}input[type=range]{padding:0;width:100%;accent-color:var(--accent)}input[type=number]{font-variant-numeric:tabular-nums}h1,h2,p{margin:0}h1{font-size:38px;font-weight:550;line-height:1.05;letter-spacing:-.045em;margin:9px 0 12px}h2{font-size:14px;font-weight:550}.eyebrow{font:9px/1.5 ui-monospace,monospace;letter-spacing:.18em;color:var(--muted)}header{display:flex;align-items:center;justify-content:space-between;gap:16px;min-height:72px;padding:16px 26px;border-bottom:1px solid var(--line)}.identity{display:flex;align-items:center;gap:11px;font-size:11px;letter-spacing:.08em;font-weight:650}.identity>span:last-child{border-left:1px solid var(--line);padding-left:12px;font-size:9px;color:var(--muted);font-weight:400}.brand-icon,.brand-icon svg{width:28px;height:28px;display:block}.file-actions,.small-actions,.exports,.transport-buttons{display:flex;align-items:center;gap:8px}main{display:grid;grid-template-columns:minmax(0,1fr) 248px;max-width:1900px;margin:auto}.main-panel{padding:30px;min-width:0}aside{padding:28px 22px;border-left:1px solid var(--line)}.project-heading{display:flex;align-items:center;justify-content:space-between;gap:32px}#brief{max-width:610px;font-size:12px;color:#aeb4c4;line-height:1.7}.project-controls{display:flex;align-items:end;gap:12px;flex-shrink:0}.project-controls label{width:67px}.project-controls input{width:100%}.project-controls #meter{font-size:11px;color:var(--muted);padding-bottom:25px}label{display:flex;flex-direction:column;gap:7px;font-size:11px;color:#c4c8d2;margin:15px 0}label output{font-size:10px;color:var(--muted)}.transport{display:flex;align-items:center;justify-content:space-between;margin:26px 0 16px;gap:14px}#time{font:11px ui-monospace,monospace;color:var(--muted);margin-left:10px;white-space:nowrap}.wave-stage{background:linear-gradient(120deg,#201e30,#191d2b);border:1px solid var(--line);border-radius:8px;overflow:hidden}.wave-stage canvas{width:100%;height:110px;display:block;cursor:pointer}.mix-stats{display:flex;justify-content:space-between;gap:10px;border-top:1px solid var(--line);padding:10px 15px;color:var(--muted);font:9px ui-monospace,monospace}.section-heading{display:flex;justify-content:space-between;align-items:center;gap:14px;margin:25px 0 13px}.small-actions button{font-size:10px;padding:6px 10px}.hint{color:var(--muted);font-size:10px;line-height:1.65;margin-top:5px}.sections{margin-left:156px;height:28px;position:relative;overflow:hidden}.section{position:absolute;top:0;height:24px;border-left:1px solid #b9acf166;color:#b9acf1;font:9px ui-monospace,monospace;white-space:nowrap;padding:4px 6px;background:#b9acf10a;overflow:hidden}.tracks{border:1px solid var(--line);border-radius:7px;overflow:hidden}.track{display:grid;grid-template-columns:155px minmax(0,1fr);border-bottom:1px solid var(--line);height:49px}.track:last-child{border-bottom:0}.track.selected{background:#b9acf110}.track-info{display:flex;align-items:center;gap:4px;padding:0 8px;border-right:1px solid var(--line);min-width:0}.track-info .track-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;text-align:left;border:0;background:transparent;padding:6px 2px;font-size:11px}.track-info .mini{font-size:8px;padding:3px 5px}.track canvas{width:100%;height:48px;display:block;cursor:pointer}.piano-stage{border:1px solid var(--line);border-radius:7px;overflow:hidden;background:#131722}#piano{height:250px;width:100%;display:block;touch-action:none;cursor:crosshair}.note-editor{display:grid;grid-template-columns:90px 90px 85px minmax(90px,1fr) auto;gap:12px;align-items:end}.note-editor button{margin-bottom:15px;font-size:10px}.note-editor input:not([type=range]){width:100%}.note-editor label{margin:12px 0 15px;font-size:10px}.edit-actions{display:flex;justify-content:space-between;align-items:center;gap:16px;margin-top:3px;padding:13px 0;border-bottom:1px solid var(--line)}.edit-actions button{font-size:10px}.edit-actions span{font-size:9px;color:var(--muted)}.handoff{display:grid;grid-template-columns:1fr 1fr;gap:30px;margin-top:27px}.handoff h2{font-size:19px;letter-spacing:-.025em;margin:5px 0 9px}.handoff p:not(.eyebrow),.handoff details{font-size:11px;line-height:1.7;color:var(--muted)}.handoff summary{color:var(--accent);cursor:pointer}.handoff details p{margin-top:12px}.rule{height:1px;background:var(--line);margin:23px 0}.mixer-buttons,.transpose{display:flex;gap:8px}.mixer-buttons button,.transpose button{flex:1;font-size:11px}.quiet{font-size:10px;width:100%;margin-top:10px;color:var(--muted)}#toast{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);max-width:90vw;border-radius:7px;background:#ede1d5;color:#17141d;padding:11px 18px;opacity:0;pointer-events:none;box-shadow:0 12px 35px #0007;z-index:20;font-size:12px}#toast.visible{opacity:1}.error{position:fixed;bottom:20px;left:20px;right:280px;background:#442628;border:1px solid #ad6160;border-radius:7px;padding:14px;color:#ffe0de;z-index:10}.notice{padding:12px 25px;background:#413623;display:flex;gap:12px;align-items:center;font-size:11px}.notice button{font-size:11px}[hidden]{display:none!important}@media(min-width:1500px){.main-panel{padding:35px 45px}main{grid-template-columns:minmax(0,1fr) 280px}#piano{height:285px}.track{height:57px}.track canvas{height:56px}}@media(max-width:1100px){.identity>span:last-child{display:none}main{grid-template-columns:minmax(0,1fr) 215px}.main-panel{padding:24px 20px}aside{padding:24px 16px}.project-heading{display:block}.project-controls{margin-top:8px}.project-controls label{margin-bottom:0}.project-controls #meter{padding-bottom:10px}.transport{flex-wrap:wrap}.note-editor{grid-template-columns:65px 70px 70px minmax(60px,1fr)}.note-editor button{grid-column:1/-1;margin-top:-10px}.handoff{grid-template-columns:1fr;gap:16px}}@media(max-width:700px){header{padding:14px;flex-wrap:wrap}.file-actions{width:100%}.file-actions button{flex:1;font-size:10px}main{display:block}.main-panel{padding:25px 14px}aside{border-top:1px solid var(--line);border-left:0;padding:24px;display:grid;grid-template-columns:1fr 1fr;gap:0 20px}aside>.eyebrow,aside>.rule,aside>.hint{grid-column:1/-1}.track{grid-template-columns:110px minmax(0,1fr)}.track-info{padding:0 5px}.track-info .track-name{font-size:9px}.track-info .mini{padding:2px 3px}.sections{margin-left:111px}.section-heading{flex-wrap:wrap}.small-actions{gap:5px;flex-wrap:wrap}.small-actions button{font-size:9px}.transport-buttons{gap:6px}#time{margin-left:0;font-size:10px}.transport button,.exports button{font-size:11px}.mix-stats{font-size:8px}.edit-actions{align-items:flex-start;flex-direction:column}.notice{flex-wrap:wrap}.error{right:20px}h1{font-size:34px}.note-editor{grid-template-columns:60px 70px 70px minmax(45px,1fr);gap:9px}.note-editor button{grid-column:auto;margin-top:0;grid-column:1/3}#piano{height:245px}}
+.transport{position:sticky;top:0;z-index:5;background:var(--bg);padding:10px 0}aside{position:sticky;top:0;height:100vh;overflow:auto}@media(max-width:700px){aside{position:static;height:auto;overflow:visible}}
diff --git a/store/agents/music-studio/template/studio/vendor/NOTICE.md b/store/agents/music-studio/template/studio/vendor/NOTICE.md
new file mode 100644
index 000000000..40c4e585c
--- /dev/null
+++ b/store/agents/music-studio/template/studio/vendor/NOTICE.md
@@ -0,0 +1,7 @@
+# Vendored MIDI parser/writer
+
+@tonejs/midi 2.0.28 by Yotam Mann, including midi-file and array-flatten.
+Source: https://github.com/Tonejs/Midi
+
+The pinned package-lock.json in toolchain records the fetched packages. The build/Midi.js browser distribution is embedded unchanged except for removal of its source-map reference. MIT licenses are preserved alongside it.
+The local `.cjs` suffix also supports CLI import inside workspaces with `type: module`.
diff --git a/store/agents/music-studio/template/studio/vendor/array-flatten-LICENSE.txt b/store/agents/music-studio/template/studio/vendor/array-flatten-LICENSE.txt
new file mode 100644
index 000000000..983fbe8ae
--- /dev/null
+++ b/store/agents/music-studio/template/studio/vendor/array-flatten-LICENSE.txt
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 Blake Embrey ([email protected])
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/store/agents/music-studio/template/studio/vendor/midi-file-LICENSE.txt b/store/agents/music-studio/template/studio/vendor/midi-file-LICENSE.txt
new file mode 100644
index 000000000..aefcf1be4
--- /dev/null
+++ b/store/agents/music-studio/template/studio/vendor/midi-file-LICENSE.txt
@@ -0,0 +1,21 @@
+[The MIT License](http://opensource.org/licenses/MIT)
+
+Copyright © 2016 Carter Thaxton
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/store/agents/music-studio/template/studio/vendor/midi.cjs b/store/agents/music-studio/template/studio/vendor/midi.cjs
new file mode 100644
index 000000000..f8ac0ecbe
--- /dev/null
+++ b/store/agents/music-studio/template/studio/vendor/midi.cjs
@@ -0,0 +1 @@
+!function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var r=e();for(var n in r)("object"==typeof exports?exports:t)[n]=r[n]}}("undefined"!=typeof self?self:this,(function(){return(()=>{var t={507:(t,e,r)=>{"use strict";function n(t){var e=[];return i(t,e),e}function i(t,e){for(var r=0;r<t.length;r++){var n=t[r];Array.isArray(n)?i(n,e):e.push(n)}}r.r(e),r.d(e,{flatten:()=>n})},289:(t,e,r)=>{e.parseMidi=r(666),e.writeMidi=r(865)},666:t=>{function e(t){for(var e,n=new r(t),i=[];!n.eof();){var a=o();i.push(a)}return i;function o(){var t={};t.deltaTime=n.readVarInt();var r=n.readUInt8();if(240==(240&r)){if(255!==r){if(240==r)return t.type="sysEx",a=n.readVarInt(),t.data=n.readBytes(a),t;if(247==r)return t.type="endSysEx",a=n.readVarInt(),t.data=n.readBytes(a),t;throw"Unrecognised MIDI event type byte: "+r}t.meta=!0;var i=n.readUInt8(),a=n.readVarInt();switch(i){case 0:if(t.type="sequenceNumber",2!==a)throw"Expected length for sequenceNumber event is 2, got "+a;return t.number=n.readUInt16(),t;case 1:return t.type="text",t.text=n.readString(a),t;case 2:return t.type="copyrightNotice",t.text=n.readString(a),t;case 3:return t.type="trackName",t.text=n.readString(a),t;case 4:return t.type="instrumentName",t.text=n.readString(a),t;case 5:return t.type="lyrics",t.text=n.readString(a),t;case 6:return t.type="marker",t.text=n.readString(a),t;case 7:return t.type="cuePoint",t.text=n.readString(a),t;case 32:if(t.type="channelPrefix",1!=a)throw"Expected length for channelPrefix event is 1, got "+a;return t.channel=n.readUInt8(),t;case 33:if(t.type="portPrefix",1!=a)throw"Expected length for portPrefix event is 1, got "+a;return t.port=n.readUInt8(),t;case 47:if(t.type="endOfTrack",0!=a)throw"Expected length for endOfTrack event is 0, got "+a;return t;case 81:if(t.type="setTempo",3!=a)throw"Expected length for setTempo event is 3, got "+a;return t.microsecondsPerBeat=n.readUInt24(),t;case 84:if(t.type="smpteOffset",5!=a)throw"Expected length for smpteOffset event is 5, got "+a;var o=n.readUInt8();return t.frameRate={0:24,32:25,64:29,96:30}[96&o],t.hour=31&o,t.min=n.readUInt8(),t.sec=n.readUInt8(),t.frame=n.readUInt8(),t.subFrame=n.readUInt8(),t;case 88:if(t.type="timeSignature",4!=a)throw"Expected length for timeSignature event is 4, got "+a;return t.numerator=n.readUInt8(),t.denominator=1<<n.readUInt8(),t.metronome=n.readUInt8(),t.thirtyseconds=n.readUInt8(),t;case 89:if(t.type="keySignature",2!=a)throw"Expected length for keySignature event is 2, got "+a;return t.key=n.readInt8(),t.scale=n.readUInt8(),t;case 127:return t.type="sequencerSpecific",t.data=n.readBytes(a),t;default:return t.type="unknownMeta",t.data=n.readBytes(a),t.metatypeByte=i,t}}else{var s;if(0==(128&r)){if(null===e)throw"Running status byte encountered before status byte";s=r,r=e,t.running=!0}else s=n.readUInt8(),e=r;var c=r>>4;switch(t.channel=15&r,c){case 8:return t.type="noteOff",t.noteNumber=s,t.velocity=n.readUInt8(),t;case 9:var u=n.readUInt8();return t.type=0===u?"noteOff":"noteOn",t.noteNumber=s,t.velocity=u,0===u&&(t.byte9=!0),t;case 10:return t.type="noteAftertouch",t.noteNumber=s,t.amount=n.readUInt8(),t;case 11:return t.type="controller",t.controllerType=s,t.value=n.readUInt8(),t;case 12:return t.type="programChange",t.programNumber=s,t;case 13:return t.type="channelAftertouch",t.amount=s,t;case 14:return t.type="pitchBend",t.value=s+(n.readUInt8()<<7)-8192,t;default:throw"Unrecognised MIDI event type: "+c}}}}function r(t){this.buffer=t,this.bufferLen=this.buffer.length,this.pos=0}r.prototype.eof=function(){return this.pos>=this.bufferLen},r.prototype.readUInt8=function(){var t=this.buffer[this.pos];return this.pos+=1,t},r.prototype.readInt8=function(){var t=this.readUInt8();return 128&t?t-256:t},r.prototype.readUInt16=function(){return(this.readUInt8()<<8)+this.readUInt8()},r.prototype.readInt16=function(){var t=this.readUInt16();return 32768&t?t-65536:t},r.prototype.readUInt24=function(){return(this.readUInt8()<<16)+(this.readUInt8()<<8)+this.readUInt8()},r.prototype.readInt24=function(){var t=this.readUInt24();return 8388608&t?t-16777216:t},r.prototype.readUInt32=function(){return(this.readUInt8()<<24)+(this.readUInt8()<<16)+(this.readUInt8()<<8)+this.readUInt8()},r.prototype.readBytes=function(t){var e=this.buffer.slice(this.pos,this.pos+t);return this.pos+=t,e},r.prototype.readString=function(t){var e=this.readBytes(t);return String.fromCharCode.apply(null,e)},r.prototype.readVarInt=function(){for(var t=0;!this.eof();){var e=this.readUInt8();if(!(128&e))return t+e;t+=127&e,t<<=7}return t},r.prototype.readChunk=function(){var t=this.readString(4),e=this.readUInt32();return{id:t,length:e,data:this.readBytes(e)}},t.exports=function(t){var n=new r(t),i=n.readChunk();if("MThd"!=i.id)throw"Bad MIDI file. Expected 'MHdr', got: '"+i.id+"'";for(var a=function(t){var e=new r(t),n={format:e.readUInt16(),numTracks:e.readUInt16()},i=e.readUInt16();return 32768&i?(n.framesPerSecond=256-(i>>8),n.ticksPerFrame=255&i):n.ticksPerBeat=i,n}(i.data),o=[],s=0;!n.eof()&&s<a.numTracks;s++){var c=n.readChunk();if("MTrk"!=c.id)throw"Bad MIDI file. Expected 'MTrk', got: '"+c.id+"'";var u=e(c.data);o.push(u)}return{header:a,tracks:o}}},865:t=>{function e(t,e,i){var a,o=new n,s=e.length,c=null;for(a=0;a<s;a++)!1!==i.running&&(i.running||e[a].running)||(c=null),c=r(o,e[a],c,i.useByte9ForNoteOff);t.writeChunk("MTrk",o.buffer)}function r(t,e,r,n){var i=e.type,a=e.deltaTime,o=e.text||"",s=e.data||[],c=null;switch(t.writeVarInt(a),i){case"sequenceNumber":t.writeUInt8(255),t.writeUInt8(0),t.writeVarInt(2),t.writeUInt16(e.number);break;case"text":t.writeUInt8(255),t.writeUInt8(1),t.writeVarInt(o.length),t.writeString(o);break;case"copyrightNotice":t.writeUInt8(255),t.writeUInt8(2),t.writeVarInt(o.length),t.writeString(o);break;case"trackName":t.writeUInt8(255),t.writeUInt8(3),t.writeVarInt(o.length),t.writeString(o);break;case"instrumentName":t.writeUInt8(255),t.writeUInt8(4),t.writeVarInt(o.length),t.writeString(o);break;case"lyrics":t.writeUInt8(255),t.writeUInt8(5),t.writeVarInt(o.length),t.writeString(o);break;case"marker":t.writeUInt8(255),t.writeUInt8(6),t.writeVarInt(o.length),t.writeString(o);break;case"cuePoint":t.writeUInt8(255),t.writeUInt8(7),t.writeVarInt(o.length),t.writeString(o);break;case"channelPrefix":t.writeUInt8(255),t.writeUInt8(32),t.writeVarInt(1),t.writeUInt8(e.channel);break;case"portPrefix":t.writeUInt8(255),t.writeUInt8(33),t.writeVarInt(1),t.writeUInt8(e.port);break;case"endOfTrack":t.writeUInt8(255),t.writeUInt8(47),t.writeVarInt(0);break;case"setTempo":t.writeUInt8(255),t.writeUInt8(81),t.writeVarInt(3),t.writeUInt24(e.microsecondsPerBeat);break;case"smpteOffset":t.writeUInt8(255),t.writeUInt8(84),t.writeVarInt(5);var u=31&e.hour|{24:0,25:32,29:64,30:96}[e.frameRate];t.writeUInt8(u),t.writeUInt8(e.min),t.writeUInt8(e.sec),t.writeUInt8(e.frame),t.writeUInt8(e.subFrame);break;case"timeSignature":t.writeUInt8(255),t.writeUInt8(88),t.writeVarInt(4),t.writeUInt8(e.numerator);var h=255&Math.floor(Math.log(e.denominator)/Math.LN2);t.writeUInt8(h),t.writeUInt8(e.metronome),t.writeUInt8(e.thirtyseconds||8);break;case"keySignature":t.writeUInt8(255),t.writeUInt8(89),t.writeVarInt(2),t.writeInt8(e.key),t.writeUInt8(e.scale);break;case"sequencerSpecific":t.writeUInt8(255),t.writeUInt8(127),t.writeVarInt(s.length),t.writeBytes(s);break;case"unknownMeta":null!=e.metatypeByte&&(t.writeUInt8(255),t.writeUInt8(e.metatypeByte),t.writeVarInt(s.length),t.writeBytes(s));break;case"sysEx":t.writeUInt8(240),t.writeVarInt(s.length),t.writeBytes(s);break;case"endSysEx":t.writeUInt8(247),t.writeVarInt(s.length),t.writeBytes(s);break;case"noteOff":(c=(!1!==n&&e.byte9||n&&0==e.velocity?144:128)|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.noteNumber),t.writeUInt8(e.velocity);break;case"noteOn":(c=144|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.noteNumber),t.writeUInt8(e.velocity);break;case"noteAftertouch":(c=160|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.noteNumber),t.writeUInt8(e.amount);break;case"controller":(c=176|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.controllerType),t.writeUInt8(e.value);break;case"programChange":(c=192|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.programNumber);break;case"channelAftertouch":(c=208|e.channel)!==r&&t.writeUInt8(c),t.writeUInt8(e.amount);break;case"pitchBend":(c=224|e.channel)!==r&&t.writeUInt8(c);var f=8192+e.value,p=127&f,l=f>>7&127;t.writeUInt8(p),t.writeUInt8(l);break;default:throw"Unrecognized event type: "+i}return c}function n(){this.buffer=[]}n.prototype.writeUInt8=function(t){this.buffer.push(255&t)},n.prototype.writeInt8=n.prototype.writeUInt8,n.prototype.writeUInt16=function(t){var e=t>>8&255,r=255&t;this.writeUInt8(e),this.writeUInt8(r)},n.prototype.writeInt16=n.prototype.writeUInt16,n.prototype.writeUInt24=function(t){var e=t>>16&255,r=t>>8&255,n=255&t;this.writeUInt8(e),this.writeUInt8(r),this.writeUInt8(n)},n.prototype.writeInt24=n.prototype.writeUInt24,n.prototype.writeUInt32=function(t){var e=t>>24&255,r=t>>16&255,n=t>>8&255,i=255&t;this.writeUInt8(e),this.writeUInt8(r),this.writeUInt8(n),this.writeUInt8(i)},n.prototype.writeInt32=n.prototype.writeUInt32,n.prototype.writeBytes=function(t){this.buffer=this.buffer.concat(Array.prototype.slice.call(t,0))},n.prototype.writeString=function(t){var e,r=t.length,n=[];for(e=0;e<r;e++)n.push(t.codePointAt(e));this.writeBytes(n)},n.prototype.writeVarInt=function(t){if(t<0)throw"Cannot write negative variable-length integer";if(t<=127)this.writeUInt8(t);else{var e=t,r=[];for(r.push(127&e),e>>=7;e;){var n=127&e|128;r.push(n),e>>=7}this.writeBytes(r.reverse())}},n.prototype.writeChunk=function(t,e){this.writeString(t),this.writeUInt32(e.length),this.writeBytes(e)},t.exports=function(t,r){if("object"!=typeof t)throw"Invalid MIDI data";r=r||{};var i,a=t.header||{},o=t.tracks||[],s=o.length,c=new n;for(function(t,e,r){var i=null==e.format?1:e.format,a=128;e.timeDivision?a=e.timeDivision:e.ticksPerFrame&&e.framesPerSecond?a=-(255&e.framesPerSecond)<<8|255&e.ticksPerFrame:e.ticksPerBeat&&(a=32767&e.ticksPerBeat);var o=new n;o.writeUInt16(i),o.writeUInt16(r),o.writeUInt16(a),t.writeChunk("MThd",o.buffer)}(c,a,s),i=0;i<s;i++)e(c,o[i],r);return c.buffer}},805:(t,e)=>{"use strict";function r(t,e,r){void 0===r&&(r="ticks");var n=0,i=t.length,a=i;if(i>0&&t[i-1][r]<=e)return i-1;for(;n<a;){var o=Math.floor(n+(a-n)/2),s=t[o],c=t[o+1];if(s[r]===e){for(var u=o;u<t.length;u++)t[u][r]===e&&(o=u);return o}if(s[r]<e&&c[r]>e)return o;s[r]>e?a=o:s[r]<e&&(n=o+1)}return-1}Object.defineProperty(e,"__esModule",{value:!0}),e.insert=e.search=void 0,e.search=r,e.insert=function(t,e,n){if(void 0===n&&(n="ticks"),t.length){var i=r(t,e[n],n);t.splice(i+1,0,e)}else t.push(e)}},543:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ControlChange=e.controlChangeIds=e.controlChangeNames=void 0,e.controlChangeNames={1:"modulationWheel",2:"breath",4:"footController",5:"portamentoTime",7:"volume",8:"balance",10:"pan",64:"sustain",65:"portamentoTime",66:"sostenuto",67:"softPedal",68:"legatoFootswitch",84:"portamentoControl"},e.controlChangeIds=Object.keys(e.controlChangeNames).reduce((function(t,r){return t[e.controlChangeNames[r]]=r,t}),{});var r=new WeakMap,n=new WeakMap,i=function(){function t(t,e){r.set(this,e),n.set(this,t.controllerType),this.ticks=t.absoluteTime,this.value=t.value}return Object.defineProperty(t.prototype,"number",{get:function(){return n.get(this)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return e.controlChangeNames[this.number]?e.controlChangeNames[this.number]:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"time",{get:function(){return r.get(this).ticksToSeconds(this.ticks)},set:function(t){var e=r.get(this);this.ticks=e.secondsToTicks(t)},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return{number:this.number,ticks:this.ticks,time:this.time,value:this.value}},t}();e.ControlChange=i},906:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createControlChanges=void 0;var n=r(543);e.createControlChanges=function(){return new Proxy({},{get:function(t,e){return t[e]?t[e]:n.controlChangeIds.hasOwnProperty(e)?t[n.controlChangeIds[e]]:void 0},set:function(t,e,r){return n.controlChangeIds.hasOwnProperty(e)?t[n.controlChangeIds[e]]=r:t[e]=r,!0}})}},54:function(t,e,r){"use strict";var n=this&&this.__spreadArray||function(t,e,r){if(r||2===arguments.length)for(var n,i=0,a=e.length;i<a;i++)!n&&i in e||(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))};Object.defineProperty(e,"__esModule",{value:!0}),e.encode=void 0;var i=r(289),a=r(535),o=r(507);function s(t,e){return{absoluteTime:t.ticks,channel:e,controllerType:t.number,deltaTime:0,type:"controller",value:Math.floor(127*t.value)}}function c(t){return{absoluteTime:0,channel:t.channel,deltaTime:0,programNumber:t.instrument.number,type:"programChange"}}e.encode=function(t){var e={header:{format:1,numTracks:t.tracks.length+1,ticksPerBeat:t.header.ppq},tracks:n([n(n(n(n([{absoluteTime:0,deltaTime:0,meta:!0,text:t.header.name,type:"trackName"}],t.header.keySignatures.map((function(t){return function(t){var e=a.keySignatureKeys.indexOf(t.key);return{absoluteTime:t.ticks,deltaTime:0,key:e+7,meta:!0,scale:"major"===t.scale?0:1,type:"keySignature"}}(t)})),!0),t.header.meta.map((function(t){return{absoluteTime:(e=t).ticks,deltaTime:0,meta:!0,text:e.text,type:e.type};var e})),!0),t.header.tempos.map((function(t){return function(t){return{absoluteTime:t.ticks,deltaTime:0,meta:!0,microsecondsPerBeat:Math.floor(6e7/t.bpm),type:"setTempo"}}(t)})),!0),t.header.timeSignatures.map((function(t){return function(t){return{absoluteTime:t.ticks,deltaTime:0,denominator:t.timeSignature[1],meta:!0,metronome:24,numerator:t.timeSignature[0],thirtyseconds:8,type:"timeSignature"}}(t)})),!0)],t.tracks.map((function(t){return n(n(n([(e=t.name,{absoluteTime:0,deltaTime:0,meta:!0,text:e,type:"trackName"}),c(t)],function(t){return(0,o.flatten)(t.notes.map((function(e){return function(t,e){return[{absoluteTime:t.ticks,channel:e,deltaTime:0,noteNumber:t.midi,type:"noteOn",velocity:Math.floor(127*t.velocity)},{absoluteTime:t.ticks+t.durationTicks,channel:e,deltaTime:0,noteNumber:t.midi,type:"noteOff",velocity:Math.floor(127*t.noteOffVelocity)}]}(e,t.channel)})))}(t),!0),function(t){for(var e=[],r=0;r<127;r++)t.controlChanges.hasOwnProperty(r)&&t.controlChanges[r].forEach((function(r){e.push(s(r,t.channel))}));return e}(t),!0),function(t){var e=[];return t.pitchBends.forEach((function(r){e.push(function(t,e){return{absoluteTime:t.ticks,channel:e,deltaTime:0,type:"pitchBend",value:t.value}}(r,t.channel))})),e}(t),!0);var e})),!0)};return e.tracks=e.tracks.map((function(t){t=t.sort((function(t,e){return t.absoluteTime-e.absoluteTime}));var e=0;return t.forEach((function(t){t.deltaTime=t.absoluteTime-e,e=t.absoluteTime,delete t.absoluteTime})),t.push({deltaTime:0,meta:!0,type:"endOfTrack"}),t})),new Uint8Array((0,i.writeMidi)(e))}},535:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Header=e.keySignatureKeys=void 0;var n=r(805),i=new WeakMap;e.keySignatureKeys=["Cb","Gb","Db","Ab","Eb","Bb","F","C","G","D","A","E","B","F#","C#"];var a=function(){function t(t){var r=this;if(this.tempos=[],this.timeSignatures=[],this.keySignatures=[],this.meta=[],this.name="",i.set(this,480),t){i.set(this,t.header.ticksPerBeat),t.tracks.forEach((function(t){t.forEach((function(t){t.meta&&("timeSignature"===t.type?r.timeSignatures.push({ticks:t.absoluteTime,timeSignature:[t.numerator,t.denominator]}):"setTempo"===t.type?r.tempos.push({bpm:6e7/t.microsecondsPerBeat,ticks:t.absoluteTime}):"keySignature"===t.type&&r.keySignatures.push({key:e.keySignatureKeys[t.key+7],scale:0===t.scale?"major":"minor",ticks:t.absoluteTime}))}))}));var n=0;t.tracks[0].forEach((function(t){n+=t.deltaTime,t.meta&&("trackName"===t.type?r.name=t.text:"text"!==t.type&&"cuePoint"!==t.type&&"marker"!==t.type&&"lyrics"!==t.type||r.meta.push({text:t.text,ticks:n,type:t.type}))})),this.update()}}return t.prototype.update=function(){var t=this,e=0,r=0;this.tempos.sort((function(t,e){return t.ticks-e.ticks})),this.tempos.forEach((function(n,i){var a=i>0?t.tempos[i-1].bpm:t.tempos[0].bpm,o=n.ticks/t.ppq-r,s=60/a*o;n.time=s+e,e=n.time,r+=o})),this.timeSignatures.sort((function(t,e){return t.ticks-e.ticks})),this.timeSignatures.forEach((function(e,r){var n=r>0?t.timeSignatures[r-1]:t.timeSignatures[0],i=(e.ticks-n.ticks)/t.ppq/n.timeSignature[0]/(n.timeSignature[1]/4);n.measures=n.measures||0,e.measures=i+n.measures}))},t.prototype.ticksToSeconds=function(t){var e=(0,n.search)(this.tempos,t);if(-1!==e){var r=this.tempos[e],i=r.time,a=(t-r.ticks)/this.ppq;return i+60/r.bpm*a}return t/this.ppq*.5},t.prototype.ticksToMeasures=function(t){var e=(0,n.search)(this.timeSignatures,t);if(-1!==e){var r=this.timeSignatures[e],i=(t-r.ticks)/this.ppq;return r.measures+i/(r.timeSignature[0]/r.timeSignature[1])/4}return t/this.ppq/4},Object.defineProperty(t.prototype,"ppq",{get:function(){return i.get(this)},enumerable:!1,configurable:!0}),t.prototype.secondsToTicks=function(t){var e=(0,n.search)(this.tempos,t,"time");if(-1!==e){var r=this.tempos[e],i=(t-r.time)/(60/r.bpm);return Math.round(r.ticks+i*this.ppq)}var a=t/.5;return Math.round(a*this.ppq)},t.prototype.toJSON=function(){return{keySignatures:this.keySignatures,meta:this.meta,name:this.name,ppq:this.ppq,tempos:this.tempos.map((function(t){return{bpm:t.bpm,ticks:t.ticks}})),timeSignatures:this.timeSignatures}},t.prototype.fromJSON=function(t){this.name=t.name,this.tempos=t.tempos.map((function(t){return Object.assign({},t)})),this.timeSignatures=t.timeSignatures.map((function(t){return Object.assign({},t)})),this.keySignatures=t.keySignatures.map((function(t){return Object.assign({},t)})),this.meta=t.meta.map((function(t){return Object.assign({},t)})),i.set(this,t.ppq),this.update()},t.prototype.setTempo=function(t){this.tempos=[{bpm:t,ticks:0}],this.update()},t}();e.Header=a},362:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Instrument=void 0;var n=r(438),i=new WeakMap,a=function(){function t(t,e){if(this.number=0,i.set(this,e),this.number=0,t){var r=t.find((function(t){return"programChange"===t.type}));r&&(this.number=r.programNumber)}}return Object.defineProperty(t.prototype,"name",{get:function(){return this.percussion?n.DrumKitByPatchID[this.number]:n.instrumentByPatchID[this.number]},set:function(t){var e=n.instrumentByPatchID.indexOf(t);-1!==e&&(this.number=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"family",{get:function(){return this.percussion?"drums":n.InstrumentFamilyByID[Math.floor(this.number/8)]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"percussion",{get:function(){return 9===i.get(this).channel},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return{family:this.family,number:this.number,name:this.name}},t.prototype.fromJSON=function(t){this.number=t.number},t}();e.Instrument=a},438:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.DrumKitByPatchID=e.InstrumentFamilyByID=e.instrumentByPatchID=void 0,e.instrumentByPatchID=["acoustic grand piano","bright acoustic piano","electric grand piano","honky-tonk piano","electric piano 1","electric piano 2","harpsichord","clavi","celesta","glockenspiel","music box","vibraphone","marimba","xylophone","tubular bells","dulcimer","drawbar organ","percussive organ","rock organ","church organ","reed organ","accordion","harmonica","tango accordion","acoustic guitar (nylon)","acoustic guitar (steel)","electric guitar (jazz)","electric guitar (clean)","electric guitar (muted)","overdriven guitar","distortion guitar","guitar harmonics","acoustic bass","electric bass (finger)","electric bass (pick)","fretless bass","slap bass 1","slap bass 2","synth bass 1","synth bass 2","violin","viola","cello","contrabass","tremolo strings","pizzicato strings","orchestral harp","timpani","string ensemble 1","string ensemble 2","synthstrings 1","synthstrings 2","choir aahs","voice oohs","synth voice","orchestra hit","trumpet","trombone","tuba","muted trumpet","french horn","brass section","synthbrass 1","synthbrass 2","soprano sax","alto sax","tenor sax","baritone sax","oboe","english horn","bassoon","clarinet","piccolo","flute","recorder","pan flute","blown bottle","shakuhachi","whistle","ocarina","lead 1 (square)","lead 2 (sawtooth)","lead 3 (calliope)","lead 4 (chiff)","lead 5 (charang)","lead 6 (voice)","lead 7 (fifths)","lead 8 (bass + lead)","pad 1 (new age)","pad 2 (warm)","pad 3 (polysynth)","pad 4 (choir)","pad 5 (bowed)","pad 6 (metallic)","pad 7 (halo)","pad 8 (sweep)","fx 1 (rain)","fx 2 (soundtrack)","fx 3 (crystal)","fx 4 (atmosphere)","fx 5 (brightness)","fx 6 (goblins)","fx 7 (echoes)","fx 8 (sci-fi)","sitar","banjo","shamisen","koto","kalimba","bag pipe","fiddle","shanai","tinkle bell","agogo","steel drums","woodblock","taiko drum","melodic tom","synth drum","reverse cymbal","guitar fret noise","breath noise","seashore","bird tweet","telephone ring","helicopter","applause","gunshot"],e.InstrumentFamilyByID=["piano","chromatic percussion","organ","guitar","bass","strings","ensemble","brass","reed","pipe","synth lead","synth pad","synth effects","world","percussive","sound effects"],e.DrumKitByPatchID={0:"standard kit",8:"room kit",16:"power kit",24:"electronic kit",25:"tr-808 kit",32:"jazz kit",40:"brush kit",48:"orchestra kit",56:"sound fx kit"}},233:function(t,e,r){"use strict";var n=this&&this.__awaiter||function(t,e,r,n){return new(r||(r=Promise))((function(i,a){function o(t){try{c(n.next(t))}catch(t){a(t)}}function s(t){try{c(n.throw(t))}catch(t){a(t)}}function c(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(o,s)}c((n=n.apply(t,e||[])).next())}))},i=this&&this.__generator||function(t,e){var r,n,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=e.call(t,o)}catch(t){a=[6,t],n=0}finally{r=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}};Object.defineProperty(e,"__esModule",{value:!0}),e.Header=e.Track=e.Midi=void 0;var a=r(289),o=r(535),s=r(334),c=r(54),u=function(){function t(t){var e=this,r=null;if(t){var n=t instanceof ArrayBuffer?new Uint8Array(t):t;(r=(0,a.parseMidi)(n)).tracks.forEach((function(t){var e=0;t.forEach((function(t){e+=t.deltaTime,t.absoluteTime=e}))})),r.tracks=function(t){for(var e=[],r=0;r<t.length;r++)for(var n=e.length,i=new Map,a=Array(16).fill(0),o=0,s=t[r];o<s.length;o++){var c=s[o],u=n,h=c.channel;if(void 0!==h){"programChange"===c.type&&(a[h]=c.programNumber);var f=a[h],p="".concat(f," ").concat(h);i.has(p)?u=i.get(p):(u=n+i.size,i.set(p,u))}e[u]||e.push([]),e[u].push(c)}return e}(r.tracks)}this.header=new o.Header(r),this.tracks=[],t&&(this.tracks=r.tracks.map((function(t){return new s.Track(t,e.header)})),1===r.header.format&&0===this.tracks[0].duration&&this.tracks.shift())}return t.fromUrl=function(e){return n(this,void 0,void 0,(function(){var r;return i(this,(function(n){switch(n.label){case 0:return[4,fetch(e)];case 1:return(r=n.sent()).ok?[4,r.arrayBuffer()]:[3,3];case 2:return[2,new t(n.sent())];case 3:throw new Error("Could not load '".concat(e,"'"))}}))}))},Object.defineProperty(t.prototype,"name",{get:function(){return this.header.name},set:function(t){this.header.name=t},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"duration",{get:function(){var t=this.tracks.map((function(t){return t.duration}));return Math.max.apply(Math,t)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"durationTicks",{get:function(){var t=this.tracks.map((function(t){return t.durationTicks}));return Math.max.apply(Math,t)},enumerable:!1,configurable:!0}),t.prototype.addTrack=function(){var t=new s.Track(void 0,this.header);return this.tracks.push(t),t},t.prototype.toArray=function(){return(0,c.encode)(this)},t.prototype.toJSON=function(){return{header:this.header.toJSON(),tracks:this.tracks.map((function(t){return t.toJSON()}))}},t.prototype.fromJSON=function(t){var e=this;this.header=new o.Header,this.header.fromJSON(t.header),this.tracks=t.tracks.map((function(t){var r=new s.Track(void 0,e.header);return r.fromJSON(t),r}))},t.prototype.clone=function(){var e=new t;return e.fromJSON(this.toJSON()),e},t}();e.Midi=u;var h=r(334);Object.defineProperty(e,"Track",{enumerable:!0,get:function(){return h.Track}});var f=r(535);Object.defineProperty(e,"Header",{enumerable:!0,get:function(){return f.Header}})},518:(t,e)=>{"use strict";function r(t){return["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"][t%12]}Object.defineProperty(e,"__esModule",{value:!0}),e.Note=void 0;var n,i,a=(n=/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,i={cbb:-2,cb:-1,c:0,"c#":1,cx:2,dbb:0,db:1,d:2,"d#":3,dx:4,ebb:2,eb:3,e:4,"e#":5,ex:6,fbb:3,fb:4,f:5,"f#":6,fx:7,gbb:5,gb:6,g:7,"g#":8,gx:9,abb:7,ab:8,a:9,"a#":10,ax:11,bbb:9,bb:10,b:11,"b#":12,bx:13},function(t){var e=n.exec(t),r=e[1],a=e[2];return i[r.toLowerCase()]+12*(parseInt(a,10)+1)}),o=new WeakMap,s=function(){function t(t,e,r){o.set(this,r),this.midi=t.midi,this.velocity=t.velocity,this.noteOffVelocity=e.velocity,this.ticks=t.ticks,this.durationTicks=e.ticks-t.ticks}return Object.defineProperty(t.prototype,"name",{get:function(){return t=this.midi,e=Math.floor(t/12)-1,r(t)+e.toString();var t,e},set:function(t){this.midi=a(t)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"octave",{get:function(){return Math.floor(this.midi/12)-1},set:function(t){var e=t-this.octave;this.midi+=12*e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pitch",{get:function(){return r(this.midi)},set:function(t){this.midi=12*(this.octave+1)+["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"].indexOf(t)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"duration",{get:function(){var t=o.get(this);return t.ticksToSeconds(this.ticks+this.durationTicks)-t.ticksToSeconds(this.ticks)},set:function(t){var e=o.get(this).secondsToTicks(this.time+t);this.durationTicks=e-this.ticks},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"time",{get:function(){return o.get(this).ticksToSeconds(this.ticks)},set:function(t){var e=o.get(this);this.ticks=e.secondsToTicks(t)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bars",{get:function(){return o.get(this).ticksToMeasures(this.ticks)},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return{duration:this.duration,durationTicks:this.durationTicks,midi:this.midi,name:this.name,ticks:this.ticks,time:this.time,velocity:this.velocity}},t}();e.Note=s},882:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PitchBend=void 0;var r=new WeakMap,n=function(){function t(t,e){r.set(this,e),this.ticks=t.absoluteTime,this.value=t.value}return Object.defineProperty(t.prototype,"time",{get:function(){return r.get(this).ticksToSeconds(this.ticks)},set:function(t){var e=r.get(this);this.ticks=e.secondsToTicks(t)},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return{ticks:this.ticks,time:this.time,value:this.value}},t}();e.PitchBend=n},334:(t,e,r)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Track=void 0;var n=r(805),i=r(543),a=r(906),o=r(882),s=r(362),c=r(518),u=new WeakMap,h=function(){function t(t,e){var r=this;if(this.name="",this.notes=[],this.controlChanges=(0,a.createControlChanges)(),this.pitchBends=[],u.set(this,e),t){var n=t.find((function(t){return"trackName"===t.type}));this.name=n?n.text:""}if(this.instrument=new s.Instrument(t,this),this.channel=0,t){for(var i=t.filter((function(t){return"noteOn"===t.type})),o=t.filter((function(t){return"noteOff"===t.type})),c=function(){var t=i.shift();h.channel=t.channel;var e=o.findIndex((function(e){return e.noteNumber===t.noteNumber&&e.absoluteTime>=t.absoluteTime}));if(-1!==e){var r=o.splice(e,1)[0];h.addNote({durationTicks:r.absoluteTime-t.absoluteTime,midi:t.noteNumber,noteOffVelocity:r.velocity/127,ticks:t.absoluteTime,velocity:t.velocity/127})}},h=this;i.length;)c();t.filter((function(t){return"controller"===t.type})).forEach((function(t){r.addCC({number:t.controllerType,ticks:t.absoluteTime,value:t.value/127})})),t.filter((function(t){return"pitchBend"===t.type})).forEach((function(t){r.addPitchBend({ticks:t.absoluteTime,value:t.value/Math.pow(2,13)})}));var f=t.find((function(t){return"endOfTrack"===t.type}));this.endOfTrackTicks=void 0!==f?f.absoluteTime:void 0}}return t.prototype.addNote=function(t){var e=u.get(this),r=new c.Note({midi:0,ticks:0,velocity:1},{ticks:0,velocity:0},e);return Object.assign(r,t),(0,n.insert)(this.notes,r,"ticks"),this},t.prototype.addCC=function(t){var e=u.get(this),r=new i.ControlChange({controllerType:t.number},e);return delete t.number,Object.assign(r,t),Array.isArray(this.controlChanges[r.number])||(this.controlChanges[r.number]=[]),(0,n.insert)(this.controlChanges[r.number],r,"ticks"),this},t.prototype.addPitchBend=function(t){var e=u.get(this),r=new o.PitchBend({},e);return Object.assign(r,t),(0,n.insert)(this.pitchBends,r,"ticks"),this},Object.defineProperty(t.prototype,"duration",{get:function(){if(!this.notes.length)return 0;for(var t=this.notes[this.notes.length-1].time+this.notes[this.notes.length-1].duration,e=0;e<this.notes.length-1;e++){var r=this.notes[e].time+this.notes[e].duration;t<r&&(t=r)}return t},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"durationTicks",{get:function(){if(!this.notes.length)return 0;for(var t=this.notes[this.notes.length-1].ticks+this.notes[this.notes.length-1].durationTicks,e=0;e<this.notes.length-1;e++){var r=this.notes[e].ticks+this.notes[e].durationTicks;t<r&&(t=r)}return t},enumerable:!1,configurable:!0}),t.prototype.fromJSON=function(t){var e=this;for(var r in this.name=t.name,this.channel=t.channel,this.instrument=new s.Instrument(void 0,this),this.instrument.fromJSON(t.instrument),void 0!==t.endOfTrackTicks&&(this.endOfTrackTicks=t.endOfTrackTicks),t.controlChanges)t.controlChanges[r]&&t.controlChanges[r].forEach((function(t){e.addCC({number:t.number,ticks:t.ticks,value:t.value})}));t.notes.forEach((function(t){e.addNote({durationTicks:t.durationTicks,midi:t.midi,ticks:t.ticks,velocity:t.velocity})}))},t.prototype.toJSON=function(){for(var t={},e=0;e<127;e++)this.controlChanges.hasOwnProperty(e)&&(t[e]=this.controlChanges[e].map((function(t){return t.toJSON()})));var r={channel:this.channel,controlChanges:t,pitchBends:this.pitchBends.map((function(t){return t.toJSON()})),instrument:this.instrument.toJSON(),name:this.name,notes:this.notes.map((function(t){return t.toJSON()}))};return void 0!==this.endOfTrackTicks&&(r.endOfTrackTicks=this.endOfTrackTicks),r},t}();e.Track=h}},e={};function r(n){var i=e[n];if(void 0!==i)return i.exports;var a=e[n]={exports:{}};return t[n].call(a.exports,a,a.exports,r),a.exports}return r.d=(t,e)=>{for(var n in e)r.o(e,n)&&!r.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r(233)})()}));
diff --git a/store/agents/music-studio/template/studio/vendor/tonejs-midi-LICENSE.txt b/store/agents/music-studio/template/studio/vendor/tonejs-midi-LICENSE.txt
new file mode 100644
index 000000000..c015913e4
--- /dev/null
+++ b/store/agents/music-studio/template/studio/vendor/tonejs-midi-LICENSE.txt
@@ -0,0 +1,21 @@
+[The MIT License](http://opensource.org/licenses/MIT)
+
+Copyright © 2016 Yotam Mann
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
diff --git a/store/agents/music-studio/template/tools/build.mjs b/store/agents/music-studio/template/tools/build.mjs
new file mode 100644
index 000000000..8279636b1
--- /dev/null
+++ b/store/agents/music-studio/template/tools/build.mjs
@@ -0,0 +1,40 @@
+#!/usr/bin/env node
+import { readFile, writeFile, mkdir, realpath } from 'node:fs/promises';
+import { resolve, dirname, extname, sep } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createHash } from 'node:crypto';
+import { validateSession } from '../studio/session.mjs';
+export async function buildMusic(workspace, { check = false } = {}) {
+ const root = resolve(workspace), read = name => readFile(resolve(root, name), 'utf8');
+ if (!check) {
+ await mkdir(resolve(root, '.harness'), { recursive: true });
+ await writeFile(resolve(root, '.harness/verdict.json'), JSON.stringify({ spec: 1, ready: false, artifact: 'piece/index.html', summary: 'Building the composition · verification pending' }));
+ }
+ const source = JSON.parse(await read('piece/session.json'));
+ for (const asset of source.assets || []) {
+ if (!asset.file) continue;
+ const dir = await realpath(resolve(root, 'piece')), path = await realpath(resolve(dir, asset.file));
+ if (!path.startsWith(dir + sep)) throw new Error('Recordings must live inside piece/.');
+ const mime = { '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.m4a': 'audio/mp4', '.ogg': 'audio/ogg' }[extname(path).toLowerCase()];
+ if (!mime) throw new Error('Use WAV, MP3, M4A or OGG audio.');
+ const bytes = await readFile(path); if (bytes.length > 18000000) throw new Error('Use audio files under 18 MB.');
+ asset.data = `data:${mime};base64,${bytes.toString('base64')}`; delete asset.file;
+ }
+ const project = validateSession(source), revision = createHash('sha256').update(JSON.stringify(project)).digest('hex');
+ const [shell, css, model, engine, files, app, midi, icon] = await Promise.all(['studio/shell.html', 'studio/style.css', 'studio/session.mjs', 'studio/audio.mjs', 'studio/files.mjs', 'studio/app.js', 'studio/vendor/midi.cjs', 'studio/icon.svg'].map(read));
+ const inline = source => source.replace(/^import .*?;\n/gm, '').replace(/^export /gm, '').replace(/<\/script/gi, '<\\/script');
+ const replacements = { '/* STUDIO_CSS */': css, '/* SESSION_MODEL */': inline(model), '/* AUDIO_ENGINE */': inline(engine), '/* FILE_TOOLS */': inline(files), '/* STUDIO_APP */': inline(app), '/* MIDI_LIBRARY */': midi, '"PROJECT_DATA"': JSON.stringify({ ...project, revision }).replace(/</g, '\\u003c'), '<!-- PROJECT_ICON -->': icon, '<!-- FAVICON -->': `<link rel="icon" href="data:image/svg+xml,${encodeURIComponent(icon)}">` };
+ let html = shell; for (const [key, value] of Object.entries(replacements)) html = html.replace(key, () => value);
+ if (check) { if (await read('piece/index.html') !== html) throw new Error('Preview is out of date. Run node tools/build.mjs.'); }
+ else await writeFile(resolve(root, 'piece/index.html'), html);
+ return { title: project.title, revision, tracks: project.tracks.length, notes: project.tracks.reduce((sum, t) => sum + t.notes.length, 0), htmlBytes: Buffer.byteLength(html) };
+}
+if (process.argv[1] && await realpath(process.argv[1]).catch(() => '') === fileURLToPath(import.meta.url)) {
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+ try { console.log(JSON.stringify(await buildMusic(root, { check: process.argv.includes('--check') }))); }
+ catch (error) {
+ console.error(error.message); process.exitCode = 1;
+ await mkdir(resolve(root, '.harness'), { recursive: true });
+ await writeFile(resolve(root, '.harness/verdict.json'), JSON.stringify({ spec: 1, ready: false, artifact: 'piece/index.html', summary: 'Build failed: ' + error.message }));
+ }
+}
diff --git a/store/agents/music-studio/template/tools/check.mjs b/store/agents/music-studio/template/tools/check.mjs
index 043022a11..4beddc84b 100644
--- a/store/agents/music-studio/template/tools/check.mjs
+++ b/store/agents/music-studio/template/tools/check.mjs
@@ -1,75 +1,3 @@
-const CONFIG = {"id":"music-studio","artifact":"piece/index.html"};
-// Compiled into each workspace's tools/check.mjs. Tests the model in the ACTUAL edited HTML.
-import { readFile, mkdir, writeFile } from "node:fs/promises";
-import { createHash } from "node:crypto";
-import vm from "node:vm";
-import { resolve, dirname } from "node:path";
-
-const args = process.argv.slice(2),
- i = args.indexOf("--seeds");
-const count = i === -1 ? 32 : Number(args[i + 1]);
-if (!Number.isInteger(count) || count < 1 || count > 1000)
- throw new Error("--seeds must be an integer from 1 to 1000");
-const artifact = resolve(CONFIG.artifact);
-const html = await readFile(artifact, "utf8");
-const script = html.match(
- /<script id="harness-model">([\s\S]*?)<\/script>/,
-)?.[1];
-if (!script)
- throw new Error(
- 'Keep the pure model in <script id="harness-model"> so this checker can exercise the actual artifact.',
- );
-const expressions = {
- "generative-art": `const m=artModel(SEED);const p=artPaths(m);({state:m,valid:p.length>0&&p.flat().every(([x,y])=>Number.isFinite(x)&&Number.isFinite(y)),metrics:{paths:p.length,palette:m.palette}})`,
- "creative-direction": `const m=directionModel(SEED);const ratio=contrast(m.colors[0],m.colors[1]);({state:m,valid:ratio>=4.5,metrics:{direction:m.name,contrast:ratio}})`,
- "lab-bench": `const p=experiment(SEED),e=treatmentEffect(p);({state:p,valid:p.length>1&&p.every(p=>Number.isFinite(p.x)&&Number.isFinite(p.y))&&Number.isFinite(e.low)&&e.low<=e.high,metrics:{samples:p.length,effect:e.difference,interval:[e.low,e.high]}})`,
- "music-studio": `const s=musicScore(SEED),r=renderMusic(s);({state:Array.from(r.samples),valid:r.peak>.001&&r.peak<=.95&&r.samples.every(Number.isFinite),metrics:{seconds:r.duration,peak:r.peak,rms:r.rms}})`,
- "game-master": `const m=arenaMatch(SEED),s=m.history.at(-1);({state:m,valid:m.history.length>1&&m.history.length<=10000&&s.units.every(u=>u.hp>=0&&u.x>=0&&u.x<m.map.w&&u.y>=0&&u.y<m.map.h),metrics:{turns:s.turn,score:s.score,winner:m.winner}})`,
- "drone-pilot": `const s=flyAutopilot(SEED);({state:s,valid:s.finished&&!s.crashed&&s.passed===flightCourse(SEED).length,metrics:{seconds:s.time,passed:s.passed,missed:s.missed}})`,
- "voxel-worlds": `const w=voxelWorld(SEED);let p={...w.spawn,vy:0,grounded:true};const clear=playerFits(w,p.x,p.y,p.z);for(let t=0;t<120;t++)p=movePlayer(w,p,{forward:1});({state:Array.from(w.blocks),valid:clear&&playerFits(w,p.x,p.y,p.z),metrics:{blocks:w.blocks.filter(Boolean).length,walkDistance:Math.hypot(p.x-w.spawn.x,p.z-w.spawn.z)}})`,
-};
-const expression = expressions[CONFIG.id];
-const digest = (value) =>
- createHash("sha256").update(JSON.stringify(value)).digest("hex");
-const results = [];
-for (let seed = 0; seed < count; seed++) {
- const run = () =>
- vm.runInNewContext(
- `${script}\n${expression}`,
- { SEED: String(seed) },
- { timeout: 10000 },
- );
- try {
- const first = run(),
- second = run(),
- signature = digest(first.state),
- repeat = digest(second.state);
- results.push({
- seed,
- ok: first.valid && signature === repeat,
- signature,
- metrics: first.metrics,
- });
- } catch (error) {
- results.push({ seed, ok: false, error: error.message });
- }
-}
-const passed = results.filter((r) => r.ok).length;
-const report = {
- spec: 1,
- harness: CONFIG.id,
- artifact: CONFIG.artifact,
- checkedAt: new Date().toISOString(),
- modelChecks: { passed, total: count },
- scope:
- "Pure model invariants and same-process repeatability. Browser interaction, layout, listening and export review still required.",
- results,
-};
-const out = resolve(".harness/model-check.json");
-await mkdir(dirname(out), { recursive: true });
-await writeFile(out, JSON.stringify(report, null, 2) + "\n");
-console.log(
- `${CONFIG.id}: ${passed}/${count} model checks passed. Report: ${out}`,
-);
-console.log(report.scope);
-if (passed !== count) process.exitCode = 1;
+import { buildMusic } from './build.mjs';
+import { fileURLToPath } from 'node:url';
+try { console.log(JSON.stringify({ ...await buildMusic(fileURLToPath(new URL('..', import.meta.url)), { check: true }), ready: false, next: 'Export, inspect the MIDI and WAV files, then listen to the complete piece.' })); } catch (error) { console.error(error.message); process.exitCode = 1; }
diff --git a/store/agents/music-studio/template/tools/export.mjs b/store/agents/music-studio/template/tools/export.mjs
new file mode 100644
index 000000000..0ba3275cc
--- /dev/null
+++ b/store/agents/music-studio/template/tools/export.mjs
@@ -0,0 +1,39 @@
+#!/usr/bin/env node
+import { mkdir, writeFile } from 'node:fs/promises';
+import { resolve, join } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { buildMusic } from './build.mjs';
+const root = fileURLToPath(new URL('..', import.meta.url)), args = process.argv.slice(2);
+const output = resolve(root, args.includes('--out') ? args[args.indexOf('--out') + 1] : 'delivery');
+await buildMusic(root); await mkdir(output, { recursive: true });
+const toolchain = process.env.MUSIC_DSH_DIR ? pathToFileURL(join(process.env.MUSIC_DSH_DIR, 'toolchain/')).href : new URL('../../toolchain/', import.meta.url).href;
+const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || new URL('node_modules/playwright-core/index.mjs', toolchain).href);
+const executablePath = process.env.BROWSER_EXECUTABLE || await (await import(new URL('browser.mjs', toolchain).href)).browserPath();
+const browser = await chromium.launch({ executablePath, headless: true });
+try {
+ const page = await browser.newPage({ viewport: { width: 1600, height: 1080 }, acceptDownloads: true }), errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await page.goto(pathToFileURL(join(root, 'piece/index.html')).href);
+ await page.locator('body[data-ready=true]').waitFor({ timeout: 30000 });
+ await page.locator('#play').click(); await page.waitForFunction(() => afterhours.getState().playing && afterhours.getState().context === 'running');
+ await page.locator('#stop').click();
+ for (const [button, name] of [['export-wav', 'mix.wav'], ['export-midi', 'composition.mid'], ['save-project', 'project.afterhours.json'], ['export-stems', 'production.zip'], ['export-html', 'studio.html']]) {
+ const event = page.waitForEvent('download', { timeout: 60000 }); await page.locator('#' + button).click(); const download = await event;
+ if (await download.failure()) throw new Error('Export failed: ' + name); await download.saveAs(join(output, name));
+ }
+ const measured = await page.evaluate(() => afterhours.getState());
+ const project = await page.evaluate(() => afterhours.getProject());
+ const repeated = await page.evaluate(async () => {
+ const a = await afterhours.render(), b = await afterhours.render(); let maxDifference = 0;
+ for (let c = 0; c < 2; c++) for (let i = 0; i < a.channels[c].length; i++) maxDifference = Math.max(maxDifference, Math.abs(a.channels[c][i] - b.channels[c][i]));
+ return { frames: a.buffer.length, sampleRate: a.sampleRate, maxDifference };
+ });
+ if (!Number.isFinite(measured.peak) || measured.peak > .951 || measured.rms <= .00001) throw new Error('The exported mix is silent, non-finite or lacks expected headroom.');
+ if (repeated.maxDifference > .00001) throw new Error('Repeated render differs beyond the audio tolerance.');
+ if (errors.length) throw new Error(errors.join('\n'));
+ await page.evaluate(() => { scrollTo(0, 0); document.querySelector('aside').scrollTop = 0; });
+ await page.screenshot({ path: join(output, 'studio.png'), fullPage: true });
+ const report = { title: project.title, brief: project.brief, sourceRevision: project.revision, ready: false, tracks: project.tracks.length, notes: project.tracks.reduce((n, t) => n + t.notes.length, 0), ...measured, repeated, limitation: 'Playback, repeatability, duration and headroom are technical checks. Musical quality, fit to the brief and the complete listening pass remain a review task.' };
+ await writeFile(join(output, 'verification.json'), JSON.stringify(report, null, 2));
+ console.log(JSON.stringify({ output, title: project.title, duration: measured.duration, tracks: project.tracks.length, peak: measured.peak, repeatedMaximumDifference: repeated.maxDifference, ready: false }));
+} finally { await browser.close(); }
diff --git a/store/agents/music-studio/template/tools/import-project.mjs b/store/agents/music-studio/template/tools/import-project.mjs
new file mode 100644
index 000000000..41bdff902
--- /dev/null
+++ b/store/agents/music-studio/template/tools/import-project.mjs
@@ -0,0 +1,21 @@
+#!/usr/bin/env node
+import { readFile, writeFile, mkdir } from 'node:fs/promises';
+import { resolve, join, extname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createRequire } from 'node:module';
+import { validateSession, readSessionMidi } from '../studio/session.mjs';
+import { buildMusic } from './build.mjs';
+if (!process.argv[2]) throw new Error('Usage: node tools/import-project.mjs project.afterhours.json OR composition.mid');
+const root = fileURLToPath(new URL('..', import.meta.url)), path = resolve(process.argv[2]), bytes = await readFile(path);
+if (bytes.length > 28000000) throw new Error('Project exceeds 28 MB.');
+let project;
+if (['.mid', '.midi'].includes(extname(path).toLowerCase())) {
+ const { Midi } = createRequire(import.meta.url)(fileURLToPath(new URL('../studio/vendor/midi.cjs', import.meta.url)));
+ project = readSessionMidi(bytes, Midi);
+} else project = validateSession(JSON.parse(bytes.toString('utf8')));
+const backup = join(root, '.harness/history', new Date().toISOString().replace(/[:.]/g, '-') + '.json');
+await mkdir(join(root, '.harness/history'), { recursive: true });
+await writeFile(backup, await readFile(join(root, 'piece/session.json')));
+delete project.revision;
+await writeFile(join(root, 'piece/session.json'), JSON.stringify(project, null, 2) + '\n');
+console.log(JSON.stringify({ ...await buildMusic(root), backup, warnings: project.importWarnings || [] }));
diff --git a/store/agents/music-studio/test/session.test.mjs b/store/agents/music-studio/test/session.test.mjs
new file mode 100644
index 000000000..7d26f2497
--- /dev/null
+++ b/store/agents/music-studio/test/session.test.mjs
@@ -0,0 +1,83 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { createRequire } from 'node:module';
+import { execFileSync } from 'node:child_process';
+import { readFile, mkdtemp, cp, writeFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { validateSession, secondsAt, beatAt, duplicateSection, writeSessionMidi, readSessionMidi, wavBytes } from '../template/studio/session.mjs';
+import { buildMusic } from '../template/tools/build.mjs';
+const { Midi } = createRequire(import.meta.url)('../template/studio/vendor/midi.cjs');
+const root = fileURLToPath(new URL('..', import.meta.url));
+const source = JSON.parse(await readFile(join(root, 'template/piece/session.json')));
+test('tempo changes are integrated in both directions, including a 3/8 score', () => {
+ const p = validateSession({ ...source, meter: [3, 8], tempos: [{ beat: 0, bpm: 120 }, { beat: 12, bpm: 60 }, { beat: 24, bpm: 90 }] });
+ assert.equal(secondsAt(p, 24), 18);
+ assert.equal(secondsAt(p, 30), 22);
+ for (const beat of [0, 1.5, 11.999, 12, 20, 24, 30, 79]) assert.ok(Math.abs(beatAt(p, secondsAt(p, beat)) - beat) < 1e-10);
+});
+test('MIDI handoff retains notes, tempo, meter and an intentionally quiet ending', () => {
+ const p = validateSession({ ...source, beats: 84, meter: [3, 4], tempos: [{ beat: 0, bpm: 100 }, { beat: 48, bpm: 80 }] });
+ const bytes = writeSessionMidi(p, Midi), result = readSessionMidi(bytes, Midi), raw = new Midi(bytes);
+ assert.equal(result.beats, 84); assert.deepEqual(result.meter, [3, 4]); assert.deepEqual(result.tempos, p.tempos);
+ assert.equal(raw.header.meta.at(-1).ticks / raw.header.ppq, 84);
+ for (let i = 0; i < p.tracks.length; i++) {
+ const expected = [...p.tracks[i].notes].sort((a, b) => a.beat - b.beat || a.midi - b.midi);
+ const actual = [...result.tracks[i].notes].sort((a, b) => a.beat - b.beat || a.midi - b.midi);
+ assert.equal(actual.length, expected.length);
+ for (let j = 0; j < expected.length; j++) {
+ assert.equal(actual[j].midi, expected[j].midi);
+ for (const key of ['beat', 'duration']) assert.ok(Math.abs(actual[j][key] - expected[j][key]) <= 1 / 480);
+ assert.ok(Math.abs(actual[j].velocity - expected[j].velocity) <= 1 / 127);
+ }
+ }
+});
+test('MIDI import warns about performance data it cannot reproduce', () => {
+ const midi = new Midi(writeSessionMidi(validateSession(source), Midi));
+ midi.tracks[0].addCC({ number: 64, ticks: 480, value: 1 });
+ assert.match(readSessionMidi(midi.toArray(), Midi).importWarnings[0], /automation/);
+ midi.header.timeSignatures.push({ ticks: 480, timeSignature: [3, 4] });
+ assert.throws(() => readSessionMidi(midi.toArray(), Midi), /one time signature/);
+});
+test('repeating a passage preserves the originals and its tempo changes', () => {
+ const p = validateSession({ ...source, tempos: [{ beat: 0, bpm: 100 }, { beat: 8, bpm: 80 }, { beat: 24, bpm: 120 }] });
+ const copy = duplicateSection(p, 4, 16);
+ assert.equal(copy.beats, 96);
+ assert.deepEqual(copy.tracks[0].notes.slice(0, p.tracks[0].notes.length), p.tracks[0].notes);
+ assert.deepEqual(copy.tempos.slice(-2), [{ beat: 80, bpm: 100 }, { beat: 84, bpm: 80 }]);
+ assert.ok(copy.tracks[0].notes.slice(p.tracks[0].notes.length).every(n => n.beat >= 80 && n.beat + n.duration <= 96));
+});
+test('invalid edits cannot silently cut notes or refer to absent recordings', () => {
+ const silentNote = structuredClone(source); silentNote.tracks[0].notes[0].velocity = 0;
+ assert.throws(() => validateSession(silentNote), /positive MIDI velocity/);
+ for (const mutate of [p => { p.beats = 12; }, p => { p.tracks[0].notes[0].midi = 128; }, p => { p.tempos = [{ beat: 1, bpm: 120 }]; }, p => { p.tracks[0].instrument = 'sampler'; }, p => { p.tracks[0].clips = [{ assetId: 'absent', beat: 0, duration: 1, offset: 0 }]; }]) {
+ const p = structuredClone(source); mutate(p); assert.throws(() => validateSession(p));
+ }
+});
+test('PCM handoff has a standard interleaved stereo header and bounded samples', () => {
+ const bytes = Buffer.from(wavBytes([new Float32Array([0, 1, -1]), new Float32Array([.5, -2, 2])], 48000));
+ assert.equal(bytes.toString('ascii', 0, 4), 'RIFF'); assert.equal(bytes.readUInt32LE(4), bytes.length - 8);
+ assert.equal(bytes.readUInt16LE(22), 2); assert.equal(bytes.readUInt32LE(24), 48000);
+ assert.deepEqual([0, 1, 2, 3, 4, 5].map(i => bytes.readInt16LE(44 + i * 2)), [0, 16384, 32767, -32767, -32767, 32767]);
+});
+test('fresh build embeds the real score, escapes user text, rejects stale HTML and stays not-ready', async () => {
+ const ws = await mkdtemp(join(tmpdir(), 'afterhours-build-'));
+ try {
+ await cp(join(root, 'template'), ws, { recursive: true });
+ await buildMusic(ws); await buildMusic(ws, { check: true });
+ const p = structuredClone(source); p.title = 'USER $& </script> & <music>';
+ await writeFile(join(ws, 'piece/session.json'), JSON.stringify(p));
+ await assert.rejects(buildMusic(ws, { check: true }), /out of date/); await buildMusic(ws);
+ const html = await readFile(join(ws, 'piece/index.html'), 'utf8');
+ const embedded = JSON.parse(html.match(/<script id="afterhours-data" type="application\/json">([\s\S]*?)<\/script>/)[1]);
+ assert.equal(embedded.title, p.title); assert.equal(embedded.tracks.length, 5);
+ assert.equal(JSON.parse(await readFile(join(ws, '.harness/verdict.json'))).ready, false);
+ // A pre-existing JavaScript workspace must not change the vendored parser's module type.
+ await writeFile(join(ws, 'package.json'), '{"type":"module"}');
+ const midiPath = join(ws, 'own-melody.mid');
+ await writeFile(midiPath, Buffer.from(writeSessionMidi(validateSession(source), Midi)));
+ execFileSync(process.execPath, [join(ws, 'tools/import-project.mjs'), midiPath], { cwd: ws });
+ assert.equal(JSON.parse(await readFile(join(ws, 'piece/session.json'))).tracks[0].notes.length, source.tracks[0].notes.length);
+ } finally { await rm(ws, { recursive: true, force: true }); }
+});
diff --git a/store/agents/music-studio/test/toolchain.test.mjs b/store/agents/music-studio/test/toolchain.test.mjs
index 26349ef58..f6e89deb9 100644
--- a/store/agents/music-studio/test/toolchain.test.mjs
+++ b/store/agents/music-studio/test/toolchain.test.mjs
@@ -28,11 +28,14 @@ test('every script the manifest names is in the folder and executable', () => {
}
})
-test('setup installs nothing and succeeds quietly', () => {
- assert.deepEqual(run(manifest.toolchain.setup), { code: 0, stdout: '', stderr: '' })
+test('setup installs local production tools and finds a browser', () => {
+ const result = run(manifest.toolchain.setup)
+ assert.equal(result.code, 0, result.stderr)
+ assert.match(result.stdout, /ok export browser:/)
+ assert.doesNotThrow(() => accessSync(join(here, 'toolchain/node_modules/playwright-core/index.mjs')))
})
-test('doctor says ok when sh is on PATH', () => {
+test('doctor verifies authoring and production tools', () => {
assert.equal(run(manifest.toolchain.doctor).code, 0)
})
diff --git a/store/agents/music-studio/toolchain/browser.mjs b/store/agents/music-studio/toolchain/browser.mjs
new file mode 100644
index 000000000..913298542
--- /dev/null
+++ b/store/agents/music-studio/toolchain/browser.mjs
@@ -0,0 +1,18 @@
+import { access, writeFile, readFile } from 'node:fs/promises';
+import { execFileSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { join } from 'node:path';
+const dir = fileURLToPath(new URL('.', import.meta.url));
+export async function browserPath({ install = false } = {}) {
+ const candidates = [process.env.BROWSER_EXECUTABLE, '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', process.env.PROGRAMFILES && join(process.env.PROGRAMFILES, 'Google/Chrome/Application/chrome.exe')].filter(Boolean);
+ for (const path of candidates) { try { await access(path); return path; } catch {} }
+ process.env.PLAYWRIGHT_BROWSERS_PATH = join(dir, 'browsers');
+ const { chromium } = await import('./node_modules/playwright-core/index.mjs');
+ const path = chromium.executablePath();
+ try { await access(path); return path; } catch {}
+ if (!install) throw new Error('Browser missing. Run the Music Studio setup script.');
+ execFileSync(process.execPath, [join(dir, 'node_modules/playwright-core/cli.js'), 'install', 'chromium'], { stdio: 'inherit', env: process.env });
+ await access(path); return path;
+}
+if (process.argv.includes('--install')) console.log(`ok export browser: ${await browserPath({ install: true })}`);
+if (process.argv.includes('--check')) console.log(`ok export browser: ${await browserPath()}`);
diff --git a/store/agents/music-studio/toolchain/doctor.sh b/store/agents/music-studio/toolchain/doctor.sh
index 348830f87..cf5f6c3c4 100755
--- a/store/agents/music-studio/toolchain/doctor.sh
+++ b/store/agents/music-studio/toolchain/doctor.sh
@@ -1,3 +1,5 @@
-#!/usr/bin/env bash
-# Doctor: the piece is just a file served by the shared web-viewer; no extra runtime needed.
-exit 0
+#!/bin/sh
+set -eu
+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+node -e 'if(Number(process.versions.node.split(".")[0]) < 20) process.exit(1); console.log("ok Node.js (authoring tools)")'
+node "$here/browser.mjs" --check
diff --git a/store/agents/music-studio/toolchain/package-lock.json b/store/agents/music-studio/toolchain/package-lock.json
new file mode 100644
index 000000000..dcba3614d
--- /dev/null
+++ b/store/agents/music-studio/toolchain/package-lock.json
@@ -0,0 +1,48 @@
+{
+ "name": "afterhours-authoring",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "afterhours-authoring",
+ "dependencies": {
+ "@tonejs/midi": "2.0.28",
+ "playwright-core": "1.63.0"
+ }
+ },
+ "node_modules/@tonejs/midi": {
+ "version": "2.0.28",
+ "resolved": "https://registry.npmjs.org/@tonejs/midi/-/midi-2.0.28.tgz",
+ "integrity": "sha512-RII6YpInPsOZ5t3Si/20QKpNqB1lZ2OCFJSOzJxz38YdY/3zqDr3uaml4JuCWkdixuPqP1/TBnXzhQ39csyoVg==",
+ "license": "MIT",
+ "dependencies": {
+ "array-flatten": "^3.0.0",
+ "midi-file": "^1.2.2"
+ }
+ },
+ "node_modules/array-flatten": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-3.0.0.tgz",
+ "integrity": "sha512-zPMVc3ZYlGLNk4mpK1NzP2wg0ml9t7fUgDsayR5Y5rSzxQilzR9FGu/EH2jQOcKSAeAfWeylyW8juy3OkWRvNA==",
+ "license": "MIT"
+ },
+ "node_modules/midi-file": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/midi-file/-/midi-file-1.2.4.tgz",
+ "integrity": "sha512-B5SnBC6i2bwJIXTY9MElIydJwAmnKx+r5eJ1jknTLetzLflEl0GWveuBB6ACrQpecSRkOB6fhTx1PwXk2BVxnA==",
+ "license": "MIT"
+ },
+ "node_modules/playwright-core": {
+ "version": "1.63.0",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
+ "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ }
+ }
+}
diff --git a/store/agents/music-studio/toolchain/package.json b/store/agents/music-studio/toolchain/package.json
new file mode 100644
index 000000000..8625cd7ba
--- /dev/null
+++ b/store/agents/music-studio/toolchain/package.json
@@ -0,0 +1,9 @@
+{
+ "name": "afterhours-authoring",
+ "private": true,
+ "type": "module",
+ "dependencies": {
+ "@tonejs/midi": "2.0.28",
+ "playwright-core": "1.63.0"
+ }
+}
diff --git a/store/agents/music-studio/toolchain/setup.sh b/store/agents/music-studio/toolchain/setup.sh
index d32f7d778..3c263d1fc 100755
--- a/store/agents/music-studio/toolchain/setup.sh
+++ b/store/agents/music-studio/toolchain/setup.sh
@@ -1,3 +1,8 @@
-#!/usr/bin/env bash
-# Music Studio has no toolchain: everything is inline HTML + Web Audio. Nothing to install.
-exit 0
+#!/bin/sh
+# Browser exports use pinned tools installed in this package, never globally.
+set -eu
+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+node -e 'if(Number(process.versions.node.split(".")[0]) < 20) process.exit(1)'
+cd "$here"
+npm ci --ignore-scripts --no-audit --no-fund
+node browser.mjs --install
diff --git a/store/showcase/generative-art/canopy.png b/store/showcase/generative-art/canopy.png
new file mode 100644
index 000000000..966ceb085
Binary files /dev/null and b/store/showcase/generative-art/canopy.png differ
diff --git a/store/showcase/generative-art/night-garden.png b/store/showcase/generative-art/night-garden.png
new file mode 100644
index 000000000..b30fad493
Binary files /dev/null and b/store/showcase/generative-art/night-garden.png differ
diff --git a/store/showcase/generative-art/rain-atlas.png b/store/showcase/generative-art/rain-atlas.png
new file mode 100644
index 000000000..a4b46175d
Binary files /dev/null and b/store/showcase/generative-art/rain-atlas.png differ
diff --git a/store/showcase/generative-art/starter.jpg b/store/showcase/generative-art/starter.jpg
index 48adf2192..859e4a3a7 100644
Binary files a/store/showcase/generative-art/starter.jpg and b/store/showcase/generative-art/starter.jpg differ
diff --git a/store/showcase/music-studio/keepsake.png b/store/showcase/music-studio/keepsake.png
new file mode 100644
index 000000000..ecaf47da3
Binary files /dev/null and b/store/showcase/music-studio/keepsake.png differ
diff --git a/store/showcase/music-studio/orbit-runner.png b/store/showcase/music-studio/orbit-runner.png
new file mode 100644
index 000000000..2720ae928
Binary files /dev/null and b/store/showcase/music-studio/orbit-runner.png differ
diff --git a/store/showcase/music-studio/starter.jpg b/store/showcase/music-studio/starter.jpg
index 28bd1591d..7c68c51b9 100644
Binary files a/store/showcase/music-studio/starter.jpg and b/store/showcase/music-studio/starter.jpg differ
diff --git a/store/tools/build-experiences.mjs b/store/tools/build-experiences.mjs
index 04b3674bb..f2be46578 100644
--- a/store/tools/build-experiences.mjs
+++ b/store/tools/build-experiences.mjs
@@ -1,8 +1,10 @@
#!/usr/bin/env node
-// Compile dependency-free, editable single-file starters. No build is needed after installation.
+// Package portable HTML studios. Art/Music use their own source-project builders.
import { readFile, writeFile, mkdir } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { resolve } from "node:path";
+import { buildArt } from "../agents/generative-art/template/tools/build.mjs";
+import { buildMusic } from "../agents/music-studio/template/tools/build.mjs";
const source = new URL("./experiences/", import.meta.url);
export const experiences = [
{
@@ -58,6 +60,23 @@ export async function build({ check = false } = {}) {
]);
let drift = false;
for (const exp of experiences) {
+ if (exp.id === "generative-art" || exp.id === "music-studio") {
+ try {
+ const packageRoot = new URL(`../agents/${exp.id}/`, import.meta.url);
+ const icon = await readFile(new URL('brand/icon.svg', packageRoot), 'utf8');
+ const studioIcon = new URL('template/studio/icon.svg', packageRoot);
+ if (check) {
+ if (await readFile(studioIcon, 'utf8') !== icon) throw new Error(`${exp.id}: packaged studio icon is out of date.`);
+ } else await writeFile(studioIcon, icon);
+ const builder = exp.id === 'generative-art' ? buildArt : buildMusic;
+ await builder(fileURLToPath(new URL(`../agents/${exp.id}/template/`, import.meta.url)), { check });
+ } catch (error) {
+ if (!check) throw error;
+ console.error(error.message);
+ drift = true;
+ }
+ continue;
+ }
const [model, style, body, app] = await Promise.all(
["mjs", "css", "html", "js"].map((ext) => read(`${exp.id}.${ext}`)),
);
diff --git a/store/tools/experience-tests/README.md b/store/tools/experience-tests/README.md
index 8801073d9..42204af24 100644
--- a/store/tools/experience-tests/README.md
+++ b/store/tools/experience-tests/README.md
@@ -1,8 +1,11 @@
# Experience verification
-The seven interactive starters are generated by `store/tools/build-experiences.mjs` from the
-reviewable model, CSS, markup and UI sources in `store/tools/experiences/`. The installed output is
-one editable HTML file and a small Node checker; the runtime has no package dependencies.
+All seven packages are withdrawn from public discovery. Art and Music have authoring rebuilds;
+their source is inside each package's `template/studio/`, with a drawing program/project or an
+editable score. `build-experiences.mjs` delegates to their package builders. The five parked
+packages and the retained original Art/Music models live in `store/tools/experiences/`.
+See [the product review](../../../work/SUPERPOWERS.md) and
+[current evidence](../../../work/AUTHORING-REBUILD.md). These are technical checks, not product approval.
From the repository root:
@@ -11,10 +14,11 @@ node store/tools/build-experiences.mjs
node store/tools/build-experiences.mjs --check
node store/tools/build-experience-branding.mjs --check
node --test store/tools/experience-tests/models.test.mjs
+node --test store/agents/generative-art/test/*.test.mjs store/agents/music-studio/test/*.test.mjs
node --test store/viewers/web-viewer/test/*.test.mjs
```
-Every generated workspace includes `tools/check.mjs`. Run it **in the workspace**:
+The parked packages include a pure-model checker. Run it **in their workspace**:
```sh
node tools/check.mjs --seeds 100
@@ -24,6 +28,23 @@ It extracts the pure model from the actual edited artifact, exercises domain inv
requested seeds, repeats each result and writes `.harness/model-check.json`. It does not claim
browser, visual or listening verification and does not mark the workspace ready.
+The rebuilt Art and Music workspaces use `node tools/check.mjs` for source/preview agreement and
+`node tools/export.mjs` for real browser delivery. Art supports `--seeds N --scale 1|2|4`; Music
+exports the score, mix, MIDI and aligned stems. Their setup scripts install pinned tools locally.
+Neither exporter sets a ready verdict from technical measurements.
+
+To reproduce all six targeted revisions, including the saved-project import/backup workflow:
+
+```sh
+node store/tools/experience-tests/revisions.mjs /tmp/authoring-revisions --export
+python3 -m venv /tmp/music-delivery-reader
+/tmp/music-delivery-reader/bin/pip install mido==1.3.3
+/tmp/music-delivery-reader/bin/python store/tools/experience-tests/verify-music-delivery.py /tmp/authoring-revisions/keepsake/after
+```
+
+The independent reader checks WAVs, MIDI and stem summation with Python wave/zipfile and Mido.
+It deliberately reports `listeningReviewed:false`.
+
## Real browser suite
Install the pinned development dependency in this directory, with system Chrome available:
@@ -35,7 +56,9 @@ npm run browser
`BROWSER_EXECUTABLE` selects another Chromium executable. `PLAYWRIGHT_MODULE` can select an existing
Playwright Core module by absolute path. `EXPERIENCE_OUTPUT` selects the evidence directory (default:
-`work/experience-evidence`). These are test dependencies, never installed into a user's workspace.
+`work/experience-evidence`). Set `EXPERIENCE_IDS=generative-art,music-studio` to select the rebuilt
+tools. The test dependency is local to this directory; production export dependencies live in
+the two packages' toolchain directories, outside user workspaces.
Set `SOFTWARE_WEBGL=1` to exercise SwiftShader instead of the machine's graphics driver.
Run `node performance.mjs` for 30 warmed artifact requests and five save-to-ready-and-paint
samples per experience. It waits for the changed document and two animation frames, not just
@@ -47,7 +70,7 @@ downloads and their contents, seed changes and reload preservation, paused file
layouts, browser exceptions and screenshots. A separate fixture verifies sibling fetch,
localStorage, ES modules and recovery when a missing artifact is created.
-The model suite checks 100 art/brand/data/music-score/arena/autopilot seeds, 16 rendered audio
+The retained original-model suite checks 100 art/brand/data/music-score/arena/autopilot seeds, 16 rendered audio
arrangements and 32 walkable voxel worlds. These are finite samples, not a claim about every seed
or every browser. Browser tests are separate from Node coverage; a Node coverage number must
never be reported as coverage of the UI or shell scripts.
@@ -59,6 +82,8 @@ this checkout, run `HARNESS_MACHINE_ID=<local machine id> node daemon.mjs`. It c
idle Claude sessions through the desktop's loopback protocol, checks engine readiness, framework
materialization, instructions, initial verdicts, installed viewer routing and a browser file reload.
It sends no prompts and deletes only its own temporary sessions and workspaces in cleanup.
+`EXPERIENCE_IDS` also selects packages here. A passing idle-session check does not establish that
+the coding engine can complete a real brief. That is a separate acceptance gate.
## Original harness identities
diff --git a/store/tools/experience-tests/browser.mjs b/store/tools/experience-tests/browser.mjs
index 65ec28618..94bdb400a 100644
--- a/store/tools/experience-tests/browser.mjs
+++ b/store/tools/experience-tests/browser.mjs
@@ -10,6 +10,7 @@ import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { createHtmlViewer } from "../../viewers/web-viewer/viewer.mjs";
import { experiences } from "../build-experiences.mjs";
+import { musicBrowser } from "./music-browser.mjs";
const { chromium } = await import(
process.env.PLAYWRIGHT_MODULE || "playwright-core"
);
@@ -127,6 +128,7 @@ async function one(exp) {
acceptDownloads: true,
}),
page = await context.newPage();
+ page.setDefaultTimeout(30000);
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
const checks = [];
@@ -161,45 +163,61 @@ async function one(exp) {
assert.equal(await page.locator("#empty").isHidden(), true);
if (exp.id === "generative-art") {
- const original = createHash("sha256")
- .update(await f.locator("#art").evaluate((c) => c.toDataURL()))
- .digest("hex");
+ const original = await f.evaluate(() => fieldwork.getSVG());
await f.locator("#next-seed").click();
- assert.notEqual(
- createHash("sha256")
- .update(await f.locator("#art").evaluate((c) => c.toDataURL()))
- .digest("hex"),
- original,
- );
+ await f.waitForFunction(before => fieldwork.getSVG() !== before, original);
await f.locator("#seed").fill("42");
await f.locator("#seed-form button[type=submit]").click();
- assert.equal(
- createHash("sha256")
- .update(await f.locator("#art").evaluate((c) => c.toDataURL()))
- .digest("hex"),
- original,
- );
- await f.locator("#mode").selectOption("orbits");
- assert.notEqual(
- createHash("sha256")
- .update(await f.locator("#art").evaluate((c) => c.toDataURL()))
- .digest("hex"),
- original,
- );
- await f.locator("#mode").selectOption("contours");
- const bytes = await download(
- page,
- () => f.locator("#export").click(),
- "fieldwork-print.png",
- );
- assert.equal(bytes.readUInt32BE(16), 1600);
- assert.equal(bytes.readUInt32BE(20), 2000);
- checks.push(
- "pixel deterministic",
- "different seeds",
- "technique control",
- "1600×2000 PNG",
- );
+ await f.waitForFunction(before => fieldwork.getSVG() === before, original);
+ await f.locator("#control-headline").fill("USER & STUDIO");
+ await f.waitForFunction(() => fieldwork.getSVG().includes('USER &amp;'));
+ await f.locator("#undo").click();
+ await f.waitForFunction(before => fieldwork.getSVG() === before, original);
+ await f.locator("#redo").click();
+ await f.waitForFunction(() => fieldwork.getSVG().includes('USER &amp;'));
+ await f.locator('#formats button').nth(2).click();
+ await f.waitForFunction(() => fieldwork.getSVG().includes('width="1920" height="800"'));
+ const bytes = await download(page, () => f.locator("#export-png").click(), "fieldwork-banner.png");
+ assert.equal(bytes.readUInt32BE(16), 1920); assert.equal(bytes.readUInt32BE(20), 800);
+ await f.locator('input[type=file][aria-label="Your logo (optional)"]').setInputFiles(join(root, 'brand/icon.png'));
+ await f.waitForFunction(() => fieldwork.getSVG().includes('data:image/png;base64,'));
+ const saved = JSON.parse((await download(page, () => f.locator('#save-project').click(), 'fieldwork-project.json')).toString());
+ assert.equal(saved.controls.find(c => c.key === 'headline').value, 'USER & STUDIO');
+ assert.ok(saved.assets[0].data.startsWith('data:image/png;base64,'));
+ await download(page, () => f.locator('#export-kit').click(), 'fieldwork-kit.zip');
+ const kit = JSON.parse(execFileSync('python3', ['-c', `import sys,json,zipfile,struct
+with zipfile.ZipFile(sys.argv[1]) as z:
+ assert z.testzip() is None
+ assert len([n for n in z.namelist() if n.endswith('.svg')])==3
+ assert len([n for n in z.namelist() if n.endswith('.png')])==3
+ assert b'USER &amp;' in z.read('03-Banner.svg')
+ assert struct.unpack('>II',z.read('03-Banner.png')[16:24])==(1920,800)
+ print(json.dumps(z.namelist()))`, join(output, 'fieldwork-kit.zip')], {encoding:'utf8'}));
+ assert.ok(kit.includes('source/artwork.js'));
+ await download(page, () => f.locator('#export-html').click(), 'fieldwork-portable.html');
+ const portable = await context.newPage();
+ await portable.goto(new URL('file://' + join(output, 'fieldwork-portable.html')).href);
+ await portable.locator('body[data-ready=true]').waitFor();
+ assert.equal(await portable.locator('#control-headline').inputValue(), 'USER & STUDIO');
+ await portable.close();
+ await f.locator('#reset-project').click();
+ await f.waitForFunction(before => fieldwork.getSVG() === before, original);
+ await f.locator('#project-file').setInputFiles(join(output, 'fieldwork-project.json'));
+ await f.waitForFunction(() => fieldwork.getSVG().includes('USER &amp;'));
+ assert.equal(await f.locator('#width').inputValue(), '1920');
+ // A user-approved draft and a new agent revision must both remain recoverable.
+ const projectPath = join(ws, 'sketch/project.json');
+ const revision = JSON.parse(await readFile(projectPath, 'utf8'));
+ revision.controls.find(c => c.key === 'headline').value = 'AGENT REVISION';
+ await writeFile(projectPath, JSON.stringify(revision));
+ execFileSync(process.execPath, [join(ws, 'tools/build.mjs')]);
+ await page.frameLocator('#preview').locator('#revision-notice:not([hidden])').waitFor();
+ f = frameOf(page);
+ await f.locator('#keep-draft').click();
+ await f.waitForFunction(() => fieldwork.getSVG().includes('USER &amp;'));
+ await f.locator('#reset-project').click();
+ await f.waitForFunction(() => fieldwork.getSVG().includes('AGENT'));
+ checks.push('same-seed geometry', 'original editable text', 'undo/redo', 'adaptive formats', 'own image import', 'editable SVG/PNG kit reopened by Python', 'portable HTML reopened', 'project roundtrip', 'agent revision preserves user draft');
} else if (exp.id === "creative-direction") {
await f.locator("#brand-name").fill("COVE STUDIO");
await f.locator("#directions button").nth(2).click();
@@ -259,43 +277,7 @@ async function one(exp) {
"filtered CSV",
);
} else if (exp.id === "music-studio") {
- const original = await f.evaluate(() =>
- Array.from(rendered.samples.slice(0, 8000)),
- );
- await f.locator("#play").click();
- await f.waitForFunction(
- () => playing && audioContext.state === "running",
- );
- await f.locator("#stop").click();
- await f.locator("#play").click();
- assert.deepEqual(
- await f.evaluate(() => Array.from(rendered.samples.slice(0, 8000))),
- original,
- );
- await f.locator("#stop").click();
- const old = await f
- .getByRole("button", { name: "Kick step 2", exact: true })
- .getAttribute("aria-pressed");
- await f.getByRole("button", { name: "Kick step 2", exact: true }).click();
- assert.notEqual(
- await f
- .getByRole("button", { name: "Kick step 2", exact: true })
- .getAttribute("aria-pressed"),
- old,
- );
- const wav = await download(
- page,
- () => f.locator("#export-wav").click(),
- "afterhours.wav",
- );
- assert.equal(wav.toString("ascii", 0, 4), "RIFF");
- assert.ok(wav.length > 500000);
- checks.push(
- "audio running",
- "replay same PCM",
- "step editing",
- "WAV export",
- );
+ f = await musicBrowser({ page, context, f, ws, output, download, frameOf, checks });
} else if (exp.id === "game-master") {
await f.locator("#step").click();
assert.match(await f.locator("#turn").textContent(), /01/);
@@ -404,6 +386,7 @@ async function one(exp) {
);
}
await visibleScreenshot(page, exp.id + "-desktop");
+ if (exp.id !== "music-studio") {
// Seed changes propagate to the shell and survive a real reload.
await f.locator("#seed").fill("73");
await f.locator("#seed-form button[type=submit]").click();
@@ -419,6 +402,12 @@ async function one(exp) {
f = await waitReady(page);
assert.equal(await f.locator("#seed").inputValue(), "73");
checks.push("seed survives reload");
+ } else {
+ await page.locator("#reload").click();
+ f = await waitReady(page);
+ assert.equal(await f.locator("#title").textContent(), "NEW AGENT SCORE");
+ checks.push("edited score survives shell reload");
+ }
// Watcher integration: pause holds the active document, resume applies the saved change.
await page.locator("#auto").click();
const held = await page.locator("#preview").getAttribute("src");
diff --git a/store/tools/experience-tests/daemon.mjs b/store/tools/experience-tests/daemon.mjs
index fa695c87c..92bfcac06 100644
--- a/store/tools/experience-tests/daemon.mjs
+++ b/store/tools/experience-tests/daemon.mjs
@@ -79,7 +79,7 @@ try {
channel: process.env.BROWSER_EXECUTABLE ? undefined : "chrome",
headless: true,
});
- for (const exp of experiences) {
+ for (const exp of experiences.filter(exp => !process.env.EXPERIENCE_IDS || process.env.EXPERIENCE_IDS.split(',').includes(exp.id))) {
const dsh = "autonomous/" + exp.id;
assert.ok(
list.dsh?.find((entry) => entry.id === dsh && entry.installed),
@@ -125,10 +125,8 @@ try {
);
assert.equal(verdict.artifact, exp.path + "/index.html");
assert.equal(verdict.ready, false);
- assert.match(
- await readFile(join(workspace, "AGENTS.md"), "utf8"),
- /Shipped experience/,
- );
+ const instructions = await readFile(join(repo, 'store/agents', exp.id, 'AGENTS.md'), 'utf8');
+ assert.ok((await readFile(join(workspace, "AGENTS.md"), "utf8")).includes(instructions.trim()), 'Installed authoring instructions must match the package.');
const actual = await readFile(
join(workspace, exp.path, "index.html"),
"utf8",
diff --git a/store/tools/experience-tests/music-browser.mjs b/store/tools/experience-tests/music-browser.mjs
new file mode 100644
index 000000000..26687bea1
--- /dev/null
+++ b/store/tools/experience-tests/music-browser.mjs
@@ -0,0 +1,86 @@
+import assert from 'node:assert/strict';
+import { readFile, writeFile } from 'node:fs/promises';
+import { execFileSync } from 'node:child_process';
+import { join } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { wavBytes } from '../../agents/music-studio/template/studio/session.mjs';
+
+export async function musicBrowser({ page, context, f, ws, output, download, frameOf, checks }) {
+ const ready = () => f.waitForFunction(() => { const s = afterhours.getState(); return s.revision === s.mixRevision && document.querySelector('#error').hidden; }, null, { timeout: 30000 });
+ const edit = async (id, value) => { await f.locator('#' + id).fill(String(value)); await f.locator('#' + id).press('Tab'); };
+ const original = await f.evaluate(() => afterhours.getProject());
+ await f.locator('#play').click();
+ await f.waitForFunction(() => afterhours.getState().playing && afterhours.getState().context === 'running');
+ await f.locator('#stop').click();
+ const basePeak = await f.evaluate(() => afterhours.getState().peak);
+ await f.locator('#solo').click(); await ready();
+ assert.notEqual(await f.evaluate(() => afterhours.getState().peak), basePeak);
+ await f.locator('#undo').click(); await ready();
+ console.log('Music: playback and solo verified');
+ // Author an actual note through the visible piano roll, then revise, drag and undo it.
+ await f.locator('#add-track').click(); await edit('track-name', 'My approved phrase');
+ await f.locator('#piano').click({ position: { x: 140, y: 75 } });
+ assert.equal(await f.evaluate(() => afterhours.getProject().tracks.at(-1).notes.length), 1);
+ await edit('note-pitch', 'F#4'); await edit('note-start', 2); await edit('note-length', .75);
+ assert.deepEqual(await f.evaluate(() => { const n = afterhours.getProject().tracks.at(-1).notes[0]; return [n.midi, n.beat, n.duration]; }), [66, 2, .75]);
+ // Geometry is read only to aim the pointer at the actual rendered note.
+ const target = await f.evaluate(() => ({ ...noteRects[0] }));
+ await f.locator('#piano').scrollIntoViewIfNeeded();
+ const box = await f.locator('#piano').boundingBox();
+ await page.mouse.move(box.x + target.x + 2, box.y + target.y + 2); await page.mouse.down();
+ await page.mouse.move(box.x + target.x + 60, box.y + target.y + 2, { steps: 6 }); await page.mouse.up();
+ assert.ok(await f.evaluate(() => afterhours.getProject().tracks.at(-1).notes[0].beat > 2));
+ await f.locator('#undo').click();
+ assert.equal(await f.evaluate(() => afterhours.getProject().tracks.at(-1).notes[0].beat), 2);
+ await f.locator('#piano').click({ position: { x: target.x + 2, y: target.y + 2 } });
+ await f.locator('#delete-note').click();
+ assert.equal(await f.evaluate(() => afterhours.getProject().tracks.at(-1).notes.length), 0);
+ await f.locator('#undo').click(); await ready();
+ console.log('Music: note authoring verified');
+ const midi = await download(page, () => f.locator('#export-midi').click(), 'afterhours-edited.mid');
+ const saved = await download(page, () => f.locator('#save-project').click(), 'afterhours-edited.json');
+ await f.locator('#midi-file').setInputFiles({ name: 'my-phrase.mid', mimeType: 'audio/midi', buffer: midi }); await ready();
+ assert.equal(await f.evaluate(() => afterhours.getProject().tracks.at(-1).notes[0].midi), 66);
+ assert.equal(await f.evaluate(() => afterhours.getProject().beats), original.beats);
+ await f.locator('#project-file').setInputFiles({ name: 'approved.afterhours.json', mimeType: 'application/json', buffer: saved }); await ready();
+ assert.equal(await f.locator('#track-name').inputValue(), original.tracks[0].name);
+ console.log('Music: MIDI and project roundtrips verified');
+ // This is an original test tone, not a claim of a user's recorded performance.
+ const tone = Float32Array.from({ length: 48000 }, (_, i) => Math.sin(i * 2 * Math.PI * 440 / 48000) * .2 * Math.min(1, i / 480, (48000 - i) / 480));
+ await f.locator('#audio-file').setInputFiles({ name: 'own-recording-fixture.wav', mimeType: 'audio/wav', buffer: Buffer.from(wavBytes([tone, tone], 48000)) });
+ await f.waitForFunction(() => afterhours.getProject().assets.length === 1); await ready();
+ await edit('clip-duration', .5); await edit('clip-offset', .2); await edit('clip-beat', 4); await ready();
+ const recording = await f.evaluate(async () => { const p = afterhours.getProject(), t = p.tracks.at(-1), r = await afterhours.render({ onlyTrack: t.id }); return { clip: t.clips[0], before: r.channels[0].slice(0, Math.floor(2.39 * r.sampleRate)).some(x => Math.abs(x) > 1e-7), peak: r.peak }; });
+ assert.deepEqual([recording.clip.beat, recording.clip.offset, recording.clip.duration], [4, .2, .5]);
+ assert.equal(recording.before, false); assert.ok(recording.peak > .01);
+ assert.equal(await f.evaluate(async () => { const p = afterhours.getProject(), t = p.tracks.at(-1); t.clips[0].gain = 0; return (await renderSession(p, { onlyTrack: t.id })).peak; }), 0, 'A zero-gain recording must be silent');
+ console.log('Music: imported recording timing verified');
+ await f.locator('#duplicate-section').click();
+ assert.equal(await f.locator('#clip-select option').count(), 2);
+ await f.locator('#clip-select').selectOption('1'); await edit('clip-beat', 86);
+ assert.deepEqual(await f.evaluate(() => afterhours.getProject().tracks.at(-1).clips.map(c => c.beat)), [4, 86]);
+ await f.locator('#undo').click(); await f.locator('#undo').click();
+ assert.equal(await f.evaluate(() => afterhours.getProject().beats), original.beats);
+ await f.locator('#add-track').click(); await f.locator('#instrument').selectOption('sampler');
+ await f.locator('#piano').click({ position: { x: 70, y: 75 } }); await ready();
+ assert.equal(await f.evaluate(() => afterhours.getProject().tracks.at(-1).instrument), 'sampler');
+ assert.ok(await f.evaluate(async () => (await afterhours.render({ onlyTrack: afterhours.getProject().tracks.at(-1).id })).peak > .001));
+ await download(page, () => f.locator('#export-wav').click(), 'afterhours-own-material.wav');
+ await download(page, () => f.locator('#export-stems').click(), 'afterhours-production.zip');
+ await download(page, () => f.locator('#export-html').click(), 'afterhours-portable.html');
+ const current = await f.evaluate(() => afterhours.getProject());
+ const portable = await context.newPage(); await portable.goto(pathToFileURL(join(output, 'afterhours-portable.html')).href);
+ await portable.locator('body[data-ready=true]').waitFor();
+ assert.deepEqual(await portable.evaluate(() => afterhours.getProject()), current); await portable.close();
+ // Source revisions and browser edits must both survive a reload.
+ const path = join(ws, 'piece/session.json'), revision = JSON.parse(await readFile(path, 'utf8'));
+ revision.title = 'NEW AGENT SCORE'; await writeFile(path, JSON.stringify(revision));
+ execFileSync(process.execPath, [join(ws, 'tools/build.mjs')]);
+ await page.frameLocator('#preview').locator('#revision-notice:not([hidden])').waitFor(); f = frameOf(page);
+ await f.locator('#keep-draft').click(); await ready();
+ assert.deepEqual(await f.evaluate(() => afterhours.getProject().tracks), current.tracks);
+ await f.locator('#reset-project').click(); await ready();
+ assert.equal(await f.locator('#title').textContent(), 'NEW AGENT SCORE');
+ checks.push('real audio playback', 'solo changes audio', 'note add/edit/drag/delete and undo', 'MIDI notes roundtrip', 'project roundtrip', 'own recording import/trim/move', 'repeated clips individually editable', 'pitched sample instrument', 'mix and aligned stem export', 'portable studio reopened', 'agent revision preserves approved work');
+ return f;
+}
diff --git a/store/tools/experience-tests/revisions.mjs b/store/tools/experience-tests/revisions.mjs
new file mode 100644
index 000000000..952c3e4ce
--- /dev/null
+++ b/store/tools/experience-tests/revisions.mjs
@@ -0,0 +1,65 @@
+// Reproducible revision scenarios, including the real saved-project -> source bridge.
+// These are authored acceptance fixtures, not testimonials or autonomous-agent evals.
+// node revisions.mjs /absolute/output [--export]
+import assert from 'node:assert/strict';
+import { readFile, writeFile, mkdir, cp, readdir } from 'node:fs/promises';
+import { execFileSync } from 'node:child_process';
+import { resolve, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { buildArt } from '../../agents/generative-art/template/tools/build.mjs';
+import { buildMusic } from '../../agents/music-studio/template/tools/build.mjs';
+import { renderProject } from '../../agents/generative-art/template/studio/project.mjs';
+const repo = fileURLToPath(new URL('../../../', import.meta.url));
+if (!process.argv[2]) throw new Error('Pass an output folder for the six revision workspaces.');
+const output = resolve(process.argv[2]), report = [];
+const artCases = [
+ ['night-garden', 'template/sketch', 'details', 'OCTOBER 9—11 · RIVERSIDE GARDENS', 'Change the date and venue; preserve the approved identity.'],
+ ['canopy', 'examples/coffee', 'lot', 'LOT 044 / HONEY CATURRA', 'Update the product lot; preserve our logo, origin, colors and illustration.'],
+ ['rain-atlas', 'examples/data-atlas', 'csv', null, 'Correct January from 42 to 84 mm; preserve every other observation and the layout.'],
+];
+for (const [id, source, key, value, request] of artCases) {
+ const root = join(repo, 'store/agents/generative-art'), ws = join(output, id);
+ await cp(join(root, 'template'), ws, { recursive: true }); await cp(join(root, source), join(ws, 'sketch'), { recursive: true });
+ await buildArt(ws);
+ const html = await readFile(join(ws, 'sketch/index.html'), 'utf8');
+ const before = JSON.parse(html.match(/<script id="fieldwork-data" type="application\/json">([\s\S]*?)<\/script>/)[1]), after = structuredClone(before);
+ const control = after.controls.find(c => c.key === key); control.value = value ?? control.value.replace('Jan,42', 'Jan,84');
+ assert.deepEqual(after.assets, before.assets); assert.equal(after.code, before.code); assert.equal(after.seed, before.seed);
+ assert.deepEqual(after.controls.filter(c => c.key !== key), before.controls.filter(c => c.key !== key));
+ await mkdir(join(ws, 'before'), { recursive: true }); await mkdir(join(ws, 'after'), { recursive: true });
+ for (let i = 0; i < before.formats.length; i++) {
+ const a = renderProject(before, { format: i }), b = renderProject(after, { format: i }); assert.notEqual(a, b);
+ if (key !== 'csv') assert.deepEqual(a.match(/<path\b[^>]*>/g), b.match(/<path\b[^>]*>/g));
+ else assert.match(b, /1430 MM/);
+ await writeFile(join(ws, 'before', `${i + 1}.svg`), a); await writeFile(join(ws, 'after', `${i + 1}.svg`), b);
+ }
+ await writeFile(join(ws, 'before/project.fieldwork.json'), JSON.stringify(before, null, 2));
+ const file = join(ws, 'revision.fieldwork.json'); await writeFile(file, JSON.stringify(after));
+ execFileSync(process.execPath, [join(ws, 'tools/import-project.mjs'), file]);
+ assert.ok((await readdir(join(ws, '.harness/history'))).length > 0); await buildArt(ws, { check: true });
+ if (process.argv.includes('--export')) execFileSync(process.execPath, [join(ws, 'tools/export.mjs'), '--seeds', '1', '--out', 'after'], { env: { ...process.env, GENART_DSH_DIR: root }, stdio: 'inherit' });
+ report.push({ id, request, preserved: ['drawing program', 'seed', 'assets', 'unrelated controls', 'source backup'], formats: before.formats.length });
+}
+for (const [id, source, target, request] of [
+ ['blue-hour', 'template/piece', 'motif', 'Add one quiet final echo of the motif; leave the accompaniment intact.'],
+ ['orbit-runner', 'examples/orbit-runner', 'kit', 'Remove the hi-hats from the first two launch bars; preserve the hook, bass, kicks and snare.'],
+ ['keepsake', 'examples/keepsake', 'answer', 'Add a small bell response before the slower section; preserve the supplied melody and tempo map.'],
+]) {
+ const root = join(repo, 'store/agents/music-studio'), ws = join(output, id);
+ await cp(join(root, 'template'), ws, { recursive: true }); await cp(join(root, source), join(ws, 'piece'), { recursive: true });
+ await buildMusic(ws);
+ const html = await readFile(join(ws, 'piece/index.html'), 'utf8'), before = JSON.parse(html.match(/<script id="afterhours-data" type="application\/json">([\s\S]*?)<\/script>/)[1]), after = structuredClone(before), track = after.tracks.find(t => t.id === target);
+ if (id === 'blue-hour') track.notes.push({ beat: 78.95, midi: 74, duration: .2, velocity: .2 });
+ else if (id === 'orbit-runner') track.notes = track.notes.filter(n => !(n.midi === 42 && n.beat >= 8 && n.beat < 16));
+ else track.notes.push({ beat: 15, midi: 79, duration: .5, velocity: .28 }, { beat: 15.75, midi: 76, duration: .6, velocity: .28 });
+ assert.deepEqual(after.tracks.filter(t => t.id !== target), before.tracks.filter(t => t.id !== target));
+ assert.deepEqual(after.tempos, before.tempos); assert.equal(after.beats, before.beats); assert.deepEqual(after.assets, before.assets);
+ await mkdir(join(ws, 'before'), { recursive: true }); await writeFile(join(ws, 'before/project.afterhours.json'), JSON.stringify(before, null, 2));
+ const file = join(ws, 'revision.afterhours.json'); await writeFile(file, JSON.stringify(after));
+ execFileSync(process.execPath, [join(ws, 'tools/import-project.mjs'), file]);
+ assert.ok((await readdir(join(ws, '.harness/history'))).length > 0); await buildMusic(ws, { check: true });
+ if (process.argv.includes('--export')) execFileSync(process.execPath, [join(ws, 'tools/export.mjs'), '--out', 'after'], { env: { ...process.env, MUSIC_DSH_DIR: root }, stdio: 'inherit' });
+ report.push({ id, request, preserved: ['unrelated tracks and notes', 'tempo map', 'duration', 'assets', 'source backup'], notesBefore: before.tracks.reduce((n, t) => n + t.notes.length, 0), notesAfter: after.tracks.reduce((n, t) => n + t.notes.length, 0) });
+}
+await writeFile(join(output, 'revisions.json'), JSON.stringify(report, null, 2));
+console.log('PASS: six targeted revisions preserve approved material and source history.');
diff --git a/store/tools/experience-tests/verify-music-delivery.py b/store/tools/experience-tests/verify-music-delivery.py
new file mode 100644
index 000000000..b6dc5f9a3
--- /dev/null
+++ b/store/tools/experience-tests/verify-music-delivery.py
@@ -0,0 +1,76 @@
+#!/usr/bin/env python3
+"""Independent delivery reader: Python wave/zipfile + mido (not the JS writer).
+Install mido==1.3.3 in a disposable venv. Pass a production ZIP or delivery folder.
+This verifies interoperability and stem summation, never musical quality.
+"""
+import array
+import io
+import json
+import math
+from pathlib import Path
+import sys
+import wave
+import zipfile
+import mido
+
+path = Path(sys.argv[1])
+bundle = zipfile.ZipFile(path if path.suffix == '.zip' else path / 'production.zip')
+assert bundle.testzip() is None, 'ZIP CRC failed'
+project = json.loads(bundle.read('project.afterhours.json'))
+report = json.loads(bundle.read('delivery.json'))
+
+def read_wave(name):
+ with wave.open(io.BytesIO(bundle.read(name)), 'rb') as w:
+ assert (w.getnchannels(), w.getframerate(), w.getsampwidth()) == (2, 48000, 2)
+ assert abs(w.getnframes() / w.getframerate() - report['duration']) < 1 / 48000
+ samples = array.array('h', w.readframes(w.getnframes()))
+ if sys.byteorder != 'little':
+ samples.byteswap()
+ return samples
+
+mix = read_wave('mix.wav')
+stems = [read_wave('stems/' + t['file']) for t in report['stems']]
+assert all(len(s) == len(mix) for s in stems), 'Stems are not aligned'
+maximum_error = max((abs(sum(values[1:]) - values[0]) for values in zip(mix, *stems)), default=0)
+assert maximum_error <= math.ceil((len(stems) + 1) / 2) + 1, ('Stem sum mismatch', maximum_error)
+assert max(map(abs, mix)) < 32767, 'Clipped output'
+assert any(abs(x) > 10 for x in mix), 'Silent output'
+
+midi = mido.MidiFile(file=io.BytesIO(bundle.read('composition.mid')))
+expected = [t for t in project['tracks'] if t['notes']]
+actual = []
+tempos, meters, markers = [], [], []
+for track in midi.tracks:
+ tick, pending, notes, name = 0, {}, [], ''
+ for msg in track:
+ tick += msg.time
+ if msg.type == 'track_name': name = msg.name
+ if msg.type == 'set_tempo': tempos.append((tick / midi.ticks_per_beat, mido.tempo2bpm(msg.tempo)))
+ if msg.type == 'time_signature': meters.append([msg.numerator, msg.denominator])
+ if msg.type == 'marker': markers.append((tick, msg.text))
+ if msg.type == 'note_on' and msg.velocity > 0:
+ pending.setdefault((msg.channel, msg.note), []).append((tick, msg.velocity))
+ elif msg.type == 'note_off' or msg.type == 'note_on' and msg.velocity == 0:
+ onset, velocity = pending[(msg.channel, msg.note)].pop(0)
+ notes.append((onset, msg.note, tick - onset, velocity))
+ assert not any(pending.values()), 'Stuck MIDI notes'
+ if notes: actual.append((name, sorted(notes)))
+assert len(actual) == len(expected)
+for (name, notes), source in zip(actual, expected):
+ assert name == source['name']
+ wanted = sorted(source['notes'], key=lambda n: (n['beat'], n['midi']))
+ assert len(notes) == len(wanted)
+ for (onset, pitch, length, velocity), n in zip(notes, wanted):
+ assert pitch == n['midi']
+ assert abs(onset / midi.ticks_per_beat - n['beat']) <= 1 / midi.ticks_per_beat
+ assert abs(length / midi.ticks_per_beat - n['duration']) <= 1 / midi.ticks_per_beat
+ assert abs(velocity / 127 - n['velocity']) <= 1 / 127
+assert meters == [project['meter']]
+assert len(tempos) == len(project['tempos'])
+for (beat, bpm), event in zip(tempos, project['tempos']):
+ assert abs(beat - event['beat']) <= 1 / midi.ticks_per_beat and abs(bpm - event['bpm']) < .001
+assert (round(project['beats'] * midi.ticks_per_beat), 'Afterhours: end') in markers
+timeline = sum((min(project['beats'], project['tempos'][i + 1]['beat'] if i + 1 < len(project['tempos']) else project['beats']) - t['beat']) * 60 / t['bpm'] for i, t in enumerate(project['tempos']) if t['beat'] < project['beats'])
+assert abs(midi.length - timeline) < .005, (midi.length, timeline)
+assert abs(report['duration'] - timeline - project['tail']) < 1 / 48000
+print(json.dumps({'title': project['title'], 'duration': report['duration'], 'midiSeconds': midi.length, 'notes': sum(len(t['notes']) for t in expected), 'stems': len(stems), 'stemMaximumErrorPCM16': maximum_error, 'independentReaders': ['Python wave', 'Python zipfile', 'mido 1.3.3'], 'listeningReviewed': False}))
diff --git a/work/AUTHORING-REBUILD.md b/work/AUTHORING-REBUILD.md
new file mode 100644
index 000000000..f69192e39
--- /dev/null
+++ b/work/AUTHORING-REBUILD.md
@@ -0,0 +1,87 @@
+# Art and Music authoring rebuild · 2026-09-20
+
+The seven earlier harnesses are withdrawn. Their source and identities remain in the repository.
+Generative Art and Music Studio now have authoring implementations; both **remain unlisted**.
+This report establishes working tools and reproducible fixtures, not completion of the product
+acceptance gates in [SUPERPOWERS.md](SUPERPOWERS.md).
+
+## What changed
+
+Fieldwork accepts an arbitrary drawing program, project-specific controls, text, images and data.
+The agent authors the program for the brief; the person edits the resulting studio. It delivers
+SVG, PNG, format/edition ZIPs, a complete editable project and portable HTML. There is no style enum
+or imitation AI prompt box. Rendering uses a terminable worker and refuses stale exports on errors.
+
+Afterhours holds an arbitrary score: notes, tempo changes, sections, instruments and recordings.
+The person can edit/drag notes, mix tracks, import MIDI/audio, trim and position recordings, and use
+their recording as a pitched instrument. Production delivery contains stereo PCM WAV, aligned WAV
+stems, standard MIDI with tempo/section/end markers, a project and portable studio.
+
+Both preserve local drafts and handle source-revision conflicts explicitly. Saved projects can be
+imported into the agent's source with a backup. Browser edits are **not automatically written back**
+to the workspace. The browser says how to save/attach the project; the agent instructions state this
+boundary. Authoring/export tools install locally; the resulting studios work offline.
+
+## Acceptance fixtures and targeted revisions
+
+These briefs and their input materials were authored in this coding session to exercise distinct
+workflows. They are not customer commissions, real rainfall observations or evidence of an
+unsupervised Claude session completing a user's brief.
+
+| Brief | Original delivery | Targeted revision | Material retained |
+|---|---|---|---|
+| Night Garden festival | 3 formats; original cut-paper geometry | New dates and venue | Illustration, seed, name, lineup and palette |
+| Canopy Coffee packaging | 3 formats; woodcut geometry and embedded logo fixture | New product lot | Logo bytes, origin, illustration and colors |
+| A Year of Rain | 3 formats; actual CSV values encoded in calendar rings | January 42 → 84 mm; total 1388 → 1430 | Other 11 observations, palette and program |
+| Blue Hour documentary cue | 48 s, 5 tracks, 249 notes | Quiet final motif echo; 250 notes | Accompaniment and timing |
+| Orbit Runner game title | 30 s, 4 tracks, 312 notes | Remove first two launch bars' hats; 296 notes | Hook, bass, kick and snare |
+| Keepsake family-film waltz | 33 s, 3/4, two tempos, 92 notes | Add bell response; 94 notes | Imported melody, accompaniment and tempo map |
+
+Source examples live inside each independently installable package. `revisions.mjs` exercises the
+actual project-import command, verifies retained material, creates source history and exports both
+editable projects and revised deliverables. Before/after vectors or scores are retained in its
+output folder. Store images are actual exported artwork or actual studio captures.
+
+## Evidence
+
+- 96 Node tests passed across package scripts, original retained models, new project/score models
+ and the shared viewer. The 13 new authoring tests also passed after final validation changes.
+- Real Chrome tests passed for both rebuilt studios through the Store viewer. They cover controls,
+ note dragging, undo/redo, own image/audio imports, MIDI/project roundtrips, portable HTML, browser
+ draft/source conflicts, viewer reload, 390px layout and no page exceptions. Music tests verify
+ a running audio context; this is **not listening evidence**.
+- Both installed packages passed running-app integration: temporary idle Claude sessions, new
+ workspaces, package instructions, viewer routing, honest initial verdict and live reload. No
+ prompts were sent. Only the test sessions were deleted.
+- Six desktop identity tests passed. Existing SVG/PNG logos remain intact; the fallback taglines
+ now describe the new capabilities.
+- All nine initial art layouts were visually inspected. Square-format collisions were fixed.
+ The final data-art formats include a scale and ring-order legend. Python XML parsing plus PNG
+ CRC/deflate decoding passed for all nine revised formats. SVG and PNG dimensions agree.
+- Python `wave`, `zipfile` and **mido 1.3.3** independently read all three original and three revised
+ music deliveries. They verified note content, tempo, meter, length, section/end markers, stereo
+ 48 kHz/16-bit WAV and matching stem lengths. Summed stems differ from the mix by at most **2 PCM
+ integer units**, within quantization error. MIDI retains intentional silence at the end.
+- Same-score Web Audio rerenders differed by less than 1e-7 in the checked samples. The measured
+ original peaks were 0.494, 0.390 and 0.229. These measurements do not assess composition quality.
+
+Reproduction commands are in [the test guide](../store/tools/experience-tests/README.md).
+CI now includes both real-browser authoring workflows and the independent music delivery reader.
+Large transient WAV/ZIP/browser captures belong in ignored evidence folders, not source control.
+
+## Remaining product review
+
+The full music listening pass has **not happened**. Musical transitions, sound quality and fit to a
+real user's brief remain unverified. The scenarios also do not replace end-to-end authoring trials
+with the installed coding engine and real user inputs. Keep both `listed:false` until that evidence
+exists; do not relist because CI passed or call this an “iPhone moment.”
+
+People can test the source packages through a local install (`harness dsh install <package> --link`).
+The existing links in this worktree already point at the rebuild; create a **new workspace** to use
+it. Existing workspaces retain their own files. A public Store catalog refresh does not overwrite
+them, and an unlisted harness is not discoverable or installable by its catalog ID.
+
+Practical limits: static RGB artwork with editable system-font text, not press certification;
+four-minute instrumental scores with 16 tracks and 28 MB embedded data, not generated singing or
+a mastered release. MIDI does not reproduce sustain, pitch bend or controller automation; import
+reports that limitation. WAV stems preserve the studio sound.
diff --git a/work/SUPERPOWERS.md b/work/SUPERPOWERS.md
index 2596d780d..4b88816cd 100644
--- a/work/SUPERPOWERS.md
+++ b/work/SUPERPOWERS.md
@@ -5,6 +5,10 @@ could not previously do. A polished simulation, a collection of presets, or a sp
does not pass. Our previous release verified its controls, but chose the wrong acceptance criteria.
The prior verification reports remain technical evidence, not evidence that these are good products.
+**Rebuild progress:** [AUTHORING-REBUILD.md](AUTHORING-REBUILD.md) records the new Art/Music tools,
+six distinct authored fixtures, revisions and real export checks. Both remain unlisted. Music
+listening and installed-engine trials with real user briefs are still outstanding.
+
## Review of our seven
| Harness | What it actually enables today | Why it falls short | Decision |