feat: automate DSH incident diagnosis repair evidence and Git issues
This commit is contained in:
1 parent
f437df2a83
commit
6c708224d2
21 files changed
+1232
-24
No files matched your search
@@ -0,0 +1,94 @@
|
||||
"""Bounded, redacted incident evidence and immutable attachment manifests."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from hashlib import sha256
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import zipfile
|
||||
|
||||
from ..trial_task_center.diagnostics_bundle import _scrub_json, _scrub_text, export_diagnostic_bundle
|
||||
|
||||
|
||||
def scrub(value):
|
||||
value = _scrub_json(value)
|
||||
if isinstance(value, dict):
|
||||
return {key: scrub(item) for key, item in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [scrub(item) for item in value]
|
||||
if isinstance(value, str):
|
||||
return re.sub(r'\bsk-[A-Za-z0-9_-]{10,}', '<REDACTED>', _scrub_text(value))
|
||||
return value
|
||||
|
||||
|
||||
def write_json(path: Path, value):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(path.suffix + '.tmp')
|
||||
with temporary.open('w', encoding='utf8') as stream:
|
||||
json.dump(scrub(value), stream, ensure_ascii=False, indent=2)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
class IncidentEvidence:
|
||||
def __init__(self, data_root: Path, incident_id: str):
|
||||
self.data_root = Path(data_root)
|
||||
self.directory = self.data_root / 'dsh' / 'incidents' / incident_id
|
||||
self.directory.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def event(self, stage, **details):
|
||||
row = scrub({'at': datetime.now(timezone.utc).isoformat(), 'stage': stage, **details})
|
||||
with (self.directory / 'timeline.jsonl').open('a', encoding='utf8') as stream:
|
||||
stream.write(json.dumps(row, ensure_ascii=False) + '\n')
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
|
||||
def capture(self, name):
|
||||
raw = self.directory / (name + '.raw.zip')
|
||||
target = self.directory / (name + '.zip')
|
||||
try:
|
||||
export_diagnostic_bundle(self.data_root, raw)
|
||||
with zipfile.ZipFile(raw) as source, zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as output:
|
||||
for member in source.namelist():
|
||||
text = source.read(member).decode('utf8')
|
||||
output.writestr(member, scrub(text))
|
||||
self.event('evidence_captured', name=target.name)
|
||||
except Exception as error:
|
||||
self.event('evidence_unavailable', name=name, error=type(error).__name__)
|
||||
finally:
|
||||
raw.unlink(missing_ok=True)
|
||||
|
||||
def excerpt(self):
|
||||
"""Only relevant bounded task events, never arbitrary engineering files."""
|
||||
snapshot = json.loads((self.directory / 'snapshot.json').read_text(encoding='utf8'))
|
||||
task_id = snapshot['task_id']
|
||||
# A task id may never become a path traversal supplied by a model.
|
||||
if not re.fullmatch(r'[\w-]{1,128}', task_id):
|
||||
return json.dumps(snapshot, ensure_ascii=False)
|
||||
path = self.data_root / 'tasks' / task_id / 'events.jsonl'
|
||||
events = ''
|
||||
if path.is_file() and not path.is_symlink():
|
||||
with path.open('rb') as stream:
|
||||
stream.seek(max(0, path.stat().st_size - 16000))
|
||||
events = stream.read(16000).decode('utf8', 'replace')
|
||||
return scrub(json.dumps(snapshot, ensure_ascii=False) + '\nTASK EVENTS:\n' + events)
|
||||
|
||||
def pack(self, record):
|
||||
write_json(self.directory / 'report.json', record)
|
||||
hashes = {}
|
||||
files = []
|
||||
for path in sorted(self.directory.iterdir()):
|
||||
if path.is_file() and path.name not in {'incident.json', 'manifest.json', 'evidence.zip', 'ticket.json'} and not path.name.endswith('.tmp'):
|
||||
hashes[path.name] = sha256(path.read_bytes()).hexdigest()
|
||||
files.append(path)
|
||||
write_json(self.directory / 'manifest.json', {'version': 1, 'sha256': hashes,
|
||||
'scope': 'Application diagnostic allowlist and model-visible incident records only',
|
||||
'unknowns': ['No external process/network sniffing; absent diagnostic entries do not prove resource release.']})
|
||||
target = self.directory / 'evidence.zip'
|
||||
with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as archive:
|
||||
for path in files + [self.directory / 'manifest.json']:
|
||||
archive.write(path, path.name)
|
||||
return target
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Fixed-target Gitea/Forgejo issues; credentials never enter model context."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from uuid import uuid4
|
||||
|
||||
from .evidence import scrub
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, *args, **kwargs):
|
||||
return None
|
||||
|
||||
|
||||
class GitIssuePublisher:
|
||||
def __init__(self, config_path: Path):
|
||||
self.config_path = Path(config_path)
|
||||
|
||||
def __call__(self, record, archive: Path):
|
||||
if not self.config_path.is_file():
|
||||
return {'status': 'unavailable', 'reason': 'issue_target_not_configured'}
|
||||
config = json.loads(self.config_path.read_text(encoding='utf8'))
|
||||
if not config.get('enabled'):
|
||||
return {'status': 'unavailable', 'reason': 'issue_submission_disabled'}
|
||||
parsed = urllib.parse.urlsplit(config['server'])
|
||||
if parsed.scheme != 'https' or not parsed.hostname or parsed.username or parsed.password or parsed.path not in {'', '/'}:
|
||||
raise ValueError('invalid_issue_server')
|
||||
owner, repo = config['repository'].split('/')
|
||||
if not all(value and all(c.isalnum() or c in '-_.' for c in value) and value not in {'.', '..'} for value in (owner, repo)):
|
||||
raise ValueError('invalid_issue_repository')
|
||||
env = os.environ | {'GIT_TERMINAL_PROMPT': '0', 'GCM_INTERACTIVE': 'never'}
|
||||
credential = subprocess.run(['git', 'credential', 'fill'], input=f'protocol=https\nhost={parsed.netloc}\n\n',
|
||||
text=True, capture_output=True, env=env, timeout=20, check=False,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
|
||||
fields = dict(line.split('=', 1) for line in credential.stdout.splitlines() if '=' in line)
|
||||
if credential.returncode or not fields.get('password'):
|
||||
return {'status': 'unavailable', 'reason': 'git_credential_unavailable'}
|
||||
authorization = 'Basic ' + base64.b64encode((fields.get('username', '') + ':' + fields['password']).encode()).decode()
|
||||
opener = urllib.request.build_opener(NoRedirect())
|
||||
api = f'{parsed.scheme}://{parsed.netloc}/api/v1/repos/{owner}/{repo}'
|
||||
def request(path, payload=None, content_type='application/json'):
|
||||
headers = {'Authorization': authorization, 'Accept': 'application/json'}
|
||||
if payload is not None:
|
||||
headers['Content-Type'] = content_type
|
||||
call = urllib.request.Request(api + path, data=payload, headers=headers)
|
||||
with opener.open(call, timeout=25) as response:
|
||||
return json.loads(response.read(2 * 1024 * 1024))
|
||||
marker = '[DSH:' + record['incident_id'] + ']'
|
||||
matches = request('/issues?' + urllib.parse.urlencode({'state': 'all', 'q': marker, 'limit': 50}))
|
||||
issue = next((row for row in matches if marker in row.get('title', '') and not row.get('pull_request')), None)
|
||||
if issue is None:
|
||||
title = ('[DSH验收] ' if config.get('acceptance') else '') + marker + ' ' + record['issue_code']
|
||||
body = (Path(record['evidence_dir']) / 'issue.md').read_text(encoding='utf8')
|
||||
issue = request('/issues', json.dumps({'title': scrub(title), 'body': scrub(body)}, ensure_ascii=False).encode())
|
||||
result = {'status': 'submitted', 'url': issue['html_url'], 'number': issue['number'],
|
||||
'attachment_status': 'pending'}
|
||||
# Existing issue and attachment are reused when an interrupted upload is retried.
|
||||
try:
|
||||
attachments = request(f"/issues/{issue['number']}/assets")
|
||||
filename = record['incident_id'] + '-evidence.zip'
|
||||
asset = next((row for row in attachments if row.get('name') == filename), None)
|
||||
if asset is None:
|
||||
if archive.stat().st_size > 70 * 1024 * 1024:
|
||||
raise ValueError('evidence_attachment_too_large')
|
||||
boundary = 'dsh-' + uuid4().hex
|
||||
payload = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{filename}"\r\n'
|
||||
'Content-Type: application/zip\r\n\r\n').encode() + archive.read_bytes() + f'\r\n--{boundary}--\r\n'.encode()
|
||||
asset = request(f"/issues/{issue['number']}/assets", payload, 'multipart/form-data; boundary=' + boundary)
|
||||
result.update(attachment_status='uploaded', attachment_url=asset.get('browser_download_url', ''))
|
||||
except Exception as error:
|
||||
result.update(attachment_status='failed', attachment_error=type(error).__name__)
|
||||
return result
|
||||
@@ -0,0 +1,214 @@
|
||||
"""Durable automatic diagnosis, bounded repair, verification and escalation."""
|
||||
from __future__ import annotations
|
||||
|
||||
from hashlib import sha256
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
from threading import Event, Lock
|
||||
|
||||
from .evidence import IncidentEvidence, scrub, write_json
|
||||
from .rules import RETRYABLE_CODES
|
||||
from .snapshot import TaskSnapshot
|
||||
|
||||
_RUN_LOCK = Lock()
|
||||
|
||||
|
||||
def decision(reply):
|
||||
text = str(reply).strip()
|
||||
blocks = list(re.finditer(r'```(?:json)?\s*\n(.*?)```', text, re.S))
|
||||
narrative = ''
|
||||
if blocks:
|
||||
narrative = text[:blocks[-1].start()].strip()
|
||||
value = json.loads(blocks[-1].group(1))
|
||||
if narrative and isinstance(value, dict):
|
||||
value.setdefault('summary', narrative[:1800])
|
||||
else:
|
||||
value = json.loads(text)
|
||||
if not isinstance(value, dict) or not isinstance(value.get('summary'), str) or value.get('action') not in {'retry_failed', 'none'}:
|
||||
raise ValueError('invalid_diagnostic_decision')
|
||||
return value
|
||||
|
||||
|
||||
class IncidentRunner:
|
||||
def __init__(self, data_root, service, analyze, publish, notify=lambda row: None):
|
||||
self.data_root, self.service = Path(data_root), service
|
||||
self.analyze, self.publish, self.notify = analyze, publish, notify
|
||||
|
||||
def run(self, task_id, issue_code, message, *, run_id='observation', execution_authorized=False, stop_event=None):
|
||||
with _RUN_LOCK:
|
||||
return self._run(task_id, issue_code, message, run_id=run_id,
|
||||
execution_authorized=execution_authorized, stop_event=stop_event or Event())
|
||||
|
||||
def _run(self, task_id, issue_code, message, *, run_id, execution_authorized, stop_event):
|
||||
incident_id = sha256(f'{task_id}:{run_id}:{issue_code}'.encode()).hexdigest()[:24]
|
||||
evidence = IncidentEvidence(self.data_root, incident_id)
|
||||
state_path = evidence.directory / 'incident.json'
|
||||
if state_path.is_file():
|
||||
previous = json.loads(state_path.read_text(encoding='utf8'))
|
||||
previous['evidence_dir'] = str(evidence.directory)
|
||||
if previous['status'] not in {'resolved', 'escalated', 'pending_issue'}:
|
||||
previous.update(status='pending_issue', recovery='Interrupted incident retained; automatic execution was not replayed.')
|
||||
write_json(state_path, previous)
|
||||
return previous
|
||||
record = scrub({'incident_id': incident_id, 'task_id': task_id, 'issue_code': issue_code,
|
||||
'message': str(message)[:2000], 'run_id': str(run_id), 'status': 'collecting',
|
||||
'evidence_dir': str(evidence.directory), 'attempts': 0, 'analyses': [], 'ticket': {}})
|
||||
# This local address is never sent as model input or issue body.
|
||||
record['evidence_dir'] = str(evidence.directory)
|
||||
def update(status, **values):
|
||||
record.update(status=status, **scrub(values))
|
||||
write_json(state_path, record)
|
||||
evidence.event(status, **values)
|
||||
self.notify(dict(record))
|
||||
update('collecting')
|
||||
snapshot, context = self._snapshot(task_id, issue_code, message)
|
||||
record['task_name'] = snapshot.get('task_name', task_id)
|
||||
budget_id = sha256(f'{task_id}:{run_id}'.encode()).hexdigest()[:24]
|
||||
budget_path = self.data_root / 'dsh' / 'retry-budget' / (budget_id + '.json')
|
||||
budget_available = not budget_path.exists()
|
||||
snapshot['intervention'] = {'original_execution_authorized': bool(execution_authorized), 'retry_attempts': 0 if budget_available else 1,
|
||||
'phase': getattr(context, 'phase', 'unknown'), 'interrupted': getattr(context, 'interrupted', True),
|
||||
'known_retryable_error': issue_code in RETRYABLE_CODES,
|
||||
'business_status_is_not_worker_liveness': True,
|
||||
'mutation_admission': 'Coordinator serializes execution; service independently checks leases and uncertainty before each action.'}
|
||||
write_json(evidence.directory / 'snapshot.json', snapshot)
|
||||
evidence.capture('diagnostics-before')
|
||||
def analyze(phase):
|
||||
update('analyzing' if phase == 'diagnose' else 'reflecting')
|
||||
try:
|
||||
result = scrub(self.analyze(incident_id, snapshot, evidence.excerpt(), phase))
|
||||
write_json(evidence.directory / (phase + '.json'), result)
|
||||
record['analyses'].append({'phase': phase, 'session_id': result.get('session_id', ''), 'reply': result['reply']})
|
||||
return decision(result['reply'])
|
||||
except Exception as error:
|
||||
failure = scrub({'phase': phase, 'error': type(error).__name__, 'detail': str(error)[:1000]})
|
||||
record['analyses'].append(failure)
|
||||
write_json(evidence.directory / (phase + '.json'), failure)
|
||||
evidence.event('analysis_unavailable', **failure)
|
||||
return None
|
||||
suggestion = analyze('diagnose')
|
||||
gates = {'context_available': context is not None, 'no_unverified_result': context is not None and not context.interrupted,
|
||||
'retry_phase': context is not None and context.phase == 'retry', 'known_retryable_error': issue_code in RETRYABLE_CODES,
|
||||
'execution_authorized': bool(execution_authorized), 'not_stopped': not stop_event.is_set(),
|
||||
'retry_budget_available': budget_available,
|
||||
'model_requested_retry': bool(suggestion and suggestion['action'] == 'retry_failed')}
|
||||
record['gates'] = gates
|
||||
write_json(evidence.directory / 'gates.json', gates)
|
||||
safe = all(gates.values())
|
||||
if safe:
|
||||
# Consume before entering a service mutation. A crash or changed error
|
||||
# code must never buy another replay of the same authorized run.
|
||||
budget_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
with budget_path.open('x', encoding='utf8') as stream:
|
||||
json.dump({'incident_id': incident_id, 'task_id': task_id, 'run_id': run_id, 'attempts': 1}, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
except FileExistsError:
|
||||
safe = False
|
||||
gates['retry_budget_available'] = False
|
||||
write_json(evidence.directory / 'gates.json', gates)
|
||||
if safe:
|
||||
update('retrying', attempts=1)
|
||||
try:
|
||||
# Re-read at the actual mutation boundary; the model never supplies parameters.
|
||||
current = self.service.task_context(task_id)
|
||||
if current.interrupted or current.phase != 'retry' or stop_event.is_set():
|
||||
raise ValueError('retry_gate_changed')
|
||||
self.service.prepare_failed_quick_run(task_id)
|
||||
prepared = self.service.task_context(task_id)
|
||||
p = prepared.progress
|
||||
expected = (str(p.next_project_path), p.next_old_part_number, p.next_new_part_number,
|
||||
'part_label' if prepared.task.copy_part_number_to_value else 'preserve')
|
||||
if prepared.interrupted or not p.next_project_path or stop_event.is_set():
|
||||
raise ValueError('retry_execution_gate_changed')
|
||||
outcome = self.service.execute_quick_run_queue(task_id, expected_item=expected, stop_event=stop_event)
|
||||
update('verifying')
|
||||
current = self.service.task_context(task_id)
|
||||
p = current.progress
|
||||
verification = {'queue_complete': p.queue_complete, 'failed_items': p.failed_items,
|
||||
'saved_items': p.saved_items, 'completed_items': p.completed_items,
|
||||
'interrupted': current.interrupted, 'paused': outcome.paused}
|
||||
write_json(evidence.directory / 'verification.json', verification)
|
||||
record['verification'] = verification
|
||||
if p.queue_complete and not p.failed_items and not current.interrupted and not outcome.paused:
|
||||
update('resolved')
|
||||
evidence.capture('diagnostics-after')
|
||||
evidence.pack(record)
|
||||
return record
|
||||
except Exception as error:
|
||||
evidence.event('retry_failed', error=type(error).__name__, code=getattr(error, 'code', ''), detail=str(error)[:1000])
|
||||
record['retry_error'] = scrub({'type': type(error).__name__, 'code': getattr(error, 'code', ''), 'detail': str(error)[:1000]})
|
||||
else:
|
||||
record['retry_skipped'] = 'Policy, execution authorization, current evidence or model recommendation did not admit replay.'
|
||||
snapshot, _ = self._snapshot(task_id, issue_code, message)
|
||||
snapshot['intervention'] = {'retry_attempts': record['attempts'], 'gates': gates,
|
||||
'verification': record.get('verification')}
|
||||
write_json(evidence.directory / 'snapshot-after.json', snapshot)
|
||||
evidence.capture('diagnostics-after')
|
||||
# Reflection gets original evidence plus the actual attempted actions and verification.
|
||||
write_json(evidence.directory / 'actions.json', {'attempts': record['attempts'],
|
||||
'verification': record.get('verification'), 'retry_error': record.get('retry_error'), 'retry_skipped': record.get('retry_skipped')})
|
||||
if suggestion is not None:
|
||||
original_excerpt = evidence.excerpt
|
||||
evidence.excerpt = lambda: original_excerpt() + '\nGATES:\n' + json.dumps(gates) + '\nACTIONS:\n' + (evidence.directory / 'actions.json').read_text(encoding='utf8')
|
||||
analyze('reflect')
|
||||
update('pending_issue')
|
||||
self._draft(record, evidence)
|
||||
archive = evidence.pack(record)
|
||||
return self._publish(record, evidence, archive)
|
||||
|
||||
def _snapshot(self, task_id, issue_code, message):
|
||||
try:
|
||||
context = self.service.task_context(task_id)
|
||||
p = context.progress
|
||||
status = 'uncertain' if context.interrupted else context.task.status.value
|
||||
progress = {key: getattr(p, source, 0) for key, source in [('completed', 'completed_items'),
|
||||
('total', 'total_items'), ('saved_items', 'saved_items'), ('failed_items', 'failed_items')]}
|
||||
return scrub(TaskSnapshot(task_id, status, progress, message, issue_code, len(context.rules)).safe_dict()
|
||||
| {'task_name': str(getattr(context.task, 'name', task_id))[:128]}), context
|
||||
except Exception as error:
|
||||
return scrub(TaskSnapshot(task_id, 'unknown', issue=message, issue_code=issue_code).safe_dict()
|
||||
| {'context_error': type(error).__name__}), None
|
||||
|
||||
def _draft(self, record, evidence):
|
||||
analyses = '\n\n'.join(row.get('reply', row.get('error', '')) for row in record['analyses'])
|
||||
text = (f"# DSH 自动异常报告\n\n事件:`{record['incident_id']}`\n任务:`{record['task_id']}`\n错误码:`{record['issue_code']}`\n\n"
|
||||
f"## 现象\n\n{record['message']}\n\n## AI 诊断与复盘\n\n{analyses}\n\n"
|
||||
f"## 实际处理与核验\n\n自动重试次数:{record['attempts']}\n\n"
|
||||
f"```json\n{json.dumps(record.get('verification', record.get('retry_error', record.get('retry_skipped', '未执行重试'))), ensure_ascii=False)}\n```\n\n"
|
||||
"## 证据\n\n附件 evidence.zip 包含前后诊断、任务快照、事件时间线、模型可见会话及 SHA256 清单。"
|
||||
"缺失或无法读取的证据记录在时间线和诊断包 manifest 中。未采集工程源文件、凭据或无关网络流量。\n\n"
|
||||
"本报告不宣称 AI 建议已经执行成功;请以实际核验字段和保留证据为准。\n")
|
||||
(evidence.directory / 'issue.md').write_text(scrub(text), encoding='utf8')
|
||||
|
||||
def _publish(self, record, evidence, archive):
|
||||
try:
|
||||
ticket = scrub(self.publish(record, archive))
|
||||
except Exception as error:
|
||||
ticket = {'status': 'failed', 'error': type(error).__name__}
|
||||
record['ticket'] = ticket
|
||||
record['status'] = 'escalated' if ticket.get('status') == 'submitted' and ticket.get('attachment_status') == 'uploaded' else 'pending_issue'
|
||||
evidence.event('issue_submission', **ticket)
|
||||
write_json(evidence.directory / 'ticket.json', ticket)
|
||||
write_json(evidence.directory / 'incident.json', record)
|
||||
self.notify(dict(record))
|
||||
return record
|
||||
|
||||
def publish_pending(self, incident_id):
|
||||
if not incident_id.isalnum() or len(incident_id) != 24:
|
||||
raise ValueError('invalid_incident_id')
|
||||
with _RUN_LOCK:
|
||||
evidence = IncidentEvidence(self.data_root, incident_id)
|
||||
record = json.loads((evidence.directory / 'incident.json').read_text(encoding='utf8'))
|
||||
record['evidence_dir'] = str(evidence.directory)
|
||||
if record['status'] != 'pending_issue':
|
||||
return record
|
||||
if not (evidence.directory / 'issue.md').is_file():
|
||||
self._draft(record, evidence)
|
||||
archive = evidence.directory / 'evidence.zip'
|
||||
if not archive.is_file():
|
||||
archive = evidence.pack(record)
|
||||
return self._publish(record, evidence, archive)
|
||||
@@ -41,11 +41,11 @@ def launch_environment(data_root: Path) -> dict[str, str]:
|
||||
return env
|
||||
|
||||
|
||||
def write_context(data_root: Path, snapshot: TaskSnapshot, *, events=(), action_result='', task_name='') -> dict:
|
||||
def write_context(data_root: Path, snapshot: TaskSnapshot, *, events=(), action_result='', task_name='', automation=None) -> dict:
|
||||
data_root.mkdir(parents=True, exist_ok=True)
|
||||
value = snapshot.safe_dict() | {'revision': uuid4().hex,
|
||||
'events': [str(e)[:300] for e in events][-20:], 'action_result': str(action_result)[:300],
|
||||
'task_name': str(task_name)[:128]}
|
||||
'task_name': str(task_name)[:128], 'automation': automation or {}}
|
||||
temporary = data_root / ('context-' + uuid4().hex + '.tmp')
|
||||
temporary.write_text(json.dumps(value, ensure_ascii=False), encoding='utf8')
|
||||
os.replace(temporary, data_root / 'task-context.json')
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
"""Qt lifecycle owner for automatic incident work and native model replies."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from threading import Event
|
||||
from uuid import uuid4
|
||||
|
||||
from PySide6.QtCore import QObject, QThreadPool, QTimer, Signal
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from ...dsh.git_issues import GitIssuePublisher
|
||||
from ...dsh.incidents import IncidentRunner, decision
|
||||
from ..stop_control import StopControl
|
||||
from .workers import ServiceWorker
|
||||
|
||||
|
||||
class DshAutomation(QObject):
|
||||
model_requested = Signal(object)
|
||||
state_changed = Signal(object)
|
||||
|
||||
def __init__(self, window):
|
||||
super().__init__(window)
|
||||
self.window = window
|
||||
self.root = window.service.layout_settings_path.parent
|
||||
self.pending = []
|
||||
self.seen = set()
|
||||
self.latest = {}
|
||||
self.waiters = {}
|
||||
self.worker = None
|
||||
self._connected_view = None
|
||||
self._native_unavailable = False
|
||||
self.model_requested.connect(self._request_model)
|
||||
self.state_changed.connect(self._state_changed)
|
||||
self._restore_pending()
|
||||
|
||||
def _restore_pending(self):
|
||||
from ...dsh.evidence import write_json
|
||||
paths = sorted((self.root / 'dsh' / 'incidents').glob('*/incident.json'), key=lambda path: path.stat().st_mtime)
|
||||
for path in paths:
|
||||
try:
|
||||
row = json.loads(path.read_text(encoding='utf8'))
|
||||
if row['status'] in {'resolved', 'escalated'}:
|
||||
continue
|
||||
row.update(status='pending_issue', evidence_dir=str(path.parent))
|
||||
write_json(path, row)
|
||||
self.latest = row
|
||||
except (OSError, ValueError, KeyError):
|
||||
continue
|
||||
|
||||
def enqueue(self, task_id, issue_code, message, *, execution_authorized=False, run_id='observation'):
|
||||
# Offscreen UI unit tests have no Chromium surface or local provider.
|
||||
if QApplication.platformName().casefold() == 'offscreen':
|
||||
return False
|
||||
if issue_code == 'operation_cancelled' or not task_id:
|
||||
return False
|
||||
item = (task_id, issue_code, message, execution_authorized, run_id)
|
||||
identity = (task_id, issue_code, run_id)
|
||||
if identity in self.seen:
|
||||
return True
|
||||
self.seen.add(identity)
|
||||
self.pending.append(item)
|
||||
QTimer.singleShot(0, self._drain)
|
||||
return True
|
||||
|
||||
def _drain(self):
|
||||
w = self.window
|
||||
if w._closed or self.worker is not None or not self.pending:
|
||||
return
|
||||
if w._workers or w._loading:
|
||||
QTimer.singleShot(200, self._drain)
|
||||
return
|
||||
task_id, code, message, authorized, run_id = self.pending.pop(0)
|
||||
self.latest = {}
|
||||
self._native_unavailable = False
|
||||
try:
|
||||
w._open_dsh()
|
||||
except Exception as error:
|
||||
self._native_unavailable = True
|
||||
w.service.report_ui_error(error)
|
||||
view = w._dsh_view
|
||||
if view is not None and view is not self._connected_view:
|
||||
view.diagnosis_event.connect(self._diagnosis_event)
|
||||
view.stopped.connect(self._runtime_stopped)
|
||||
self._connected_view = view
|
||||
stop = StopControl()
|
||||
# The same worker gate reserves the mutation lane throughout diagnosis.
|
||||
w._batch_stop = stop
|
||||
w._active_quick_run_task_id = task_id
|
||||
runner = IncidentRunner(self.root, w.service, self._analyze,
|
||||
GitIssuePublisher(self.root / 'dsh' / 'issue-config.json'), self.state_changed.emit)
|
||||
allow_execution = authorized and not w.plan_panel.has_unsaved_plans()
|
||||
worker = ServiceWorker(lambda: runner.run(task_id, code, message, run_id=run_id,
|
||||
execution_authorized=allow_execution, stop_event=stop))
|
||||
self._start_worker(worker)
|
||||
|
||||
def _start_worker(self, worker):
|
||||
w = self.window
|
||||
self.worker = worker
|
||||
w._workers.add(worker)
|
||||
worker.signals.succeeded.connect(self._completed)
|
||||
worker.signals.failed.connect(self._failed)
|
||||
worker.signals.finished.connect(self._finished)
|
||||
w._update_gates()
|
||||
QThreadPool.globalInstance().start(worker)
|
||||
|
||||
def _analyze(self, incident_id, snapshot, evidence, phase):
|
||||
if self._native_unavailable:
|
||||
raise RuntimeError('native_harness_unavailable')
|
||||
request_id = uuid4().hex
|
||||
complete, holder = Event(), {}
|
||||
self.waiters[request_id] = (complete, holder)
|
||||
try:
|
||||
self.model_requested.emit({'request_id': request_id, 'incident_id': incident_id,
|
||||
'snapshot': snapshot, 'evidence': evidence[:38000], 'phase': phase})
|
||||
if not complete.wait(190):
|
||||
raise TimeoutError('native_diagnosis_timeout')
|
||||
if holder.get('status') != 'completed':
|
||||
raise RuntimeError(holder.get('error', 'native_diagnosis_failed'))
|
||||
return holder
|
||||
finally:
|
||||
self.waiters.pop(request_id, None)
|
||||
|
||||
def _request_model(self, request):
|
||||
if self.window._closed:
|
||||
return
|
||||
view = self.window._dsh_view
|
||||
if view is None or not view.is_running:
|
||||
self._diagnosis_event({'request_id': request['request_id'], 'status': 'failed', 'error': 'native_harness_unavailable'})
|
||||
else:
|
||||
view.request_diagnosis(request)
|
||||
|
||||
def _runtime_stopped(self):
|
||||
for complete, holder in list(self.waiters.values()):
|
||||
holder.update(status='failed', error='native_harness_stopped')
|
||||
complete.set()
|
||||
|
||||
def _diagnosis_event(self, value):
|
||||
if value.get('status') == 'started':
|
||||
self.latest['session_id'] = value['session_id']
|
||||
self._publish_context()
|
||||
else:
|
||||
waiter = self.waiters.get(value.get('request_id'))
|
||||
if waiter:
|
||||
complete, holder = waiter
|
||||
holder.update(value)
|
||||
complete.set()
|
||||
|
||||
def _state_changed(self, row):
|
||||
self.latest.update(row)
|
||||
self._publish_context()
|
||||
|
||||
def _publish_context(self):
|
||||
w = self.window
|
||||
if not w._dsh_view or w._closed:
|
||||
return
|
||||
row = self.latest
|
||||
summary = ''
|
||||
for analysis in reversed(row.get('analyses', [])):
|
||||
try:
|
||||
summary = decision(analysis.get('reply', '{}'))['summary']
|
||||
break
|
||||
except (ValueError, KeyError, TypeError):
|
||||
continue
|
||||
w._dsh_view.automation = {key: row.get(key, '') for key in
|
||||
('incident_id', 'task_id', 'task_name', 'issue_code', 'status', 'session_id', 'evidence_dir', 'attempts')}
|
||||
w._dsh_view.automation.update(summary=summary, ticket=row.get('ticket', {}))
|
||||
w._bind_dsh_context()
|
||||
|
||||
def _completed(self, row):
|
||||
self._state_changed(row)
|
||||
labels = {'resolved': 'AI 自动处理已通过实际核验。', 'escalated': 'AI 未能解决,证据已保存并提交 Git 工单。',
|
||||
'pending_issue': 'AI 诊断与证据已保存,工单暂未完整提交,可在任务监管中重试。'}
|
||||
self.window._set_operator_message(labels.get(row.get('status'), 'AI 介入记录已保存。'),
|
||||
'success' if row.get('status') == 'resolved' else 'warning')
|
||||
|
||||
def _failed(self, error):
|
||||
# Never recursively diagnose an incident subsystem failure.
|
||||
self.window.service.report_ui_error(error)
|
||||
self.window._set_operator_message('AI 介入未完成,已保留应用日志和现有现场。', 'warning')
|
||||
|
||||
def _finished(self):
|
||||
w = self.window
|
||||
w._workers.discard(self.worker)
|
||||
self.worker = None
|
||||
w._finish_run()
|
||||
w._load_task_data()
|
||||
w._update_gates()
|
||||
if w._close_pending:
|
||||
QTimer.singleShot(0, w.close)
|
||||
else:
|
||||
QTimer.singleShot(0, self._drain)
|
||||
|
||||
def resubmit(self, incident_id):
|
||||
if self.worker is not None or self.window._workers:
|
||||
return
|
||||
runner = IncidentRunner(self.root, self.window.service, self._analyze,
|
||||
GitIssuePublisher(self.root / 'dsh' / 'issue-config.json'), self.state_changed.emit)
|
||||
self._start_worker(ServiceWorker(lambda: runner.publish_pending(incident_id)))
|
||||
@@ -28,6 +28,7 @@ class NativeHarnessView(QWidget):
|
||||
action_requested = Signal(object)
|
||||
ready = Signal()
|
||||
stopped = Signal()
|
||||
diagnosis_event = Signal(object)
|
||||
|
||||
def __init__(self, data_root: Path, parent=None):
|
||||
super().__init__(parent)
|
||||
@@ -35,6 +36,8 @@ class NativeHarnessView(QWidget):
|
||||
self.setStyleSheet('QWidget#dshNativeWorkspace {background:white;}')
|
||||
self.data_root = Path(data_root)
|
||||
self.context = None
|
||||
self.automation = {}
|
||||
self._diagnosis_queue = []
|
||||
self._buffer = ''
|
||||
self._started = False
|
||||
self._stopping = False
|
||||
@@ -69,7 +72,14 @@ class NativeHarnessView(QWidget):
|
||||
self.timeout.timeout.connect(self._startup_timeout)
|
||||
|
||||
def bind(self, snapshot: TaskSnapshot, *, events=(), action_result='', task_name=''):
|
||||
self.context = write_context(self.data_root, snapshot, events=events, action_result=action_result, task_name=task_name)
|
||||
self.context = write_context(self.data_root, snapshot, events=events, action_result=action_result, task_name=task_name,
|
||||
automation=self.automation)
|
||||
|
||||
def request_diagnosis(self, request):
|
||||
if self._started:
|
||||
self.process.write((json.dumps({'type': 'diagnose', **request}, ensure_ascii=False) + '\n').encode('utf8'))
|
||||
else:
|
||||
self._diagnosis_queue.append(request)
|
||||
|
||||
def start(self):
|
||||
if self.is_running:
|
||||
@@ -118,6 +128,11 @@ class NativeHarnessView(QWidget):
|
||||
self.status.hide()
|
||||
self.web.load(url)
|
||||
self.ready.emit()
|
||||
queued, self._diagnosis_queue = self._diagnosis_queue, []
|
||||
for request in queued:
|
||||
self.request_diagnosis(request)
|
||||
elif line.startswith('DX_DSH_DIAGNOSIS '):
|
||||
self.diagnosis_event.emit(json.loads(line[len('DX_DSH_DIAGNOSIS '):]))
|
||||
elif line.startswith('DX_DSH_ACTION '):
|
||||
request = json.loads(line[len('DX_DSH_ACTION '):])
|
||||
if self.context and request.get('task_id') == self.context['task_id'] and request.get('revision') == self.context['revision']:
|
||||
|
||||
@@ -36,6 +36,9 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self._dsh = DshSupervisor(DshServiceAdapter(service).execute)
|
||||
self._dsh_view = None
|
||||
self._dsh_stopping = False
|
||||
self._dsh_automation = None
|
||||
self._dsh_run_id = 'observation'
|
||||
self._dsh_authorized_tasks = set()
|
||||
self.task_center_action = QAction('任务中心', self)
|
||||
self.task_center_action.triggered.connect(lambda: self.content_stack.setCurrentIndex(0))
|
||||
self.dsh_action = QAction('DSH助手', self)
|
||||
@@ -148,6 +151,9 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
widget.restoreState(saved)
|
||||
self._refresh_task_list()
|
||||
self._update_gates()
|
||||
if (self.service.layout_settings_path.parent / 'dsh' / 'incidents').is_dir():
|
||||
from .dsh_automation import DshAutomation
|
||||
self._dsh_automation = DshAutomation(self)
|
||||
if getattr(service, '_supervised', False):
|
||||
QTimer.singleShot(0, self._startup_resource_recheck)
|
||||
|
||||
@@ -588,6 +594,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
enabled = sum(row.enabled for row in context.targets) if context.task.target_plan_mode else sum(r.enabled for r in context.rules)
|
||||
if not self._quick_run_confirmer('current', 1, enabled):
|
||||
return
|
||||
self._dsh_authorized_tasks.add(context.task.task_id)
|
||||
p = context.progress
|
||||
expected = (str(p.next_project_path), p.next_old_part_number, p.next_new_part_number,
|
||||
'part_label' if context.task.copy_part_number_to_value else 'preserve')
|
||||
@@ -611,6 +618,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
return
|
||||
if not self._quick_run_confirmer('batch', len(ids), 0):
|
||||
return
|
||||
self._dsh_authorized_tasks.update(ids)
|
||||
from ..task_queue import execute_task_queue
|
||||
self._begin_run(ids[0])
|
||||
stop = self._batch_stop
|
||||
@@ -624,6 +632,10 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
failures = sum(e.state in {'failed', 'blocked'} for e in result.entries)
|
||||
if failures:
|
||||
self._close_pending = False
|
||||
for entry in result.entries:
|
||||
if entry.state in {'failed', 'blocked'}:
|
||||
self._queue_dsh_incident(entry.task_id,
|
||||
'task_queue_blocked' if entry.state == 'blocked' else 'execution_failed', entry.message)
|
||||
self._show_task_log(force=True)
|
||||
self._set_operator_message(f'本批任务已暂停。失败/阻断 {failures} 项。' if result.paused else f'本批任务已结束。失败 {failures} 项。',
|
||||
'warning' if result.paused or failures else 'success')
|
||||
@@ -631,6 +643,8 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self.task_list.queue_button)
|
||||
|
||||
def _begin_run(self, task_id):
|
||||
from uuid import uuid4
|
||||
self._dsh_run_id = uuid4().hex
|
||||
self._batch_stop = StopControl()
|
||||
self._active_quick_run_task_id = task_id
|
||||
self._run_started_at = time.time()
|
||||
@@ -682,6 +696,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
p = result.progress
|
||||
if p.failed_items:
|
||||
self._close_pending = False
|
||||
self._queue_dsh_incident(owner, 'execution_failed', f'执行结束仍有失败项:{p.failed_items},已保存 {p.saved_items}。')
|
||||
self._set_operator_message(f"任务「{name}」{'已暂停' if result.paused else '已结束'}:已保存 {p.saved_items},失败 {p.failed_items},未命中 {p.no_match_items}。",
|
||||
'warning' if result.paused or p.failed_items else 'success')
|
||||
|
||||
@@ -869,6 +884,8 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
else:
|
||||
self._bind_dsh_context()
|
||||
self.content_stack.setCurrentWidget(self._dsh_view)
|
||||
if self._dsh_automation is not None and self._dsh_automation.latest:
|
||||
self._dsh_automation._publish_context()
|
||||
|
||||
def _create_dsh_view(self):
|
||||
# Load Chromium only when the menu is opened; all task-center paths stay lazy.
|
||||
@@ -899,6 +916,18 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
if view is None or not view.context or request.get('task_id') != self._task_id or request.get('revision') != view.context['revision']:
|
||||
return
|
||||
action = request.get('action')
|
||||
if action in {'retry_issue', 'open_evidence'} and self._dsh_automation:
|
||||
incident = self._dsh_automation.latest
|
||||
if incident.get('task_id') != self._task_id:
|
||||
return
|
||||
if action == 'retry_issue':
|
||||
self._dsh_automation.resubmit(incident['incident_id'])
|
||||
else:
|
||||
from PySide6.QtCore import QUrl
|
||||
from PySide6.QtGui import QDesktopServices
|
||||
directory = self.service.layout_settings_path.parent / 'dsh' / 'incidents' / incident['incident_id']
|
||||
QDesktopServices.openUrl(QUrl.fromLocalFile(str(directory)))
|
||||
return
|
||||
if action == 'refresh_snapshot':
|
||||
self._bind_dsh_context('任务上下文已刷新')
|
||||
return
|
||||
@@ -1007,13 +1036,23 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
if task_id and not (isinstance(error, TaskCenterError) and error.code == 'operation_cancelled'):
|
||||
issue_code = getattr(error, 'code', error.__class__.__name__).lower()
|
||||
try:
|
||||
self._dsh.observe(TaskSnapshot(task_id, 'failed', issue_code=issue_code, issue=message))
|
||||
self._dsh.observe(TaskSnapshot(task_id, 'failed', issue_code=issue_code, issue=message), auto=False)
|
||||
except Exception:
|
||||
# DSH must never hide or replace the original operation error.
|
||||
pass
|
||||
self._bind_dsh_context()
|
||||
managed = self._queue_dsh_incident(task_id, issue_code, message)
|
||||
else:
|
||||
managed = False
|
||||
if owner_task_id is None or owner_task_id == self._task_id:
|
||||
self._append_log(message)
|
||||
self._update_gates()
|
||||
if self.isVisible() and QApplication.platformName().casefold() != 'offscreen':
|
||||
if not managed and self.isVisible() and QApplication.platformName().casefold() != 'offscreen':
|
||||
QMessageBox.warning(self, '操作未完成', message)
|
||||
|
||||
def _queue_dsh_incident(self, task_id, issue_code, message):
|
||||
if self._dsh_automation is None:
|
||||
from .dsh_automation import DshAutomation
|
||||
self._dsh_automation = DshAutomation(self)
|
||||
return self._dsh_automation.enqueue(task_id, issue_code, message,
|
||||
execution_authorized=task_id in self._dsh_authorized_tasks, run_id=self._dsh_run_id)
|
||||
Reference in new issue
Block a user