Merge remote-tracking branch 'origin/main' into HEAD

This commit is contained in:
阿白叔 committed 2026-11-03 10:42:21 +08:00
commit e9454cf01f
104 files changed
+8458 -100

No files matched your search

@@ -0,0 +1,38 @@
"""Safe local DSH response settings; provider credentials stay elsewhere."""
import json
from pathlib import Path
from uuid import uuid4
DEFAULTS = {'response_timeout_seconds': 90, 'model_context_limit': 16000}
def validate(raw):
if not isinstance(raw, dict) or set(raw) - set(DEFAULTS):
raise ValueError('unsupported assistant setting')
value = dict(DEFAULTS); value.update(raw)
if type(value['response_timeout_seconds']) is not int or not 15 <= value['response_timeout_seconds'] <= 600:
raise ValueError('response timeout must be 15..600 seconds')
if type(value['model_context_limit']) is not int or not 2000 <= value['model_context_limit'] <= 128000:
raise ValueError('model context limit must be 2000..128000 tokens')
return value
def load_settings(data_root):
try:
return validate(json.loads((Path(data_root) / 'dsh/assistant-settings.json').read_text(encoding='utf8')))
except (OSError, ValueError, TypeError):
return dict(DEFAULTS)
def save_settings(data_root, raw):
from ..trial_task_center.path_access import retry_sharing_violation
value = validate(raw)
path = Path(data_root) / 'dsh/assistant-settings.json'
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name('settings-' + uuid4().hex + '.tmp')
try:
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf8')
retry_sharing_violation(lambda: temporary.replace(path), target=path)
finally:
temporary.unlink(missing_ok=True)
return value
@@ -0,0 +1,65 @@
"""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')
if type(row['failed_items']) is not int or row['failed_items'] != 0:
blockers.append('failed_items')
if row['queue_complete'] is not True:
blockers.append('queue_incomplete')
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))}
+127
View File
@@ -0,0 +1,127 @@
"""Append-only, hash-linked records for automatic DSH decisions."""
from __future__ import annotations
from collections import deque
from datetime import datetime, timezone
from hashlib import sha256
import json
import os
from pathlib import Path
import re
from threading import RLock
from .evidence import scrub
_ID = re.compile(r"^[0-9a-f]{24}$")
_MAX = 2000 # Presentation limit only; never limits append or verification.
_LOCK = RLock()
def _bounded(value, limit=1000):
value = scrub(value)
if isinstance(value, str):
return value[:limit]
if isinstance(value, list):
return [_bounded(item, limit) for item in value[:20]]
if isinstance(value, dict):
return {str(key)[:80]: _bounded(item, limit) for key, item in list(value.items())[:40]}
return value
def _record_hash(value):
body = {key: item for key, item in value.items() if key != 'record_hash'}
payload = json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
return sha256(payload.encode('utf8')).hexdigest()
class _CorruptLog(ValueError):
def __init__(self, code, checked):
super().__init__('decision_log_corrupt: ' + code)
self.code, self.checked = code, checked
class DecisionLog:
def __init__(self, data_root):
self.path = Path(data_root) / "dsh" / "decisions.jsonl"
def append(self, record):
if not isinstance(record, dict) or not _ID.fullmatch(str(record.get("incident_id", ""))):
raise ValueError("incident_id")
# Validate the original bytes all the way to EOF. Display truncation or
# redaction must never choose the next sequence or change hashed input.
with _LOCK:
sequence, previous = 0, ''
for row in self._records():
sequence, previous = row['sequence'], row['record_hash']
value = self._new_record(record, sequence + 1, previous)
self.path.parent.mkdir(parents=True, exist_ok=True)
with self.path.open('a+b') as stream:
if stream.tell():
stream.seek(-1, os.SEEK_END)
if stream.read(1) != b'\n':
stream.write(b'\n')
stream.write((json.dumps(value, ensure_ascii=False, sort_keys=True) + '\n').encode('utf8'))
stream.flush()
os.fsync(stream.fileno())
return value
@staticmethod
def _new_record(record, sequence, previous):
value = {"sequence": sequence, "at_utc": datetime.now(timezone.utc).isoformat(),
"previous_hash": previous, "incident_id": record["incident_id"],
"trigger": _bounded(record.get("trigger", ""), 160),
"evidence_refs": _bounded(record.get("evidence_refs", []), 300),
"gates": _bounded(record.get("gates", {}), 300),
"candidate_action": _bounded(record.get("candidate_action", "none"), 160),
"authorized_scope": _bounded(record.get("authorized_scope", {}), 600),
"outcome": _bounded(record.get("outcome", "unknown"), 160),
"human_takeover": bool(record.get("human_takeover", False))}
value['record_hash'] = _record_hash(value)
return value
def _records(self, sequence=None):
"""Stream the complete raw chain, failing at the first invalid record."""
try:
stream = self.path.open('rb')
except FileNotFoundError:
return
previous, checked = '', 0
with stream:
while sequence is None or checked < sequence:
line = stream.readline()
if not line:
break
try:
value = json.loads(line)
except (ValueError, UnicodeError) as error:
raise _CorruptLog('invalid_json', checked) from error
if not isinstance(value, dict) or not _ID.fullmatch(str(value.get('incident_id', ''))):
raise _CorruptLog('invalid_record', checked)
if type(value.get('sequence')) is not int or value['sequence'] != checked + 1:
raise _CorruptLog('sequence_mismatch', checked)
if value.get('previous_hash') != previous or value.get('record_hash') != _record_hash(value):
raise _CorruptLog('hash_mismatch', checked)
previous, checked = value['record_hash'], checked + 1
yield value
def list(self, limit=20):
if type(limit) is not int or limit <= 0:
return []
with _LOCK:
rows = deque(self._records(), maxlen=min(limit, _MAX))
return [_bounded(row, 2000) for row in rows]
def verify(self, sequence=None):
"""Verify every record unless the caller explicitly requests a prefix."""
if sequence is not None and (type(sequence) is not int or sequence < 1):
raise ValueError('decision_sequence')
with _LOCK:
previous, checked = '', 0
try:
for value in self._records(sequence):
previous, checked = value['record_hash'], checked + 1
except _CorruptLog as error:
return {'valid': False, 'checked': error.checked, 'error': error.code}
except OSError:
return {'valid': False, 'checked': checked, 'error': 'read_unavailable'}
return {"valid": True, "checked": checked, "last_hash": previous}
+121
View File
@@ -0,0 +1,121 @@
"""Execute a natively confirmed frozen scope and persist its actual receipt."""
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
def _failure_evidence(service, journal, run_id, baseline):
evidence = {key: baseline[key] for key in ('tasks', 'entries') if key in baseline}
if not baseline:
return evidence
try:
# Inspect while the journal still records this authorized attempt as
# running. Only its verified, monotonic progress may advance the old
# baseline; terminal changes, failed/uncertain results and rollbacks
# must remain visible to the next inspection.
inspected = journal.inspect(service, run_id)
changes = inspected['diff']['evidence_changes']
if (inspected['status'] != 'running' or not inspected['diff']['safe']
or not changes or not all(row.get('expected_progress') is True for row in changes)):
return evidence
tasks = {row['task_id']: dict(row) for row in baseline['tasks']}
for change in changes:
tasks[change['task_id']][change['field']] = change['current']
evidence.update(tasks=list(tasks.values()), verified_progress=changes)
except Exception:
# Readback failure must neither hide the original execution error nor
# replace the last durable evidence with an incomplete snapshot.
pass
return evidence
def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None, automatic=False):
prior = RunJournal(root).get(run_id) if resume else None
schedule_id = schedule['schedule_id'] if schedule else (prior or {}).get('schedule_id')
if schedule_id:
with ScheduleStore(root).execution_lease(schedule_id):
return _execute_confirmed_run(service, root, task_ids, report, stop, run_id,
resume=resume, schedule=schedule, automatic=automatic)
return _execute_confirmed_run(service, root, task_ids, report, stop, run_id, resume=resume)
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)
schedules = ScheduleStore(root)
initialized = False
claimed = False
baseline = {}
try:
if schedule:
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'], 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']:
raise TaskCenterError('run_blocked', '原执行范围或证据已变化,请先核验。')
baseline = inspected.get('result') or {}
journal.resume(run_id)
else:
journal.begin(run_id, task_ids, report['plan_hashes'], schedule_id=schedule['schedule_id'] if schedule else None)
initialized = True
result = execute_task_queue(service, tuple(task_ids), stop_event=stop,
expected_plan_hashes=report['plan_hashes'],
queue_id=run_id if resume and resume['queue_available'] else None,
checkpoint_id=None if resume and resume['queue_available'] else run_id)
except Exception as error:
failure = {**(_failure_evidence(service, journal, run_id, baseline) if initialized else {}),
'status': 'interrupted', 'run_id': run_id, 'queue_id': run_id,
'code': getattr(error, 'code', 'execution_interrupted'), 'message': '执行未完成,请按原队列证据核验后接续。'}
if initialized:
journal.finish(run_id, failure)
if claimed:
schedules.finish(schedule['schedule_id'], 'interrupted', run_id=run_id, receipt=failure)
raise
entries = [{'task_id': e.task_id, 'state': e.state, 'message': e.message} for e in result.entries]
status = ('blocked' if result.paused and any(e['state'] == 'blocked' for e in entries)
else 'paused' if result.paused else 'failed' if any(e['state'] == 'failed' for e in entries) else 'completed')
receipt = {'status': status, 'run_id': run_id, 'queue_id': result.queue_id, 'paused': result.paused,
'user_pause_requested': bool(stop.is_set()), 'awaiting_user_resume': bool(result.paused and stop.is_set()),
'entries': entries, 'tasks': [], 'reporting_errors': [],
'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}
try:
context = service.task_context(entry['task_id']); p = context.progress
actual.update(name=context.task.name, saved_items=p.saved_items, failed_items=p.failed_items,
no_match_items=p.no_match_items, interrupted=context.interrupted, queue_complete=p.queue_complete)
except Exception as error:
receipt['reporting_errors'].append({'task_id': entry['task_id'], 'code': getattr(error, 'code', 'context_unavailable')})
receipt['tasks'].append(actual)
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')})
try:
journal.finish(run_id, receipt)
except Exception:
receipt['reporting_errors'].append({'code': 'receipt_enrichment_unavailable'})
return receipt
+204
View File
@@ -0,0 +1,204 @@
"""A bounded, read-only index of previously recorded DSH incident evidence."""
from __future__ import annotations
import json
from datetime import datetime, timezone
from pathlib import Path
import re
from .evidence import scrub, write_json
_IDENTIFIER = re.compile(r"^[0-9a-f]{24}$")
_KNOWN_EVIDENCE = (
"verification.json", "snapshot.json", "snapshot-after.json", "gates.json",
"actions.json", "diagnostics-before.zip", "diagnostics-after.zip", "manifest.json",
)
def _text(value, limit):
# Scrub before bounding so truncation cannot expose a partial credential.
return scrub(value)[:limit] if isinstance(value, str) else ""
def _attempts(value):
return value if type(value) is int and value in (0, 1) else 0
def _retry_error(value):
if not isinstance(value, dict):
return None
return {key: _text(value.get(key), limit) for key, limit in
(("type", 128), ("code", 160), ("detail", 1000))}
def _outcome(verification, *, verified):
result = {"verified": verified}
if isinstance(verification, dict):
for key in ("queue_complete", "interrupted", "paused"):
if type(verification.get(key)) is bool:
result[key] = verification[key]
for key in ("saved_items", "failed_items", "no_match_items", "completed_items"):
if type(verification.get(key)) is int and 0 <= verification[key] <= 10**9:
result[key] = verification[key]
return result
def _newest(value):
try:
date = datetime.fromisoformat(value.replace("Z", "+00:00"))
return date.replace(tzinfo=timezone.utc).timestamp() if date.tzinfo is None else date.timestamp()
except (TypeError, ValueError, OverflowError, OSError):
return 0
class ExperienceStore:
"""Index only incident records and named evidence files; never crawl CAD files."""
def __init__(self, data_root):
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 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
record = self._read_json(path, 256 * 1024)
if not isinstance(record, dict):
continue
row = self._entry(directory, record)
if row:
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:
incident_id = str(record.get("incident_id", directory.name))
if not _IDENTIFIER.fullmatch(incident_id) or incident_id != directory.name:
return None
issue_code = str(record.get("issue_code", ""))[:160]
message = str(record.get("message", ""))[:2000]
task_id = str(record.get("task_id", ""))[:128]
evidence_refs = []
# Evidence identity is explicit and bounded. Do not recurse into project/CAD files.
for name in _KNOWN_EVIDENCE:
candidate = directory / name
if candidate.is_file() and not candidate.is_symlink():
evidence_refs.append(candidate.relative_to(self.data_root).as_posix())
verification = None
verification_path = directory / "verification.json"
if verification_path.is_file() and not verification_path.is_symlink():
value = self._read_json(verification_path, 32 * 1024)
verification = scrub(value) if isinstance(value, dict) else None
verified = self._verified(verification, evidence_refs)
analyses = []
if isinstance(record.get("analyses"), list):
for analysis in record["analyses"][:2]:
if isinstance(analysis, dict):
analyses.append({"phase": _text(analysis.get("phase"), 64),
"reply": _text(analysis.get("reply", analysis.get("error")), 1500)})
actions = {}
actions_path = directory / "actions.json"
if actions_path.is_file() and not actions_path.is_symlink():
value = self._read_json(actions_path, 32 * 1024)
if isinstance(value, dict):
# Fixed observational fields only: model tool calls, commands and
# claimed authorizations never become reusable execution rights.
actions = {"attempts": _attempts(value.get("attempts")),
"retry_error": _retry_error(value.get("retry_error")),
"retry_skipped": _text(value.get("retry_skipped"), 1000),
"outcome": _outcome(value.get("verification"), verified=verified)}
newest = _text(record.get("updated_utc") or record.get("created_utc"), 64)
if not newest:
newest = datetime.fromtimestamp((directory / "incident.json").stat().st_mtime,
timezone.utc).isoformat()
return scrub({
"incident_id": incident_id,
"task_id": task_id,
"issue_code": issue_code,
"message": message,
"status": str(record.get("status", ""))[:64],
"verified": verified,
"verification": verification,
"analyses": analyses,
"attempts": _attempts(record.get("attempts")),
"actions": actions,
"retry_error": _retry_error(record.get("retry_error")),
"retry_skipped": _text(record.get("retry_skipped"), 1000),
"outcome": _outcome(verification, verified=verified),
"updated_utc": newest,
"evidence_refs": evidence_refs,
"ticket": {}, # Ticket closure is feedback, never verification.
} | ({"task_name": str(record["task_name"])[:128]} if "task_name" in record else {}))
@staticmethod
def _verified(verification, evidence_refs: list[str]) -> bool:
# verification.json itself is the assertion; require at least one separate
# persisted evidence artifact (snapshot, gates, or diagnostic bundle).
if not isinstance(verification, dict) or len(evidence_refs) < 2:
return False
# These are persisted worker facts, rather than a model's ``resolved`` claim.
return (verification.get("queue_complete") is True
and type(verification.get("failed_items")) is int
and verification.get("failed_items") == 0
and verification.get("interrupted") is False
and verification.get("paused") is False)
def search(self, issue_code: str = "", *, limit: int = 5) -> list[dict]:
if not isinstance(limit, int) or limit <= 0:
return []
self.refresh()
query = str(issue_code or "").strip().casefold()
matches = []
for row in self._rows:
context = " ".join((row.get("issue_code", ""), row.get("message", ""),
row.get("task_id", ""), row.get("task_name", ""),
json.dumps(row.get("analyses", []), ensure_ascii=False),
json.dumps(row.get("actions", {}), ensure_ascii=False),
row.get("retry_skipped", ""))).casefold()
if not query or query in context:
matches.append(dict(row))
matches.sort(key=lambda row: (row.get("verified") is True,
bool(query) and row.get("issue_code", "").casefold() == query,
_newest(row.get("updated_utc", "")), row["incident_id"]), reverse=True)
return matches[:min(limit, 50)]
def summary(self) -> dict:
self.refresh()
counts = {}
for row in self._rows:
code = row.get("issue_code", "") or "unknown"
counts[code] = counts.get(code, 0) + 1
return {"total": len(self._rows), "verified": sum(bool(row["verified"]) for row in self._rows),
"unverified": sum(not row["verified"] for row in self._rows), "by_issue_code": counts}
@staticmethod
def _read_json(path, limit):
try:
with path.open("rb") as stream:
raw = stream.read(limit + 1)
return json.loads(raw) if len(raw) <= limit else None
except (OSError, ValueError, TypeError):
return 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}
+4
View File
@@ -13,6 +13,7 @@ from uuid import uuid4
from .evidence import scrub
from .issue_credentials import issue_target, load_bootstrap
from .issue_transport import IssueTransport
class NoRedirect(urllib.request.HTTPRedirectHandler):
@@ -34,6 +35,9 @@ class GitIssuePublisher:
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')
transport = IssueTransport(self.config_path).credentials(config)
if transport.get('headers'):
return config, transport['headers'], transport.get('source', 'issue_transport')
bootstrap = load_bootstrap()
if (bootstrap and bootstrap['server'].rstrip('/') == config['server'].rstrip('/')
and bootstrap['repository'] == config['repository']):
+80
View File
@@ -0,0 +1,80 @@
"""Read-only, bounded health checks for the DSH assistant."""
from __future__ import annotations
from datetime import datetime, timezone
import json
from pathlib import Path
from .evidence import scrub
from .issue_credentials import load_bootstrap, issue_target
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, execution=None):
checked = now.isoformat(timespec="seconds") if now is not None else _now()
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})
def _provider(self):
path = self.data_root / "dsh" / "provider.json"
try:
value = json.loads(path.read_text(encoding="utf8"))
configured = isinstance(value, dict) and bool(value.get("base_url")) and bool(value.get("default_model"))
except (OSError, ValueError, TypeError):
configured = False
return {"name": "provider", "status": "ok" if configured else "degraded",
"code": "ready" if configured else "provider_unconfigured",
"message": "模型提供方已配置" if configured else "尚未配置模型提供方"}
def _stores(self):
dsh = self.data_root / "dsh"
try:
if dsh.exists() and not dsh.is_dir():
raise OSError("state path is not a directory")
# Health is observational: do not create files or alter timestamps.
return {"name": "stores", "status": "ok", "code": "ready", "message": "本地状态目录可用"}
except OSError:
return {"name": "stores", "status": "blocked", "code": "store_unavailable", "message": "本地状态目录不可写"}
def _tickets(self):
cache = self.data_root / "dsh" / "ticket-cache"
if not cache.exists():
return {"name": "tickets", "status": "ok", "code": "no_cache", "message": "暂无工单同步缓存"}
try:
count = sum(1 for path in cache.iterdir() if path.is_file() and path.suffix == ".json")
except OSError:
return {"name": "tickets", "status": "degraded", "code": "ticket_cache_unreadable", "message": "工单缓存不可读"}
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": "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": "当前使用预置工单凭据,需要服务端吊销和轮换管理"}
return {"name": "issue_credentials", "status": "ok", "code": "machine_credential_or_disabled",
"message": "未发现预置工单凭据"}
+194
View File
@@ -0,0 +1,194 @@
"""Read-only execution impact reports for saved DSH task plans.
This module deliberately consumes persisted task contexts and target plans only.
It never scans CAD files or attempts to resolve mapping rules against a project.
"""
from __future__ import annotations
from hashlib import sha256
import json
from typing import Any
from ..trial_task_center.errors import TaskCenterError
_MAX_TASKS = 20
_MAX_LIMIT = 100
def _hash(value: Any) -> str:
encoded = json.dumps(value, sort_keys=True, ensure_ascii=False,
separators=(",", ":"), allow_nan=False).encode("utf-8")
return sha256(encoded).hexdigest()
def _scope(task_ids: object) -> tuple[str, ...]:
if not isinstance(task_ids, (list, tuple)) or not 1 <= len(task_ids) <= _MAX_TASKS:
raise TaskCenterError("assistant_task_scope", "请选择 1 至 20 个不同的真实任务。")
if any(not isinstance(task_id, str) or not task_id or len(task_id) > 128 for task_id in task_ids):
raise TaskCenterError("assistant_task_scope", "任务编号无效。")
if len(set(task_ids)) != len(task_ids):
raise TaskCenterError("assistant_task_scope", "请选择 1 至 20 个不同的真实任务。")
return tuple(task_ids)
def _limit(limit: object) -> int:
if type(limit) is not int or not 1 <= limit <= _MAX_LIMIT:
raise TaskCenterError("assistant_impact_limit", "影响预览条数必须是 1 至 100 的整数。")
return limit
def _policy(task, row) -> tuple[str, str | None]:
if bool(getattr(row, "custom_value_enabled", False)):
return "custom", str(getattr(row, "custom_value", ""))
if bool(getattr(task, "copy_part_number_to_value", False)):
# The library label is only known during the CAD execution read. It is
# unsafe for a preview to present the replacement part number as Value.
return "part_label", None
return "preserve", None
def _target_row(task, task_id: str, row) -> dict[str, Any]:
target = row.target
value_policy, proposed = _policy(task, row)
if value_policy == "preserve":
proposed = target.old_value
sync_nc = bool(getattr(row, "sync_nc", True))
target_cell = getattr(row, "target_cell", "")
return {
"task_id": task_id,
"project": str(target.project_path),
"coverage": "exact",
"enabled": bool(row.enabled),
"component_count": int(bool(row.enabled)),
"schematic_name": target.schematic_name,
"sheet": target.sheet_number,
"sheet_number": target.sheet_number,
"refdes": target.refdes,
"uid": target.uid,
"old_part_number": target.old_part_number,
"new_part_number": row.new_part_number,
"old_value": target.old_value,
"proposed_value": proposed,
"value_policy": value_policy,
"target_cell": target_cell,
"target_cell_policy": target_cell,
"sync_nc": sync_nc,
"nc_policy": "sync" if sync_nc else "preserve",
"mapping_scope": None,
}
def _mapping_row(task, context, task_id: str, rule) -> dict[str, Any]:
value_policy, proposed = _policy(task, rule)
project = getattr(context, "project", None)
project_path = str(project.path) if project is not None else ""
sync_nc = bool(getattr(rule, "sync_nc", True))
return {
"task_id": task_id,
"project": project_path,
"coverage": "mapping_only",
"enabled": bool(getattr(rule, "enabled", True)),
"component_count": None,
"schematic_name": None,
"sheet": None,
"sheet_number": None,
"refdes": None,
"uid": None,
"old_part_number": rule.old_part_number,
"new_part_number": rule.new_part_number,
"old_value": None,
"proposed_value": proposed,
"value_policy": value_policy,
"target_cell": getattr(rule, "target_cell", ""),
"target_cell_policy": getattr(rule, "target_cell", ""),
"sync_nc": sync_nc,
"nc_policy": "sync" if sync_nc else "preserve",
"mapping_scope": {"old_part_number": rule.old_part_number,
"new_part_number": rule.new_part_number},
}
def execution_impact(service, task_ids, *, limit: int = 100) -> dict[str, Any]:
"""Return a bounded, deterministic report of the saved execution scope.
Mapping tasks retain ``component_count=None`` because no CAD inventory is
consulted. Exact target plans count enabled saved rows and include their
stable identities and policies.
"""
ids = _scope(task_ids)
bound = _limit(limit)
from ..trial_task_center.task_queue import _plan_hash
all_rows: list[dict[str, Any]] = []
task_reports: list[dict[str, Any]] = []
plan_hashes: dict[str, str] = {}
coverage_values: list[str] = []
known_component_count = 0
enabled_scope = 0
for task_id in ids:
context = service.task_context(task_id)
task = context.task
exact = bool(getattr(task, "target_plan_mode", False))
task_rows: list[dict[str, Any]] = []
if exact:
# service.target_plan() is the authoritative saved-row API and
# retains target_cell on versions whose context projection is old.
saved_rows = tuple(service.target_plan(task_id))
task_rows = [_target_row(task, task_id, row) for row in saved_rows]
task_coverage = "exact"
task_count = sum(row["component_count"] for row in task_rows)
known_component_count += task_count
enabled_scope += task_count
else:
task_rows = [_mapping_row(task, context, task_id, rule)
for rule in tuple(getattr(context, "rules", ()))]
task_coverage = "mapping_only"
enabled_scope += sum(1 for row in task_rows if row["enabled"])
coverage_values.append(task_coverage)
plan_hashes[task_id] = _plan_hash(service.for_project_task(task_id), task_id)
project = getattr(context, "project", None)
task_reports.append({
"task_id": task_id,
"name": getattr(task, "name", ""),
"project": str(project.path) if project is not None else "",
"coverage": task_coverage,
"component_count": task_count if exact else None,
"enabled_scope": sum(row["component_count"] for row in task_rows) if exact else sum(1 for row in task_rows if row["enabled"]),
"total_rows": len(task_rows),
"returned_rows": 0,
"omitted_row_count": 0,
})
all_rows.extend(task_rows)
full_payload = {"task_ids": list(ids), "rows": all_rows, "plan_hashes": plan_hashes}
full_fingerprint = _hash(full_payload)
visible_rows = all_rows[:bound]
remaining = bound
for report in task_reports:
count = min(report["total_rows"], remaining)
report["returned_rows"] = count
report["omitted_row_count"] = report["total_rows"] - count
remaining -= count
omitted = len(all_rows) - len(visible_rows)
coverage = coverage_values[0] if len(set(coverage_values)) == 1 else "mixed"
return {
"task_ids": list(ids),
"coverage": coverage,
"component_count": known_component_count if coverage == "exact" else None,
"known_component_count": known_component_count,
"enabled_scope": enabled_scope,
"tasks": task_reports,
"rows": visible_rows,
"total_rows": len(all_rows),
"returned_rows": len(visible_rows),
"omitted_row_count": omitted,
"truncated": bool(omitted),
"limit": bound,
"plan_hashes": plan_hashes,
"fingerprint": full_fingerprint,
"full_fingerprint": full_fingerprint,
"cad_connection_checked": False,
"read_only": True,
}
+36 -3
View File
@@ -9,6 +9,8 @@ import re
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
@@ -35,6 +37,28 @@ 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
self.decisions = DecisionLog(self.data_root)
def _record_decision(self, record, evidence, *, outcome, human_takeover=False):
refs = []
for path in sorted(evidence.directory.iterdir()):
if path.is_file() and path.name in {'snapshot.json', 'snapshot-after.json', 'gates.json',
'actions.json', 'verification.json', 'diagnose.json', 'reflect.json', 'evidence.zip'}:
refs.append(path.relative_to(self.data_root).as_posix())
try:
value = self.decisions.append({
'incident_id': record['incident_id'], 'trigger': record.get('issue_code', ''),
'evidence_refs': refs, 'gates': record.get('gates', {}),
'candidate_action': 'retry_failed' if record.get('attempts') else 'none',
'authorized_scope': {'task_id': record.get('task_id'), 'run_id': record.get('run_id')},
'outcome': outcome, 'human_takeover': human_takeover})
record['decision_sequence'] = value['sequence']
record['decision_hash'] = value['record_hash']
except Exception as error:
# Evidence and the incident state remain authoritative; make the
# missing append visible rather than claiming an auditable result.
record['decision_log_status'] = 'unavailable'
evidence.event('decision_log_unavailable', error=type(error).__name__)
def run(self, task_id, issue_code, message, *, run_id='observation', execution_authorized=False, stop_event=None):
with _RUN_LOCK:
@@ -89,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.
@@ -136,6 +164,8 @@ class IncidentRunner:
if p.queue_complete and not p.failed_items and not current.interrupted and not outcome.paused:
update('resolved')
evidence.capture('diagnostics-after')
self._record_decision(record, evidence, outcome='resolved')
write_json(state_path, record)
evidence.pack(record)
return record
except Exception as error:
@@ -158,7 +188,10 @@ class IncidentRunner:
update('pending_issue')
self._draft(record, evidence)
archive = evidence.pack(record)
return self._publish(record, evidence, archive)
result = self._publish(record, evidence, archive)
self._record_decision(record, evidence, outcome=record.get('status', 'pending_issue'))
write_json(state_path, record)
return result
def _snapshot(self, task_id, issue_code, message):
try:
+75
View File
@@ -0,0 +1,75 @@
"""Fixed-target issue-token broker core used by the reference HTTP service."""
from __future__ import annotations
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 = 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 '')
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(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 = 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', ''))
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', ''))
if not 1 <= len(key) <= 160:
raise ValueError('missing_idempotency_key')
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)
@@ -0,0 +1,68 @@
"""Fixed-target issue credentials with explicit static broker provenance."""
from __future__ import annotations
import json
from pathlib import Path
import urllib.parse
import urllib.request
from .issue_credentials import issue_target, load_bootstrap
def _post_broker(url, payload, timeout=10):
request = urllib.request.Request(url, data=json.dumps(payload).encode("utf8"),
headers={"Content-Type": "application/json", "Accept": "application/json"})
with urllib.request.build_opener(_NoRedirect()).open(request, timeout=timeout) as response:
return json.loads(response.read(64 * 1024))
class _NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
class IssueTransport:
def __init__(self, config_path):
self.config_path = Path(config_path)
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}
broker = config.get("broker_url")
if broker:
try:
parsed = urllib.parse.urlsplit(str(broker))
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')
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": 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")
if not isinstance(token, str) or not 1 <= len(token) <= 4096 or '\n' in token or '\r' in token:
raise ValueError("invalid_broker_response")
return {"headers": {"Authorization": "token " + token}, "source": "broker",
"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()
if bootstrap and self._same_target(bootstrap, target):
return {"headers": {"Authorization": "token " + bootstrap["token"]},
"source": "prefilled_issue_token", "expires_utc": None, "rotation_required": True}
return {"source": "credential_unavailable", "rotation_required": True}
@staticmethod
def _same_target(left, right):
return (isinstance(left, dict) and isinstance(right, dict)
and str(left.get("server", "")).rstrip("/") == str(right.get("server", "")).rstrip("/")
and left.get("repository") == right.get("repository"))
+16
View File
@@ -0,0 +1,16 @@
"""Bounded live execution state shared by the task center and DSH dock."""
def read_live_run(service, feedback, *, elapsed, pause_requested, run_id, task_ids):
task_id = feedback.task_id or (task_ids[0] if task_ids else None)
context = service.task_context(task_id) if task_id else None
progress = context.progress if context else None
return {'active': True, 'run_id': run_id, 'task_id': task_id,
'task_ids': list(task_ids), 'name': context.task.name if context else '',
'stage': feedback.stage, 'stage_seconds': feedback.stage_seconds,
'elapsed_seconds': int(elapsed), 'pause_requested': bool(pause_requested),
'saved_items': getattr(progress, 'saved_items', 0),
'failed_items': getattr(progress, 'failed_items', 0),
'no_match_items': getattr(progress, 'no_match_items', 0),
'completed_items': getattr(progress, 'completed_items', 0),
'total_items': getattr(progress, 'total_items', 0), 'component_count_known': False}
+2 -2
View File
@@ -42,11 +42,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='', automation=None, creation=None) -> dict:
def write_context(data_root: Path, snapshot: TaskSnapshot, *, events=(), action_result='', task_name='', automation=None, creation=None, lifecycle=None, operations=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], 'automation': automation or {}, 'creation': creation or {}}
'task_name': str(task_name)[:128], 'automation': automation or {}, 'creation': creation or {}, 'lifecycle': lifecycle or {}, 'operations': operations or {}}
temporary = data_root / ('context-' + uuid4().hex + '.tmp')
temporary.write_text(json.dumps(value, ensure_ascii=False), encoding='utf8')
destination = data_root / 'task-context.json'
+62
View File
@@ -0,0 +1,62 @@
"""Bounded differences used before confirming an original queue resume."""
from __future__ import annotations
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 = {} if current_plan_hashes is None else dict(current_plan_hashes)
blockers = list(inspected_run.get('blockers') or [])
contexts = {}
for task_id in ids:
try:
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')
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', [])}
previous_entries = {row['task_id']: row.get('state')
for row in (inspected_run.get('result') or {}).get('entries', [])}
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')}}
# A resumed run can crash after verified progress has landed, before
# its final receipt. The old pause receipt remains a useful baseline,
# but is immutable only for tasks that were already terminal then.
progressing = (
inspected_run.get('status') == 'running'
and inspected_run.get('queue_available') is True
and previous_entries.get(task_id) in {'pending', 'paused', 'running', 'blocked'}
and inspected_run.get('checkpoint_states', {}).get(task_id) in {'running', 'paused', 'completed'}
and saved.get('interrupted') is False and actual['interrupted'] is False
and saved.get('queue_complete') is False and type(actual['queue_complete']) is bool
and type(saved.get('failed_items')) is int and saved['failed_items'] == 0
and type(actual['failed_items']) is int and actual['failed_items'] == 0
and all(type(saved.get(key)) is int and type(actual[key]) is int
and 0 <= saved[key] <= actual[key] for key in ('saved_items', 'no_match_items')))
for field, value in actual.items():
if saved.get(field) is not None and value != saved[field]:
change = {'task_id': task_id, 'field': field, 'saved': saved[field], 'current': value}
if progressing:
change['expected_progress'] = True
evidence_changes.append(change)
if any(not row.get('expected_progress') for row in 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': evidence_changes[:100], 'evidence_baseline_available': bool(baseline),
'blockers': blockers[:20]}
+235
View File
@@ -0,0 +1,235 @@
"""Durable, Qt-free execution run receipts and read-only recovery inspection."""
from __future__ import annotations
from dataclasses import asdict, is_dataclass
from contextlib import contextmanager
from datetime import datetime, timezone
import json
from pathlib import Path
import re
import sqlite3
from typing import Any
from ..trial_task_center.errors import TaskCenterError
_ID = re.compile(r"^[0-9a-f]{32}$")
_TASK_ID = re.compile(r"(?:[0-9a-f]{32}|[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})")
def _now() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def _json(value: Any) -> Any:
if is_dataclass(value):
return _json(asdict(value))
if isinstance(value, Path):
return str(value)
if isinstance(value, (tuple, list)):
return [_json(item) for item in value]
if isinstance(value, dict):
return {str(key): _json(item) for key, item in value.items()}
return value
def _check_scope(run_id: str, task_ids: Any, plan_hashes: Any) -> tuple[list[str], dict[str, str]]:
if not isinstance(run_id, str) or not _ID.fullmatch(run_id):
raise TaskCenterError("run_id", "run identifier is invalid")
if not isinstance(task_ids, (list, tuple)) or not 1 <= len(task_ids) <= 20:
raise TaskCenterError("run_scope", "run must contain 1 to 20 tasks")
ids = list(task_ids)
if any(not isinstance(item, str) or not _TASK_ID.fullmatch(item) for item in ids) or len(set(ids)) != len(ids):
raise TaskCenterError("run_scope", "task identifiers are invalid")
if not isinstance(plan_hashes, dict) or set(plan_hashes) != set(ids) or any(
not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value) for value in plan_hashes.values()
):
raise TaskCenterError("run_plan", "frozen plan hashes are invalid")
return ids, dict(plan_hashes)
class RunJournal:
def __init__(self, data_root):
self.data_root = Path(data_root)
self.data_root.mkdir(parents=True, exist_ok=True)
self.path = self.data_root / "dsh-state.sqlite3"
with self._connect() as db:
db.execute("""CREATE TABLE IF NOT EXISTS run_journal (
run_id TEXT PRIMARY KEY, queue_id TEXT NOT NULL UNIQUE, task_ids TEXT NOT NULL,
plan_hashes TEXT NOT NULL, schedule_id TEXT, status TEXT NOT NULL,
started_utc TEXT NOT NULL, finished_utc TEXT, result TEXT)""")
db.execute("""CREATE TABLE IF NOT EXISTS run_journal_receipts (
receipt_id INTEGER PRIMARY KEY AUTOINCREMENT, run_id TEXT NOT NULL,
finished_utc TEXT NOT NULL, status TEXT NOT NULL, result TEXT NOT NULL)""")
@contextmanager
def _connect(self):
db = sqlite3.connect(self.path, timeout=10, isolation_level=None)
db.row_factory = sqlite3.Row
db.execute("PRAGMA busy_timeout=10000")
db.execute("PRAGMA journal_mode=WAL")
try:
yield db
finally:
db.close()
@staticmethod
def _row(row):
if row is None:
return None
return {"run_id": row["run_id"], "queue_id": row["queue_id"],
"task_ids": json.loads(row["task_ids"]), "plan_hashes": json.loads(row["plan_hashes"]),
"schedule_id": row["schedule_id"], "status": row["status"],
"started_utc": row["started_utc"], "finished_utc": row["finished_utc"],
"result": json.loads(row["result"]) if row["result"] else None}
def begin(self, run_id, task_ids, plan_hashes, *, schedule_id=None):
ids, hashes = _check_scope(run_id, task_ids, plan_hashes)
if schedule_id is not None and (not isinstance(schedule_id, str) or not _ID.fullmatch(schedule_id)):
raise TaskCenterError("schedule_id", "schedule identifier is invalid")
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
existing = db.execute("SELECT * FROM run_journal WHERE run_id = ?", (run_id,)).fetchone()
if existing:
current = self._row(existing)
if current["task_ids"] != ids or current["plan_hashes"] != hashes or current["schedule_id"] != schedule_id:
raise TaskCenterError("run_conflict", "run is already bound to another frozen scope")
db.execute("COMMIT")
return current
started = _now()
db.execute("INSERT INTO run_journal VALUES (?, ?, ?, ?, ?, ?, ?, NULL, NULL)",
(run_id, run_id, json.dumps(ids), json.dumps(hashes, sort_keys=True), schedule_id, "running", started))
db.execute("COMMIT")
return self.get(run_id)
def finish(self, run_id, result):
if not isinstance(run_id, str) or not _ID.fullmatch(run_id):
raise TaskCenterError("run_id", "run identifier is invalid")
value = _json(result)
status = value.get("status") if isinstance(value, dict) else getattr(result, "status", None)
if status not in {"completed", "failed", "paused", "blocked", "interrupted"}:
status = "completed" if isinstance(value, dict) and value.get("paused") is False else "paused"
entries = value.get("entries", []) if isinstance(value, dict) else []
if any(entry.get("state") == "blocked" for entry in entries):
status = "blocked"
elif any(entry.get("state") == "failed" for entry in entries) and status == "completed":
status = "failed"
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
if db.execute("SELECT 1 FROM run_journal WHERE run_id = ?", (run_id,)).fetchone() is None:
raise TaskCenterError("run_missing", "run does not exist")
stamp = _now()
payload = json.dumps(value, ensure_ascii=False)
db.execute("INSERT INTO run_journal_receipts (run_id, finished_utc, status, result) VALUES (?, ?, ?, ?)",
(run_id, stamp, status, payload))
db.execute("UPDATE run_journal SET status = ?, finished_utc = ?, result = ? WHERE run_id = ?",
(status, stamp, payload, run_id))
db.execute("COMMIT")
return self.get(run_id)
def resume(self, run_id):
"""Mark a natively reconfirmed continuation; keep its last durable receipt."""
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT status FROM run_journal WHERE run_id = ?", (run_id,)).fetchone()
if row is None:
raise TaskCenterError("run_missing", "run does not exist")
if row["status"] not in {"running", "paused", "blocked", "interrupted"}:
raise TaskCenterError("run_terminal", "this run has no resumable execution")
db.execute("UPDATE run_journal SET status = 'running', finished_utc = NULL WHERE run_id = ?", (run_id,))
db.execute("COMMIT")
return self.get(run_id)
def get(self, run_id):
with self._connect() as db:
return self._row(db.execute("SELECT * FROM run_journal WHERE run_id = ?", (run_id,)).fetchone())
def list_runs(self, limit=20):
if not isinstance(limit, int) or not 1 <= limit <= 1000:
raise TaskCenterError("run_limit", "run limit is invalid")
with self._connect() as db:
rows = db.execute("SELECT * FROM run_journal ORDER BY started_utc DESC LIMIT ?", (limit,)).fetchall()
return [self._row(row) for row in rows]
def inspect(self, service, run_id):
row = self.get(run_id)
if row is None:
raise TaskCenterError("run_missing", "run does not exist")
blockers: list[str] = []
checkpoint = self.data_root / "task-queues" / f"{run_id}.json"
queue = None
try:
queue = json.loads(checkpoint.read_text(encoding="utf-8"))
if queue.get("version") != 1 or queue.get("task_ids") != row["task_ids"] or queue.get("plan_hashes") != row["plan_hashes"]:
raise ValueError
entries = queue["entries"]
if set(entries) != set(row["task_ids"]) or any(
not isinstance(entry, dict) or set(entry) != {"state", "message"} or
entry["state"] not in {"pending", "running", "paused", "blocked", "completed", "failed", "skipped"} or
not isinstance(entry["message"], str) for entry in entries.values()
):
raise ValueError
except (OSError, ValueError, TypeError, KeyError, json.JSONDecodeError):
queue = None
blockers.append("queue_missing" if not checkpoint.exists() else "queue_invalid")
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:
context = service.task_context(task_id)
has_evidence = has_evidence or context.has_evidence
progress = context.progress
item.update({"status": context.task.status.value, "interrupted": bool(context.interrupted),
"saved_items": int(getattr(progress, "saved_items", 0)),
"failed_items": int(getattr(progress, "failed_items", 0)),
"no_match_items": int(getattr(progress, "no_match_items", 0)),
"total_items": int(getattr(progress, "total_items", 0))})
for key in ("saved_items", "failed_items", "no_match_items"):
counters[key] += item[key]
counters["total"] += item["total_items"]
if context.interrupted:
blockers.append("interrupted")
if getattr(progress, "failed_items", 0):
blockers.append("failed_items")
if queue and queue['entries'][task_id]['state'] == 'completed' and not (
context.has_evidence and progress.queue_complete is True
and type(progress.failed_items) is int and progress.failed_items == 0
and context.interrupted is False):
blockers.append('checkpoint_evidence_mismatch')
from ..trial_task_center.task_queue import _plan_hash
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")
tasks.append(item)
if queue:
counters["completed"] = sum(queue["entries"][task_id]["state"] in {"completed", "failed", "skipped"} for task_id in row["task_ids"])
remaining = [task_id for task_id in row["task_ids"] if not queue or queue["entries"][task_id]["state"] not in {"completed", "failed", "skipped"}]
if "queue_missing" in blockers and not has_evidence:
# The receipt may have committed before the executor created its checkpoint.
# A native reconfirmation can safely create the original queue; no auto replay.
blockers.remove("queue_missing")
if remaining:
try:
from .task_lifecycle import preflight
if not preflight(service, remaining, allow_completed=True)["ready"]:
blockers.append("preflight_blocked")
except Exception:
blockers.append("preflight_unavailable")
elif service.pending_batch_resources():
blockers.append("resources_pending")
blockers = list(dict.fromkeys(blockers))
value = {**row, "queue_available": queue is not None, "tasks": tasks, "counters": counters,
"checkpoint_states": {key: entry['state'] for key, entry in queue['entries'].items()} if queue else {},
"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, current_plan_hashes=current_hashes)
if not value['diff']['safe']:
value['blockers'] = value['diff']['blockers']
value['resume_ready'] = False
return value
+71
View File
@@ -0,0 +1,71 @@
"""Lossless rotation of schedule audit events out of the hot SQLite table."""
from hashlib import sha256
import json
import os
from uuid import uuid4
def _write_archive(root, rows):
body = b''.join((json.dumps(row, ensure_ascii=False, sort_keys=True) + '\n').encode('utf8') for row in rows)
digest = sha256(body).hexdigest()
root.mkdir(parents=True, exist_ok=True)
name = f"{rows[0]['sequence']:012d}-{rows[-1]['sequence']:012d}-{digest}.jsonl"
path = root / name
if path.exists():
if path.read_bytes() != body:
raise OSError('schedule_archive_conflict')
else:
temporary = root / (uuid4().hex + '.tmp')
try:
with temporary.open('xb') as stream:
stream.write(body)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
if sha256(path.read_bytes()).hexdigest() != digest:
raise OSError('schedule_archive_verification')
return name, digest
def archive_events(store, *, keep=5000, batch=1000):
if type(keep) is not int or keep < 1 or type(batch) is not int or not 1 <= batch <= 1000:
raise ValueError('schedule_archive_limit')
with store._connect() as db:
db.execute('BEGIN IMMEDIATE')
cutoff = db.execute('SELECT sequence FROM schedule_events ORDER BY sequence DESC LIMIT 1 OFFSET ?', (keep - 1,)).fetchone()
rows = db.execute('SELECT * FROM schedule_events WHERE sequence < ? ORDER BY sequence LIMIT ?',
(cutoff['sequence'], batch)).fetchall() if cutoff else []
if not rows:
db.execute('COMMIT')
return {'archived': 0}
values = [{**dict(row), 'payload': json.loads(row['payload'])} for row in rows]
name, digest = _write_archive(store.data_root / 'dsh' / 'schedule-audit', values)
# The archive is durable before deleting. If the DB transaction or
# process fails, retry verifies/reuses the same immutable file.
db.execute('INSERT INTO schedule_event_archives (file, first_sequence, last_sequence, event_count, sha256) VALUES (?, ?, ?, ?, ?)',
(name, rows[0]['sequence'], rows[-1]['sequence'], len(rows), digest))
db.execute('DELETE FROM schedule_events WHERE sequence BETWEEN ? AND ?', (rows[0]['sequence'], rows[-1]['sequence']))
db.execute('COMMIT')
return {'archived': len(rows), 'file': name, 'sha256': digest}
def verify_archives(root, records, cache):
current = {}
for row in records:
path = root / row['file']
if path.name != row['file'] or path.is_symlink():
raise OSError('schedule_archive_invalid')
stat = path.stat()
stamp = (stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns, stat.st_ino, row['sha256'])
if cache.get(row['file']) != stamp:
digest = sha256()
with path.open('rb') as stream:
for chunk in iter(lambda: stream.read(65536), b''):
digest.update(chunk)
if digest.hexdigest() != row['sha256']:
raise OSError('schedule_archive_corrupt')
current[row['file']] = stamp
cache.clear()
cache.update(current)
+339
View File
@@ -0,0 +1,339 @@
"""Durable scheduling decisions. This module never starts a worker or CAD operation."""
from __future__ import annotations
from datetime import datetime, timezone
from contextlib import contextmanager
import json
from pathlib import Path
import re
import sqlite3
from typing import Any
from uuid import uuid4
from ..trial_task_center.errors import TaskCenterError
_ID = re.compile(r"^[0-9a-f]{32}$")
_TASK_ID = re.compile(r"(?:[0-9a-f]{32}|[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})")
_PRIORITY = {"low": 0, "normal": 1, "high": 2, "urgent": 3}
_FIELDS = {"task_ids", "priority", "not_before", "due_at", "dependencies", "auto_start", "idle_only", "title"}
def _utc(value, *, required=False):
if value is None and not required:
return None
if not isinstance(value, str):
raise TaskCenterError("schedule_datetime", "datetime must be an ISO 8601 string with timezone")
try:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError as error:
raise TaskCenterError("schedule_datetime", "datetime must be an ISO 8601 string with timezone") from error
if parsed.tzinfo is None:
raise TaskCenterError("schedule_datetime", "datetime timezone is required")
return parsed.astimezone(timezone.utc).isoformat(timespec="seconds")
def _now():
return datetime.now(timezone.utc)
def _ids(values, *, required=True):
if not isinstance(values, (list, tuple)) or (required and not 1 <= len(values) <= 20):
raise TaskCenterError("schedule_scope", "schedule must contain 1 to 20 task identifiers")
values = list(values)
if len(values) > 20 or any(not isinstance(value, str) or not _TASK_ID.fullmatch(value) for value in values) or len(set(values)) != len(values):
raise TaskCenterError("schedule_scope", "task identifiers are invalid")
return values
class ScheduleStore:
def __init__(self, data_root):
self.data_root = Path(data_root)
self.data_root.mkdir(parents=True, exist_ok=True)
self.path = self.data_root / "dsh-state.sqlite3"
self._archive_stamps = {}
with self._connect() as db:
db.execute("""CREATE TABLE IF NOT EXISTS schedules (
schedule_id TEXT PRIMARY KEY, task_ids TEXT NOT NULL, plan_hashes TEXT NOT NULL,
priority TEXT NOT NULL, not_before TEXT NOT NULL, due_at TEXT, dependencies TEXT NOT NULL,
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)""")
db.execute("""CREATE TABLE IF NOT EXISTS schedule_event_archives (
file TEXT PRIMARY KEY, first_sequence INTEGER NOT NULL, last_sequence INTEGER NOT NULL,
event_count INTEGER NOT NULL, sha256 TEXT NOT NULL)""")
@contextmanager
def _connect(self):
db = sqlite3.connect(self.path, timeout=10, isolation_level=None)
db.row_factory = sqlite3.Row
db.execute("PRAGMA busy_timeout=10000")
db.execute("PRAGMA journal_mode=WAL")
try:
yield db
finally:
db.close()
@staticmethod
def _row(row):
if row is None:
return None
return {"schedule_id": row["schedule_id"], "task_ids": json.loads(row["task_ids"]),
"plan_hashes": json.loads(row["plan_hashes"]), "priority": row["priority"],
"not_before": row["not_before"], "due_at": row["due_at"],
"dependencies": json.loads(row["dependencies"]), "auto_start": bool(row["auto_start"]),
"idle_only": bool(row["idle_only"]), "title": row["title"], "status": row["status"],
"created_utc": row["created_utc"], "updated_utc": row["updated_utc"],
"claimed_utc": row["claimed_utc"], "finished_utc": row["finished_utc"],
"run_id": row["run_id"], "result": json.loads(row["result"]) if row["result"] else None}
def get(self, schedule_id):
with self._connect() as db:
return self._row(db.execute("SELECT * FROM schedules WHERE schedule_id = ?", (schedule_id,)).fetchone())
def list_schedules(self):
with self._connect() as db:
return [self._row(row) for row in db.execute("SELECT * FROM schedules ORDER BY not_before, created_utc").fetchall()]
def _validate_spec(self, spec, plan_hashes):
if not isinstance(spec, dict) or set(spec) - _FIELDS:
raise TaskCenterError("schedule_fields", "schedule contains unsupported fields")
ids = _ids(spec.get("task_ids"))
if not isinstance(spec.get("priority", "normal"), str) or spec.get("priority", "normal") not in _PRIORITY:
raise TaskCenterError("schedule_priority", "schedule priority is invalid")
before = _utc(spec.get("not_before"), required=True)
due = _utc(spec.get("due_at"))
if due and due < before:
raise TaskCenterError("schedule_datetime", "due time cannot precede not-before time")
dependencies = _ids(spec.get("dependencies", []), required=False)
if set(ids) & set(dependencies):
raise TaskCenterError("schedule_dependency", "schedule cannot depend on itself")
if not isinstance(spec.get("auto_start", False), bool) or not isinstance(spec.get("idle_only", True), bool):
raise TaskCenterError("schedule_fields", "schedule switches must be booleans")
title = spec.get("title", "")
if not isinstance(title, str) or len(title) > 200 or "\x00" in title:
raise TaskCenterError("schedule_title", "schedule title is invalid")
if not isinstance(plan_hashes, dict) or set(plan_hashes) != set(ids) or any(
not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value) for value in plan_hashes.values()
):
raise TaskCenterError("schedule_plan", "frozen plan hashes are invalid")
return ids, dict(plan_hashes), spec.get("priority", "normal"), before, due, dependencies, bool(spec.get("auto_start", False)), bool(spec.get("idle_only", True)), title
def _check_cycles(self, db, ids, dependencies):
graph = {}
for stored in db.execute("SELECT * FROM schedules WHERE status IN ('pending', 'claimed')").fetchall():
row = self._row(stored)
for task_id in row["task_ids"]:
graph.setdefault(task_id, set()).update(row["dependencies"])
for task_id in ids:
graph.setdefault(task_id, set()).update(dependencies)
def visit(node, active, seen):
if node in active:
return True
if node in seen:
return False
seen.add(node); active.add(node)
if any(visit(dep, active, seen) for dep in graph.get(node, ())):
return True
active.remove(node)
return False
if any(visit(node, set(), set()) for node in graph):
raise TaskCenterError("schedule_dependency_cycle", "schedule dependencies contain a cycle")
def preview(self, spec, plan_hashes):
"""Normalize a native confirmation draft without saving or granting authority."""
ids, _, priority, before, due, deps, auto_start, idle_only, title = self._validate_spec(spec, plan_hashes)
with self._connect() as db:
self._check_cycles(db, ids, deps)
return {"task_ids": ids, "priority": priority, "not_before": before, "due_at": due,
"dependencies": deps, "auto_start": auto_start, "idle_only": idle_only, "title": title}
def save(self, spec, plan_hashes):
ids, hashes, priority, before, due, deps, auto_start, idle_only, title = self._validate_spec(spec, plan_hashes)
schedule_id = uuid4().hex
stamp = _now().isoformat(timespec="seconds")
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
self._check_cycles(db, ids, deps)
db.execute("INSERT INTO schedules VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL)",
(schedule_id, json.dumps(ids), json.dumps(hashes, sort_keys=True), priority, before, due,
json.dumps(deps), int(auto_start), int(idle_only), title, "pending", stamp, stamp))
db.execute("COMMIT")
return self.get(schedule_id)
def cancel(self, schedule_id):
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT status 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_owned", "claimed or finished schedules cannot be cancelled")
db.execute("UPDATE schedules SET status = 'cancelled', updated_utc = ? WHERE schedule_id = ?", (_now().isoformat(timespec="seconds"), schedule_id))
db.execute("COMMIT")
return self.get(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]
def archive_events(self, *, keep=5000, batch=1000):
from .schedule_audit import archive_events
return archive_events(self, keep=keep, batch=batch)
def audit_status(self, *, keep=5000):
from .schedule_audit import verify_archives
with self._connect() as db:
records = db.execute('SELECT file, sha256 FROM schedule_event_archives').fetchall()
count = db.execute('SELECT COUNT(*) FROM schedule_events').fetchone()[0]
verify_archives(self.data_root / 'dsh' / 'schedule-audit', records, self._archive_stamps)
# Bounded work per refresh. Old evidence is exported, never discarded.
batch = min(keep, 1000)
if count >= keep + batch:
self.archive_events(keep=keep, batch=batch)
with self._connect() as db:
live = db.execute('SELECT COUNT(*) FROM schedule_events').fetchone()[0]
archived = db.execute('SELECT COALESCE(SUM(event_count), 0) FROM schedule_event_archives').fetchone()[0]
return {'status': 'ok', 'live_events': live, 'archived_events': archived, 'retained_limit': keep + batch}
@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 * 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 = ?, 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)
@contextmanager
def execution_lease(self, schedule_id):
"""Hold from before claim until the final receipt, across processes."""
if not isinstance(schedule_id, str) or not _ID.fullmatch(schedule_id):
raise TaskCenterError('schedule_missing', '排期编号无效。')
from ..trial_task_center.task_queue import _lock_file, _os_lock
with _lock_file(self.data_root / 'dsh' / 'schedule-leases' / schedule_id) as handle:
try:
_os_lock(handle, True)
except OSError as error:
raise TaskCenterError('schedule_busy', '排期仍有活动执行,不能对账收尾。') from error
try:
yield
finally:
_os_lock(handle, False)
def reconcile_claim(self, service, schedule_id):
"""Native-confirmed orphan reconciliation; never dispatch or reset a claim."""
from ..trial_task_center.task_queue import assert_task_queue_idle, _queue_lease
with self.execution_lease(schedule_id):
assert_task_queue_idle(self.data_root)
with _queue_lease(self.data_root):
if service.pending_batch_resources():
raise TaskCenterError('schedule_busy', '后台资源尚未释放,请先在任务中心核验和清理。')
with self._connect() as db:
db.execute('BEGIN IMMEDIATE')
row = self._row(db.execute('SELECT * FROM schedules WHERE schedule_id = ?', (schedule_id,)).fetchone())
if not row or row['status'] != 'claimed':
raise TaskCenterError('schedule_status', '只有已领取的失联排期需要对账。')
run = None
if db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='run_journal'").fetchone():
run = db.execute('SELECT * FROM run_journal WHERE run_id = ?', (row['run_id'],)).fetchone()
if run and (run['schedule_id'] != schedule_id or json.loads(run['task_ids']) != row['task_ids']
or json.loads(run['plan_hashes']) != row['plan_hashes']):
raise TaskCenterError('schedule_run_conflict', '运行记录与排期范围不一致,请保留证据人工核对。')
status = run['status'] if run and run['status'] in {'completed', 'failed'} else 'interrupted'
receipt = json.loads(run['result']) if run and run['result'] else None
payload = {'run_id': row['run_id'], 'reconciled': True,
'reason': 'run_receipt' if run else 'claim_without_run', 'receipt': receipt}
stamp = _now().isoformat(timespec='seconds')
db.execute('UPDATE schedules SET status = ?, updated_utc = ?, finished_utc = ?, result = ? WHERE schedule_id = ?',
(status, stamp, stamp, json.dumps(payload, ensure_ascii=False), schedule_id))
self._event(db, schedule_id, stamp, 'result', row['run_id'], {'status': status, **payload})
db.execute('COMMIT')
return self.get(schedule_id)
def finish(self, schedule_id, status, **values):
if status not in {"completed", "failed", "interrupted", "cancelled"}:
raise TaskCenterError("schedule_status", "schedule finish status is invalid")
with self._connect() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT status 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"] != "claimed":
db.execute("ROLLBACK"); raise TaskCenterError("schedule_status", "only a claimed schedule can finish")
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)
def _completed(self, service, task_id):
try:
context = service.task_context(task_id)
progress = context.progress
return context.task.status.value == "completed" and not context.interrupted and bool(progress.queue_complete) and not getattr(progress, "failed_items", 0)
except Exception:
return False
def evaluate(self, service, *, now=None, busy=False):
when = now or _now()
if when.tzinfo is None:
raise TaskCenterError("schedule_datetime", "evaluation time timezone is required")
rows = []
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")
if busy: blockers.append("worker_busy")
try:
for task_id in row["task_ids"]:
if service.task_context(task_id).task.status.value == "paused":
blockers.append("task_paused")
if _plan_hash(service.for_project_task(task_id), task_id) != row["plan_hashes"][task_id]:
blockers.append("plan_changed")
except Exception:
blockers.append("task_unavailable")
try:
from .task_lifecycle import preflight
check = preflight(service, row["task_ids"])
if not check["ready"]:
blockers.append("preflight_blocked")
except Exception:
blockers.append("preflight_unavailable")
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": 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
+7 -3
View File
@@ -27,12 +27,16 @@ def validate_creation_spec(raw):
if not isinstance(rules, list) or len(rules) > 30:
raise TaskCenterError('assistant_task_rules', '一次最多创建 30 条替换规则。')
for row in rules:
if not isinstance(row, dict) or set(row) - {'old_part_number', 'new_part_number', 'target_cell', 'custom_value', 'sync_nc'}:
if not isinstance(row, dict) or set(row) - {'old_part_number', 'new_part_number', 'target_cell', 'custom_value', 'sync_nc', 'enabled'}:
raise TaskCenterError('assistant_task_rule_fields', '替换规则字段无效。')
normalized = {'old_part_number': text(row.get('old_part_number'), 128, True),
'new_part_number': text(row.get('new_part_number'), 128, True),
'target_cell': text(row.get('target_cell', ''), 128),
'sync_nc': row.get('sync_nc', True)}
if 'enabled' in row:
if not isinstance(row['enabled'], bool):
raise TaskCenterError('assistant_task_rule_option', '规则启用状态必须为明确开关。')
normalized['enabled'] = row['enabled']
if 'custom_value' in row:
normalized['custom_value'] = text(row['custom_value'], 500)
if not isinstance(normalized['sync_nc'], bool):
@@ -81,8 +85,8 @@ def create_confirmed_tasks(service, request_id, raw, root, selected_paths):
tasks.append(store.set_copy_part_number_to_value(task.task_id, spec['copy_part_number_to_value']))
if tasks:
for rule in spec['rules']:
mutate_batch_rules(service, tasks[0].task_id, 'add', **rule,
enabled=True, custom_value_enabled='custom_value' in rule)
mutate_batch_rules(service, tasks[0].task_id, 'add', **({'enabled': True} | rule),
custom_value_enabled='custom_value' in rule)
result = {'status': 'created' if tasks else 'existing', 'created_count': len(tasks),
'existing_count': len(existing_ids), 'task_ids': [task.task_id for task in tasks] or existing_ids,
'existing_task_ids': existing_ids, 'rules_count': len(spec['rules']), 'cad_execution_started': False,
+221
View File
@@ -0,0 +1,221 @@
"""Bounded task intents, immutable previews and confirmed task-center mutations."""
from dataclasses import asdict
from hashlib import sha256
import json
import re
from ..trial_task_center.errors import TaskCenterError
from ..trial_task_center.models import TaskStatus
from ..trial_task_center.batch_rules import members, mutate_batch_rules
from ..trial_task_center.rule_validation import validate_mapping_pairs
def _digest(value):
return sha256(json.dumps(value, sort_keys=True, ensure_ascii=False, default=str).encode()).hexdigest()
def _summary(task):
return {'task_id': task.task_id, 'name': task.name, 'status': task.status.value,
'group_id': task.group_id, 'note': task.note[:2000]}
def catalog(service, task_id=None):
result = {'tasks': [_summary(t) for t in service.tasks()][:500], 'limit': 500}
if task_id is not None:
context = _context(service, task_id)
result['detail'] = {**_summary(context.task), 'project': str(context.project.path) if context.project else '',
'rules': [asdict(rule) for rule in context.rules], 'targets_count': len(context.targets),
'copy_part_number_to_value': context.task.copy_part_number_to_value,
'interrupted': context.interrupted, 'phase': context.phase}
return result
def _context(service, task_id):
if not isinstance(task_id, str) or not task_id or len(task_id) > 128:
raise TaskCenterError('assistant_task_id', '请使用任务列表中的真实任务编号。')
return service.task_context(task_id)
def fingerprint(service, ids):
return _digest([asdict(_context(service, key)) for key in ids])
def preflight(service, task_ids, *, allow_completed=False):
from ..trial_task_center.ui.execution_state import execution_state
from ..trial_task_center.task_queue import _plan_hash
if not isinstance(task_ids, list) or not 1 <= len(task_ids) <= 20 or len(set(task_ids)) != len(task_ids):
raise TaskCenterError('assistant_task_scope', '请选择 1 至 20 个不同的真实任务。')
tasks, paths, hashes = [], set(), {}
pending = bool(service.pending_batch_resources())
for task_id in task_ids:
context = _context(service, task_id)
state = execution_state(context)
blockers = []
finished = (allow_completed and context.task.status is TaskStatus.COMPLETED
and context.progress.queue_complete and not context.progress.failed_items and not context.interrupted)
if not state.execute and not finished:
blockers.append(state.message)
if context.phase == 'retry':
blockers.append('存在失败项,请先核对证据并准备失败项重试。')
path = context.project.path if context.project else None
if path is None or not path.is_file():
blockers.append('工程文件不存在或不可访问。')
elif str(path.resolve()).casefold() in paths:
blockers.append('本次范围重复包含同一个工程。')
else:
paths.add(str(path.resolve()).casefold())
count = sum(row.enabled for row in (context.targets if context.task.target_plan_mode else context.rules))
if not count:
blockers.append('没有已启用的替换规则或位号。')
try:
service._execution_rules(task_id)
except TaskCenterError as error:
blockers.append(error.message)
if pending:
blockers.append('上一次执行的后台资源尚未释放。')
hashes[task_id] = _plan_hash(service.for_project_task(task_id), task_id)
tasks.append({**_summary(context.task), 'project': str(path or ''), 'enabled_rules': count,
'phase': context.phase, 'blockers': list(dict.fromkeys(blockers)),
'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 连接、备份与保存核验由正式执行流程完成。'}
def _text(value, limit, required=False):
if not isinstance(value, str) or len(value) > limit or '\x00' in value or (required and not value.strip()):
raise TaskCenterError('assistant_patch', '任务或规则文本无效。')
return value.strip()
def preview(service, raw):
if not isinstance(raw, dict) or set(raw) - {'operation', 'task_id', 'patch'}:
raise TaskCenterError('assistant_fields', '任务操作包含不支持的字段。')
op = raw.get('operation')
if op not in {'select', 'copy', 'update', 'archive'}:
raise TaskCenterError('assistant_operation', '不支持此任务操作。')
context = _context(service, raw.get('task_id'))
if context.task.status is TaskStatus.DELETED:
raise TaskCenterError('assistant_deleted', '任务已归档,请先在回收站恢复。')
patch = raw.get('patch', {})
if not isinstance(patch, dict) or set(patch) - {'name', 'note', 'copy_part_number_to_value', 'rules'} or (patch and op != 'update'):
raise TaskCenterError('assistant_patch', '只支持修改名称、备注、Value 开关和已有料号规则。')
patch = dict(patch)
if op == 'update' and not patch:
raise TaskCenterError('assistant_patch', '请明确需要修改的字段。')
for key, limit in [('name', 120), ('note', 2000)]:
if key in patch:
patch[key] = _text(patch[key], limit, key == 'name')
if 'copy_part_number_to_value' in patch and not isinstance(patch['copy_part_number_to_value'], bool):
raise TaskCenterError('assistant_patch', 'Value 策略必须为明确开关。')
affected = members(service._store, context.task.task_id) if 'rules' in patch else (context.task,)
changes = []
for key in ('name', 'note', 'copy_part_number_to_value'):
if key in patch:
changes.append({'task_id': context.task.task_id, 'field': key,
'before': getattr(context.task, key), 'after': patch[key]})
if 'copy_part_number_to_value' in patch:
if not service.can_edit_value_options(context.task.task_id):
raise TaskCenterError('quick_run_options_locked', '当前任务的 Value 策略已冻结。')
if 'rules' in patch:
rows = patch['rules']
if not isinstance(rows, list) or not 1 <= len(rows) <= 30:
raise TaskCenterError('assistant_patch', '一次可修改 1 至 30 条已有规则。')
for task in affected:
if task.status not in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.FAILED}:
raise TaskCenterError('rules_locked', f'同批任务「{task.name}」已冻结。')
service._editable_rules(task.task_id, lambda: None)
existing = {r.old_part_number.casefold(): r for r in context.rules}
normalized, seen = [], set()
for row in rows:
if not isinstance(row, dict) or set(row) - {'old_part_number', 'new_part_number', 'target_cell', 'custom_value', 'custom_value_enabled', 'sync_nc', 'enabled'}:
raise TaskCenterError('assistant_patch', '规则修改字段无效。')
row = dict(row)
old = _text(row.get('old_part_number'), 128, True).casefold()
if old not in existing or old in seen or len(row) < 2:
raise TaskCenterError('assistant_patch', '只能按唯一旧料号修改已有规则。')
seen.add(old)
row['old_part_number'] = existing[old].old_part_number
for key in ('new_part_number', 'target_cell', 'custom_value'):
if key in row:
row[key] = _text(row[key], 500 if key == 'custom_value' else 128, key == 'new_part_number')
for key in ('sync_nc', 'enabled', 'custom_value_enabled'):
if key in row and not isinstance(row[key], bool):
raise TaskCenterError('assistant_patch', '规则开关必须为布尔值。')
if 'new_part_number' in row and row['new_part_number'] != existing[old].new_part_number:
row.setdefault('target_cell', '')
if 'custom_value' in row:
row.setdefault('custom_value_enabled', True)
for key, value in row.items():
if key != 'old_part_number':
changes.append({'task_id': '同批全部任务', 'field': row['old_part_number'] + '.' + key,
'before': getattr(existing[old], key), 'after': value})
normalized.append(row)
pairs = {r.old_part_number.casefold(): r.new_part_number for r in context.rules}
for row in normalized:
pairs[row['old_part_number'].casefold()] = row.get('new_part_number', pairs[row['old_part_number'].casefold()])
validate_mapping_pairs(pairs.items())
patch['rules'] = normalized
ids = [t.task_id for t in affected]
return {'spec': {'operation': op, 'task_id': context.task.task_id, **({'patch': patch} if patch else {})},
'affected_tasks': [_summary(t) for t in affected], 'changes': changes,
'fingerprint': fingerprint(service, ids)}
def apply_confirmed(service, request_id, plan):
if not isinstance(request_id, str) or not re.fullmatch('[a-f0-9]{32}', request_id):
raise TaskCenterError('assistant_request_id', '任务请求编号无效。')
digest = _digest(plan)
def apply():
store = service._store
with store.transaction():
prior = store.assistant_operation_receipt(request_id)
if prior:
if prior['request_hash'] != digest:
raise TaskCenterError('assistant_request_conflict', '请求编号已用于另一项操作。')
return prior['result'] | {'replayed': True}
current = preview(service, plan['spec'])
if current != plan:
raise TaskCenterError('assistant_stale', '任务配置已变化,请重新生成预览后确认。')
spec = plan['spec']; task_id = spec['task_id']; op = spec['operation']
if op == 'archive':
store.soft_delete_task(task_id)
status = 'archived'
elif op == 'update':
patch = spec['patch']; task = store.get_task(task_id)
if 'name' in patch or 'note' in patch:
store.update_task(task_id, name=patch.get('name', task.name), note=patch.get('note', task.note))
if 'copy_part_number_to_value' in patch:
store.set_copy_part_number_to_value(task_id, patch['copy_part_number_to_value'])
for row in patch.get('rules', []):
rule = next(r for r in service.rules(task_id) if r.old_part_number == row['old_part_number'])
options = {key: getattr(rule, key) for key in ('old_part_number', 'new_part_number', 'enabled',
'target_cell', 'custom_value', 'custom_value_enabled', 'sync_nc')}
options.update(row)
mutate_batch_rules(service, task_id, 'update', rule_id=rule.rule_id, **options)
status = 'updated'
else:
raise TaskCenterError('assistant_operation', '此操作不属于配置写入。')
result = {'status': status, 'task_id': task_id, 'task_ids': [t['task_id'] for t in plan['affected_tasks']],
'cad_execution_started': False}
store.record_assistant_operation(request_id, digest, result)
return result
return service._idle_quick_run_operation('assistant_task_change', plan['spec']['task_id'], apply)
def copy_spec(service, task_id):
context = _context(service, task_id)
if context.legacy:
raise TaskCenterError('assistant_legacy', '历史任务请在任务中心查看后重新创建。')
return {'name': context.task.name[:115] + ' 副本', 'note': context.task.note,
'copy_part_number_to_value': context.task.copy_part_number_to_value,
'rules': [{'old_part_number': r.old_part_number, 'new_part_number': r.new_part_number,
'target_cell': r.target_cell, 'sync_nc': r.sync_nc, 'enabled': r.enabled,
**({'custom_value': r.custom_value} if r.custom_value_enabled else {})} for r in context.rules]}
+177
View File
@@ -0,0 +1,177 @@
"""Read-only tracking of the fixed issue associated with an existing incident."""
from __future__ import annotations
from datetime import datetime, timezone
import json
from pathlib import Path
import re
import urllib.parse
import urllib.request
from .evidence import scrub, write_json
from .git_issues import GitIssuePublisher, NoRedirect
from .issue_credentials import issue_target
_IDENTIFIER = re.compile(r"^[0-9a-f]{24}$")
_MAX_COMMENTS = 20
_MAX_BYTES = 2 * 1024 * 1024
class TicketTracker:
def __init__(self, data_root):
self.data_root = Path(data_root)
self.incidents = self.data_root / "dsh" / "incidents"
self.cache_root = self.data_root / "dsh" / "ticket-cache"
self.config_path = self.data_root / "dsh" / "issue-config.json"
def refresh(self, incident_id: str) -> dict:
if not isinstance(incident_id, str) or not _IDENTIFIER.fullmatch(incident_id):
raise ValueError("invalid_incident_id")
incident_path = self.incidents / incident_id / "incident.json"
local = self._read_json(incident_path)
if not isinstance(local, dict) or local.get("incident_id") != incident_id:
return self._unavailable(incident_id, "incident_unavailable")
ticket = local.get("ticket")
if not isinstance(ticket, dict):
return self._unavailable(incident_id, "ticket_unavailable")
try:
target = issue_target(self.config_path)
except (OSError, ValueError, TypeError):
return self._unavailable(incident_id, "invalid_issue_config")
expected = self._target_url(target, ticket)
if expected is None:
return self._unavailable(incident_id, "invalid_ticket_target")
# Strict local target checks complete before credentials are obtained.
try:
config, auth, source = GitIssuePublisher(self.config_path).connection()
except Exception as error:
return self._unavailable(incident_id, type(error).__name__)
if not auth:
return self._unavailable(incident_id, source)
if self._target_url(config, ticket) != expected:
return self._unavailable(incident_id, "invalid_ticket_target")
try:
owner, repo = config["repository"].split("/", 1)
parsed = urllib.parse.urlsplit(config["server"])
api = f"{parsed.scheme}://{parsed.netloc}/api/v1/repos/{owner}/{repo}/issues/{ticket['number']}"
opener = urllib.request.build_opener(NoRedirect())
issue = self._get(opener, api, auth)
if not isinstance(issue, dict) or not self._remote_matches(issue, incident_id, expected, ticket["number"]):
return self._unavailable(incident_id, "ticket_identity_mismatch")
count = issue.get("comments", 0)
page = max(1, (count - 1) // _MAX_COMMENTS + 1) if type(count) is int and 0 <= count <= 10**7 else 1
comments = self._get(opener, api + "/comments?" + urllib.parse.urlencode({"page": page, "limit": _MAX_COMMENTS}), auth)
if not isinstance(comments, list):
comments = []
comments = [scrub(self._comment(row)) for row in comments[:_MAX_COMMENTS] if isinstance(row, dict)]
now = datetime.now(timezone.utc).isoformat()
result = scrub({"incident_id": incident_id, "number": ticket["number"], "url": expected,
"state": str(issue.get("state", "unknown"))[:32],
"title": str(issue.get("title", ""))[:300], "updated_at": issue.get("updated_at"),
"comments": comments, "status": "synced", "last_sync_at": now, "last_attempt_at": now,
"credential_source": source, "locally_verified": False})
self._save_cache(incident_id, result)
return result
except Exception as error:
return self._unavailable(incident_id, type(error).__name__)
def list_tickets(self) -> list[dict]:
try:
target = issue_target(self.config_path)
except (OSError, ValueError, TypeError):
return []
rows = []
if not self.incidents.is_dir():
return rows
# Discover tickets from the existing incident binding, not cache filenames
# or a caller-provided URL. Listing is entirely local and does not obtain auth.
for directory in sorted(self.incidents.iterdir(), key=lambda value: value.name):
identity = directory.name
if not _IDENTIFIER.fullmatch(identity) or not directory.is_dir() or directory.is_symlink():
continue
incident = self._read_json(directory / "incident.json")
if not isinstance(incident, dict) or incident.get("incident_id") != identity:
continue
ticket = incident.get("ticket")
if not isinstance(ticket, dict):
continue
expected = self._target_url(target, ticket)
if expected is None:
continue
binding = {"incident_id": identity, "number": ticket["number"], "url": expected,
"status": "not_synced", "last_sync_at": None, "locally_verified": False}
value = self._read_json(self.cache_root / f"{identity}.json")
if (not isinstance(value, dict) or value.get("incident_id") != identity
or value.get("number", ticket["number"]) != ticket["number"]
or value.get("url", expected) != expected):
value = {}
rows.append(scrub(binding | value))
if len(rows) >= 100:
break
return rows
def _target_url(self, config: dict, ticket: dict):
number = ticket.get("number")
url = ticket.get("url") or ticket.get("html_url")
if isinstance(number, bool) or not isinstance(number, int) or number <= 0 or number > 2**31:
return None
if not isinstance(url, str):
return None
try:
server = urllib.parse.urlsplit(str(config.get("server", "")))
value = urllib.parse.urlsplit(url)
owner, repo = str(config.get("repository", "")).split("/", 1)
if (server.scheme != "https" or not server.hostname or server.username or server.password
or server.path not in {"", "/"} or server.query or server.fragment
or not all(re.fullmatch(r"[\w.-]+", part) and part not in {".", ".."} for part in (owner, repo))):
return None
expected = f"{server.scheme}://{server.netloc}/{owner}/{repo}/issues/{number}"
if (value.scheme, value.netloc, value.path, value.query, value.fragment, value.username, value.password) != (
server.scheme, server.netloc, f"/{owner}/{repo}/issues/{number}", "", "", None, None):
return None
return expected
except (ValueError, TypeError):
return None
@staticmethod
def _remote_matches(issue, incident_id, expected, number):
return (issue.get("number") == number and issue.get("html_url") == expected
and (f"[DSH:{incident_id}]" in str(issue.get("title", ""))
or f"[DSH:{incident_id}]" in str(issue.get("body", ""))))
@staticmethod
def _comment(row):
return {"id": row.get("id"), "body": str(row.get("body", ""))[:4000],
"created_at": row.get("created_at"), "updated_at": row.get("updated_at"),
"user": {"login": str((row.get("user") or {}).get("login", ""))[:128]}}
@staticmethod
def _get(opener, url, auth):
request = urllib.request.Request(url, headers=auth | {"Accept": "application/json"}, method="GET")
with opener.open(request, timeout=25) as response:
return json.loads(response.read(_MAX_BYTES))
def _unavailable(self, incident_id, error):
cached = self._read_json(self.cache_root / f"{incident_id}.json")
result = dict(cached) if isinstance(cached, dict) else {"incident_id": incident_id}
result.update(status="unavailable", error=error, last_attempt_at=datetime.now(timezone.utc).isoformat())
# Exception text can contain credentials or URLs. Keep only the typed error.
result = scrub(result)
self._save_cache(incident_id, result)
return result
def _save_cache(self, incident_id, value):
self.cache_root.mkdir(parents=True, exist_ok=True)
write_json(self.cache_root / f"{incident_id}.json", value)
@staticmethod
def _read_json(path):
try:
if not path.is_file() or path.is_symlink():
return None
with path.open("rb") as stream:
raw = stream.read(_MAX_BYTES + 1)
return json.loads(raw) if len(raw) <= _MAX_BYTES else None
except (OSError, ValueError, TypeError):
return None
@@ -160,6 +160,17 @@ class TaskStore:
def _initialize_schema(self) -> None:
return self._schema._initialize_schema()
def assistant_operation_receipt(self, request_id):
with self._lock:
row = self._connection.execute('SELECT request_hash, result_json FROM assistant_task_operations WHERE request_id = ?',
(request_id,)).fetchone()
return None if row is None else {'request_hash': row['request_hash'], 'result': json.loads(row['result_json'])}
def record_assistant_operation(self, request_id, request_hash, result):
with self.transaction():
self._connection.execute('INSERT INTO assistant_task_operations VALUES (?, ?, ?)',
(request_id, request_hash, json.dumps(result, ensure_ascii=False)))
def _create_schema_v1(self) -> None:
return self._schema._create_schema_v1()
@@ -84,6 +84,7 @@ def read_task_bundle(store, task_id: str, read_control=None) -> TaskBundle:
row['uid'], row['refdes'], row['old_part_number'], row['old_value']),
bool(row['enabled']), row['new_part_number'], bool(row['custom_value_enabled']),
row['custom_value'], bool(row['sync_nc']),
row['target_cell'],
)
targets = records(
"SELECT * FROM target_plan WHERE task_id = ? ORDER BY project_path, schematic_name, sheet_number, refdes, uid",
@@ -54,6 +54,8 @@ class StoreSchema:
self._store._create_target_plan_schema()
self._store._connection.execute('''CREATE TABLE IF NOT EXISTS assistant_task_creations (
request_id TEXT PRIMARY KEY, request_hash TEXT NOT NULL, result_json TEXT NOT NULL)''')
self._store._connection.execute('''CREATE TABLE IF NOT EXISTS assistant_task_operations (
request_id TEXT PRIMARY KEY, request_hash TEXT NOT NULL, result_json TEXT NOT NULL)''')
def _create_schema_v1(self) -> None:
statements = (
@@ -129,15 +129,17 @@ def _save(path: Path, state: dict) -> None:
def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
queue_id: str | None = None, runtime=None) -> TaskQueueResult:
queue_id: str | None = None, runtime=None, expected_plan_hashes=None, checkpoint_id=None) -> TaskQueueResult:
"""Execute the frozen order; uncertain state stops before the next project."""
if runtime is None and getattr(service, '_supervised', False):
return service._supervise('execute_task_queue', {'task_ids': task_ids, 'queue_id': queue_id}, stop_event=stop_event)
return service._supervise('execute_task_queue', {'task_ids': task_ids, 'queue_id': queue_id,
'expected_plan_hashes': expected_plan_hashes, 'checkpoint_id': checkpoint_id}, stop_event=stop_event)
if runtime is None:
from .batch_runtime import BatchCadRuntime
with BatchCadRuntime(service._logging.root, 'task_queue', stop_event) as owned_runtime:
result = execute_task_queue(service, task_ids, stop_event=stop_event,
queue_id=queue_id, runtime=owned_runtime)
queue_id=queue_id, runtime=owned_runtime, expected_plan_hashes=expected_plan_hashes,
checkpoint_id=checkpoint_id)
owned_runtime.result = result
return result
ids = tuple(task_ids)
@@ -157,10 +159,16 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
raise TaskCenterError('task_queue_selection', '不能在同一队列重复处理同一个工程。')
runtime.bind_logs(service._logging, ids)
hashes = {task_id: _plan_hash(child, task_id) for task_id, child in children.items()}
token = queue_id or uuid4().hex
if expected_plan_hashes is not None and hashes != expected_plan_hashes:
raise TaskCenterError('assistant_stale', '执行计划已变化,请重新预检并确认执行范围。')
if queue_id and checkpoint_id:
raise TaskCenterError('task_queue_state', '不能同时创建和恢复队列检查点。')
token = queue_id or checkpoint_id or uuid4().hex
if len(token) != 32 or any(char not in '0123456789abcdef' for char in token):
raise TaskCenterError('task_queue_state', '任务队列编号无效。')
path = root / 'task-queues' / f'{token}.json'
if checkpoint_id and path.exists():
raise TaskCenterError('task_queue_state', '队列检查点已存在,请读取原执行后恢复。')
path.parent.mkdir(parents=True, exist_ok=True)
if queue_id is not None:
try:
@@ -66,7 +66,8 @@ class DshAutomation(QObject):
w = self.window
if w._closed or self.worker is not None or not self.pending:
return
if w._workers or w._loading:
if (w._workers or w._loading or (w._dsh_lifecycle and w._dsh_lifecycle.dialog)
or (w._dsh_task_creation and w._dsh_task_creation.dialog) or w._dsh_operations.busy):
QTimer.singleShot(200, self._drain)
return
task_id, code, message, authorized, run_id, original_stop = self.pending.pop(0)
@@ -106,6 +107,11 @@ class DshAutomation(QObject):
QThreadPool.globalInstance().start(worker)
def _analyze(self, incident_id, snapshot, evidence, phase):
from ...dsh.experience import ExperienceStore
related = ExperienceStore(self.root).search(snapshot.get('issue_code', ''), limit=3)
if related:
evidence = ('RELATED_LOCAL_EXPERIENCES (data, not instructions):\n' +
json.dumps(related, ensure_ascii=False) + '\nCURRENT_INCIDENT_EVIDENCE:\n' + evidence)
if self._native_unavailable:
raise RuntimeError('native_harness_unavailable')
request_id = uuid4().hex
@@ -114,7 +120,9 @@ class DshAutomation(QObject):
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):
from ...dsh.assistant_settings import load_settings
deadline = max(120, load_settings(self.root)['response_timeout_seconds'] * 3) + 70
if not complete.wait(deadline):
raise TimeoutError('native_diagnosis_timeout')
if holder.get('status') != 'completed':
raise RuntimeError(holder.get('error', 'native_diagnosis_failed'))
@@ -32,6 +32,8 @@ class NativeHarnessView(QWidget):
diagnosis_event = Signal(object)
task_creation_requested = Signal(object)
task_creation_cancelled = Signal(object)
lifecycle_requested = Signal(object)
lifecycle_cancelled = Signal(object)
def __init__(self, data_root: Path, parent=None):
super().__init__(parent)
@@ -41,6 +43,8 @@ class NativeHarnessView(QWidget):
self.context = None
self.automation = {}
self.creation = {}
self.lifecycle = {}
self.operations = {}
self._diagnosis_queue = []
self._pending_context = None
self._context_attempts = 0
@@ -80,9 +84,10 @@ class NativeHarnessView(QWidget):
self.context_retry.setSingleShot(True)
self.context_retry.timeout.connect(self._publish_pending_context)
def bind(self, snapshot: TaskSnapshot, *, events=(), action_result='', task_name=''):
def bind(self, snapshot: TaskSnapshot, *, events=(), action_result='', task_name='', operations=None):
self.operations = dict(operations or {})
self._pending_context = (snapshot, {'events': tuple(events), 'action_result': action_result, 'task_name': task_name,
'automation': dict(self.automation), 'creation': dict(self.creation)})
'automation': dict(self.automation), 'creation': dict(self.creation), 'lifecycle': dict(getattr(self, 'lifecycle', {})), 'operations': dict(self.operations)})
self._context_attempts = 0
self._publish_pending_context()
@@ -108,6 +113,10 @@ class NativeHarnessView(QWidget):
if self.is_running:
self.process.write((json.dumps({'type': 'task_creation_result', **result}, ensure_ascii=False) + '\n').encode('utf8'))
def complete_lifecycle(self, result):
if self.is_running:
self.process.write((json.dumps({'type': 'task_lifecycle_result', **result}, ensure_ascii=False) + '\n').encode('utf8'))
def request_diagnosis(self, request):
if self._started:
self.process.write((json.dumps({'type': 'diagnose', **request}, ensure_ascii=False) + '\n').encode('utf8'))
@@ -142,7 +151,7 @@ class NativeHarnessView(QWidget):
self.process.setProgram(node)
self.process.setArguments([str(root / 'start.mjs')])
self.process.start()
self.timeout.start(60000)
self.timeout.start(120000)
def _reset_output(self):
self._buffer = ''
@@ -156,7 +165,7 @@ class NativeHarnessView(QWidget):
for line in lines:
prefix, _, payload = line.partition(' ')
if prefix not in {'DX_DSH_READY','DX_DSH_DIAGNOSIS','DX_DSH_CREATE_REQUEST',
'DX_DSH_CREATE_CANCEL','DX_DSH_ACTION'}:
'DX_DSH_CREATE_CANCEL','DX_DSH_ACTION','DX_DSH_LIFECYCLE_REQUEST','DX_DSH_LIFECYCLE_CANCEL'}:
continue
try:
data = json.loads(payload)
@@ -184,6 +193,10 @@ class NativeHarnessView(QWidget):
self.task_creation_requested.emit(data)
elif prefix == 'DX_DSH_CREATE_CANCEL':
self.task_creation_cancelled.emit(data)
elif prefix == 'DX_DSH_LIFECYCLE_REQUEST':
self.lifecycle_requested.emit(data)
elif prefix == 'DX_DSH_LIFECYCLE_CANCEL':
self.lifecycle_cancelled.emit(data)
elif prefix == 'DX_DSH_ACTION':
if self.context and data.get('task_id') == self.context['task_id'] and data.get('revision') == self.context['revision']:
self.action_requested.emit(data)
@@ -0,0 +1,442 @@
"""Application-owned operations, persisted planning and native confirmations."""
from __future__ import annotations
from datetime import datetime, timedelta
import json
import re
from uuid import uuid4
from shiboken6 import isValid
from PySide6.QtCore import QObject, QThreadPool, QTimer
from PySide6.QtWidgets import (QApplication, QCheckBox, QComboBox, QDialogButtonBox,
QFormLayout, QLabel, QLineEdit, QPlainTextEdit)
from ...dsh import task_lifecycle as tasks
from ...dsh.run_journal import RunJournal
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, execution_check
from ...dsh.decision_log import DecisionLog
from ..errors import TaskCenterError
from .dsh_task_lifecycle import DshLifecycleDialog
from .workers import ServiceWorker
class DshScheduleDialog(DshLifecycleDialog):
def __init__(self, spec, report, parent):
scope = '\n'.join(f"{t['name']} [{t['task_id']}]\n{t['project']}" for t in report['tasks'])
impact = report.get('impact', {})
scope += '\n\n' + ('器件数量未知,仅有料号映射。' if impact.get('component_count') is None else f"已选中 {impact['component_count']} 个器件。")
for row in impact.get('rows', []):
scope += 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')}"
super().__init__('保存任务排期', scope + '\n\n应用打开且空闲时检查排期;计划变化、未保存编辑、暂停或待核验结果会阻断。', parent)
self.setObjectName('dshScheduleDialog')
form = QFormLayout()
self.title_edit = QLineEdit(spec.get('title', ''), objectName='dshScheduleTitle')
self.time_edit = QLineEdit(spec['not_before'], objectName='dshScheduleTime')
self.due_edit = QLineEdit(spec.get('due_at') or '', objectName='dshScheduleDue')
self.priority = QComboBox(objectName='dshSchedulePriority')
for name, key in [('低', 'low'), ('普通', 'normal'), ('高', 'high'), ('紧急', 'urgent')]:
self.priority.addItem(name, key)
self.priority.setCurrentIndex(self.priority.findData(spec.get('priority', 'normal')))
self.dependencies = QLineEdit(','.join(spec.get('dependencies', [])), objectName='dshScheduleDependencies')
self.auto_start = QCheckBox('授权到时空闲自动执行并保存以上工程(仍检查原有门禁)', objectName='dshScheduleAutoStart')
self.auto_start.setChecked(spec.get('auto_start', False))
for label, widget in [('名称', self.title_edit), ('最早运行时间(含时区)', self.time_edit),
('截止时间(可留空)', self.due_edit), ('优先级', self.priority), ('前置任务编号(逗号分隔)', self.dependencies)]:
form.addRow(label, widget)
self.layout().insertLayout(1, form)
self.layout().insertWidget(2, self.auto_start)
self.resize(820, 700)
self.spec = spec
def values(self):
return {**self.spec, 'title': self.title_edit.text().strip(), 'not_before': self.time_edit.text().strip(),
'due_at': self.due_edit.text().strip() or None, 'priority': self.priority.currentData(),
'dependencies': [x.strip() for x in self.dependencies.text().split(',') if x.strip()],
'auto_start': self.auto_start.isChecked(), 'idle_only': True}
class DshOperationsController(QObject):
def __init__(self, window):
super().__init__(window)
self.window = window
self.root = window.service.layout_settings_path.parent
self.runs = RunJournal(self.root)
self.schedules = ScheduleStore(self.root)
self.experiences = ExperienceStore(self.root)
self.tickets = TicketTracker(self.root)
self.health = HealthStore(self.root)
self.decisions = DecisionLog(self.root)
self.dialog = None
self.worker = None
self.request_id = None
self._observed_execution = None
self.results = {}
self.cache = {'runs': [], 'schedules': [], 'schedule_events': [], 'schedule_audit': {}, 'section_errors': [],
'experiences': [], 'tickets': [], 'decisions': [],
'decision_audit': {'status': 'unknown'},
'health': {'status': 'degraded', 'checks': []}, 'activity': {}}
self.timer = QTimer(self)
self.timer.setInterval(15000)
self.timer.timeout.connect(self.tick)
self._ticks = 0
if QApplication.platformName().casefold() != 'offscreen':
self.timer.start()
QTimer.singleShot(0, self.refresh)
@property
def busy(self):
return bool(self.worker or self.dialog or self.request_id)
def attach(self, view):
view.stopped.connect(self.runtime_stopped)
def context(self):
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}
self.window._bind_dsh_context()
def _respond(self, request_id, **result):
value = {'request_id': request_id, **result}
self.results[request_id] = value
if len(self.results) > 100:
self.results.pop(next(iter(self.results)))
if self.request_id == request_id:
self.request_id = None
self._state(result['status'], result.get('message', ''))
if self.window._dsh_view:
self.window._dsh_view.complete_lifecycle(value)
def _failed(self, request_id, error):
if not isinstance(error, (TaskCenterError, ValueError)):
self.window.service.report_ui_error(error)
self._respond(request_id, status='rejected', message=getattr(error, 'message', '操作未完成,请核对输入或保留日志。'),
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:
self.window._workers.add(worker)
def succeeded(value):
if not isValid(self.window) or self.window._closed or (request_id and self.request_id != request_id):
return
try:
done(value)
except Exception as error:
self._failed(request_id or uuid4().hex, error)
def failed(error):
if not isValid(self.window) or self.window._closed:
return
if request_id:
self._failed(request_id, error)
else:
self._state('unavailable', '监管记录暂不可用,已有执行不受影响。')
def finished():
self.window._workers.discard(worker)
if self.worker is worker:
self.worker = None
if not isValid(self.window) or self.window._closed:
return
self.window._bind_dsh_context()
self.window._update_gates()
if self.window._close_pending:
QTimer.singleShot(0, self.window.close)
worker.signals.succeeded.connect(succeeded); worker.signals.failed.connect(failed)
worker.signals.finished.connect(finished)
self.window._update_gates()
QThreadPool.globalInstance().start(worker)
def _read_decisions(self):
# A corrupt audit chain must fail closed for append/verification without
# making independent history, tickets, health or scheduling unreadable.
try:
rows = self.decisions.list(20)
except ValueError as error:
return [], {'status': 'corrupt', 'code': 'audit_log_corrupt',
'checked': getattr(error, 'checked', 0),
'message': '审计日志损坏,原文件已保留;请导出证据并人工核对。'}
except OSError:
return [], {'status': 'unavailable', 'code': 'audit_log_unavailable',
'message': '审计日志暂不可读,请检查访问权限并保留原文件。'}
return rows, {'status': 'ok', 'code': 'audit_log_verified',
'checked': rows[-1]['sequence'] if rows else 0,
'message': '审计日志完整性校验通过。'}
def _read(self, *, synchronize_tickets=False):
service = self.window.service
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': []}
by_id = {task['task_id']: task for task in value['tasks']}
value['counters'] = {}
for key in ('saved_items', 'failed_items', 'no_match_items'):
counts = [by_id.get(task_id, {}).get(key) for task_id in row['task_ids']]
value['counters'][key] = (sum(counts) if counts and all(
type(count) is int and count >= 0 for count in counts) else None)
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 '') 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, []),
'schedule_audit': observe('schedule_audit', self.schedules.audit_status, {'status': 'unavailable'}),
'experiences': observe('experiences', lambda: self.experiences.refresh()[:20], []),
'tickets': observe('tickets', read_tickets, [])}
decisions, audit = self._read_decisions()
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'
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():
return
def done(value):
self.cache.update(value)
self.window._bind_dsh_context()
self._work(lambda: self._read(synchronize_tickets=synchronize_tickets), done, reserve_lane=False)
def _other_dialog(self):
lifecycle = self.window._dsh_lifecycle
creation = self.window._dsh_task_creation
return bool((lifecycle and lifecycle.request_id) or (creation and creation.request_id))
def tick(self):
if self.window._closed or self.window._workers or self.busy or self._other_dialog():
return
self._ticks += 1
def ready(value):
self.cache.update(value)
self.window._bind_dsh_context()
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.
QTimer.singleShot(0, lambda: self._dispatch(candidate, automatic=True))
self._work(lambda: self._read(synchronize_tickets=self._ticks % 20 == 0), ready)
def _dispatch(self, row, *, automatic, request_id=None):
if not isValid(self.window) or self.window._closed:
return
if self.worker:
# The read result can arrive before that worker's finished signal.
QTimer.singleShot(100, lambda: self._dispatch(row, automatic=automatic, request_id=request_id))
return
if self.window._workers or self.window._closed or self.busy:
return
self.window._ensure_dsh_view()
self.window._dsh_lifecycle.start_schedule(row, automatic=automatic, request_id=request_id)
def request(self, value):
key = value.get('request_id'); spec = value.get('spec')
if not isinstance(key, str) or not re.fullmatch('[a-f0-9]{32}', key):
return
if key in self.results:
if self.window._dsh_view:
self.window._dsh_view.complete_lifecycle(self.results[key])
return
if not isinstance(spec, dict):
self._failed(key, ValueError('invalid operation')); return
op = spec.get('operation')
if op == 'pause':
if set(spec) != {'operation', 'task_ids'}:
self._failed(key, ValueError('invalid pause')); return
self.window._dsh_lifecycle.request({'request_id': key, 'capability': 'execute',
'spec': {'operation': 'pause', 'task_ids': spec['task_ids']}})
return
if op == 'resume':
if set(spec) != {'operation', 'run_id'}:
self._failed(key, ValueError('invalid resume')); return
self.window._dsh_lifecycle.request({'request_id': key, 'capability': 'execute',
'spec': {'operation': 'resume', 'run_id': spec['run_id']}})
return
if self.busy or self.window._workers or self._other_dialog() or self.window._closed:
self._respond(key, status='busy', message='请等待当前操作或确认窗口收尾。'); return
self.request_id = key
self._state('checking')
allowed = {
'refresh': set(), 'history': set(), 'health': set(), 'decisions': set(), 'impact': {'task_ids'}, 'experience': {'issue_code'}, 'tickets': set(),
'refresh_ticket': {'incident_id'}, 'schedule_dialog': {'task_ids'}, 'cancel_schedule': {'schedule_id'},
'run_schedule': {'schedule_id'}, 'reconcile_schedule': {'schedule_id'}, 'open_incident': {'incident_id'},
'schedule': {'task_ids', 'priority', 'not_before', 'due_at', 'dependencies', 'auto_start', 'idle_only', 'title'}}
if op not in allowed or set(spec) - ({'operation'} | allowed[op]):
self._failed(key, ValueError('unknown operation fields')); return
if op in {'refresh', 'history', 'health', 'decisions', 'tickets'}:
def read(value):
self.cache.update(value)
self._respond(key, status='read', **value)
self._work(self._read, read, request_id=key)
elif op == 'impact':
def impact(report):
self.cache['impact'] = report
self._respond(key, status='impact', **report)
self._work(lambda: execution_impact(self.window.service, spec.get('task_ids')), impact, request_id=key)
elif op == 'experience':
def found(rows):
self.cache['experiences'] = rows
self._respond(key, status='experience', experiences=rows)
self._work(lambda: self.experiences.search(spec.get('issue_code', '')), found, request_id=key)
elif op == 'refresh_ticket':
def synced(row):
self.cache['tickets'] = self.tickets.list_tickets()[:20]
self._respond(key, status='ticket', ticket=row)
self._work(lambda: self.tickets.refresh(spec.get('incident_id')), synced, request_id=key)
elif op == 'open_incident':
incident = spec.get('incident_id')
if not isinstance(incident, str) or not re.fullmatch('[a-f0-9]{24}', incident):
self._failed(key, ValueError('invalid incident')); return
path = self.root / 'dsh/incidents' / incident
if not (path / 'incident.json').is_file():
self._failed(key, ValueError('incident unavailable')); return
from PySide6.QtCore import QUrl
from PySide6.QtGui import QDesktopServices
QDesktopServices.openUrl(QUrl.fromLocalFile(str(path)))
self._respond(key, status='opened', incident_id=incident)
elif op in {'schedule', 'schedule_dialog'}:
ids = spec.get('task_ids')
if self.window.plan_panel.has_unsaved_plan(ids if isinstance(ids, list) else ()):
self._failed(key, TaskCenterError('assistant_dirty', '请先保存所选任务的位号计划。')); return
raw = {k: v for k, v in spec.items() if k != 'operation'}
if op == 'schedule_dialog':
raw['not_before'] = (datetime.now().astimezone()+timedelta(hours=1)).isoformat(timespec='seconds')
def prepare():
report = tasks.preflight(self.window.service, ids)
draft = self.schedules.preview(raw, report['plan_hashes'])
for dependency in draft['dependencies']:
self.window.service.get_task(dependency)
return draft, report
self._work(prepare, lambda result: self._schedule_ready(key, *result), request_id=key)
elif op in {'cancel_schedule', 'run_schedule', 'reconcile_schedule'}:
def loaded():
row = self.schedules.get(spec.get('schedule_id'))
if row is None:
raise ValueError('schedule missing')
return row
self._work(loaded, lambda row: self._schedule_action(key, op, row), request_id=key)
def _schedule_ready(self, key, draft, report):
self.cache['impact'] = execution_impact(self.window.service, draft['task_ids'])
self.dialog = DshScheduleDialog(draft, report, self.window)
dialog = self.dialog
self._state('awaiting_confirmation', '请核对排期时间、依赖和自动执行授权。')
def accept():
value = dialog.values(); self.dialog = None; dialog.deleteLater()
if self.window.plan_panel.has_unsaved_plan(value['task_ids']):
self._failed(key, TaskCenterError('assistant_dirty', '存在未保存编辑,请重新确认排期。')); return
self._state('saving', '正在保存已确认排期。')
def save():
current = tasks.preflight(self.window.service, value['task_ids'])
if current['plan_hashes'] != report['plan_hashes'] or current['fingerprint'] != report['fingerprint']:
raise TaskCenterError('assistant_stale', '计划已变化,请重新生成排期预览。')
for dependency in value['dependencies']:
self.window.service.get_task(dependency)
return self.schedules.save(value, report['plan_hashes'])
def saved(row):
self.cache['schedules'] = self.schedules.evaluate(self.window.service)
self._respond(key, status='scheduled', schedule=row, message='排期已保存;仅在主工具打开且门禁通过时运行。')
QTimer.singleShot(0, lambda: self._work(save, saved, request_id=key))
def reject():
self.dialog = None; dialog.deleteLater()
self._respond(key, status='cancelled', message='已取消,未保存排期。')
dialog.accepted.connect(accept); dialog.rejected.connect(reject); dialog.open()
def _schedule_action(self, key, op, row):
if op == 'run_schedule':
self.request_id = None
QTimer.singleShot(0, lambda: self._dispatch(row, automatic=False, request_id=key))
return
reconcile = op == 'reconcile_schedule'
self.dialog = DshLifecycleDialog('核对失联排期' if reconcile else '取消排期',
(row['title'] or row['schedule_id']) + ('\n运行编号:' + str(row.get('run_id') or '未建立') +
'\n仅在没有活动执行且后台资源已释放时,按持久回执收尾。未完成的运行保留供人工核验和恢复。不会启动 CAD 或自动重放。'
if reconcile else '\n只取消尚未领取的排期,不强制结束正在执行的任务。'), self.window)
dialog = self.dialog
def accept():
self.dialog = None; dialog.deleteLater()
self._state('saving', '正在核对失联排期。' if reconcile else '正在取消已确认排期。')
def done(result):
value, rows, events = result
self.cache['schedules'] = rows
self.cache['schedule_events'] = events
self._respond(key, status='schedule_reconciled' if reconcile else 'schedule_cancelled', schedule=value,
message='排期已按持久回执收尾,原运行记录保留,未启动执行。' if reconcile else '排期已取消。')
def action():
value = self.schedules.reconcile_claim(self.window.service, row['schedule_id']) if reconcile else (
self.schedules.cancel(row['schedule_id']))
return value, self.schedules.evaluate(self.window.service), self.schedules.events()
QTimer.singleShot(0, lambda: self._work(action, done, request_id=key))
def reject():
self.dialog = None; dialog.deleteLater(); self._respond(key, status='cancelled', message='未更改排期。')
dialog.accepted.connect(accept); dialog.rejected.connect(reject); dialog.open()
def cancel(self, value):
if value.get('request_id') != self.request_id:
return
if self.dialog:
self.dialog.reject()
elif self.cache['activity'].get('status') == 'checking':
self._respond(self.request_id, status='cancelled', message='已取消读取,未提交变更。')
def runtime_stopped(self):
if self.dialog:
self.dialog.reject()
def close(self):
self.timer.stop()
@@ -3,7 +3,7 @@ from __future__ import annotations
import re
from PySide6.QtCore import QObject, QThreadPool, QTimer
from PySide6.QtCore import QObject, QThreadPool, QTimer, Signal
from PySide6.QtWidgets import QDialogButtonBox, QLabel, QLineEdit, QPlainTextEdit
from ...dsh.task_creation import validate_creation_spec
@@ -23,7 +23,7 @@ class DshTaskCreationDialog(DirectoryTaskDialog):
preview = QPlainTextEdit(objectName='dshTaskDraftPreview')
preview.setReadOnly(True)
preview.setMaximumHeight(150)
rows = [f"{r['old_part_number']} → {r['new_part_number']}" + (f" · 封装 {r['target_cell']}" if r['target_cell'] else '')
rows = [f"{r['old_part_number']} → {r['new_part_number']}" + (' · 已禁用' if not r.get('enabled', True) else '') + (f" · 封装 {r['target_cell']}" if r['target_cell'] else '')
+ (f" · Value {r['custom_value']}" if 'custom_value' in r else '') + (' · 同步 NC' if r['sync_nc'] else ' · 不同步 NC') for r in spec['rules']]
preview.setPlainText((spec['note'] + '\n\n' if spec['note'] else '') +
('替换规则:\n' + '\n'.join(rows) if rows else '暂未填写替换规则,创建后可在任务中心补齐。') +
@@ -37,6 +37,8 @@ class DshTaskCreationDialog(DirectoryTaskDialog):
class DshTaskCreationController(QObject):
completed = Signal(object)
def __init__(self, window, view):
super().__init__(window)
self.window, self.view = window, view
@@ -55,6 +57,7 @@ class DshTaskCreationController(QObject):
def _respond(self, result):
self._state(result['status'], result=result)
self.view.complete_task_creation(result)
self.completed.emit(result)
self.results[result['request_id']] = result
if len(self.results) > 100:
self.results.pop(next(iter(self.results)))
@@ -69,7 +72,9 @@ class DshTaskCreationController(QObject):
return
if self.request_id == request_id:
return
if self.request_id is not None or self.worker is not None or self.window._workers or self.window._closed:
lifecycle = self.window._dsh_lifecycle
if (self.request_id is not None or self.worker is not None or self.window._workers or self.window._closed
or (lifecycle and lifecycle.dialog is not None) or self.window._dsh_operations.busy):
self.view.complete_task_creation({'request_id': request_id, 'status': 'busy',
'message': '任务中心当前正在处理其他操作,请收尾后再创建。'})
return
@@ -126,6 +131,7 @@ class DshTaskCreationController(QObject):
def finished():
self.window._workers.discard(worker)
self.worker = None
self.window._bind_dsh_context()
self.window._update_gates()
if self.window._close_pending:
QTimer.singleShot(0, self.window.close)
@@ -0,0 +1,328 @@
"""Native task previews and existing queue execution for Harness conversations."""
from __future__ import annotations
import re
from uuid import uuid4
from PySide6.QtCore import QObject, QThreadPool, QTimer
from PySide6.QtWidgets import QDialog, QDialogButtonBox, QLabel, QPlainTextEdit, QVBoxLayout
from ...dsh import task_lifecycle as api
from ..errors import TaskCenterError
from ...dsh.execution_runs import execute_confirmed_run
from .workers import ServiceWorker
class DshLifecycleDialog(QDialog):
def __init__(self, title, text, parent):
super().__init__(parent)
self.setWindowTitle('DSH助手 · ' + title)
self.setObjectName('dshLifecyclePreview')
self.resize(740, 550)
layout = QVBoxLayout(self)
layout.addWidget(QLabel(title))
self.preview = QPlainTextEdit(text, objectName='dshLifecycleText')
self.preview.setReadOnly(True)
layout.addWidget(self.preview)
self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText('确认' + title)
self.buttons.accepted.connect(self.accept)
self.buttons.rejected.connect(self.reject)
layout.addWidget(self.buttons)
self.setModal(True)
class DshTaskLifecycleController(QObject):
def __init__(self, window, view):
super().__init__(window)
self.window, self.view = window, view
self.dialog = None
self.request_id = None
self.worker = None
self.results = {}
self.active_ids = ()
self.copy_requests = set()
view.lifecycle_requested.connect(self.request)
view.lifecycle_cancelled.connect(self.cancel)
view.stopped.connect(self.runtime_stopped)
window._dsh_task_creation.completed.connect(self._copied)
def _copied(self, result):
key = result['request_id']
if key in self.copy_requests:
self.copy_requests.discard(key)
if self.request_id is None:
self.request_id = key
self._respond(key, **{k: v for k, v in result.items() if k != 'request_id'})
def _state(self, status, **values):
self.view.lifecycle = {'request_id': self.request_id, 'status': status, **values}
self.window._bind_dsh_context()
def _respond(self, request_id, **result):
result = {'request_id': request_id, **result}
if 'queue_id' in result:
self.window._dsh_last_execution = dict(result)
self.results[request_id] = result
if len(self.results) > 100:
self.results.pop(next(iter(self.results)))
if self.request_id == request_id:
self._state(result['status'], result=result)
self.request_id = None
elif result['status'] in {'busy', 'rejected'}:
self.window._dsh_operations.cache['activity'] = {'status': result['status'],
'message': result.get('message', '当前操作尚未收尾,请稍后重试。')}
self.window._bind_dsh_context()
self.view.complete_lifecycle(result)
def _failed(self, request_id, error):
if not isinstance(error, TaskCenterError):
self.window.service.report_ui_error(error)
self._respond(request_id, status='rejected' if isinstance(error, TaskCenterError) else 'failed',
message=getattr(error, 'message', '操作未完成,请核对任务中心日志。'), code=getattr(error, 'code', 'assistant_error'))
def _work(self, operation, done, *, executing=False):
worker = ServiceWorker(operation)
self.worker = worker
self.window._workers.add(worker)
request_id = self.request_id
def succeeded(result):
if self.request_id != request_id or self.window._closed:
return
try:
done(result)
except Exception as error:
failed(error)
worker.signals.succeeded.connect(succeeded)
def failed(error):
if executing:
self.window._finish_run()
self.active_ids = ()
self.window._show_error(error, owner_task_id=self._execution_owner)
self.window._metadata_changed(None)
self._failed(request_id, error)
def finished():
if self.worker is worker:
self.worker = None
self.window._workers.discard(worker)
self.window._bind_dsh_context()
self.window._update_gates()
if self.window._close_pending:
QTimer.singleShot(0, self.window.close)
worker.signals.failed.connect(failed)
worker.signals.finished.connect(finished)
self.window._update_gates()
QThreadPool.globalInstance().start(worker)
def request(self, value):
request_id = value.get('request_id')
if not isinstance(request_id, str) or not re.fullmatch('[a-f0-9]{32}', request_id):
return
if request_id in self.results:
self.view.complete_lifecycle(self.results[request_id]); return
if self.request_id == request_id:
return
spec = value.get('spec', {})
capability = value.get('capability')
if capability == 'operations':
self.window._dsh_operations.request(value)
return
# Pause must be available during an execution. It can never select a different run.
if capability == 'execute' and isinstance(spec, dict) and spec.get('operation') == 'pause':
ids = spec.get('task_ids')
owner = self.window._active_quick_run_task_id
live = self.window._dsh_live_run
published = tuple(live.get('task_ids', ())) if live.get('active') else ()
allowed = self.active_ids or published or ((owner,) if owner else ())
if (set(spec) != {'operation', 'task_ids'} or not isinstance(ids, list) or not ids
or len(ids) != len(set(ids)) or set(ids) != set(allowed)
or not owner or self.window._batch_stop is None):
self._respond(request_id, status='rejected', message='没有与所选范围一致的活动执行。'); return
self.window._pause_queue()
self._respond(request_id, status='pause_requested', task_ids=list(allowed),
message='已请求安全暂停,当前项收尾后才会停止。尚未声称已暂停。')
return
creation = self.window._dsh_task_creation
if (self.request_id or self.worker or self.window._workers or self.window._closed
or (creation and creation.request_id) or self.window._dsh_operations.busy):
self._respond(request_id, status='busy', message='请等待当前操作或确认窗口收尾。'); return
self.request_id = request_id
self._state('checking')
if capability == 'execute' and isinstance(spec, dict) and spec.get('operation') == 'resume':
if set(spec) != {'operation', 'run_id'}:
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'] 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]))
return
if capability == 'catalog' and isinstance(spec, dict) and not set(spec) - {'task_id'}:
self._work(lambda: api.catalog(self.window.service, spec.get('task_id')),
lambda result: self._respond(request_id, status='read', **result))
elif capability in {'preflight', 'execute'}:
if not isinstance(spec, dict) or set(spec) - ({'task_ids', 'operation'} if capability == 'execute' else {'task_ids'}) or (capability == 'execute' and spec.get('operation') != 'start'):
self._failed(request_id, TaskCenterError('assistant_fields', '执行请求字段无效。')); return
ids = spec.get('task_ids')
if self.window.plan_panel.has_unsaved_plan(ids if isinstance(ids, list) else ()):
self._failed(request_id, TaskCenterError('assistant_dirty', '所选任务有未保存位号计划,请先保存。')); return
self._work(lambda: api.preflight(self.window.service, ids),
lambda report: self._preflight_ready(request_id, capability, ids, report))
elif capability == 'manage':
self._work(lambda: api.preview(self.window.service, spec), lambda plan: self._plan_ready(request_id, plan))
else:
self._failed(request_id, TaskCenterError('assistant_capability', '未开放此能力。'))
def _show(self, title, text, accepted):
self._state('awaiting_confirmation', title=title, preview=text)
self.dialog = DshLifecycleDialog(title, text, self.window)
dialog = self.dialog
request_id = self.request_id
def yes():
self.dialog = None
dialog.deleteLater()
# A read worker's finished signal can arrive after its result signal.
QTimer.singleShot(0, accepted)
def no():
self.dialog = None
dialog.deleteLater()
self._respond(request_id, status='cancelled', message='用户已取消,未提交变更或执行。')
dialog.accepted.connect(yes); dialog.rejected.connect(no)
dialog.open()
def _plan_ready(self, request_id, plan):
spec = plan['spec']; op = spec['operation']; task_id = spec['task_id']
if op == 'select':
self.window.open_task(task_id)
self._respond(request_id, status='selected', task_id=task_id)
return
if op == 'copy':
# Project scope and configuration preview use the existing creation controller.
try:
draft = api.copy_spec(self.window.service, task_id)
except Exception as error:
self._failed(request_id, error); return
self._state('awaiting_confirmation', title='复制任务:请选择新工程')
def launch():
if self.request_id != request_id:
return
creation = self.window._dsh_task_creation
self.copy_requests.add(request_id)
self.request_id = None
creation.request({'request_id': request_id, 'spec': draft})
QTimer.singleShot(0, launch)
return
text = '\n'.join(f"{t['name']} [{t['task_id']}]" for t in plan['affected_tasks'])
labels = {'name': '名称', 'note': '备注', 'copy_part_number_to_value': '料号复制到 Value'}
for change in plan['changes']:
text += f"\n\n{labels.get(change['field'], change['field'])}:{change['before']} → {change['after']}"
if op == 'archive':
text += '\n\n移入回收站,保留执行证据;不永久删除,不修改工程。'
else:
text += '\n\n仅写入任务配置,不执行 CAD。同批规则变更会应用到以上全部任务。'
def apply():
if self.request_id != request_id:
return
if self.window._workers or self.window._closed or self.window.plan_panel.has_unsaved_plan([t['task_id'] for t in plan['affected_tasks']]):
self._failed(request_id, TaskCenterError('assistant_busy', '任务正在处理或有未保存计划,请重新确认。')); return
self._state('applying')
def done(result):
self.window._metadata_changed(None)
self._respond(request_id, **result)
self._work(lambda: api.apply_confirmed(self.window.service, request_id, plan), done)
self._show('归档任务' if op == 'archive' else '修改任务', text, apply)
def start_schedule(self, row, *, automatic=False, request_id=None):
if self.request_id or self.worker or self.window._workers or self.window._closed:
return
request_id = request_id or uuid4().hex
self.request_id = request_id
self._state('checking')
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['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],
schedule=pair[0], automatic=automatic))
def _preflight_ready(self, request_id, capability, ids, report, *, resume=None, schedule=None, automatic=False):
self.window._dsh_operations.cache['impact'] = report.get('impact', {})
if capability == 'preflight' or not report['ready']:
self._respond(request_id, status='preflight' if capability == 'preflight' else 'blocked', **report)
return
text = '\n\n'.join(f"{t['name']} [{t['task_id']}]\n工程:{t['project']}\n启用规则/位号:{t['enabled_rules']}" for t in report['tasks'])
text += '\n\n将按以上顺序执行/继续既有队列,可能替换并保存工程。保留已有备份、核验与中断门禁。\n' + report['message']
impact = report.get('impact', {})
text += '\n\n执行影响:' + ('器件数量未知,仅有料号映射,执行时按实际命中核验。' if impact.get('component_count') is None else f"已保存计划选中 {impact['component_count']} 个器件。")
for row in impact.get('rows', [])[:100]:
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
if self.worker is not None and not self.active_ids:
QTimer.singleShot(100, start)
return
if self.window._workers or self.window._closed or self.window.plan_panel.has_unsaved_plan(ids):
self._failed(request_id, TaskCenterError('assistant_busy', '任务状态已变化,请重新预检。')); return
run_id = resume['run_id'] if resume else uuid4().hex
self._state('executing', task_ids=ids, run_id=run_id)
self.active_ids = tuple(ids)
self._execution_owner = ids[0]
self.window._dsh_authorized_tasks.update(ids)
self.window._begin_run(ids[0])
self.window._dsh_run_id = run_id
self.window._dsh_live_run.update(run_id=run_id, task_ids=list(ids))
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, automatic=automatic)
def done(result):
self.window._finish_run(); self.active_ids = ()
self.window._metadata_changed(None)
for task in result['tasks']:
if task['state'] in {'failed', 'blocked'} or task['failed_items']:
self.window._queue_dsh_incident(task['task_id'], 'execution_failed', task['message'])
self._respond(request_id, **result)
QTimer.singleShot(0, self.window._dsh_operations.refresh)
self._work(operation, done, executing=True)
if automatic:
QTimer.singleShot(0, start)
else:
self._show('执行所选任务', text, start)
def cancel(self, value):
self.window._dsh_operations.cancel(value)
if value.get('request_id') in self.copy_requests:
self.window._dsh_task_creation.cancel(value)
return
if value.get('request_id') != self.request_id:
return
if self.worker is not None:
# A service worker has no safe cancellation point. Do not clear its
# request or claim cancellation while an update or queue is already
# committing; the worker must publish the real receipt.
if not self.dialog and not self.active_ids:
# A read-only preflight/catalog can be abandoned safely. The
# later result must be ignored so it cannot open a confirmation
# dialog after the model has cancelled its request.
if self.view.lifecycle.get('status') == 'checking':
self._respond(self.request_id, status='cancelled', message='已取消,未提交变更。')
return
if self.dialog:
self.dialog.reject()
elif self.active_ids and self.window._batch_stop:
if value.get('reason') != 'conversation_cancelled':
self.window._pause_queue()
else:
self._respond(self.request_id, status='cancelled', message='请求已取消,未提交变更或执行。')
def runtime_stopped(self):
if self.request_id:
self.cancel({'request_id': self.request_id})
@@ -40,9 +40,13 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._dsh = DshSupervisor(DshServiceAdapter(service).execute)
self._dsh_view = None
self._dsh_task_creation = None
self._dsh_lifecycle = None
self._dsh_operations = None
self._dsh_stopping = False
self._dsh_automation = None
self._dsh_run_id = 'observation'
self._dsh_live_run = {'active': False}
self._dsh_last_execution = {}
self._dsh_run_stop = None
self._dsh_authorized_tasks = set()
self.task_center_action = QAction('任务中心', self)
@@ -172,6 +176,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
saved = self._layout_settings.value(f'single_project/{name}')
if saved is not None:
widget.restoreState(saved)
from .dsh_operations import DshOperationsController
self._dsh_operations = DshOperationsController(self)
self._resource_status.changed.connect(self._update_gates)
self._resource_status.refresh()
self._refresh_task_list()
@@ -297,7 +303,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
if self._close_saving:
event.ignore()
return
if self._workers:
if self._workers or (self._dsh_operations and self._dsh_operations.worker):
self._close_pending = True
self.plan_panel.cancel_operation()
self._pause_queue()
@@ -305,6 +311,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
event.ignore()
return
self._close_pending = False
if self._dsh_operations and self._dsh_operations.dialog:
self._dsh_operations.dialog.reject()
if self.plan_panel.has_unsaved_plans():
choice = self._close_plan_confirmer()
if choice == 'cancel':
@@ -339,6 +347,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._layout_settings.setValue(f'single_project/{name}', widget.saveState())
self._layout_settings.setValue('tasks/sort', self.task_list.sort.currentData())
self._closed = True
if self._dsh_operations:
self._dsh_operations.close()
self._context_query.close()
self._task_query.close()
self._feedback_query.close()
@@ -661,6 +671,13 @@ class TrialTaskCenterWindow(MaterialMainWindow):
return
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
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
self._dsh_authorized_tasks.add(context.task.task_id)
@@ -670,8 +687,22 @@ class TrialTaskCenterWindow(MaterialMainWindow):
task_id = context.task.task_id
self._begin_run(task_id)
stop = self._batch_stop
self._run_async(lambda: self.service.execute_quick_run_queue(task_id, expected_item=expected, stop_event=stop),
self._show_batch_result, self.run_panel.quick_run_button, expected_task_id=task_id)
run_id = self._dsh_run_id
def execute():
from ...dsh.execution_runs import execute_confirmed_run
current = self.service.task_context(task_id); p = current.progress
actual = (str(p.next_project_path), p.next_old_part_number, p.next_new_part_number,
'part_label' if current.task.copy_part_number_to_value else 'preserve')
if actual != expected:
raise TaskCenterError('assistant_stale', '确认时的执行范围或 Value 策略已变化。')
return execute_confirmed_run(self.service, self.service.layout_settings_path.parent,
[task_id], report, stop, run_id)
def done(receipt):
from ..batch import BatchRunResult
self._show_batch_result(BatchRunResult(self.service.quick_run_progress(task_id), receipt['paused']))
self._dsh_last_execution = receipt
self._bind_dsh_context()
self._run_async(execute, done, self.run_panel.quick_run_button, expected_task_id=task_id)
def _execute_project_tasks(self):
if not self.task_list.queue_button.isEnabled():
@@ -684,11 +715,24 @@ class TrialTaskCenterWindow(MaterialMainWindow):
if self.plan_panel.has_unsaved_plan(ids):
self._set_operator_message('本批任务有未保存计划,请先逐个保存。', 'warning')
return
report = None
if len(ids) <= 20:
from ...dsh import task_lifecycle as lifecycle
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
self._dsh_authorized_tasks.update(ids)
from ..task_queue import execute_task_queue
self._begin_run(ids[0])
self._dsh_live_run['task_ids'] = list(ids)
run_id = token or self._dsh_run_id
self._dsh_run_id = run_id
self._dsh_live_run['run_id'] = run_id
stop = self._batch_stop
def done(result):
if result.paused:
@@ -707,8 +751,28 @@ class TrialTaskCenterWindow(MaterialMainWindow):
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')
self._run_async(lambda: execute_task_queue(self.service, ids, stop_event=stop, queue_id=token), done,
self.task_list.queue_button)
def execute():
if report is None:
return execute_task_queue(self.service, ids, stop_event=stop, queue_id=token)
from ...dsh.execution_runs import execute_confirmed_run
from ..task_queue import TaskQueueEntry, TaskQueueResult
resume = None
if token:
resume = self._dsh_operations.runs.inspect(self.service, token)
receipt = execute_confirmed_run(self.service, self.service.layout_settings_path.parent,
list(ids), report, stop, run_id, resume=resume)
result = TaskQueueResult(receipt['queue_id'], tuple(TaskQueueEntry(**entry) for entry in receipt['entries']),
receipt['paused'])
return result, receipt
def completed(value):
if isinstance(value, tuple):
result, receipt = value
done(result)
self._dsh_last_execution = receipt
self._bind_dsh_context()
else:
done(value)
self._run_async(execute, completed, self.task_list.queue_button)
def _begin_run(self, task_id):
from uuid import uuid4
@@ -719,6 +783,9 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._run_started_at = time.time()
self._quick_run_elapsed.start()
self._quick_run_timer.start()
self._dsh_live_run = {'active': True, 'run_id': self._dsh_run_id, 'task_id': task_id,
'task_ids': [task_id], 'pause_requested': False, 'stage': 'starting',
'elapsed_seconds': 0, 'saved_items': 0, 'failed_items': 0, 'no_match_items': 0}
self.run_panel.busy_indicator.show()
self._message = ''
@@ -734,12 +801,18 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._batch_stop = None
self.run_panel.busy_indicator.hide()
self.run_panel.stop_queue_button.setText('完成当前项后暂停')
if self._dsh_live_run.get('active'):
self._dsh_last_execution = dict(self._dsh_live_run)
self._dsh_live_run = {'active': False}
self._bind_dsh_context()
def _pause_queue(self):
if self._batch_stop:
self._batch_stop.set()
self.run_panel.stop_queue_button.setText('等待当前项收尾…')
self._set_operator_message('已请求暂停;当前项安全收尾后停止。', 'warning')
self._dsh_live_run['pause_requested'] = True
self._bind_dsh_context()
self._update_gates()
def _force_batch_stop(self):
@@ -895,6 +968,10 @@ class TrialTaskCenterWindow(MaterialMainWindow):
+ '逐项执行原生 Replace Part + Library Wins,保留每行 Value/NC 策略;创建备份并自动保存、关闭、重开核验。'
+ '\n默认在受监督的私有桌面执行,结束后释放自有 CAD 会话;主桌面可继续查看其他文件。请确保待处理工程未在其他 CAD 会话中打开。'
+ '\n确认后连续执行,暂停等待当前步骤收尾;状态不确定时停止。')
impact = getattr(self, '_dsh_confirmation_impact', {})
if impact:
text += '\n\n执行影响:' + ('器件数量未知,执行时按实际命中核验。' if impact['component_count'] is None else f"已选中 {impact['component_count']} 个器件。")
text += '\n' + '\n'.join(f"{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')}" for row in impact['rows'])
return QMessageBox.question(self, '确认执行当前任务' if scope == 'current' else '确认顺序执行本批任务', text,
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No) == QMessageBox.StandardButton.Yes
@@ -902,16 +979,32 @@ class TrialTaskCenterWindow(MaterialMainWindow):
def _update_quick_run_elapsed(self):
if self._batch_stop is not None and not self._feedback_query.busy:
task_id, started = self._active_quick_run_task_id, self._run_started_at
def received(value):
run_id = self._dsh_run_id
elapsed = self._quick_run_elapsed.elapsed() // 1000
pause_requested = bool(self._batch_stop and self._batch_stop.is_set())
scope = list(self._dsh_live_run.get('task_ids') or [task_id])
def read(control):
from ...dsh.live_state import read_live_run
feedback = self.service.execution_feedback(task_id, started_after=started, read_control=control)
live = read_live_run(self.service, feedback, elapsed=elapsed,
pause_requested=pause_requested, run_id=run_id, task_ids=scope)
return feedback, live
def received(pair):
if self._batch_stop is None or run_id != self._dsh_run_id:
return
value, live = pair
self._active_quick_run_task_id = value.task_id or task_id
name = next((t.name for t in self._tasks if t.task_id == value.task_id), value.task_id or '')
self.run_panel.execution_status.setText(format_feedback(
value, name, self._quick_run_elapsed.elapsed() // 1000,
bool(self._batch_stop and self._batch_stop.is_set())))
live['message'] = self.run_panel.execution_status.text()
self._dsh_live_run = live
self._bind_dsh_context()
if self._batch_stop and self._batch_stop.control_error:
self._set_operator_message(self._batch_stop.control_error, 'warning')
self._update_gates()
self._feedback_query.request(lambda control: self.service.execution_feedback(task_id, started_after=started, read_control=control),
self._feedback_query.request(read,
received, lambda _: None, cancellable=True)
if self.run_panel.toggle_log_button.isChecked():
self._refresh_live_task_log()
@@ -948,19 +1041,36 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self.run_panel.operator_band.style().polish(self.run_panel.operator_band)
def _open_dsh(self):
try:
self._ensure_dsh_view()
self.content_stack.setCurrentWidget(self._dsh_view)
if self._dsh_automation is not None and self._dsh_automation.latest:
self._dsh_automation._publish_context()
except Exception as error:
# QAction slots do not surface exceptions visibly in a frozen Qt
# app. Route lazy import/WebEngine failures through the operator
# error path instead of making the click appear to do nothing.
try:
self.service.report_ui_error(error)
except Exception:
pass
self._show_error(TaskCenterError(
'dsh_startup', 'DSH助手启动失败,请检查发布包中的运行时和 Node.js。'))
def _ensure_dsh_view(self):
if self._dsh_view is None:
self._dsh_view = self._create_dsh_view()
from .dsh_task_creation import DshTaskCreationController
self._dsh_task_creation = DshTaskCreationController(self, self._dsh_view)
from .dsh_task_lifecycle import DshTaskLifecycleController
self._dsh_lifecycle = DshTaskLifecycleController(self, self._dsh_view)
self._dsh_operations.attach(self._dsh_view)
self._dsh_view.action_requested.connect(self._handle_dsh_action)
self.content_stack.addWidget(self._dsh_view)
self._bind_dsh_context()
self._dsh_view.start()
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.
@@ -974,17 +1084,23 @@ class TrialTaskCenterWindow(MaterialMainWindow):
status = getattr(getattr(self, '_context', None), 'task', None)
status_value = getattr(getattr(status, 'status', None), 'value', 'observe')
progress = getattr(self._context, 'progress', None)
live = dict(self._dsh_live_run)
if live.get('active'):
live.update(task_id=self._active_quick_run_task_id or task_id,
elapsed_seconds=self._quick_run_elapsed.elapsed() // 1000)
operations = {**(self._dsh_operations.context() if self._dsh_operations else {}),
'live_run': live, 'last_execution': dict(self._dsh_last_execution)}
counts = {key: getattr(progress, source, 0) for key, source in (
('completed', 'completed_items'), ('total', 'total_items'), ('saved_items', 'saved_items'),
('failed_items', 'failed_items'), ('no_match_items', 'no_match_items'))}
latest = next((r['snapshot'] for r in reversed(self._dsh.history)
if r['snapshot']['task_id'] == task_id), {})
self._dsh_view.bind(TaskSnapshot(task_id, str(status_value),
self._dsh_view.bind(TaskSnapshot(task_id, 'running' if live.get('active') and live.get('task_id') == task_id else str(status_value),
progress=counts,
rules_count=len(getattr(self._context, 'rules', ())),
issue=latest.get('issue', ''), issue_code=latest.get('issue_code', '')),
events=[r['classification'] for r in self._dsh.history if r['snapshot']['task_id'] == task_id],
action_result=action_result, task_name=getattr(status, 'name', ''))
action_result=action_result, task_name=getattr(status, 'name', ''), operations=operations)
def _handle_dsh_action(self, request):
view = self._dsh_view
@@ -1041,7 +1157,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
def _run_async(self, operation, callback, button=None, *, expected_task_id=None,
retain_result=False, operation_area='', **_unused):
if (self._workers or self._closed or (self._dsh_task_creation is not None and self._dsh_task_creation.dialog is not None)
):
or (self._dsh_lifecycle is not None and self._dsh_lifecycle.dialog is not None)
or (self._dsh_operations is not None and self._dsh_operations.dialog is not None)):
return
worker = ServiceWorker(operation)
self._workers.add(worker)
@@ -1094,6 +1211,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._workers.discard(worker)
if not isValid(self) or self._closed:
return
self._bind_dsh_context()
self._resource_status.refresh()
self.plan_panel.finish_operation(error=operation_error)
self._close_saving = False
@@ -4,6 +4,7 @@ import json
import re
ERROR_TEXT = {
"dsh_startup": "DSH助手启动失败,请检查发布包中的运行时和 Node.js。",
'user_forced_stop': '操作已强制中断,结果待核验。',
'application_shutdown_failed': '业务结果已保留,但应用收尾异常。',
"batch_resources_pending": "后台资源尚未确认释放,请使用“重新清理资源”后再开始下一批。",
@@ -10,6 +10,7 @@ from PySide6.QtGui import QAction,QKeySequence
from PySide6.QtWidgets import (QDialog, QDialogButtonBox, QFileDialog, QHBoxLayout, QLabel,
QLineEdit, QListWidget, QListWidgetItem, QMessageBox, QPushButton,
QVBoxLayout, QWidget, QToolButton, QMenu)
from shiboken6 import isValid
from .detail_windows import BomReportDialog
from .target_table import TargetTable
@@ -669,6 +670,11 @@ class ProjectPlanPanel(QWidget):
self.report_toggle.setChecked(False)
def _restore_bom_report(self, scope):
# Qt may reclaim an owned control while the parent window is already
# closing. Cleanup still needs to release the in-memory preview, but
# must not call into a dead C++ wrapper.
if not isValid(self) or not isValid(self.report_toggle):
return
machine = self._bom_imports.get(scope)
state = machine.state if machine is not None else BomImportState()
self.last_bom_report = state.report
@@ -1 +1 @@
VERSION = "1.1.4-beta.4"
VERSION = "1.2.1"