fix(dsh): align recovery, scheduling audit and credential guarantees

This commit is contained in:
阿白叔 committed 2026-10-31 14:16:27 +08:00
1 parent e565f67b46
commit 9552f1eb95
32 files changed
+514 -135

No files matched your search

+10 -4
View File
@@ -9,7 +9,7 @@ from ..trial_task_center.errors import TaskCenterError
from ..trial_task_center.task_queue import execute_task_queue
def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None):
def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None, automatic=False):
if tasks.fingerprint(service, task_ids) != report['fingerprint']:
raise TaskCenterError('assistant_stale', '任务状态已变化,请重新预检后确认。')
journal = RunJournal(root)
@@ -21,7 +21,7 @@ def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resu
current = next((r for r in schedules.evaluate(service) if r['schedule_id'] == schedule['schedule_id']), None)
if not current or not current['ready'] or current['plan_hashes'] != report['plan_hashes']:
raise TaskCenterError('schedule_blocked', '排期计划、依赖或执行条件已变化,未启动。')
schedules.claim(schedule['schedule_id']); claimed = True
schedules.claim(schedule['schedule_id'], run_id=run_id, automatic=automatic); claimed = True
if resume:
inspected = journal.inspect(service, resume['run_id'])
if not inspected['resume_ready'] or inspected['plan_hashes'] != report['plan_hashes']:
@@ -66,12 +66,18 @@ def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resu
except Exception as error:
receipt['reporting_errors'].append({'task_id': entry['task_id'], 'code': getattr(error, 'code', 'context_unavailable')})
receipt['tasks'].append(actual)
journal.finish(run_id, receipt)
try:
journal.finish(run_id, receipt)
except Exception as error:
receipt['reporting_errors'].append({'code': 'receipt_enrichment_unavailable', 'error': type(error).__name__})
if claimed:
try:
schedules.finish(schedule['schedule_id'], 'interrupted' if status in {'paused', 'blocked'} else status,
run_id=run_id, receipt=receipt)
except Exception as error:
receipt['reporting_errors'].append({'code': getattr(error, 'code', 'schedule_receipt_unavailable')})
journal.finish(run_id, receipt)
try:
journal.finish(run_id, receipt)
except Exception:
receipt['reporting_errors'].append({'code': 'receipt_enrichment_unavailable'})
return receipt
+21 -6
View File
@@ -59,11 +59,27 @@ class ExperienceStore:
self.data_root = Path(data_root)
self.root = self.data_root / "dsh" / "incidents"
self._rows: list[dict] = []
self._source_stamp = None
def refresh(self) -> list[dict]:
directories = sorted((p for p in self.root.iterdir()
if _IDENTIFIER.fullmatch(p.name) and p.is_dir() and not p.is_symlink()),
key=lambda p: p.name) if self.root.is_dir() else []
stamp = []
for directory in directories:
for name in dict.fromkeys(('incident.json', *_KNOWN_EVIDENCE)):
try:
stat = (directory / name).lstat()
stamp.append((directory.name, name, stat.st_mtime_ns, stat.st_ctime_ns,
stat.st_size, stat.st_ino, stat.st_mode))
except FileNotFoundError:
stamp.append((directory.name, name, None))
index = self.data_root / 'dsh' / 'experience' / 'index.json'
if stamp == self._source_stamp and index.is_file():
return [dict(row) for row in self._rows]
rows = []
if self.root.is_dir():
for directory in sorted(self.root.iterdir(), key=lambda p: p.name):
if directories:
for directory in directories:
path = directory / "incident.json"
if not directory.is_dir() or directory.is_symlink() or not path.is_file() or path.is_symlink():
continue
@@ -75,6 +91,7 @@ class ExperienceStore:
rows.append(row)
self._rows = rows
write_json(self.data_root / "dsh" / "experience" / "index.json", {"version": 1, "entries": rows})
self._source_stamp = stamp
return [dict(row) for row in rows]
def _entry(self, directory: Path, record: dict) -> dict | None:
@@ -152,8 +169,7 @@ class ExperienceStore:
def search(self, issue_code: str = "", *, limit: int = 5) -> list[dict]:
if not isinstance(limit, int) or limit <= 0:
return []
if not self._rows:
self.refresh()
self.refresh()
query = str(issue_code or "").strip().casefold()
matches = []
for row in self._rows:
@@ -170,8 +186,7 @@ class ExperienceStore:
return matches[:min(limit, 50)]
def summary(self) -> dict:
if not self._rows:
self.refresh()
self.refresh()
counts = {}
for row in self._rows:
code = row.get("issue_code", "") or "unknown"
+14 -11
View File
@@ -13,13 +13,22 @@ def _now():
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def execution_check(state=None):
values = {'running': ('execution_running', '任务中心正在执行工程操作'),
'busy': ('worker_active', '任务中心有后台操作'),
'confirmation': ('awaiting_confirmation', '等待原生确认'),
'idle': ('idle', '任务中心空闲')}
code, message = values.get(state, ('execution_not_observed', '尚未获取桌面执行状态'))
return {'name': 'execution', 'status': 'ok' if state == 'idle' else 'degraded', 'code': code, 'message': message}
class HealthStore:
def __init__(self, data_root):
self.data_root = Path(data_root)
def snapshot(self, service, *, now=None):
def snapshot(self, service, *, now=None, execution=None):
checked = now.isoformat(timespec="seconds") if now is not None else _now()
checks = [self._provider(), self._execution(service), self._stores(), self._tickets(), self._credentials()]
checks = [self._provider(), execution_check(execution), self._stores(), self._tickets(), self._credentials()]
status = "ok" if all(row["status"] == "ok" for row in checks) else (
"blocked" if any(row["status"] == "blocked" for row in checks) else "degraded")
return scrub({"status": status, "checked_utc": checked, "checks": checks})
@@ -35,12 +44,6 @@ class HealthStore:
"code": "ready" if configured else "provider_unconfigured",
"message": "模型提供方已配置" if configured else "尚未配置模型提供方"}
def _execution(self, service):
active = bool(getattr(service, "_workers", set()))
return {"name": "execution", "status": "degraded" if active else "ok",
"code": "worker_active" if active else "idle",
"message": "任务中心有后台操作" if active else "任务中心空闲"}
def _stores(self):
dsh = self.data_root / "dsh"
try:
@@ -65,13 +68,13 @@ class HealthStore:
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": "已配置固定目标短期凭据中转"}
return {"name": "issue_credentials", "status": "degraded", "code": "broker_static_credential",
"message": "已配置长期可吊销工单凭据中转,仍需服务端轮换;未验证连通性"}
except (OSError, ValueError, TypeError):
pass
value = load_bootstrap()
if value:
return {"name": "issue_credentials", "status": "degraded", "code": "credential_rotation_required",
"message": "当前使用预置工单凭据,建议切换短期中转凭据"}
"message": "当前使用预置工单凭据,需要服务端吊销和轮换管理"}
return {"name": "issue_credentials", "status": "ok", "code": "machine_credential_or_disabled",
"message": "未发现预置工单凭据"}
+40 -19
View File
@@ -1,54 +1,75 @@
"""Fixed-target issue-token broker core used by the reference HTTP service."""
from __future__ import annotations
from dataclasses import dataclass
from collections import OrderedDict
from dataclasses import dataclass, field
from hashlib import sha256
import hmac
import os
import time
from threading import Lock
from urllib.parse import urlsplit
@dataclass(frozen=True)
class IssueBrokerConfig:
server: str
repository: str
token: str
secret: str
expires_in: int = 300
token: str = field(repr=False)
secret: str = field(repr=False)
cache_seconds: int = 300
max_entries: int = 1024
@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:
parsed = urlsplit(server)
if (parsed.scheme != 'https' or not parsed.hostname or parsed.username or parsed.password
or parsed.path not in {'', '/'} or parsed.query or parsed.fragment
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)))
return cls(server.rstrip('/'), repository, token, secret,
max(1, min(int(values.get('cache_seconds', 300)), 3600)),
max(1, min(int(values.get('max_entries', 1024)), 10000)))
class IssueBroker:
def __init__(self, config):
self.config = config
self._issued = {}
self._issued = OrderedDict()
self._lock = Lock()
def proof(self, instance_id):
return hmac.new(self.config.secret.encode(), str(instance_id).encode(), 'sha256').hexdigest()
def exchange(self, payload):
if not isinstance(payload, dict):
raise ValueError('invalid_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)):
instance = str(payload.get('instance_id', ''))
if not 1 <= len(instance) <= 128 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:
key = str(payload.get('idempotency_key', ''))
if not 1 <= len(key) <= 160:
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)
with self._lock:
now = time.monotonic()
for identity in [identity for identity, (until, _) in self._issued.items() if until <= now]:
del self._issued[identity]
identity = (instance, key)
if identity in self._issued:
self._issued.move_to_end(identity)
return dict(self._issued[identity][1])
# This reference service distributes a revocable static Git token.
# Cache expiry is not token expiry; never advertise a false TTL.
value = {'token': self.config.token, 'credential_kind': 'revocable_static', 'expires_utc': None,
'server': self.config.server, 'repository': self.config.repository,
'issued_at': int(time.time())}
self._issued[identity] = (now + self.config.cache_seconds, value)
while len(self._issued) > self.config.max_entries:
self._issued.popitem(last=False)
return dict(value)
+9 -7
View File
@@ -1,7 +1,6 @@
"""Fixed-target issue credentials with optional short-lived broker exchange."""
"""Fixed-target issue credentials with explicit static broker provenance."""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
import json
from pathlib import Path
import urllib.parse
@@ -34,7 +33,8 @@ class IssueTransport:
if broker:
try:
parsed = urllib.parse.urlsplit(str(broker))
if parsed.scheme != "https" or not parsed.hostname:
if (parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password
or parsed.query or parsed.fragment):
raise ValueError("invalid_broker_url")
instance = str(config.get("instance_id", ""))[:128]
proof = instance_proof or config.get('instance_proof')
@@ -44,13 +44,15 @@ class IssueTransport:
response = _post_broker(broker, {"server": target["server"], "repository": target["repository"],
"instance_id": instance, "instance_proof": str(proof)[:128],
"idempotency_key": str(idem)[:160]})
if (not isinstance(response, dict) or not self._same_target(response, target)
or response.get('credential_kind') != 'revocable_static'
or response.get('expires_utc') is not None or 'expires_in' in response):
raise ValueError('invalid_broker_response')
token = response.get("token")
expires = int(response.get("expires_in", 0))
if not isinstance(token, str) or not token or not 30 <= expires <= 3600:
if not isinstance(token, str) or not 1 <= len(token) <= 4096 or '\n' in token or '\r' in token:
raise ValueError("invalid_broker_response")
stamp = now or datetime.now(timezone.utc)
return {"headers": {"Authorization": "token " + token}, "source": "broker",
"expires_utc": (stamp + timedelta(seconds=expires)).isoformat(), "rotation_required": False}
"credential_kind": "revocable_static", "expires_utc": None, "rotation_required": True}
except Exception as error:
return {"source": "broker_unavailable", "error": type(error).__name__, "rotation_required": True}
bootstrap = load_bootstrap()
+27 -12
View File
@@ -2,27 +2,42 @@
from __future__ import annotations
def resume_diff(service, inspected_run):
def resume_diff(service, inspected_run, *, current_plan_hashes=None):
from ..trial_task_center.task_queue import _plan_hash
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]
current = {} if current_plan_hashes is None else dict(current_plan_hashes)
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')
contexts = {}
for task_id in ids:
try:
if bool(getattr(service.task_context(task_id), 'interrupted', False)):
contexts[task_id] = service.task_context(task_id)
if current_plan_hashes is None:
current[task_id] = _plan_hash(service.for_project_task(task_id), task_id)
if contexts[task_id].interrupted:
blockers.append('interrupted')
except Exception:
blockers.append('task_unavailable')
if not inspected_run.get('queue_available', False):
blockers.append('queue_missing')
changed = [key for key in ids if not expected.get(key) or not current.get(key) or current[key] != expected[key]]
if changed:
blockers.append('plan_changed')
remaining = list(inspected_run.get('remaining_task_ids', ids))
completed = [key for key in ids if key not in remaining]
baseline = {row['task_id']: row for row in (inspected_run.get('result') or {}).get('tasks', [])}
evidence_changes = []
for task_id, context in contexts.items():
saved = baseline.get(task_id, {})
actual = {'interrupted': context.interrupted,
**{field: getattr(context.progress, field, None) for field in
('saved_items', 'failed_items', 'no_match_items', 'queue_complete')}}
for field, value in actual.items():
if saved.get(field) is not None and value != saved[field]:
evidence_changes.append({'task_id': task_id, 'field': field, 'saved': saved[field], 'current': value})
if evidence_changes:
blockers.append('evidence_changed')
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]}
'evidence_changes': evidence_changes[:100], 'evidence_baseline_available': bool(baseline),
'blockers': blockers[:20]}
+7 -2
View File
@@ -174,6 +174,7 @@ class RunJournal:
counters = {"completed": 0, "total": 0, "saved_items": 0, "failed_items": 0, "no_match_items": 0}
tasks = []
has_evidence = False
current_hashes = {}
for task_id in row["task_ids"]:
item = {"task_id": task_id, "status": "unknown", "saved_items": 0, "failed_items": 0, "no_match_items": 0}
try:
@@ -193,7 +194,8 @@ class RunJournal:
if getattr(progress, "failed_items", 0):
blockers.append("failed_items")
from ..trial_task_center.task_queue import _plan_hash
if _plan_hash(service.for_project_task(task_id), task_id) != row["plan_hashes"][task_id]:
current_hashes[task_id] = _plan_hash(service.for_project_task(task_id), task_id)
if current_hashes[task_id] != row["plan_hashes"][task_id]:
blockers.append("plan_changed")
except Exception:
blockers.append("task_unavailable")
@@ -220,5 +222,8 @@ class RunJournal:
"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)
value['diff'] = resume_diff(service, value, current_plan_hashes=current_hashes)
if not value['diff']['safe']:
value['blockers'] = value['diff']['blockers']
value['resume_ready'] = False
return value
+33 -4
View File
@@ -57,6 +57,9 @@ class ScheduleStore:
auto_start INTEGER NOT NULL, idle_only INTEGER NOT NULL, title TEXT NOT NULL,
status TEXT NOT NULL, created_utc TEXT NOT NULL, updated_utc TEXT NOT NULL,
claimed_utc TEXT, finished_utc TEXT, run_id TEXT, result TEXT)""")
db.execute("""CREATE TABLE IF NOT EXISTS schedule_events (
sequence INTEGER PRIMARY KEY AUTOINCREMENT, schedule_id TEXT NOT NULL,
at_utc TEXT NOT NULL, event TEXT NOT NULL, run_id TEXT, payload TEXT NOT NULL)""")
@contextmanager
def _connect(self):
@@ -168,16 +171,34 @@ class ScheduleStore:
db.execute("COMMIT")
return self.get(schedule_id)
def claim(self, schedule_id):
def events(self, limit=20):
limit = max(1, min(int(limit), 100))
with self._connect() as db:
rows = db.execute('SELECT * FROM schedule_events ORDER BY sequence DESC LIMIT ?', (limit,)).fetchall()
return [{**dict(row), 'payload': json.loads(row['payload'])} for row in rows]
@staticmethod
def _event(db, schedule_id, stamp, event, run_id, payload):
from .evidence import scrub
db.execute('INSERT INTO schedule_events (schedule_id, at_utc, event, run_id, payload) VALUES (?, ?, ?, ?, ?)',
(schedule_id, stamp, event, run_id, json.dumps(scrub(payload), ensure_ascii=False)))
def claim(self, schedule_id, *, run_id=None, automatic=False):
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT status FROM schedules WHERE schedule_id = ?", (schedule_id,)).fetchone()
row = db.execute("SELECT * FROM schedules WHERE schedule_id = ?", (schedule_id,)).fetchone()
if row is None:
db.execute("ROLLBACK"); raise TaskCenterError("schedule_missing", "schedule does not exist")
if row["status"] != "pending":
db.execute("ROLLBACK"); raise TaskCenterError("schedule_claimed", "schedule is already claimed or finished")
if automatic and not row['auto_start']:
db.execute('ROLLBACK'); raise TaskCenterError('schedule_authority', 'automatic dispatch requires saved native authorization')
stamp = _now().isoformat(timespec="seconds")
db.execute("UPDATE schedules SET status = 'claimed', claimed_utc = ?, updated_utc = ? WHERE schedule_id = ?", (stamp, stamp, schedule_id))
db.execute("UPDATE schedules SET status = 'claimed', claimed_utc = ?, updated_utc = ?, run_id = ? WHERE schedule_id = ?", (stamp, stamp, run_id, schedule_id))
self._event(db, schedule_id, stamp, 'dispatch', run_id, {
'automatic': bool(automatic),
'authority': 'native_future_authorization' if automatic else 'native_confirmation',
'scope': {'task_ids': json.loads(row['task_ids']), 'plan_hashes': json.loads(row['plan_hashes'])}})
db.execute("COMMIT")
return self.get(schedule_id)
@@ -194,6 +215,7 @@ class ScheduleStore:
stamp = _now().isoformat(timespec="seconds")
db.execute("UPDATE schedules SET status = ?, updated_utc = ?, finished_utc = ?, run_id = ?, result = ? WHERE schedule_id = ?",
(status, stamp, stamp, values.get("run_id"), json.dumps(values, ensure_ascii=False), schedule_id))
self._event(db, schedule_id, stamp, 'result', values.get('run_id'), {'status': status, **values})
db.execute("COMMIT")
return self.get(schedule_id)
@@ -213,6 +235,12 @@ class ScheduleStore:
from ..trial_task_center.task_queue import _plan_hash
for row in self.list_schedules():
blockers = []
if row['status'] != 'pending':
rows.append({**row, 'blockers': ['already_claimed' if row['status'] == 'claimed' else 'finished'],
'ready': False, 'requires_confirmation': not row['auto_start'], 'dispatchable': False,
'dispatch_authority': 'native_future_authorization' if row['auto_start'] else 'native_confirmation_required',
'scope': {'task_ids': row['task_ids'], 'plan_hashes': row['plan_hashes']}})
continue
if row["status"] == "claimed": blockers.append("already_claimed")
elif row["status"] != "pending": blockers.append("finished")
if datetime.fromisoformat(row["not_before"]) > when.astimezone(timezone.utc): blockers.append("not_due")
@@ -235,7 +263,8 @@ class ScheduleStore:
if row["dependencies"] and not all(self._completed(service, task_id) for task_id in row["dependencies"]): blockers.append("dependency_incomplete")
blockers = list(dict.fromkeys(blockers))
rows.append({**row, "blockers": blockers, "ready": not blockers,
"requires_confirmation": True, "dispatchable": False,
"requires_confirmation": not row['auto_start'], "dispatchable": not blockers and row['auto_start'],
"dispatch_authority": 'native_future_authorization' if row['auto_start'] else 'native_confirmation_required',
"scope": {"task_ids": row["task_ids"], "plan_hashes": row["plan_hashes"]}})
rows.sort(key=lambda item: (-_PRIORITY[item["priority"]], item["not_before"], item["created_utc"]))
return rows
@@ -17,7 +17,7 @@ from ...dsh.scheduling import ScheduleStore
from ...dsh.experience import ExperienceStore
from ...dsh.ticket_tracking import TicketTracker
from ...dsh.impact import execution_impact
from ...dsh.health import HealthStore
from ...dsh.health import HealthStore, execution_check
from ...dsh.decision_log import DecisionLog
from ..errors import TaskCenterError
from .dsh_task_lifecycle import DshLifecycleDialog
@@ -73,8 +73,10 @@ class DshOperationsController(QObject):
self.dialog = None
self.worker = None
self.request_id = None
self._observed_execution = None
self.results = {}
self.cache = {'runs': [], 'schedules': [], 'experiences': [], 'tickets': [], 'decisions': [],
self.cache = {'runs': [], 'schedules': [], 'schedule_events': [], 'section_errors': [],
'experiences': [], 'tickets': [], 'decisions': [],
'decision_audit': {'status': 'unknown'},
'health': {'status': 'degraded', 'checks': []}, 'activity': {}}
self.timer = QTimer(self)
@@ -93,7 +95,23 @@ class DshOperationsController(QObject):
view.stopped.connect(self.runtime_stopped)
def context(self):
return {**self.cache, 'busy': bool(self.busy or self.window._workers or self._other_dialog())}
value = {**self.cache, 'busy': bool(self.busy or self.window._workers or self._other_dialog())}
health = self.cache.get('health', {})
if health.get('checks'):
checks = [execution_check(self._execution_state()) if row['name'] == 'execution' else dict(row)
for row in health['checks']]
value['health'] = {**health, 'checks': checks,
'status': 'blocked' if any(row['status'] == 'blocked' for row in checks) else
'degraded' if any(row['status'] == 'degraded' for row in checks) else 'ok'}
return value
def _execution_state(self):
if self.window._dsh_live_run.get('active'):
return 'running'
if self.dialog or any(getattr(ctl, 'dialog', None) for ctl in
(self.window._dsh_lifecycle, self.window._dsh_task_creation)):
return 'confirmation'
return 'busy' if any(worker is not self.worker for worker in self.window._workers) else 'idle'
def _state(self, status, message='', **values):
self.cache['activity'] = {'status': status, 'message': message, **values}
@@ -117,6 +135,7 @@ class DshOperationsController(QObject):
code=getattr(error, 'code', 'operations_error'))
def _work(self, action, done, *, request_id=None, reserve_lane=True):
self._observed_execution = self._execution_state()
worker = ServiceWorker(action)
self.worker = worker
if reserve_lane:
@@ -168,29 +187,56 @@ class DshOperationsController(QObject):
def _read(self, *, synchronize_tickets=False):
service = self.window.service
runs = []
for row in self.runs.list_runs():
value = self.runs.inspect(service, row['run_id'])
if not value.get('remaining_task_ids') or value['status'] == 'completed':
value['resume_ready'] = False
runs.append(value)
tickets = self.tickets.list_tickets()
if synchronize_tickets:
errors = []
def observe(section, operation, default):
try:
return operation()
except Exception:
errors.append({'section': section, 'code': 'section_unavailable'})
return default
def read_runs():
rows = []
for row in self.runs.list_runs():
if row['status'] in {'completed', 'failed'}:
# Terminal history displays its persisted outcome, without
# rehashing current CAD inputs on every timer tick.
value = {**row, 'tasks': (row.get('result') or {}).get('tasks', []),
'resume_ready': False, 'remaining_task_ids': [], 'blockers': []}
else:
value = self.runs.inspect(service, row['run_id'])
if not value.get('remaining_task_ids'):
value['resume_ready'] = False
rows.append(value)
return rows
def read_tickets():
tickets = self.tickets.list_tickets()
# One existing ticket per refresh keeps the desktop responsive and
# avoids polling every model turn or creating any remote content.
candidates = sorted(tickets, key=lambda row: row.get('last_attempt_at') or '')
candidates = sorted(tickets, key=lambda row: row.get('last_attempt_at') or '') if synchronize_tickets else []
if candidates:
self.tickets.refresh(candidates[0]['incident_id'])
tickets = self.tickets.list_tickets()
return tickets[:20]
result = {
'runs': observe('runs', read_runs, []),
'schedules': observe('schedules', lambda: self.schedules.evaluate(service), []),
'schedule_events': observe('schedule_events', self.schedules.events, []),
'experiences': observe('experiences', lambda: self.experiences.refresh()[:20], []),
'tickets': observe('tickets', read_tickets, [])}
decisions, audit = self._read_decisions()
health = self.health.snapshot(service)
health = observe('health', lambda: self.health.snapshot(service, execution=self._observed_execution),
{'status': 'degraded', 'checks': []})
health['checks'].append({'name': 'decision_audit', 'status': 'ok' if audit['status'] == 'ok' else 'degraded',
'code': audit['code'], 'message': audit['message']})
if audit['status'] != 'ok' and health['status'] == 'ok':
health['status'] = 'degraded'
return {'runs': runs, 'schedules': self.schedules.evaluate(service),
'experiences': self.experiences.refresh()[:20], 'tickets': tickets[:20],
'health': health, 'decisions': decisions, 'decision_audit': audit}
for error in errors:
health['checks'].append({'name': error['section'], 'status': 'degraded',
'code': error['code'], 'message': '此区块暂不可读,请保留原记录并检查访问权限。'})
if errors and health['status'] == 'ok':
health['status'] = 'degraded'
return {**result, 'section_errors': errors,
'health': health, 'decisions': decisions, 'decision_audit': audit}
def refresh(self, *, synchronize_tickets=False):
if self.window._closed or self.window._workers or self.busy or self._other_dialog():
@@ -212,7 +258,7 @@ class DshOperationsController(QObject):
def ready(value):
self.cache.update(value)
self.window._bind_dsh_context()
candidate = next((r for r in value['schedules'] if r['ready'] and r['auto_start']), None)
candidate = next((r for r in value['schedules'] if r['dispatchable']), None)
if candidate and not self.window.plan_panel.has_unsaved_plan(candidate['task_ids']):
# Preserve the original native future-run authorization. This
# is not a model-supplied confirmation flag.
@@ -242,7 +242,7 @@ class DshTaskLifecycleController(QObject):
def check():
current = next((r for r in self.window._dsh_operations.schedules.evaluate(self.window.service)
if r['schedule_id'] == row['schedule_id']), None)
if not current or not current['ready'] or (automatic and not current['auto_start']):
if not current or not current['ready'] or (automatic and not current['dispatchable']):
raise TaskCenterError('schedule_blocked', '排期尚未满足时间、依赖或执行门禁。')
return current, api.preflight(self.window.service, current['task_ids'])
self._work(check, lambda pair: self._preflight_ready(request_id, 'execute', pair[0]['task_ids'], pair[1],
@@ -282,7 +282,7 @@ class DshTaskLifecycleController(QObject):
stop = self.window._batch_stop
def operation():
return execute_confirmed_run(self.window.service, self.window.service.layout_settings_path.parent,
ids, report, stop, run_id, resume=resume, schedule=schedule)
ids, report, stop, run_id, resume=resume, schedule=schedule, automatic=automatic)
def done(result):
self.window._finish_run(); self.active_ids = ()
self.window._metadata_changed(None)
@@ -649,7 +649,11 @@ class TrialTaskCenterWindow(MaterialMainWindow):
context = self._context
enabled = sum(row.enabled for row in context.targets) if context.task.target_plan_mode else sum(r.enabled for r in context.rules)
from ...dsh import task_lifecycle as lifecycle
report = lifecycle.preflight(self.service, [context.task.task_id])
try:
report = lifecycle.preflight(self.service, [context.task.task_id])
except Exception as error:
self._show_error(error, owner_task_id=context.task.task_id)
return
self._dsh_confirmation_impact = report.get('impact', {})
if not self._quick_run_confirmer('current', 1, enabled):
return
@@ -692,7 +696,11 @@ class TrialTaskCenterWindow(MaterialMainWindow):
report = None
if len(ids) <= 20:
from ...dsh import task_lifecycle as lifecycle
report = lifecycle.preflight(self.service, list(ids), allow_completed=True)
try:
report = lifecycle.preflight(self.service, list(ids), allow_completed=True)
except Exception as error:
self._show_error(error, owner_task_id=ids[0])
return
self._dsh_confirmation_impact = report.get('impact', {}) if report else {}
if not self._quick_run_confirmer('batch', len(ids), 0):
return