feat(dsh): add CAD verification recovery diff and issue broker

This commit is contained in:
阿白叔 committed 2026-10-31 10:17:26 +08:00
1 parent eee4e6bde9
commit 27334fef81
23 files changed
+553 -12

No files matched your search

@@ -0,0 +1,61 @@
"""Read-only bridge to the existing native CAD identity and evidence lifecycle."""
from __future__ import annotations
from pathlib import Path
class CadVerificationAdapter:
def __init__(self, service):
self.service = service
def preflight(self, task_ids):
projects, blockers, refs = [], [], []
for task_id in task_ids:
try:
context = self.service.task_context(task_id)
project = getattr(context, 'project', None)
path = Path(getattr(project, 'path', ''))
row = {'task_id': task_id, 'path': str(path), 'project_id': getattr(project, 'project_id', ''),
'project_exists': path.is_file(), 'probe_available': False, 'component_count': None}
if not row['project_exists']:
blockers.append('project_missing')
try:
probe = Path(self.service.expected_probe_path(task_id, row['project_id']))
row['probe_path'] = str(probe)
row['probe_available'] = probe.is_file()
if row['probe_available']:
refs.append(str(probe))
else:
blockers.append('probe_baseline_missing')
except Exception:
blockers.append('probe_baseline_missing')
except Exception as error:
row = {'task_id': task_id, 'path': '', 'project_id': '', 'project_exists': False,
'probe_available': False, 'component_count': None, 'error': type(error).__name__}
blockers.append('task_unavailable')
projects.append(row)
return {'mode': 'task_center_native', 'status': 'ready' if not blockers else 'blocked',
'projects': projects, 'blockers': list(dict.fromkeys(blockers)),
'evidence_refs': refs[:20]}
def after_run(self, task_ids):
tasks, blockers = [], []
for task_id in task_ids:
try:
context = self.service.task_context(task_id)
progress = context.progress
row = {'task_id': task_id, 'saved_items': getattr(progress, 'saved_items', None),
'failed_items': getattr(progress, 'failed_items', None),
'no_match_items': getattr(progress, 'no_match_items', None),
'queue_complete': getattr(progress, 'queue_complete', None),
'interrupted': bool(getattr(context, 'interrupted', True))}
if row['interrupted']:
blockers.append('interrupted')
except Exception as error:
row = {'task_id': task_id, 'saved_items': None, 'failed_items': None,
'no_match_items': None, 'queue_complete': None, 'interrupted': True,
'error': type(error).__name__}
blockers.append('task_unavailable')
tasks.append(row)
return {'mode': 'task_center_native', 'status': 'ready' if not blockers else 'uncertain',
'tasks': tasks, 'blockers': list(dict.fromkeys(blockers))}
@@ -4,6 +4,7 @@ from __future__ import annotations
from . import task_lifecycle as tasks
from .run_journal import RunJournal
from .scheduling import ScheduleStore
from .cad_verification import CadVerificationAdapter
from ..trial_task_center.errors import TaskCenterError
from ..trial_task_center.task_queue import execute_task_queue
@@ -50,6 +51,11 @@ def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resu
'message': '请按每项实际计数判断;未命中不表示已替换保存。'}
# Persist the executor's known outcome before optional readback/enrichment.
journal.finish(run_id, receipt)
try:
receipt['cad_verification'] = CadVerificationAdapter(service).after_run(task_ids)
except Exception as error:
receipt['cad_verification'] = {'status': 'uncertain', 'mode': 'task_center_native',
'blockers': ['verification_unavailable'], 'error': type(error).__name__}
for entry in entries:
actual = {**entry, 'saved_items': None, 'failed_items': None, 'no_match_items': None,
'interrupted': None, 'queue_complete': None}
+23
View File
@@ -0,0 +1,23 @@
"""Conservative classification for automatic incident intervention."""
from __future__ import annotations
_TRANSIENT = {'worker_error', 'worker_timeout', 'timeout', 'quick_run_failed', 'execution_failed', 'native_failed'}
_DETERMINISTIC = {'target_identity', 'probe_baseline_missing', 'task_not_retryable', 'assistant_stale'}
def classify_failure(issue_code, status, *, interrupted=False, authorized=False):
code = str(issue_code or '').casefold()
state = str(status or '').casefold()
if interrupted or state in {'uncertain', 'saved_unverified'} or 'uncertain' in code or 'readback' in code:
category, reason = 'uncertain', '存在未核验或回读不确定状态'
elif state == 'paused' or code in {'paused', 'user_pause'}:
category, reason = 'paused', '任务已暂停,需要人工确认后继续'
elif code in _TRANSIENT or state in {'timeout', 'timed_out'}:
category, reason = 'transient', '可重试的临时执行错误'
elif code in _DETERMINISTIC:
category, reason = 'deterministic', '错误需要先修正任务或工程状态'
else:
category, reason = 'observe', '错误类型未进入自动处理白名单'
allowed = category == 'transient' and authorized
return {'category': category, 'retry_allowed': allowed, 'reason': reason,
'backoff_seconds': 5 if allowed else 0, 'max_attempts': 1 if allowed else 0}
+8 -1
View File
@@ -6,7 +6,7 @@ import json
from pathlib import Path
from .evidence import scrub
from .issue_credentials import load_bootstrap
from .issue_credentials import load_bootstrap, issue_target
def _now():
@@ -62,6 +62,13 @@ class HealthStore:
return {"name": "tickets", "status": "ok", "code": "cache_available", "message": f"已有 {min(count, 100)} 条工单缓存"}
def _credentials(self):
try:
config = issue_target(self.data_root / 'dsh' / 'issue-config.json')
if config.get('broker_url') and config.get('instance_id') and config.get('instance_proof') and config.get('idempotency_key'):
return {"name": "issue_credentials", "status": "ok", "code": "broker_configured",
"message": "已配置固定目标短期凭据中转"}
except (OSError, ValueError, TypeError):
pass
value = load_bootstrap()
if value:
return {"name": "issue_credentials", "status": "degraded", "code": "credential_rotation_required",
+7 -2
View File
@@ -10,6 +10,7 @@ from threading import Event, Lock
from .evidence import IncidentEvidence, scrub, write_json
from .decision_log import DecisionLog
from .failure_policy import classify_failure
from .rules import RETRYABLE_CODES
from .snapshot import TaskSnapshot
@@ -112,14 +113,18 @@ class IncidentRunner:
evidence.event('analysis_unavailable', **failure)
return None
suggestion = analyze('diagnose')
policy = classify_failure(issue_code, getattr(context.task.status, 'value', '') if context is not None else 'unknown',
interrupted=context is None or bool(getattr(context, 'interrupted', True)),
authorized=bool(execution_authorized))
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')}
'model_requested_retry': bool(suggestion and suggestion['action'] == 'retry_failed'),
'failure_policy': policy}
record['gates'] = gates
write_json(evidence.directory / 'gates.json', gates)
safe = all(gates.values())
safe = all(value is True for key, value in gates.items() if key != 'failure_policy') and policy['retry_allowed']
if safe:
# Consume before entering a service mutation. A crash or changed error
# code must never buy another replay of the same authorized run.
+54
View File
@@ -0,0 +1,54 @@
"""Fixed-target issue-token broker core used by the reference HTTP service."""
from __future__ import annotations
from dataclasses import dataclass
from hashlib import sha256
import hmac
import os
import time
@dataclass(frozen=True)
class IssueBrokerConfig:
server: str
repository: str
token: str
secret: str
expires_in: int = 300
@classmethod
def from_environment(cls, values=None):
values = os.environ if values is None else values
server, repository = str(values.get('server') or values.get('DSH_ISSUE_SERVER') or ''), str(values.get('repository') or values.get('DSH_ISSUE_REPOSITORY') or '')
token, secret = str(values.get('token') or values.get('DSH_ISSUE_TOKEN') or ''), str(values.get('secret') or values.get('DSH_BROKER_SECRET') or '')
if not server.startswith('https://') or repository.count('/') != 1 or not token or not secret:
raise ValueError('invalid_broker_config')
return cls(server.rstrip('/'), repository, token, secret, max(30, min(int(values.get('expires_in', 300)), 3600)))
class IssueBroker:
def __init__(self, config):
self.config = config
self._issued = {}
def proof(self, instance_id):
return hmac.new(self.config.secret.encode(), str(instance_id).encode(), 'sha256').hexdigest()
def exchange(self, payload):
if (payload.get('server', '').rstrip('/') != self.config.server
or payload.get('repository') != self.config.repository):
raise ValueError('invalid_target')
instance = str(payload.get('instance_id', ''))[:128]
if not instance or not hmac.compare_digest(str(payload.get('instance_proof', '')), self.proof(instance)):
raise ValueError('invalid_instance_proof')
key = str(payload.get('idempotency_key', ''))[:160]
if not key:
raise ValueError('missing_idempotency_key')
prior = self._issued.get(key)
if prior is not None:
return dict(prior)
value = {'token': self.config.token, 'expires_in': self.config.expires_in,
'server': self.config.server, 'repository': self.config.repository,
'issued_at': int(time.time())}
self._issued[key] = value
return dict(value)
+8 -2
View File
@@ -26,7 +26,7 @@ class IssueTransport:
def __init__(self, config_path):
self.config_path = Path(config_path)
def credentials(self, target, *, now=None):
def credentials(self, target, *, now=None, instance_proof=None, idempotency_key=None):
config = issue_target(self.config_path)
if not self._same_target(config, target):
return {"source": "invalid_target", "rotation_required": False}
@@ -36,8 +36,14 @@ class IssueTransport:
parsed = urllib.parse.urlsplit(str(broker))
if parsed.scheme != "https" or not parsed.hostname:
raise ValueError("invalid_broker_url")
instance = str(config.get("instance_id", ""))[:128]
proof = instance_proof or config.get('instance_proof')
idem = idempotency_key or config.get('idempotency_key')
if not instance or not proof or not idem:
return {"source": "broker_metadata_missing", "rotation_required": True}
response = _post_broker(broker, {"server": target["server"], "repository": target["repository"],
"instance_id": str(config.get("instance_id", ""))[:128]})
"instance_id": instance, "instance_proof": str(proof)[:128],
"idempotency_key": str(idem)[:160]})
token = response.get("token")
expires = int(response.get("expires_in", 0))
if not isinstance(token, str) or not token or not 30 <= expires <= 3600:
+28
View File
@@ -0,0 +1,28 @@
"""Bounded differences used before confirming an original queue resume."""
from __future__ import annotations
def resume_diff(service, inspected_run):
ids = list(inspected_run.get('task_ids') or [])
expected = dict(inspected_run.get('plan_hashes') or {})
current = dict(getattr(service, 'current_plan_hashes', {}) or {})
changed = [task_id for task_id in ids if task_id in current and current[task_id] != expected.get(task_id)]
completed = [row['task_id'] for row in inspected_run.get('tasks', []) if row.get('status') == 'completed']
remaining = [task_id for task_id in ids if task_id not in completed]
blockers = list(inspected_run.get('blockers') or [])
if changed: blockers.append('plan_changed')
if any(row.get('interrupted') for row in inspected_run.get('tasks', [])):
blockers.append('interrupted')
for task_id in ids:
try:
if bool(getattr(service.task_context(task_id), 'interrupted', False)):
blockers.append('interrupted')
except Exception:
blockers.append('task_unavailable')
if not inspected_run.get('queue_available', False):
blockers.append('queue_missing')
blockers = list(dict.fromkeys(blockers))
return {'safe': bool(inspected_run.get('resume_ready')) and not blockers,
'changed': changed[:20], 'completed': completed[:20], 'remaining': remaining[:20],
'plan_changes': [{'task_id': task_id, 'saved': expected.get(task_id), 'current': current.get(task_id)} for task_id in changed[:20]],
'evidence_changes': [], 'blockers': blockers[:20]}
+4 -1
View File
@@ -215,7 +215,10 @@ class RunJournal:
elif service.pending_batch_resources():
blockers.append("resources_pending")
blockers = list(dict.fromkeys(blockers))
return {**row, "queue_available": queue is not None, "tasks": tasks, "counters": counters,
value = {**row, "queue_available": queue is not None, "tasks": tasks, "counters": counters,
"remaining_task_ids": remaining, "blockers": blockers, "resume_ready": not blockers,
"requires_confirmation": True,
"cad_execution_started": False, "original_scope": {"task_ids": row["task_ids"], "plan_hashes": row["plan_hashes"]}}
from .resume_diff import resume_diff
value['diff'] = resume_diff(service, value)
return value
@@ -79,10 +79,13 @@ def preflight(service, task_ids, *, allow_completed=False):
'saved_items': context.progress.saved_items, 'failed_items': context.progress.failed_items,
'no_match_items': context.progress.no_match_items})
from .impact import execution_impact
from .cad_verification import CadVerificationAdapter
impact = execution_impact(service, task_ids)
cad_verification = CadVerificationAdapter(service).preflight(task_ids)
return {'ready': all(not t['blockers'] for t in tasks), 'tasks': tasks, 'impact': impact,
'plan_hashes': hashes, 'fingerprint': fingerprint(service, task_ids),
'cad_connection_checked': False,
'cad_verification': cad_verification,
'message': '已核对保存的配置和执行证据;CAD 连接、备份与保存核验由正式执行流程完成。'}
@@ -153,7 +153,7 @@ class DshTaskLifecycleController(QObject):
self._failed(request_id, TaskCenterError('assistant_fields', '接续请求字段无效。')); return
def inspect():
record = self.window._dsh_operations.runs.inspect(self.window.service, spec['run_id'])
if not record['resume_ready'] or not record['remaining_task_ids']:
if not record['resume_ready'] or not record['remaining_task_ids'] or not record.get('diff', {}).get('safe', False):
raise TaskCenterError('run_blocked', '原执行不可直接接续:' + ', '.join(record['blockers']))
return record, api.preflight(self.window.service, record['task_ids'], allow_completed=True)
self._work(inspect, lambda pair: self._preflight_ready(request_id, capability, pair[0]['task_ids'], pair[1], resume=pair[0]))
@@ -261,6 +261,8 @@ class DshTaskLifecycleController(QObject):
text += f"\n{row.get('refdes') or '映射范围'} · {row['old_part_number']} → {row['new_part_number']} · Value {row.get('value_policy')} · Cell {row.get('target_cell') or '自动匹配'} · NC {row.get('sync_nc')}"
if resume:
text += '\n\n恢复原队列:' + resume['run_id'] + ';保留已完成项,不重复替换。'
diff = resume.get('diff', {})
text += f"\n已完成:{len(diff.get('completed', []))} 项;待执行:{len(diff.get('remaining', []))} 项;计划变化:{len(diff.get('changed', []))} 项。"
def start():
if self.request_id != request_id:
return