Integrate infrastructure preparation and qualified map delivery with local scenes. Add semantic editing, object provenance, survey caching and operator scene tools.
61 lines
4.5 KiB
Python
61 lines
4.5 KiB
Python
"""Plan/apply exact qualified artifacts through the existing local worker API.
|
|
|
|
No inference or geometry processing. Immutable previous versions are retained.
|
|
Token is read only for apply and never emitted. Re-running an applied plan is safe.
|
|
"""
|
|
from pathlib import Path
|
|
import argparse,hashlib,json,sys,urllib.request,urllib.error
|
|
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'src'))
|
|
from k1link.simulation.ai_polygon.qualified_maps import qualified_document
|
|
|
|
BASE='http://127.0.0.1:8000/api/v1/ai-polygon'
|
|
def encoded(obj):return json.dumps(obj,sort_keys=True,ensure_ascii=False,allow_nan=False).encode()
|
|
def sha(raw):return hashlib.sha256(raw).hexdigest()
|
|
def get(path):
|
|
try:
|
|
with urllib.request.urlopen(BASE+path,timeout=30)as r:return json.load(r)
|
|
except urllib.error.HTTPError as e:
|
|
if e.code==404:return None
|
|
raise
|
|
|
|
def main():
|
|
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('mode',choices=['plan','apply']);ap.add_argument('manifest',type=Path);ap.add_argument('evidence',type=Path);args=ap.parse_args()
|
|
manifest_raw=args.manifest.read_bytes();m=json.loads(manifest_raw);dest=args.evidence;dest.mkdir(parents=True,exist_ok=True);planpath=dest/'publication-plan.json'
|
|
vpath=Path(m['verification']);vraw=vpath.read_bytes();v=json.loads(vraw)
|
|
if sha(vraw)!=m['verification_sha256']or not v['passed']or v['source_snapshot']!=m['source_snapshot']:raise ValueError('Qualification receipt mismatch')
|
|
catalog=get('/catalog');worlds={w['world_id']:w for w in catalog['worlds']};items=[]
|
|
for item in m['scenes']:
|
|
world=worlds[item['world_id']];raw=Path(item['artifact']).read_bytes();audit=v['scenes'][item['scene']]['audit']
|
|
if not audit['passed']or audit['full_map_sha256']!=item['artifact_sha256']:raise ValueError('Artifact is not qualified')
|
|
document=qualified_document(raw,world,artifact_sha256=item['artifact_sha256'],source_world_sha256=item['source_world_sha256'],qualification=m['qualification'],source_snapshot=m['source_snapshot'],tiles_total=item['tiles_total'])
|
|
body=encoded(document)
|
|
if len(body)>12*1024**2:raise ValueError('Map exceeds API size limit')
|
|
current=get('/worlds/'+item['world_id']+'/urban-map');items.append(dict(scene=item['scene'],world_id=item['world_id'],world_sha256=world['sha256'],collider_sha256=world.get('collider_sha256'),target_sha256=sha(body),current_sha256=sha(encoded(current))if current is not None else None,document=document,current=current))
|
|
if args.mode=='plan':
|
|
if planpath.exists():raise ValueError('Existing plan retained; choose a fresh evidence directory')
|
|
for i in items:
|
|
(dest/(i['scene']+'-target.json')).write_bytes(encoded(i['document']))
|
|
(dest/(i['scene']+'-previous.json')).write_bytes(encoded(i['current']))
|
|
plan=dict(manifest_sha256=sha(manifest_raw),items=[{k:x for k,x in i.items()if k not in ['document','current']}for i in items]);planpath.write_text(json.dumps(plan,indent=2));print(json.dumps(plan));return
|
|
plan=json.loads(planpath.read_text())
|
|
if plan['manifest_sha256']!=sha(manifest_raw):raise ValueError('Publication manifest changed')
|
|
planned={x['scene']:x for x in plan['items']}
|
|
# Preflight every scene before the first write; never overwrite unrelated updates.
|
|
for i in items:
|
|
p=planned[i['scene']]
|
|
for k in ['world_id','world_sha256','collider_sha256','target_sha256']:
|
|
if i[k]!=p[k]:raise ValueError('Source/target changed since planning: '+k)
|
|
if i['current_sha256']not in [p['current_sha256'],p['target_sha256']]:raise ValueError('Live map changed since planning')
|
|
token=(Path(__file__).resolve().parents[1]/'.runtime/mission-core/ai-polygon/worker.token').read_text().strip();results=[]
|
|
for i in items:
|
|
if i['current_sha256']!=i['target_sha256']:
|
|
req=urllib.request.Request(BASE+'/worker/worlds/'+i['world_id']+'/urban-map',data=encoded(i['document']),headers={'Content-Type':'application/json','Authorization':'Bearer '+token},method='POST')
|
|
with urllib.request.urlopen(req,timeout=30)as response:receipt=json.load(response)
|
|
if receipt['sha256']!=i['target_sha256']:raise ValueError('Unexpected saved map hash')
|
|
saved=get('/worlds/'+i['world_id']+'/urban-map')
|
|
if saved!=i['document']:raise ValueError('Readback differs from qualified map')
|
|
results.append(dict(scene=i['scene'],world_id=i['world_id'],sha256=i['target_sha256'],features=len(saved['features']),readback_exact=True))
|
|
(dest/'publication-result.json').write_text(json.dumps(dict(complete=len(results)==len(items),scenes=results),indent=2))
|
|
print(json.dumps(dict(complete=True,scenes=results)))
|
|
if __name__=='__main__':main()
|