"""Durable, explicitly driven interpreter for published Java Skill graphs.""" import time import uuid import threading from contextlib import contextmanager from collections import Counter from src.modules.skill.domain.models import SkillError, digest from src.modules.context.service import ContextService from src.modules.tool_gateway.service import ToolGateway TERMINAL = {'succeeded', 'failed', 'unknown', 'cancelled'} UNKNOWN = {'MODEL_RESULT_UNKNOWN', 'MODEL_USAGE_INVALID', 'MODEL_OUTPUT_INCOMPLETE', 'MODEL_RESPONSE_TOO_LARGE', 'SANDBOX_TIMEOUT', 'SANDBOX_CLEANUP_UNKNOWN', 'INVALID_SANDBOX_RECEIPT', 'VM_RESULT_UNKNOWN'} REPAIRABLE = {'JAVA_BUILD_FAILED', 'JAVA_TEST_FAILED'} class AgentRuntime: activity_interval = 5 def __init__(self, store, skills, knowledge, llm, harness, sandbox, *, clock=time.time, artifacts=None): self.store, self.skills, self.knowledge = store, skills, knowledge self.llm, self.harness, self.sandbox, self.clock = llm, harness, sandbox, clock self.context = ContextService() self.tools = ToolGateway(sandbox, harness) self.artifacts = artifacts @contextmanager def activity(self, run_id, claim, stage): """A live interpreter lease heartbeat, never an invented model/test result.""" from src.modules.orchestrator.feedback import CHECKPOINT_SECONDS, short_message, audit stop = threading.Event() started = self.clock() def beat(): original=self.store.get(run_id) checkpoint=max([int(max(0,e['timestamp']-original['created_at'])//CHECKPOINT_SECONDS) for e in self.store.stages(run_id) if e['status']=='checkpoint'] or [0]) while not stop.wait(self.activity_interval): try: run = self.store.get(run_id) if run['claim'] != claim or run['status'] != 'running' or run['cancel_requested'] or self.clock() > run['lease_until']: return self.store.stage_event(run_id, stage, 'active', '执行器仍持有本任务租约,正在等待实际响应;本次心跳不代表编译或测试通过。') current = int(max(0, self.clock()-run['created_at']) // CHECKPOINT_SECONDS) if current > checkpoint: import json self.store.stage_event(run_id, stage, 'audit', json.dumps( audit(self,run,stage,max(0,self.clock()-started)),ensure_ascii=False,separators=(',',':'))) self.store.stage_event(run_id, stage, 'checkpoint', short_message(stage)) checkpoint = current except Exception: return thread = threading.Thread(target=beat, daemon=True) thread.start() try: yield finally: stop.set() thread.join(timeout=2) def _access(self, actor, run_id, *, owner=False): run = self.store.get(run_id) if (run['tenant_id'] != actor.tenant_id or (run['owner_id'] != actor.user_id and (owner or not set(actor.roles).intersection({'reviewer', 'admin'})))): raise SkillError('RUN_NOT_FOUND', '任务不存在或不可见。', 404) self.skills.project_access(actor, run['project_id']) return run def get(self, actor, run_id): run = self._access(actor, run_id) return dict(run, model_calls=self.store.calls(run_id)) def repair_diagnostics(self, run): """Only enrich reported failures with corresponding public expected values, never test code.""" observed=run.get('diagnostics') or {} if isinstance(observed,dict) and isinstance(observed.get('diagnostics'),str): import re text=observed['diagnostics'];lines=text.splitlines() starts=[i for i,line in enumerate(lines) if re.search(r'\.java:\d+: error:',line)] if starts: relevant=sorted({j for i in starts for j in range(i,min(i+4,len(lines)))}) observed={**observed,'diagnostics':'\n'.join(lines[i] for i in relevant), 'full_log_digest':digest(text),'full_log_location':'run.diagnostics', 'compiler_error_count':len(starts)} expectations=[] config=getattr(self.sandbox,'config',None) cases=getattr(config,'tests',[]) for failure in observed.get('failures',[])[:10] if isinstance(observed,dict) else []: if not isinstance(failure,dict):continue index=failure.get('case_index') if (type(index) is int and 0<=index 6000: raise SkillError('REQUIREMENT_LIMIT', '需求需为非空且不超过6000字节。') snapshot = self.skills.prepare(actor, request['release_ref'], request['project_id'], request['source_digest'], 'runtime-' + digest({'key': key, 'request': request})) with self.skills.repository.transaction() as tx: release = self.skills.need(tx, actor, 'release', request['release_ref']) body = release['body'] self.harness.framework(body['framework']) if (body['draft'].get('execution_profile_ref') or body['skill_id']) not in self.sandbox.skill_ids: raise SkillError('ACCEPTANCE_SUITE_NOT_BOUND', '该Skill未绑定服务端批准的独立测试套。', 409) from src.modules.orchestrator.profile import supported_graph if not supported_graph(body['draft']['graph']): raise SkillError('UNSUPPORTED_EXECUTION_GRAPH', '当前画像支持重复需求/检索/上下文/策略原子;模型、制品和执行阶段须各有一个权威实例。') run = {'id': 'run-' + uuid.uuid4().hex, 'tenant_id': actor.tenant_id, 'owner_id': actor.user_id, 'project_id': request['project_id'], 'request': request, 'snapshot': snapshot, 'release': body, 'budget': snapshot['budget'], 'status': 'queued', 'revision': 1, 'cursor': 0, 'outputs': {}, 'approvals': [], 'repairs': 0, 'cancel_requested': False, 'claim': None, 'created_at': self.clock(), 'active_seconds': 0.0, 'error': None} if request.get('resource_limits'): from src.modules.governance.resource_limits import configured policy=configured(request['resource_limits']) run['budget']={k:min(v,policy.get(k,v)) for k,v in run['budget'].items()} return self.store.create(run, key, request) def trial(self, actor, skill_id, request, key): self.skills.read_draft(actor, skill_id) if request['release_ref'].split('@')[0] != skill_id: raise SkillError('SKILL_RELEASE_MISMATCH', '试运行必须绑定同一Skill的已发布版本。') return self.create(actor, request, key) def _recheck(self, actor, run): checked = self.skills.prepare(actor, run['request']['release_ref'], run['project_id'], run['request']['source_digest'], 'recheck-' + run['id'], inspect_only=True) if checked['release_digest'] != run['snapshot']['release_digest']: raise SkillError('RELEASE_CHANGED', 'Skill发布摘要变化。', 409) self.harness.framework(run['snapshot']['framework']) def _write(self, run_id, claim, updates): def change(run): if run['claim'] != claim or run['status'] != 'running': raise SkillError('RUN_CLAIM_LOST', '运行租约已失效。', 409) if run['cancel_requested']: raise SkillError('RUN_CANCELLED', '任务已取消。', 409) if updates.get('status', 'running') != 'running': run['active_seconds'] += max(0, self.clock() - run['claim_started_at']) run.update(updates) return self.store.mutate(run_id, change) def advance(self, actor, run_id): run = self._access(actor, run_id, owner=True) self._recheck(actor, run) claim = uuid.uuid4().hex start = self.clock() def take(current): if current['status'] != 'queued' or current['cancel_requested']: raise SkillError('RUN_NOT_QUEUED', '任务不能重复推进。', 409) remaining = (360 if current['request'].get('budget_policy',{}).get('mode')=='unlimited-usage-v1' else current['budget']['max_seconds'] - current['active_seconds']) if remaining <= 0: if current['request'].get('resource_limits') or current['request'].get('budget_policy'): current.update(status='waiting_limit',error='RUN_TIME_BUDGET_EXCEEDED');return raise SkillError('RUN_TIME_BUDGET_EXCEEDED', '任务时间预算耗尽。', 409) current.update(status='running', claim=claim, claim_started_at=start, lease_until=start + min(remaining, 900 if current['request'].get('resource_limits') else 360)) run = self.store.mutate(run_id, take) if run['status']=='waiting_limit': from src.modules.orchestrator.budget_approval import limit_proposal,seal proposal=self._limit_proposal(run,self.store.calls(run_id)) return self.store.mutate(run_id,lambda r:r.update(limit_request=seal(r,proposal,r['revision']+1) if proposal else None)) def cancelled(): state = self.store.get(run_id) return state['cancel_requested'] or state['claim'] != claim or self.clock() > state['lease_until'] try: if run.get('repair_pending'): self.store.stage_event(run_id,'repair','started','根据实际编译或测试诊断请求模型修复') design=self._operation_output(run, 'AO04')['design'] new_context=any(op['operation_id']=='AO05' and op['version']=='0.2.0' for op in run['release']['operations'].values()) analysis=None if (new_context and not run['request'].get('budget_policy') and run['repairs']>=2 and run['budget']['max_model_calls']-len(self.store.calls(run_id))>=2 and any('diagnose' in getattr(p,'task_roles',[]) for p in self.llm.providers)): failure=self.repair_diagnostics(run) observed=failure['observed'] if isinstance(observed,dict) and 'failures' in observed: failure={**failure,'observed':{**observed,'failures':observed['failures'][:3]}, 'public_contract_expectations':failure['public_contract_expectations'][:3]} self.store.stage_event(run_id,'diagnosis','started','修复后仍未通过,先定位最小失败请求的具体代码原因') try: with self.activity(run_id,claim,'diagnosis'): hypothesis=self.llm.generate(run_id,'diagnose',{'source':self._operation_output(run,'AO06')['source']['files'], 'failure':failure,'runtime_contract':self.sandbox.runtime_contract},cancelled,26000, dispatch_guard=lambda:self._recheck(actor,self.store.get(run_id))) analysis={**hypothesis,'source_digest':self._operation_output(run,'AO06')['source']['source_digest'], 'trust':'model_hypothesis_requires_independent_tests'} run=self._write(run_id,claim,{'failure_analysis':analysis}) self.store.stage_event(run_id,'diagnosis','completed',hypothesis['summary']) except SkillError as exc: if exc.code not in {'CONTEXT_BUDGET_EXCEEDED','STAGE_CONTEXT_BUDGET_EXCEEDED','MODEL_ROUTE_UNAVAILABLE','MODEL_OUTPUT_INVALID','MODEL_OUTPUT_TRUNCATED'}:raise self.store.stage_event(run_id,'diagnosis','skipped','诊断建议不可用:'+exc.code+';调用记录保留,按原预算修复') if analysis:self.store.stage_event(run_id,'repair','started','按定位建议修复源码;仍须独立编译和系统测试') from src.modules.execution.scenarios import business_app business=run['snapshot']['framework']['profile_id']==business_app.PROFILE previous=self._operation_output(run,'AO06')['source']['files'] failure_code=run.get('repair_failure_code') or run['error'] repair_inputs=self.context.repair_inputs(previous,failure_code,run.get('diagnostics')) with self.activity(run_id, claim, 'repair'): patch = self.llm.generate(run_id, 'repair', self.context.model_payload({ **({'design_reference':digest(design)} if repair_inputs.get('repair_scope',{}).get('mode')=='exact-edits' else {'design':design}), **repair_inputs, 'failure_code': failure_code, 'diagnostics': self.repair_diagnostics(run), **({'failure_analysis':analysis} if analysis else {})},run['request']['requirement'],self.sandbox.runtime_contract), cancelled, 32000 if new_context or 'code_review' in run['outputs'] else 26000 if run['snapshot']['framework']['profile_id']=='java17-pdfbox-web' else 20000, dispatch_guard=lambda:self._recheck(actor,self.store.get(run_id))) prepared=self._candidate_patch(run, patch) self.harness.files(prepared, run['snapshot']['framework']) outputs = dict(run['outputs']) nodes = run['release']['draft']['graph']['nodes'] code = next(n['id'] for n in nodes if (n.get('operation_ref') or '').startswith('AO05@')) apply = next(n['id'] for n in nodes if (n.get('operation_ref') or '').startswith('AO06@')) cursor = run['release']['execution_order'].index(apply) for nid in run['release']['execution_order'][cursor:]: outputs.pop(nid, None) outputs[code] = {'patch': prepared if business else patch} # One review per new task. Later diagnostic repairs do not inherit a # claim that the new candidate was reviewed; retain the original report. for node in nodes: if (node.get('operation_ref') or '').startswith('AO13@'): reviewed=outputs[node['id']] outputs[node['id']]={'patch':prepared if business else patch, 'review':dict(reviewed['review'],superseded_by_repair=True)} run = self._write(run_id, claim, {'outputs': outputs, 'cursor': cursor, 'repair_pending': False, 'repair_failure_code':None,'error': None}) self.store.stage_event(run_id,'repair','completed','修复候选已返回;尚需重新构建与独立测试') return self._wait(run, claim, 'repair-execution', 'execution', increment=False) while run['cursor'] < len(run['release']['execution_order']): if cancelled(): raise SkillError('RUN_CANCELLED', '运行取消或租约到期。', 409) self._recheck(actor, run) node_id = run['release']['execution_order'][run['cursor']] node = next(n for n in run['release']['draft']['graph']['nodes'] if n['id'] == node_id) if node['kind'] == 'approval': self.store.stage_event(run_id,node_id,'waiting','等待'+{'design':'设计','execution':'执行','acceptance':'用户验收'}.get(node['approval_scope'],node['approval_scope'])+'确认') return self._wait(run, claim, node_id, node['approval_scope']) self.store.stage_event(run_id,node_id,'started') inputs = dict(node['inputs']) for edge in run['release']['draft']['graph']['data_edges']: if edge['target'] == node_id: inputs[edge['target_port']] = run['outputs'][edge['source']][edge['source_port']] if node['kind'] == 'start': result = {'requirement': run['request']['requirement'], 'query': run['request']['query']} elif node['kind'] == 'end': result = {'manifest': inputs['manifest']} else: operation = run['release']['operations'][node['operation_ref']] if operation['operation_id'] in {'AO04', 'AO05', 'AO08', 'AO13'}: with self.activity(run_id, claim, node_id): result = self._handle(actor, run, operation, inputs, cancelled) else: result = self._handle(actor, run, operation, inputs, cancelled) outputs = dict(run['outputs'], **{node_id: result}) run = self._write(run_id, claim, {'outputs': outputs, 'cursor': run['cursor'] + 1}) self.store.stage_event(run_id,node_id,'completed') if not self.sandbox.cleanup(run_id): raise SkillError('SANDBOX_CLEANUP_UNKNOWN', '回收状态未知。', 503) return self._finish(run_id, claim, 'succeeded') except SkillError as exc: self.store.diagnostic(run_id,'orchestrator',exc.code,exc) self.store.stage_event(run_id,'repair' if run.get('repair_pending') else run['release']['execution_order'][min(run['cursor'],len(run['release']['execution_order'])-1)],'failed',exc.code) current = self.store.get(run_id) self.store.mutate(run_id, lambda r: r.update(failure_details=exc.details)) if exc.code in REPAIRABLE: self.store.mutate(run_id, lambda r: r.update(diagnostics=exc.details)) cleaned = self.sandbox.cleanup(run_id) unknown_call = any(c['state'] in {'unknown', 'reserved'} for c in self.store.calls(run_id)) if not cleaned or exc.code in UNKNOWN or unknown_call: status = 'unknown' elif current['cancel_requested'] or exc.code == 'RUN_CANCELLED': status = 'waiting_limit' if current['request'].get('resource_limits') and not current['cancel_requested'] and self.clock()>current.get('lease_until',0) else 'cancelled' if status=='waiting_limit':exc.code='RUN_TIME_BUDGET_EXCEEDED' elif self.clock()>current.get('lease_until',0): status='waiting_limit' if current['request'].get('resource_limits') else 'unknown' if status=='waiting_limit':exc.code='RUN_TIME_BUDGET_EXCEEDED' elif current['request'].get('resource_limits') and (exc.code in {'RUN_TIME_BUDGET_EXCEEDED','RESOURCE_QUEUE_TIMEOUT','MODEL_CALL_BUDGET_EXCEEDED','MODEL_OUTPUT_LIMIT','SANDBOX_BOOT_FAILED','ISOLATION_UNAVAILABLE','ISOLATION_IMAGE_MISMATCH','SANDBOX_CAPACITY_EXCEEDED'} or (exc.code in REPAIRABLE and current['repairs']>=current['budget']['max_repairs'])): status='waiting_limit' self.store.stage_event(run_id,'limits','waiting','安全暂停:本轮资源或修复上限已到;未启动新工作,保留源码、诊断、账本及原验收。') elif exc.code=='OVERDRAFT_APPROVAL_PENDING': status='waiting_budget' elif exc.code in {'STAGE_CONTEXT_BUDGET_EXCEEDED','TASK_TOKEN_BUDGET_EXCEEDED'}: check=exc.details['budget_check'] from src.modules.orchestrator.budget_approval import propose if current.get('repair_pending') and not current.get('repair_failure_code'): current=self.store.mutate(run_id,lambda r:r.update(repair_failure_code=r['error'])) proposal,refusal=propose(current,check,self.store.calls(run_id),self.clock(),self._budget_provider(current,check)) if proposal: self.store.mutate(run_id,lambda r:r.update(budget_request=proposal)) status='waiting_budget' self.store.stage_event(run_id,proposal['stage'],'waiting_budget','预算预检暂停,等待当前任务的阶段/任务限额调整确认;未发起模型调用。') else: status='failed' exc.code=refusal elif exc.code in REPAIRABLE and (current['repairs'] < current['budget']['max_repairs'] or current['request'].get('budget_policy',{}).get('mode')=='one-call-overdraft-v1'): status = 'repair_required' else: status = 'failed' return self._finish(run_id, claim, status, exc.code) except Exception as exc: self.store.diagnostic(run_id,'orchestrator','EXECUTION_RESULT_UNKNOWN',exc) self.store.stage_event(run_id,'execution','unknown','EXECUTION_RESULT_UNKNOWN') self.sandbox.cleanup(run_id) return self._finish(run_id, claim, 'unknown', 'EXECUTION_RESULT_UNKNOWN') def _finish(self, run_id, claim, status, error=None): def finish(run,calls): if run['claim'] != claim: raise SkillError('RUN_CLAIM_LOST', '运行租约已失效。', 409) if run['cancel_requested'] and status == 'succeeded': status_value = 'cancelled' else: status_value = status run['active_seconds'] += max(0, self.clock() - run['claim_started_at']) run.update(status=status_value, error=error, claim=None) if status_value=='waiting_limit': from src.modules.orchestrator.budget_approval import limit_proposal,seal proposal=self._limit_proposal(run,calls) run['limit_request']=seal(run,proposal,run['revision']+1) if proposal else None if status_value=='waiting_budget' and run.get('budget_request') and run['budget_request'].get('mode')!='overdraft': from src.modules.orchestrator.budget_approval import seal run['budget_request']=seal(run,run['budget_request'],run['revision']+1) return self.store.mutate(run_id, finish,with_calls=True) def _budget_provider(self,run,check): from src.modules.llm_gateway.routing import plan candidates,_=plan(self.llm.providers,check['stage'],run) return candidates[0] if candidates else None def _limit_proposal(self,run,calls): from src.modules.orchestrator.budget_approval import limit_proposal proposal=limit_proposal(run,calls,self.clock()) if proposal: routes={} for stage in ('design','code','repair'): provider=self._budget_provider(run,{'stage':stage}) if provider:routes[stage]=getattr(provider,'model',provider.name) proposal['routes']=routes proposal['model']=routes.get(proposal['stage'],'当前步骤不直接调用模型;后续阶段沿用下列路由') return proposal def decide_limit(self,actor,run_id,expected_digest,accept,expected_revision=None): run=self._access(actor,run_id,owner=True);self._recheck(actor,run) from src.modules.orchestrator.budget_approval import limit_proposal,seal,context_binding,ledger_binding applied=False;changed=False def decide(run,calls): nonlocal applied,changed if any(a['digest']==expected_digest and a['actor']==actor.user_id and a['approved']==accept for a in run.get('budget_authorizations',[])):return if any(c['state'] in {'unknown','reserved'} for c in calls):raise SkillError('MODEL_RESULT_UNKNOWN','结果未确认,不得通过审批重放。',409) p=run.get('limit_request');fresh=self._limit_proposal(run,calls) if run['status']!='waiting_limit' or not p or p['digest']!=expected_digest:raise SkillError('BUDGET_REQUEST_CHANGED','限额申请已变化。',409) if not fresh or p.get('task_revision')!=run['revision'] or expected_revision not in (None,run['revision']) or p['expires_at']<=self.clock() or p['ledger_binding']!=ledger_binding(calls) or p['context_binding']!=context_binding(run,{}) or p['after']!=fresh['after'] or p.get('routes')!=fresh['routes']: run['limit_request']=seal(run,fresh,run['revision']+1) if fresh else None;changed=True;return run['budget_authorizations']=[*run.get('budget_authorizations',[]),{**p,'actor':actor.user_id,'approved':accept,'at':self.clock()}] if not accept:run['limit_request']=seal(run,{**p,'deferred':True},run['revision']+1);return run['budget']=p['after'];run['limit_request']=None run['approved_budget_models']={**run.get('approved_budget_models',{}),**p['routes']} if p['reason'] in REPAIRABLE: run.update(repair_pending=True,repair_failure_code=p['reason'],repairs=run['repairs']+1) run.update(status='queued',error=None);applied=True updated=self.store.mutate(run_id,decide,with_calls=True) if changed:raise SkillError('BUDGET_REQUEST_CHANGED','申请已过期或任务变化,已重新计算,请再次确认。',409) return {**updated,'budget_decision_applied':applied} def decide_budget(self,actor,run_id,expected_digest,accept,expected_revision=None): initial=self._access(actor,run_id,owner=True) self._recheck(actor,initial) if ((initial.get('budget_request') or {}).get('mode')=='overdraft' or any(a.get('mode')=='overdraft' and a['digest']==expected_digest for a in initial.get('budget_authorizations',[]))): return self.decide_overdraft(actor,run_id,expected_digest,accept) from src.modules.orchestrator.budget_approval import propose,seal,context_binding,ledger_binding applied=False;changed=False def decide(run,calls): nonlocal applied,changed previous=next((a for a in run.get('budget_authorizations',[]) if a['digest']==expected_digest),None) if previous and previous['actor']==actor.user_id and previous['approved']==accept: return # Same decision is a read, never another queue submission. if any(c['state'] in {'unknown','reserved'} for c in calls): raise SkillError('MODEL_RESULT_UNKNOWN','尚有未结算调用,不能通过预算批准重放。',409) pending=run.get('budget_request') if run['status']!='waiting_budget' or not pending or pending['digest']!=expected_digest: raise SkillError('BUDGET_REQUEST_CHANGED','预算申请已变化,请重新读取。',409) check=run.get('failure_details',{}).get('budget_check') or run['budget_checks'][-1] provider=self._budget_provider(run,check) context_valid=pending.get('context_binding')==context_binding(run,check) fresh,refusal=propose(run,check,calls,self.clock(),provider) stale=(not context_valid or pending.get('task_revision')!=run['revision'] or (expected_revision is not None and expected_revision!=run['revision']) or pending.get('expires_at',0)<=self.clock() or pending.get('ledger_binding')!=ledger_binding(calls) or not fresh or any(pending.get(k)!=fresh.get(k) for k in ('model','stage_limit','task_limit','output_reservation','model_context_limit'))) if stale: if fresh and (context_valid or 'context_binding' not in pending): run['budget_request']=seal(run,fresh,run['revision']+1) else: run.update(status='failed',error=refusal or 'BUDGET_RECHECK_REQUIRED',budget_request=None) changed=True;return receipt={**pending,'approved':accept,'actor':actor.user_id,'at':self.clock()} run['budget_authorizations']=[*run.get('budget_authorizations',[]),receipt] if accept: run['budget_request']=None run['budget']={**run['budget'],'max_tokens':pending['task_limit']} run['approved_stage_limits']={**run.get('approved_stage_limits',{}),pending['stage']:pending['stage_limit']} run['approved_budget_models']={**run.get('approved_budget_models',{}),pending['stage']:pending['model']} run.update(status='queued',error=None) applied=True else: run['budget_request']=seal(run,{**pending,'deferred':True},run['revision']+1) updated=self.store.mutate(run_id,decide,with_calls=True) if changed: raise SkillError('BUDGET_REQUEST_CHANGED','任务版本、模型或申请有效期已变化;已重新核对,请查看当前申请并再次确认。',409) return {**updated,'budget_decision_applied':applied} def decide_overdraft(self,actor,run_id,expected_digest,accept): """Decide one call-bound advance without replaying an in-flight call.""" applied=False;enqueue=False def decide(run,calls): nonlocal applied,enqueue if any(a['digest']==expected_digest and a['actor']==actor.user_id and a['approved']==accept for a in run.get('budget_authorizations',[])):return p=run.get('budget_request') or {} if (p.get('mode')!='overdraft' or p.get('digest')!=expected_digest or p['snapshot']!=run['snapshot']['snapshot_digest']): raise SkillError('BUDGET_REQUEST_CHANGED','先行额度申请已变化,请重新读取。',409) call=next((c for i,c in enumerate(calls,1) if i==p['call_number']),None) if not call:raise SkillError('BUDGET_REQUEST_CHANGED','先行调用记录缺失。',409) run['budget_authorizations']=[*run.get('budget_authorizations',[]), {**p,'approved':accept,'actor':actor.user_id,'at':self.clock(),'call_state_at_decision':call['state']}] run['budget_request']=None;applied=True if accept: run['budget']={**run['budget'],**{k:max(run['budget'][k],v) for k,v in p['after'].items()}} run['approved_stage_limits']={**run.get('approved_stage_limits',{}), p['stage']:max(run.get('approved_stage_limits',{}).get(p['stage'],0),p['stage_limit'])} if run['status']=='waiting_budget' and run['error']=='OVERDRAFT_APPROVAL_PENDING' and not run['cancel_requested']: if any(c['state'] in {'reserved','unknown'} for c in calls):return run.update(status='queued',error=None);enqueue=True else: run.update(cancel_requested=True,error='BUDGET_DECLINED') if run['status'] not in {'running','unknown'}:run['status']='cancelled' updated=self.store.mutate(run_id,decide,with_calls=True) return {**updated,'budget_decision_applied':applied,'budget_enqueue_required':enqueue} def _wait(self, run, claim, node, scope, increment=True): approval = {'node': node, 'scope': scope, 'increment': increment, 'digest': digest({'run': run['id'], 'snapshot': run['snapshot']['snapshot_digest'], 'outputs': run['outputs'], 'node': node, 'repairs': run['repairs']})} return self._write(run['id'], claim, {'pending_approval': approval, 'status': 'waiting_approval', 'claim': None}) def approve(self, actor, run_id, expected_digest, *, delegation=None): run = self._access(actor, run_id) self._recheck(actor, run) def approve(current): pending = current.get('pending_approval') if current['status'] != 'waiting_approval' or not pending or pending['digest'] != expected_digest: raise SkillError('APPROVAL_TARGET_CHANGED', '确认对象已变化。', 409) if pending['scope'] == 'acceptance' and (actor.user_id == current['owner_id'] or not set(actor.roles).intersection({'reviewer', 'admin'})): raise SkillError('INDEPENDENT_REVIEW_REQUIRED', '最终验收需要独立评审人。', 403) if delegation and (pending['scope'] == 'acceptance' or current['release'].get('publication_scope') != 'local-validation-only' or delegation != current['release'].get('authorization_ref')): raise SkillError('VALIDATION_SCOPE_REQUIRED', '委托不能扩大到人工验收或其他版本。', 403) current['approvals'].append(dict(pending, user_id=actor.user_id, **({'mechanism': 'delegated_local_validation', 'authorization_ref': delegation} if delegation else {}))) current['cursor'] += int(pending['increment']) current.update(status='queued', pending_approval=None) return self.store.mutate(run_id, approve) def repair(self, actor, run_id): self._access(actor, run_id, owner=True) def repair(current): if current['status'] != 'repair_required' or (current['repairs'] >= current['budget']['max_repairs'] and current['request'].get('budget_policy',{}).get('mode')!='one-call-overdraft-v1'): raise SkillError('REPAIR_NOT_ALLOWED', '不可修复或次数耗尽。', 409) if current['repairs']>=current['budget']['max_repairs']:current['pending_repair_extension']=True current.update(status='queued', repair_pending=True, repair_failure_code=current['error'],repairs=current['repairs'] + 1) return self.store.mutate(run_id, repair) def cancel(self, actor, run_id): self._access(actor, run_id, owner=True) def cancel(current): if current['status'] in TERMINAL: return current['cancel_requested'] = True if current['status'] != 'running': current['status'] = 'cancelled' run = self.store.mutate(run_id, cancel) if run['status'] == 'cancelled' and not self.sandbox.cleanup(run_id): run = self.store.mutate(run_id, lambda r: r.update(status='unknown', error='SANDBOX_CLEANUP_UNKNOWN')) return run def recover(self, actor, run_id): self._access(actor, run_id, owner=True) def recover(run): if run['status'] != 'running' or self.clock() <= run['lease_until']: raise SkillError('RECOVERY_NOT_ALLOWED', '仅可恢复租约已过期的运行任务。', 409) run['active_seconds'] += max(0, self.clock() - run.get('claim_started_at', self.clock())) run.update(status='unknown', claim=None, error='WORKER_RESULT_UNKNOWN') run = self.store.mutate(run_id, recover) self.sandbox.cleanup(run_id) return run @staticmethod def _operation_output(run, operation): node = next(n for n in run['release']['draft']['graph']['nodes'] if (n.get('operation_ref') or '').startswith(operation + '@')) return run['outputs'][node['id']] @staticmethod def _candidate_patch(run, patch): from src.modules.execution.scenarios import webapp,business_app if run['snapshot']['framework']['profile_id'] == webapp.PROFILE: return webapp.prepare_patch(patch) if (run['snapshot']['framework']['profile_id']==business_app.PROFILE and isinstance(patch,dict) and isinstance(patch.get('files'),dict) and set(patch['files'])=={business_app.JAVA}): prior=None if run.get('repair_pending'): prior=AgentRuntime._operation_output(run,'AO06')['source'] elif run['request'].get('recovery_diagnostics'): prior=run['request'].get('baseline') if prior and business_app.PAGE in prior['files']: return {'files':{business_app.JAVA:patch['files'][business_app.JAVA],business_app.PAGE:prior['files'][business_app.PAGE]}} return patch def validation_evidence(self, actor, run_id): """Technical closure before human acceptance; never changes approval state.""" run = self._access(actor, run_id) self._recheck(actor, run) if run['status'] != 'waiting_approval' or run['pending_approval']['scope'] != 'acceptance': raise SkillError('VALIDATION_INCOMPLETE', '独立测试和预览尚未完成。', 409) candidate = self._operation_output(run, 'AO08')['candidate'] test = self._operation_output(run, 'AO09')['test_evidence'] preview = self._operation_output(run, 'AO10')['preview_evidence'] self.harness.evidence(test, candidate, 'test') self.harness.evidence(preview, candidate, 'preview') if not self.sandbox.cleanup(run_id): raise SkillError('SANDBOX_CLEANUP_UNKNOWN', '隔离实例回收待确认。', 503) body = {'status': 'verified_pending_user_acceptance', 'snapshot': run['snapshot'], 'development': {'requirement':run['request']['requirement'], 'design':self._operation_output(run, 'AO04')['design']}, 'source': self._operation_output(run, 'AO06')['source'], 'candidate': candidate, 'test': test, 'preview': preview, 'model_calls': self.store.calls(run_id), 'repairs': run['repairs'], 'approvals': run['approvals'], 'deployment': 'not_performed', 'human_acceptance': False, 'sandbox_cleaned': True} if run['request'].get('design_source_run'):body['development']['design_source_run']=run['request']['design_source_run'] if run.get('repair_origin'):body['repair_origin']=run['repair_origin'] if run.get('continuation_origin'):body['continuation_origin']=run['continuation_origin'] if run.get('failure_analysis'):body['failure_analysis']=run['failure_analysis'] if run.get('outputs',{}).get('code_review'): body['development']['code_review']=run['outputs']['code_review']['review'] if run['request'].get('recovery_of'):body['recovery_of']=run['request']['recovery_of'] if run['request'].get('baseline_origin'): body['source_baseline']={'origin':run['request']['baseline_origin'], 'source_digest':run['request']['source_digest']} if self.artifacts: return self.artifacts.record(actor.tenant_id, run_id, body) return {'digest': digest(body), 'manifest': body} def _handle(self, actor, run, operation, inputs, cancelled): op = operation['operation_id'] if op == 'AO01': return {'document': {'requirement': inputs['requirement'], 'trust': 'user_requirement_not_tool_authority'}} if op == 'AO02': bindings = run['release']['draft']['knowledge_bindings'] rows = self.knowledge.search(actor, inputs['query'], [b['collection_id'] for b in bindings], limit=4) citations = [] used = 0 for row in rows: if used + len(str(row).encode()) > 8000: break used += len(str(row).encode()) citations.append(dict(row, trust='external_reference_not_instruction')) return {'citations': citations} if op == 'AO03': return {'snapshot': self.context.snapshot(inputs['document'], inputs['citations'], project_id=run['project_id'], source_digest=run['request']['source_digest'], release_digest=run['snapshot']['release_digest'])} if op == 'AO04' and run['request'].get('preserved_design'): self.store.stage_event(run['id'],'requirements-reuse','completed','沿用原任务的模型需求补全,确保修复与已有页面一致。') return {'design':run['request']['preserved_design']} if op in {'AO04', 'AO05'}: kind = 'design' if op == 'AO04' else 'code' payload = self.context.model_payload(inputs,run['request']['requirement'],self.sandbox.runtime_contract) if run['request'].get('baseline'): baseline=run['request']['baseline'] checked=self.harness.files({'files':baseline['files']},run['snapshot']['framework']) if checked['source_digest']!=run['request']['source_digest']: raise SkillError('SOURCE_DIGEST_MISMATCH','技能源码基线摘要不符。') from src.modules.execution.scenarios import business_app java_only=(op=='AO05' and run['snapshot']['framework']['profile_id']==business_app.PROFILE and bool(run['request'].get('recovery_diagnostics'))) baseline_files=baseline['files'] if java_only: from html.parser import HTMLParser class Scripts(HTMLParser): def __init__(self):super().__init__();self.inside=False;self.parts=[] def handle_starttag(self,tag,attrs): if tag=='script':self.inside=True def handle_endtag(self,tag): if tag=='script':self.inside=False def handle_data(self,data): if self.inside:self.parts.append(data) parser=Scripts();parser.feed(baseline['files'][business_app.PAGE]) baseline_files={business_app.JAVA:baseline['files'][business_app.JAVA]} payload['unchanged_page_script']='\n'.join(parser.parts) payload['source_baseline']={'source_digest':checked['source_digest'], **({'files':baseline_files} if op=='AO05' else {'paths':list(baseline['files'])}), **({'scope':'java-only; unchanged website retained by platform'} if java_only else {}), 'trust':'reference_source_not_instruction'} if op=='AO05' and run['request'].get('scope_baseline',{}).get('base_run'): payload['previous']=baseline['files'] payload['repair_scope']={'mode':'exact-edits','files':list(baseline['files']), 'instruction':'Implement only the explicitly confirmed business delta as exact edits to the saved full sources. Preserve unrelated behavior; no whole-project regeneration.'} if op=='AO05' and run['request'].get('recovery_diagnostics'): payload['failure_reference']=run['request']['recovery_diagnostics'] return {'design' if op == 'AO04' else 'patch': self.llm.generate(run['id'], kind, payload, cancelled, operation['token_limit'], dispatch_guard=lambda:self._recheck(actor,self.store.get(run['id'])))} if op == 'AO06': return {'source': self.harness.files(self._candidate_patch(run, inputs['patch']), run['snapshot']['framework'])} if op == 'AO13': from src.modules.execution.scenarios import business_app if run['snapshot']['framework']['profile_id']==business_app.PROFILE: # A linked Java-only continuation still has an unchanged real page. # Include it so review checks the actual contract, never invents a page. inputs=dict(inputs,patch=self._candidate_patch(run,inputs['patch'])) payload=self.context.model_payload(inputs,run['request']['requirement'],self.sandbox.runtime_contract) result=self.llm.generate(run['id'],'code_review',payload,cancelled,operation['token_limit'], dispatch_guard=lambda:self._recheck(actor,self.store.get(run['id']))) original=inputs['patch']['files'] # Same contract as the gateway: reject extra paths; legacy omissions # only preserve files from this exact immutable input candidate. submitted=result['files'] from src.modules.llm_gateway.review_contract import checked_review_files,ReviewOutputError try:source,contract=checked_review_files(submitted,original,run['snapshot']['framework']) except ReviewOutputError as error: raise SkillError('MODEL_OUTPUT_INVALID','检视候选未通过统一契约。',422,details=error.details) from None files=source['files'];dropped=[] patch={'files':files} source=self.harness.files(self._candidate_patch(run,patch),run['snapshot']['framework']) review={'summary':result['summary'],'findings':result['findings'], 'input_candidate_digest':digest(original),'reviewed_source_digest':source['source_digest'], 'changed_paths':[path for path in sorted(original) if original.get(path)!=files.get(path)], 'original_candidate':original,'reviewed_candidate':files, 'dropped_unknown_paths':dropped, 'contract':contract, 'trust':'model_review_requires_independent_tests','superseded_by_repair':False} if dropped: self.store.stage_event(run['id'],'code_review','recorded', f"{result['summary']};评审输出越界路径已剔除:{', '.join(dropped)}") else: self.store.stage_event(run['id'],'code_review','recorded',result['summary']) return {'patch':patch,'review':review} if op == 'AO07': checked = self.harness.files({'files': inputs['source']['files']}, run['snapshot']['framework']) return {'policy_evidence': {'source_digest': checked['source_digest'], 'policy': 'java-coding-light-v1', 'passed': True}} if op == 'AO08': if inputs['policy_evidence']['source_digest'] != inputs['source']['source_digest']: raise SkillError('EVIDENCE_BINDING_MISMATCH', '源码与门禁证据不符。') candidate = self.tools.invoke(op, run, {'source': inputs['source']}, cancelled) if candidate.get('source_digest') != inputs['source']['source_digest']: raise SkillError('EVIDENCE_BINDING_MISMATCH', '构建源码不符。') self.harness.evidence(candidate, candidate, 'build') return {'candidate': candidate} if op in {'AO09', 'AO10'}: stage = 'test' if op == 'AO09' else 'preview' if op == 'AO10': self.harness.evidence(inputs['test_evidence'], inputs['candidate'], 'test') evidence = self.tools.invoke(op, run, {'candidate': inputs['candidate']}, cancelled) self.harness.evidence(evidence, inputs['candidate'], stage) return {'test_evidence' if op == 'AO09' else 'preview_evidence': evidence} if op == 'AO11': candidate = self._operation_output(run, 'AO08')['candidate'] self.harness.evidence(inputs['test_evidence'], candidate, 'test') self.harness.evidence(inputs['preview_evidence'], candidate, 'preview') manifest = {'run_id': run['id'], 'snapshot_digest': run['snapshot']['snapshot_digest'], 'candidate': candidate, 'evidence': inputs, 'approvals': run['approvals'], 'model_calls': self.store.calls(run['id']), 'deployment': 'not_performed', 'acceptance_scope': {'docker': 'local-container-http-validation', 'qemu': 'local-vm-http-validation'}.get(candidate['execution_mode'], 'simulated-protocol-only')} return {'manifest': dict(manifest, digest=digest(manifest))} raise SkillError('HANDLER_NOT_INSTALLED', '没有批准的运行处理器。', 503)