"""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.""" stop = threading.Event() def beat(): 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', '执行器仍持有本任务租约,正在等待实际响应;本次心跳不代表编译或测试通过。') 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 {} 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['skill_id'] not in self.sandbox.skill_ids: raise SkillError('ACCEPTANCE_SUITE_NOT_BOUND', '该Skill未绑定服务端批准的独立测试套。', 409) counts = Counter(n.get('operation_ref', '').split('@')[0] for n in body['draft']['graph']['nodes'] if n['kind'] == 'operation') if counts != Counter({f'AO{i:02}': 1 for i in range(1, 12)}): 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} 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 = current['budget']['max_seconds'] - current['active_seconds'] if remaining <= 0: raise SkillError('RUN_TIME_BUDGET_EXCEEDED', '任务时间预算耗尽。', 409) current.update(status='running', claim=claim, claim_started_at=start, lease_until=start + min(remaining, 360)) run = self.store.mutate(run_id, take) 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 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','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','按定位建议修复源码;仍须独立编译和系统测试') with self.activity(run_id, claim, 'repair'): patch = self.llm.generate(run_id, 'repair', {'design':{'digest':digest(design)}, 'previous': self._operation_output(run, 'AO06')['source']['files'], 'failure_code': run['error'], 'diagnostics': self.repair_diagnostics(run), **({'failure_analysis':analysis} if analysis else {}), 'runtime_contract': self.sandbox.runtime_contract}, cancelled, 32000 if new_context else 26000 if run['snapshot']['framework']['profile_id']=='java17-pdfbox-web' else 20000, dispatch_guard=lambda:self._recheck(actor,self.store.get(run_id))) self.harness.files(patch, 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': patch} run = self._write(run_id, claim, {'outputs': outputs, 'cursor': cursor, 'repair_pending': False, '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'}: 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.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 or self.clock() > current.get('lease_until', 0): status = 'unknown' elif current['cancel_requested'] or exc.code == 'RUN_CANCELLED': status = 'cancelled' elif exc.code in REPAIRABLE and current['repairs'] < current['budget']['max_repairs']: status = 'repair_required' else: status = 'failed' return self._finish(run_id, claim, status, exc.code) except Exception: 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): 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) return self.store.mutate(run_id, finish) 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']: raise SkillError('REPAIR_NOT_ALLOWED', '不可修复或次数耗尽。', 409) current.update(status='queued', repair_pending=True, 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']] 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.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['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 seen = set() for row in rows: # 1. 跳过内容完全相同的知识 content_hash = row.get('content_sha256') if content_hash and content_hash in seen: continue # 2. 保留原来的 8000 Bytes 限制 citation = dict( row, trust='external_reference_not_instruction') size = len(str(citation).encode('utf-8')) if used + size > 8000: continue # 3. 记录已经选过的知识 citations.append(citation) used += size if content_hash: seen.add(content_hash) 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 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','技能源码基线摘要不符。') payload['source_baseline']={'source_digest':checked['source_digest'], **({'files':baseline['files']} if op=='AO05' else {'paths':list(baseline['files'])}), 'trust':'reference_source_not_instruction'} 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(inputs['patch'], run['snapshot']['framework'])} 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)