From 3802fbeb071333c1344f91bbf7b1803886e37dba Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:40:28 +0700 Subject: [PATCH 01/29] feat(m2): exact uint64 native v6 snapshot and ACK-later-readback JS reconciler --- web/approved-native-contract.js | 183 ++++++++++++++++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 web/approved-native-contract.js diff --git a/web/approved-native-contract.js b/web/approved-native-contract.js new file mode 100644 index 000000000..f08cfc2d4 --- /dev/null +++ b/web/approved-native-contract.js @@ -0,0 +1,183 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Pure, deterministic v8/schemaVersion=6 accepted-state reconciler. +// NO DSP, mock meter, ordinal ChannelId, optimistic graph, or second GUI. +// Also loaded by node:test; no browser APIs required by the core. +(function (root, factory) { + const api = factory(); + if (typeof module === "object" && module.exports) module.exports = api; + if (root) root.ArSonApprovedNativeContract = api; +})(typeof globalThis === "object" ? globalThis : undefined, function () { + "use strict"; + const MAX64 = (1n << 64n) - 1n; + const decimal = value => { + if (typeof value !== "string" || !/^(0|[1-9]\d*)$/.test(value)) return null; + try { return BigInt(value) <= MAX64 ? value : null; } catch { return null; } + }; + const cmp = (a, b) => BigInt(a) < BigInt(b) ? -1 : BigInt(a) > BigInt(b) ? 1 : 0; + const object = value => value !== null && typeof value === "object" && !Array.isArray(value); + const fields = (item, names) => object(item) && names.every(key => Object.prototype.hasOwnProperty.call(item, key)); + const isBool = x => typeof x === "boolean"; + const unique = values => new Set(values).size === values.length; + function normalizeSnapshot(raw) { + if (!fields(raw, ["schemaVersion","productionCallbackLive","device","graph","telemetry"]) || + raw.schemaVersion !== 6 || !isBool(raw.productionCallbackLive)) return null; + const d = raw.device, g = raw.graph, t = raw.telemetry; + if (!fields(d, ["epoch","backend","captureDevice","playbackDevice","inputEndpoints", + "outputEndpoints","enabledInputs","enabledOutputs","sampleRate","bufferFrames","outputArmed"]) || + !fields(g, ["revision","rosterRevision","channels","destinations","capabilities"]) || + !object(t) || decimal(d.epoch) === null || decimal(g.revision) === null || + decimal(g.rosterRevision) === null || !Array.isArray(g.channels) || + !Array.isArray(g.destinations) || !Array.isArray(d.inputEndpoints) || + !Array.isArray(d.outputEndpoints) || !Array.isArray(d.enabledInputs) || + !Array.isArray(d.enabledOutputs) || !isBool(d.outputArmed) || + !Number.isFinite(d.sampleRate) || !Number.isInteger(d.bufferFrames)) return null; + const caps = g.capabilities; + if (!fields(caps, ["callbackOwnsChannelIds","supportedOps","dynamicChannels", + "groups","fxReturns","monitor"]) || !isBool(caps.callbackOwnsChannelIds) || + !Array.isArray(caps.supportedOps) || !caps.supportedOps.every(s => typeof s === "string")) return null; + const enabled = arr => unique(arr) && arr.every(n => Number.isInteger(n) && n >= 0 && n <= 255); + if (!enabled(d.enabledInputs) || !enabled(d.enabledOutputs)) return null; + // Physical endpoint numbers are safe *port indices*; graph ChannelIds are never numbers. + const goodEndpoints = (entries,pins,prefix) => entries.every(e => + object(e) && Number.isInteger(e.port) && pins.includes(e.port) && + typeof e.id === "string" && e.id === prefix + e.port && + typeof e.label === "string" && Number.isInteger(e.callback) && + e.callback >= 0 && typeof e.active === "boolean"); + if (!goodEndpoints(d.inputEndpoints,d.enabledInputs,"in:") || + !goodEndpoints(d.outputEndpoints,d.enabledOutputs,"out:")) return null; + const ids = []; + for (const ch of g.channels) { + if (!object(ch) || decimal(ch.id) === null || !ch.id || !["INPUT","GROUP","FX_RETURN","MAIN","MONITOR"].includes(ch.role) || + typeof ch.name !== "string" || !["MONO","STEREO"].includes(ch.processingFormat)) return null; + ids.push(ch.id); + if (ch.primaryOutId !== undefined && + (decimal(ch.primaryOutId) === null || ch.primaryOutId === ch.id)) return null; + if (ch.controls !== undefined && + (!object(ch.controls) || + (ch.controls.faderDb !== undefined && !Number.isFinite(ch.controls.faderDb)) || + (ch.controls.pan !== undefined && !Number.isFinite(ch.controls.pan)) || + (ch.controls.mute !== undefined && !isBool(ch.controls.mute)) || + (ch.controls.solo !== undefined && !isBool(ch.controls.solo)))) return null; + } + if (!unique(ids)) return null; + for (const ch of g.channels) { + if (ch.primaryOutId !== undefined && !ids.includes(ch.primaryOutId)) return null; + } + const edges = Array.isArray(g.edges) ? g.edges : []; + if (edges.some(e => !object(e) || decimal(e.edgeId) === null || + decimal(e.from) === null || decimal(e.to) === null || + !ids.includes(e.from) || !ids.includes(e.to) || e.from === e.to || + e.signalKind !== "AUDIO" || !isBool(e.enabled) || + !Number.isFinite(e.gainLinear) || e.gainLinear < 0)) return null; + if (!unique(edges.map(e => e.edgeId))) return null; + if (g.mainChannelId !== undefined && + (decimal(g.mainChannelId) === null || !ids.includes(g.mainChannelId))) return null; + // Advertised LIVE is gated by real native callback, valid graph, and actual hardware. + // A dishonest producer cannot be "fixed" by manufacturing Channels in JS. + const admitted = raw.productionCallbackLive === true && caps.callbackOwnsChannelIds === true && + cmp(d.epoch,"0") > 0 && cmp(g.revision,"0") > 0 && + g.channels.length > 0 && typeof g.mainChannelId === "string" && + g.channels.some(ch => ch.id === g.mainChannelId && ch.role === "MAIN"); + if (!admitted && (raw.productionCallbackLive || caps.callbackOwnsChannelIds) && + g.channels.length === 0) return null; + return { raw, device:d, graph:g, telemetry:t, admitted, + identity: d.epoch + ":" + g.revision + ":" + g.rosterRevision }; + } + function createController({emit, onStatus=()=>{}, onAccepted=()=>{}}) { + if (typeof emit !== "function") throw Error("Native emitter required"); + let current = null, pending = null, lastRequest = 0, lastError = "NATIVE_NOT_SUBSCRIBED"; + let sessionCounter = 0; + // Per-WebView-session token. Never claim cryptographic authentication. + const session = "m2-" + Date.now().toString(36) + "-" + + Math.floor(Math.random() * 0x100000000).toString(36); + const state = () => ({current, pending:pending && {requestId:pending.requestId,operation:pending.operation}, + lastError, accepted:!!current?.admitted}); + const notify = () => onStatus(state()); + function subscribe() { emit("arMixConsoleSubscribe",{schemaVersion:6,requestId:session+"-sub-"+(++sessionCounter)}); } + function onSnapshot(raw) { + const next = normalizeSnapshot(raw); + if (!next) { lastError="INVALID_NATIVE_SNAPSHOT";notify();return false; } + if (current) { + const epochCompare = cmp(next.device.epoch,current.device.epoch); + if (epochCompare < 0) {lastError="OLD_DEVICE_EPOCH";notify();return false;} + if (epochCompare === 0 && + (cmp(next.graph.revision,current.graph.revision) < 0 || + (cmp(next.graph.revision,current.graph.revision) === 0 && + cmp(next.graph.rosterRevision,current.graph.rosterRevision) < 0))) { + lastError="OLD_NATIVE_REVISION";notify();return false; + } + if (pending && epochCompare !== 0) { + pending=null;lastError="STALE_DEVICE"; + } + } + if (pending && pending.ack) { + const ack=pending.ack; + if (next.device.epoch !== ack.deviceEpoch) { + pending=null;lastError="STALE_DEVICE"; + } else if (next.graph.revision === ack.graphRevision && + next.graph.rosterRevision === ack.rosterRevision) { + pending=null;lastError="ACCEPTED_READBACK"; + current=next;onAccepted(next); + notify();return true; + } else if (cmp(next.graph.revision,ack.graphRevision) > 0 || + (cmp(next.graph.revision,ack.graphRevision) === 0 && + cmp(next.graph.rosterRevision,ack.rosterRevision) > 0)) { + pending=null;lastError="CONFLICTING_NATIVE_READBACK"; + subscribe(); + } + } + // No local optimistic edit: existing accepted UI projection is frozen + // until its exact matching native readback arrives. + if (!pending || !pending.ack) { + current=next;onAccepted(next); + } + notify();return true; + } + function intent(operation,targetChannelId,payload={}) { + if (!current || !current.admitted || !current.graph.capabilities.supportedOps.includes(operation)) { + lastError="UNSUPPORTED_OR_UNADMITTED";notify();return {ok:false,error:lastError}; + } + if (pending) {lastError="PENDING_NATIVE_ACK";notify();return {ok:false,error:lastError};} + if (decimal(targetChannelId) === null || !current.graph.channels.some(ch => ch.id === targetChannelId)) { + lastError="UNKNOWN_CHANNEL_ID";notify();return {ok:false,error:lastError}; + } + if (!object(payload)) {lastError="INVALID_PAYLOAD";notify();return {ok:false,error:lastError};} + const requestId=session+"-"+(++lastRequest); + const msg={requestId,deviceEpoch:current.device.epoch, + baseGraphRevision:current.graph.revision, + baseRosterRevision:current.graph.rosterRevision, + operation,targetChannelId,payload}; + pending={requestId,operation,deviceEpoch:msg.deviceEpoch, + baseGraphRevision:msg.baseGraphRevision,baseRosterRevision:msg.baseRosterRevision,ack:null}; + lastError="PENDING_NATIVE_ACK"; + emit("arMixConsoleIntent",msg);notify();return {ok:true,requestId}; + } + function onAck(raw) { + if (!pending || !fields(raw,["requestId","status","deviceEpoch","graphRevision","rosterRevision","errorCode"]) || + typeof raw.requestId !== "string" || raw.requestId !== pending.requestId) return false; + if ([raw.deviceEpoch,raw.graphRevision,raw.rosterRevision].some(x=>decimal(x)===null)) { + pending=null;lastError="INVALID_NATIVE_ACK";notify();return false; + } + if (raw.deviceEpoch !== pending.deviceEpoch || + !current || raw.deviceEpoch !== current.device.epoch) { + pending=null;lastError="STALE_DEVICE";subscribe();notify();return false; + } + if (raw.status !== "ACCEPTED" || raw.errorCode !== "NONE") { + lastError=typeof raw.errorCode==="string"?raw.errorCode:"NATIVE_REJECTED"; + pending=null;subscribe();notify();return false; + } + if (cmp(raw.graphRevision,pending.baseGraphRevision) < 0 || + cmp(raw.rosterRevision,pending.baseRosterRevision) < 0) { + pending=null;lastError="STALE_NATIVE_ACK";subscribe();notify();return false; + } + pending.ack={deviceEpoch:raw.deviceEpoch,graphRevision:raw.graphRevision, + rosterRevision:raw.rosterRevision}; + lastError="PENDING_ACCEPTED_SNAPSHOT";notify(); + // Reject ACK-only "success": explicitly request a LATER independent readback. + subscribe(); + return true; + } + return Object.freeze({subscribe,onSnapshot,onAck,intent,state}); + } + return Object.freeze({decimal,cmp,normalizeSnapshot,createController}); +}); From 7d65e0c790145795f0319056b86e82c95183867f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:41:22 +0700 Subject: [PATCH 02/29] feat(m2 native): publish actual JUCE device pins and explicit non-admitted ChannelId graph; reject unsupported intents --- src/ApprovedConsoleNativeTransportV6.h | 156 +++++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 src/ApprovedConsoleNativeTransportV6.h diff --git a/src/ApprovedConsoleNativeTransportV6.h b/src/ApprovedConsoleNativeTransportV6.h new file mode 100644 index 000000000..f36905e3f --- /dev/null +++ b/src/ApprovedConsoleNativeTransportV6.h @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include + +// M2 message-thread adapter for the ONE approved Pages WebView2 mixer. +// This G0 adapter reports TRUE current device pins and unadmitted ChannelId +// capability. It MUST NOT invent PCM, approve uninstalled engine ops, create a +// callback, allocate from the audio thread, or borrow historic demo ChannelIds. +// ENGINE #266 replaces G0 with actual accepted topology on production cutover. +namespace armix::native_console_m2 +{ +inline juce::String decimal (std::uint64_t number) +{ + return juce::String (std::to_string (number)); +} + +inline std::uint64_t deviceGeneration (const juce::var& live) +{ + const auto value = live.getProperty ("deviceGeneration", {}); + if (! value.isInt() && ! value.isInt64() && ! value.isDouble()) return 0; + const auto number = static_cast (value); + if (! std::isfinite (number) || number < 0 || + number > 9007199254740991.0 || std::floor (number) != number) + return 0; + return static_cast (number); +} + +inline juce::var realDevicePorts (const juce::StringArray& labels, + const juce::BigInteger& active, + const char* direction, + juce::Array& enabled) +{ + juce::Array endpoints; + int callbackOrdinal = 0; + for (int pin = 0; pin < juce::jmin (labels.size(), 64); ++pin) + { + if (! active[pin]) continue; + enabled.add (pin); + auto row = std::make_unique(); + row->setProperty ("id", juce::String (direction) + juce::String (pin)); + row->setProperty ("port", pin); + row->setProperty ("callback", callbackOrdinal++); + row->setProperty ("label", labels[pin]); + row->setProperty ("active", true); + endpoints.add (juce::var (row.release())); + } + return juce::var (endpoints); +} + +inline juce::var snapshot (const juce::var& live, + juce::AudioDeviceManager& manager, + bool allOutputsDisarmed) +{ + // Message-thread read of the REAL engine and real current JUCE device. + // When separate clocks are active, direct JUCE input pins cannot be + // mistaken for capture-device callback pin mapping. + auto root = std::make_unique(); + root->setProperty ("schemaVersion", 6); + root->setProperty ("productionCallbackLive", false); + root->setProperty ("provenance", "G0_CURRENT_JUCE_DEVICE_ONLY__CHANNELID_NOT_ADMITTED"); + + auto dev = std::make_unique(); + dev->setProperty ("epoch", decimal (deviceGeneration (live))); + dev->setProperty ("backend", manager.getCurrentAudioDeviceType()); + dev->setProperty ("captureDevice", live.getProperty ("inputDevice", juce::var (""))); + dev->setProperty ("playbackDevice", live.getProperty ("outputDevice", juce::var (""))); + juce::Array enabledInputs, enabledOutputs; + juce::var inputs (juce::Array{}), outputs (juce::Array{}); + const auto* active = manager.getCurrentAudioDevice(); + const bool direct = ! static_cast (live.getProperty ("adaptiveClockActive", false)); + if (active != nullptr && active->isOpen()) + { + outputs = realDevicePorts (active->getOutputChannelNames(), + active->getActiveOutputChannels(), "out:", enabledOutputs); + if (direct) + inputs = realDevicePorts (active->getInputChannelNames(), + active->getActiveInputChannels(), "in:", enabledInputs); + } + dev->setProperty ("inputEndpoints", inputs); + dev->setProperty ("outputEndpoints", outputs); + dev->setProperty ("enabledInputs", juce::var (enabledInputs)); + dev->setProperty ("enabledOutputs", juce::var (enabledOutputs)); + dev->setProperty ("sampleRate", active != nullptr && active->isOpen() + ? active->getCurrentSampleRate() : 0.0); + dev->setProperty ("bufferFrames", active != nullptr && active->isOpen() + ? active->getCurrentBufferSizeSamples() : 0); + dev->setProperty ("outputArmed", ! allOutputsDisarmed); + root->setProperty ("device", juce::var (dev.release())); + + auto caps = std::make_unique(); + caps->setProperty ("callbackOwnsChannelIds", false); + caps->setProperty ("fullVendorFxMigration", false); + caps->setProperty ("dynamicChannels", false); + caps->setProperty ("groups", false); + caps->setProperty ("fxReturns", false); + caps->setProperty ("monitor", false); + caps->setProperty ("supportedOps", juce::var (juce::Array{})); + auto graph = std::make_unique(); + graph->setProperty ("revision", juce::String ("0")); + graph->setProperty ("rosterRevision", juce::String ("0")); + graph->setProperty ("channels", juce::var (juce::Array{})); + graph->setProperty ("destinations", juce::var (juce::Array{})); + graph->setProperty ("edges", juce::var (juce::Array{})); + graph->setProperty ("capabilities", juce::var (caps.release())); + root->setProperty ("graph", juce::var (graph.release())); + + auto telemetry = std::make_unique(); + telemetry->setProperty ("rawCapturePresent", false); + telemetry->setProperty ("rawCapturePeak", 0.0); + telemetry->setProperty ("mainPcmPresent", false); + telemetry->setProperty ("monitorPcmPresent", false); + root->setProperty ("telemetry", juce::var (telemetry.release())); + return juce::var (root.release()); +} + +inline juce::String rejectReason (const juce::var& intent, const juce::var& accepted) +{ + if (! intent.isObject()) return "INVALID_INTENT"; + const auto request = intent.getProperty ("requestId", {}); + if (! request.isString() || request.toString().isEmpty() || + request.toString().length() > 128) return "INVALID_REQUEST_ID"; + const auto device = accepted.getProperty ("device", {}); + const auto graph = accepted.getProperty ("graph", {}); + const auto e = intent.getProperty ("deviceEpoch", {}); + const auto gr = intent.getProperty ("baseGraphRevision", {}); + const auto rr = intent.getProperty ("baseRosterRevision", {}); + if (! e.isString() || ! gr.isString() || ! rr.isString()) + return "INVALID_REVISION_TYPE"; + if (e.toString() != device.getProperty ("epoch", {}).toString()) + return "STALE_DEVICE"; + if (gr.toString() != graph.getProperty ("revision", {}).toString()) + return "STALE_GRAPH"; + if (rr.toString() != graph.getProperty ("rosterRevision", {}).toString()) + return "STALE_ROSTER"; + return "UNSUPPORTED_OP"; // G0 intentionally permits ZERO PCM mutations. +} + +inline juce::var reject (const juce::var& intent, const juce::var& accepted) +{ + auto ack = std::make_unique(); + const auto request = intent.getProperty ("requestId", {}); + ack->setProperty ("requestId", request.isString() ? request : juce::var ("")); + ack->setProperty ("status", "REJECTED"); + ack->setProperty ("errorCode", rejectReason (intent, accepted)); + ack->setProperty ("deviceEpoch", + accepted.getProperty ("device", {}).getProperty ("epoch", "0")); + const auto graph = accepted.getProperty ("graph", {}); + ack->setProperty ("graphRevision", graph.getProperty ("revision", "0")); + ack->setProperty ("rosterRevision", graph.getProperty ("rosterRevision", "0")); + ack->setProperty ("productionCallbackLive", false); + return juce::var (ack.release()); +} +} // namespace armix::native_console_m2 From 073ffe212416f058ace329c4fef1bba8be0c6828 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:41:57 +0700 Subject: [PATCH 03/29] feat(m2): wire actual JUCE snapshot/explicit REJECTED intent/subscribe transport into one console window --- src/Main.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/Main.cpp b/src/Main.cpp index daf27bab2..46c588e08 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -5,6 +5,7 @@ #include #include #include "ApprovedGuiResources.h" +#include "ApprovedConsoleNativeTransportV6.h" #include "LiveAudioEngine.h" #include "ArSonMixStartupSplash.h" #include "VstOrbitController.h" @@ -193,6 +194,23 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr browser_.repaint(); if (onStartupStage_) onStartupStage_ (1); }) + .withEventListener ("arMixConsoleSubscribe", [this] (juce::var) { + // G0 real-device native producer, NEVER a synthetic ChannelId callback. + consoleSubscribed_ = true; + emitApprovedNativeSnapshot(); + }) + .withEventListener ("arMixConsoleIntent", [this] (juce::var args) { + // Until ENGINE #266 owns production ChannelId graph, ALL v6 + // control intents are native-rejected, never silently emulated + // via the old ordinal-only M4 engine. + const auto accepted = approvedNativeSnapshot(); + if (browser_.loaded) + { + browser_.emitEventIfBrowserIsVisible ("arMixConsoleAck", + armix::native_console_m2::reject (args, accepted)); + browser_.emitEventIfBrowserIsVisible ("arMixConsoleSnapshot", accepted); + } + }) .withEventListener ("arMixParameter", [this] (juce::var args) { onParameter (args); }) .withEventListener ("arMixAction", [this] (juce::var args) { onAction (args); }) .withResourceProvider (assetFor)) @@ -259,6 +277,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr std::unique_ptr audioSetupWindow_; juce::String startupError_, lastAudioXml_; bool initialStateSent_ = false; + bool consoleSubscribed_ = false; // WebView v6 G0 subscription, not PCM admission bool webViewPeerWarmed_ = false; bool webViewStartupNoticeSent_ = false; juce::uint32 webViewStartupTick_ = 0; @@ -677,6 +696,19 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr emitOrbitState (previousSlot); } + juce::var approvedNativeSnapshot() + { + return armix::native_console_m2::snapshot ( + engine_.status(), engine_.devices(), engine_.allOutputsDisarmed()); + } + + void emitApprovedNativeSnapshot() + { + if (consoleSubscribed_ && browser_.loaded) + browser_.emitEventIfBrowserIsVisible ( + "arMixConsoleSnapshot", approvedNativeSnapshot()); + } + void onParameter (const juce::var& args) { const auto name = args.getProperty ("parameter", {}).toString(); @@ -2471,6 +2503,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr auto health = engine_.status(); crackleEvidence_.push (makeEvidenceSample(health)); diagnostics_.record ("AUDIO_HEALTH", juce::JSON::toString (health, false)); + if (consoleSubscribed_ && browser_.loaded) + browser_.emitEventIfBrowserIsVisible ("arMixConsoleSnapshot", + armix::native_console_m2::snapshot ( + health, engine_.devices(), engine_.allOutputsDisarmed())); } if (deviceSettingsDirty_) From c8003852c1895cd74a064fc946cb6a375ea3762a Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:43:04 +0700 Subject: [PATCH 04/29] build(m2): add pure state protocol before existing nonvisual JUCE bridge in approved Pages asset bundle --- scripts/build_approved_native_gui.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index a0a32b4e2..5077bc0f0 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -21,7 +21,8 @@ ROOT = Path(__file__).resolve().parents[1] CANONICAL = ROOT / "site" / "preview-v2" NATIVE_ADAPTER = ROOT / "web" / "approved-native-bridge.js" -ADAPTER_MARKER = '' +ADAPTER_MARKER = ('\n' + '') SCHEMA = "arsonmix.approved-native-pages-bundle.v2" @@ -111,6 +112,8 @@ def stage(out: Path) -> dict: out.mkdir(parents=True) shutil.copytree(pages / "assets", out / "assets") shutil.copy2(NATIVE_ADAPTER, out / "assets" / "approved-native-bridge.js") + shutil.copy2(ROOT / "web" / "approved-native-contract.js", + out / "assets" / "approved-native-contract.js") native = native_html(approved.decode("utf-8")).encode("utf-8") (out / "index.html").write_bytes(native) files = [out / "index.html", *sorted(p for p in (out / "assets").rglob("*") if p.is_file())] From cf87668d86487ad7ea1e49b7b1fcf094e601f13e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:45:18 +0700 Subject: [PATCH 05/29] feat(m2 pages): preserve approved DOM; native hook intercepts all physical edits before demo mutation --- site/preview-v2/index.html | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/site/preview-v2/index.html b/site/preview-v2/index.html index 7be436edb..b1442ac65 100644 --- a/site/preview-v2/index.html +++ b/site/preview-v2/index.html @@ -345,6 +345,7 @@ } } function wireGraphCommit(ops,{record=true}={}){ + if(window.__ARMIX_NATIVE_M2__?.consumeWire?.(ops))return false; const before=record?wireWsSnapshot():null; const result=ArSonWireGraph.applyWireTransaction({ channels:tracks,mainId:master.id,edges:wireEdges,nextId:nextWireId @@ -1005,6 +1006,7 @@ const btn=document.getElementById('wireWsUndo');if(btn)btn.disabled=false; } function wireWsUndo(){ + if(window.__ARMIX_NATIVE_M2__?.consumeUndo?.())return false; const entry=wireWsHistory[wireWsHistory.length-1]; if(!entry){say('WIRE: no routing change to undo');return false;} if(wireWsSignature(wireWsSnapshot())!==entry.afterSig){ @@ -1708,6 +1710,7 @@ render();say(groups.size?'Removed '+groups.size+' channel group(s)':'Select a grouped channel to ungroup'); } function handleField(event){ + if(window.__ARMIX_NATIVE_M2__?.consumeField?.(event))return; const el=event.target,field=el.dataset.field;if(!field)return; const t=findTrack(el);if(!t)return; if(field==='wireGain'){ @@ -1963,6 +1966,7 @@ const btn=e.target.closest('[data-action]');if(!btn)return; const t=findTrack(btn);if(!t)return; const a=btn.dataset.action; + if(window.__ARMIX_NATIVE_M2__?.consumeAction?.(t,a,btn))return; if(a==='wireExpand'){document.querySelector('.section-rail [data-section="send"]')?.click();return;} if(a==='resetClip'){ t.clip=false;btn.classList.remove('clipping'); @@ -2015,6 +2019,7 @@ }); document.querySelector('.console-body').addEventListener('dblclick',e=>{ const t=findTrack(e.target);if(!t)return; + if(window.__ARMIX_NATIVE_M2__?.consumeDoubleClick?.(e,t))return; if(e.target.closest?.('.wire-gain,.wire-pot')){ const el=e.target.closest('.wire-pot')?.querySelector('.wire-gain')||e.target.closest('.wire-gain');el.value='0';handleField({target:el,type:'change'});return; } From 56e98416e3f4ca21559c94e946214164eb005b9f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:47:14 +0700 Subject: [PATCH 06/29] feat(m2): bind approved GUI controls to native intent gate, ACK snapshot projection and truthful G0 device status --- web/approved-native-bridge.js | 270 +++++++++++++++++++++++++++++++--- 1 file changed, 248 insertions(+), 22 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 6b43c23c3..7ad3a86d5 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1,30 +1,256 @@ // SPDX-License-Identifier: AGPL-3.0-only -// Thin transport seam for the ONE already-approved Pages GUI. -// IMPORTANT: this is an M1 source/visual integration bridge, NOT a PCM driver. -// Native ChannelId/EdgeId ACK/readback binding must be added before product UAT. +// ONE approved /preview/ DOM, native authority only. No new UI, no JS PCM. (() => { "use strict"; const backend = window.__JUCE__?.backend; - const descriptor = Object.freeze({ - source: "site/preview-v2 + site/preview-buttons", - pagesRoute: "/preview/", - nativeTransport: Boolean(backend?.emitEvent && backend?.addEventListener), - acceptedGraphConnected: false, - productionCallbackLive: false, - status: "M1_VISUAL_BUNDLE_ONLY__NOT_AUDIO_READY" + const protocol = window.ArSonApprovedNativeContract; + const connected = Boolean(backend?.emitEvent && backend?.addEventListener && protocol); + // The old M1 wording is retained as an explicit boot-time fallback for + // release-train compatibility, NOT a claim that a demo graph is audio. + const fallback = "M1_VISUAL_BUNDLE_ONLY__NOT_AUDIO_READY"; + const flags = {acceptedGraphConnected:false,productionCallbackLive:false}; + const nativeByUiId = new Map(); // SMALL UI ordinal -> EXACT decimal-string native ChannelId + const uiByNativeId = new Map(); // EXACT uint64 string -> local view-only ordinal + const wireByUiId = new Map(); // view-only EdgeId -> EXACT decimal-string native EdgeId + const uiByWireId = new Map(); + let lastPaintedIdentity = "", lastNativeError = "NATIVE_NOT_SUBSCRIBED"; + let controller = null; + const status = message => { + lastNativeError = message; + const info = document.getElementById("info"); + if (info) info.textContent = message; + }; + const stopDemo = () => { + // The public Pages demo remains unchanged. In native, DEMO meters and + // reference-only physical operations are never passed off as live audio. + const demo = document.getElementById("preview"); + if (demo) {demo.disabled = true;demo.title = "Demo meters disabled in native Windows application";} + if (typeof preview !== "undefined" && preview) { + preview = false; // original Pages animation sees false and stops itself + demo?.setAttribute("aria-pressed","false"); + } + document.documentElement.dataset.armixNativeAuthority = flags.productionCallbackLive ? + "accepted" : "not-admitted"; + }; + const nativeIdFor = t => nativeByUiId.get(t?.id) || null; + const intent = (operation,t,payload) => { + const id = nativeIdFor(t); + const result = controller?.intent(operation,id,payload) || {ok:false,error:"NATIVE_UNAVAILABLE"}; + if (!result.ok) status("NATIVE: "+result.error+" — controls unchanged"); + return result.ok; + }; + function projection(native) { + if (!native?.admitted || !Array.isArray(native.graph.edges) || + typeof make !== "function" || typeof render !== "function" || + typeof ArSonWireGraph === "undefined") return false; + const accepted = native.graph; + // No fake default fader/mute/solo when the producer omitted real readback. + if (accepted.channels.some(ch => !ch.controls || + !["faderDb","pan","mute","solo"].every(k => Object.hasOwn(ch.controls,k)))) return false; + const previous = new Map(tracks.concat(master).map(t=>[t.id,t])); + const nextTracks = [], localByNative = new Map(), nextNativeByUi = new Map(); + let nextMaster = null; + for (const [index,ch] of accepted.channels.entries()) { + const kind = ch.role==="MAIN"?"master":ch.role==="GROUP"?"bus": + ch.role==="FX_RETURN"?"fx":"audio"; + const savedId = uiByNativeId.get(ch.id); + const t = savedId !== undefined && previous.has(savedId) ? + previous.get(savedId) : make(ch.name,kind,COLORS[index%COLORS.length]||"#568ead"); + if (savedId !== undefined) t.id = savedId; + // No Number(ch.id): all native identities stay canonical uint64 strings. + localByNative.set(ch.id,t.id); + nextNativeByUi.set(t.id,ch.id); + t.name=ch.name;t.kind=kind; + t.format=ch.processingFormat.toLowerCase(); + t.level=ch.controls.faderDb; + t.pan=ch.controls.pan; + t.mute=ch.controls.mute; + t.solo=ch.controls.solo; + t.selected=previous.get(t.id)?.selected || false; + if (Array.isArray(ch.inserts)) { + t.fx=Array.from({length:8},(_,i)=>ch.inserts[i]?.name||"None"); + t.slotBypass=Array.from({length:8},(_,i)=>Boolean(ch.inserts[i]?.bypassed)); + t.fxInsertIds=Array.from({length:8},(_,i)=>ch.inserts[i]? + {name:ch.inserts[i].name,id:ch.inserts[i].id}:null); + } + if (ch.role==="MAIN") nextMaster=t; + else nextTracks.push(t); + } + if (!nextMaster || nextMaster.id !== localByNative.get(accepted.mainChannelId)) return false; + const edges = [], newWireByUi = new Map(), newUiByWire = new Map(); + for (const edge of accepted.edges) { + if (!edge.enabled) continue; + const src=localByNative.get(edge.from), dst=localByNative.get(edge.to); + if (!src || !dst || edge.from===accepted.mainChannelId) return false; + const source=accepted.channels.find(ch=>ch.id===edge.from); + const isMain=edge.to===accepted.mainChannelId; + const isPrimary=source?.primaryOutId===edge.to; + const kind=isMain||isPrimary?"primary":edge.tap==="SPLIT_PRE"||edge.tap==="SPLIT_POST"?"split":"send"; + const mode=isMain?"postFader":kind==="primary"?"routeOnly": + kind==="split"?(edge.tap==="SPLIT_PRE"?"splitPre":"splitPost"):"send"; + if (isMain && edge.gainLinear!==1) return false; + const gainDb=isMain?0:Math.round(Math.max(-60,Math.min(6, + edge.gainLinear>0?20*Math.log10(edge.gainLinear):-60))*10)/10; + let uiId=uiByWireId.get(edge.edgeId); + if (uiId===undefined) uiId=nextWireId++; + newWireByUi.set(uiId,edge.edgeId); + newUiByWire.set(edge.edgeId,uiId); + edges.push({id:uiId,sourceId:src,destId:dst,kind,mode, + enabled:true,levelDb:gainDb}); + } + if (!ArSonWireGraph.validateCandidateGraph(nextTracks,nextMaster.id,edges).ok) return false; + const previouslySelected = nextTracks.filter(t=>t.selected); + if (!previouslySelected.length && nextTracks.length) nextTracks[0].selected=true; + // One atomic accepted readback projection. Demo wire reducer NEVER runs. + tracks=nextTracks;master=nextMaster;wireEdges=edges; + for (const [id,ui] of localByNative) uiByNativeId.set(id,ui); + nativeByUiId.clear();for(const [ui,id] of nextNativeByUi)nativeByUiId.set(ui,id); + wireByUiId.clear();for(const [ui,id] of newWireByUi)wireByUiId.set(ui,id); + uiByWireId.clear();for(const [id,ui] of newUiByWire)uiByWireId.set(id,ui); + if (typeof wireWsHistory!=="undefined")wireWsHistory=[]; + selectedWireEdgeId=null; + syncWireOutputProjection();render(); + return true; + } + function onNativeReadback(next) { + const caps=next?.graph?.capabilities; + const nativeAdmitted=next.admitted && caps?.callbackOwnsChannelIds===true; + if (!nativeAdmitted) { + flags.productionCallbackLive=false;flags.acceptedGraphConnected=false; + stopDemo(); + status("NATIVE G0 · perangkat aktual terbaca; ChannelId PCM/WIRE belum diterima. Edit audio diblokir."); + return; + } + if (next.identity===lastPaintedIdentity)return; + if (!projection(next)) { + flags.acceptedGraphConnected=false;flags.productionCallbackLive=false; + stopDemo();status("NATIVE READBACK INVALID · existing GUI controls unchanged"); + return; + } + flags.productionCallbackLive=true;flags.acceptedGraphConnected=true; + lastPaintedIdentity=next.identity;stopDemo(); + status("NATIVE ACCEPTED · device "+next.device.epoch+ + " · graph "+next.graph.revision+" · roster "+next.graph.rosterRevision); + } + if (connected) { + controller = protocol.createController({ + emit:(name,payload)=>backend.emitEvent(name,payload), + onAccepted:onNativeReadback, + onStatus:state=>{ + if(state.lastError==="PENDING_NATIVE_ACK"||state.lastError==="PENDING_ACCEPTED_SNAPSHOT") + status("NATIVE "+state.lastError+" · awaiting authoritative readback"); + else if(state.lastError!=="ACCEPTED_READBACK"&&state.lastError!=="NONE"&& + state.lastError!=="NATIVE_NOT_SUBSCRIBED"&& + state.lastError!=="INVALID_NATIVE_SNAPSHOT") + lastNativeError=state.lastError; + } + }); + backend.addEventListener("arMixConsoleSnapshot", snapshot=>controller.onSnapshot(snapshot)); + backend.addEventListener("arMixConsoleAck", ack=>controller.onAck(ack)); + } + const nativeHooks=Object.freeze({ + enabled:connected, + consumeField(event) { + if (!connected)return false; + const el=event.target,field=el?.dataset?.field; + if (!field)return false; + const t=typeof findTrack==="function"?findTrack(el):null; + if (!t)return true; + if (event.type!=="change") return true; // no optimistic input-frame mutations + const numeric=Number(el.value); + if (field==="level"&&Number.isFinite(numeric)) + intent("SET_FADER",t,{valueDb:numeric}); + else if (field==="pan"&&Number.isFinite(numeric)) + intent("SET_PAN",t,{value:numeric/100}); + else status("NATIVE: "+field+" awaits native capability; reference graph unchanged"); + return true; + }, + consumeAction(t,action,btn) { + if (!connected)return false; + // Selection, WIRE inspection and section presentation are UI-only. + if (["wireExpand","wireSource","wireRoute","editIdentity","rename"].includes(action)) + return !["wireExpand","wireSource","wireRoute"].includes(action); + if (action==="mute"||action==="solo") { + const key=action==="mute"?"SET_MUTE":"SET_SOLO"; + intent(key,t,{value:!t[action],enabled:!t[action]});return true; + } + status("NATIVE: "+action+" is not an accepted ChannelId operation");return true; + }, + consumeWire(ops) { + if (!connected)return false; + const current=controller?.state().current; + if (!current?.admitted || !current.graph.capabilities.supportedOps.includes("APPLY_WIRE_TRANSACTION")) { + status("NATIVE: WIRE transaction not admitted; graph unchanged");return true; + } + const changes=[]; + for (const op of ops) { + const sourceId=nativeByUiId.get(op.sourceId); + const destId=op.destId===undefined?undefined:nativeByUiId.get(op.destId); + const edgeId=op.edgeId===undefined?undefined:wireByUiId.get(op.edgeId); + if (!sourceId || (op.destId!==undefined&&!destId) || + (op.edgeId!==undefined&&!edgeId)) { + status("NATIVE: WIRE mapped identity missing; no mutation");return true; + } + changes.push({type:op.type,sourceId,...(destId?{destId}:{}), + ...(edgeId?{edgeId}:{}), + ...(op.mode?{mode:op.mode}:{}), + ...(op.levelDb!==undefined?{levelDb:op.levelDb}:{})}); + } + const source=changes[0]?.sourceId; + controller.intent("APPLY_WIRE_TRANSACTION",source,{changes}); + return true; + }, + consumeUndo() {if (!connected)return false;status("NATIVE: WIRE undo requires accepted native transaction");return true;}, + consumeDoubleClick(event,t) { + if (!connected)return false; + if (event.target.classList.contains("fader"))intent("SET_FADER",t,{valueDb:0}); + else if(event.target.classList.contains("center-pan"))intent("SET_PAN",t,{value:0}); + else status("NATIVE: identity editor unavailable until native ACK contract"); + return true; + }, + state:()=>controller?.state() || null }); - Object.defineProperty(window, "__ARMIX_APPROVED_NATIVE_GUI__", { - value: descriptor, configurable: false, writable: false + window.__ARMIX_NATIVE_M2__ = nativeHooks; + const descriptor = Object.freeze({ + source:"site/preview-v2 + site/preview-buttons", + pagesRoute:"/preview/", + nativeTransport:connected, + get acceptedGraphConnected(){return flags.acceptedGraphConnected;}, + get productionCallbackLive(){return flags.productionCallbackLive;}, + status:fallback, + m2:nativeHooks }); - // The native startup signal certifies ONLY that the approved DOM loaded. - // It never reports VST3, PCM, hardware pins or graph capabilities as live. - if (!descriptor.nativeTransport) return; - const ready = () => backend.emitEvent("arMixGuiReady", { - gui: "APPROVED_PAGES_PREVIEW_BUTTONS", - visualReady: true, - audioReady: false + Object.defineProperty(window,"__ARMIX_APPROVED_NATIVE_GUI__",{ + value:descriptor,configurable:false,writable:false }); - if (document.readyState === "loading") { - document.addEventListener("DOMContentLoaded", ready, {once:true}); - } else ready(); + if (!connected)return; + // Reference-only buttons outside strips must not mutate fake Show/FX state. + document.addEventListener("click",event=>{ + const target=event.target.closest?.( + "#preview,#addTrack,#addBus,#addFx,#reset,#saveScene,#recallScene,#sceneSafe,#group,#ungroup,#copy,#paste,#clearCue,#pluginsButton,#pluginScan,#pluginImport,#pluginAddPath"); + if(!target)return; + event.preventDefault();event.stopImmediatePropagation(); + status("NATIVE: "+target.id+" requires real engine admission and readback"); + },true); + // Native pointer fader uses the approved physical fader geometry, but no + // reference JS gain state. Send once at release, not on every pointer frame. + window.addEventListener("pointerup",()=>{ + if (typeof faderGesture==="undefined"||!faderGesture)return; + const input=faderGesture.input,t=typeof findTrack==="function"?findTrack(input):null; + if (t) { + const db=Number(input.value); + if(Number.isFinite(db))intent("SET_FADER",t,{valueDb:db}); + } + },true); + const ready=()=>{ + stopDemo(); + status("NATIVE: subscribed · waiting for true device and accepted ChannelId graph"); + backend.emitEvent("arMixGuiReady",{ + gui:"APPROVED_PAGES_PREVIEW_BUTTONS",visualReady:true,audioReady:false + }); + controller.subscribe(); + }; + if(document.readyState==="loading") + document.addEventListener("DOMContentLoaded",ready,{once:true}); + else ready(); })(); From 42980f2edc03f78b70e2f71bcf85eab4ee6ce3ec Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:47:54 +0700 Subject: [PATCH 07/29] fix(m2): freeze unacknowledged source projection and bound native intent timeout --- web/approved-native-contract.js | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/web/approved-native-contract.js b/web/approved-native-contract.js index f08cfc2d4..f35a0a902 100644 --- a/web/approved-native-contract.js +++ b/web/approved-native-contract.js @@ -110,6 +110,14 @@ pending=null;lastError="STALE_DEVICE"; } } + if (pending && !pending.ack) { + // Unsolicited snapshot must never repaint an un-ACKed local edit. + notify();return true; + } + if (pending && pending.ack && !next.admitted) { + pending=null;lastError="CALLBACK_UNADMITTED"; + notify();return false; + } if (pending && pending.ack) { const ack=pending.ack; if (next.device.epoch !== ack.deviceEpoch) { @@ -177,7 +185,12 @@ subscribe(); return true; } - return Object.freeze({subscribe,onSnapshot,onAck,intent,state}); + function expire(requestId) { + if (!pending || pending.requestId!==requestId) return false; + pending=null;lastError="NATIVE_ACK_OR_READBACK_TIMEOUT"; + subscribe();notify();return true; + } + return Object.freeze({subscribe,onSnapshot,onAck,intent,state,expire}); } return Object.freeze({decimal,cmp,normalizeSnapshot,createController}); }); From 4be2137107d2e40fbd1d3c493352666f05a14ce3 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:48:08 +0700 Subject: [PATCH 08/29] fix(m2): bounded native ACK/readback timeout retains last accepted GUI --- web/approved-native-bridge.js | 1 + 1 file changed, 1 insertion(+) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 7ad3a86d5..750b88485 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -37,6 +37,7 @@ const id = nativeIdFor(t); const result = controller?.intent(operation,id,payload) || {ok:false,error:"NATIVE_UNAVAILABLE"}; if (!result.ok) status("NATIVE: "+result.error+" — controls unchanged"); + else window.setTimeout(()=>controller?.expire(result.requestId),8000); return result.ok; }; function projection(native) { From 1fe80752fc160a9d355ec8f841ccda5763e85796 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:49:31 +0700 Subject: [PATCH 09/29] test(m2): deterministic uint64, stale/reject, accepted ACK + later same revision, live capability gate --- tests/approved_native_m2_contract.test.cjs | 142 +++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 tests/approved_native_m2_contract.test.cjs diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs new file mode 100644 index 000000000..69eb34a58 --- /dev/null +++ b/tests/approved_native_m2_contract.test.cjs @@ -0,0 +1,142 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// M2 deterministic native transport: no fake ChannelIds, ACK-only success or PCM. +const test=require("node:test"); +const assert=require("node:assert/strict"); +const {readFileSync}=require("node:fs"); +const protocol=require("../web/approved-native-contract.js"); +const read=p=>readFileSync(p,"utf8"); +const fixtures=JSON.parse(read("integration/console-v6/fixtures.json")); +const clone=x=>JSON.parse(JSON.stringify(x)); +function acceptedFixture(){ + const s=clone(fixtures.g0); + s.device.epoch="18446744073709551610"; + s.productionCallbackLive=true; + s.graph.revision="5";s.graph.rosterRevision="7"; + s.graph.mainChannelId="18446744073709551615"; + s.graph.capabilities.callbackOwnsChannelIds=true; + s.graph.capabilities.supportedOps=["SET_FADER","SET_MUTE","APPLY_WIRE_TRANSACTION"]; + const input="9007199254740993",main=s.graph.mainChannelId; + s.graph.channels=[ + {id:input,role:"INPUT",name:"Vocal",processingFormat:"MONO",primaryOutId:main, + controls:{faderDb:-6,pan:0,mute:false,solo:false},inserts:[],sends:[]}, + {id:main,role:"MAIN",name:"MAIN",processingFormat:"STEREO", + controls:{faderDb:0,pan:0,mute:false,solo:false},inserts:[],sends:[]} + ]; + s.graph.destinations=[{id:main}]; + s.graph.edges=[{edgeId:"9223372036854775808",from:input,to:main, + tap:"POST",gainLinear:1,enabled:true,signalKind:"AUDIO"}]; + return s; +} +test("G0 current JUCE device snapshot is valid, never ChannelId PCM LIVE",()=>{ + const s=protocol.normalizeSnapshot(fixtures.g0); + assert.ok(s);assert.equal(s.admitted,false); + assert.deepEqual(s.graph.channels,[]); + assert.deepEqual(s.graph.capabilities.supportedOps,[]); + assert.equal(protocol.decimal("18446744073709551615"),"18446744073709551615"); + for(const invalid of ["01","-1","1.1",1,9007199254740993,"18446744073709551616",null," 1"]) { + assert.equal(protocol.decimal(invalid),null); + } +}); +test("strict producer rejects JS Number identities, invalid hardware pins and fake LIVE",()=>{ + const cases=[ + s=>{s.device.epoch=69;}, + s=>{s.graph.revision=5;}, + s=>{s.device.enabledInputs=[0,0];}, + s=>{s.device.inputEndpoints[0].port=88;}, + s=>{s.graph.channels[0].id=Number.MAX_SAFE_INTEGER+5;}, + s=>{s.graph.edges[0].edgeId="18446744073709551616";}, + s=>{s.graph.edges[0].to="0";}, + s=>{s.graph.channels[1].id=s.graph.channels[0].id;}, + ]; + for(const corrupt of cases){ + const s=acceptedFixture();corrupt(s); + assert.equal(protocol.normalizeSnapshot(s),null); + } + const s=acceptedFixture(); + assert.equal(protocol.normalizeSnapshot(s).admitted,true); + assert.equal(s.graph.channels[0].id,"9007199254740993"); +}); +test("SET_FADER: one exact string request, ACK then LATER same-revision native readback",()=>{ + const sent=[],visible=[]; + const c=protocol.createController({emit:(name,payload)=>sent.push({name,payload}),onAccepted:s=>visible.push(s.identity)}); + const s=acceptedFixture(); + assert.equal(c.onSnapshot(s),true); + const result=c.intent("SET_FADER","9007199254740993",{valueDb:-12}); + assert.equal(result.ok,true); + const message=sent.at(-1).payload; + assert.match(message.requestId,/^m2-[0-9a-z]+-[0-9a-z]+-1$/); + assert.equal(message.targetChannelId,"9007199254740993"); + assert.equal(message.deviceEpoch,s.device.epoch); + assert.equal(message.baseGraphRevision,"5"); + assert.equal(message.baseRosterRevision,"7"); + const later=clone(s);later.graph.revision="6";later.graph.channels[0].controls.faderDb=-12; + assert.equal(c.onSnapshot(later),true); + assert.equal(c.state().current.graph.revision,"5","no unACKed repaint"); + assert.equal(visible.length,1); + assert.equal(c.onAck({requestId:"wrong",status:"ACCEPTED",deviceEpoch:s.device.epoch, + graphRevision:"6",rosterRevision:"7",errorCode:"NONE"}),false); + assert.equal(c.onAck({requestId:result.requestId,status:"ACCEPTED",deviceEpoch:s.device.epoch, + graphRevision:"6",rosterRevision:"7",errorCode:"NONE"}),true); + assert.equal(c.state().current.graph.revision,"5","ACK alone MUST NOT repaint"); + assert.equal(sent.at(-1).name,"arMixConsoleSubscribe","later readback requested"); + assert.equal(c.onSnapshot(later),true); + assert.equal(c.state().current.graph.revision,"6"); + assert.equal(c.state().pending,null); + assert.equal(visible.length,2); +}); +test("STALE/REJECTED/timeout leave accepted GUI untouched and request fresh native readback",()=>{ + const sent=[],c=protocol.createController({emit:(name,payload)=>sent.push({name,payload})}); + const s=acceptedFixture();c.onSnapshot(s); + assert.equal(c.intent("SET_PAN","9007199254740993",{value:0.5}).ok,false); + assert.equal(c.intent("SET_FADER","1",{valueDb:0}).ok,false); + const one=c.intent("SET_FADER","9007199254740993",{valueDb:0}); + assert.equal(c.intent("SET_FADER","9007199254740993",{valueDb:1}).ok,false); + assert.equal(c.onAck({requestId:one.requestId,status:"REJECTED", + deviceEpoch:s.device.epoch,graphRevision:"5",rosterRevision:"7",errorCode:"STALE_GRAPH"}),false); + assert.equal(c.state().current.graph.revision,"5"); + assert.equal(c.state().pending,null); + assert.equal(c.state().lastError,"STALE_GRAPH"); + const two=c.intent("SET_FADER","9007199254740993",{valueDb:1}); + assert.equal(c.expire(two.requestId),true); + assert.equal(c.expire(two.requestId),false); + assert.equal(c.state().pending,null); + assert.equal(c.state().current.graph.revision,"5"); + const three=c.intent("SET_FADER","9007199254740993",{valueDb:2}); + const changed=clone(s);changed.device.epoch="18446744073709551611"; + changed.graph.revision="0";changed.graph.rosterRevision="0"; + changed.productionCallbackLive=false; + changed.graph.channels=[];changed.graph.edges=[];changed.graph.destinations=[]; + changed.graph.capabilities.callbackOwnsChannelIds=false; + changed.graph.capabilities.supportedOps=[]; + assert.equal(c.onSnapshot(changed),true); + assert.equal(c.state().current.admitted,false); + assert.equal(c.state().pending,null); + assert.equal(c.state().lastError,"STALE_DEVICE"); + assert.equal(c.onAck({requestId:three.requestId,status:"ACCEPTED", + deviceEpoch:s.device.epoch,graphRevision:"6",rosterRevision:"7",errorCode:"NONE"}),false); + assert.ok(sent.filter(x=>x.name==="arMixConsoleSubscribe").length>=2); +}); +test("M2 code edits approved Pages *events* only, not a second native GUI/audio engine",()=>{ + const page=read("site/preview-v2/index.html"); + const native=read("src/Main.cpp"); + const header=read("src/ApprovedConsoleNativeTransportV6.h"); + const adapter=read("web/approved-native-bridge.js"); + const bundle=read("scripts/build_approved_native_gui.py"); + for(const key of ["consumeField","consumeAction","consumeWire","consumeUndo","consumeDoubleClick"]) { + assert.match(page,new RegExp("__ARMIX_NATIVE_M2__\\?\\."+key)); + assert.match(adapter,new RegExp(key+"\\(")); + } + for(const name of ["arMixConsoleSubscribe","arMixConsoleSnapshot","arMixConsoleIntent","arMixConsoleAck"]) { + assert.match(native,new RegExp(name)); + assert.match(adapter,new RegExp(name)); + } + assert.match(header,/getActiveInputChannels/); + assert.match(header,/getActiveOutputChannels/); + assert.match(header,/G0_CURRENT_JUCE_DEVICE_ONLY__CHANNELID_NOT_ADMITTED/); + assert.match(header,/UNSUPPORTED_OP/); + assert.match(header,/productionCallbackLive", false/); + assert.match(header,/callbackOwnsChannelIds", false/); + assert.match(bundle,/approved-native-contract\.js/); + assert.doesNotMatch(native,/BinaryData::consolenative_html|BinaryData::index_html/); + assert.doesNotMatch(adapter,/AudioContext|AudioWorklet|processBlock|setChannelGainDb/); +}); From 1a20686c4a11ad4161d9e556a409f460f765c067 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:50:43 +0700 Subject: [PATCH 10/29] test(m2): check explicit fail-closed initial authority flags in updated approved GUI bridge --- tests/native_artifact_packaging_contract_test.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/native_artifact_packaging_contract_test.mjs b/tests/native_artifact_packaging_contract_test.mjs index 6b33b1a86..b2f8216f1 100644 --- a/tests/native_artifact_packaging_contract_test.mjs +++ b/tests/native_artifact_packaging_contract_test.mjs @@ -79,8 +79,8 @@ test('native bridge authenticates UI readiness but never hallucinates PCM/VST3 L assert.match(nativeMain,/withEventListener \("arMixGuiReady"/); assert.doesNotMatch(nativeMain,/pageFinishedLoading \(const juce::String&\) override \{ loaded = true; \}/); assert.match(adapter,/emitEvent\("arMixGuiReady"/); - assert.match(adapter,/acceptedGraphConnected: false/); - assert.match(adapter,/productionCallbackLive: false/); + assert.match(adapter,/acceptedGraphConnected:false/); + assert.match(adapter,/productionCallbackLive:false/); assert.match(packaging,/webView2LoaderMode = "JUCE_WEBVIEW2_LOADER_STATIC_LINKED_V1"/); assert.match(verify,/manifest\.webView2LoaderMode/); assert.match(verify,/WEBVIEW2_GUI_READY_TIMEOUT/); From 1a25670b8a2a2c2e4f7d921fc56a0864cfb7d251 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:50:48 +0700 Subject: [PATCH 11/29] test(m2): check explicit fail-closed initial authority flags in updated approved GUI bridge --- tests/reconciled_gui_engine_contract_test.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/reconciled_gui_engine_contract_test.mjs b/tests/reconciled_gui_engine_contract_test.mjs index 5fede272e..2d527eef5 100644 --- a/tests/reconciled_gui_engine_contract_test.mjs +++ b/tests/reconciled_gui_engine_contract_test.mjs @@ -65,8 +65,8 @@ test('JUCE native resources use EXACT assembled Pages /preview/, not archived we assert.match(pagesBuilder,/buttons_dest=dst\/'preview'/); assert.match(generator,/approvedPagesHtmlSha256/); assert.match(generator,/SCAFFOLD_ONLY__NOT_LIVE_PCM/); - assert.match(nativeAdapter,/acceptedGraphConnected: false/); - assert.match(nativeAdapter,/productionCallbackLive: false/); + assert.match(nativeAdapter,/acceptedGraphConnected:false/); + assert.match(nativeAdapter,/productionCallbackLive:false/); // Historical web app still verifies its archival CSS/standalone consistency. // It is NEVER the native compiled mixer or a second GUI product. assert.ok(css.endsWith(oldSourceCss),'archival CSS byte relationship drift'); From 97aa0cec3a3cdf14020bf04bfb46d5c4fea359b1 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:51:23 +0700 Subject: [PATCH 12/29] ci(m2): cover actual native transport JS and contract replay in existing Windows job --- .github/workflows/p1-windows.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 93e3c2c89..b40e86125 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -9,6 +9,8 @@ on: - 'integration/console-v6/**' - 'src/**' - 'web/approved-native-bridge.js' + - 'web/approved-native-contract.js' + - 'tests/approved_native_m2_contract.test.cjs' - 'scripts/build_approved_native_gui.py' - 'tests/approved_native_gui_bundle_test.py' - 'engine/**' @@ -32,6 +34,8 @@ on: - 'integration/console-v6/**' - 'src/**' - 'web/approved-native-bridge.js' + - 'web/approved-native-contract.js' + - 'tests/approved_native_m2_contract.test.cjs' - 'scripts/build_approved_native_gui.py' - 'tests/approved_native_gui_bundle_test.py' - 'web/bridge.js' @@ -91,12 +95,13 @@ jobs: run: | # Do not hide earlier Node failures with the exit code of the LAST # command. One Node invocation also avoids repeated startup costs. - foreach ($file in @('web/bridge.js', 'web/plugin-ui.js', 'web/monitor.js', 'web/app.js', 'web/mixer-io.js', 'web/mixer-layout.js')) { + foreach ($file in @('web/bridge.js', 'web/plugin-ui.js', 'web/monitor.js', 'web/app.js', 'web/mixer-io.js', 'web/mixer-layout.js', 'web/approved-native-contract.js', 'web/approved-native-bridge.js')) { node --check $file if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } } $contracts = @( 'tests/gui_workflow_contract_test.mjs' + 'tests/approved_native_m2_contract.test.cjs' 'tests/native_ui_contract_test.mjs' 'tests/native_preset_contract_test.mjs' 'tests/fx_add_contract_test.mjs' From 3135b0831a83c6f29dea1a43624b58a1ca0fbd07 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:51:49 +0700 Subject: [PATCH 13/29] ci(m2 browser): run pure readback/ACK replay next to existing UI tests without creating workflows --- .github/workflows/ui-smoke.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 3d2884c28..c04be840b 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -19,6 +19,7 @@ on: - 'tests/wire_graph_canonical_model.test.cjs' - 'tests/wire_main_native_handoff_contract.test.cjs' - 'tests/ci_workflow_efficiency_test.mjs' + - 'tests/approved_native_m2_contract.test.cjs' - 'scripts/build_ui_css.py' - '.github/workflows/ui-smoke.yml' - '.github/workflows/pages-publish.yml' @@ -36,6 +37,7 @@ on: - 'tests/native_ui_contract_test.mjs' - 'tests/native_orbit_ui_smoke.py' - 'tests/ci_workflow_efficiency_test.mjs' + - 'tests/approved_native_m2_contract.test.cjs' - 'tests/wire_graph_canonical_model.test.cjs' - 'tests/wire_main_native_handoff_contract.test.cjs' - '.github/workflows/ui-smoke.yml' @@ -77,7 +79,7 @@ jobs: node --check web/plugin-ui.js node --check web/mixer-io.js node --check web/mixer-layout.js - node --test tests/gui_workflow_contract_test.mjs tests/plugin_ui_contract_test.mjs tests/ci_workflow_efficiency_test.mjs tests/fx_drag_reorder_contract_test.mjs tests/mixer_io_operator_contract_test.mjs tests/mixer_shell_contract_test.mjs + node --test tests/gui_workflow_contract_test.mjs tests/plugin_ui_contract_test.mjs tests/ci_workflow_efficiency_test.mjs tests/fx_drag_reorder_contract_test.mjs tests/mixer_io_operator_contract_test.mjs tests/mixer_shell_contract_test.mjs tests/approved_native_m2_contract.test.cjs - name: Validate approved GUI checkpoint and single publisher run: python tests/gui_baseline_lock_test.py - name: CSS V28 zero-regression source-order recovery (every GUI CI run) From dd1574f3c7ba32508f4af71de277bc3905b7d3a9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:52:20 +0700 Subject: [PATCH 14/29] test(m2): unadmitted device switch drops stale MAIN graph identity --- tests/approved_native_m2_contract.test.cjs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 69eb34a58..e0aa4b174 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -106,6 +106,7 @@ test("STALE/REJECTED/timeout leave accepted GUI untouched and request fresh nati changed.graph.revision="0";changed.graph.rosterRevision="0"; changed.productionCallbackLive=false; changed.graph.channels=[];changed.graph.edges=[];changed.graph.destinations=[]; + delete changed.graph.mainChannelId; changed.graph.capabilities.callbackOwnsChannelIds=false; changed.graph.capabilities.supportedOps=[]; assert.equal(c.onSnapshot(changed),true); From f82b556399a800b0923c6e22dfba3fae60d0afb7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:53:01 +0700 Subject: [PATCH 15/29] test(ci): M2 native JS and replay tests trigger only existing relevant Windows+UI workflows --- tests/ci_workflow_efficiency_test.mjs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/ci_workflow_efficiency_test.mjs b/tests/ci_workflow_efficiency_test.mjs index e7a64eabb..3f28e4d7d 100644 --- a/tests/ci_workflow_efficiency_test.mjs +++ b/tests/ci_workflow_efficiency_test.mjs @@ -74,6 +74,8 @@ test('native PCM and device changes always use Windows/CTest, never Chromium by test('approved Pages to JUCE build seam is a native gate, never an unrelated CSS-only job', () => { for (const filename of [ 'web/approved-native-bridge.js', + 'web/approved-native-contract.js', + 'tests/approved_native_m2_contract.test.cjs', 'scripts/build_approved_native_gui.py', 'tests/approved_native_gui_bundle_test.py' ]) { From fdff3b5d9811af19cf6f96f01a484dcac26b6878 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:54:32 +0700 Subject: [PATCH 16/29] fix(test m2): count subscribe/intent event names in the exact protocol module that emits them --- tests/approved_native_m2_contract.test.cjs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index e0aa4b174..29c0d01f4 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -127,9 +127,11 @@ test("M2 code edits approved Pages *events* only, not a second native GUI/audio assert.match(page,new RegExp("__ARMIX_NATIVE_M2__\\?\\."+key)); assert.match(adapter,new RegExp(key+"\\(")); } + const protocolSource=read("web/approved-native-contract.js"); for(const name of ["arMixConsoleSubscribe","arMixConsoleSnapshot","arMixConsoleIntent","arMixConsoleAck"]) { assert.match(native,new RegExp(name)); - assert.match(adapter,new RegExp(name)); + assert.ok(adapter.includes(name)||protocolSource.includes(name), + "same transport operation must be sent or consumed by JS: "+name); } assert.match(header,/getActiveInputChannels/); assert.match(header,/getActiveOutputChannels/); From 43ff9c39453af50797deaa114dc06a814a9c66f4 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:56:45 +0700 Subject: [PATCH 17/29] fix(m2): keep approved public /preview/ HTML byte-identical; native-only hook belongs in bundle stage --- site/preview-v2/index.html | 5 ----- 1 file changed, 5 deletions(-) diff --git a/site/preview-v2/index.html b/site/preview-v2/index.html index b1442ac65..7be436edb 100644 --- a/site/preview-v2/index.html +++ b/site/preview-v2/index.html @@ -345,7 +345,6 @@ } } function wireGraphCommit(ops,{record=true}={}){ - if(window.__ARMIX_NATIVE_M2__?.consumeWire?.(ops))return false; const before=record?wireWsSnapshot():null; const result=ArSonWireGraph.applyWireTransaction({ channels:tracks,mainId:master.id,edges:wireEdges,nextId:nextWireId @@ -1006,7 +1005,6 @@ const btn=document.getElementById('wireWsUndo');if(btn)btn.disabled=false; } function wireWsUndo(){ - if(window.__ARMIX_NATIVE_M2__?.consumeUndo?.())return false; const entry=wireWsHistory[wireWsHistory.length-1]; if(!entry){say('WIRE: no routing change to undo');return false;} if(wireWsSignature(wireWsSnapshot())!==entry.afterSig){ @@ -1710,7 +1708,6 @@ render();say(groups.size?'Removed '+groups.size+' channel group(s)':'Select a grouped channel to ungroup'); } function handleField(event){ - if(window.__ARMIX_NATIVE_M2__?.consumeField?.(event))return; const el=event.target,field=el.dataset.field;if(!field)return; const t=findTrack(el);if(!t)return; if(field==='wireGain'){ @@ -1966,7 +1963,6 @@ const btn=e.target.closest('[data-action]');if(!btn)return; const t=findTrack(btn);if(!t)return; const a=btn.dataset.action; - if(window.__ARMIX_NATIVE_M2__?.consumeAction?.(t,a,btn))return; if(a==='wireExpand'){document.querySelector('.section-rail [data-section="send"]')?.click();return;} if(a==='resetClip'){ t.clip=false;btn.classList.remove('clipping'); @@ -2019,7 +2015,6 @@ }); document.querySelector('.console-body').addEventListener('dblclick',e=>{ const t=findTrack(e.target);if(!t)return; - if(window.__ARMIX_NATIVE_M2__?.consumeDoubleClick?.(e,t))return; if(e.target.closest?.('.wire-gain,.wire-pot')){ const el=e.target.closest('.wire-pot')?.querySelector('.wire-gain')||e.target.closest('.wire-gain');el.value='0';handleField({target:el,type:'change'});return; } From 741530ec8c5b9fc3ff720bce1749c8bae88dde2d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:58:25 +0700 Subject: [PATCH 18/29] fix(m2): instrument control hooks in generated native-only HTML; retain exact approved public checkpoint --- scripts/build_approved_native_gui.py | 50 ++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index 5077bc0f0..32493f2f2 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -52,11 +52,57 @@ def accepted_pages_html() -> str: return (build_public_pages(Path(tmp) / "public") / "index.html").read_text("utf-8") +# Native-only event seam: the original PUBLIC Pages HTML is byte-for-byte +# unchanged. Insert five small control hooks ONLY into the generated WebView2 +# HTML at native build time. Every anchor must occur exactly once: no silent +# breakage if Pages GUI source evolves. No extra layout or simulated PCM. +NATIVE_EVENT_HOOKS = ( + ("function wireGraphCommit(ops,{record=true}={}){\n", + "function wireGraphCommit(ops,{record=true}={}){\n" + " if(window.__ARMIX_NATIVE_M2__?.consumeWire?.(ops))return false;\n"), + ("function wireWsUndo(){\n", + "function wireWsUndo(){\n" + " if(window.__ARMIX_NATIVE_M2__?.consumeUndo?.())return false;\n"), + ("function handleField(event){\n", + "function handleField(event){\n" + " if(window.__ARMIX_NATIVE_M2__?.consumeField?.(event))return;\n"), + (" if(a==='wireExpand'){document.querySelector('.section-rail", + " if(window.__ARMIX_NATIVE_M2__?.consumeAction?.(t,a,btn))return;\n" + " if(a==='wireExpand'){document.querySelector('.section-rail"), + ("document.querySelector('.console-body').addEventListener('dblclick',e=>{\n" + " const t=findTrack(e.target);if(!t)return;\n", + "document.querySelector('.console-body').addEventListener('dblclick',e=>{\n" + " const t=findTrack(e.target);if(!t)return;\n" + " if(window.__ARMIX_NATIVE_M2__?.consumeDoubleClick?.(e,t))return;\n"), +) + + def native_html(approved: str | None = None) -> str: - html = accepted_pages_html() if approved is None else approved + original = accepted_pages_html() if approved is None else approved + newline = "\r\n" if "\r\n" in original else "\n" + html = original.replace("\r\n", "\n") if html.count("") != 1 or ADAPTER_MARKER in html: raise ValueError("Approved Pages must have exactly one body and no prior native injection") - return html.replace("", ADAPTER_MARKER + "\n") + for before, after in NATIVE_EVENT_HOOKS: + if html.count(before) != 1 or after in html: + raise ValueError("Native-only M2 control hook anchor drift: " + before[:55]) + html = html.replace(before, after, 1) + html = html.replace("", ADAPTER_MARKER + "\n") + return html.replace("\n", newline) + + +def public_from_native(native: str) -> str: + """Reconstruct original public Pages HTML byte-for-byte from the native source.""" + newline = "\r\n" if "\r\n" in native else "\n" + html = native.replace("\r\n", "\n") + if html.count(ADAPTER_MARKER + "\n") != 1: + raise ValueError("Native adapter marker missing or duplicated") + html = html.replace(ADAPTER_MARKER + "\n", "", 1) + for before, after in reversed(NATIVE_EVENT_HOOKS): + if html.count(after) != 1: + raise ValueError("Native-only M2 control hook missing or duplicated") + html = html.replace(after, before, 1) + return html.replace("\n", newline) def safe_symbol(filename: str) -> str: From 6e09c7210cbc2a196ae5b5f10f622d56e05e34eb Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:58:46 +0700 Subject: [PATCH 19/29] test(m2): enforce exact unchanged public Pages and reversible native-only control hooks --- tests/approved_native_gui_bundle_test.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/approved_native_gui_bundle_test.py b/tests/approved_native_gui_bundle_test.py index ff19498c2..a00b6d92a 100644 --- a/tests/approved_native_gui_bundle_test.py +++ b/tests/approved_native_gui_bundle_test.py @@ -21,7 +21,9 @@ def test_native_is_exact_assembled_public_pages_plus_nonvisual_native_seam(self) self.assertEqual(manifest["adapterState"], "SCAFFOLD_ONLY__NOT_LIVE_PCM") approved = (source / "index.html").read_text("utf-8") native = (out / "index.html").read_text("utf-8") - self.assertEqual(native.replace(bundle.ADAPTER_MARKER + "\n", ""), approved) + self.assertEqual(bundle.public_from_native(native), approved) + self.assertNotIn("__ARMIX_NATIVE_M2__", approved) + self.assertIn("__ARMIX_NATIVE_M2__", native) self.assertEqual(manifest["approvedPagesHtmlSha256"], bundle.sha256((source / "index.html").read_bytes())) self.assertNotEqual(native, (ROOT / "web/index.html").read_text("utf-8")) self.assertIn("approved-native-bridge.js", native) From 13271dd3c10cabbd2e2adfaad4a813c51749d049 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 19:58:51 +0700 Subject: [PATCH 20/29] test(m2): enforce exact unchanged public Pages and reversible native-only control hooks --- tests/approved_native_m2_contract.test.cjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 29c0d01f4..9a5e0a0e2 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -124,7 +124,8 @@ test("M2 code edits approved Pages *events* only, not a second native GUI/audio const adapter=read("web/approved-native-bridge.js"); const bundle=read("scripts/build_approved_native_gui.py"); for(const key of ["consumeField","consumeAction","consumeWire","consumeUndo","consumeDoubleClick"]) { - assert.match(page,new RegExp("__ARMIX_NATIVE_M2__\\?\\."+key)); + assert.doesNotMatch(page,/__ARMIX_NATIVE_M2__/,"public Pages checkpoint stays untouched"); + assert.match(read("scripts/build_approved_native_gui.py"),new RegExp("__ARMIX_NATIVE_M2__\\?\\."+key)); assert.match(adapter,new RegExp(key+"\\(")); } const protocolSource=read("web/approved-native-contract.js"); From f818a4479f4039105d2d618f1b2a54d3b4f2b12a Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 20:04:58 +0700 Subject: [PATCH 21/29] fix(m2 win): use mutable JUCE AudioIODevice pointer for non-const SDK methods --- src/ApprovedConsoleNativeTransportV6.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ApprovedConsoleNativeTransportV6.h b/src/ApprovedConsoleNativeTransportV6.h index f36905e3f..453f39288 100644 --- a/src/ApprovedConsoleNativeTransportV6.h +++ b/src/ApprovedConsoleNativeTransportV6.h @@ -69,7 +69,7 @@ inline juce::var snapshot (const juce::var& live, dev->setProperty ("playbackDevice", live.getProperty ("outputDevice", juce::var (""))); juce::Array enabledInputs, enabledOutputs; juce::var inputs (juce::Array{}), outputs (juce::Array{}); - const auto* active = manager.getCurrentAudioDevice(); + auto* active = manager.getCurrentAudioDevice(); // JUCE AudioIODevice getters are not const-qualified const bool direct = ! static_cast (live.getProperty ("adaptiveClockActive", false)); if (active != nullptr && active->isOpen()) { From 904345f3008115fe040d6604f1eb6c5804ac1b38 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 20:05:17 +0700 Subject: [PATCH 22/29] fix(m2): require exactly one native MAIN identity and explicit edge readback before LIVE admission --- web/approved-native-contract.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/web/approved-native-contract.js b/web/approved-native-contract.js index f35a0a902..e4c93bb9a 100644 --- a/web/approved-native-contract.js +++ b/web/approved-native-contract.js @@ -74,9 +74,11 @@ (decimal(g.mainChannelId) === null || !ids.includes(g.mainChannelId))) return null; // Advertised LIVE is gated by real native callback, valid graph, and actual hardware. // A dishonest producer cannot be "fixed" by manufacturing Channels in JS. + const mainCount = g.channels.filter(ch=>ch.role==="MAIN").length; const admitted = raw.productionCallbackLive === true && caps.callbackOwnsChannelIds === true && cmp(d.epoch,"0") > 0 && cmp(g.revision,"0") > 0 && - g.channels.length > 0 && typeof g.mainChannelId === "string" && + Array.isArray(g.edges) && g.channels.length > 0 && mainCount === 1 && + typeof g.mainChannelId === "string" && g.channels.some(ch => ch.id === g.mainChannelId && ch.role === "MAIN"); if (!admitted && (raw.productionCallbackLive || caps.callbackOwnsChannelIds) && g.channels.length === 0) return null; From 94d86547b99daa1fc76d0d4da67acef6626f3581 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 4 Nov 2026 20:05:53 +0700 Subject: [PATCH 23/29] fix(m2): block unprojected native intents, refresh same-revision controls, disable G0 physical gestures --- web/approved-native-bridge.js | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 750b88485..dc6ef49f6 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -13,7 +13,7 @@ const uiByNativeId = new Map(); // EXACT uint64 string -> local view-only ordinal const wireByUiId = new Map(); // view-only EdgeId -> EXACT decimal-string native EdgeId const uiByWireId = new Map(); - let lastPaintedIdentity = "", lastNativeError = "NATIVE_NOT_SUBSCRIBED"; + let lastPaintedSignature = "", lastNativeError = "NATIVE_NOT_SUBSCRIBED"; let controller = null; const status = message => { lastNativeError = message; @@ -34,6 +34,10 @@ }; const nativeIdFor = t => nativeByUiId.get(t?.id) || null; const intent = (operation,t,payload) => { + if (!flags.acceptedGraphConnected) { + status("NATIVE: accepted graph not projected; control unchanged"); + return false; + } const id = nativeIdFor(t); const result = controller?.intent(operation,id,payload) || {ok:false,error:"NATIVE_UNAVAILABLE"}; if (!result.ok) status("NATIVE: "+result.error+" — controls unchanged"); @@ -122,14 +126,18 @@ status("NATIVE G0 · perangkat aktual terbaca; ChannelId PCM/WIRE belum diterima. Edit audio diblokir."); return; } - if (next.identity===lastPaintedIdentity)return; + // Control readback may change at the SAME structural graph revision. + // Compare the actual accepted controls/edges, never skip native fader updates. + const signature=next.identity+"|"+JSON.stringify(next.graph.channels.map(ch=>[ + ch.id,ch.controls,ch.inserts,ch.primaryOutId]))+"|"+JSON.stringify(next.graph.edges); + if (signature===lastPaintedSignature)return; if (!projection(next)) { flags.acceptedGraphConnected=false;flags.productionCallbackLive=false; stopDemo();status("NATIVE READBACK INVALID · existing GUI controls unchanged"); return; } flags.productionCallbackLive=true;flags.acceptedGraphConnected=true; - lastPaintedIdentity=next.identity;stopDemo(); + lastPaintedSignature=signature;stopDemo(); status("NATIVE ACCEPTED · device "+next.device.epoch+ " · graph "+next.graph.revision+" · roster "+next.graph.rosterRevision); } @@ -157,6 +165,12 @@ if (!field)return false; const t=typeof findTrack==="function"?findTrack(el):null; if (!t)return true; + if (!flags.acceptedGraphConnected) { + if (field==="level")el.value=String(t.level); + else if (field==="pan")el.value=String(t.pan); + status("NATIVE: ChannelId PCM not admitted; control unchanged"); + return true; + } if (event.type!=="change") return true; // no optimistic input-frame mutations const numeric=Number(el.value); if (field==="level"&&Number.isFinite(numeric)) @@ -180,7 +194,8 @@ consumeWire(ops) { if (!connected)return false; const current=controller?.state().current; - if (!current?.admitted || !current.graph.capabilities.supportedOps.includes("APPLY_WIRE_TRANSACTION")) { + if (!flags.acceptedGraphConnected || !current?.admitted || + !current.graph.capabilities.supportedOps.includes("APPLY_WIRE_TRANSACTION")) { status("NATIVE: WIRE transaction not admitted; graph unchanged");return true; } const changes=[]; @@ -225,6 +240,14 @@ value:descriptor,configurable:false,writable:false }); if (!connected)return; + // Disable physical control gestures while G0 has no accepted ChannelId graph. + // Presentation-only bank/selection remains available. + document.addEventListener("pointerdown",event=>{ + if (flags.acceptedGraphConnected) return; + if (!event.target.closest?.(".fader-box,.center-pan")) return; + event.preventDefault();event.stopImmediatePropagation(); + status("NATIVE G0: physical gain/pan unavailable until engine graph admission"); + },true); // Reference-only buttons outside strips must not mutate fake Show/FX state. document.addEventListener("click",event=>{ const target=event.target.closest?.( From b963342deaf448718c0767f78a1aaf7f69886407 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 02:15:44 +0700 Subject: [PATCH 24/29] M2: separate accepted PCM graph from product LIVE and verify native ACK effect before GUI commit --- web/approved-native-contract.js | 75 ++++++++++++++++++++++++++++++--- 1 file changed, 68 insertions(+), 7 deletions(-) diff --git a/web/approved-native-contract.js b/web/approved-native-contract.js index e4c93bb9a..2fa1eb97b 100644 --- a/web/approved-native-contract.js +++ b/web/approved-native-contract.js @@ -75,16 +75,72 @@ // Advertised LIVE is gated by real native callback, valid graph, and actual hardware. // A dishonest producer cannot be "fixed" by manufacturing Channels in JS. const mainCount = g.channels.filter(ch=>ch.role==="MAIN").length; - const admitted = raw.productionCallbackLive === true && caps.callbackOwnsChannelIds === true && + // Real accepted ChannelId PCM may exist before vendor/Show/hardware product + // FAT. Never equate an installed PCM graph with a release-ready product. + // Conversely, callbackOwnsChannelIds is ONLY advertised by the real + // installed callback; the legacy M4/Pages demo must remain unadmitted. + const admitted = caps.callbackOwnsChannelIds === true && cmp(d.epoch,"0") > 0 && cmp(g.revision,"0") > 0 && + d.sampleRate > 0 && d.bufferFrames > 0 && + d.enabledOutputs.length > 0 && d.outputEndpoints.length > 0 && Array.isArray(g.edges) && g.channels.length > 0 && mainCount === 1 && typeof g.mainChannelId === "string" && - g.channels.some(ch => ch.id === g.mainChannelId && ch.role === "MAIN"); - if (!admitted && (raw.productionCallbackLive || caps.callbackOwnsChannelIds) && - g.channels.length === 0) return null; + g.channels.some(ch => ch.id === g.mainChannelId && ch.role === "MAIN") && + g.channels.every(ch => fields(ch,["controls","inserts","sends"]) && + fields(ch.controls,["faderDb","pan","mute","solo"]) && + Number.isFinite(ch.controls.faderDb) && + Number.isFinite(ch.controls.pan) && isBool(ch.controls.mute) && + isBool(ch.controls.solo) && Array.isArray(ch.inserts) && + Array.isArray(ch.sends)); + // A producer may stage PCM without claiming full release/UAT. A producer + // must NEVER claim product LIVE without an admitted PCM graph. + if (raw.productionCallbackLive && !admitted) return null; + if (caps.callbackOwnsChannelIds && !admitted) return null; return { raw, device:d, graph:g, telemetry:t, admitted, + productLive:admitted && raw.productionCallbackLive, identity: d.epoch + ":" + g.revision + ":" + g.rosterRevision }; } + // ACK alone is never physical evidence. Readback must prove that a known + // control/route actually reached the accepted native graph. No invented UI + // updates and no optimistic fader/edge commits. + function readbackProvesIntent(next, pending) { + const {operation,targetChannelId,payload} = pending; + const ch = next.graph.channels.find(c=>c.id===targetChannelId); + if (!ch) return false; + if (operation === "SET_FADER") + return Number.isFinite(payload.valueDb) && + Math.abs(ch.controls.faderDb-payload.valueDb)<=0.11; + if (operation === "SET_PAN") + return Number.isFinite(payload.value) && + Math.abs(ch.controls.pan-payload.value)<=0.015; + if (operation === "SET_MUTE" || operation === "SET_SOLO") + return typeof payload.value==="boolean" && + ch.controls[operation==="SET_MUTE"?"mute":"solo"]===payload.value; + if (operation !== "APPLY_WIRE_TRANSACTION" || + !Array.isArray(payload.changes) || !payload.changes.length) return false; + // A structural WIRE transaction must advance the actual PCM graph. + if (cmp(next.graph.revision,pending.baseGraphRevision)<=0) return false; + const edges=next.graph.edges.filter(e=>e.enabled); + return payload.changes.every(edit=>{ + if (!object(edit) || decimal(edit.sourceId)===null) return false; + if (edit.type==="REMOVE" || edit.type==="DISCONNECT") + return decimal(edit.edgeId)!==null && + !edges.some(e=>e.edgeId===edit.edgeId); + if (edit.type==="CONNECT" || edit.type==="ROUTE_ONLY") + return decimal(edit.destId)!==null && + edges.some(e=>e.from===edit.sourceId&&e.to===edit.destId); + if (edit.type==="REPLUG") + return decimal(edit.edgeId)!==null && decimal(edit.destId)!==null && + edges.some(e=>e.edgeId===edit.edgeId&&e.from===edit.sourceId&&e.to===edit.destId); + if (edit.type==="GAIN") + return decimal(edit.edgeId)!==null && Number.isFinite(edit.levelDb) && + edges.some(e=>e.edgeId===edit.edgeId&&e.from===edit.sourceId&& + Math.abs((e.gainLinear>0?20*Math.log10(e.gainLinear):-60)-edit.levelDb)<=0.21); + // MODE and other operations require a native readback verifier before + // they can be advertised as effective by this consumer. + return false; + }); + } function createController({emit, onStatus=()=>{}, onAccepted=()=>{}}) { if (typeof emit !== "function") throw Error("Native emitter required"); let current = null, pending = null, lastRequest = 0, lastError = "NATIVE_NOT_SUBSCRIBED"; @@ -126,6 +182,10 @@ pending=null;lastError="STALE_DEVICE"; } else if (next.graph.revision === ack.graphRevision && next.graph.rosterRevision === ack.rosterRevision) { + if (!readbackProvesIntent(next,pending)) { + pending=null;lastError="ACK_READBACK_EFFECT_MISMATCH"; + subscribe();notify();return false; + } pending=null;lastError="ACCEPTED_READBACK"; current=next;onAccepted(next); notify();return true; @@ -157,8 +217,9 @@ baseGraphRevision:current.graph.revision, baseRosterRevision:current.graph.rosterRevision, operation,targetChannelId,payload}; - pending={requestId,operation,deviceEpoch:msg.deviceEpoch, - baseGraphRevision:msg.baseGraphRevision,baseRosterRevision:msg.baseRosterRevision,ack:null}; + pending={requestId,operation,targetChannelId,payload, + deviceEpoch:msg.deviceEpoch,baseGraphRevision:msg.baseGraphRevision, + baseRosterRevision:msg.baseRosterRevision,ack:null}; lastError="PENDING_NATIVE_ACK"; emit("arMixConsoleIntent",msg);notify();return {ok:true,requestId}; } @@ -194,5 +255,5 @@ } return Object.freeze({subscribe,onSnapshot,onAck,intent,state,expire}); } - return Object.freeze({decimal,cmp,normalizeSnapshot,createController}); + return Object.freeze({decimal,cmp,normalizeSnapshot,readbackProvesIntent,createController}); }); From 2590660b14c1ab8714b411d6e3ba9c7ac9def6fa Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 02:16:59 +0700 Subject: [PATCH 25/29] M2: read actual native meter telemetry and stage PCM graph separately from product LIVE --- web/approved-native-bridge.js | 52 +++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index dc6ef49f6..1e2891e89 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -29,8 +29,9 @@ preview = false; // original Pages animation sees false and stops itself demo?.setAttribute("aria-pressed","false"); } - document.documentElement.dataset.armixNativeAuthority = flags.productionCallbackLive ? - "accepted" : "not-admitted"; + document.documentElement.dataset.armixNativeAuthority = + flags.productionCallbackLive ? "product-live" : + flags.acceptedGraphConnected ? "pcm-accepted" : "not-admitted"; }; const nativeIdFor = t => nativeByUiId.get(t?.id) || null; const intent = (operation,t,payload) => { @@ -68,7 +69,8 @@ t.name=ch.name;t.kind=kind; t.format=ch.processingFormat.toLowerCase(); t.level=ch.controls.faderDb; - t.pan=ch.controls.pan; + // Native PAN is normalized [-1,+1]; approved fader console uses [-100,+100]. + t.pan=ch.controls.pan*100; t.mute=ch.controls.mute; t.solo=ch.controls.solo; t.selected=previous.get(t.id)?.selected || false; @@ -117,11 +119,40 @@ syncWireOutputProjection();render(); return true; } + // Native telemetry owns the physical meter. When no measured per-channel + // samples are published, leave the meter dark; never use Pages sine demo. + function paintNativeMeters(next) { + if (typeof displayMeterDbfs!=="function")return; + const data=next.telemetry?.channelMeterRmsPeak; + if (!data || typeof data!=="object")return; + const ts=performance.now(); + for (const ch of next.graph.channels) { + const ui=uiByNativeId.get(ch.id); + if (ui===undefined)continue; + const root=document.querySelector('.strip[data-id="'+ui+'"]'); + if (!root)continue; + const entry=data[ch.id]; + const one=typeof entry==="number"&&Number.isFinite(entry)&&entry>=0?entry:null; + const l=typeof entry?.peakL==="number"&&Number.isFinite(entry.peakL)&&entry.peakL>=0? + entry.peakL:one; + const right=typeof entry?.peakR==="number"&&Number.isFinite(entry.peakR)&&entry.peakR>=0? + entry.peakR:ch.processingFormat==="MONO"?l:null; + const paint=(side,peak)=>{ + const fill=root.querySelector('.meter-fill.'+side); + if(!fill)return; + const db=peak===null || peak===0?-90:20*Math.log10(peak); + displayMeterDbfs(fill,Math.max(-90,Math.min(6,db)),ts,ui+':'+(side==="left"?"L":"R")); + }; + paint("left",l); + paint("right",right); + } + } function onNativeReadback(next) { const caps=next?.graph?.capabilities; const nativeAdmitted=next.admitted && caps?.callbackOwnsChannelIds===true; if (!nativeAdmitted) { flags.productionCallbackLive=false;flags.acceptedGraphConnected=false; + lastPaintedSignature=""; stopDemo(); status("NATIVE G0 · perangkat aktual terbaca; ChannelId PCM/WIRE belum diterima. Edit audio diblokir."); return; @@ -130,15 +161,20 @@ // Compare the actual accepted controls/edges, never skip native fader updates. const signature=next.identity+"|"+JSON.stringify(next.graph.channels.map(ch=>[ ch.id,ch.controls,ch.inserts,ch.primaryOutId]))+"|"+JSON.stringify(next.graph.edges); - if (signature===lastPaintedSignature)return; + if (signature===lastPaintedSignature) { + // Telemetry often advances without a structural graph revision. + paintNativeMeters(next); + return; + } if (!projection(next)) { flags.acceptedGraphConnected=false;flags.productionCallbackLive=false; stopDemo();status("NATIVE READBACK INVALID · existing GUI controls unchanged"); return; } - flags.productionCallbackLive=true;flags.acceptedGraphConnected=true; - lastPaintedSignature=signature;stopDemo(); - status("NATIVE ACCEPTED · device "+next.device.epoch+ + flags.productionCallbackLive=next.productLive;flags.acceptedGraphConnected=true; + lastPaintedSignature=signature;stopDemo();paintNativeMeters(next); + status((next.productLive?"NATIVE PRODUCT LIVE":"NATIVE PCM GRAPH ACCEPTED · FAT PENDING")+ + " · device "+next.device.epoch+ " · graph "+next.graph.revision+" · roster "+next.graph.rosterRevision); } if (connected) { @@ -233,7 +269,7 @@ nativeTransport:connected, get acceptedGraphConnected(){return flags.acceptedGraphConnected;}, get productionCallbackLive(){return flags.productionCallbackLive;}, - status:fallback, + get status(){return lastNativeError||fallback;}, m2:nativeHooks }); Object.defineProperty(window,"__ARMIX_APPROVED_NATIVE_GUI__",{ From f1657b05aa29d39d3a0f9efab5b4052a5d435479 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 02:17:41 +0700 Subject: [PATCH 26/29] M2 tests: reject ACK without applied PCM controls or EdgeId route and separate product FAT from graph --- tests/approved_native_m2_contract.test.cjs | 100 +++++++++++++++++++++ 1 file changed, 100 insertions(+) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 9a5e0a0e2..9df8999cd 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -56,6 +56,106 @@ test("strict producer rejects JS Number identities, invalid hardware pins and fa assert.equal(protocol.normalizeSnapshot(s).admitted,true); assert.equal(s.graph.channels[0].id,"9007199254740993"); }); +test("real ChannelId PCM graph is usable before product/vendor FAT, without fake LIVE",()=>{ + const staged=acceptedFixture(); + staged.productionCallbackLive=false; + const parsed=protocol.normalizeSnapshot(staged); + assert.ok(parsed); + assert.equal(parsed.admitted,true,"native callback admission is independent of product FAT"); + assert.equal(parsed.productLive,false,"staged graph NEVER claims full product LIVE"); + const shipped=acceptedFixture(); + assert.equal(protocol.normalizeSnapshot(shipped).productLive,true); + const lying=acceptedFixture(); + lying.graph.capabilities.callbackOwnsChannelIds=false; + assert.equal(protocol.normalizeSnapshot(lying),null, + "product LIVE cannot be claimed without an installed ChannelId PCM callback"); + const fake=acceptedFixture(); + fake.graph.channels[0].controls=undefined; + assert.equal(protocol.normalizeSnapshot(fake),null, + "missing native fader/mute/solo readback cannot be papered over in JS"); +}); + +test("ACCEPTED ACK without matching physical control readback is rejected, not painted",()=>{ + const sent=[],visible=[]; + const c=protocol.createController({emit:(name,payload)=>sent.push({name,payload}), + onAccepted:x=>visible.push(x.graph.channels[0].controls.faderDb)}); + const staged=acceptedFixture();staged.productionCallbackLive=false; + assert.equal(c.onSnapshot(staged),true); + const i=c.intent("SET_FADER","9007199254740993",{valueDb:-23}); + assert.equal(i.ok,true); + assert.equal(c.onAck({requestId:i.requestId,status:"ACCEPTED", + deviceEpoch:staged.device.epoch,graphRevision:"6",rosterRevision:"7", + errorCode:"NONE"}),true); + const lied=clone(staged); + lied.graph.revision="6"; // claimed graph revision, but fader still -6 dB + assert.equal(c.onSnapshot(lied),false); + assert.equal(c.state().current.graph.revision,"5"); + assert.deepEqual(visible,[-6]); + assert.equal(c.state().pending,null); + assert.equal(c.state().lastError,"ACK_READBACK_EFFECT_MISMATCH"); + assert.equal(sent.at(-1).name,"arMixConsoleSubscribe"); +}); + +test("staged PCM PAN/MUTE checks real native controls and rejects wrong readback",()=>{ + const s=acceptedFixture();s.productionCallbackLive=false; + const c=protocol.createController({emit:()=>{}}); + c.onSnapshot(s); + const pan=c.intent("SET_PAN","9007199254740993",{value:0.5}); + assert.equal(pan.ok,false,"never advertise an uninstalled operation"); + s.graph.capabilities.supportedOps.push("SET_PAN"); + const d=protocol.createController({emit:()=>{}}); + d.onSnapshot(s); + const p=d.intent("SET_PAN","9007199254740993",{value:0.5}); + assert.equal(p.ok,true); + assert.equal(d.onAck({requestId:p.requestId,status:"ACCEPTED", + deviceEpoch:s.device.epoch,graphRevision:"5",rosterRevision:"7",errorCode:"NONE"}),true); + const updated=clone(s);updated.graph.channels[0].controls.pan=0.5; + assert.equal(d.onSnapshot(updated),true); + assert.equal(d.state().current.graph.channels[0].controls.pan,0.5); + const m=d.intent("SET_MUTE","9007199254740993",{value:true}); + assert.equal(m.ok,true); + assert.equal(d.onAck({requestId:m.requestId,status:"ACCEPTED", + deviceEpoch:s.device.epoch,graphRevision:"5",rosterRevision:"7",errorCode:"NONE"}),true); + const mute=clone(updated);mute.graph.channels[0].controls.mute=true; + assert.equal(d.onSnapshot(mute),true); + assert.equal(d.state().current.graph.channels[0].controls.mute,true); +}); + +test("WIRE REMOVE requires actual native EdgeId absent from later accepted graph",()=>{ + const s=acceptedFixture();s.productionCallbackLive=false; + const source="9007199254740993",edge="9223372036854775808"; + const sent=[]; + const c=protocol.createController({emit:(n,p)=>sent.push({n,p})}); + c.onSnapshot(s); + const removed=c.intent("APPLY_WIRE_TRANSACTION",source, + {changes:[{type:"REMOVE",sourceId:source,edgeId:edge}]}); + assert.equal(removed.ok,true); + assert.equal(c.onAck({requestId:removed.requestId,status:"ACCEPTED", + deviceEpoch:s.device.epoch,graphRevision:"6",rosterRevision:"7",errorCode:"NONE"}),true); + const before=clone(s);before.graph.revision="6"; + assert.equal(c.onSnapshot(before),false,"ACK with unchanged cable MUST NOT light a false connection"); + assert.equal(c.state().current.graph.edges.length,1); + assert.equal(c.state().lastError,"ACK_READBACK_EFFECT_MISMATCH"); + const verified=protocol.createController({emit:()=>{}}); + verified.onSnapshot(s); + const req=verified.intent("APPLY_WIRE_TRANSACTION",source, + {changes:[{type:"REMOVE",sourceId:source,edgeId:edge}]}); + verified.onAck({requestId:req.requestId,status:"ACCEPTED", + deviceEpoch:s.device.epoch,graphRevision:"6",rosterRevision:"7",errorCode:"NONE"}); + before.graph.edges=[]; + assert.equal(verified.onSnapshot(before),true); + assert.deepEqual(verified.state().current.graph.edges,[]); +}); + +test("native meter and PAN scale are driven by PCM readback, not Pages demo",()=>{ + const source=read("web/approved-native-bridge.js"); + assert.match(source,/paintNativeMeters\(next\)/); + assert.match(source,/displayMeterDbfs\(fill,/); + assert.match(source,/t\.pan=ch\.controls\.pan\*100/); + assert.match(source,/next\.productLive/); + assert.doesNotMatch(source,/Math\.sin\(/); +}); + test("SET_FADER: one exact string request, ACK then LATER same-revision native readback",()=>{ const sent=[],visible=[]; const c=protocol.createController({emit:(name,payload)=>sent.push({name,payload}),onAccepted:s=>visible.push(s.identity)}); From 0659f6998b78f703ab455bba0c895ad545d85d15 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 02:22:25 +0700 Subject: [PATCH 27/29] M2 release guard: verify real CMake /preview/ bundle and transport assets on Windows CI --- .github/workflows/p1-windows.yml | 2 + scripts/check_approved_native_gui_release.mjs | 127 +++++++++++------- 2 files changed, 81 insertions(+), 48 deletions(-) diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index b40e86125..871c4955a 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -132,6 +132,8 @@ jobs: -DJUCE_ROOT="${{ github.workspace }}/third_party/JUCE" -DBUILD_TESTING=ON -DJUCE_WEBVIEW2_PACKAGE_LOCATION="${{ github.workspace }}/.deps" + - name: Verify exact ONE approved /preview/ GUI CMake bundle + run: node scripts/check_approved_native_gui_release.mjs --source-only --bundle build/approved_gui - name: Build executable and native RT tests run: cmake --build build --config Release --target ARMixConsole ARMixFactoryFxRegistryTests ARMixFxOrderTests ARMixFxStructuralHandoffTests ARMixMixerRoutingTests ARMixChannelRoutingContractTests ARMixChannelSendTests ARMixPreparedMixerBlockTests ARMixLiveRoutingEpochTests ARMixJucePortMaskTests ARMixNativeMixerSessionTests ARMixNativeDrySendTests ARMixLiveChannelFxTests ARMixDedicatedAuxBusTests ARMixTenChannelLiveControlTests ARMixWorkspaceTests ARMixVaultTests ARMixBackupTests ARMixOrbitPhaseTests ARMixOrbitControlTests ARMixOrbitMotionTests ARMixOrbitDistanceTests ARMixFxBypassEnvelopeTests ARMixDearVrPolarPolicyTests ARMixRTTests ARMixPresetTests ARMixShowSchemaTests ARMixShowStoreTests ARMixLiveShowCaptureTests ARMixNativeMasterLoudnessTests ARMixDiagnosticTests ARMixClockBridgeTests ARMixVirtualClockSoakTests ARMixCadenceTests ARMixCaptureBoundaryTests ARMixCrackleWindowTests ARMixHealthTests ARMixPolicyTests ARMixPeriodEvidenceTests ARMixLifecycleTests ARMixWasapiProbeTests ARMixDualJuceTests ARMixClockSizingTests ARMixIndependentFormatTests ARMixRecoveryTests ARMixStreamWatchdogTests ARMixBridgeContinuityTests ARMixEndpointPolicyTests ARMixEndpointGuardTests ARMixAsioPolicyTests ARMixAsioBackendTests ARMixAsioRegistryIdentityTests ARMixDirectFenceTests --parallel 2 - name: Test realtime control primitives diff --git a/scripts/check_approved_native_gui_release.mjs b/scripts/check_approved_native_gui_release.mjs index 6eb4b0348..1e6398f7c 100644 --- a/scripts/check_approved_native_gui_release.mjs +++ b/scripts/check_approved_native_gui_release.mjs @@ -1,53 +1,84 @@ // SPDX-License-Identifier: AGPL-3.0-only -// Native RELEASE gate: user-approved /preview/ is the ONLY allowable Windows GUI. -// Necessary static provenance, NOT proof of rendered EXE screenshots or PCM FAT. +// ONE approved /preview/ Windows WebView2 resource bundle, not an old +// web/approved-preview staging fiction. Source proof != product PCM/hardware FAT. import {readFileSync, existsSync} from 'node:fs'; -import {resolve} from 'node:path'; +import {resolve, join, sep} from 'node:path'; import {createHash} from 'node:crypto'; +import {spawnSync} from 'node:child_process'; + const root=resolve('.'); -const abs=p=>resolve(root,p); -const exists=p=>existsSync(abs(p)); -const read=p=>readFileSync(abs(p)); -const digest=b=>createHash('sha256').update(b).digest('hex'); -const fail=s=>{console.error('RELEASE BLOCKED — approved /preview/ GUI: '+s);process.exitCode=1;}; -const entry='web/approved-preview/index.html'; -const manifest='web/approved-preview/native-manifest.json'; -const source='site/preview-v2/index.html'; // INTERNAL HTML seed, NOT /preview-v2/ product -const buttons='site/preview-buttons/assets/'; -if(!exists(entry)||!exists(manifest)){ - fail('Windows approved GUI bundle missing. Generate the exact /preview/ assembled HTML, CSS/JS/PNG, then embed it into JUCE.'); - process.exit(1); +const argv=process.argv.slice(2); +const value=flag=>{ + const at=argv.indexOf(flag); + return at<0?null:argv[at+1] || null; +}; +const sourceOnly=argv.includes('--source-only'); +const release=argv.includes('--release'); +const bundle=resolve(value('--bundle') || process.env.ARMIX_NATIVE_GUI_BUNDLE || 'build/approved_gui'); +const read=path=>readFileSync(path); +const sha=bytes=>createHash('sha256').update(bytes).digest('hex'); +const block=reason=>{throw Error('APPROVED /preview/ native bundle BLOCKED: '+reason);}; +const requireFile=(path,why)=>{ + if(!existsSync(path))block(why+': '+path); + return read(path); +}; +try { + if(!sourceOnly&&!release)block('Pass --source-only or --release explicitly'); + const manifestPath=join(bundle,'approved-gui-manifest.json'); + const manifest=JSON.parse(requireFile(manifestPath,'Missing actual CMake-generated manifest').toString('utf8')); + if(manifest.schema!=='arsonmix.approved-native-pages-bundle.v2' || + manifest.authoritativePagesRoute!=='/preview/' || + manifest.authoritativePagesOutput!=='preview/index.html') + block('Wrong public GUI identity/manifest schema'); + const html=requireFile(join(bundle,'index.html'),'Missing native Pages entry'); + if(sha(html)!==manifest.nativeHtmlSha256)block('Approved native HTML hash mismatch'); + if(!Array.isArray(manifest.files)||manifest.files.length<4) + block('Native BinaryData resource inventory incomplete'); + const paths=new Set(); + for(const item of manifest.files) { + if(typeof item.path!=='string' || !/^[a-zA-Z0-9_./-]+$/.test(item.path) || + item.path.startsWith('/') || item.path.split('/').includes('..') || + paths.has(item.path)) + block('Unexpected, repeated, or unsafe resource path'); + paths.add(item.path); + const resolved=resolve(bundle,item.path); + if(!resolved.startsWith(bundle+sep))block('Resource escapes approved bundle'); + if(sha(requireFile(resolved,'Missing approved native resource'))!==item.sha256) + block('Native resource hash mismatch: '+item.path); + } + for(const name of ['index.html','assets/approved-native-contract.js', + 'assets/approved-native-bridge.js', + 'assets/mixer-control-keys.css', + 'assets/mixer-control-keys.js', + 'assets/mute-solo-pfl-56x37.png','assets/mixer-wire-dots.css']) + if(!paths.has(name))block('Mandatory approved GUI/V8 transport resource missing: '+name); + const cmake=requireFile(join(root,'CMakeLists.txt'),'Missing native CMake').toString('utf8'); + const host=requireFile(join(root,'src/Main.cpp'),'Missing JUCE host').toString('utf8'); + if(!cmake.includes('scripts/build_approved_native_gui.py') || + !cmake.includes('ARMIX_APPROVED_GUI_DIR') || + !cmake.includes('juce_add_binary_data(ARMixAssets SOURCES')) + block('JUCE BinaryData does not use approved Pages source generator'); + if(!host.includes('resolveApprovedGuiResource') || + !host.includes('withResourceProvider (assetFor)')) + block('JUCE WebView ResourceProvider does not serve approved Pages assets'); + if(/juce_add_binary_data\(ARMixAssets SOURCES\s*web\//.test(cmake) || + host.includes('BinaryData::consolenative_html')) + block('Forbidden alternative GUI compiled in Windows executable'); + const py=process.env.PYTHON || 'python'; + const result=spawnSync(py,['scripts/build_approved_native_gui.py', + '--out',bundle,'--verify'],{cwd:root,encoding:'utf8',timeout:60000}); + if(result.error || result.status!==0) + block('Pages→native byte-for-byte regeneration failed: '+ + String(result.error?.message||result.stderr||result.stdout).slice(0,700)); + if(release && + host.includes('native_console_m2::reject (args, accepted)') && + !host.includes('consoleBridge_.processNativeBusIntent')) + block('G0 rejects all PCM/WIRE operations; ENGINE #266 + native FAT not yet installed'); + // This gate proves the CMake bundle; it cannot replace the separate exact + // Windows executable screenshot, PCM/VST3, or ASIO/WASAPI hardware FAT gate. + console.log('PASS: exact /preview/ GUI CMake resources, native v8 bridge and SHA256 manifest'); + console.log('NOT hardware/PCM FAT — product promotion still requires #270 and #15 evidence'); +} catch(error) { + console.error(error.message); + process.exitCode=1; } -let m;try{m=JSON.parse(read(manifest).toString('utf8'));}catch(e){fail('Invalid manifest: '+e.message);process.exit(1);} -if(m.canonicalUrl!=='https://masarray.github.io/arsonmix/preview/'||m.nativeEntrypoint!==entry)fail('Canonical GUI identity is NOT /preview/'); -if(m.entrySha256!==digest(read(entry)))fail('Native approved HTML digest mismatch'); -const sourceHtml=read(source).toString('utf8'); -let expected=sourceHtml; -for(const name of ['mixer-control-keys.css','mixer-control-keys.js']){ - const key=buttons+name; - if(!exists(key)){fail('Missing approved PNG button asset '+key);continue;} - const rev=digest(read(key)).slice(0,16); - const token='assets/'+name; - const pattern=name.endsWith('.css') ? /assets\/mixer-control-keys\.css(?:\?[^"'\s>]*)?/g : /assets\/mixer-control-keys\.js(?:\?[^"'\s>]*)?/g; - const matches=[...expected.matchAll(pattern)]; - if(matches.length!==1)fail('Expected exactly one PNG-button source reference '+name); - expected=expected.replace(pattern,token+'?rev='+rev); -} -if(read(entry).toString('utf8')!==expected)fail('Native HTML does not match EXACT approved /preview/ assembly'); -const linked=[...new Set([...sourceHtml.matchAll(/(?:src|href)=["'](assets\/[^"'?]+)(?:\?[^"']*)?["']/g)].map(v=>v[1]))]; -for(const rel of linked){ - const name=rel.slice('assets/'.length); - const sourceAsset=['mixer-control-keys.css','mixer-control-keys.js','mute-solo-pfl-56x37.png'].includes(name)?buttons+name:'site/preview-v2/'+rel; - const nativeAsset='web/approved-preview/'+rel; - if(!exists(sourceAsset)||!exists(nativeAsset)||digest(read(sourceAsset))!==digest(read(nativeAsset)))fail('Native CSS/JS/art missing/changed: '+rel); -} -for(const name of ['mute-solo-pfl-56x37.png','mixer-wire-dots.css','knob-ICON.svg']){ - const ref=name==='mute-solo-pfl-56x37.png'?buttons+name:'site/preview-v2/assets/'+name; - const native='web/approved-preview/assets/'+name; - if(!exists(native)||!exists(ref)||digest(read(native))!==digest(read(ref)))fail('Mandatory GUI art mismatch: '+name); -} -const cmake=read('CMakeLists.txt').toString('utf8'),host=read('src/Main.cpp').toString('utf8'); -if(!cmake.includes(entry)||!cmake.includes('web/approved-preview/assets/'))fail('CMake BinaryData not built from approved /preview/ GUI and assets'); -if(!/approved-preview|approvedPreview/i.test(host))fail('JUCE ResourceProvider not serving approved /preview/ GUI'); -if(cmake.includes('web/console-native.html')||cmake.includes('web/index.html'))fail('Compiled alternate native/legacy HTML renderer'); -if(!process.exitCode)console.log('APPROVED /preview/ static source/asset+JUCE contract PASS (actual Windows GUI/PCM FAT still required)'); From 6118310253de3f7c19c423c890d75bb0645c9109 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 02:25:53 +0700 Subject: [PATCH 28/29] M2: encode WIRE intents to real ENGINE C2 op/from/to/EdgeId ABI and verify accepted route readback --- tests/approved_native_m2_contract.test.cjs | 8 +++--- web/approved-native-bridge.js | 31 +++++++++++++++++----- web/approved-native-contract.js | 25 ++++++++--------- 3 files changed, 41 insertions(+), 23 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 9df8999cd..ed625a91c 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -128,7 +128,7 @@ test("WIRE REMOVE requires actual native EdgeId absent from later accepted graph const c=protocol.createController({emit:(n,p)=>sent.push({n,p})}); c.onSnapshot(s); const removed=c.intent("APPLY_WIRE_TRANSACTION",source, - {changes:[{type:"REMOVE",sourceId:source,edgeId:edge}]}); + {changes:[{op:"REMOVE",from:source,edgeId:edge}]}); assert.equal(removed.ok,true); assert.equal(c.onAck({requestId:removed.requestId,status:"ACCEPTED", deviceEpoch:s.device.epoch,graphRevision:"6",rosterRevision:"7",errorCode:"NONE"}),true); @@ -139,7 +139,7 @@ test("WIRE REMOVE requires actual native EdgeId absent from later accepted graph const verified=protocol.createController({emit:()=>{}}); verified.onSnapshot(s); const req=verified.intent("APPLY_WIRE_TRANSACTION",source, - {changes:[{type:"REMOVE",sourceId:source,edgeId:edge}]}); + {changes:[{op:"REMOVE",from:source,edgeId:edge}]}); verified.onAck({requestId:req.requestId,status:"ACCEPTED", deviceEpoch:s.device.epoch,graphRevision:"6",rosterRevision:"7",errorCode:"NONE"}); before.graph.edges=[]; @@ -152,7 +152,9 @@ test("native meter and PAN scale are driven by PCM readback, not Pages demo",()= assert.match(source,/paintNativeMeters\(next\)/); assert.match(source,/displayMeterDbfs\(fill,/); assert.match(source,/t\.pan=ch\.controls\.pan\*100/); - assert.match(source,/next\.productLive/); + assert.match(source,/next\\.productLive/); + assert.match(source,/op:op\\.type,from:sourceId/); + assert.doesNotMatch(source,/changes\\.push\\(\\{type:op\\.type,sourceId/); assert.doesNotMatch(source,/Math\.sin\(/); }); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 1e2891e89..3e4e79617 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -243,13 +243,32 @@ (op.edgeId!==undefined&&!edgeId)) { status("NATIVE: WIRE mapped identity missing; no mutation");return true; } - changes.push({type:op.type,sourceId,...(destId?{destId}:{}), - ...(edgeId?{edgeId}:{}), - ...(op.mode?{mode:op.mode}:{}), - ...(op.levelDb!==undefined?{levelDb:op.levelDb}:{})}); + // ENGINE #266's real PCM decoder consumes op/from/to/edgeId, + // NOT the Pages reducer's type/sourceId/destId. Never feed it + // an unrecognized demo command or an unbound EdgeId. + if (!["CONNECT","REMOVE","RETARGET","ROUTE_ONLY"].includes(op.type) || + (op.mode && !["send","postFader","routeOnly"].includes(op.mode))) { + status("NATIVE: WIRE "+op.type+" needs real engine capability; unchanged"); + return true; + } + const change={op:op.type,from:sourceId}; + if (destId)change.to=destId; + if (edgeId)change.edgeId=edgeId; + if (op.type==="CONNECT" || op.type==="ROUTE_ONLY") { + change.tap="POST_FADER"; + change.gainLinear=op.levelDb===undefined?1: + Math.pow(10,Math.max(-60,Math.min(6,Number(op.levelDb)))/20); + } + changes.push(change); + } + const source=changes[0]?.from; + if (!source || changes.some(change=>change.from!==source)) { + status("NATIVE: multi-source transaction requires native batch admission"); + return true; } - const source=changes[0]?.sourceId; - controller.intent("APPLY_WIRE_TRANSACTION",source,{changes}); + const accepted=controller.intent("APPLY_WIRE_TRANSACTION",source,{changes}); + if (!accepted.ok)status("NATIVE: "+accepted.error+"; WIRE unchanged"); + else window.setTimeout(()=>controller?.expire(accepted.requestId),8000); return true; }, consumeUndo() {if (!connected)return false;status("NATIVE: WIRE undo requires accepted native transaction");return true;}, diff --git a/web/approved-native-contract.js b/web/approved-native-contract.js index 2fa1eb97b..6837e91b2 100644 --- a/web/approved-native-contract.js +++ b/web/approved-native-contract.js @@ -122,22 +122,19 @@ if (cmp(next.graph.revision,pending.baseGraphRevision)<=0) return false; const edges=next.graph.edges.filter(e=>e.enabled); return payload.changes.every(edit=>{ - if (!object(edit) || decimal(edit.sourceId)===null) return false; - if (edit.type==="REMOVE" || edit.type==="DISCONNECT") + if (!object(edit) || decimal(edit.from)===null || + edit.from!==targetChannelId) return false; + if (edit.op==="REMOVE") return decimal(edit.edgeId)!==null && !edges.some(e=>e.edgeId===edit.edgeId); - if (edit.type==="CONNECT" || edit.type==="ROUTE_ONLY") - return decimal(edit.destId)!==null && - edges.some(e=>e.from===edit.sourceId&&e.to===edit.destId); - if (edit.type==="REPLUG") - return decimal(edit.edgeId)!==null && decimal(edit.destId)!==null && - edges.some(e=>e.edgeId===edit.edgeId&&e.from===edit.sourceId&&e.to===edit.destId); - if (edit.type==="GAIN") - return decimal(edit.edgeId)!==null && Number.isFinite(edit.levelDb) && - edges.some(e=>e.edgeId===edit.edgeId&&e.from===edit.sourceId&& - Math.abs((e.gainLinear>0?20*Math.log10(e.gainLinear):-60)-edit.levelDb)<=0.21); - // MODE and other operations require a native readback verifier before - // they can be advertised as effective by this consumer. + if (edit.op==="CONNECT" || edit.op==="ROUTE_ONLY") + return decimal(edit.to)!==null && + edges.some(e=>e.from===edit.from&&e.to===edit.to); + if (edit.op==="RETARGET") + return decimal(edit.edgeId)!==null && decimal(edit.to)!==null && + edges.some(e=>e.edgeId===edit.edgeId&&e.from===edit.from&&e.to===edit.to); + // Gain/tap controls remain unsupported by ENGINE #266's native + // transaction decoder. Never announce an applied JS-only edit. return false; }); } From 896aa6f1a8a8f2688efa60ead39c7d748aaad46a Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 02:27:38 +0700 Subject: [PATCH 29/29] M2 CI: fix JS test syntax for native wire payload ABI assertions --- tests/approved_native_m2_contract.test.cjs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index ed625a91c..4541898b0 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -152,9 +152,9 @@ test("native meter and PAN scale are driven by PCM readback, not Pages demo",()= assert.match(source,/paintNativeMeters\(next\)/); assert.match(source,/displayMeterDbfs\(fill,/); assert.match(source,/t\.pan=ch\.controls\.pan\*100/); - assert.match(source,/next\\.productLive/); - assert.match(source,/op:op\\.type,from:sourceId/); - assert.doesNotMatch(source,/changes\\.push\\(\\{type:op\\.type,sourceId/); + assert.ok(source.includes("next.productLive")); + assert.ok(source.includes("op:op.type,from:sourceId")); + assert.ok(!source.includes("changes.push({type:op.type,sourceId")); assert.doesNotMatch(source,/Math\.sin\(/); });