Files
adaptive-music/scripts/release.py
T
Jason 95b0427aa1
Validate and generate manual release / package (push) Waiting to run
Adaptive Music v0.8.0 release candidate
2026-12-05 09:40:14 -05:00

213 lines
14 KiB
Python

"""Offline Foundry/Gitea/GitHub release generation. Never contacts a Git host."""
from __future__ import annotations
import argparse
import hashlib
import ipaddress
import json
from pathlib import Path, PurePosixPath
import re
import stat
import subprocess
import sys
import urllib.parse
import zipfile
ROOT=Path(__file__).resolve().parents[1]
DEFAULT_REPOSITORY='https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music'
ZIP_TIME=(2000,1,1,0,0,0)
RELEASE_DOCS=('README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md',
'TESTING.md','PROGRESS.md','HANDOFF.md','USER-ACCEPTANCE.md','LICENSE','THIRD-PARTY-NOTICES')
if str(ROOT/'scripts') not in sys.path:sys.path.insert(0,str(ROOT/'scripts'))
def public_url(value):
parsed=urllib.parse.urlsplit(value)
if parsed.scheme!='https' or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment:
raise ValueError('public HTTPS URL required')
try:
address=ipaddress.ip_address(parsed.hostname)
except ValueError:
if parsed.hostname in ('localhost',) or parsed.hostname.endswith(('.local','.invalid')):raise ValueError('placeholder/local release URL')
else:
if not address.is_global:raise ValueError('private release address')
return value.rstrip('/')
def urls(repository,version,branch='main'):
repository=public_url(repository)
parsed=urllib.parse.urlsplit(repository)
if repository.endswith('.git'):repository=repository[:-4]
if not re.fullmatch(r'[A-Za-z0-9._-]+',branch):raise ValueError('invalid branch')
if not re.fullmatch(r'\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?',version):raise ValueError('invalid release version')
if parsed.hostname=='github.com':
parts=urllib.parse.urlsplit(repository).path.strip('/').split('/')
if len(parts)!=2:raise ValueError('GitHub owner/repo required')
manifest=f'https://raw.githubusercontent.com/{parts[0]}/{parts[1]}/{branch}/module.json'
else:manifest=f'{repository}/raw/branch/{branch}/module.json'
return {'url':repository,'manifest':manifest,'download':f'{repository}/releases/download/v{version}/adaptive-music.zip'}
def release_manifest(repository=DEFAULT_REPOSITORY,version=None,branch='main'):
manifest=json.loads((ROOT/'module.json').read_text())
if version is not None and version!=manifest['version']:raise ValueError('tag/version must match source module.json')
manifest['version']=version or manifest['version'];manifest.update(urls(repository,manifest['version'],branch))
validate_manifest(manifest);return manifest
def validate_manifest(manifest):
if not isinstance(manifest,dict) or any(k not in manifest for k in ('id','authors','compatibility','version','url','manifest','download','esmodules')):raise ValueError('incomplete manifest')
if manifest.get('id')!='adaptive-music' or manifest.get('authors')!=[{'name':'CheddahBoxMB'}]:raise ValueError('module identity mismatch')
if manifest.get('compatibility',{}).get('minimum')!='14' or manifest['compatibility'].get('maximum')!='14' or 'verified' in manifest['compatibility']:raise ValueError('unsupported compatibility claim')
if manifest.get('relationships',{}).get('requires',[]) or manifest.get('systems'):raise ValueError('mandatory system/module dependency')
expected=urls(manifest['url'],manifest['version'])
for key in ('manifest','download'):
public_url(manifest[key])
if manifest[key]!=expected[key]:raise ValueError('manifest/update URL mismatch')
if 'v'+manifest['version'] not in manifest['download']:raise ValueError('unversioned download')
def module_files():
names=['module.json','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES']
for directory,pattern in [('src','*.mjs'),('styles','*.css'),('licenses','*'),('vendor','*')]:
names.extend(str(p.relative_to(ROOT)) for p in sorted((ROOT/directory).rglob(pattern)) if p.is_file())
return names
def write_zip(path,entries):
path.parent.mkdir(parents=True,exist_ok=True)
with zipfile.ZipFile(path,'w',zipfile.ZIP_DEFLATED) as archive:
for name,data in sorted(entries.items()):
info=zipfile.ZipInfo(name,ZIP_TIME);info.compress_type=zipfile.ZIP_DEFLATED;info.external_attr=0o100644<<16
archive.writestr(info,data)
def module_entries(manifest):
result={}
for name in module_files():
path=ROOT/name
if path.is_symlink():raise ValueError('package symlink refused')
data=(json.dumps(manifest,indent=2)+'\n').encode() if name=='module.json' else path.read_bytes()
if name.endswith('.mjs') and (b'node:' in data or b"from '../../gateway/" in data):raise ValueError('server code in browser package')
result['adaptive-music/'+name]=data
return result
def validate_package(path,manifest=None):
from audit_repository import findings
with zipfile.ZipFile(path) as archive:
names=archive.namelist()
expected={'adaptive-music/'+name for name in module_files()}
if len(names)!=len(set(names)) or set(names)!=expected or any(
str(PurePosixPath(n))!=n or '\\' in n or any(part in ('..','.local','node_modules','gateway') for part in PurePosixPath(n).parts)
for n in names
) or any(
stat.S_IFMT(item.external_attr>>16) not in (0,stat.S_IFREG) for item in archive.infolist()
):raise ValueError('unsafe or incomplete package inventory')
actual=json.loads(archive.read('adaptive-music/module.json'));validate_manifest(actual)
if manifest and actual!=manifest:raise ValueError('embedded and standalone manifest mismatch')
for name in names:
data=archive.read(name);problems=findings(name,data.decode(errors='replace'))
if problems:raise ValueError('private content in release: '+name)
if name.endswith('.mjs'):
text=data.decode();relative_imports=re.findall(r"""\b(?:from\s*|import\s*(?:\(\s*)?)['"](\.[^'"]+)['"]""",text)
import posixpath
for relative in relative_imports:
resolved=posixpath.normpath(posixpath.join(posixpath.dirname(name),relative))
if resolved not in names:raise ValueError('missing browser import: '+resolved)
for asset in actual['esmodules']+actual.get('styles',[]):
if 'adaptive-music/'+asset not in names:raise ValueError('missing manifest asset')
provenance=json.loads(archive.read('adaptive-music/vendor/provenance.json'))
if provenance!=json.loads((ROOT/'vendor/provenance.json').read_bytes()):raise ValueError('SDK provenance mismatch')
if hashlib.sha256(archive.read('adaptive-music/vendor/sendspin-5.0.0.mjs')).hexdigest()!=provenance['sha256']:raise ValueError('SDK bundle hash mismatch')
required=['licenses/VGM-MIT.txt','licenses/Apache-2.0.txt','licenses/vendor/-sendspin-sendspin-js.txt','licenses/vendor/-noble-ciphers.txt','licenses/vendor/-noble-curves.txt','licenses/vendor/-noble-hashes.txt']
if any('adaptive-music/'+name not in names for name in required):raise ValueError('missing license')
return actual
def runtime_assets_sha256(path):
"""Fingerprint the installed browser assets independently of documentation."""
digest=hashlib.sha256()
prefixes=('adaptive-music/src/','adaptive-music/styles/','adaptive-music/vendor/')
with zipfile.ZipFile(path) as archive:
for name in sorted(n for n in archive.namelist() if n.startswith(prefixes)):
digest.update(name.encode('utf8')+b'\0')
digest.update(hashlib.sha256(archive.read(name)).digest())
return digest.hexdigest()
def local_revision():
try:return subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
except (subprocess.CalledProcessError,FileNotFoundError):
file=ROOT/'SOURCE_REVISION.txt'
return file.read_text().strip() if file.is_file() else 'unknown (source archive without Git metadata)'
def source_revision_status(manifest):
try:
status=subprocess.check_output(['git','status','--porcelain=v1','--untracked-files=all'],
cwd=ROOT,text=True,stderr=subprocess.DEVNULL)
except (subprocess.CalledProcessError,FileNotFoundError):
return 'source archive without Git metadata'
if status:
return 'working tree changes included; sourceCommit identifies the base revision'
manifest_bytes=(json.dumps(manifest,indent=2)+'\n').encode()
if (ROOT/'module.json').read_bytes()!=manifest_bytes:
return 'clean Git checkout with generated release manifest'
return 'clean Git checkout'
def source_entries(manifest):
from audit_repository import findings
try:names=subprocess.check_output(['git','ls-files','-z','--cached','--others','--exclude-standard'],cwd=ROOT,stderr=subprocess.DEVNULL).decode().split('\0')
except (subprocess.CalledProcessError,FileNotFoundError):
root_files={*RELEASE_DOCS,'.gitignore','AGENTS.md','MODEL-EVALUATION.md',
'module.json','package.json','package-lock.json','SOURCE_REVISION.txt'}
names=[p.name for p in ROOT.iterdir() if p.is_file() and p.name in root_files]
for directory in ('src','styles','licenses','vendor','gateway','scripts','tests','evidence','.github','.gitea'):
names.extend(str(p.relative_to(ROOT)) for p in (ROOT/directory).rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.suffix!='.pyc')
entries={}
for name in sorted(set(filter(None,names))):
path=ROOT/name
if name.startswith(('.local/','dist/','node_modules/','.git/')) or path.is_symlink():raise ValueError('private/unsafe source path')
if path.is_file():
data=path.read_bytes()
if findings(name,data.decode(errors='replace')):raise ValueError('private material in source: '+name)
entries['adaptive-music-source/'+name]=data
entries['adaptive-music-source/module.json']=(json.dumps(manifest,indent=2)+'\n').encode()
entries['adaptive-music-source/SOURCE_REVISION.txt']=(local_revision()+'\n').encode()
return entries
def build_release(repository=DEFAULT_REPOSITORY,version=None,output=None):
manifest=release_manifest(repository,version);version=manifest['version'];output=output or ROOT/'dist/releases'/('v'+version)
output=Path(output).resolve()
if output.is_relative_to(ROOT) and not output.is_relative_to(ROOT/'dist'):raise ValueError('in-repository output must be under ignored dist/')
output.mkdir(parents=True,exist_ok=True)
allowed={*RELEASE_DOCS,'adaptive-music.zip','module.json','adaptive-music-source.zip','release.json',
'SHA256SUMS',f'adaptive-music-release-v{version}.zip',f'adaptive-music-release-v{version}.zip.sha256'}
evidence_name=f'evidence/v{version}-live.json'
if (ROOT/evidence_name).is_file():allowed.add(evidence_name)
allowed.update(str(p.relative_to(ROOT)) for p in (ROOT/'licenses').rglob('*') if p.is_file())
for file in output.rglob('*'):
if file.is_symlink() or file.is_file() and str(file.relative_to(output)) not in allowed:raise ValueError('unmanaged file in release output')
write_zip(output/'adaptive-music.zip',module_entries(manifest));validate_package(output/'adaptive-music.zip',manifest)
(output/'module.json').write_text(json.dumps(manifest,indent=2)+'\n')
source=source_entries(manifest)
write_zip(output/'adaptive-music-source.zip',source)
evidence=source.get(f'adaptive-music-source/{evidence_name}')
if evidence is not None:
(output/evidence_name).parent.mkdir(parents=True,exist_ok=True)
(output/evidence_name).write_bytes(evidence)
for name in RELEASE_DOCS:(output/name).write_bytes(source['adaptive-music-source/'+name])
for path in (ROOT/'licenses').rglob('*'):
if path.is_file():target=output/path.relative_to(ROOT);target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(path.read_bytes())
metadata={'version':version,'repository':manifest['url'],'manifest':manifest['manifest'],'download':manifest['download'],
'sourceCommit':local_revision(),'sourceRevisionStatus':source_revision_status(manifest),'sourceArchiveSHA256':hashlib.sha256((output/'adaptive-music-source.zip').read_bytes()).hexdigest(),'runtimeAssetsSHA256':runtime_assets_sha256(output/'adaptive-music.zip'),'destinationStatus':'user-reported existing Gitea; never contacted by this builder','networkAccessRequired':False}
acceptance=json.loads(evidence) if evidence is not None else {}
metadata['foundryLiveVerified']=acceptance.get('serverInstalledExactVersion') is True
metadata['maCoreFlowDemonstrated']=acceptance.get('completedCoreRunPassed') is True
metadata['macPrivateRouteVerified']=acceptance.get('macPrivateRouteVerified') is True
metadata['publicationReady']=acceptance.get('publicationReady') is True and all(
metadata[key] for key in ('foundryLiveVerified','maCoreFlowDemonstrated','macPrivateRouteVerified')
)
metadata['acceptanceStatus']='staged; exact installed version and device acceptance pending' if not metadata['publicationReady'] else 'operator acceptance recorded'
(output/'release.json').write_text(json.dumps(metadata,indent=2)+'\n')
files={str(p.relative_to(output)):p.read_bytes() for p in output.rglob('*') if p.is_file() and p.name not in ('SHA256SUMS',) and not p.name.startswith('adaptive-music-release-')}
(output/'SHA256SUMS').write_text(''.join(f'{hashlib.sha256(data).hexdigest()} {name}\n' for name,data in sorted(files.items())))
files['SHA256SUMS']=(output/'SHA256SUMS').read_bytes();bundle=output/f'adaptive-music-release-v{version}.zip';write_zip(bundle,files)
(output/(bundle.name+'.sha256')).write_text(hashlib.sha256(bundle.read_bytes()).hexdigest()+' '+bundle.name+'\n')
return bundle
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--repository',default=DEFAULT_REPOSITORY);parser.add_argument('--version');parser.add_argument('--output',type=Path);parser.add_argument('--validate',type=Path);parser.add_argument('--runtime-sha256',type=Path);args=parser.parse_args()
if args.validate:validate_package(args.validate);print('PASS: standalone Foundry package, imports, manifest/update URLs, privacy and licenses')
elif args.runtime_sha256:validate_package(args.runtime_sha256);print(runtime_assets_sha256(args.runtime_sha256))
else:print(build_release(args.repository,args.version,args.output))