feat(simulation): integrate infrastructure jobs and semantic scene editing

Integrate infrastructure preparation and qualified map delivery with local scenes. Add semantic editing, object provenance, survey caching and operator scene tools.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:01 +03:00
parent 25dc0a1b44
commit f48411f8fe
116 changed files with 10690 additions and 263 deletions
@@ -10,7 +10,7 @@ param(
$ErrorActionPreference='Stop'
$root='D:\NDC_MISSIONCORE\runtime\simulation'
$name='ndc-ai-polygon-worker'
foreach($marker in @('active.json','editor-active.json','route-active.json')) {
foreach($marker in @('active.json','editor-active.json','route-active.json','infrastructure-active.json')) {
if(Test-Path "$root\state\$marker") { throw 'Active simulation work prevents update' }
}
$task=Get-ScheduledTask -TaskName $name
+60
View File
@@ -0,0 +1,60 @@
"""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()
+101
View File
@@ -0,0 +1,101 @@
"""Build an immutable worker release from a verified installed release and explicit overlays.
Does not activate services. The complete predecessor remains the rollback.
"""
import argparse
import base64
import hashlib
import json
import re
import shutil
from pathlib import Path, PurePosixPath
def sha(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def confined(root, relative):
path = PurePosixPath(relative)
if (
path.is_absolute()
or not path.parts
or ".." in path.parts
or "\\" in relative
or ":" in relative
):
raise ValueError("Invalid release path")
target = root.joinpath(*path.parts)
if target.is_symlink() or not target.resolve().is_relative_to(root.resolve()):
raise ValueError("Release path escaped its owner")
return target
def stage(runtime, recipe):
previous = recipe["base_release"]
if not re.fullmatch("[a-f0-9]{16}", previous):
raise ValueError("Invalid base release")
releases = runtime / "releases"
base = releases / ("ai-polygon-" + previous)
manifest_path = releases / ("ai-polygon-" + previous + ".manifest.json")
if sha(manifest_path) != recipe["base_manifest_sha256"] or not sha(manifest_path).startswith(
previous
):
raise ValueError("Base manifest changed")
before = json.loads(manifest_path.read_text())
for name, digest in before.items():
if sha(confined(base, name)) != digest:
raise ValueError("Base file changed: " + name)
overlays = {}
for name, item in recipe["overlays"].items():
confined(base, name)
raw = base64.b64decode(item["base64"], validate=True)
if hashlib.sha256(raw).hexdigest() != item["sha256"]:
raise ValueError("Overlay changed: " + name)
overlays[name] = raw
if not overlays:
raise ValueError("Empty patch")
after = {**before, **{name: hashlib.sha256(raw).hexdigest() for name, raw in overlays.items()}}
encoded = json.dumps(after, sort_keys=True, indent=2).encode()
identity = hashlib.sha256(encoded).hexdigest()
target = releases / ("ai-polygon-" + identity[:16])
output_manifest = target.with_suffix(".manifest.json")
if target.exists() or output_manifest.exists():
raise ValueError("Release already exists; inspect it instead of overwriting")
temporary = releases / (".staging-" + identity[:16])
temporary.mkdir()
for name, digest in after.items():
dest = confined(temporary, name)
dest.parent.mkdir(parents=True, exist_ok=True)
if name in overlays:
dest.write_bytes(overlays[name])
else:
shutil.copyfile(confined(base, name), dest)
if sha(dest) != digest:
raise ValueError("Staged content changed: " + name)
temporary.rename(target)
output_manifest.write_bytes(encoded)
result = dict(
previous=previous,
release=identity[:16],
manifest_sha256=identity,
files=len(after),
changed=sorted(overlays),
activated=False,
previous_files_verified=len(before),
recipe_sha256=hashlib.sha256(json.dumps(recipe, sort_keys=True).encode()).hexdigest(),
)
receipt = runtime / "preparations" / ("worker-patch-" + identity[:16] + ".json")
receipt.parent.mkdir(exist_ok=True)
receipt.write_text(json.dumps(result, indent=2))
return result
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--runtime", type=Path, required=True)
parser.add_argument("--recipe", type=Path, required=True)
args = parser.parse_args()
print(json.dumps(stage(args.runtime, json.loads(args.recipe.read_text()))))