feat(application): integrate measured-load ingestion training and planner source

This commit is contained in:
ENELIX Agent
2026-10-02 21:00:05 +00:00
parent 44362e4bf5
commit fc024fcfba
96 changed files with 8933 additions and 0 deletions
+131
View File
@@ -0,0 +1,131 @@
"""Count-checked optional bridge installation. Default CHECK ONLY, no service action.
Only dedicated V4 GUI files are added. app.js/index.html/styles.css stay untouched.
Every changed legacy source is backed up with hashes. Concurrent changes abort.
"""
from pathlib import Path
from datetime import datetime,timezone
import argparse,ast,hashlib,json,os,tempfile
ROOT=Path(__file__).resolve().parent
SERVICES=Path('/home/agent/services')
def once(text,old,new):
if text.count(old)!=1:raise ValueError('Source anchor changed/ambiguous; review before updating')
return text.replace(old,new,1)
def patch_forecast(text):
if '# ENELIX_V4_SHADOW_BRIDGE' in text:return text
text='from netplan_v4_publisher import publish_forecasts as _v4_publish_forecasts\n'+text
anchor=' p_3 = v3.predict(data_obj, p_1, p_2)'
text=once(text,anchor,' # ENELIX_V4_SHADOW_BRIDGE\n _v4_publish_forecasts(config, [(3,p_1,p_2),(13,p_10,p_11),(23,p_21,p_22)])\n\n'+anchor)
text=once(text,' d[key] = float(d.get(key) or default)',' raw_value = d.get(key)\n d[key] = float(default if raw_value is None or raw_value == "" else raw_value)')
ast.parse(text);return text
def patch_api(text):
if '# ENELIX_V4_SHADOW_BRIDGE' in text:return text
text='from netplan_v4_publisher import publish_tariffs as _v4_publish_tariffs\n'+text
anchor=' _portal_store_configuration(anlagen_id, configuration)\n'
text=once(text,anchor,anchor+' # ENELIX_V4_SHADOW_BRIDGE\n _v4_publish_tariffs(anlagen_id, configuration)\n')
ast.parse(text);return text
def patch_tariff(text):
if '# ENELIX_V4_SHADOW_BRIDGE' in text:return text
text='from netplan_v4_publisher import publish_ckw as _v4_publish_ckw\n'+text
anchor=' return candidate_points\n'
text=once(text,anchor," # ENELIX_V4_SHADOW_BRIDGE\n _v4_publish_ckw(source['label'], rows, data.get('publication_timestamp') if isinstance(data, dict) else None, tariff_type)\n"+anchor)
for name in ('row','integrated'):
old=f'{name}.get("value") or {name}.get("price") or {name}.get("amount")'
if old in text:text=once(text,old,f'next(({name}[key] for key in ("value", "price", "amount") if {name}.get(key) is not None), None)')
ast.parse(text);return text
def patch_portal(text):
if '// ENELIX_V4_SHADOW_BRIDGE' in text:return text
anchor='const server = createServer(async (req, res) => {'
extra="""// ENELIX_V4_SHADOW_BRIDGE
// No dependency or changed route while NETPLAN_V4_URL is absent.
const plannerV4Bridge = process.env.NETPLAN_V4_URL
? (await import('./netplan-v4-bridge.mjs')).createPlannerV4Bridge({
configuredPrognosisPlant, roleAllowed, bodyJson, json, deviceActivation,
checkDeviceRate, ownedLicenseState, serviceToken: prognosisServiceToken,
upstreamUrl: process.env.NETPLAN_V4_URL
})
: null;
"""
text=once(text,anchor,extra+anchor)
anchor=' if (url.pathname === "/healthz" && req.method === "GET") return json(res, 200, {'
return once(text,anchor,' if (plannerV4Bridge && await plannerV4Bridge(req, res, url)) return;\n'+anchor)
def plan(root=SERVICES, approved_assets=None):
root=Path(root).resolve();project=root/'prognosis-manager-enelix2';result={}
if approved_assets is None:
manifest=ROOT/'approved_previous_assets.json'
approved_assets=json.loads(manifest.read_text()) if manifest.is_file() else {}
for path,patch in [(project/'api/main.py',patch_api),(project/'forecast_engine/main.py',patch_forecast),(project/'tariff_importer/main.py',patch_tariff),(root/'license/server.mjs',patch_portal)]:
if path.is_symlink() or not path.resolve().is_relative_to(root):raise ValueError('External/symlink target refused')
old=path.read_bytes();new=patch(old.decode()).encode()
if old!=new:result[path]=(old,new)
files={project/service/'netplan_v4_publisher.py':ROOT/'integrations/netplan_v4_publisher.py' for service in ('api','forecast_engine','tariff_importer')}
files[root/'license/netplan-v4-bridge.mjs']=ROOT/'integrations/netplan-v4-bridge.mjs'
for name in ('netplan-v4.html','netplan-v4.js','netplan-v4.css'):files[root/'license/public'/name]=ROOT/'gui'/name
for path,source in files.items():
if path.is_symlink() or not path.resolve().is_relative_to(root):raise ValueError('External/symlink target refused')
old=path.read_bytes() if path.exists() else None;new=source.read_bytes()
if old is not None and old!=new:
approved=approved_assets.get(str(path.relative_to(root)),[])
if hashlib.sha256(old).hexdigest() not in approved:
raise ValueError('Existing V4 file differs from the reviewed previous release; explicit merge required: '+str(path))
if old!=new:result[path]=(old,new)
return result
def atomic(path,data,mode=0o644):
path.parent.mkdir(parents=True,exist_ok=True);fd,tmp=tempfile.mkstemp(prefix=path.name+'.v4-',dir=path.parent)
try:
with os.fdopen(fd,'wb') as out:out.write(data);out.flush();os.fsync(out.fileno())
os.chmod(tmp,mode);os.replace(tmp,path)
finally:
if os.path.exists(tmp):os.unlink(tmp)
def apply(entries,root=SERVICES):
root=Path(root).resolve()
for path,(old,new) in entries.items():
if (path.read_bytes() if path.exists() else None)!=old:raise ValueError('Concurrent change: no files modified')
if not entries:return None
backup=root/'change-backups'/'netplan-v4'/datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
backup.mkdir(parents=True);receipt={'root':str(root),'files':[]};written=[]
try:
for path,(old,new) in entries.items():
if (path.read_bytes() if path.exists() else None)!=old:raise ValueError('Concurrent source change during install')
rel=path.relative_to(root);mode=path.stat().st_mode&0o777 if path.exists() else 0o644
if old is not None:
original=backup/'originals'/rel;original.parent.mkdir(parents=True,exist_ok=True);original.write_bytes(old)
atomic(path,new,mode);written.append(path)
receipt['files'].append({'path':str(rel),'before':hashlib.sha256(old).hexdigest() if old is not None else None,'after':hashlib.sha256(new).hexdigest(),'mode':mode})
atomic(backup/'receipt.json',json.dumps(receipt,indent=2).encode());return backup/'receipt.json'
except Exception:
for path in reversed(written):
old,new=entries[path]
if path.read_bytes()==new:
if old is None:path.unlink()
else:atomic(path,old)
raise
def rollback(receipt_path):
path=Path(receipt_path).resolve();data=json.loads(path.read_text());root=Path(data['root']).resolve()
for item in data['files']:
target=(root/item['path']).resolve()
if not target.is_relative_to(root) or hashlib.sha256(target.read_bytes()).hexdigest()!=item['after']:raise ValueError('Later change detected; automatic rollback refused')
for item in reversed(data['files']):
target=root/item['path']
if item['before'] is None:target.unlink()
else:
original=(path.parent/'originals'/item['path']).read_bytes()
if hashlib.sha256(original).hexdigest()!=item['before']:raise ValueError('Backup checksum mismatch')
atomic(target,original,item['mode'])
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--apply',action='store_true');parser.add_argument('--rollback');args=parser.parse_args()
if args.rollback:rollback(args.rollback);print('Source rollback completed. No service restart.')
else:
entries=plan()
for path in entries:print(path)
print('Receipt:',apply(entries)) if args.apply else print('CHECK ONLY:',len(entries),'files. No source/database/service changed.')