diff --git a/docs/FIRST_SOUND_FAT_QUICKSTART_20261101.md b/docs/FIRST_SOUND_FAT_QUICKSTART_20261101.md index baa97a730..61afc89c0 100644 --- a/docs/FIRST_SOUND_FAT_QUICKSTART_20261101.md +++ b/docs/FIRST_SOUND_FAT_QUICKSTART_20261101.md @@ -28,3 +28,9 @@ Send: (a) screenshot of active driver/rate/buffer/pins, (b) accepted CH01 patch **PASS is hardware-grounded:** correct MAIN source path, verified mute/fader control, no wrong-endpoint output, clean 0FX wired audio for >=30 minutes on the recorded device/rate/buffer, followed by real plugin testing. A green Windows CTest/Chromium CI is not a substitute. Historical full test matrix remains `docs/HARDWARE_FAT_GUI10_ENGINE_P012_20261027.md`. This packaged guide supersedes obsolete manual START AUDIO instructions. + +## M3-E matched 44.1/48 kHz exact-SHA evidence tools + +The verified FAT ZIP now contains two source+manifest SHA256-bound files: collect_hardware_fat_windows.ps1 and m3e_fat_evidence_gate.mjs. Both are **independent field QA**, not audio engines. Use the collector with -Action Verify, Start, Stop and Summary beside BUILD_PROVENANCE.json and the original EXE. Run four modes (OUTPUT_ONLY_TONE, CAPTURE_ONLY, DRY_THROUGH_0FX, LIVE_THROUGH_1FX) for **each** supported 44100/48000 Hz profile; both matched wired 0FX/1FX sessions need >= 30 minutes, same actual backend/buffer/physical pins and copied complete report, with human witness. A genuine active VST3 is required for the 1FX comparison. Do not invent unsupported hardware rates. + +With Node 20+ available, run: node ./m3e_fat_evidence_gate.mjs . to verify source/EXE/tools integrity and independent report SHA256/mode matching. **EVIDENCE_READY_FOR_HUMAN_REVIEW is not a PASS.** M3C #402's readback projection has merged but it is NOT proof of a joined ENGINE #266 PCM callback and M3F accepted mutating ACK/snapshot; physical hardware #15 remains STOP-SHIP. The checker always leaves native PCM and final release readiness PENDING until separate true evidence exists. Full guidance: docs/M3E_FAT_RELEASE_ADMISSION_20261105.md in repository. Review raw logs for device information before sharing; these tools upload nothing. diff --git a/docs/M3E_FAT_RELEASE_ADMISSION_20261105.md b/docs/M3E_FAT_RELEASE_ADMISSION_20261105.md new file mode 100644 index 000000000..eccaa34e7 --- /dev/null +++ b/docs/M3E_FAT_RELEASE_ADMISSION_20261105.md @@ -0,0 +1,51 @@ +# M3-E — First Real Sound & Exact-SHA FAT Evidence + +Authority: AGENTS.md, issue #397; ONLY approved /preview/ GUI. Hardware crackle #15 is STOP-SHIP. ENGINE #266 solely owns callback PCM; INTEGRATOR #402 owns native ACK/readback; FAT only owns evidence and packaging. + +## Implemented FAT intake + +- Independent native Windows release packaging copies collect_hardware_fat_windows.ps1 (selectively extracted ONLY from parked #270) and m3e_fat_evidence_gate.mjs beside the EXE. No old callback/GUI is merged. +- BUILD_PROVENANCE.json records exact sourceCommit, EXE SHA256, approved /preview/ GUI asset hashes, both FAT tool hashes, and EXPLICIT UNQUALIFIED status. +- Windows verify_native_windows_artifact.ps1 compares tool bytes from the checked-out source, distributed directory and compressed ZIP entries; it verifies actual AMD64 PE32+ GUI application, not a console-test executable. +- The offline field recorder never starts audio, changes device, arms output, opens VST3 or uploads logs. It only records operator-entered evidence and cryptographic copies of full reports. +- The Node assessment validates **both 44,100 and 48,000 Hz** using OUTPUT_ONLY_TONE, CAPTURE_ONLY, DRY_THROUGH_0FX, LIVE_THROUGH_1FX; requires 30-minute wired 0FX and matched 1FX, matching driver/buffer/ports, full report hashes, human witness and honest CLEAR observations. + +## Windows field procedure + +1. Extract the complete exact Actions ZIP, then independently compare its sourceCommit to the GitHub run. Use a wired headset and low output level. Do not use Bluetooth as the reference output. +2. From the extracted folder, run PowerShell: ./collect_hardware_fat_windows.ps1 -Action Verify. The script fails when the EXE or FAT collector differs from the manifest. +3. In the running native approved /preview/ UI, apply an ACTUAL supported driver, physical I/O pins, clock and buffer, and explicitly ARM only through the app's verified safe workflow. +4. For each supported sample rate (44100 and 48000), record the 4 required modes with -Action Start and -Action Stop. The 1FX run requires a prior complete matching 0FX baseline. See the existing HARDWARE_FAT_GUIDE.md for mode setup; the app's COPY FULL REPORT and manual witness are required. +5. Run: ./collect_hardware_fat_windows.ps1 -Action Summary; then, when Node 20+ is available, run: node ./m3e_fat_evidence_gate.mjs . +6. Review FAT_RUNS.json and raw reports for device identifiers before sharing. Neither script transmits files. If the actual interface does not support a requested rate, keep the full two-rate evidence gate PENDING, rather than fabricating a result. + +Example: ./collect_hardware_fat_windows.ps1 -Action Start -Mode DRY_THROUGH_0FX -Backend 'ASIO' -SampleRate 48000 -BufferFrames 256 -InputPins '0' -OutputPins '0,1' -CaptureEndpoint 'actual-pin-identity' -RenderEndpoint 'actual-wired-output' -Wired +After at least 30 minutes with the actual native route playing: ./collect_hardware_fat_windows.ps1 -Action Stop -Result CLEAR -Witness 'qualified-observer' -ReportPath '.\COPY_FULL_REPORT.txt' + +## Three independent verdicts (non-interchangeable) + +| Gate | Exact meaning | Current progression | +| --- | --- | --- | +| BUILD | Same-SHA GUI EXE + approved /preview/ byte hashes + FAT tools + ZIP. Local hashes alone do not prove external CI status. | Verifiable after the exact-head Windows package job. | +| NATIVE PCM | Real installed JUCE callback, CH1–10 + dynamic ChannelId, real fader/PAN/MUTE/SOLO, GROUP/MAIN, actual VST3 and ACK plus readback. | #402 readback projection MERGED; real installed ENGINE #266 producer + M3F accepted mutating ACK/snapshot remain PENDING. | +| PHYSICAL FAT | Recorded genuine 44.1/48-kHz wired zero-FX and FX sessions plus human independent acoustic review, including hotplug/reconnect and crackling #15. | PENDING real hardware. | + +Both the collector and gate deliberately output EVIDENCE_READY_FOR_HUMAN_REVIEW at most, never hardware PASS or product release-ready. The package is experimental. A GUI screenshot, mock PCM fixture, green CTest, assumed callback, or user-entered VST3 name is NOT real acoustic evidence. + +## Reliability / crackle provenance + +Capture discontinuity flags, callback gap, DSP deadline and render-driver XRUN are **different** signals. In JUCE WASAPI getXRunCount can count capture discontinuities rather than render hardware underrun; do not infer clean output from zero capture flags. Unknown counters remain UNAVAILABLE, not zero. Segment reports by device epoch, driver, sample rate, buffer and actual endpoint. Operator mark and full COPY FULL REPORT are the audit source. + +## Mandatory owner handoffs + +ENGINE #266: one signed source-SHA+epoch numerical callback PCM capture for all original ten input strips + dynamic CH11, fader/PAN/MUTE/SOLO, wet-only FX return and real VST3 plugin lease. No second audio callback. INTEGRATOR M3F (continuing merged #402): one accepted native publisher/epoch with GUI intent, matching ACK, and exact later accepted snapshot; do not enable unsupported operations. FAT consumes their evidence only on a joined exact Windows EXE. Keep #15 open until genuinely qualified. + +## Windows PowerShell 5.1 JSON interoperability + +Windows PowerShell 5.1 writes UTF-8 BOM with `Set-Content -Encoding UTF8`. The independent M3-E Node checker accepts an optional BOM at the beginning of `BUILD_PROVENANCE.json` and `FAT_RUNS.json` without weakening EXE/collector/report SHA256, source-commit matching, schema validation, or `hardwareCertified=false`. Regression fixtures prove genuine BOM-encoded journals remain reviewable while malformed or cross-build records fail closed. The Windows PowerShell-only `-Action Summary` now independently checks that each selected session's start/end timestamps match `elapsedSeconds` (5-second tolerance). The Windows regression runs the real field script with an intentionally forged 1800-second duration and asserts `EVIDENCE_INCOMPLETE`, without requiring Node on the field operator's computer. + +The FAT field collector uses streaming .NET SHA256 rather than relying on the optional `Get-FileHash` cmdlet/module autoload in the Windows runner. This checks the collector, GUI executable and copied native reports without changing the SHA256 admission contract; the field action still never touches hardware audio. + +## Independent physical pin-validation gate + +Manual `FAT_RUNS.json` is untrusted evidence. PowerShell `-Action Summary` now repeats start-time pin checks for **every** selected 44.1/48-kHz run: capture/render arrays must exist with valid unique 0–255 physical ordinals; output-only excludes capture, capture-only excludes render, and both 0FX/1FX through-runs require both real pin directions plus verified endpoint identities. Equal empty channel arrays never count as a matched device. A Windows PowerShell regression uses a synthetic exact-hash field kit and proves empty, duplicate and out-of-range pins remain `EVIDENCE_INCOMPLETE`. As before, passing the software evidence gate never proves the actual hardware pin mapping or sound. diff --git a/scripts/collect_hardware_fat_windows.ps1 b/scripts/collect_hardware_fat_windows.ps1 new file mode 100644 index 000000000..731da9e44 --- /dev/null +++ b/scripts/collect_hardware_fat_windows.ps1 @@ -0,0 +1,369 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Offline Windows field evidence recorder. NEVER controls audio devices, DSP, ARM or plugins. +param( + [ValidateSet('Verify','Start','Stop','Summary')][string]$Action='Verify', + [ValidateSet('OUTPUT_ONLY_TONE','CAPTURE_ONLY','DRY_THROUGH_0FX','LIVE_THROUGH_1FX')][string]$Mode='DRY_THROUGH_0FX', + [string]$Backend='', + [int]$SampleRate=0, + [int]$BufferFrames=0, + [string]$InputPins='', + [string]$OutputPins='', + [string]$CaptureEndpoint='', + [string]$RenderEndpoint='', + # MANUALLY read from the native VST3 rack; not a synthetic software probe. + # A 1FX run must identify exactly one active, non-bypassed vendor insert. + [ValidateRange(0,8)][int]$FxCount=0, + [string]$Vst3Name='', + [switch]$Wired, + [ValidateSet('CLEAR','CRACKLE','INCONCLUSIVE')][string]$Result='INCONCLUSIVE', + [string]$ReportPath='', + [string]$Witness='', + [string]$Notes='' +) +Set-StrictMode -Version Latest +$ErrorActionPreference='Stop' +$root=$PSScriptRoot +# SHA256 must remain available in Windows PowerShell even when optional modules +# are unavailable; never depend on Get-FileHash module auto-loading. +function Get-FatSha256([string] $Path) { + $filePath=(Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath + $stream=[System.IO.File]::OpenRead($filePath) + $hasher=[System.Security.Cryptography.SHA256]::Create() + try { + return ([BitConverter]::ToString($hasher.ComputeHash($stream))).Replace('-','').ToLowerInvariant() + } finally { + $stream.Dispose() + $hasher.Dispose() + } +} +$manifestPath=Join-Path $root 'BUILD_PROVENANCE.json' +if (-not (Test-Path -LiteralPath $manifestPath -PathType Leaf)) { throw 'Missing BUILD_PROVENANCE.json: extract the complete verified Windows FAT ZIP first' } +$m=Get-Content -LiteralPath $manifestPath -Raw -Encoding UTF8 | ConvertFrom-Json +if ([string]$m.fatStatus -ne 'EXPERIMENTAL_NOT_HARDWARE_QUALIFIED') { throw 'Unexpected hardware qualification claim' } +if ([string]$m.sourceCommit -notmatch '^[a-f0-9]{40}$') { throw 'Invalid exact source SHA' } +if ([string]$m.fatCollectorSha256 -notmatch '^[a-f0-9]{64}$') { throw 'Missing FAT collector provenance' } +$selfHash=(Get-FatSha256 -Path $PSCommandPath) +if ($selfHash -ne [string]$m.fatCollectorSha256) { throw 'FAT collector was modified after packaging' } +$app=Join-Path $root ([string]$m.executable) +if (-not (Test-Path -LiteralPath $app -PathType Leaf)) { throw 'Missing packaged native GUI EXE' } +$exeHash=(Get-FatSha256 -Path $app) +if ($exeHash -ne [string]$m.exeSha256) { throw 'GUI EXE SHA-256 mismatch: do not test or label this artifact' } +$journalPath=Join-Path $root 'FAT_RUNS.json' +function Save-Journal($j) { + $j | ConvertTo-Json -Depth 12 | Set-Content -LiteralPath $journalPath -Encoding UTF8 +} +function Read-Journal { + if (Test-Path -LiteralPath $journalPath -PathType Leaf) { + $j=Get-Content -LiteralPath $journalPath -Raw -Encoding UTF8 | ConvertFrom-Json + if ($j.schema -ne 'arsonmix.hardware-fat-field-journal.v1' -or + $j.sourceSha -ne $m.sourceCommit -or $j.exeSha256 -ne $exeHash) { + throw 'FAT_RUNS.json belongs to a different or unsupported build' + } + return $j + } + return [pscustomobject]@{ + schema='arsonmix.hardware-fat-field-journal.v1' + sourceSha=[string]$m.sourceCommit + exeSha256=$exeHash + active=$null + sessions=@() + } +} +function Parse-Pins([string]$raw) { + if ([string]::IsNullOrWhiteSpace($raw)) { return @() } + $parsed=@() + foreach ($part in $raw.Split(',')) { + $pin=0 + if (-not [int]::TryParse($part.Trim(),[ref]$pin) -or $pin -lt 0 -or $pin -gt 255) { + throw 'Pin values must be physical callback ordinals 0..255 separated by commas, confirmed from native readback' + } + if ($parsed -contains $pin) { throw 'Duplicate physical pin in evidence' } + $parsed+= $pin + } + return $parsed +} +if ($Action -eq 'Verify') { + Write-Host ('FAT PACKAGE OK; build='+$m.sourceCommit+'; EXE SHA256='+$exeHash) + Write-Host 'UNQUALIFIED 10CH/4AUX candidate. No sound, device, latency or hardware result has been tested.' + exit 0 +} +$j=Read-Journal +if ($Action -eq 'Start') { + if ($null -ne $j.active) { throw 'A FAT mode is already active; Stop it before starting another' } + if (-not $Backend.Trim() -or $SampleRate -notin @(44100,48000) -or + $BufferFrames -lt 16 -or $BufferFrames -gt 16384) { + throw 'Specify actual native readback -Backend, -SampleRate, -BufferFrames (not draft device values)' + } + $inputs=@(Parse-Pins $InputPins) + $outputs=@(Parse-Pins $OutputPins) + if ($Mode -eq 'OUTPUT_ONLY_TONE' -and ($inputs.Count -ne 0 -or $outputs.Count -lt 1)) { + throw 'OUTPUT_ONLY_TONE must have NO capture pins and a real render pin' + } + if ($Mode -eq 'CAPTURE_ONLY' -and ($outputs.Count -ne 0 -or $inputs.Count -lt 1)) { + throw 'CAPTURE_ONLY must have NO render pins and a real capture pin' + } + if ($Mode -in @('DRY_THROUGH_0FX','LIVE_THROUGH_1FX') -and + ($inputs.Count -lt 1 -or $outputs.Count -lt 1)) { + throw 'Live-through FAT requires actual capture and render pins' + } + if (($inputs.Count -gt 0 -and [string]::IsNullOrWhiteSpace($CaptureEndpoint)) -or + ($outputs.Count -gt 0 -and [string]::IsNullOrWhiteSpace($RenderEndpoint))) { + throw 'Real physical capture/render endpoint identity required before timer starts' + } + # Prevent confusing a 0FX soak with a real active vendor effect. The + # operator enters verified-in-GUI details; collector cannot observe DSP. + if ($Mode -in @('DRY_THROUGH_0FX','LIVE_THROUGH_1FX') -and -not $Wired) { + throw 'Both matched 0FX/1FX tests require actual -Wired hardware routing' + } + if ($Mode -eq 'LIVE_THROUGH_1FX') { + if ($FxCount -ne 1 -or [string]::IsNullOrWhiteSpace($Vst3Name) -or + $Vst3Name.Length -gt 120) { + throw '1FX FAT requires -FxCount 1 and -Vst3Name copied from the active native VST3 rack' + } + # A user should not spend another 30 minutes on an incomparable setup. + # Compare against the most recent completed, witnessed 0FX baseline + # BEFORE the 1FX timer starts; never accept a guess about the device. + $baseline=@($j.sessions | Where-Object { $_.mode -eq 'DRY_THROUGH_0FX' -and [int]$_.sampleRate -eq $SampleRate } | Select-Object -Last 1) + if ($baseline.Count -ne 1 -or $baseline[0].elapsedSeconds -lt 1800 -or + -not $baseline[0].wired -or -not $baseline[0].reportSha256 -or + -not $baseline[0].witness -or + $baseline[0].operatorObservation -eq 'INCONCLUSIVE') { + throw 'Record a completed 30-minute wired 0FX baseline with witness and full report before 1FX' + } + $base=$baseline[0] + if ($base.backend -ne $Backend -or + $base.sampleRate -ne $SampleRate -or + $base.bufferFrames -ne $BufferFrames -or + ($base.capturePins -join ',') -ne ($inputs -join ',') -or + ($base.renderPins -join ',') -ne ($outputs -join ',') -or + $base.captureEndpoint -ne $CaptureEndpoint -or + $base.renderEndpoint -ne $RenderEndpoint) { + throw '1FX must use the identical ASIO/WASAPI device, clock, buffer and physical ports as the 0FX baseline' + } + } elseif ($FxCount -ne 0 -or -not [string]::IsNullOrWhiteSpace($Vst3Name)) { + throw 'Only LIVE_THROUGH_1FX accepts an active VST3 rack; other FAT modes require zero FX' + } + # The operator must select the mode in the running native app FIRST. + # Starting this timer does not change any endpoint or output ARM. + $j.active=[pscustomobject]@{ + mode=$Mode + startedUtc=[DateTime]::UtcNow.ToString('o') + backend=$Backend + sampleRate=$SampleRate + bufferFrames=$BufferFrames + capturePins=$inputs + renderPins=$outputs + captureEndpoint=$CaptureEndpoint + renderEndpoint=$RenderEndpoint + operatorReportedFxCount=$FxCount + operatorReportedVst3Name=$Vst3Name.Trim() + wired=[bool]$Wired + } + Save-Journal $j + Write-Host ('FAT TIMER STARTED '+$Mode+' at '+$j.active.startedUtc) + Write-Host 'Listen at LOW wired volume; use SIGNAL CHECK > MARK CRACKLE, COPY FULL REPORT. No audio or ARM controls were changed.' + exit 0 +} +if ($Action -eq 'Stop') { + if ($null -eq $j.active) { throw 'No active FAT session; use -Action Start after selecting actual native mode' } + $end=[DateTime]::UtcNow + $elapsed=[math]::Max(0,[math]::Floor(($end-([DateTime]::Parse($j.active.startedUtc).ToUniversalTime())).TotalSeconds)) + $reportFileName=$null + $reportHash=$null + if (-not [string]::IsNullOrWhiteSpace($ReportPath)) { + if (-not (Test-Path -LiteralPath $ReportPath -PathType Leaf)) { throw 'COPY FULL REPORT file not found' } + $reportFileName=('FAT_REPORT_'+$j.active.mode+'_'+$end.ToString('yyyyMMddTHHmmssZ')+'.txt') + $destination=Join-Path $root $reportFileName + Copy-Item -LiteralPath $ReportPath -Destination $destination -ErrorAction Stop + $reportHash=(Get-FatSha256 -Path $destination) + } + $session=[pscustomobject]@{ + mode=$j.active.mode + startedUtc=$j.active.startedUtc + endedUtc=$end.ToString('o') + elapsedSeconds=[int]$elapsed + backend=$j.active.backend + sampleRate=$j.active.sampleRate + bufferFrames=$j.active.bufferFrames + capturePins=$j.active.capturePins + renderPins=$j.active.renderPins + captureEndpoint=$j.active.captureEndpoint + renderEndpoint=$j.active.renderEndpoint + operatorReportedFxCount=$j.active.operatorReportedFxCount + operatorReportedVst3Name=$j.active.operatorReportedVst3Name + wired=$j.active.wired + operatorObservation=$Result + witness=$Witness + reportFile=$reportFileName + reportSha256=$reportHash + notes=$Notes + } + $j.sessions=@($j.sessions)+@($session) + $j.active=$null + Save-Journal $j + Write-Host ('FAT '+$session.mode+' ended: '+$elapsed+' seconds; observation='+$Result) + if ($null -eq $reportHash) { Write-Warning 'No full report supplied. Evidence will be incomplete.' } + if ($session.mode -in @('DRY_THROUGH_0FX','LIVE_THROUGH_1FX') -and $elapsed -lt 1800) { + Write-Warning 'Under 30 minutes; this does NOT satisfy the matched 0FX/1FX soak comparison.' + } + exit 0 +} +if ($Action -eq 'Summary') { + $missing=@() + $selected=@() + foreach ($rate in @(44100,48000)) { + $byMode=@{} + foreach ($required in @('OUTPUT_ONLY_TONE','CAPTURE_ONLY','DRY_THROUGH_0FX','LIVE_THROUGH_1FX')) { + $matches=@($j.sessions | Where-Object { + [int]$_.sampleRate -eq $rate -and $_.mode -eq $required + } | Sort-Object endedUtc) + $tag=([string]$rate+' '+$required) + if ($matches.Count -lt 1) { $missing+=($tag+': not recorded'); continue } + $s=$matches[-1] + $byMode[$required]=$s + $selected+= $s + # Independent 30-minute evidence cannot trust a typed elapsedSeconds. + # Use UTC-aware instants: a forged 1800s counter with 1s timestamps is + # INCOMPLETE even if all other user-entered fields claim CLEAR. + try { + $startUtc=[DateTimeOffset]::Parse([string]$s.startedUtc,[Globalization.CultureInfo]::InvariantCulture) + $endUtc=[DateTimeOffset]::Parse([string]$s.endedUtc,[Globalization.CultureInfo]::InvariantCulture) + $wallSeconds=($endUtc-$startUtc).TotalSeconds + $claimedSeconds=[double]$s.elapsedSeconds + if ($wallSeconds -lt 0 -or $claimedSeconds -lt 0 -or + [double]::IsNaN($claimedSeconds) -or [double]::IsInfinity($claimedSeconds) -or + [Math]::Abs($wallSeconds-$claimedSeconds) -gt 5) { + $missing+=($tag+': recorded duration inconsistent with UTC start/end') + } + } catch { + $missing+=($tag+': invalid UTC start/end or elapsed duration') + } + if ($s.operatorObservation -ne 'CLEAR' -or + [string]::IsNullOrWhiteSpace([string]$s.witness)) { + $missing+=($tag+': verified CLEAR observation and human witness required') + } + if ([string]::IsNullOrWhiteSpace([string]$s.reportFile) -or + [string]$s.reportSha256 -notmatch '^[0-9a-f]{64}$') { + $missing+=($tag+': native COPY FULL REPORT and digest required') + } else { + $reportName=[string]$s.reportFile + if ([IO.Path]::GetFileName($reportName) -ne $reportName) { + $missing+=($tag+': unsafe report filename') + } else { + $reportInKit=Join-Path $root $reportName + if (-not (Test-Path -LiteralPath $reportInKit -PathType Leaf)) { + $missing+=($tag+': native report file missing') + } elseif ((Get-FatSha256 -Path $reportInKit) -ne + [string]$s.reportSha256) { + $missing+=($tag+': native report SHA256 mismatch') + } + } + } + if ([string]::IsNullOrWhiteSpace([string]$s.backend) -or + [int]$s.bufferFrames -lt 16 -or [int]$s.bufferFrames -gt 16384) { + $missing+=($tag+': actual backend and buffer required') + } + if ($required -ne 'OUTPUT_ONLY_TONE' -and + [string]::IsNullOrWhiteSpace([string]$s.captureEndpoint)) { + $missing+=($tag+': capture endpoint identity missing') + } + if ($required -ne 'CAPTURE_ONLY' -and + [string]::IsNullOrWhiteSpace([string]$s.renderEndpoint)) { + $missing+=($tag+': render endpoint identity missing') + } + # Validate the real pin inventory here too, independently of Start. + # FAT_RUNS.json may be manually edited; two equally empty 0FX/1FX + # inventories must NEVER satisfy the PowerShell-only Summary gate. + foreach ($field in @('capturePins','renderPins')) { + $pinField=$s.PSObject.Properties[$field] + if ($null -eq $pinField -or $null -eq $pinField.Value -or + $pinField.Value -isnot [System.Array]) { + $missing+=($tag+': invalid physical '+$field+' inventory') + continue + } + $seenPin=@{} + foreach ($pin in $pinField.Value) { + $physicalPin=0 + if ($null -eq $pin -or $pin -is [bool] -or + -not [int]::TryParse([string]$pin,[ref]$physicalPin) -or + $physicalPin -lt 0 -or $physicalPin -gt 255) { + $missing+=($tag+': invalid physical '+$field+' ordinal (0..255 required)') + break + } + if ($seenPin.ContainsKey([string]$physicalPin)) { + $missing+=($tag+': duplicate physical '+$field+' ordinal') + break + } + $seenPin[[string]$physicalPin]=$true + } + } + $capturePinCount=@($s.capturePins | Where-Object { $null -ne $_ }).Count + $renderPinCount=@($s.renderPins | Where-Object { $null -ne $_ }).Count + if ($required -eq 'OUTPUT_ONLY_TONE' -and + ($capturePinCount -ne 0 -or $renderPinCount -lt 1)) { + $missing+=($tag+': output-only must have no capture and >=1 render pin') + } + if ($required -eq 'CAPTURE_ONLY' -and + ($renderPinCount -ne 0 -or $capturePinCount -lt 1)) { + $missing+=($tag+': capture-only must have no render and >=1 capture pin') + } + if ($required -in @('DRY_THROUGH_0FX','LIVE_THROUGH_1FX') -and + ($capturePinCount -lt 1 -or $renderPinCount -lt 1)) { + $missing+=($tag+': wired through-mode requires actual capture and render pins') + } + if ($required -in @('DRY_THROUGH_0FX','LIVE_THROUGH_1FX')) { + if ($s.elapsedSeconds -lt 1800 -or -not $s.wired) { + $missing+=($tag+': 1800-second real wired route required') + } + } + if ($required -eq 'LIVE_THROUGH_1FX') { + if ($s.operatorReportedFxCount -ne 1 -or + [string]::IsNullOrWhiteSpace([string]$s.operatorReportedVst3Name)) { + $missing+=($tag+': one real native VST3 insert identity required') + } + } elseif ($s.operatorReportedFxCount -ne 0 -or + -not [string]::IsNullOrWhiteSpace([string]$s.operatorReportedVst3Name)) { + $missing+=($tag+': 0FX/source isolation must have zero active inserts') + } + } + if ($byMode.ContainsKey('DRY_THROUGH_0FX') -and + $byMode.ContainsKey('LIVE_THROUGH_1FX')) { + $zero=$byMode['DRY_THROUGH_0FX'] + $one=$byMode['LIVE_THROUGH_1FX'] + if ($zero.backend -ne $one.backend -or + $zero.sampleRate -ne $one.sampleRate -or + $zero.bufferFrames -ne $one.bufferFrames -or + ($zero.capturePins -join ',') -ne ($one.capturePins -join ',') -or + ($zero.renderPins -join ',') -ne ($one.renderPins -join ',') -or + $zero.captureEndpoint -ne $one.captureEndpoint -or + $zero.renderEndpoint -ne $one.renderEndpoint) { + $missing+=([string]$rate+': 0FX/1FX native device/clock/buffer/pins mismatch') + } + if ([DateTime]::Parse($one.startedUtc).ToUniversalTime() -lt + [DateTime]::Parse($zero.endedUtc).ToUniversalTime()) { + $missing+=([string]$rate+': 1FX started before its 0FX baseline ended') + } + } + } + if ($null -ne $j.active) { $missing+='An active session must be stopped first' } + $state=if ($missing.Count -eq 0) { 'EVIDENCE_READY_FOR_HUMAN_REVIEW' } else { 'EVIDENCE_INCOMPLETE' } + $resultJson=[ordered]@{ + schema='arsonmix.hardware-fat-summary.v1' + sourceSha=$m.sourceCommit + exeSha256=$exeHash + recordedAtUtc=[DateTime]::UtcNow.ToString('o') + status=$state + hardwareCertified=$false + physicalAudibilityVerifiedBySoftware=$false + fxComparisonSource='OPERATOR_REPORTED_ONLY' + unresolvedIssue=15 + sessions=$selected + blockers=$missing + caution='Manual observations are NOT actual callback/DAC proof. Review reports, real 0FX/1FX audio and clock/pins. Capture discontinuity flags are NOT render xruns.' + } + $outPath=Join-Path $root 'FAT_SUMMARY.json' + $resultJson | ConvertTo-Json -Depth 12 | Set-Content -LiteralPath $outPath -Encoding UTF8 + Write-Host ($state+'; wrote '+$outPath+'; certified=false') + Write-Warning 'Inspect report/log files for sensitive device info before sharing. Issue #15 remains open.' + exit 0 +} diff --git a/scripts/m3e_fat_evidence_gate.mjs b/scripts/m3e_fat_evidence_gate.mjs new file mode 100644 index 000000000..f2b71634a --- /dev/null +++ b/scripts/m3e_fat_evidence_gate.mjs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// M3-E: independent field-evidence intake; NEVER a sound generator or DSP. +// Exact EXE/collector byte checks do NOT certify a native callback or DAC. +// No device access, output arming, audio capture, or automatic upload. +import {readFileSync,existsSync} from 'node:fs'; +import {createHash} from 'node:crypto'; +import {join,resolve,basename} from 'node:path'; +import {fileURLToPath} from 'node:url'; + +export const M3E_RATES=Object.freeze([44100,48000]); +export const M3E_MODES=Object.freeze([ + 'OUTPUT_ONLY_TONE','CAPTURE_ONLY','DRY_THROUGH_0FX','LIVE_THROUGH_1FX' +]); +export const M3E_SCHEMA='arsonmix.hardware-fat-field-journal.v1'; +const HEX40=/^[a-f0-9]{40}$/,HEX64=/^[a-f0-9]{64}$/; +const hash=x=>createHash('sha256').update(x).digest('hex'); +const nonempty=v=>typeof v==='string'&&v.trim().length>0; +const uniqueInts=v=>Array.isArray(v)&&v.every(n=>Number.isSafeInteger(n)&&n>=0&&n<=255) + &&new Set(v).size===v.length; +const safeName=v=>typeof v==='string'&&/^[A-Za-z0-9][A-Za-z0-9_.-]{0,179}$/.test(v)&& + basename(v)===v&&v!=='.'&&v!=='..'; +const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b); +const time=v=>typeof v==='string'?Date.parse(v):NaN; +// Windows PowerShell 5.1 -Encoding UTF8 emits a BOM; retain strict JSON+SHA checks. +const readJsonFile=path=>{ + const s=readFileSync(path,'utf8'); + return JSON.parse(s.charCodeAt(0)===0xfeff?s.slice(1):s); +}; +function checkPe64Gui(bytes){ + if(bytes.length<4*1024*1024||bytes.toString('ascii',0,2)!=='MZ') + throw Error('Native EXE missing / under 4 MiB / invalid MZ'); + const pos=bytes.readUInt32LE(0x3c); + if(pos<64||pos>bytes.length-128|| + bytes.toString('ascii',pos,pos+4)!=='PE\0\0'|| + bytes.readUInt16LE(pos+4)!==0x8664|| + bytes.readUInt16LE(pos+24)!==0x20b|| + bytes.readUInt16LE(pos+24+68)!==2) + throw Error('Package target is not an AMD64 PE32+ WINDOWS_GUI EXE'); +} +function readExact(root,filename,expectedHash){ + if(!safeName(filename)||!HEX64.test(expectedHash||'')) + throw Error('Unsafe or non-attested FAT evidence file'); + const absolute=join(root,filename); + if(!existsSync(absolute))throw Error('Missing expected FAT file: '+filename); + const bytes=readFileSync(absolute); + if(hash(bytes)!==expectedHash) + throw Error('SHA256 mismatch: '+filename); + return bytes; +} +export function inspectM3ePackage(root){ + const p=resolve(root),manifest=readJsonFile(join(p,'BUILD_PROVENANCE.json')); + if(manifest.schema!=='arsonmix.native-artifact-provenance.v1'|| + !HEX40.test(manifest.sourceCommit||'')|| + manifest.executable!=='ArSonMix-GUI10CH-P012-Windows-x64.exe'|| + manifest.approvedGuiRoute!=='/preview/'|| + manifest.approvedGuiOutput!=='preview/index.html'|| + !HEX64.test(manifest.approvedGuiPagesSha256||'')|| + !HEX64.test(manifest.approvedGuiNativeHtmlSha256||'')|| + !HEX64.test(manifest.approvedGuiManifestSha256||'')|| + manifest.fatStatus!=='EXPERIMENTAL_NOT_HARDWARE_QUALIFIED') + throw Error('Source/GUI/qualification manifest is not approved and fail-closed'); + const exe=readExact(p,manifest.executable,manifest.exeSha256); + checkPe64Gui(exe); + if(manifest.guiExeBytes!==exe.length)throw Error('Native EXE length not attested'); + readExact(p,'collect_hardware_fat_windows.ps1',manifest.fatCollectorSha256); + readExact(p,'m3e_fat_evidence_gate.mjs',manifest.fatGateSha256); + // The separate Windows verifier performs independent ZIP entry/digest + // inspection. This tool does not claim compressed ZIP verification. + return {sourceSha:manifest.sourceCommit,exeSha256:manifest.exeSha256, + build:'EXE_AND_FAT_BYTES_VERIFIED',zip:'EXTERNAL_WINDOWS_VERIFIER_REQUIRED', + gui:'APPROVED_PREVIEW_PROVENANCE_MANIFEST',manifest}; +} +function verifySession(run,mode,rate,root,blockers){ + const tag=rate+' '+mode; + if(!run||typeof run!=='object'){blockers.push(tag+': missing');return false;} + if(run.mode!==mode||run.sampleRate!==rate)blockers.push(tag+': mode/rate mismatch'); + if(!nonempty(run.backend)||!Number.isInteger(run.bufferFrames)|| + run.bufferFrames<16||run.bufferFrames>16384) + blockers.push(tag+': unverified backend or device buffer'); + if(!uniqueInts(run.capturePins)||!uniqueInts(run.renderPins)) + blockers.push(tag+': invalid actual physical pin inventory'); + const inCount=Array.isArray(run.capturePins)?run.capturePins.length:0; + const outCount=Array.isArray(run.renderPins)?run.renderPins.length:0; + // A manual port ordinal without the actual capture/render endpoint identity + // cannot establish that 0FX and 1FX used the same wired device. + if((mode!=='OUTPUT_ONLY_TONE'&&!nonempty(run.captureEndpoint))|| + (mode!=='CAPTURE_ONLY'&&!nonempty(run.renderEndpoint))) + blockers.push(tag+': actual capture/render endpoint identity missing'); + if((mode==='OUTPUT_ONLY_TONE'&&(inCount!==0||outCount===0))|| + (mode==='CAPTURE_ONLY'&&(outCount!==0||inCount===0))|| + (mode.includes('THROUGH')&&(inCount===0||outCount===0||run.wired!==true))) + blockers.push(tag+': physical I/O configuration is not valid for mode'); + const start=time(run.startedUtc),end=time(run.endedUtc); + const elapsed=run.elapsedSeconds; + if(!Number.isFinite(start)||!Number.isFinite(end)||end5) + blockers.push(tag+': elapsed seconds not consistent with UTC start/end'); + if(mode.includes('THROUGH')&&elapsed<1800) + blockers.push(tag+': 30-minute wired soak not completed'); + if(run.operatorObservation!=='CLEAR') + blockers.push(tag+': operator audio result is not CLEAR'); + if(!nonempty(run.witness))blockers.push(tag+': human witness missing'); + if(!safeName(run.reportFile)||!HEX64.test(run.reportSha256||'')) + blockers.push(tag+': full native report and SHA256 missing'); + else { + try{const bytes=readExact(root,run.reportFile,run.reportSha256); + if(bytes.length<16)throw Error('report too short'); + }catch(error){blockers.push(tag+': report integrity '+error.message);} + } + if(mode==='LIVE_THROUGH_1FX'){ + if(run.operatorReportedFxCount!==1||!nonempty(run.operatorReportedVst3Name)) + blockers.push(tag+': one real native VST3 identity missing'); + }else if(run.operatorReportedFxCount!==0|| + nonempty(run.operatorReportedVst3Name)) + blockers.push(tag+': baseline must have zero active VST3'); + // Capture flags are backend-dependent; neither callback gaps nor WASAPI + // capture DATA_DISCONTINUITY are hardware render starvation counters. + return true; +} +function comparable(a,b){ + return ['backend','sampleRate','bufferFrames','captureEndpoint','renderEndpoint'] + .every(k=>a?.[k]===b?.[k])&& + same(a?.capturePins,b?.capturePins)&&same(a?.renderPins,b?.renderPins); +} +export function inspectM3eJournal(journal,{root='.'}={}){ + const blockers=[],warnings=[]; + if(!journal||journal.schema!==M3E_SCHEMA|| + !HEX40.test(journal.sourceSha||'')|| + !HEX64.test(journal.exeSha256||'')|| + !Array.isArray(journal.sessions)){ + return {physical:'PENDING',blockers:['Invalid or missing FAT field journal'], + warnings,reviewReady:false}; + } + if(journal.active!==null&&journal.active!==undefined) + blockers.push('A running FAT session must be stopped'); + const selected=[]; + for(const rate of M3E_RATES){ + const byMode={}; + for(const mode of M3E_MODES){ + const matches=journal.sessions.filter(s=>s?.sampleRate===rate&&s.mode===mode) + .sort((a,b)=>time(a.endedUtc)-time(b.endedUtc)); + const run=matches.at(-1); + if(run){byMode[mode]=run;selected.push(run);} + verifySession(run,mode,rate,root,blockers); + } + const a=byMode.DRY_THROUGH_0FX,b=byMode.LIVE_THROUGH_1FX; + if(a&&b&&!comparable(a,b)) + blockers.push(rate+': 0FX/1FX must use identical backend, buffer, endpoint and physical pins'); + if(a&&b&&time(b.startedUtc)s?.operatorObservation==='CRACKLE')) + warnings.push('Recorded crackle history exists; #15 requires independent investigation'); + if(journal.sessions.some(s=>![44100,48000].includes(s?.sampleRate))) + warnings.push('Additional unqualified sample-rate sessions were recorded'); + const reviewReady=blockers.length===0; + return {physical:reviewReady?'EVIDENCE_READY_FOR_HUMAN_REVIEW':'PENDING', + reviewReady,blockers,warnings,selectedSessions:selected.length, + actualRenderXrunEvidence:'UNAVAILABLE_UNLESS_SEPARATELY_MEASURED', + operatorObservations:'SELF_REPORTED_NOT_AUTOMATICALLY_CERTIFIED', + hardwareCertified:false}; +} +export function assessM3eFat(root){ + let packageResult; + try{packageResult=inspectM3ePackage(root);} + catch(error){return {build:'BLOCKED',nativePcm:'PENDING_NATIVE_CALLBACK_PROOF', + physical:'PENDING',releaseReady:false,hardwareCertified:false, + blockers:['Package integrity: '+error.message]};} + const journalPath=join(resolve(root),'FAT_RUNS.json'); + if(!existsSync(journalPath)) + return {sourceSha:packageResult.sourceSha,build:packageResult.build, + zip:packageResult.zip,nativePcm:'PENDING_NATIVE_CALLBACK_PROOF', + physical:'PENDING',releaseReady:false,hardwareCertified:false, + blockers:['No physical FAT_RUNS.json: no 44.1/48-kHz field evidence']}; + try{ + const journal=readJsonFile(journalPath); + if(journal.sourceSha!==packageResult.sourceSha|| + journal.exeSha256!==packageResult.exeSha256) + throw Error('Journal source/executable SHA differs from packaged native EXE'); + const physical=inspectM3eJournal(journal,{root:resolve(root)}); + return {sourceSha:packageResult.sourceSha,build:packageResult.build, + zip:packageResult.zip,nativePcm:'PENDING_NATIVE_CALLBACK_PROOF', + physical:physical.physical,releaseReady:false,hardwareCertified:false, + selectedSessions:physical.selectedSessions,blockers:physical.blockers, + warnings:physical.warnings, + renderHardwareXrun:physical.actualRenderXrunEvidence}; + }catch(error){ + return {sourceSha:packageResult.sourceSha,build:packageResult.build, + zip:packageResult.zip,nativePcm:'PENDING_NATIVE_CALLBACK_PROOF', + physical:'PENDING',releaseReady:false,hardwareCertified:false, + blockers:['FAT journal integrity: '+error.message]}; + } +} +// CLI is read-only. Exit 2 only on invalid package; missing hardware logs +// are an explicit PENDING result, not a CI packaging failure and never PASS. +if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){ + const output=assessM3eFat(process.argv[2]||'.'); + console.log(JSON.stringify(output,null,2)); + if(output.build==='BLOCKED')process.exitCode=2; +} diff --git a/scripts/package_native_windows.ps1 b/scripts/package_native_windows.ps1 index 9e546fc1f..a1881b24c 100644 --- a/scripts/package_native_windows.ps1 +++ b/scripts/package_native_windows.ps1 @@ -81,6 +81,15 @@ if (-not (Test-Path -LiteralPath $fatGuide -PathType Leaf)) { } Copy-Item -LiteralPath $readme -Destination (Join-Path $OutputDir "README.md") Copy-Item -LiteralPath $fatGuide -Destination (Join-Path $OutputDir "HARDWARE_FAT_GUIDE.md") +# Selective FAT-only extraction from parked #270, no PCM or GUI production code. +$fatBundleFiles = @("collect_hardware_fat_windows.ps1", "m3e_fat_evidence_gate.mjs") +foreach ($file in $fatBundleFiles) { + $source = Join-Path "scripts" $file + if (-not (Test-Path -LiteralPath $source -PathType Leaf)) { + throw "Missing reviewed M3-E FAT tool: $source" + } + Copy-Item -LiteralPath $source -Destination (Join-Path $OutputDir $file) -Force +} # Same executable, same features. Portable ZIP selects the adjacent Studio/ # data root; installed apps without this file continue using legacy AppData. "ARSONMIX_PORTABLE_WORKSPACE_V1" | @@ -105,6 +114,8 @@ $manifest = [ordered]@{ peFormat = "PE32+" peSubsystem = "WINDOWS_GUI (2)" exeSha256 = (Get-FileHash -LiteralPath $destination -Algorithm SHA256).Hash.ToLowerInvariant() + fatCollectorSha256 = (Get-FileHash -LiteralPath (Join-Path $OutputDir "collect_hardware_fat_windows.ps1") -Algorithm SHA256).Hash.ToLowerInvariant() + fatGateSha256 = (Get-FileHash -LiteralPath (Join-Path $OutputDir "m3e_fat_evidence_gate.mjs") -Algorithm SHA256).Hash.ToLowerInvariant() approvedGuiRoute = $approvedGui.authoritativePagesRoute approvedGuiOutput = $approvedGui.authoritativePagesOutput approvedGuiCanonicalSource = $approvedGui.canonicalSource diff --git a/scripts/verify_native_windows_artifact.ps1 b/scripts/verify_native_windows_artifact.ps1 index fce66be51..f11114569 100644 --- a/scripts/verify_native_windows_artifact.ps1 +++ b/scripts/verify_native_windows_artifact.ps1 @@ -11,7 +11,9 @@ $expected = @( "BUILD_PROVENANCE.json", "HARDWARE_FAT_GUIDE.md", "README.md", - "portable_mode.txt" + "portable_mode.txt", + "collect_hardware_fat_windows.ps1", + "m3e_fat_evidence_gate.mjs" ) foreach ($name in $expected) { if (-not (Test-Path -LiteralPath (Join-Path $OutputDir $name) -PathType Leaf)) { @@ -33,6 +35,29 @@ if (@(Compare-Object -ReferenceObject $expected -DifferenceObject $actual).Count } $manifest = Get-Content -LiteralPath (Join-Path $OutputDir "BUILD_PROVENANCE.json") -Raw -Encoding UTF8 | ConvertFrom-Json +# FAT tools match source bytes, distributed bytes AND the current SHA manifest. +$fatTools = @{ + "collect_hardware_fat_windows.ps1" = [string]$manifest.fatCollectorSha256 + "m3e_fat_evidence_gate.mjs" = [string]$manifest.fatGateSha256 +} +foreach ($filename in $fatTools.Keys) { + if ($fatTools[$filename] -notmatch '^[0-9a-f]{64}$') { + throw "M3-E evidence tool hash missing: $filename" + } + $sourceFile = Join-Path "scripts" $filename + $packageFile = Join-Path $OutputDir $filename + if (-not (Test-Path -LiteralPath $sourceFile -PathType Leaf)) { + throw "Current exact SHA checkout lacks FAT tool: $filename" + } + $sourceHash = (Get-FileHash -LiteralPath $sourceFile -Algorithm SHA256).Hash.ToLowerInvariant() + $distHash = (Get-FileHash -LiteralPath $packageFile -Algorithm SHA256).Hash.ToLowerInvariant() + if ($sourceHash -ne $fatTools[$filename] -or $distHash -ne $fatTools[$filename]) { + throw "FAT tool differs from exact source / manifest: $filename" + } +} +& node scripts/m3e_fat_evidence_gate.mjs $OutputDir +if ($LASTEXITCODE -ne 0) { throw "Independent M3-E FAT bundle verifier failed" } +# No physical FAT journal in a build artifact is PENDING, never a false PASS. # App-only ZIP does not ship an untracked dynamic WebView2Loader.dll. if ($manifest.webView2LoaderMode -ne "JUCE_WEBVIEW2_LOADER_STATIC_LINKED_V1" -or $manifest.guiStartupVerification -ne "WEBVIEW2_PREFLIGHT_AND_AR_MIX_GUI_READY_HANDSHAKE") { @@ -53,7 +78,11 @@ $exePath = Join-Path $OutputDir "ArSonMix-GUI10CH-P012-Windows-x64.exe" $bytes = [System.IO.File]::ReadAllBytes((Resolve-Path -LiteralPath $exePath).Path) if ($bytes.Length -lt 4MB) { throw "REJECT: suspiciously small executable ($($bytes.Length) bytes)" } if ($bytes.Length -ne $manifest.guiExeBytes) { throw "Mismatch: actual EXE size and recorded size" } +if ([Text.Encoding]::ASCII.GetString($bytes,0,2) -ne "MZ") { throw "Invalid EXE MZ signature" } $pe = [BitConverter]::ToInt32($bytes,0x3c) +if ([Text.Encoding]::ASCII.GetString($bytes,$pe,4) -ne ("PE" + [char]0 + [char]0)) { + throw "Invalid EXE PE signature" +} if ($pe -lt 64 -or $pe -ge $bytes.Length - 128) { throw "Invalid PE header offset" } if ([BitConverter]::ToUInt16($bytes,$pe+4) -ne 0x8664 -or [BitConverter]::ToUInt16($bytes,$pe+24) -ne 0x020b -or @@ -186,6 +215,22 @@ try { $stream.Dispose() } if ($inZipHash -ne $appHash) { throw "ZIP entry hash mismatch" } + foreach ($filename in $fatTools.Keys) { + $toolEntry = $zip.GetEntry($filename) + if ($null -eq $toolEntry) { throw "FAT tool missing in verified ZIP: $filename" } + $toolStream = $toolEntry.Open() + $toolHasher = [Security.Cryptography.SHA256]::Create() + try { + $inZipToolHash = [BitConverter]::ToString($toolHasher.ComputeHash($toolStream)).Replace("-","").ToLowerInvariant() + } finally { + $toolStream.Dispose() + $toolHasher.Dispose() + } + if ($inZipToolHash -ne $fatTools[$filename]) { + throw "FAT tool ZIP payload digest differs: $filename" + } + } + foreach ($rel in $factoryZipFiles) { $item = $zip.GetEntry($rel) if ($null -eq $item) { throw "FactoryFX file missing in ZIP: $rel" } diff --git a/tests/m3e_fat_evidence_gate.test.mjs b/tests/m3e_fat_evidence_gate.test.mjs new file mode 100644 index 000000000..18ed40a12 --- /dev/null +++ b/tests/m3e_fat_evidence_gate.test.mjs @@ -0,0 +1,262 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Synthetic package and field-ledger fixtures. Tests MUST NOT certify sound. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {createHash} from 'node:crypto'; +import {mkdtempSync,writeFileSync,readFileSync,rmSync} from 'node:fs'; +import {execFileSync} from 'node:child_process'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import {inspectM3eJournal,inspectM3ePackage,assessM3eFat,M3E_MODES,M3E_RATES} from + '../scripts/m3e_fat_evidence_gate.mjs'; + +const sha=b=>createHash('sha256').update(b).digest('hex'); +const exeName='ArSonMix-GUI10CH-P012-Windows-x64.exe'; +const commit='a'.repeat(40); +const makeTemp=()=>mkdtempSync(join(tmpdir(),'m3e-fat-')); +const clean=(path)=>rmSync(path,{recursive:true,force:true}); +function fakePe(){ + const b=Buffer.alloc(4*1024*1024+16); + b.write('MZ',0,'ascii');b.writeUInt32LE(0x80,0x3c); + b.write('PE\0\0',0x80,'binary'); + b.writeUInt16LE(0x8664,0x84);b.writeUInt16LE(0x20b,0x80+24); + b.writeUInt16LE(2,0x80+24+68); + return b; +} +function makePackage(dir){ + const exe=fakePe(),collector=Buffer.from('synthetic-collector-fixture'), + gate=Buffer.from('synthetic-node-gate-fixture'); + writeFileSync(join(dir,exeName),exe); + writeFileSync(join(dir,'collect_hardware_fat_windows.ps1'),collector); + writeFileSync(join(dir,'m3e_fat_evidence_gate.mjs'),gate); + const m={schema:'arsonmix.native-artifact-provenance.v1', + sourceCommit:commit,executable:exeName,exeSha256:sha(exe),guiExeBytes:exe.length, + approvedGuiRoute:'/preview/',approvedGuiOutput:'preview/index.html', + approvedGuiPagesSha256:'1'.repeat(64),approvedGuiNativeHtmlSha256:'2'.repeat(64), + approvedGuiManifestSha256:'3'.repeat(64), + fatStatus:'EXPERIMENTAL_NOT_HARDWARE_QUALIFIED', + fatCollectorSha256:sha(collector),fatGateSha256:sha(gate)}; + const save=()=>writeFileSync(join(dir,'BUILD_PROVENANCE.json'),JSON.stringify(m)); + save();return {m,save,exe,collector}; +} +function makeSession(mode,rate,index,dir){ + const start=Date.parse('2026-11-05T00:00:00.000Z')+index*3600*1000; + const input=mode==='OUTPUT_ONLY_TONE'?[]:[0,1]; + const output=mode==='CAPTURE_ONLY'?[]:[0,1]; + const name='FAT_REPORT_'+rate+'_'+mode+'.txt',report=Buffer.from( + 'SIMULATED REPORT ONLY -- NEVER HARDWARE EVIDENCE '+rate+' '+mode); + writeFileSync(join(dir,name),report); + return {mode,sampleRate:rate,startedUtc:new Date(start).toISOString(), + endedUtc:new Date(start+1800e3).toISOString(),elapsedSeconds:1800, + backend:'ASIO_MATCHED',bufferFrames:256,capturePins:input,renderPins:output, + captureEndpoint:'verified-input',renderEndpoint:'verified-output', + operatorReportedFxCount:mode==='LIVE_THROUGH_1FX'?1:0, + operatorReportedVst3Name:mode==='LIVE_THROUGH_1FX'?'Vendor Compressor':'', + wired:mode.includes('THROUGH'),operatorObservation:'CLEAR', + witness:'human-operator-manual-only',reportFile:name,reportSha256:sha(report)}; +} +function journal(dir){ + let i=0;const sessions=[]; + for(const rate of M3E_RATES) + for(const mode of M3E_MODES) + sessions.push(makeSession(mode,rate,i++,dir)); + return {schema:'arsonmix.hardware-fat-field-journal.v1', + sourceSha:commit,exeSha256:sha(fakePe()),active:null,sessions}; +} +test('no captured hardware record is PENDING, even if package hashes/PE match',()=>{ + const d=makeTemp();try{ + makePackage(d); + assert.equal(inspectM3ePackage(d).build,'EXE_AND_FAT_BYTES_VERIFIED'); + const r=assessM3eFat(d); + assert.equal(r.physical,'PENDING');assert.equal(r.nativePcm,'PENDING_NATIVE_CALLBACK_PROOF'); + assert.equal(r.hardwareCertified,false);assert.equal(r.releaseReady,false); + }finally{clean(d);} +}); +test('native PE target, original package SHA and approved GUI are required',()=>{ + const d=makeTemp();try{ + const p=makePackage(d); + p.m.approvedGuiRoute='/preview-v2/';p.save(); + assert.equal(assessM3eFat(d).build,'BLOCKED'); + p.m.approvedGuiRoute='/preview/';p.save(); + writeFileSync(join(d,exeName),Buffer.from('not a Windows application')); + assert.equal(assessM3eFat(d).build,'BLOCKED'); + }finally{clean(d);} +}); +test('FAT executable and offline verifier cannot be replaced without hash detection',()=>{ + const d=makeTemp();try{ + makePackage(d); + writeFileSync(join(d,'collect_hardware_fat_windows.ps1'),'tampered'); + assert.match(assessM3eFat(d).blockers.join(' '),/SHA256 mismatch/); + }finally{clean(d);} +}); +test('44.1 and 48 kHz matched 0FX/1FX and source-only modes are review-ready, NEVER PASS',()=>{ + const d=makeTemp();try{ + makePackage(d);const j=journal(d); + const a=inspectM3eJournal(j,{root:d}); + assert.equal(a.physical,'EVIDENCE_READY_FOR_HUMAN_REVIEW'); + assert.equal(a.selectedSessions,8); + writeFileSync(join(d,'FAT_RUNS.json'),JSON.stringify(j)); + const b=assessM3eFat(d); + assert.equal(b.physical,'EVIDENCE_READY_FOR_HUMAN_REVIEW'); + assert.equal(b.releaseReady,false);assert.equal(b.hardwareCertified,false); + assert.equal(b.nativePcm,'PENDING_NATIVE_CALLBACK_PROOF'); + assert.equal(b.renderHardwareXrun,'UNAVAILABLE_UNLESS_SEPARATELY_MEASURED'); + }finally{clean(d);} +}); +test('0FX and 1FX must be matched: device/pin/clock and chronological baseline',()=>{ + const d=makeTemp();try{ + const j=journal(d),one=j.sessions.find(s=>s.sampleRate===48000&&s.mode==='LIVE_THROUGH_1FX'); + one.bufferFrames=512; + assert.match(inspectM3eJournal(j,{root:d}).blockers.join(' '),/identical backend/); + one.bufferFrames=256; + one.startedUtc=new Date('2026-11-05T00:00:00.000Z').toISOString(); + assert.match(inspectM3eJournal(j,{root:d}).blockers.join(' '),/after its completed 0FX baseline/); + }finally{clean(d);} +}); +test('missing 48 kHz, 0FX too short and forged elapsed time all fail closed',()=>{ + const d=makeTemp();try{ + const j=journal(d); + j.sessions=j.sessions.filter(s=>s.sampleRate!==48000); + assert.equal(inspectM3eJournal(j,{root:d}).physical,'PENDING'); + const a=journal(d),dry=a.sessions.find(s=>s.mode==='DRY_THROUGH_0FX'); + dry.elapsedSeconds=60; + assert.match(inspectM3eJournal(a,{root:d}).blockers.join(' '),/30-minute wired soak/); + const b=journal(d);b.sessions[0].elapsedSeconds=1800+60; + assert.match(inspectM3eJournal(b,{root:d}).blockers.join(' '),/not consistent/); + }finally{clean(d);} +}); +test('crackle is never renamed to PASS and prior incident remains visible',()=>{ + const d=makeTemp();try{ + const j=journal(d);j.sessions.find(s=>s.mode==='DRY_THROUGH_0FX').operatorObservation='CRACKLE'; + const r=inspectM3eJournal(j,{root:d}); + assert.equal(r.physical,'PENDING'); + assert.match(r.blockers.join(' '),/not CLEAR/); + assert.match(r.warnings.join(' '),/crackle history/); + }finally{clean(d);} +}); +test('tampered reports and path escapes never become hardware evidence',()=>{ + const d=makeTemp();try{ + const j=journal(d);j.sessions[0].reportSha256='1'.repeat(64); + assert.match(inspectM3eJournal(j,{root:d}).blockers.join(' '),/report integrity SHA256 mismatch/); + const k=journal(d);k.sessions[0].reportFile='../outside.txt'; + assert.match(inspectM3eJournal(k,{root:d}).blockers.join(' '),/report and SHA256 missing/); + }finally{clean(d);} +}); +test('hardware journal binds exact artifact and source SHA, rejects next-build reuse',()=>{ + const d=makeTemp();try{ + makePackage(d);const j=journal(d);j.sourceSha='b'.repeat(40); + writeFileSync(join(d,'FAT_RUNS.json'),JSON.stringify(j)); + const a=assessM3eFat(d); + assert.equal(a.physical,'PENDING');assert.match(a.blockers.join(' '),/source\/executable SHA differs/); + }finally{clean(d);} +}); +test('an active FAT timer, missing native vendor identity or fake VST in 0FX block review',()=>{ + const d=makeTemp();try{ + const j=journal(d);j.active={mode:'DRY_THROUGH_0FX'}; + assert.match(inspectM3eJournal(j,{root:d}).blockers.join(' '),/running FAT session/); + j.active=null; + j.sessions.find(s=>s.mode==='LIVE_THROUGH_1FX').operatorReportedVst3Name=''; + assert.match(inspectM3eJournal(j,{root:d}).blockers.join(' '),/native VST3 identity missing/); + j.sessions.find(s=>s.mode==='DRY_THROUGH_0FX').operatorReportedFxCount=1; + assert.match(inspectM3eJournal(j,{root:d}).blockers.join(' '),/zero active VST3/); + }finally{clean(d);} +}); + +test('physical endpoint IDs are mandatory for wired 0FX/1FX evidence, not just pin ordinals',()=>{ + const d=makeTemp();try{ + const j=journal(d); + for(const s of j.sessions)if(s.mode==='DRY_THROUGH_0FX')s.renderEndpoint=''; + assert.equal(inspectM3eJournal(j,{root:d}).physical,'PENDING'); + assert.match(inspectM3eJournal(j,{root:d}).blockers.join(' '),/actual capture\/render endpoint identity missing/); + }finally{clean(d);} +}); + +test('UTF-8 BOM written by Windows PowerShell 5.1 preserves exact source and report SHA verification',()=>{ + const d=makeTemp();try{ + const p=makePackage(d),bom=Buffer.from([0xef,0xbb,0xbf]); + writeFileSync(join(d,'BUILD_PROVENANCE.json'),Buffer.concat([bom,Buffer.from(JSON.stringify(p.m))])); + assert.equal(inspectM3ePackage(d).build,'EXE_AND_FAT_BYTES_VERIFIED'); + const j=journal(d); + writeFileSync(join(d,'FAT_RUNS.json'),Buffer.concat([bom,Buffer.from(JSON.stringify(j))])); + const r=assessM3eFat(d); + assert.equal(r.physical,'EVIDENCE_READY_FOR_HUMAN_REVIEW'); + assert.equal(r.hardwareCertified,false); + assert.equal(r.releaseReady,false); + }finally{clean(d);} +}); +test('BOM does not weaken malformed-journal rejection or source SHA pinning',()=>{ + const d=makeTemp();try{ + makePackage(d); + writeFileSync(join(d,'FAT_RUNS.json'), '\uFEFF{"schema":bad}'); + const malformed=assessM3eFat(d); + assert.equal(malformed.physical,'PENDING'); + assert.match(malformed.blockers.join(' '),/FAT journal integrity/); + const j=journal(d);j.sourceSha='b'.repeat(40); + writeFileSync(join(d,'FAT_RUNS.json'), '\uFEFF'+JSON.stringify(j)); + const altered=assessM3eFat(d); + assert.equal(altered.physical,'PENDING'); + assert.equal(altered.hardwareCertified,false); + assert.match(altered.blockers.join(' '),/source\/executable SHA differs/); + }finally{clean(d);} +}); + +test('PowerShell Summary validates 44.1/48 kHz real start/end duration rather than a forged 30-minute field',()=>{ + if(process.platform!=='win32')return; + const d=makeTemp();try{ + const p=makePackage(d); + // This is a synthetic source-verified test-only FAT kit, NOT live hardware. + const actualCollector=readFileSync('scripts/collect_hardware_fat_windows.ps1'); + writeFileSync(join(d,'collect_hardware_fat_windows.ps1'),actualCollector); + p.m.fatCollectorSha256=sha(actualCollector);p.save(); + const j=journal(d),journalPath=join(d,'FAT_RUNS.json'); + const bom='\uFEFF'; + const runSummary=()=>{ + writeFileSync(journalPath,bom+JSON.stringify(j)); + execFileSync('powershell.exe',[ + '-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass', + '-File',join(d,'collect_hardware_fat_windows.ps1'), + '-Action','Summary' + ],{cwd:d,timeout:30000,encoding:'utf8'}); + return JSON.parse(readFileSync(join(d,'FAT_SUMMARY.json'),'utf8').replace(/^\uFEFF/,'')); + }; + const good=runSummary(); + assert.equal(good.status,'EVIDENCE_READY_FOR_HUMAN_REVIEW'); + assert.equal(good.hardwareCertified,false); + const forged=j.sessions.find(s=>s.sampleRate===48000&&s.mode==='DRY_THROUGH_0FX'); + forged.endedUtc=new Date(Date.parse(forged.startedUtc)+1000).toISOString(); + const bad=runSummary(); + assert.equal(bad.status,'EVIDENCE_INCOMPLETE'); + assert.equal(bad.hardwareCertified,false); + assert.match(bad.blockers.join(' '),/48000 DRY_THROUGH_0FX: recorded duration inconsistent with UTC start\/end/); + forged.endedUtc=new Date(Date.parse(forged.startedUtc)+1800e3).toISOString(); + for(const mode of ['DRY_THROUGH_0FX','LIVE_THROUGH_1FX']){ + const s=j.sessions.find(x=>x.sampleRate===48000&&x.mode===mode); + s.capturePins=[];s.renderPins=[]; + } + const missingPins=runSummary(); + assert.equal(missingPins.status,'EVIDENCE_INCOMPLETE'); + assert.match(missingPins.blockers.join(' '),/wired through-mode requires actual capture and render pins/); + const dry=j.sessions.find(x=>x.sampleRate===44100&&x.mode==='DRY_THROUGH_0FX'); + dry.capturePins=[0,0]; + const duplicatePins=runSummary(); + assert.equal(duplicatePins.status,'EVIDENCE_INCOMPLETE'); + assert.match(duplicatePins.blockers.join(' '),/duplicate physical capturePins ordinal/); + dry.capturePins=[-1,257]; + const outOfRange=runSummary(); + assert.equal(outOfRange.status,'EVIDENCE_INCOMPLETE'); + assert.match(outOfRange.blockers.join(' '),/invalid physical capturePins ordinal/); + }finally{clean(d);} +}); + +test('field collector uses module-independent streaming SHA256 and preserves exact package provenance',()=>{ + const ps=readFileSync('scripts/collect_hardware_fat_windows.ps1','utf8'); + assert.match(ps,/function Get-FatSha256/); + assert.match(ps,/System\.Security\.Cryptography\.SHA256/); + assert.match(ps,/filePath=\(Resolve-Path -LiteralPath \$Path/); + assert.match(ps,/\$stream\.Dispose\(\)/); + assert.match(ps,/\$hasher\.Dispose\(\)/); + assert.doesNotMatch(ps,/^\s*\$[a-zA-Z]\w*=\(Get-FileHash\b/m); + assert.match(ps,/FAT collector was modified after packaging/); + assert.match(ps,/GUI EXE SHA-256 mismatch/); + assert.match(ps,/native report SHA256 mismatch/); +}); diff --git a/tests/native_artifact_packaging_contract_test.mjs b/tests/native_artifact_packaging_contract_test.mjs index b2f8216f1..126c24cda 100644 --- a/tests/native_artifact_packaging_contract_test.mjs +++ b/tests/native_artifact_packaging_contract_test.mjs @@ -4,6 +4,9 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import {readFileSync} from 'node:fs'; +import {execFileSync} from 'node:child_process'; +// FAT regression tests share the existing Windows Node contract runner. +import './m3e_fat_evidence_gate.test.mjs'; const read=path=>readFileSync(path,'utf8'); const workflow=read('.github/workflows/p1-windows.yml'); const packaging=read('scripts/package_native_windows.ps1'); @@ -108,3 +111,53 @@ test('FAT bundle retains the reviewed first-sound guide and SHA protection',()=> 'CAPTURE_ONLY','COPY FULL REPORT','30 minutes','no separate manual START AUDIO']) assert.ok(quick.includes(text),text); }); + +test('M3-E same-SHA native ZIP carries SHA-pinned FAT tools and no fake hardware claims',()=>{ + const p=read('scripts/package_native_windows.ps1'); + const v=read('scripts/verify_native_windows_artifact.ps1'); + const collector=read('scripts/collect_hardware_fat_windows.ps1'); + const checker=read('scripts/m3e_fat_evidence_gate.mjs'); + assert.match(p,/fatCollectorSha256 =/); + assert.match(p,/fatGateSha256 =/); + assert.match(v,/FAT tool differs from exact source \/ manifest/); + assert.match(v,/FAT tool ZIP payload digest differs/); + assert.match(v,/scripts\/m3e_fat_evidence_gate\.mjs/); + assert.match(collector,/FAT_RUNS\.json/); + assert.match(collector,/EXPERIMENTAL_NOT_HARDWARE_QUALIFIED/); + assert.match(collector,/physicalAudibilityVerifiedBySoftware=\$false/); + assert.match(checker,/PENDING_NATIVE_CALLBACK_PROOF/); + assert.match(checker,/EVIDENCE_READY_FOR_HUMAN_REVIEW/); + assert.doesNotMatch(checker,/hardwareCertified:true/); +}); + +test('FAT PowerShell tools parse on real Windows PowerShell before native build',()=>{ + if (process.platform !== 'win32') return; + for (const file of [ + 'scripts/collect_hardware_fat_windows.ps1', + 'scripts/package_native_windows.ps1', + 'scripts/verify_native_windows_artifact.ps1' + ]) { + const command="$tokens=$null;$parseErrors=$null;" + + "[System.Management.Automation.Language.Parser]::ParseFile('"+file+"',[ref]$tokens,[ref]$parseErrors)|Out-Null;" + + "if($parseErrors.Count -gt 0){$parseErrors|ForEach-Object{Write-Output $_.Message};exit 1}"; + assert.doesNotThrow(()=>execFileSync('powershell.exe', + ['-NoProfile','-NonInteractive','-Command',command], + {cwd:process.cwd(),encoding:'utf8',timeout:15000}), + file+' must have a complete parseable PowerShell AST'); + } +}); + +test('FAT collector requires an exact rate and real endpoints before timers, plus both-rate honest summary',()=>{ + const source=read('scripts/collect_hardware_fat_windows.ps1'); + const verifier=read('scripts/verify_native_windows_artifact.ps1'); + assert.match(source,/SampleRate -notin @\(44100,48000\)/); + assert.match(source,/Real physical capture\/render endpoint identity required before timer starts/); + assert.match(source,/\$_.mode -eq 'DRY_THROUGH_0FX' -and \[int\]\$_.sampleRate -eq \$SampleRate/); + assert.match(source,/foreach \(\$rate in @\(44100,48000\)\)/); + assert.match(source,/verified CLEAR observation and human witness required/); + assert.match(source,/native report SHA256 mismatch/); + assert.match(verifier,/M3-E evidence tool hash missing/); + assert.match(verifier,/FAT tool differs from exact source \/ manifest/); + assert.match(verifier,/FAT tool ZIP payload digest differs/); + assert.doesNotMatch(verifier,/\n\) \{\n\s*throw "M3-E evidence tool hash missing/); +});