dellweb3 commited on
Commit
8a54d70
·
verified ·
1 Parent(s): 85a8dbe

Upload src/modules/orchestrator/service.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src/modules/orchestrator/service.py +451 -0
src/modules/orchestrator/service.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Durable, explicitly driven interpreter for published Java Skill graphs."""
2
+ import time
3
+ import uuid
4
+ import threading
5
+ from contextlib import contextmanager
6
+ from collections import Counter
7
+ from src.modules.skill.domain.models import SkillError, digest
8
+ from src.modules.context.service import ContextService
9
+ from src.modules.tool_gateway.service import ToolGateway
10
+
11
+ TERMINAL = {'succeeded', 'failed', 'unknown', 'cancelled'}
12
+ UNKNOWN = {'MODEL_RESULT_UNKNOWN', 'MODEL_USAGE_INVALID', 'MODEL_OUTPUT_INCOMPLETE',
13
+ 'MODEL_RESPONSE_TOO_LARGE', 'SANDBOX_TIMEOUT', 'SANDBOX_CLEANUP_UNKNOWN', 'INVALID_SANDBOX_RECEIPT', 'VM_RESULT_UNKNOWN'}
14
+ REPAIRABLE = {'JAVA_BUILD_FAILED', 'JAVA_TEST_FAILED'}
15
+
16
+
17
+ class AgentRuntime:
18
+ activity_interval = 5
19
+ def __init__(self, store, skills, knowledge, llm, harness, sandbox, *, clock=time.time, artifacts=None):
20
+ self.store, self.skills, self.knowledge = store, skills, knowledge
21
+ self.llm, self.harness, self.sandbox, self.clock = llm, harness, sandbox, clock
22
+ self.context = ContextService()
23
+ self.tools = ToolGateway(sandbox, harness)
24
+ self.artifacts = artifacts
25
+
26
+ @contextmanager
27
+ def activity(self, run_id, claim, stage):
28
+ """A live interpreter lease heartbeat, never an invented model/test result."""
29
+ stop = threading.Event()
30
+ def beat():
31
+ while not stop.wait(self.activity_interval):
32
+ try:
33
+ run = self.store.get(run_id)
34
+ if run['claim'] != claim or run['status'] != 'running' or run['cancel_requested'] or self.clock() > run['lease_until']:
35
+ return
36
+ self.store.stage_event(run_id, stage, 'active',
37
+ '执行器仍持有本任务租约,正在等待实际响应;本次心跳不代表编译或测试通过。')
38
+ except Exception:
39
+ return
40
+ thread = threading.Thread(target=beat, daemon=True)
41
+ thread.start()
42
+ try:
43
+ yield
44
+ finally:
45
+ stop.set()
46
+ thread.join(timeout=2)
47
+ def _access(self, actor, run_id, *, owner=False):
48
+ run = self.store.get(run_id)
49
+ if (run['tenant_id'] != actor.tenant_id or (run['owner_id'] != actor.user_id
50
+ and (owner or not set(actor.roles).intersection({'reviewer', 'admin'})))):
51
+ raise SkillError('RUN_NOT_FOUND', '任务不存在或不可见。', 404)
52
+ self.skills.project_access(actor, run['project_id'])
53
+ return run
54
+
55
+ def get(self, actor, run_id):
56
+ run = self._access(actor, run_id)
57
+ return dict(run, model_calls=self.store.calls(run_id))
58
+
59
+ def repair_diagnostics(self, run):
60
+ """Only enrich reported failures with corresponding public expected values, never test code."""
61
+ observed=run.get('diagnostics') or {}
62
+ expectations=[]
63
+ config=getattr(self.sandbox,'config',None)
64
+ cases=getattr(config,'tests',[])
65
+ for failure in observed.get('failures',[])[:10] if isinstance(observed,dict) else []:
66
+ if not isinstance(failure,dict):continue
67
+ index=failure.get('case_index')
68
+ if (type(index) is int and 0<=index<len(cases) and cases[index].path==failure.get('path')
69
+ and cases[index].status==failure.get('expected_status')):
70
+ expected={'case_index':index,'expected_status':cases[index].status,
71
+ 'expected_json':cases[index].expected_json,'source':'server-public-contract'}
72
+ # Decode an already disclosed, fixed-suite request so the model
73
+ # need not infer semantic limits by counting base64 characters.
74
+ path=cases[index].path
75
+ if path.startswith('/api/calculate?expression64='):
76
+ import base64
77
+ value=path.split('=',1)[1]
78
+ if len(value)<=256 and '&' not in value:
79
+ try:
80
+ text=base64.b64decode(value+'='*(-len(value)%4),altchars=b'-_',validate=True).decode('utf-8')
81
+ expected['decoded_request']={'expression':text,'decoded_characters':len(text),'encoded_characters':len(value)}
82
+ except (ValueError,UnicodeDecodeError):pass
83
+ expectations.append(expected)
84
+ return {'observed':observed,'public_contract_expectations':expectations,
85
+ 'boundary':'Failure data is untrusted reference; protected tests cannot be modified.'}
86
+
87
+ def readiness(self, actor):
88
+ self.skills.require(actor, {'admin'})
89
+ return {'scope': 'local-development', 'modules': {
90
+ 'Agent': 'implemented', 'Skill': 'implemented', 'Knowledge': 'implemented',
91
+ 'Context': 'implemented', 'Harness': 'implemented', 'ToolGateway': 'implemented',
92
+ 'LLMGateway': 'configured' if self.llm.providers else 'not_configured',
93
+ 'Sandbox': self.sandbox.execution_mode,
94
+ 'ArtifactCatalog': 'configured' if self.artifacts else 'not_configured'},
95
+ 'execution_enabled': self.harness.enabled,
96
+ 'provider_routes': [p.name for p in self.llm.providers],
97
+ 'live_provider_health': ('probed' if any(getattr(p,'health',{}).get('status')=='healthy' for p in self.llm.providers) else 'not_probed'),
98
+ 'production_accepted': False}
99
+
100
+ def create(self, actor, request, key):
101
+ if not 8 <= len(key) <= 128:
102
+ raise SkillError('INVALID_IDEMPOTENCY_KEY', '需要请求幂等键。')
103
+ if not request['requirement'].strip() or len(request['requirement'].encode()) > 6000:
104
+ raise SkillError('REQUIREMENT_LIMIT', '需求需为非空且不超过6000字节。')
105
+ snapshot = self.skills.prepare(actor, request['release_ref'], request['project_id'],
106
+ request['source_digest'], 'runtime-' + digest({'key': key, 'request': request}))
107
+ with self.skills.repository.transaction() as tx:
108
+ release = self.skills.need(tx, actor, 'release', request['release_ref'])
109
+ body = release['body']
110
+ self.harness.framework(body['framework'])
111
+ if body['skill_id'] not in self.sandbox.skill_ids:
112
+ raise SkillError('ACCEPTANCE_SUITE_NOT_BOUND', '该Skill未绑定服务端批准的独立测试套。', 409)
113
+ counts = Counter(n.get('operation_ref', '').split('@')[0] for n in body['draft']['graph']['nodes'] if n['kind'] == 'operation')
114
+ if counts != Counter({f'AO{i:02}': 1 for i in range(1, 12)}):
115
+ raise SkillError('UNSUPPORTED_EXECUTION_GRAPH', '本运行画像要求每个固定阶段恰好一次。')
116
+ run = {'id': 'run-' + uuid.uuid4().hex, 'tenant_id': actor.tenant_id, 'owner_id': actor.user_id,
117
+ 'project_id': request['project_id'], 'request': request, 'snapshot': snapshot, 'release': body,
118
+ 'budget': snapshot['budget'], 'status': 'queued', 'revision': 1, 'cursor': 0, 'outputs': {},
119
+ 'approvals': [], 'repairs': 0, 'cancel_requested': False, 'claim': None,
120
+ 'created_at': self.clock(), 'active_seconds': 0.0, 'error': None}
121
+ return self.store.create(run, key, request)
122
+
123
+ def trial(self, actor, skill_id, request, key):
124
+ self.skills.read_draft(actor, skill_id)
125
+ if request['release_ref'].split('@')[0] != skill_id:
126
+ raise SkillError('SKILL_RELEASE_MISMATCH', '试运行必须绑定同一Skill的已发布版本。')
127
+ return self.create(actor, request, key)
128
+
129
+ def _recheck(self, actor, run):
130
+ checked = self.skills.prepare(actor, run['request']['release_ref'], run['project_id'],
131
+ run['request']['source_digest'], 'recheck-' + run['id'], inspect_only=True)
132
+ if checked['release_digest'] != run['snapshot']['release_digest']:
133
+ raise SkillError('RELEASE_CHANGED', 'Skill发布摘要变化。', 409)
134
+ self.harness.framework(run['snapshot']['framework'])
135
+
136
+ def _write(self, run_id, claim, updates):
137
+ def change(run):
138
+ if run['claim'] != claim or run['status'] != 'running':
139
+ raise SkillError('RUN_CLAIM_LOST', '运行租约已失效。', 409)
140
+ if run['cancel_requested']:
141
+ raise SkillError('RUN_CANCELLED', '任务已取消。', 409)
142
+ if updates.get('status', 'running') != 'running':
143
+ run['active_seconds'] += max(0, self.clock() - run['claim_started_at'])
144
+ run.update(updates)
145
+ return self.store.mutate(run_id, change)
146
+
147
+ def advance(self, actor, run_id):
148
+ run = self._access(actor, run_id, owner=True)
149
+ self._recheck(actor, run)
150
+ claim = uuid.uuid4().hex
151
+ start = self.clock()
152
+ def take(current):
153
+ if current['status'] != 'queued' or current['cancel_requested']:
154
+ raise SkillError('RUN_NOT_QUEUED', '任务不能重复推进。', 409)
155
+ remaining = current['budget']['max_seconds'] - current['active_seconds']
156
+ if remaining <= 0:
157
+ raise SkillError('RUN_TIME_BUDGET_EXCEEDED', '任务时间预算耗尽。', 409)
158
+ current.update(status='running', claim=claim, claim_started_at=start, lease_until=start + min(remaining, 360))
159
+ run = self.store.mutate(run_id, take)
160
+ def cancelled():
161
+ state = self.store.get(run_id)
162
+ return state['cancel_requested'] or state['claim'] != claim or self.clock() > state['lease_until']
163
+ try:
164
+ if run.get('repair_pending'):
165
+ self.store.stage_event(run_id,'repair','started','根据实际编译或测试诊断请求模型修复')
166
+ design=self._operation_output(run, 'AO04')['design']
167
+ new_context=any(op['operation_id']=='AO05' and op['version']=='0.2.0' for op in run['release']['operations'].values())
168
+ analysis=None
169
+ if (new_context and run['repairs']>=2 and run['budget']['max_model_calls']-len(self.store.calls(run_id))>=2
170
+ and any('diagnose' in getattr(p,'task_roles',[]) for p in self.llm.providers)):
171
+ failure=self.repair_diagnostics(run)
172
+ observed=failure['observed']
173
+ if isinstance(observed,dict) and 'failures' in observed:
174
+ failure={**failure,'observed':{**observed,'failures':observed['failures'][:3]},
175
+ 'public_contract_expectations':failure['public_contract_expectations'][:3]}
176
+ self.store.stage_event(run_id,'diagnosis','started','修复后仍未通过,先定位最小失败请求的具体代码原因')
177
+ try:
178
+ with self.activity(run_id,claim,'diagnosis'):
179
+ hypothesis=self.llm.generate(run_id,'diagnose',{'source':self._operation_output(run,'AO06')['source']['files'],
180
+ 'failure':failure,'runtime_contract':self.sandbox.runtime_contract},cancelled,26000,
181
+ dispatch_guard=lambda:self._recheck(actor,self.store.get(run_id)))
182
+ analysis={**hypothesis,'source_digest':self._operation_output(run,'AO06')['source']['source_digest'],
183
+ 'trust':'model_hypothesis_requires_independent_tests'}
184
+ run=self._write(run_id,claim,{'failure_analysis':analysis})
185
+ self.store.stage_event(run_id,'diagnosis','completed',hypothesis['summary'])
186
+ except SkillError as exc:
187
+ if exc.code not in {'CONTEXT_BUDGET_EXCEEDED','MODEL_ROUTE_UNAVAILABLE','MODEL_OUTPUT_INVALID','MODEL_OUTPUT_TRUNCATED'}:raise
188
+ self.store.stage_event(run_id,'diagnosis','skipped','诊断建议不可用:'+exc.code+';调用记录保留,按原预算修复')
189
+ if analysis:self.store.stage_event(run_id,'repair','started','按定位建议修复源码;仍须独立编译和系统测试')
190
+ with self.activity(run_id, claim, 'repair'):
191
+ patch = self.llm.generate(run_id, 'repair', {'design':{'digest':digest(design)},
192
+ 'previous': self._operation_output(run, 'AO06')['source']['files'], 'failure_code': run['error'],
193
+ 'diagnostics': self.repair_diagnostics(run),
194
+ **({'failure_analysis':analysis} if analysis else {}),
195
+ 'runtime_contract': self.sandbox.runtime_contract}, cancelled,
196
+ 32000 if new_context else 26000 if run['snapshot']['framework']['profile_id']=='java17-pdfbox-web' else 20000,
197
+ dispatch_guard=lambda:self._recheck(actor,self.store.get(run_id)))
198
+ self.harness.files(patch, run['snapshot']['framework'])
199
+ outputs = dict(run['outputs'])
200
+ nodes = run['release']['draft']['graph']['nodes']
201
+ code = next(n['id'] for n in nodes if (n.get('operation_ref') or '').startswith('AO05@'))
202
+ apply = next(n['id'] for n in nodes if (n.get('operation_ref') or '').startswith('AO06@'))
203
+ cursor = run['release']['execution_order'].index(apply)
204
+ for nid in run['release']['execution_order'][cursor:]:
205
+ outputs.pop(nid, None)
206
+ outputs[code] = {'patch': patch}
207
+ run = self._write(run_id, claim, {'outputs': outputs, 'cursor': cursor, 'repair_pending': False, 'error': None})
208
+ self.store.stage_event(run_id,'repair','completed','修复候选已返回;尚需重新构建与独立测试')
209
+ return self._wait(run, claim, 'repair-execution', 'execution', increment=False)
210
+ while run['cursor'] < len(run['release']['execution_order']):
211
+ if cancelled():
212
+ raise SkillError('RUN_CANCELLED', '运行取消或租约到期。', 409)
213
+ self._recheck(actor, run)
214
+ node_id = run['release']['execution_order'][run['cursor']]
215
+ node = next(n for n in run['release']['draft']['graph']['nodes'] if n['id'] == node_id)
216
+ if node['kind'] == 'approval':
217
+ self.store.stage_event(run_id,node_id,'waiting','等待'+{'design':'设计','execution':'执行','acceptance':'用户验收'}.get(node['approval_scope'],node['approval_scope'])+'确认')
218
+ return self._wait(run, claim, node_id, node['approval_scope'])
219
+ self.store.stage_event(run_id,node_id,'started')
220
+ inputs = dict(node['inputs'])
221
+ for edge in run['release']['draft']['graph']['data_edges']:
222
+ if edge['target'] == node_id:
223
+ inputs[edge['target_port']] = run['outputs'][edge['source']][edge['source_port']]
224
+ if node['kind'] == 'start':
225
+ result = {'requirement': run['request']['requirement'], 'query': run['request']['query']}
226
+ elif node['kind'] == 'end':
227
+ result = {'manifest': inputs['manifest']}
228
+ else:
229
+ operation = run['release']['operations'][node['operation_ref']]
230
+ if operation['operation_id'] in {'AO04', 'AO05', 'AO08'}:
231
+ with self.activity(run_id, claim, node_id):
232
+ result = self._handle(actor, run, operation, inputs, cancelled)
233
+ else:
234
+ result = self._handle(actor, run, operation, inputs, cancelled)
235
+ outputs = dict(run['outputs'], **{node_id: result})
236
+ run = self._write(run_id, claim, {'outputs': outputs, 'cursor': run['cursor'] + 1})
237
+ self.store.stage_event(run_id,node_id,'completed')
238
+ if not self.sandbox.cleanup(run_id):
239
+ raise SkillError('SANDBOX_CLEANUP_UNKNOWN', '回收状态未知。', 503)
240
+ return self._finish(run_id, claim, 'succeeded')
241
+ except SkillError as exc:
242
+ 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)
243
+ current = self.store.get(run_id)
244
+ self.store.mutate(run_id, lambda r: r.update(failure_details=exc.details))
245
+ if exc.code in REPAIRABLE:
246
+ self.store.mutate(run_id, lambda r: r.update(diagnostics=exc.details))
247
+ cleaned = self.sandbox.cleanup(run_id)
248
+ unknown_call = any(c['state'] in {'unknown', 'reserved'} for c in self.store.calls(run_id))
249
+ if not cleaned or exc.code in UNKNOWN or unknown_call or self.clock() > current.get('lease_until', 0):
250
+ status = 'unknown'
251
+ elif current['cancel_requested'] or exc.code == 'RUN_CANCELLED':
252
+ status = 'cancelled'
253
+ elif exc.code in REPAIRABLE and current['repairs'] < current['budget']['max_repairs']:
254
+ status = 'repair_required'
255
+ else:
256
+ status = 'failed'
257
+ return self._finish(run_id, claim, status, exc.code)
258
+ except Exception:
259
+ self.store.stage_event(run_id,'execution','unknown','EXECUTION_RESULT_UNKNOWN')
260
+ self.sandbox.cleanup(run_id)
261
+ return self._finish(run_id, claim, 'unknown', 'EXECUTION_RESULT_UNKNOWN')
262
+
263
+ def _finish(self, run_id, claim, status, error=None):
264
+ def finish(run):
265
+ if run['claim'] != claim:
266
+ raise SkillError('RUN_CLAIM_LOST', '运行租约已失效。', 409)
267
+ if run['cancel_requested'] and status == 'succeeded':
268
+ status_value = 'cancelled'
269
+ else:
270
+ status_value = status
271
+ run['active_seconds'] += max(0, self.clock() - run['claim_started_at'])
272
+ run.update(status=status_value, error=error, claim=None)
273
+ return self.store.mutate(run_id, finish)
274
+
275
+ def _wait(self, run, claim, node, scope, increment=True):
276
+ approval = {'node': node, 'scope': scope, 'increment': increment,
277
+ 'digest': digest({'run': run['id'], 'snapshot': run['snapshot']['snapshot_digest'],
278
+ 'outputs': run['outputs'], 'node': node, 'repairs': run['repairs']})}
279
+ return self._write(run['id'], claim, {'pending_approval': approval, 'status': 'waiting_approval', 'claim': None})
280
+
281
+ def approve(self, actor, run_id, expected_digest, *, delegation=None):
282
+ run = self._access(actor, run_id)
283
+ self._recheck(actor, run)
284
+ def approve(current):
285
+ pending = current.get('pending_approval')
286
+ if current['status'] != 'waiting_approval' or not pending or pending['digest'] != expected_digest:
287
+ raise SkillError('APPROVAL_TARGET_CHANGED', '确认对象已变化。', 409)
288
+ if pending['scope'] == 'acceptance' and (actor.user_id == current['owner_id'] or not set(actor.roles).intersection({'reviewer', 'admin'})):
289
+ raise SkillError('INDEPENDENT_REVIEW_REQUIRED', '最终验收需要独立评审人。', 403)
290
+ if delegation and (pending['scope'] == 'acceptance' or current['release'].get('publication_scope') != 'local-validation-only'
291
+ or delegation != current['release'].get('authorization_ref')):
292
+ raise SkillError('VALIDATION_SCOPE_REQUIRED', '委托不能扩大到人工验收或其他版本。', 403)
293
+ current['approvals'].append(dict(pending, user_id=actor.user_id,
294
+ **({'mechanism': 'delegated_local_validation', 'authorization_ref': delegation} if delegation else {})))
295
+ current['cursor'] += int(pending['increment'])
296
+ current.update(status='queued', pending_approval=None)
297
+ return self.store.mutate(run_id, approve)
298
+
299
+ def repair(self, actor, run_id):
300
+ self._access(actor, run_id, owner=True)
301
+ def repair(current):
302
+ if current['status'] != 'repair_required' or current['repairs'] >= current['budget']['max_repairs']:
303
+ raise SkillError('REPAIR_NOT_ALLOWED', '不可修复或次数耗尽。', 409)
304
+ current.update(status='queued', repair_pending=True, repairs=current['repairs'] + 1)
305
+ return self.store.mutate(run_id, repair)
306
+
307
+ def cancel(self, actor, run_id):
308
+ self._access(actor, run_id, owner=True)
309
+ def cancel(current):
310
+ if current['status'] in TERMINAL:
311
+ return
312
+ current['cancel_requested'] = True
313
+ if current['status'] != 'running':
314
+ current['status'] = 'cancelled'
315
+ run = self.store.mutate(run_id, cancel)
316
+ if run['status'] == 'cancelled' and not self.sandbox.cleanup(run_id):
317
+ run = self.store.mutate(run_id, lambda r: r.update(status='unknown', error='SANDBOX_CLEANUP_UNKNOWN'))
318
+ return run
319
+
320
+ def recover(self, actor, run_id):
321
+ self._access(actor, run_id, owner=True)
322
+ def recover(run):
323
+ if run['status'] != 'running' or self.clock() <= run['lease_until']:
324
+ raise SkillError('RECOVERY_NOT_ALLOWED', '仅可恢复租约已过期的运行任务。', 409)
325
+ run['active_seconds'] += max(0, self.clock() - run.get('claim_started_at', self.clock()))
326
+ run.update(status='unknown', claim=None, error='WORKER_RESULT_UNKNOWN')
327
+ run = self.store.mutate(run_id, recover)
328
+ self.sandbox.cleanup(run_id)
329
+ return run
330
+
331
+ @staticmethod
332
+ def _operation_output(run, operation):
333
+ node = next(n for n in run['release']['draft']['graph']['nodes'] if (n.get('operation_ref') or '').startswith(operation + '@'))
334
+ return run['outputs'][node['id']]
335
+
336
+ def validation_evidence(self, actor, run_id):
337
+ """Technical closure before human acceptance; never changes approval state."""
338
+ run = self._access(actor, run_id)
339
+ self._recheck(actor, run)
340
+ if run['status'] != 'waiting_approval' or run['pending_approval']['scope'] != 'acceptance':
341
+ raise SkillError('VALIDATION_INCOMPLETE', '独立测试和预览尚未完成。', 409)
342
+ candidate = self._operation_output(run, 'AO08')['candidate']
343
+ test = self._operation_output(run, 'AO09')['test_evidence']
344
+ preview = self._operation_output(run, 'AO10')['preview_evidence']
345
+ self.harness.evidence(test, candidate, 'test')
346
+ self.harness.evidence(preview, candidate, 'preview')
347
+ if not self.sandbox.cleanup(run_id):
348
+ raise SkillError('SANDBOX_CLEANUP_UNKNOWN', '隔离实例回收待确认。', 503)
349
+ body = {'status': 'verified_pending_user_acceptance', 'snapshot': run['snapshot'],
350
+ 'development': {'requirement':run['request']['requirement'],
351
+ 'design':self._operation_output(run, 'AO04')['design']},
352
+ 'source': self._operation_output(run, 'AO06')['source'], 'candidate': candidate,
353
+ 'test': test, 'preview': preview, 'model_calls': self.store.calls(run_id),
354
+ 'repairs': run['repairs'], 'approvals': run['approvals'],
355
+ 'deployment': 'not_performed', 'human_acceptance': False, 'sandbox_cleaned': True}
356
+ if run.get('repair_origin'):body['repair_origin']=run['repair_origin']
357
+ if run.get('continuation_origin'):body['continuation_origin']=run['continuation_origin']
358
+ if run.get('failure_analysis'):body['failure_analysis']=run['failure_analysis']
359
+ if run['request'].get('recovery_of'):body['recovery_of']=run['request']['recovery_of']
360
+ if run['request'].get('baseline_origin'):
361
+ body['source_baseline']={'origin':run['request']['baseline_origin'],
362
+ 'source_digest':run['request']['source_digest']}
363
+ if self.artifacts:
364
+ return self.artifacts.record(actor.tenant_id, run_id, body)
365
+ return {'digest': digest(body), 'manifest': body}
366
+
367
+ def _handle(self, actor, run, operation, inputs, cancelled):
368
+ op = operation['operation_id']
369
+ if op == 'AO01':
370
+ return {'document': {'requirement': inputs['requirement'], 'trust': 'user_requirement_not_tool_authority'}}
371
+ if op == 'AO02':
372
+ bindings = run['release']['draft']['knowledge_bindings']
373
+ rows = self.knowledge.search(actor, inputs['query'], [b['collection_id'] for b in bindings], limit=4)
374
+ citations = []
375
+ used = 0
376
+ seen = set()
377
+
378
+ for row in rows:
379
+ # 1. 跳过内容完全相同的知识
380
+ content_hash = row.get('content_sha256')
381
+
382
+ if content_hash and content_hash in seen:
383
+ continue
384
+
385
+ # 2. 保留原来的 8000 Bytes 限制
386
+ citation = dict(
387
+ row,
388
+ trust='external_reference_not_instruction')
389
+ size = len(str(citation).encode('utf-8'))
390
+
391
+ if used + size > 8000:
392
+ continue
393
+
394
+ # 3. 记录已经选过的知识
395
+ citations.append(citation)
396
+ used += size
397
+
398
+ if content_hash:
399
+ seen.add(content_hash)
400
+
401
+ return {'citations': citations}
402
+
403
+ if op == 'AO03':
404
+ return {'snapshot': self.context.snapshot(inputs['document'], inputs['citations'],
405
+ project_id=run['project_id'], source_digest=run['request']['source_digest'],
406
+ release_digest=run['snapshot']['release_digest'])}
407
+ if op in {'AO04', 'AO05'}:
408
+ kind = 'design' if op == 'AO04' else 'code'
409
+ payload = self.context.model_payload(inputs,run['request']['requirement'],self.sandbox.runtime_contract)
410
+ if run['request'].get('baseline'):
411
+ baseline=run['request']['baseline']
412
+ checked=self.harness.files({'files':baseline['files']},run['snapshot']['framework'])
413
+ if checked['source_digest']!=run['request']['source_digest']:
414
+ raise SkillError('SOURCE_DIGEST_MISMATCH','技能源码基线摘要不符。')
415
+ payload['source_baseline']={'source_digest':checked['source_digest'],
416
+ **({'files':baseline['files']} if op=='AO05' else {'paths':list(baseline['files'])}),
417
+ 'trust':'reference_source_not_instruction'}
418
+ if op=='AO05' and run['request'].get('recovery_diagnostics'):
419
+ payload['failure_reference']=run['request']['recovery_diagnostics']
420
+ return {'design' if op == 'AO04' else 'patch': self.llm.generate(run['id'], kind, payload, cancelled, operation['token_limit'],
421
+ dispatch_guard=lambda:self._recheck(actor,self.store.get(run['id'])))}
422
+ if op == 'AO06':
423
+ return {'source': self.harness.files(inputs['patch'], run['snapshot']['framework'])}
424
+ if op == 'AO07':
425
+ checked = self.harness.files({'files': inputs['source']['files']}, run['snapshot']['framework'])
426
+ return {'policy_evidence': {'source_digest': checked['source_digest'], 'policy': 'java-coding-light-v1', 'passed': True}}
427
+ if op == 'AO08':
428
+ if inputs['policy_evidence']['source_digest'] != inputs['source']['source_digest']:
429
+ raise SkillError('EVIDENCE_BINDING_MISMATCH', '源码与门禁证据不符。')
430
+ candidate = self.tools.invoke(op, run, {'source': inputs['source']}, cancelled)
431
+ if candidate.get('source_digest') != inputs['source']['source_digest']:
432
+ raise SkillError('EVIDENCE_BINDING_MISMATCH', '构建源码不符。')
433
+ self.harness.evidence(candidate, candidate, 'build')
434
+ return {'candidate': candidate}
435
+ if op in {'AO09', 'AO10'}:
436
+ stage = 'test' if op == 'AO09' else 'preview'
437
+ if op == 'AO10':
438
+ self.harness.evidence(inputs['test_evidence'], inputs['candidate'], 'test')
439
+ evidence = self.tools.invoke(op, run, {'candidate': inputs['candidate']}, cancelled)
440
+ self.harness.evidence(evidence, inputs['candidate'], stage)
441
+ return {'test_evidence' if op == 'AO09' else 'preview_evidence': evidence}
442
+ if op == 'AO11':
443
+ candidate = self._operation_output(run, 'AO08')['candidate']
444
+ self.harness.evidence(inputs['test_evidence'], candidate, 'test')
445
+ self.harness.evidence(inputs['preview_evidence'], candidate, 'preview')
446
+ manifest = {'run_id': run['id'], 'snapshot_digest': run['snapshot']['snapshot_digest'],
447
+ 'candidate': candidate, 'evidence': inputs, 'approvals': run['approvals'],
448
+ 'model_calls': self.store.calls(run['id']), 'deployment': 'not_performed',
449
+ 'acceptance_scope': {'docker': 'local-container-http-validation', 'qemu': 'local-vm-http-validation'}.get(candidate['execution_mode'], 'simulated-protocol-only')}
450
+ return {'manifest': dict(manifest, digest=digest(manifest))}
451
+ raise SkillError('HANDLER_NOT_INSTALLED', '没有批准的运行处理器。', 503)