"""Run real native-Harness blocker diagnosis with memory-only resource fixtures.""" from __future__ import annotations import json import os from pathlib import Path from queue import Queue import subprocess import sys from threading import Event, Thread from time import monotonic from uuid import uuid4 REPO = Path(__file__).resolve().parents[1] sys.path.insert(0, str(REPO / 'src')) class NativeDiagnosis: """Use the production stdin/stdout protocol without exposing provider values.""" def __init__(self, root): from dx_productivity.dsh.native_runtime import launch_environment, node_executable from dx_productivity.dsh.provider_config import load_provider from dx_productivity.trial_task_center.application import resolve_data_root directory = root / 'dsh' directory.mkdir(parents=True, exist_ok=True) (directory / 'task-context.json').write_text(json.dumps({ 'task_id': 'unrelated-live-task', 'revision': 'unrelated-live-revision'}), encoding='utf8') provider = load_provider(resolve_data_root(None) / 'dsh') environment = launch_environment(directory) | provider assert all(environment.get(key) for key in ('DSH_API_BASE', 'DSH_MODEL', 'DSH_API_KEY')), 'provider_not_configured' self.process = subprocess.Popen([node_executable(), str(REPO / 'integration/dsh/start.mjs')], cwd=REPO, env=environment, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding='utf8', creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0) self.events, self.calls = Queue(), [] Thread(target=self._read, daemon=True).start() def _read(self): for line in self.process.stdout: if line.startswith('DX_DSH_READY '): self.events.put({'status': 'ready'}) elif line.startswith('DX_DSH_DIAGNOSIS '): self.events.put(json.loads(line[len('DX_DSH_DIAGNOSIS '):])) self.events.put({'status': 'runtime_exited'}) def __enter__(self): try: assert self.events.get(timeout=65)['status'] == 'ready', 'native_runtime_not_ready' except BaseException: self.close() raise return self def __call__(self, incident_id, snapshot, evidence, phase): request_id = uuid4().hex request = {'type': 'diagnose', 'request_id': request_id, 'incident_id': incident_id, 'snapshot': snapshot, 'evidence': evidence, 'phase': phase} self.process.stdin.write(json.dumps(request, ensure_ascii=False) + '\n') self.process.stdin.flush() deadline = monotonic() + 240 while True: remaining = deadline - monotonic() if remaining <= 0: raise TimeoutError('native_diagnosis_deadline') value = self.events.get(timeout=remaining) assert value.get('status') != 'runtime_exited', 'native_runtime_exited' if value.get('request_id') != request_id or value.get('status') == 'started': continue assert value.get('status') == 'completed', 'native_diagnosis_did_not_complete' self.calls.append({'incident_id': incident_id, 'phase': phase, 'session_id': value.get('session_id', '')}) return value def close(self): if self.process.stdin: self.process.stdin.close() try: self.process.wait(timeout=8) except subprocess.TimeoutExpired: self.process.kill() self.process.wait(timeout=8) self.process.stdout.close() def __exit__(self, *args): self.close() class OwnedResourceFixture: """No CAD, OS process handles, or engineering files exist in this fixture.""" def __init__(self): self.pending = [{'session_id': 'controlled-owned-session', 'state': 'blocked', 'resource_type': 'in-memory-owned-resource-fixture'}] self.calls, self.context_calls, self.pending_reads = [], 0, 0 def task_context(self, task_id): self.context_calls += 1 raise AssertionError('cached_snapshot_must_not_read_live_task_context') def pending_batch_resources(self): self.pending_reads += 1 return tuple(dict(item) for item in self.pending) def cleanup_batch_resources(self): self.calls.append('cleanup') self.pending.clear() return () def prepare_failed_quick_run(self, *args, **kwargs): self.calls.append('forbidden_prepare') raise AssertionError('engineering_mutation_forbidden') def execute_quick_run_queue(self, *args, **kwargs): self.calls.append('forbidden_execute') raise AssertionError('engineering_mutation_forbidden') def main(): from dx_productivity.dsh.incidents import IncidentRunner, decision root = REPO / 'build' / ('dsh-blocker-recovery-' + uuid4().hex[:8]) root.mkdir(parents=True) report_path = root / 'report.json' service, publication_attempts = OwnedResourceFixture(), [] report = {'status': 'running', 'model': 'real configured API through native Harness', 'executor': 'in-memory fixture; no CAD or OS process writes', 'remoteIssueWrites': 0} def local_outbox(record, archive): assert archive.is_file(), 'missing_local_evidence_archive' publication_attempts.append(record['incident_id']) return {'status': 'unavailable', 'reason': 'remote_publication_disabled_for_acceptance'} try: with NativeDiagnosis(root) as native: permission = Event() permission.set() runner = IncidentRunner(root, service, native, local_outbox) cleanup = runner.run('controlled-resource-task', 'batch_resources_pending', '受控资源释放验收:任务队列已空闲,仅有一个本验收持有的内存资源待释放。' '资源所有权已在受控服务中确认;cleanup_allowed=true。' '资源释放不会打开工程、恢复队列或执行 CAD;不需要原始 CAD 执行授权。', run_id='controlled-resource-run', execution_enabled=permission, cleanup_allowed=True, snapshot_override={'task_id': 'controlled-resource-task', 'task_name': '受控自有资源释放', 'status': 'blocked', 'progress': {}}, trigger={'operation': 'release_resources', 'source': 'controlled-owned-resource-fixture', 'outcome': 'resources_pending', 'task_queue_idle': True, 'ownership_verified': True, 'pending_resources': service.pending_batch_resources()}) report['cleanupIncident'] = cleanup assert decision(cleanup['analyses'][0]['reply'])['action'] == 'cleanup_resources', 'model_did_not_recommend_cleanup' assert cleanup['status'] == 'resolved', 'cleanup_not_resolved' assert cleanup['verification']['resources_released'] is True, 'resources_not_verified_released' assert cleanup['verification']['remaining_resources'] == [], 'resources_still_pending' assert service.calls == ['cleanup'], 'unexpected_cleanup_or_engineering_call' assert service.pending_reads >= 3, 'missing_independent_resource_reread' assert service.context_calls == 0, 'cleanup_read_live_task_context' assert not publication_attempts, 'resolved_cleanup_attempted_publication' stall = runner.run('controlled-stall-task', 'operation_stalled', '受控停滞验收:BOM 检查轮询连续未产生新进度。当前只有缓存事件,' '活动操作可能持有服务锁,执行结果尚不确定。应诊断并保留证据供人工核对。', run_id='controlled-stall-run', execution_enabled=permission, snapshot_override={'task_id': 'controlled-stall-task', 'task_name': '受控 BOM 轮询停滞', 'status': 'running', 'progress': {'completed': 0, 'total': 1}}, trigger={'operation': 'inspect_bom_batch', 'source': 'controlled-stall-event', 'outcome': 'stalled', 'last_progress_age_seconds': 180, 'result_unverified': True, 'worker_active': True}) report['stallIncident'] = stall assert stall['status'] == 'pending_issue', 'stall_did_not_remain_in_local_outbox' assert stall['attempts'] == 0, 'stall_retried_engineering' assert service.calls == ['cleanup'], 'stall_mutated_resources_or_engineering' assert service.context_calls == 0, 'stall_read_live_task_context' assert publication_attempts == [stall['incident_id']], 'unexpected_publication_attempts' assert [row['phase'] for row in stall['analyses']] == ['diagnose', 'reflect'], 'missing_real_stall_diagnosis_or_reflection' sessions = [row.get('session_id') for row in stall['analyses']] assert sessions[0] and sessions[0] == sessions[1], 'reflection_did_not_reuse_native_session' directory = Path(stall['evidence_dir']) assert all((directory / name).is_file() for name in ('trigger.json', 'issue.md', 'evidence.zip', 'ticket.json')), 'missing_local_stall_evidence' report.update(status='passed', actualCalls=service.calls, contextCalls=service.context_calls, resourceReads=service.pending_reads, modelCalls=native.calls, resources_released=True, localOutboxCount=len(publication_attempts)) except BaseException as error: report.update(status='failed', errorType=type(error).__name__, actualCalls=service.calls, contextCalls=service.context_calls, localOutboxCount=len(publication_attempts)) raise finally: report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf8') print(json.dumps({'status': report['status'], 'report': str(report_path), 'actualCalls': service.calls, 'contextCalls': service.context_calls, 'modelCallCount': len(report.get('modelCalls', [])), 'localOutboxCount': len(publication_attempts)}, ensure_ascii=False)) if __name__ == '__main__': main()