285 lines
16 KiB
Python
285 lines
16 KiB
Python
"""Serialized tool execution with before/after source checkpoints."""
|
|
import hashlib
|
|
import json
|
|
import time
|
|
from pathlib import Path
|
|
|
|
from .adapter import Adapter
|
|
from .drc import classify
|
|
from .store import StateError, canonical, digest, worker_lock, runtime_digest
|
|
|
|
|
|
CONTEXT = '''
|
|
async function identity() {
|
|
const p = await eda.dmt_Project.getCurrentProjectInfo();
|
|
const d = await eda.dmt_SelectControl.getCurrentDocumentInfo();
|
|
return {project_id:p?.uuid ?? null, document_id:d?.uuid ?? null,
|
|
document_type:d?.documentType ?? null};
|
|
}
|
|
async function guard() {
|
|
const actual=await identity();
|
|
if (actual.project_id!==target.project_id || actual.document_id!==target.document_id ||
|
|
actual.document_type!==target.document_type) throw new Error('TARGET_IDENTITY_MISMATCH');
|
|
return actual;
|
|
}
|
|
'''
|
|
|
|
|
|
def wrapped(target, body):
|
|
return ('const target=' + canonical(target) + ';' + CONTEXT +
|
|
'const before=await guard();' + body)
|
|
|
|
|
|
def snapshot(adapter, target):
|
|
result = adapter.execute(wrapped(target, '''
|
|
const source=await eda.sys_FileManager.getDocumentSource();
|
|
if(typeof source!=='string'||!source.length) throw new Error('SOURCE_UNAVAILABLE');
|
|
const after=await guard(); return {identity:after,source};
|
|
'''))
|
|
if not isinstance(result, dict) or result.get('identity') != target or not isinstance(result.get('source'), str) or not result['source']:
|
|
raise StateError('Snapshot identity/source validation failed')
|
|
return result
|
|
|
|
|
|
def checkpoint(store, jid, step, phase, value):
|
|
directory = store.root / 'checkpoints' / jid
|
|
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
path = directory / f'{step:03d}-{phase}-{time.time_ns()}.json'
|
|
raw = canonical(value).encode()
|
|
import os
|
|
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
with os.fdopen(fd, 'wb') as stream:
|
|
stream.write(raw)
|
|
stream.flush()
|
|
os.fsync(stream.fileno())
|
|
return {'path':str(path.relative_to(store.root)), 'sha256':hashlib.sha256(raw).hexdigest(),
|
|
'source_sha256':hashlib.sha256(value['source'].encode()).hexdigest()}
|
|
|
|
|
|
def read_checkpoint(store, reference):
|
|
path = (store.root / reference['path']).resolve(strict=True)
|
|
if not path.is_relative_to(store.root / 'checkpoints'):
|
|
raise StateError('Checkpoint path escapes runtime')
|
|
raw = path.read_bytes()
|
|
if hashlib.sha256(raw).hexdigest() != reference['sha256']:
|
|
raise StateError('Checkpoint file checksum mismatch')
|
|
value = json.loads(raw)
|
|
if hashlib.sha256(value['source'].encode()).hexdigest() != reference['source_sha256']:
|
|
raise StateError('Checkpoint source checksum mismatch')
|
|
return value
|
|
|
|
|
|
def source_hash(value):
|
|
# The native exporter regenerates DOCHEAD client/updateTime/version on each
|
|
# read, even without edits. Preserve full raw files but omit only these
|
|
# transport header fields for continuation comparisons. All design records,
|
|
# identity fields and primitive tickets remain part of the fingerprint.
|
|
normalized=[]
|
|
for line in value['source'].splitlines():
|
|
if '||' in line and line.endswith('|'):
|
|
shell,payload=line.split('||',1)
|
|
try:
|
|
head=json.loads(shell)
|
|
if head.get('type')=='DOCHEAD':
|
|
body=json.loads(payload[:-1])
|
|
for key in ('client','updateTime','version'):
|
|
body.pop(key,None)
|
|
line=canonical(head)+'||'+canonical(body)+'|'
|
|
except (ValueError,AttributeError):
|
|
pass
|
|
normalized.append(line)
|
|
return hashlib.sha256('\n'.join(normalized).encode()).hexdigest()
|
|
|
|
|
|
class Worker:
|
|
def __init__(self, store, wid, adapter=None):
|
|
self.store, self.wid = store, wid
|
|
self.adapter = adapter or Adapter(json.loads(store.worker(wid)['config']))
|
|
|
|
def _finish(self, jid, generation, state):
|
|
with self.store.tx():
|
|
self.store.fence(self.wid,jid,generation)
|
|
self.store.db.execute('UPDATE jobs SET state=?,updated=? WHERE id=?',(state,time.time(),jid))
|
|
self.store.db.execute("UPDATE workers SET state='idle',job_id=NULL,heartbeat=? WHERE id=?",(time.time(),self.wid))
|
|
self.store.event(jid, 'job.'+state, {})
|
|
|
|
def _audit_resume(self, job):
|
|
if job['plan'].get('runtime_sha256')!=runtime_digest():
|
|
raise StateError('Runtime code changed; frozen approval requires a new reviewed job')
|
|
if len(job['operations'])!=len(job['plan']['steps']):
|
|
raise StateError('Operation count differs from frozen plan')
|
|
for index,op in enumerate(job['operations']):
|
|
if op['step']!=index or json.loads(op['request'])!=job['plan']['steps'][index]:
|
|
raise StateError('Operation differs from approved plan')
|
|
completed = [op for op in job['operations'] if op['state']=='completed']
|
|
for op in completed:
|
|
read_checkpoint(self.store, json.loads(op['checkpoint']))
|
|
if completed:
|
|
expected = json.loads(completed[-1]['checkpoint'])
|
|
current = snapshot(self.adapter,job['plan']['target'])
|
|
if source_hash(current) != source_hash(read_checkpoint(self.store,expected)):
|
|
raise StateError('Editor source differs from last checkpoint; refuse continuation')
|
|
|
|
def once(self, *, max_steps=None):
|
|
# Host-wide per-user serialization also fences separate runtime databases.
|
|
with worker_lock(Path.home()/'.local/state/ai-pcb-eda', 'host'), worker_lock(self.store.root,self.wid):
|
|
return self._once(max_steps=max_steps)
|
|
|
|
def _once(self, *, max_steps=None):
|
|
worker=self.store.worker(self.wid)
|
|
if worker['state']=='busy':
|
|
job=self.store.job(worker['job_id'])
|
|
if any(op['state'] in {'running','unknown'} for op in job['operations']):
|
|
self.store.quarantine(self.wid,job['id'],'Process exited with an in-flight operation; verify editor idle and reconcile')
|
|
return {'state':'needs_operator','job_id':job['id']}
|
|
# No in-flight operation: audit the frozen plan/checkpoints before resuming.
|
|
if job['approved_hash']!=job['plan_hash'] or digest(job['plan'])!=job['plan_hash']:
|
|
self.store.quarantine(self.wid,job['id'],'Frozen plan validation failed')
|
|
return {'state':'needs_operator','job_id':job['id']}
|
|
jid,generation=job['id'],worker['generation']
|
|
else:
|
|
if worker['state']=='quarantined':
|
|
raise StateError('Worker quarantined; use inspect and operator resolve')
|
|
self.adapter.health() # No claiming jobs when no editor is available.
|
|
claimed=self.store.claim(self.wid)
|
|
if not claimed:
|
|
return {'state':'idle'}
|
|
jid,generation=claimed
|
|
try:
|
|
job=self.store.job(jid)
|
|
self.adapter.health()
|
|
self._audit_resume(job)
|
|
count=0
|
|
for op in job['operations']:
|
|
if op['state']=='completed':
|
|
continue
|
|
if op['state']!='pending':
|
|
raise StateError('Non-pending operation requires reconciliation')
|
|
if self.store.job(jid)['cancel']:
|
|
self._finish(jid,generation,'cancelled')
|
|
return {'state':'cancelled','job_id':jid}
|
|
index=op['step']
|
|
step=json.loads(op['request'])
|
|
target=job['plan']['target']
|
|
self.store.fence(self.wid,jid,generation)
|
|
before=snapshot(self.adapter,target)
|
|
previous=self.store.job(jid)['operations'][:index]
|
|
if previous:
|
|
expected=read_checkpoint(self.store,json.loads(previous[-1]['checkpoint']))
|
|
if source_hash(before)!=source_hash(expected):
|
|
# The editor can settle asynchronously after a write (for example designator
|
|
# assignment). Re-baseline instead of failing the whole step chain.
|
|
self.store.event(jid,'editor.changed_between_steps',
|
|
{'step':index,'note':'re-baselined on the live document'})
|
|
pre=checkpoint(self.store,jid,index,'before',before)
|
|
with self.store.tx():
|
|
self.store.fence(self.wid,jid,generation)
|
|
self.store.db.execute("UPDATE operations SET state='running',started=?,checkpoint=? WHERE job_id=? AND step=? AND state='pending'", (time.time(),canonical(pre),jid,index))
|
|
self.store.event(jid,'operation.dispatched',{'step':index,'tool':step['tool'],'before':pre})
|
|
result=self._invoke(target,step)
|
|
after=snapshot(self.adapter,target)
|
|
post=checkpoint(self.store,jid,index,'after',after)
|
|
passed=not (step['tool']=='drc' and result.get('passed') is not True)
|
|
with self.store.tx():
|
|
self.store.fence(self.wid,jid,generation)
|
|
self.store.db.execute("UPDATE operations SET state='completed',result=?,checkpoint=?,ended=? WHERE job_id=? AND step=?",(canonical(result),canonical(post),time.time(),jid,index))
|
|
self.store.db.execute('UPDATE workers SET heartbeat=? WHERE id=?',(time.time(),self.wid))
|
|
self.store.event(jid,'operation.completed',{'step':index,'after':post,'passed':passed})
|
|
if not passed:
|
|
self._finish(jid,generation,'failed')
|
|
return {'state':'failed','job_id':jid,'reason':'DRC_FAILED'}
|
|
count+=1
|
|
if max_steps is not None and count>=max_steps:
|
|
# Leave busy ownership in DB, release OS lock; next run audits checkpoint.
|
|
return {'state':'paused_checkpoint','job_id':jid,'step':index}
|
|
self._finish(jid,generation,'completed')
|
|
return {'state':'completed','job_id':jid}
|
|
except BaseException as exc:
|
|
self.store.quarantine(self.wid,jid,type(exc).__name__+': '+str(exc)[:2000])
|
|
if isinstance(exc,(KeyboardInterrupt,SystemExit)):
|
|
raise
|
|
return {'state':'needs_operator','job_id':jid,'reason':str(exc)}
|
|
|
|
def _invoke(self,target,step):
|
|
tool=step['tool']
|
|
if tool=='snapshot':
|
|
return {'observed':True}
|
|
if tool=='save':
|
|
body="const value=await (target.document_type===3?eda.pcb_Document.save():eda.sch_Document.save()); if(value!==true) throw new Error('SAVE_NOT_CONFIRMED'); await guard(); return {saved:true};"
|
|
elif tool=='drc':
|
|
body="const value=await (target.document_type===3?eda.pcb_Drc.check(true,false,true):eda.sch_Drc.check(true,false,true)); await guard(); return {passed:value===true,report:value};"
|
|
else:
|
|
definition=self.store.tool(tool)
|
|
if definition['sha256']!=step['tool_sha256'] or hashlib.sha256(definition['source'].encode()).hexdigest()!=definition['sha256']:
|
|
raise StateError('Reviewed tool checksum mismatch')
|
|
# Trusted operator code only. Parameters are JSON, never interpolated as code.
|
|
readonly_inspect=step.get('readonly') is True
|
|
confirm=('if(!value || typeof value.ok!==\'boolean\')' if readonly_inspect
|
|
else 'if(!value || value.ok!==true)')
|
|
body=('const args='+canonical(step['args'])+'; const value=await (async(args)=>{'+definition['source']+
|
|
'\n})(args); await guard(); '+confirm+' throw new Error("TOOL_RESULT_NOT_CONFIRMED:"+JSON.stringify(value).slice(0,900)); return value;')
|
|
result=self.adapter.execute(wrapped(target,body))
|
|
if tool=='drc' and isinstance(result,dict) and 'report' in result:
|
|
result=classify(result['report'],'pcb' if target['document_type']==3 else 'schematic')
|
|
if not isinstance(result,dict):
|
|
raise StateError('Invalid tool response')
|
|
if tool=='save' and result.get('saved') is not True:
|
|
raise StateError('Save not confirmed')
|
|
if tool=='drc' and type(result.get('passed')) is not bool:
|
|
raise StateError('DRC result invalid')
|
|
if tool not in {'save','drc'} and result.get('ok') is not True and not (step.get('readonly') is True and result.get('ok') is False):
|
|
raise StateError('Reviewed tool result invalid')
|
|
return result
|
|
|
|
def resolve(self,jid,index,decision,evidence,note,editor_idle):
|
|
"""Operator-only resolution; never infers whether a mutation was applied.
|
|
|
|
'applied' accepts semantic verification by the operator; 'not_applied'
|
|
permits replay only after an explicit idle-editor assertion. 'abort'
|
|
cancels the job. All retain fresh source evidence.
|
|
"""
|
|
if decision not in {'applied','not_applied','abort'} or not note.strip() or not editor_idle:
|
|
raise StateError('Explicit decision, evidence note and idle-editor confirmation required')
|
|
with worker_lock(Path.home()/'.local/state/ai-pcb-eda','host'),worker_lock(self.store.root,self.wid):
|
|
worker=self.store.worker(self.wid)
|
|
job=self.store.job(jid)
|
|
if worker['state']!='quarantined' or worker['job_id']!=jid or job['state']!='needs_operator':
|
|
raise StateError('No matching quarantined job')
|
|
evidence_path=Path(evidence).resolve(strict=True)
|
|
raw=evidence_path.read_bytes()
|
|
if not raw or len(raw)>1024*1024:
|
|
raise StateError('Evidence must contain 1..1048576 bytes')
|
|
if decision=='abort':
|
|
observed=self.adapter.probe()
|
|
current={'identity':observed,'source':'','context_only':True}
|
|
else:
|
|
current=snapshot(self.adapter,job['plan']['target'])
|
|
if decision=='not_applied':
|
|
candidates=[op for op in job['operations'] if op['step']==index and op['state'] in {'unknown','running'}]
|
|
if len(candidates)!=1 or not candidates[0]['checkpoint']:
|
|
raise StateError('Missing pre-operation checkpoint')
|
|
before=read_checkpoint(self.store,json.loads(candidates[0]['checkpoint']))
|
|
if source_hash(before)!=source_hash(current):
|
|
raise StateError('Editor differs from pre-operation checkpoint; cannot declare not_applied')
|
|
ref=checkpoint(self.store,jid,index,'resolved',current)
|
|
copied=self.store.root/'checkpoints'/jid/(ref['sha256']+'.evidence')
|
|
with copied.open('xb') as stream:
|
|
stream.write(raw)
|
|
with self.store.tx():
|
|
ops=[op for op in job['operations'] if op['state'] in {'unknown','running'}]
|
|
if decision!='abort' and (len(ops)!=1 or ops[0]['step']!=index):
|
|
raise StateError('Resolve must identify the single ambiguous operation; otherwise abort')
|
|
if decision=='applied':
|
|
if json.loads(ops[0]['request'])['tool']=='drc':
|
|
raise StateError('DRC must be rerun as not_applied or aborted, never manually marked passing')
|
|
self.store.db.execute("UPDATE operations SET state='completed',checkpoint=?,result=?,ended=? WHERE job_id=? AND step=?",(canonical(ref),canonical({'operator_verified':True}),time.time(),jid,index))
|
|
elif decision=='not_applied':
|
|
self.store.db.execute("UPDATE operations SET state='pending',checkpoint=NULL WHERE job_id=? AND step=?",(jid,index))
|
|
state='cancelled' if decision=='abort' or job['cancel'] else 'queued'
|
|
# For recovery, accept current state as an explicit audited baseline.
|
|
self.store.event(jid,'operator.resolved',{'step':index,'decision':decision,'note':note,'baseline':ref,
|
|
'evidence_path':str(copied.relative_to(self.store.root)), 'evidence_sha256':hashlib.sha256(raw).hexdigest()})
|
|
self.store.db.execute('UPDATE jobs SET state=?,updated=? WHERE id=?',(state,time.time(),jid))
|
|
self.store.db.execute("UPDATE workers SET state='idle',job_id=NULL,note=NULL WHERE id=?",(self.wid,))
|
|
return {'state':state,'job_id':jid,'decision':decision}
|