diff --git a/CMakeLists.txt b/CMakeLists.txt index d97d5e1f4..e9ce7939d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -104,6 +104,14 @@ if(BUILD_TESTING) add_test(NAME ConsoleV6NativeAcceptedSnapshotAndGoldenPCM COMMAND ARMixConsoleBridgeV6Tests) # Existing Windows build target pulls in this test without a second workflow. add_dependencies(ARMixMixerRoutingTests ARMixConsoleBridgeV6Tests) + # M3-B INTEGRATOR-only readback serialization of real ChannelId PCM. + # Never installs a second callback, renderer or fake live source. + juce_add_console_app(ARMixNativeV8ProjectionTests PRODUCT_NAME "ArSonMix Native V8 Readback Projection Tests") + target_sources(ARMixNativeV8ProjectionTests PRIVATE tests/approved_native_v8_projection_test.cpp integration/ApprovedNativeV8Projection.h integration/ApprovedNativeControlIntent.h integration/ApprovedNativeRuntimeSnapshot.h) + target_link_libraries(ARMixNativeV8ProjectionTests PRIVATE juce::juce_core juce::juce_recommended_config_flags) + target_compile_features(ARMixNativeV8ProjectionTests PRIVATE cxx_std_20) + add_test(NAME M3BNativeV8StableIdReadbackAndFailClosedProjection COMMAND ARMixNativeV8ProjectionTests) + add_dependencies(ARMixMixerRoutingTests ARMixNativeV8ProjectionTests) add_executable(ARMixChannelRoutingContractTests tests/channel_routing_contract_test.cpp) target_compile_features(ARMixChannelRoutingContractTests PRIVATE cxx_std_20) add_test(NAME MonoStereoSparsePhysicalPortRouting COMMAND ARMixChannelRoutingContractTests) diff --git a/integration/ApprovedNativeControlIntent.h b/integration/ApprovedNativeControlIntent.h new file mode 100644 index 000000000..29e049293 --- /dev/null +++ b/integration/ApprovedNativeControlIntent.h @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "ApprovedNativeV8Projection.h" +#include +#include +#include +#include +#include + +// INTEGRATOR M3-B: bridge the approved /preview/ control ABI to the ONE +// native ChannelId PCM owner from ENGINE #266. Translation is CONTROL-thread +// only and has NO side effects. It does not install, drive or claim audio. +// Real JUCE nativeBus/callback admission and genuine mutating operation +// support must be independently established by the producer before use. +// +// The public UI submits SET_FADER/PAN/MUTE/SOLO; native PCM currently uses +// NATIVE_SET_CHANNEL_MIX / NATIVE_SET_CHANNEL_MUTE_SOLO / NATIVE_SET_BUS_MIX. +// This translator NEVER fabricates capability support or stable ChannelIds. +namespace armix::console { +struct ApprovedNativeControlIntent { + juce::var translated; + juce::String error; + bool ok() const noexcept { return translated.isObject() && error.isEmpty(); } +}; + +inline bool approvedHasOperation(const juce::var& list,const char* name) { + const auto* values=list.getArray(); + return values && values->contains(juce::var(juce::String(name))); +} + +inline ApprovedNativeControlIntent translateApprovedNativeControl( + const juce::var& publicIntent, + const juce::var& acceptedSnapshot, + const juce::var& installedBus) { + const auto reject=[](const char* code)->ApprovedNativeControlIntent { + return {{},juce::String(code)}; + }; + if(!publicIntent.isObject() || !acceptedSnapshot.isObject() || + !installedBus.isObject())return reject("NATIVE_READBACK_UNAVAILABLE"); + const auto device=acceptedSnapshot.getProperty("device",{}); + const auto graph=acceptedSnapshot.getProperty("graph",{}); + const auto caps=graph.getProperty("capabilities",{}); + const auto rows=graph.getProperty("channels",{}); + const auto nativeRows=installedBus.getProperty("channels",{}); + const auto& ids=publicIntent.getProperty("targetChannelId",{}); + const auto& request=publicIntent.getProperty("requestId",{}); + const auto op=publicIntent.getProperty("operation",{}).toString(); + const auto epoch=device.getProperty("epoch",{}); + const auto revision=graph.getProperty("revision",{}); + const auto roster=graph.getProperty("rosterRevision",{}); + if(!device.isObject() || !graph.isObject() || !caps.isObject() || + !rows.isArray() || !nativeRows.isArray() || + !static_cast(caps.getProperty("callbackOwnsChannelIds",false)) || + !nativeV8Decimal(epoch) || epoch.toString()=="0" || + !nativeV8Decimal(revision) || revision.toString()=="0" || + !nativeV8Decimal(roster) || roster.toString()=="0" || + !nativeV8Decimal(ids) || ids.toString()=="0") + return reject("CHANNELID_CALLBACK_NOT_ADMITTED"); + // Reject cross-device / cross-graph commands BEFORE any conversion. + if(publicIntent.getProperty("deviceEpoch",{}).toString()!=epoch.toString() || + publicIntent.getProperty("baseGraphRevision",{}).toString()!=revision.toString() || + publicIntent.getProperty("baseRosterRevision",{}).toString()!=roster.toString() || + installedBus.getProperty("graphRevision",{}).toString()!=revision.toString() || + installedBus.getProperty("rosterRevision",{}).toString()!=roster.toString()) + return reject("STALE_NATIVE_CONTROL_REVISION"); + if(!request.isString() || request.toString().isEmpty() || + request.toString().length()>128)return reject("INVALID_REQUEST_ID"); + if(op!="SET_FADER" && op!="SET_PAN" && op!="SET_MUTE" && + op!="SET_SOLO")return reject("UNSUPPORTED_APPROVED_CONTROL"); + // Both native *and* GUI-side capabilities must be explicitly advertised + // from real installed PCM. Native ops alone do not prove that legacy M4 + // ChannelIds (especially original CH1-10) support these controls. + if(!approvedHasOperation(caps.getProperty("supportedOps",{}), + op.toRawUTF8())) + return reject("PUBLIC_CONTROL_NOT_ADMITTED"); + juce::var channel,producer; + for(const auto& item:*rows.getArray()) + if(item.getProperty("id","").toString()==ids.toString()) { + if(channel.isObject())return reject("DUPLICATE_APPROVED_CHANNEL"); + channel=item; + } + for(const auto& item:*nativeRows.getArray()) + if(item.getProperty("id","").toString()==ids.toString()) { + if(producer.isObject())return reject("DUPLICATE_NATIVE_CHANNEL"); + producer=item; + } + if(!channel.isObject() || !producer.isObject()) + return reject("UNKNOWN_OR_STALE_CHANNELID"); + const auto role=channel.getProperty("role","").toString(); + if(role!=producer.getProperty("role","").toString()) + return reject("NATIVE_ROLE_MISMATCH"); + const bool input=role=="INPUT"; + const bool bus=role=="GROUP" || role=="FX_RETURN"; + if(!input && !bus)return reject("CHANNEL_ROLE_NOT_MUTABLE"); + if(bus && (op=="SET_MUTE" || op=="SET_SOLO")) + return reject("BUS_MUTE_SOLO_NOT_ADMITTED"); + const auto controls=channel.getProperty("controls",{}); + if(!controls.isObject())return reject("INVALID_NATIVE_CONTROLS"); + const auto fader=controls.getProperty("faderDb",{}); + const auto pan=controls.getProperty("pan",{}); + const auto mute=controls.getProperty("mute",{}); + const auto solo=controls.getProperty("solo",{}); + double acceptedDb=0.,acceptedPan=0.,nativeGain=0.,nativePan=0.; + if(!nativeV8Number(fader,acceptedDb) || + !nativeV8Number(pan,acceptedPan) || + !nativeV8Number(producer.getProperty("fader",{}),nativeGain) || + !nativeV8Number(producer.getProperty("pan",{}),nativePan) || + !mute.isBool() || !solo.isBool() || + !producer.getProperty("mute",{}).isBool() || + !producer.getProperty("solo",{}).isBool() || + nativeGain<0. || nativeGain>4. || + std::abs(nativePan-acceptedPan)>0.015 || + static_cast(mute)!=static_cast( + producer.getProperty("mute",{})) || + static_cast(solo)!=static_cast( + producer.getProperty("solo",{}))) + return reject("NATIVE_CONTROL_READBACK_MISMATCH"); + const double nativeDb=nativeGain>0.?20.*std::log10(nativeGain):-60.; + if(std::abs(nativeDb-acceptedDb)>0.11) + return reject("STALE_NATIVE_CONTROL_READBACK"); + const auto payload=publicIntent.getProperty("payload",{}); + if(!payload.isObject())return reject("INVALID_CONTROL_PAYLOAD"); + const auto value=payload.getProperty( + op=="SET_FADER"?"valueDb":"value",{}); + const char* nativeOperation=nullptr; + auto translatedPayload=std::make_unique(); + if(op=="SET_FADER" || op=="SET_PAN") { + if(op=="SET_FADER") { + double requested=0.; + if(!nativeV8Number(value,requested) || + requested< -60. || requested>(bus?12.:10.)) + return reject("INVALID_FADER_VALUE"); + acceptedDb=requested; + } else { + double requested=0.; + if(!nativeV8Number(value,requested) || + requested< -1. || requested>1.) + return reject("INVALID_PAN_VALUE"); + acceptedPan=requested; + } + // PAN must not round-trip the companion fader through a clipped dB + // projection: an accepted -60 dB can represent 0.001 linear, not + // silence, and an upper-clamped +12 dB can represent gain 4.0. + // Keep the verified native linear gain byte-for-byte on PAN edits. + // Only an explicit SET_FADER request converts dB into new gain. + const double gain=op=="SET_PAN"?nativeGain: + (acceptedDb<= -60.?0.:std::pow(10.,acceptedDb/20.)); + if(!std::isfinite(gain) || gain>4.) + return reject("UNREPRESENTABLE_GAIN"); + nativeOperation=bus?"NATIVE_SET_BUS_MIX":"NATIVE_SET_CHANNEL_MIX"; + translatedPayload->setProperty("gain",gain); + translatedPayload->setProperty("pan",acceptedPan); + } else { + if(!value.isBool())return reject("INVALID_MUTE_SOLO_VALUE"); + nativeOperation="NATIVE_SET_CHANNEL_MUTE_SOLO"; + translatedPayload->setProperty("mute",op=="SET_MUTE"?value:mute); + translatedPayload->setProperty("solo",op=="SET_SOLO"?value:solo); + } + if(!approvedHasOperation(installedBus.getProperty("supportedOps",{}), + nativeOperation)) + return reject("NATIVE_PCM_OPERATION_NOT_ADMITTED"); + auto converted=std::make_unique(); + converted->setProperty("requestId",request); + converted->setProperty("deviceEpoch",epoch); + converted->setProperty("baseGraphRevision",revision); + converted->setProperty("baseRosterRevision",roster); + converted->setProperty("targetChannelId",ids); + converted->setProperty("operation",nativeOperation); + converted->setProperty("payload",juce::var(translatedPayload.release())); + return {juce::var(converted.release()),{}}; +} +} // namespace armix::console diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h new file mode 100644 index 000000000..b0c663162 --- /dev/null +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "ApprovedNativeV8Projection.h" +#include +#include + +// Sole JUCE MESSAGE-thread production readback for approved /preview/. +// Never creates a ChannelId bus, audio callback, synthetic device, or +// browser-owned PCM. ENGINE #266 reports nativeChannelIdPcmActive ONLY after +// its installed realtime callback owns the accepted publisher/epoch. +// G0/M4 and any forged nativeBus without that predicate MUST stay unadmitted. +namespace armix::console { +// Legacy M2 counted only device START callbacks; the actual routing epoch +// also advances on STOP. After ASIO/WASAPI re-open they can differ (e.g., +// G0 start=2 while accepted routing epoch=3). Always use the installed +// LiveDryRoutingLab epoch for both G0 and native accepted snapshots so a +// disconnected physical device cannot leave a stale accepted GUI LIVE. +// This remains a CONTROL-only metadata correction; never creates a graph. +inline bool synchronizeApprovedRouteDeviceEpoch( + juce::var& snapshot,const juce::var& live) +{ + if (!snapshot.isObject() || !live.isObject()) return false; + const auto device=snapshot.getProperty("device",{}); + const auto route=live.getProperty("dryRoutingLab",{}); + if (!device.isObject() || !route.isObject()) return false; + const auto generation=device.getProperty("epoch",{}); + const auto epoch=route.getProperty("epoch",{}); + if (!generation.isString() || + !(generation.toString()=="0" || nativeV8Decimal(generation)) || + !(epoch.isInt() || epoch.isInt64())) return false; + const auto actual=static_cast(epoch); + if(actual<0 || actualsetProperty("epoch",juce::String(actual)); + return true; +} + +inline bool projectInstalledNativeChannelIdGraph( + juce::var& snapshot, const juce::var& live) +{ + if (!snapshot.isObject() || !live.isObject()) return false; + const auto route=live.getProperty("dryRoutingLab",{}); + const auto device=snapshot.getProperty("device",{}); + if (!route.isObject() || !device.isObject()) return false; + const auto actualFlag=[&](const juce::var& source,const char* key) { + const auto value=source.getProperty(key,{}); + return value.isBool() && static_cast(value); + }; + const auto actualFalse=[&](const juce::var& source,const char* key) { + const auto value=source.getProperty(key,{}); + return value.isBool() && !static_cast(value); + }; + if (!actualFlag(live,"connected") || + !actualFlag(live,"directRouteAuthorized") || + !actualFalse(live,"adaptiveClockActive") || + !actualFlag(route,"ready") || + !actualFlag(route,"hasAcceptedRoute") || + !actualFlag(route,"nativeChannelIdPcmActive") || + !actualFalse(route,"topologyFault")) + return false; + const auto epoch=device.getProperty("epoch",{}); + const auto nativeEpoch=route.getProperty("epoch",{}); + if (!nativeV8Decimal(epoch) || epoch.toString()=="0" || + !(nativeEpoch.isInt() || nativeEpoch.isInt64()) || + static_cast(nativeEpoch)<=0 || + juce::String(static_cast(nativeEpoch))!=epoch.toString()) + return false; + const auto outputMask=device.getProperty("enabledOutputs",{}); + const auto inputMask=device.getProperty("enabledInputs",{}); + const auto rate=device.getProperty("sampleRate",{}); + const auto frames=device.getProperty("bufferFrames",{}); + double actualRate=0.,actualFrames=0.; + if (!outputMask.isArray() || !inputMask.isArray() || + outputMask.getArray()->size()<2 || inputMask.getArray()->isEmpty() || + !nativeV8Number(rate,actualRate) || + !nativeV8Number(frames,actualFrames) || + actualRate<8000. || actualRate>384000. || + actualFrames<16. || actualFrames>32768.) + return false; + const auto bus=route.getProperty("nativeBus",{}); + if (!bus.isObject()) return false; + // This function has no independent "true" argument. Callback admission + // comes from the verified installed ENGINE status above, not the caller. + if (!projectApprovedNativeV8(snapshot,bus,true)) + return false; + // Reading a PCM graph is not a mutating operation: Main.cpp still has a + // G0 reject handler. Until ENGINE/INTEGRATOR jointly install a real + // dispatcher and matching readback, advertise ZERO supported controls. + // In particular, projectApprovedNativeV8's generic WIRE structure alone + // must not enable WIRE intent before native transaction dispatch exists. + const auto graph=snapshot.getProperty("graph",{}); + const auto caps=graph.getProperty("capabilities",{}); + if (auto* props=caps.getDynamicObject()) + props->setProperty("supportedOps",juce::var(juce::Array{})); + // Full vendor/Show/physical FAT not done. Never promote product LIVE. + return true; +} +} // namespace armix::console diff --git a/integration/ApprovedNativeV8Projection.h b/integration/ApprovedNativeV8Projection.h new file mode 100644 index 000000000..a2f6b3ee1 --- /dev/null +++ b/integration/ApprovedNativeV8Projection.h @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include +#include +#include + +// Extracted from ENGINE #266 with explicit callback admission gate. +// Single JUCE CONTROL-thread adapter: installed PCM/ChannelId readback -> +// approved /preview/ public schema v8. No new renderer, callback or DSP. +namespace armix::console { +inline bool nativeV8Decimal(const juce::var& value) { + if(!value.isString())return false; + const auto s=value.toString().toStdString(); + if(s.empty()||s.size()>20||(s.size()>1&&s[0]=='0'))return false; + std::uint64_t n=0; + for(char c:s) { + if(c<'0'||c>'9')return false; + auto d=static_cast(c-'0'); + if(n>(std::numeric_limits::max()-d)/10)return false; + n=n*10+d; + } + return n!=0; +} +inline bool nativeV8Number(const juce::var& value,double& n) { + if(!value.isInt()&&!value.isInt64()&&!value.isDouble())return false; + n=static_cast(value); + return std::isfinite(n); +} +// A structurally correct bus is NOT proof that its IDs own the installed +// JUCE callback. The real PCM owner must explicitly admit the producer. +// G0 must pass false and keep the accepted GUI graph unmodified. +inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, + bool installedChannelIdCallbackAdmitted) { + if(!installedChannelIdCallbackAdmitted)return false; + const auto device=snapshot.getProperty("device",{}); + if(!nativeV8Decimal(device.getProperty("epoch",{})))return false; + const auto rawRows=bus.getProperty("channels",{}),rawEdges=bus.getProperty("edges",{}); + const auto* rows=rawRows.getArray();const auto* edges=rawEdges.getArray(); + const auto rev=bus.getProperty("graphRevision",{}),roster=bus.getProperty("rosterRevision",{}); + if(!rows||rows->isEmpty()||!edges||!nativeV8Decimal(rev)|| + !nativeV8Decimal(roster))return false; + juce::Array channels,wires,destinations; + std::unordered_set ids,edgeIds; + auto meters=std::make_unique(); + juce::String mainId; + for(const auto& row:*rows) { + const auto id=row.getProperty("id",{}),name=row.getProperty("name",{}); + const auto role=row.getProperty("role","").toString(); + const auto format=row.getProperty("format","").toString(); + const auto out=row.getProperty("primaryOutput",{}); + const auto fader=row.getProperty("fader",{}),pan=row.getProperty("pan",{}); + const auto mute=row.getProperty("mute",{}),solo=row.getProperty("solo",{}); + const auto inserts=row.getProperty("inserts",{}); + double linear=0.,p=0.; + if(!nativeV8Decimal(id)||!ids.insert(id.toString().toStdString()).second || + !name.isString()||name.toString().isEmpty()|| + (role!="INPUT"&&role!="GROUP"&&role!="FX_RETURN"&&role!="MAIN"&&role!="MONITOR")|| + (format!="MONO"&&format!="STEREO")|| + !out.isString()||!nativeV8Number(fader,linear)|| + !nativeV8Number(pan,p)||linear<0.||linear>4.||p< -1.||p>1.|| + !mute.isBool()||!solo.isBool()||!inserts.isArray())return false; + if(role=="MAIN"){if(mainId.isNotEmpty())return false;mainId=id.toString();} + auto ch=std::make_unique(); + ch->setProperty("id",id);ch->setProperty("name",name); + ch->setProperty("role",role);ch->setProperty("processingFormat",format); + if(out.toString()!="0") { + if(!nativeV8Decimal(out)||out.toString()==id.toString())return false; + ch->setProperty("primaryOutId",out); + } + const auto source=row.getProperty("source",{}); + if(source.isObject())ch->setProperty("source",source); + auto controls=std::make_unique(); + const double db=linear>0.?20.*std::log10(linear):-60.; + controls->setProperty("faderDb",juce::jlimit(-60.,12.,db)); + controls->setProperty("pan",p); + controls->setProperty("mute",mute);controls->setProperty("solo",solo); + ch->setProperty("controls",juce::var(controls.release())); + juce::Array fx; + for(const auto& item:*inserts.getArray()){ + const auto token=item.getProperty("instanceId",{}),label=item.getProperty("name",{}); + const auto bypass=item.getProperty("bypassed",{}); + if(!token.isString()||!label.isString()||!bypass.isBool())return false; + auto insert=std::make_unique(); + insert->setProperty("id",token);insert->setProperty("name",label); + insert->setProperty("bypassed",bypass); + fx.add(juce::var(insert.release())); + } + ch->setProperty("inserts",juce::var(fx)); + ch->setProperty("sends",juce::var(juce::Array{})); + if(role!="INPUT"){ + auto dst=std::make_unique(); + dst->setProperty("id",id);dst->setProperty("name",name); + dst->setProperty("role",role); + destinations.add(juce::var(dst.release())); + } + double left=0.,right=0.; + if(nativeV8Number(row.getProperty("peakL",{}),left) && + nativeV8Number(row.getProperty("peakR",{}),right) && + left>=0.&&right>=0.){ + auto peak=std::make_unique(); + peak->setProperty("peakL",left);peak->setProperty("peakR",right); + meters->setProperty(juce::Identifier(id.toString()),juce::var(peak.release())); + } + channels.add(juce::var(ch.release())); + } + if(mainId.isEmpty())return false; + for(const auto& channel:channels) { + const auto out=channel.getProperty("primaryOutId",{}); + if(out.isString()&&!ids.count(out.toString().toStdString()))return false; + } + for(const auto& edge:*edges) { + const auto id=edge.getProperty("edgeId",{}),from=edge.getProperty("from",{}), + to=edge.getProperty("to",{}),gain=edge.getProperty("gainLinear",{}); + const auto tap=edge.getProperty("tap","").toString(); + const auto primary=edge.getProperty("primaryOutput",{}); + double linear=0.; + if(!nativeV8Decimal(id)||!nativeV8Decimal(from)||!nativeV8Decimal(to)|| + from.toString()==to.toString()|| + !edgeIds.insert(id.toString().toStdString()).second|| + !ids.count(from.toString().toStdString())|| + !ids.count(to.toString().toStdString())|| + from.toString()==mainId||(tap!="PRE_FADER"&&tap!="POST_FADER")|| + !nativeV8Number(gain,linear)||linear<0.||linear>4.|| + !primary.isBool())return false; + auto w=std::make_unique(); + w->setProperty("edgeId",id);w->setProperty("from",from);w->setProperty("to",to); + w->setProperty("tap",tap);w->setProperty("gainLinear",linear); + w->setProperty("primaryOutput",primary); + w->setProperty("enabled",true);w->setProperty("signalKind","AUDIO"); + wires.add(juce::var(w.release())); + if(!static_cast(primary))for(auto& channel:channels) { + if(channel.getProperty("id","").toString()!=from.toString())continue; + auto send=std::make_unique(); + send->setProperty("id",id);send->setProperty("targetId",to); + send->setProperty("tap",tap);send->setProperty("gainLinear",linear); + const auto list=channel.getProperty("sends",{}); + if(auto* a=list.getArray())a->add(juce::var(send.release())); + break; + } + } + const auto graph=snapshot.getProperty("graph",{}); + const auto telemetry=snapshot.getProperty("telemetry",{}); + auto* g=graph.getDynamicObject();auto* t=telemetry.getDynamicObject(); + if(!g||!t||!graph.getProperty("capabilities",{}).isObject())return false; + // All validation completed before anything becomes authoritative. + g->setProperty("revision",rev);g->setProperty("rosterRevision",roster); + g->setProperty("mainChannelId",mainId); + g->setProperty("channels",juce::var(channels)); + g->setProperty("destinations",juce::var(destinations)); + g->setProperty("edges",juce::var(wires)); + if(auto* caps=graph.getProperty("capabilities",{}).getDynamicObject()){ + caps->setProperty("callbackOwnsChannelIds",true); + juce::Array ops;ops.add("APPLY_WIRE_TRANSACTION"); + caps->setProperty("supportedOps",juce::var(ops)); + } + t->setProperty("channelMeterRmsPeak",juce::var(meters.release())); + // productionCallbackLive deliberately stays FALSE until full FAT. + return true; +} +} // namespace armix::console diff --git a/integration/console-v6/m4-operator-routing.mjs b/integration/console-v6/m4-operator-routing.mjs index 31c17db9e..d841e0ff7 100644 --- a/integration/console-v6/m4-operator-routing.mjs +++ b/integration/console-v6/m4-operator-routing.mjs @@ -49,7 +49,8 @@ function admittedView(accepted){ if(!object(e)||!id(e.edgeId)||edgeIds.has(e.edgeId)|| !id(e.from)||!id(e.to)||!channels.has(e.from)||!channels.has(e.to)|| e.from===e.to||e.from===main||e.signalKind!=='AUDIO'|| - e.enabled!==true||typeof e.primaryOutput!=='boolean'|| + e.enabled!==true|| + (e.primaryOutput!==undefined&&typeof e.primaryOutput!=='boolean')|| !safeGain(e.gainLinear)) return fail('INVALID_NATIVE_AUDIO_EDGE'); edgeIds.add(e.edgeId);edges.push(e);arcs.get(e.from).push(e.to); @@ -65,10 +66,30 @@ function admittedView(accepted){ } return false; }; + // v8 canonical primary OUT belongs to the CHANNEL (primaryOutId). + // An edge.primaryOutput flag is permitted but not required by the public + // ABI. Resolve its identity exactly once, and reject contradictions or + // ambiguous duplicate edges instead of guessing where the dry path goes. + const primaryEdges=new Set(); + for(const ch of channels.values()){ + const explicit=edges.filter(e=>e.from===ch.id&&e.primaryOutput===true); + if(explicit.length>1)return fail('MULTIPLE_ACCEPTED_PRIMARY_OUTPUTS'); + if(ch.primaryOutId===undefined){ + if(explicit.length)return fail('PRIMARY_OUT_ID_MISSING'); + continue; + } + if(!id(ch.primaryOutId)||!channels.has(ch.primaryOutId)|| + ch.primaryOutId===ch.id)return fail('INVALID_ACCEPTED_PRIMARY_OUT'); + const matching=edges.filter(e=>e.from===ch.id&&e.to===ch.primaryOutId); + if(matching.length!==1||matching[0].primaryOutput===false|| + (explicit.length&&explicit[0].edgeId!==matching[0].edgeId)) + return fail('AMBIGUOUS_ACCEPTED_PRIMARY_OUT'); + primaryEdges.add(matching[0].edgeId); + } // Do not use a rejected/feedback graph as a source of proposed changes. for(const [src,targets] of arcs.entries()) if(targets.some(to=>path(to,src)))return fail('ACCEPTED_GRAPH_CYCLE'); - return {ok:true,channels,main,edges,arcs,path,accepted}; + return {ok:true,channels,main,edges,primaryEdges,arcs,path,accepted}; } function sendsToMain(view,source,candidate){ const next=new Map([...view.channels.keys()].map(x=>[x,[]])); @@ -91,6 +112,15 @@ function sendsToMain(view,source,candidate){ }; return count(source,new Set()); } +// Validate the proposed audible DAG for EVERY upstream input, not just the +// bus receiving the gesture. Otherwise INPUT -> MAIN and INPUT -> GROUP -> +// MAIN can silently double the dry signal after routing the GROUP. +function upstreamDryHasDuplicates(view,candidate){ + for(const ch of view.channels.values()) + if(ch.role==='INPUT'&&sendsToMain(view,ch.id,candidate)>1) + return true; + return false; +} function planWire(view,request){ const {kind,sourceId,destinationId}=request; if(!id(sourceId)||!view.channels.has(sourceId)|| @@ -104,7 +134,8 @@ function planWire(view,request){ if(view.path(destinationId,sourceId))return fail('ROUTING_FEEDBACK_CYCLE'); if(destination.role==='INPUT')return fail('INPUT_NOT_A_ROUTING_DESTINATION'); const same=view.edges.filter(e=>e.from===sourceId&&e.to===destinationId); - const currentPrimary=view.edges.filter(e=>e.from===sourceId&&e.primaryOutput); + const currentPrimary=view.edges.filter(e=> + e.from===sourceId&&view.primaryEdges.has(e.edgeId)); if(currentPrimary.length>1)return fail('MULTIPLE_ACCEPTED_PRIMARY_OUTPUTS'); if(kind==='ROUTE_ONLY'){ if(destination.role!=='GROUP'&&destination.role!=='MAIN') @@ -113,11 +144,14 @@ function planWire(view,request){ return fail('PRIMARY_ALREADY_AT_DESTINATION'); if(same.length)return fail('DUPLICATE_NATIVE_ROUTE'); const simulated=view.edges.filter(e=> - !(e.from===sourceId&&e.primaryOutput)); + !(e.from===sourceId&&view.primaryEdges.has(e.edgeId))); simulated.push({from:sourceId,to:destinationId,primaryOutput:true}); if(sendsToMain(view,sourceId,simulated)>1) return fail('EXCLUSIVE_ROUTE_RETAINS_PARALLEL_DRY_PATH', 'Native Route Only changes the primary OUT; existing parallel sends remain.'); + if(upstreamDryHasDuplicates(view,simulated)) + return fail('UPSTREAM_DOUBLE_DRY_TO_MAIN', + 'An upstream input would reach MAIN twice through a new GROUP route.'); return {ok:true,intent:{operation:M4_OPERATOR_ABI.nativeWireOperation, targetChannelId:sourceId,payload:{changes:[{ op:'ROUTE_ONLY',from:sourceId,to:destinationId, @@ -136,7 +170,9 @@ function planWire(view,request){ if(request.gainDb!==undefined&&request.gainDb!==0) return fail('SEND_GAIN_ACK_READBACK_NOT_AVAILABLE'); const simulated=[...view.edges,{from:sourceId,to:destinationId,primaryOutput:false}]; - if(destination.role!=='FX_RETURN'&&sendsToMain(view,sourceId,simulated)>1) + if(destination.role!=='FX_RETURN'&& + (sendsToMain(view,sourceId,simulated)>1|| + upstreamDryHasDuplicates(view,simulated))) return fail('DOUBLE_DRY_TO_MAIN', 'Choose Route Only for subgroup instead of mixing direct MAIN twice.'); return {ok:true,intent:{operation:M4_OPERATOR_ABI.nativeWireOperation, diff --git a/src/Main.cpp b/src/Main.cpp index 46c588e08..398cc5b25 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -6,6 +6,7 @@ #include #include "ApprovedGuiResources.h" #include "ApprovedConsoleNativeTransportV6.h" +#include "../integration/ApprovedNativeRuntimeSnapshot.h" #include "LiveAudioEngine.h" #include "ArSonMixStartupSplash.h" #include "VstOrbitController.h" @@ -696,10 +697,22 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr emitOrbitState (previousSlot); } + juce::var approvedNativeSnapshot (const juce::var& live) + { + auto accepted=armix::native_console_m2::snapshot ( + live, engine_.devices(), engine_.allOutputsDisarmed()); + // Native routing's generation advances on STOP as well as START. + // Keep even disconnected G0 snapshots monotonic to invalidate UI. + (void) armix::console::synchronizeApprovedRouteDeviceEpoch ( + accepted, live); + (void) armix::console::projectInstalledNativeChannelIdGraph ( + accepted, live); + return accepted; + } + juce::var approvedNativeSnapshot() { - return armix::native_console_m2::snapshot ( - engine_.status(), engine_.devices(), engine_.allOutputsDisarmed()); + return approvedNativeSnapshot (engine_.status()); } void emitApprovedNativeSnapshot() @@ -2505,8 +2518,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr 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())); + approvedNativeSnapshot (health)); } if (deviceSettingsDirty_) diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp new file mode 100644 index 000000000..ed7e0629f --- /dev/null +++ b/tests/approved_native_v8_projection_test.cpp @@ -0,0 +1,376 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// M3-B CONTROL-thread projection regression. No mock PCM is installed. +#include "../integration/ApprovedNativeV8Projection.h" +#include "../integration/ApprovedNativeControlIntent.h" +#include "../integration/ApprovedNativeRuntimeSnapshot.h" +#if defined(NDEBUG) +#undef NDEBUG +#endif +#include +#include +#include +using namespace armix::console; + +static juce::var parse(const char* bytes) { + auto json=juce::JSON::parse(juce::String::fromUTF8(bytes)); + assert(json.isObject()); + return json; +} +static juce::var canonicalSnapshot() { + return parse(R"JSON({ + "schemaVersion":6,"productionCallbackLive":false, + "device":{"epoch":"91","backend":"WASAPI","enabledInputs":[0,2],"enabledOutputs":[0,1]}, + "graph":{"revision":"0","rosterRevision":"0","channels":[],"edges":[], + "capabilities":{"callbackOwnsChannelIds":false,"supportedOps":[]}}, + "telemetry":{"channelMeterRmsPeak":{},"rawCapturePresent":false} + })JSON"); +} +static juce::var realBusReadbackFixture() { + // Fixtures carry the shape of actual accepted producer readback ONLY. + // They can exercise serialization, but never establish callback authority. + return parse(R"JSON({ + "graphRevision":"25","rosterRevision":"9", + "channels":[ + {"id":"9007199254740993","name":"Vocal","role":"INPUT","format":"MONO", + "primaryOutput":"18446744073709551615","fader":0.5,"pan":0.0, + "mute":false,"solo":false,"inserts":[], + "peakL":0.25,"peakR":0.25}, + {"id":"18446744073709551615","name":"MAIN","role":"MAIN","format":"STEREO", + "primaryOutput":"0","fader":1.0,"pan":0.0, + "mute":false,"solo":false,"inserts":[], + "peakL":0.125,"peakR":0.125} + ], + "edges":[ + {"edgeId":"9223372036854775808","from":"9007199254740993", + "to":"18446744073709551615","tap":"POST_FADER", + "gainLinear":1.0,"primaryOutput":true} + ] + })JSON"); +} +static void noMutationOnReject(juce::var snapshot,juce::var bus,bool admitted) { + const auto before=juce::JSON::toString(snapshot,false); + assert(!projectApprovedNativeV8(snapshot,bus,admitted)); + assert(juce::JSON::toString(snapshot,false)==before); +} + +static void controlIntentTranslationCases(const juce::var& canonical, + const juce::var& rawBus) { + // Simulate an admitted native CONTROL ABI, not physical PCM. Real engine + // MUST expose these capabilities only after CH1-10 and dynamic IDs work. + auto accepted=juce::JSON::parse(juce::JSON::toString(canonical,false)); + auto bus=juce::JSON::parse(juce::JSON::toString(rawBus,false)); + juce::Array publicOps; + for(const char* op:{"SET_FADER","SET_PAN","SET_MUTE","SET_SOLO"}) + publicOps.add(juce::String(op)); + accepted.getProperty("graph",{}).getProperty("capabilities",{}) + .getDynamicObject()->setProperty("supportedOps",juce::var(publicOps)); + juce::Array nativeOps; + for(const char* op:{"NATIVE_SET_CHANNEL_MIX", + "NATIVE_SET_CHANNEL_MUTE_SOLO","NATIVE_SET_BUS_MIX"}) + nativeOps.add(juce::String(op)); + bus.getDynamicObject()->setProperty("supportedOps",juce::var(nativeOps)); + const auto source=juce::String("9007199254740993"); + const auto device=accepted.getProperty("device",{}); + const auto graph=accepted.getProperty("graph",{}); + auto makeIntent=[&](const char* operation,const juce::var& value, + const juce::String& id)->juce::var { + auto payload=std::make_unique(); + payload->setProperty(juce::String(operation)=="SET_FADER"? + "valueDb":"value",value); + auto request=std::make_unique(); + request->setProperty("requestId","m3b-controlled-intent-001"); + request->setProperty("deviceEpoch",device.getProperty("epoch",{})); + request->setProperty("baseGraphRevision",graph.getProperty("revision",{})); + request->setProperty("baseRosterRevision",graph.getProperty("rosterRevision",{})); + request->setProperty("operation",operation); + request->setProperty("targetChannelId",id); + request->setProperty("payload",juce::var(payload.release())); + return juce::var(request.release()); + }; + const auto fader=makeIntent("SET_FADER",juce::var(-12.0),source); + const auto translated=translateApprovedNativeControl(fader,accepted,bus); + assert(translated.ok()); + assert(translated.translated.getProperty("operation","").toString() + =="NATIVE_SET_CHANNEL_MIX"); + assert(translated.translated.getProperty("targetChannelId","").toString() + ==source); + assert(translated.translated.getProperty("requestId","").toString() + =="m3b-controlled-intent-001"); + const auto gain=translated.translated.getProperty("payload",{}) + .getProperty("gain",{}); + const auto keptPan=translated.translated.getProperty("payload",{}) + .getProperty("pan",{}); + assert(std::abs(static_cast(gain)-std::pow(10.,-12./20.))<0.000001); + assert(std::abs(static_cast(keptPan))<0.000001); + const auto pan=translateApprovedNativeControl( + makeIntent("SET_PAN",juce::var(0.75),source),accepted,bus); + assert(pan.ok()); + assert(std::abs(static_cast(pan.translated.getProperty("payload",{}) + .getProperty("gain",{}))-.5)<0.000001); + assert(std::abs(static_cast(pan.translated.getProperty("payload",{}) + .getProperty("pan",{}))-.75)<0.000001); + // A PAN-only gesture must preserve the original LINEAR PCM gain. + // In particular, -60 dB in the GUI can be a nonzero 0.001 producer + // gain, while +12 dB can be a clamped readback of native gain 4.0. + // Recomputing from projected dB would unintentionally silence/attenuate + // the same channel despite a perfectly accepted PAN intent. + for(const double level : {0.0,0.001,4.0}) { + auto physicalBus=juce::JSON::parse(juce::JSON::toString(bus,false)); + physicalBus.getProperty("channels",{})[0].getDynamicObject() + ->setProperty("fader",level); + auto physicalAccepted=canonicalSnapshot(); + assert(projectApprovedNativeV8(physicalAccepted,physicalBus,true)); + physicalAccepted.getProperty("graph",{}).getProperty("capabilities",{}) + .getDynamicObject()->setProperty("supportedOps",juce::var(publicOps)); + const auto panOnly=translateApprovedNativeControl( + makeIntent("SET_PAN",juce::var(-0.35),source), + physicalAccepted,physicalBus); + assert(panOnly.ok()); + const auto cmd=panOnly.translated.getProperty("payload",{}); + assert(std::abs(static_cast( + cmd.getProperty("gain",{}))-level)<0.000000000001); + assert(std::abs(static_cast( + cmd.getProperty("pan",{}))+0.35)<0.000000000001); + if(level==0.001) { + const auto explicitlySilent=translateApprovedNativeControl( + makeIntent("SET_FADER",juce::var(-60.),source), + physicalAccepted,physicalBus); + assert(explicitlySilent.ok()); + assert(static_cast(explicitlySilent.translated + .getProperty("payload",{}).getProperty("gain",-1.0))==0.); + } + } + const auto muted=translateApprovedNativeControl( + makeIntent("SET_MUTE",juce::var(true),source),accepted,bus); + assert(muted.ok()); + assert(muted.translated.getProperty("operation","").toString() + =="NATIVE_SET_CHANNEL_MUTE_SOLO"); + assert(static_cast(muted.translated.getProperty("payload",{}) + .getProperty("mute",false))); + assert(!static_cast(muted.translated.getProperty("payload",{}) + .getProperty("solo",true))); + const auto solo=translateApprovedNativeControl( + makeIntent("SET_SOLO",juce::var(true),source),accepted,bus); + assert(solo.ok()); + assert(!static_cast(solo.translated.getProperty("payload",{}) + .getProperty("mute",true))); + assert(static_cast(solo.translated.getProperty("payload",{}) + .getProperty("solo",false))); + // Nothing in the original request or accepted readback was edited. + assert(fader.getProperty("operation","").toString()=="SET_FADER"); + assert(graph.getProperty("channels",{})[0].getProperty("controls",{}) + .getProperty("faderDb",0.0)==canonical.getProperty("graph",{}) + .getProperty("channels",{})[0].getProperty("controls",{}) + .getProperty("faderDb",0.0)); + const auto before=juce::JSON::toString(accepted,false); + auto fail=[&](const juce::var& request,const juce::var& pub, + const juce::var& native)->juce::String { + const auto oldPub=juce::JSON::toString(pub,false); + const auto oldBus=juce::JSON::toString(native,false); + const auto result=translateApprovedNativeControl(request,pub,native); + assert(!result.ok()); + assert(!result.translated.isObject()); + assert(juce::JSON::toString(pub,false)==oldPub); + assert(juce::JSON::toString(native,false)==oldBus); + return result.error; + }; + assert(fail(fader,canonicalSnapshot(),bus)=="CHANNELID_CALLBACK_NOT_ADMITTED"); + assert(fail(makeIntent("SET_FADER",juce::var(-100.),source), + accepted,bus)=="INVALID_FADER_VALUE"); + assert(fail(makeIntent("SET_PAN",juce::var(2.),source), + accepted,bus)=="INVALID_PAN_VALUE"); + assert(fail(makeIntent("SET_MUTE",juce::var(1),source), + accepted,bus)=="INVALID_MUTE_SOLO_VALUE"); + assert(fail(makeIntent("SET_FADER",juce::var(-12.), + "9007199254740994"),accepted,bus) + =="UNKNOWN_OR_STALE_CHANNELID"); + assert(fail(makeIntent("SET_MUTE",juce::var(true), + "18446744073709551615"),accepted,bus) + =="CHANNEL_ROLE_NOT_MUTABLE"); + const auto stale=makeIntent("SET_PAN",juce::var(0.5),source); + stale.getDynamicObject()->setProperty("baseGraphRevision","24"); + assert(fail(stale,accepted,bus)=="STALE_NATIVE_CONTROL_REVISION"); + const auto fakeOp=makeIntent("SET_FADER",juce::var(-12.),source); + fakeOp.getDynamicObject()->setProperty("operation","NATIVE_SET_CHANNEL_MIX"); + assert(fail(fakeOp,accepted,bus)=="UNSUPPORTED_APPROVED_CONTROL"); + auto unadvertised=juce::JSON::parse(juce::JSON::toString(accepted,false)); + unadvertised.getProperty("graph",{}).getProperty("capabilities",{}) + .getDynamicObject()->setProperty("supportedOps", + juce::var(juce::Array{})); + assert(fail(fader,unadvertised,bus)=="PUBLIC_CONTROL_NOT_ADMITTED"); + auto noLease=juce::JSON::parse(juce::JSON::toString(bus,false)); + noLease.getDynamicObject()->setProperty("supportedOps", + juce::var(juce::Array{})); + assert(fail(fader,accepted,noLease)=="NATIVE_PCM_OPERATION_NOT_ADMITTED"); + auto staleReadback=juce::JSON::parse(juce::JSON::toString(bus,false)); + staleReadback.getProperty("channels",{})[0].getDynamicObject() + ->setProperty("fader",0.25); + assert(fail(fader,accepted,staleReadback)=="STALE_NATIVE_CONTROL_READBACK"); + auto wrongRole=juce::JSON::parse(juce::JSON::toString(bus,false)); + wrongRole.getProperty("channels",{})[0].getDynamicObject() + ->setProperty("role","GROUP"); + assert(fail(fader,accepted,wrongRole)=="NATIVE_ROLE_MISMATCH"); + assert(juce::JSON::toString(accepted,false)==before); +} + + +static void installedCallbackAdmissionRegression(const juce::var& rawBus) { + // This fixture is ONLY accepted native readback; not a hardware device. + // It proves Main.cpp cannot publish a fake live graph from G0/M4 JSON. + auto snap=canonicalSnapshot(); + auto dev=snap.getProperty("device",{}); + dev.getDynamicObject()->setProperty("sampleRate",48000.0); + dev.getDynamicObject()->setProperty("bufferFrames",256); + juce::Array inputs,outputs; + inputs.add(0);outputs.add(0);outputs.add(1); + dev.getDynamicObject()->setProperty("enabledInputs",juce::var(inputs)); + dev.getDynamicObject()->setProperty("enabledOutputs",juce::var(outputs)); + auto live=parse(R"JSON({"connected":true,"directRouteAuthorized":true, + "adaptiveClockActive":false,"dryRoutingLab":{"ready":true, + "hasAcceptedRoute":true,"topologyFault":false, + "nativeChannelIdPcmActive":true,"epoch":91}})JSON"); + live.getProperty("dryRoutingLab",{}).getDynamicObject() + ->setProperty("nativeBus",rawBus); + auto fail=[&](const juce::var& candidate) { + auto before=juce::JSON::toString(snap,false); + assert(!projectInstalledNativeChannelIdGraph(snap,candidate)); + assert(juce::JSON::toString(snap,false)==before); + }; + fail(parse(R"JSON({"dryRoutingLab":{"nativeBus":{}}})JSON")); + auto deny=juce::JSON::parse(juce::JSON::toString(live,false)); + deny.getProperty("dryRoutingLab",{}).getDynamicObject() + ->setProperty("nativeChannelIdPcmActive",false); + fail(deny); + deny=juce::JSON::parse(juce::JSON::toString(live,false)); + deny.getProperty("dryRoutingLab",{}).getDynamicObject() + ->setProperty("topologyFault",true); + fail(deny); + deny=juce::JSON::parse(juce::JSON::toString(live,false)); + deny.getProperty("dryRoutingLab",{}).getDynamicObject() + ->setProperty("epoch",92); + fail(deny); + deny=juce::JSON::parse(juce::JSON::toString(live,false)); + deny.getDynamicObject()->setProperty("directRouteAuthorized",false); + fail(deny); + deny=juce::JSON::parse(juce::JSON::toString(live,false)); + deny.getDynamicObject()->setProperty("adaptiveClockActive",true); + fail(deny); + deny=juce::JSON::parse(juce::JSON::toString(live,false)); + deny.getProperty("dryRoutingLab",{}).getDynamicObject() + ->setProperty("nativeBus",juce::var()); + fail(deny); + assert(synchronizeApprovedRouteDeviceEpoch(snap,live)); + assert(projectInstalledNativeChannelIdGraph(snap,live)); + // Real restart: lab routing epoch counts STOP+START, unlike M2 + // deviceStartCount. This G0-to-native authority switch must advance. + auto disconnected=canonicalSnapshot(); + // Simulate the SAME actual driver pin masks after reconnect. A default + // G0 no-device fixture would otherwise correctly refuse native admit. + auto disconnectedDevice=disconnected.getProperty("device",{}).getDynamicObject(); + disconnectedDevice->setProperty("sampleRate",48000.0); + disconnectedDevice->setProperty("bufferFrames",256); + disconnectedDevice->setProperty("enabledInputs",juce::var(inputs)); + disconnectedDevice->setProperty("enabledOutputs",juce::var(outputs)); + auto dead=juce::JSON::parse(juce::JSON::toString(live,false)); + dead.getProperty("dryRoutingLab",{}).getDynamicObject() + ->setProperty("nativeChannelIdPcmActive",false); + dead.getProperty("dryRoutingLab",{}).getDynamicObject() + ->setProperty("epoch",93); + assert(synchronizeApprovedRouteDeviceEpoch(disconnected,dead)); + assert(disconnected.getProperty("device",{}) + .getProperty("epoch","").toString()=="93"); + assert(!projectInstalledNativeChannelIdGraph(disconnected,dead)); + const auto ghost=disconnected.getProperty("graph",{}); + assert(!static_cast(ghost.getProperty("capabilities",{}) + .getProperty("callbackOwnsChannelIds",false))); + auto restarted=juce::JSON::parse(juce::JSON::toString(live,false)); + restarted.getProperty("dryRoutingLab",{}).getDynamicObject() + ->setProperty("epoch",93); + assert(synchronizeApprovedRouteDeviceEpoch(disconnected,restarted)); + assert(projectInstalledNativeChannelIdGraph(disconnected,restarted)); + assert(disconnected.getProperty("graph",{}) + .getProperty("revision","").toString()=="25"); + // Never roll back to an older route generation after device reconnect. + auto stale=juce::JSON::parse(juce::JSON::toString(restarted,false)); + stale.getProperty("dryRoutingLab",{}).getDynamicObject() + ->setProperty("epoch",90); + assert(!synchronizeApprovedRouteDeviceEpoch(disconnected,stale)); + assert(disconnected.getProperty("device",{}) + .getProperty("epoch","").toString()=="93"); + const auto graph=snap.getProperty("graph",{}); + assert(static_cast(graph.getProperty("capabilities",{}) + .getProperty("callbackOwnsChannelIds",false))); + assert(graph.getProperty("channels",{}).getArray()->size()==2); + assert(graph.getProperty("capabilities",{}) + .getProperty("supportedOps",{}).getArray()->isEmpty()); + assert(!static_cast(snap.getProperty("productionCallbackLive",false))); +} + +int main() { + auto snap=canonicalSnapshot(); + auto bus=realBusReadbackFixture(); + // Merely having matching native-shaped JSON cannot enable fake LIVE. + noMutationOnReject(snap,bus,false); + assert(nativeV8Decimal(juce::String("18446744073709551615"))); + assert(!nativeV8Decimal(juce::String("18446744073709551616"))); + assert(!nativeV8Decimal(juce::String("9007199254740993x"))); + assert(!nativeV8Decimal(juce::String("0002"))); + assert(!nativeV8Decimal(juce::String("0"))); + + assert(projectApprovedNativeV8(snap,bus,true)); + const auto graph=snap.getProperty("graph",{}); + const auto chans=graph.getProperty("channels",{}); + const auto wires=graph.getProperty("edges",{}); + assert(graph.getProperty("revision","").toString()=="25"); + assert(graph.getProperty("rosterRevision","").toString()=="9"); + assert(graph.getProperty("mainChannelId","").toString()=="18446744073709551615"); + assert(chans.getArray() && chans.getArray()->size()==2); + assert(wires.getArray() && wires.getArray()->size()==1); + assert(chans[0].getProperty("id","").toString()=="9007199254740993"); + assert(wires[0].getProperty("edgeId","").toString()=="9223372036854775808"); + assert(std::abs(static_cast( + chans[0].getProperty("controls",{}).getProperty("faderDb",0.0)) + +6.020599913279624)<0.00001); + assert(static_cast(graph.getProperty("capabilities",{}) + .getProperty("callbackOwnsChannelIds",false))); + // NOTE: structural ChannelId proof NEVER promotes universal product-live. + assert(!static_cast(snap.getProperty("productionCallbackLive",false))); + + controlIntentTranslationCases(snap,bus); + installedCallbackAdmissionRegression(bus); + + auto missingMain=realBusReadbackFixture(); + missingMain.getProperty("channels",{})[1].getDynamicObject() + ->setProperty("role","GROUP"); + noMutationOnReject(canonicalSnapshot(),missingMain,true); + + auto badEdge=realBusReadbackFixture(); + badEdge.getProperty("edges",{})[0].getDynamicObject() + ->setProperty("to","18446744073709551614"); + noMutationOnReject(canonicalSnapshot(),badEdge,true); + + auto badIdentifier=realBusReadbackFixture(); + badIdentifier.getProperty("channels",{})[0].getDynamicObject() + ->setProperty("id","9007199254740993.0"); + noMutationOnReject(canonicalSnapshot(),badIdentifier,true); + + auto badGain=realBusReadbackFixture(); + badGain.getProperty("channels",{})[0].getDynamicObject() + ->setProperty("fader",-0.1); + noMutationOnReject(canonicalSnapshot(),badGain,true); + + auto duplicate=realBusReadbackFixture(); + duplicate.getProperty("channels",{})[1].getDynamicObject() + ->setProperty("id","9007199254740993"); + noMutationOnReject(canonicalSnapshot(),duplicate,true); + + auto staleDevice=canonicalSnapshot(); + staleDevice.getProperty("device",{}).getDynamicObject() + ->setProperty("epoch","0"); + noMutationOnReject(staleDevice,realBusReadbackFixture(),true); + + auto unavailableGraph=canonicalSnapshot(); + unavailableGraph.getDynamicObject()->removeProperty("graph"); + noMutationOnReject(unavailableGraph,realBusReadbackFixture(),true); + return 0; +} diff --git a/tests/m4_operator_routing.test.mjs b/tests/m4_operator_routing.test.mjs index e6fc7d5e0..834ea0516 100644 --- a/tests/m4_operator_routing.test.mjs +++ b/tests/m4_operator_routing.test.mjs @@ -261,3 +261,90 @@ test('POST send ACK requires actual accepted gain and tap, not cable existence', assert.equal(check(1,'PRE_FADER').pass,false); assert.equal(check(1,'POST_FADER').pass,true); }); + + +test('accepted v8 primaryOutId works when edge primaryOutput flags are absent',()=>{ + const raw=base(); + for(const edge of raw.graph.edges)delete edge.primaryOutput; + const current=accepted(raw); + const plan=planM4OperatorIntent(current,{kind:'ROUTE_ONLY', + sourceId:ids.v,destinationId:ids.group}); + assert.equal(plan.ok,true,'public v8 does not require an edge primary flag'); + const c=createController({emit:()=>{}}); + assert.equal(c.onSnapshot(raw),true); + const issued=c.intent(plan.intent.operation,plan.intent.targetChannelId, + plan.intent.payload); + assert.equal(issued.ok,true); + c.onAck({requestId:issued.requestId,status:'ACCEPTED',errorCode:'NONE', + deviceEpoch:'69',graphRevision:'4',rosterRevision:'2'}); + const applied=clone(raw);applied.graph.revision='4'; + applied.graph.channels[0].primaryOutId=ids.group; + applied.graph.edges[0].to=ids.group; + assert.equal(c.onSnapshot(applied),true, + 'ACK+later accepted snapshot with channel.primaryOutId must be sufficient'); + const inconsistent=base(); + inconsistent.graph.edges[0].primaryOutput=false; + assert.equal(planM4OperatorIntent(accepted(inconsistent),{ + kind:'ROUTE_ONLY',sourceId:ids.v,destinationId:ids.group}).error, + 'AMBIGUOUS_ACCEPTED_PRIMARY_OUT'); +}); +test('Route Only rejects old unflagged GROUP output after a valid ACK',()=>{ + const original=base(); + // Start with the primary path via an existing GROUP instead of MAIN. + original.graph.channels[0].primaryOutId=ids.group; + original.graph.edges[0].to=ids.group; + for(const edge of original.graph.edges)delete edge.primaryOutput; + const destination='102'; + original.graph.channels.push({id:destination,role:'GROUP',name:'BUS 2', + processingFormat:'STEREO',primaryOutId:ids.main, + controls:{faderDb:0,pan:0,mute:false,solo:false},inserts:[],sends:[]}); + original.graph.destinations.push({id:destination}); + original.graph.edges.push({edgeId:'90',from:destination,to:ids.main, + tap:'POST_FADER',gainLinear:1,enabled:true,signalKind:'AUDIO'}); + const plan=planM4OperatorIntent(accepted(original),{ + kind:'ROUTE_ONLY',sourceId:ids.v,destinationId:destination}); + assert.equal(plan.ok,true); + const controller=createController({emit:()=>{}}); + controller.onSnapshot(original); + const req=controller.intent(plan.intent.operation,plan.intent.targetChannelId, + plan.intent.payload); + controller.onAck({requestId:req.requestId,status:'ACCEPTED',errorCode:'NONE', + deviceEpoch:'69',graphRevision:'4',rosterRevision:'2'}); + const lied=clone(original);lied.graph.revision='4'; + lied.graph.channels[0].primaryOutId=destination; + lied.graph.edges.push({edgeId:'91',from:ids.v,to:destination, + tap:'POST_FADER',gainLinear:1,enabled:true,signalKind:'AUDIO'}); + assert.equal(controller.onSnapshot(lied),false, + 'stale GROUP dry path must not survive exclusive Route Only'); + const valid=clone(original);valid.graph.revision='4'; + valid.graph.channels[0].primaryOutId=destination; + valid.graph.edges[0].to=destination; + assert.equal(controller.onSnapshot(valid),true); +}); +test('upstream INPUT double-dry is rejected for GROUP Route Only and POST send',()=>{ + const raw=base(),group=raw.graph.channels[2]; + delete group.primaryOutId; + raw.graph.edges=raw.graph.edges.filter(e=>e.from!==ids.group); + raw.graph.edges.push({edgeId:'80',from:ids.v,to:ids.group, + tap:'POST_FADER',gainLinear:1,primaryOutput:false, + enabled:true,signalKind:'AUDIO'}); + const current=accepted(raw); + const p=planM4OperatorIntent(current,{kind:'ROUTE_ONLY', + sourceId:ids.group,destinationId:ids.main}); + assert.equal(p.ok,false); + assert.equal(p.error,'UPSTREAM_DOUBLE_DRY_TO_MAIN'); + // Adding a GROUP-to-GROUP post send is equally dangerous when the + // upstream input already has a direct independent MAIN route. + const second='102'; + raw.graph.channels.push({id:second,role:'GROUP',name:'BUS 2', + processingFormat:'STEREO',primaryOutId:ids.main, + controls:{faderDb:0,pan:0,mute:false,solo:false},inserts:[],sends:[]}); + raw.graph.destinations.push({id:second}); + raw.graph.edges.push({edgeId:'81',from:second,to:ids.main, + tap:'POST_FADER',gainLinear:1,primaryOutput:true, + enabled:true,signalKind:'AUDIO'}); + const q=planM4OperatorIntent(accepted(raw),{kind:'SEND_POST', + sourceId:ids.group,destinationId:second}); + assert.equal(q.ok,false); + assert.equal(q.error,'DOUBLE_DRY_TO_MAIN'); +}); diff --git a/web/approved-native-contract.js b/web/approved-native-contract.js index 964a93d13..b3d323c5b 100644 --- a/web/approved-native-contract.js +++ b/web/approved-native-contract.js @@ -144,15 +144,29 @@ !Number.isFinite(e.gainLinear) || Math.abs(edit.gainLinear-e.gainLinear)>0.0001)) return false; - return edit.op!=="ROUTE_ONLY" || e.primaryOutput===true; + // v8 makes channel.primaryOutId authoritative; primaryOutput on + // an edge is optional, but an explicitly false flag cannot be + // interpreted as a physical primary cable. + return edit.op!=="ROUTE_ONLY" || + (ch.primaryOutId===edit.to&&e.primaryOutput!==false); }); if (!effect) return false; if (edit.op==="ROUTE_ONLY") { - // Route Only must REMOVE the previous primary dry path. An ACK - // with both new BUS and original MAIN remains double-dry even - // when the graph revision advanced. - if (ch.primaryOutId!==edit.to) return false; - if (edges.some(e=>e.from===edit.from&&e.primaryOutput===true&&e.to!==edit.to)) + // A unique primary cable must match both the channel-level + // identity and requested destination. Do not accept a second + // matching SEND cable as proof of exclusive output. + if (ch.primaryOutId!==edit.to||matching.length!==1|| + matching[0].primaryOutput===false) return false; + if (edges.some(e=>e.from===edit.from&& + e.primaryOutput===true&&e.to!==edit.to)) + return false; + // Preserve the original primary destination in the pending + // control transaction so even an old GROUP cable without an edge + // primaryOutput flag cannot survive Route Only unnoticed. + if (pending.originalPrimaryOutId && + pending.originalPrimaryOutId!==edit.to && + edges.some(e=>e.from===edit.from&& + e.to===pending.originalPrimaryOutId)) return false; if (edit.to!==next.graph.mainChannelId && edges.some(e=>e.from===edit.from&&e.to===next.graph.mainChannelId)) @@ -245,6 +259,8 @@ baseRosterRevision:current.graph.rosterRevision, operation,targetChannelId,payload}; pending={requestId,operation,targetChannelId,payload, + originalPrimaryOutId:current.graph.channels.find( + ch=>ch.id===targetChannelId)?.primaryOutId||null, deviceEpoch:msg.deviceEpoch,baseGraphRevision:msg.baseGraphRevision, baseRosterRevision:msg.baseRosterRevision,ack:null}; lastError="PENDING_NATIVE_ACK";