Support bridge-owned TALK layers and recover free P4a candidate

This commit is contained in:
zenord
2026-10-13 04:35:33 +08:00
parent fcc55b8370
commit a53600db92
22 changed files with 18696 additions and 43 deletions
+2 -1
View File
@@ -59,7 +59,8 @@ def main():
try:
for i,row in enumerate(m['patches']):
raw=pipe.stdout.read(480*848*4);assert len(raw)==480*848*4
if i not in (0,26,43,52,69,96):continue
fixed=(0,26,43,52,69,96) if len(m['patches'])==97 else tuple(sorted({round(k*(len(m['patches'])-1)/5) for k in range(6)}))
if i not in fixed:continue
body=np.frombuffer(raw,np.uint8).reshape(848,480,4)
for level in (0,1,2,3,4):
patch=np.asarray(Image.open(args.runtime/row['levels'][level]['path']).convert('RGBA'))
+4 -2
View File
@@ -73,8 +73,10 @@ for name, main, real in suites:
index_path=args.index_manifest.resolve(strict=True)
raw=index_path.read_bytes();digest=hashlib.sha256(raw).hexdigest()
data=json.loads(raw);runtimes={};hashes={}
for row in data['conversationPackages']:
reference=row['runtimeManifest'];path=reference['path']
references=[row['runtimeManifest'] for row in data['conversationPackages']]
references += [edge['mouthRuntimeManifest'] for edge in data['edges'] if 'mouthRuntimeManifest' in edge]
for reference in references:
path=reference['path']
runtime_path=(index_path.parent/path).resolve(strict=True)
if not runtime_path.is_relative_to(index_path.parent): raise ValueError('Runtime path escape')
runtime_raw=runtime_path.read_bytes();runtime_hash=hashlib.sha256(runtime_raw).hexdigest()
+350
View File
@@ -0,0 +1,350 @@
#!/usr/bin/env python3
"""Bounded CPU-only recovery export; no AI, no models, never edits the source pack."""
import argparse
import copy
from decimal import Decimal
from fractions import Fraction
import hashlib
import json
import math
from pathlib import Path
import shutil
import subprocess
import numpy as np
from PIL import Image, ImageDraw, ImageFont
ROOT = Path(__file__).resolve().parents[1]
FFMPEG = '/home/ubuntu/gori-bin/ffmpeg'
FFPROBE = '/home/ubuntu/miniconda3/envs/gori-speech/bin/ffprobe'
LEVELS = np.array([0, .25, .5, .75, 1.])
def require(condition, reason):
if not condition:
raise ValueError(reason)
def digest(path):
with Path(path).open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
def write_json(path, data):
with path.open('x') as stream:
json.dump(data, stream, indent=2)
stream.write('\n')
def safe_file(root, name):
require(isinstance(name, str) and not name.startswith('/') and
all(part not in ('', '.', '..') for part in name.split('/')), 'relative file required')
path = (root/name).resolve(strict=True)
require(path.is_relative_to(root.resolve()) and path.is_file(), 'file escape')
return path
def decode(path, body):
probe = json.loads(subprocess.check_output([FFPROBE, '-v', 'error', '-show_streams',
'-show_frames', '-of', 'json', str(path)], timeout=60))
require(len(probe['streams']) == 1, 'silent single video track required')
stream = probe['streams'][0]
require(stream['codec_name'] == 'h264' and (stream['width'], stream['height']) == (480, 848), 'body shape/codec')
us = lambda value: int((Decimal(value)*1_000_000).to_integral_value())
pts = [us(frame['best_effort_timestamp_time']) for frame in probe['frames']]
require(pts == body['ptsUs'] and len(pts) == body['frameCount'], 'actual N/PTS mismatch')
require(us(stream['duration']) == body['durationUs'] and
Fraction(stream['r_frame_rate']) == Fraction(body['fpsNumerator'], body['fpsDenominator']), 'actual timing mismatch')
require(digest(path) == body['sha256'], 'body bytes changed')
raw = subprocess.check_output([FFMPEG, '-nostdin', '-v', 'error', '-xerror', '-i', str(path),
'-map', '0:v:0', '-pix_fmt', 'rgb24', '-f', 'rawvideo', '-'], timeout=60)
frames = np.frombuffer(raw, np.uint8).reshape(-1, 848, 480, 3)
require(len(frames) == body['frameCount'], 'full decode N')
return frames
def make_patches(frames, pts, destination):
"""Same source-seam deformation method as owner runtime04, local ROI arithmetic."""
first = frames[0].astype(float)
roi = first[103:137, 202:265]
score = roi[:, :, 0]-roi[:, :, 1]+.20*(255-roi.mean(axis=2))
ys, xs = np.where(score > np.percentile(score, 88))
cx, cy = float(np.median(xs)+202), float(np.median(ys)+103)
require(210 < cx < 252 and 111 < cy < 133, 'own first-frame lip center outside fixture bounds')
x0, x1, y0, y1 = int(cx-31), int(cx+32), int(cy-30), int(cy+17)
reference = first[y0:y1, x0:x1].mean(axis=2)
yy, xx = np.mgrid[y0:y1, x0:x1]
tracking_mask = ((yy < cy-9) | (xx < cx-22) | (xx > cx+23)) & (yy < cy+12)
patches, tracks = [], []
for i, frame in enumerate(frames):
f = frame.astype(float)
gray = f.mean(axis=2)
scores = {}
for dy in range(-8, 9):
for dx in range(-14, 15):
diff = gray[y0+dy:y1+dy, x0+dx:x1+dx]-reference
diff -= diff[tracking_mask].mean()
scores[dx, dy] = float((diff[tracking_mask]**2).mean())
dx, dy = min(scores, key=scores.get)
require(abs(dx) < 14 and abs(dy) < 8, 'tracking hit search boundary; manual review required')
cxi, cyi = cx+dx, cy+dy
left, right = int(round(cxi-15)), int(round(cxi+15))
curve = []
for x in range(left, right+1):
rows = np.arange(int(round(cyi-4)), int(round(cyi+5)))
pixels = f[rows, x]
darkness = pixels.mean(axis=1)-.6*(pixels[:, 0]-pixels[:, 1])
curve.append(float(rows[np.argmin(darkness)]))
curve = np.convolve(np.pad(curve, 2, mode='edge'), np.ones(5)/5, mode='valid')
# These bounds contain the same mask>.005 support as the owner's full-frame computation.
Y, X = np.mgrid[int(cyi)-22:int(cyi)+23, int(cxi)-19:int(cxi)+20]
seam = np.interp(X, np.arange(left, right+1), curve)
dist = Y-seam
taper = np.clip(1-((X-cxi)/17)**2, 0, 1)**1.5
vertical = np.exp(-(dist/5)**2)
mask = taper*vertical
support_y, support_x = np.where(mask > .005)
ys = slice(support_y.min(), support_y.max()+1)
xs = slice(support_x.min(), support_x.max()+1)
bx, by = int(X[ys, xs].min()), int(Y[ys, xs].min())
height, width = mask[ys, xs].shape
require(width <= 128 and height <= 128, 'patch shape cap')
levels = []
for li, aperture in enumerate(LEVELS):
gap = aperture*1.1*taper
source_y = np.clip(Y-np.where(dist >= 0, gap*.65, -gap*.35)*vertical, 0, 847)
j0 = np.floor(source_y).astype(int)
j1 = np.minimum(j0+1, 847)
fraction = (source_y-j0)[..., None]
warped = f[j0, X]*(1-fraction)+f[j1, X]*fraction
seam_rows = np.clip(np.rint(seam).astype(int), 0, 847)
interior = f[seam_rows, X]*.65
inside = np.clip((gap*.55-np.abs(dist-.05*aperture))/.6, 0, 1)*taper
warped = warped*(1-inside[..., None])+interior*inside[..., None]
if li == 0:
warped = f[Y, X]
rgba = np.dstack([np.rint(warped[ys, xs]).astype(np.uint8),
np.rint(mask[ys, xs]*255).astype(np.uint8)])
name = f'patches/{i:03d}-l{li}.png'
Image.fromarray(rgba).save(destination/name)
levels.append({'levelIndex': li, 'aperture': float(aperture), 'path': name,
'sha256': digest(destination/name)})
patches.append({'frameIndex': i, 'ptsUs': pts[i], 'x': bx, 'y': by,
'width': width, 'height': height, 'path': levels[4]['path'], 'sha256': levels[4]['sha256'],
'levels': levels, 'observedLipSeamPixels': curve.tolist(), 'seamSourceXRange': [left, right+1]})
tracks.append({'frameIndex': i, 'ptsUs': pts[i], 'dx': dx, 'dy': dy,
'ssd': scores[dx, dy], 'searchBoundary': False})
return patches, tracks, [cx, cy]
def compose(frame, patch, runtime, level):
if level == 0:
return frame
rgba = np.asarray(Image.open(runtime/patch['levels'][level]['path']).convert('RGBA'))
x, y, w, h = (patch[k] for k in ('x', 'y', 'width', 'height'))
output = frame.copy()
alpha = rgba[:, :, 3:4]/255.
output[y:y+h, x:x+w] = np.clip(np.rint(frame[y:y+h, x:x+w]*(1-alpha)+rgba[:, :, :3]*alpha), 0, 255).astype(np.uint8)
return output
def encode(frames, path, width=480, height=848):
proc = subprocess.Popen([FFMPEG, '-nostdin', '-n', '-v', 'error', '-xerror', '-f', 'rawvideo',
'-pix_fmt', 'rgb24', '-s', f'{width}x{height}', '-r', '24', '-i', '-', '-an', '-c:v',
'libx264', '-threads', '2', '-crf', '16', '-pix_fmt', 'yuv420p', '-g', '12', '-movflags', '+faststart', str(path)], stdin=subprocess.PIPE)
try:
for frame in frames:
proc.stdin.write(frame.tobytes())
finally:
proc.stdin.close()
require(proc.wait() == 0, 'preview encoder failed')
subprocess.run([FFMPEG, '-nostdin', '-v', 'error', '-xerror', '-i', str(path), '-f', 'null', '-'], check=True, timeout=60)
def previews(index, output, bodies, runtimes):
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 13)
all_items, trace = [], []
for edge in index['edges']:
if edge.get('nativeLoop'):
continue
own = runtimes['bridge:'+edge['id']]
source = runtimes[edge['from']]
target = runtimes[edge['to']]
items = [(edge['from'], (edge['fromFrame']-k) % len(bodies[edge['from']])) for k in range(47, -1, -1)]
items += [('bridge:'+edge['id'], i) for i in range(len(bodies['bridge:'+edge['id']]))]
items += [(edge['to'], (edge['toFrame']+k) % len(bodies[edge['to']])) for k in range(48)]
start = len(all_items)
all_items.extend(items)
trace.append({'edgeId': edge['id'], 'startFrame': start, 'bridgeStartFrame': start+48,
'bridgeEndFrameExclusive': start+48+25, 'endFrameExclusive': len(all_items),
'syntheticTalk': True, 'realPCM': False, 'realDevice': 'not_run'})
# Both junctions, own layers kept at the same fixed aperture for seam review.
dense = items[36:60]+items[61:85]
require(len(dense) == 48, 'dense junction inventory')
for view, box, width in [('face', (170, 45, 295, 165), 250), ('full', (0, 0, 480, 848), 180)]:
height = round((box[3]-box[1])*width/(box[2]-box[0]))
sheet = Image.new('RGB', (4*width, 12*(height+24)+26), (20, 20, 25))
draw = ImageDraw.Draw(sheet)
draw.text((3, 3), edge['id']+' own mouths at level3 / candidate', font=font, fill='white')
for k, (key, i) in enumerate(dense):
root, manifest = runtimes[key]
frame = compose(bodies[key][i], manifest['patches'][i], root, 3)
x, y = k % 4*width, k//4*(height+24)+26
sheet.paste(Image.fromarray(frame).crop(box).resize((width, height)), (x, y))
draw.text((x+3, y+height+2), f'{key[:19]} f{i}', font=font, fill='white')
sheet.save(output/'review'/f'{edge["id"]}-{view}-talk-junctions.png')
# All25 frames and all5 levels: engineering localization/shape evidence.
sheet = Image.new('RGB', (5*180, 25*144), (20, 20, 25))
draw = ImageDraw.Draw(sheet)
for i in range(25):
for level in range(5):
frame = compose(bodies['bridge:'+edge['id']][i], own[1]['patches'][i], own[0], level)
sheet.paste(Image.fromarray(frame).crop((190, 98, 272, 148)).resize((180, 110)), (level*180, i*144))
draw.text((level*180+2, i*144+112), f'f{i} L{level} / own1.1px', font=font, fill='white')
sheet.save(output/'review'/f'{edge["id"]}-all25-fivelevels.png')
# Four isolated five-second windows, each has true source→bridge→target cursors.
# Between windows the cut is explicitly a new independent fixture, not a graph edge.
require(len(all_items) == 484, '20.167s preview frame count')
def render(annotated=False, mouth=False):
for k, (key, i) in enumerate(all_items):
root, manifest = runtimes[key]
# Synthetic TALK crosses every bridge; one phase per window, not reset at boundaries.
local = k % 121
alpha = .5-.5*math.cos(math.pi*local/5) if local < 6 else 1-.88*math.sin(2*math.pi*((local-6) % 12)/11)**2
level = int(np.argmin(np.abs(LEVELS-alpha)))
frame = compose(bodies[key][i], manifest['patches'][i], root, level)
if annotated:
image = Image.fromarray(frame.copy())
draw = ImageDraw.Draw(image)
draw.rectangle((0, 0, 479, 58), fill=(20, 20, 25))
draw.text((3, 3), 'SYNTHETIC TALK / NO PCM / NOT DEVICE', font=font, fill='white')
draw.text((3, 21), f'window{k//121+1} t{k/24:.3f}s {key[:31]} f{i} L{level}', font=font, fill='white')
draw.text((3, 39), 'independent windows; ownbody/ownbridge; pending Pi', font=font, fill='white')
frame = np.asarray(image)
if mouth:
frame = np.asarray(Image.fromarray(frame).crop((190, 98, 272, 148)).resize((656, 400)))
yield frame
encode(render(), output/'review/bridge-talk-20s-clean.mp4')
encode(render(annotated=True), output/'review/bridge-talk-20s-annotated.mp4')
encode(render(mouth=True), output/'review/bridge-talk-20s-mouth.mp4', 656, 400)
write_json(output/'review/synthetic-intent-trace.json', {'fps': 24, 'frames': len(all_items), 'durationSeconds': len(all_items)/24,
'windowCuts': 'four independent fixtures, not continuous graph edges', 'windows': trace,
'TTSintentOnly': True, 'audio': False, 'naturalness': 'not_certified'})
def finalize(source, source_sha, output, old):
index=copy.deepcopy(old)
bridge_reports=[]
for edge in index['edges']:
if edge.get('nativeLoop'): continue
path=output/'runtime-bridges'/edge['id']/'manifest.json'
runtime=json.loads(path.read_bytes());body=runtime['body']
require(body['sha256']==edge['clip']['sha256'] and body['ptsUs']==edge['clip']['ptsUs'],'recovery binding drift')
require(digest(path.parent/body['path'])==body['sha256'],'recovery body drift')
for patch in runtime['patches']:
for level in patch['levels']:
require(digest(path.parent/level['path'])==level['sha256'],'recovery patch drift')
edge['mouthRuntimeManifest']={'path':str(path.relative_to(output)),'sha256':digest(path)}
edge['mouthAllowed']=True
bridge_reports.append({'edgeId':edge['id'],'bodySha256':body['sha256'],'N':body['frameCount'],'ptsUs':body['ptsUs'],'runtimeSha256':digest(path),'ownPatchCount':len(runtime['patches'])*5,'rgbaBytes':sum(p['width']*p['height']*4*5 for p in runtime['patches']),'firstFrameLipCenter':runtime['sourceSpecificLipLocalization']['firstFrameCenter']})
for row in old['files']:
require(digest(safe_file(output,row['path']))==row['sha256'],'copied source payload drift')
for name in ('bridge-talk-20s-clean.mp4','bridge-talk-20s-annotated.mp4','bridge-talk-20s-mouth.mp4'):
require((output/'review'/name).stat().st_size>0,'preview absent')
(output/'docs').mkdir(exist_ok=True)
write_json(output/'docs/free-recovery-provenance.json', {'sourceIndexSha256': source_sha,
'exportScriptSha256': digest(Path(__file__)), 'methodReusedFrom': 'asset owner build_own_mouth_current.py',
'methodSourceSha256': digest(source.parent.parent/'docs/build_own_mouth_current.py'),
'sourcePayloadUnmodified': True, 'reusedPixelsFromEndpoint': False,
'controlCurves': 'same authored scalar phase contract; every bridge has own serialized state PTS; only control timing reused',
'sourceVideosUnchanged': True, 'AIcalls': 0, 'knownFeeUSD': 0, 'bridgeReports': bridge_reports,
'naturalness': 'pending_independent_Pi', 'realDevice': 'not_run'})
index['reviewStatus'] = 'recovery_bridge_own_mouth_pending_new_exact_Pi_pin'
index['advancedGateKeep'] = False
index['publishApproval'] = False
index['sceneTimeline'] = 'See review/synthetic-intent-trace.json; four separate TALK windows, not full graph execution'
index['files'] = [{'path': str(path.relative_to(output)), 'sha256': digest(path), 'bytes': path.stat().st_size}
for path in sorted(output.rglob('*')) if path.is_file() and path != output/'manifest.json']
write_json(output/'manifest.json', index)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source-manifest', type=Path, required=True)
parser.add_argument('--source-sha', required=True)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--finish-existing',action='store_true',help='Finish metadata only after an interrupted export; all original/own file hashes still verified')
args = parser.parse_args()
source = args.source_manifest.resolve(strict=True)
output = args.output.resolve()
require(digest(source) == args.source_sha, 'old index drift')
require(not output.is_relative_to(source.parent) and not (output/'manifest.json').exists(), 'new independent index required')
require(args.finish_existing or not output.exists(),'existing output preserved; explicit metadata finish only')
old = json.loads(source.read_bytes())
require(old['actions'] == [] and len(old['edges']) == 7, 'only current partial P4a recovery')
for row in old['files']:
path = safe_file(source.parent, row['path'])
require(digest(path) == row['sha256'] and path.stat().st_size == row['bytes'], 'old indexed file drift')
if args.finish_existing:
finalize(source,args.source_sha,output,old)
require(digest(source)==args.source_sha,'old index drift')
print('RECOVERY_BRIDGE_INDEX_READY',digest(output/'manifest.json'),flush=True)
return
output.mkdir(parents=True)
for row in old['files']:
destination = output/row['path']
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(safe_file(source.parent, row['path']), destination)
index = copy.deepcopy(old)
bodies, runtimes = {}, {}
for row in index['conversationPackages']:
path = output/row['runtimeManifest']['path']
runtime = json.loads(path.read_bytes())
bodies[row['id']] = decode(path.parent/runtime['body']['path'], runtime['body'])
runtimes[row['id']] = (path.parent, runtime)
template = runtimes[index['fallbackPackageId']][1]
bridge_reports = []
for edge in index['edges']:
if edge.get('nativeLoop'):
continue
clip = edge['clip']
require(clip['frameCount'] == 25, 'current bridge actual25 required')
frames = decode(output/clip['path'], clip)
destination = output/'runtime-bridges'/edge['id']
for folder in ('body', 'patches', 'docs'):
(destination/folder).mkdir(parents=True)
shutil.copyfile(output/clip['path'], destination/'body/bridge.mp4')
patches, tracking, center = make_patches(frames, clip['ptsUs'], destination)
body = dict(clip, path='body/bridge.mp4')
runtime = {'schemaVersion': 2, 'identityId': 'a01', 'packId': 'a01-expression-action-v1-'+edge['id']+'-runtime-04',
'publishApproval': False, 'runtimeReady': True, 'naturalQualityStatus': 'pending_independent_Pi',
'advancedGateKeep': False, 'rightsStatus': 'unknown', 'deviceTestStatus': 'not_run',
'playbackMode': 'one_shot', 'body': body, 'patchFormat': {
'bodySha256': body['sha256'], 'format': 'PNG RGBA 8bit', 'alphaEncoding': 'straight_unassociated',
'apertureLevels': LEVELS.tolist(), 'requiresRendererExtension': True,
'loopMapping': 'actual displayed bridge frame index only; no wrap'},
'patches': patches, 'mouthStates': copy.deepcopy(template['mouthStates']),
'stateRouting': copy.deepcopy(template['stateRouting']), 'amplitudeSourcePx': 1.1,
'sourceSpecificLipLocalization': {'firstFrameCenter': center, 'method': 'own first-frame red/dark lip ROI; own cheek/nose SSD; own per-frame lip seam',
'neutralPatchReuse': False, 'trackingBoundaryFrames': []},
'additionalAICalls': 0, 'knownAdditionalFeeUSD': 0}
write_json(destination/'manifest.json', runtime)
write_json(destination/'docs/tracking.json', tracking)
edge['mouthRuntimeManifest'] = {'path': str((destination/'manifest.json').relative_to(output)), 'sha256': digest(destination/'manifest.json')}
edge['mouthAllowed'] = True
bodies['bridge:'+edge['id']] = frames
runtimes['bridge:'+edge['id']] = (destination, runtime)
bridge_reports.append({'edgeId': edge['id'], 'bodySha256': body['sha256'], 'N': len(frames), 'ptsUs': body['ptsUs'],
'runtimeSha256': digest(destination/'manifest.json'), 'ownPatchCount': len(patches)*5,
'rgbaBytes': sum(p['width']*p['height']*4*5 for p in patches), 'firstFrameLipCenter': center})
print('BRIDGE_OWN_MOUTH_EXPORTED', edge['id'], edge['mouthRuntimeManifest']['sha256'], flush=True)
previews(index, output, bodies, runtimes)
finalize(source,args.source_sha,output,old)
require(digest(source) == args.source_sha, 'old index changed during recovery')
for row in old['files']:
require(digest(safe_file(source.parent, row['path'])) == row['sha256'], 'old source payload changed during recovery')
print('RECOVERY_BRIDGE_INDEX_READY', digest(output/'manifest.json'), 'files', len(index['files']), flush=True)
if __name__ == '__main__':
main()
+58 -6
View File
@@ -87,14 +87,16 @@ def check_bundle(manifest,expected,output):
files[name]=row
require(sum(f['bytes'] for f in files.values())<=512_000_000,'bundle byte bound')
return p
for row in rows:
ref=row['runtimeManifest'];path=add(ref['path'],ref['sha256'],2_000_000)
references=[(row['id'],row['runtimeManifest']) for row in rows]
references += [('bridge:'+edge['id'],edge['mouthRuntimeManifest']) for edge in index['edges'] if 'mouthRuntimeManifest' in edge]
for runtime_id,ref in references:
path=add(ref['path'],ref['sha256'],2_000_000)
evidence,verified=runtime_gate.check_runtime(path,ref['sha256'],kotlin=False)
m=read_json(path);prefix=PurePosixPath(ref['path']).parent
for name,digest in verified.items(): add(str(prefix/name),digest,64_000_000 if name.endswith('.mp4') else 256_000)
body=m['body'];measurements[str(prefix/body['path'])]={'ptsUs':body['ptsUs'] if m['schemaVersion']==2 else [i*1_000_000//24 for i in range(body['frameCount'])],
'durationUs':body['durationUs'],'fps':Fraction(body['fpsNumerator'],body['fpsDenominator'])}
runtimes.append({'package_id':row['id'],**evidence})
runtimes.append({'package_id':runtime_id,**evidence})
rgba=sum(r['rgba_cache_bytes'] for r in runtimes);require(rgba<=32_000_000,'combined runtime cache bound')
require(len(index['edges'])<=100,'edge count bound')
for edge in index['edges']:
@@ -149,6 +151,45 @@ def import_files(root,files,target):
finally: os.unlink(tmp)
def replace_known_import(root,files,target,previous_report,previous_pin,backup):
"""Replace only a completely verified code-owned previous import; retain rollback."""
require(re.fullmatch('[0-9a-f]{64}',previous_pin or ''),'previous exact pin required')
require(not target.is_symlink() and target.is_dir(),'previous target directory')
old=read_json(previous_report)
require(old['status']=='passed' and old['manifest_sha256']==previous_pin,'previous report pin mismatch')
previous_manifest=target/'manifest.json'
require(file_sha(previous_manifest)==previous_pin,'previous import index drift')
inventory=read_json(previous_manifest)['files']
if isinstance(inventory,dict): inventory=[dict(row,path=name) for name,row in inventory.items()]
known={relative(row['path']):{'sha256':row['sha256'],'bytes':row['bytes']} for row in inventory}
known['manifest.json']={'sha256':previous_pin,'bytes':previous_manifest.stat().st_size}
previous=old['files']
require(all(known.get(relative(name))==row for name,row in previous.items()),'previous report not bound to pinned inventory')
require(not any(p.is_symlink() for p in target.rglob('*')),'previous import symlink preserved')
actual={str(p.relative_to(target)) for p in target.rglob('*') if p.is_file()}
require(actual==set(previous),'unknown import files preserved')
def verify_previous():
for name,row in previous.items():
p=locate(target,name)
require(p.stat().st_size==row['bytes'] and file_sha(p)==row['sha256'],'previous import bytes drift: '+name)
verify_previous()
require(not backup.exists() and not backup.is_symlink() and not backup.resolve().is_relative_to(target.resolve()),'new external backup required')
require(not backup.resolve().is_relative_to(root.resolve()),'backup must not modify asset owner directory')
target.parent.mkdir(parents=True,exist_ok=True)
staging=Path(tempfile.mkdtemp(prefix='.emotion-stage-',dir=target.parent))
try:
import_files(root,files,staging)
verify_previous()
backup.parent.mkdir(parents=True,exist_ok=True)
os.rename(target,backup)
try: os.rename(staging,target)
except BaseException:
os.rename(backup,target);raise
finally:
if staging.exists(): shutil.rmtree(staging)
def badging(path):
return subprocess.check_output([str(TOOLS/'aapt'),'dump','badging',str(path)],text=True,stderr=subprocess.STDOUT)
@@ -162,7 +203,7 @@ def tested_source():
client=json.loads((ROOT/'logs/avatar-safe-061/client-tests.json').read_text())
require(client['status']=='passed' and client['jvm_entry_points']==9,'client regression evidence')
for name,digest in client['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested source: '+name)
evidence=json.loads((ROOT/'logs/action-emotion/media-wiring/delivery.json').read_text())
evidence=json.loads((ROOT/'logs/action-emotion/bridge-talk/delivery.json').read_text())
require(evidence['gateway_passed']==97 and evidence['gateway_skipped']==1 and evidence['offline_gles_goldens']==40,'gateway/GLES evidence')
for name,digest in evidence['source_hashes'].items():
if name.startswith('app/'): require(file_sha(ROOT/name)==digest,'media evidence drift: '+name)
@@ -175,6 +216,8 @@ def packaging_tests_current():
def publish(report,output,requested):
require(all(edge.get('nativeLoop') is True or 'mouthRuntimeManifest' in edge for edge in read_json(ROOT/'app/src/main/assets'/ASSET_ROOT/'manifest.json')['edges']),
'live emotion release needs bridge-own TALK runtimes')
tested_source();packaging_tests_current();require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback drift')
version=next_version((ROOT/'artifacts').glob('*.apk'))
if requested is not None:
@@ -183,7 +226,7 @@ def publish(report,output,requested):
'-PavatarNatural=true','-PavatarMouthCandidate=true','-PnaturalManifestSha='+LEGACY_PIN,
'-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version)],check=True,cwd=ROOT)
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built)
for text in ("name='com.gorios.lanvoice'",f"versionCode='{version}'","versionName='0.7.0-stage-dev'","sdkVersion:'26'","targetSdkVersion:'34'"):
for text in ("name='com.gorios.lanvoice'",f"versionCode='{version}'","versionName='0.7.0-emotion-stage-dev'","sdkVersion:'26'","targetSdkVersion:'34'"):
require(text in badge,'APK metadata: '+text)
require(re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'",'APK ABI')
cert=subprocess.check_output([str(TOOLS/'apksigner'),'verify','--verbose','--print-certs',str(built)],text=True)
@@ -221,6 +264,9 @@ def main():
parser.add_argument('--output',type=Path,required=True,help='New evidence directory outside owner storage')
parser.add_argument('--pi-pin',help='External exact Pi pin, required for import/publish')
mode=parser.add_mutually_exclusive_group();mode.add_argument('--import-only',action='store_true');mode.add_argument('--publish',action='store_true')
parser.add_argument('--previous-import-report',type=Path,help='Verified previous bundle-gate.json; requires --previous-pin and fresh backup')
parser.add_argument('--previous-pin')
parser.add_argument('--backup',type=Path)
parser.add_argument('--version-code',type=int,help='Default max existing APK code+1, minimum17')
args=parser.parse_args();manifest=args.manifest.resolve(strict=True);output=args.output.resolve()
require(not output.exists() and not output.is_relative_to(manifest.parent),'new evidence outside owner root required')
@@ -228,7 +274,13 @@ def main():
output.mkdir(parents=True)
report=check_bundle(manifest,args.sha256,output)
if args.import_only or args.publish:
import_files(manifest.parent,report['files'],ROOT/'app/src/main/assets'/ASSET_ROOT)
target=ROOT/'app/src/main/assets'/ASSET_ROOT
if args.previous_import_report:
require(args.previous_pin and args.backup,'previous replacement requires exact pin and backup')
replace_known_import(manifest.parent,report['files'],target,args.previous_import_report,args.previous_pin,args.backup)
else:
require(not args.previous_pin and not args.backup,'previous import report required')
import_files(manifest.parent,report['files'],target)
(output/'import.json').write_text(json.dumps({'externally_pinned_sha256':args.pi_pin,'files':len(report['files']),'naturalness':'not_certified'})+'\n')
result=publish(report,output,args.version_code) if args.publish else {k:v for k,v in report.items() if k!='files'}
print(json.dumps(result,indent=2))