fix(dsh): keep AI waits off task execution and adapt main capabilities
Core regression / Python 3.12 core, intervention UI and release configuration (push) Failing after 21s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python 3.12 core, intervention UI and release configuration (pull_request) Failing after 21s
Core regression / JavaScript syntax (pull_request) Successful in 3s

This commit is contained in:
阿白叔 committed 2026-11-05 17:15:29 +08:00
1 parent 3ecb6fa276
commit eba935e710
24 files changed
+929 -128

No files matched your search

+8
View File
@@ -42,6 +42,13 @@ def _limit(limit: object) -> int:
def _policy(task, row) -> tuple[str, str | None]:
if bool(getattr(row, "custom_value_enabled", False)):
return "custom", str(getattr(row, "custom_value", ""))
mode = getattr(row, "value_mode", "inherit")
if mode == "custom":
return "custom", str(getattr(row, "custom_value", ""))
if mode == "part_number":
return mode, row.new_part_number
if mode in {"preserve", "part_label"}:
return mode, None
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.
@@ -72,6 +79,7 @@ def _target_row(task, task_id: str, row) -> dict[str, Any]:
"old_value": target.old_value,
"proposed_value": proposed,
"value_policy": value_policy,
"value_mode": row.value_mode,
"target_cell": target_cell,
"target_cell_policy": target_cell,
"sync_nc": sync_nc,
+80 -69
View File
@@ -1,6 +1,7 @@
"""Durable automatic diagnosis, bounded repair, verification and escalation."""
from __future__ import annotations
from contextlib import nullcontext
from hashlib import sha256
from itertools import islice
import json
@@ -127,10 +128,11 @@ def decision(reply):
class IncidentRunner:
def __init__(self, data_root, service, analyze, publish, notify=lambda row: None):
def __init__(self, data_root, service, analyze, publish, notify=lambda row: None, *, action_scope=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)
self.action_scope = action_scope or (lambda action: nullcontext())
def _record_decision(self, record, evidence, *, outcome, human_takeover=False):
refs = []
@@ -215,6 +217,8 @@ class IncidentRunner:
snapshot['trigger'] = trigger
return snapshot, context
snapshot, context = take_snapshot()
# Keep the original immutable evidence across the asynchronous model wait.
context_fingerprint = repr(context)
record['task_name'] = snapshot.get('task_name', task_id)
budget_id = sha256(f'{task_id}:{run_id}'.encode()).hexdigest()[:24]
budget_path = self.data_root / 'dsh' / 'retry-budget' / (budget_id + '.json')
@@ -275,35 +279,42 @@ class IncidentRunner:
update('cleaning_resources')
cleanup = {}
try:
pending = tuple(self.service.pending_batch_resources())
cleanup['resources_before'] = _bounded_details(pending)
if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()):
raise ValueError('cleanup_gate_changed')
if pending:
update('cleaning_resources', cleanup_attempts=1)
if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()):
raise ValueError('cleanup_gate_changed')
record['action'] = 'cleanup_resources'
write_json(state_path, record)
if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()):
record['action'] = 'none'
raise ValueError('cleanup_gate_changed')
cleanup['returned_resources'] = _bounded_details(self.service.cleanup_batch_resources())
with self.action_scope('cleanup_resources'):
try:
pending = tuple(self.service.pending_batch_resources())
cleanup['resources_before'] = _bounded_details(pending)
if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()):
raise ValueError('cleanup_gate_changed')
if pending:
update('cleaning_resources', cleanup_attempts=1)
if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()):
raise ValueError('cleanup_gate_changed')
record['action'] = 'cleanup_resources'
write_json(state_path, record)
if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()):
record['action'] = 'none'
raise ValueError('cleanup_gate_changed')
cleanup['returned_resources'] = _bounded_details(self.service.cleanup_batch_resources())
except Exception as error:
cleanup['error'] = scrub({'type': type(error).__name__, 'code': getattr(error, 'code', ''), 'detail': str(error)[:1000]})
if 'resources_before' not in cleanup:
cleanup['resources_before_error'] = cleanup['error']
evidence.event('cleanup_failed', **cleanup['error'])
try:
remaining = tuple(self.service.pending_batch_resources())
cleanup['remaining_resources'] = _bounded_details(remaining)
cleanup['remaining_resources_observed'] = True
released = not remaining
except Exception as error:
cleanup['verification_error'] = scrub({'type': type(error).__name__, 'detail': str(error)[:1000]})
cleanup['remaining_resources'], released = None, None
cleanup['remaining_resources_observed'] = False
evidence.event('cleanup_verification_unavailable', **cleanup['verification_error'])
except Exception as error:
cleanup['error'] = scrub({'type': type(error).__name__, 'code': getattr(error, 'code', ''), 'detail': str(error)[:1000]})
if 'resources_before' not in cleanup:
cleanup['resources_before_error'] = cleanup['error']
evidence.event('cleanup_failed', **cleanup['error'])
try:
remaining = tuple(self.service.pending_batch_resources())
cleanup['remaining_resources'] = _bounded_details(remaining)
cleanup['remaining_resources_observed'] = True
released = not remaining
except Exception as error:
cleanup['verification_error'] = scrub({'type': type(error).__name__, 'detail': str(error)[:1000]})
cleanup['remaining_resources'], released = None, None
cleanup['error'] = scrub({'type': type(error).__name__, 'detail': str(error)[:1000]})
cleanup.setdefault('remaining_resources', None)
cleanup['remaining_resources_observed'] = False
evidence.event('cleanup_verification_unavailable', **cleanup['verification_error'])
released = None
incomplete = 'error' in cleanup or 'verification_error' in cleanup
performed = record['action'] == 'cleanup_resources'
verification_status = 'incomplete' if incomplete else ('observed_cleared' if released and not performed else 'complete')
@@ -331,48 +342,48 @@ class IncidentRunner:
if cancel_event.is_set():
return cancelled()
if safe:
# Consume before entering a service mutation. A crash or changed error
# code must never buy another replay of the same authorized run.
budget_path.parent.mkdir(parents=True, exist_ok=True)
try:
with budget_path.open('x', encoding='utf8') as stream:
json.dump({'incident_id': incident_id, 'task_id': task_id, 'run_id': run_id, 'attempts': 1}, stream)
stream.flush()
os.fsync(stream.fileno())
except FileExistsError:
safe = False
gates['retry_budget_available'] = False
write_json(evidence.directory / 'gates.json', gates)
if safe:
update('retrying', attempts=1)
try:
# Re-read at the actual mutation boundary; the model never supplies parameters.
current = self.service.task_context(task_id)
if (current.interrupted or current.phase != 'retry' or stop_event.is_set() or cancel_event.is_set()
or (execution_enabled is not None and not execution_enabled.is_set())):
raise ValueError('retry_gate_changed')
record['action'] = 'retry_failed'
write_json(state_path, record)
if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()):
record['action'] = 'none'
raise ValueError('retry_gate_changed')
self.service.prepare_failed_quick_run(task_id)
prepared = self.service.task_context(task_id)
p = prepared.progress
expected = (str(p.next_project_path), p.next_old_part_number, p.next_new_part_number,
'part_label' if prepared.task.copy_part_number_to_value else 'preserve')
if (prepared.interrupted or not p.next_project_path or stop_event.is_set() or cancel_event.is_set()
or (execution_enabled is not None and not execution_enabled.is_set())):
raise ValueError('retry_execution_gate_changed')
outcome = self.service.execute_quick_run_queue(task_id, expected_item=expected, stop_event=stop_event)
update('verifying')
current = self.service.task_context(task_id)
p = current.progress
verification = {'queue_complete': p.queue_complete, 'failed_items': p.failed_items,
'saved_items': p.saved_items, 'completed_items': p.completed_items,
'interrupted': current.interrupted, 'paused': outcome.paused}
write_json(evidence.directory / 'verification.json', verification)
record['verification'] = verification
with self.action_scope('retry_failed'):
# Re-read at the actual mutation boundary; the model never supplies parameters.
current = self.service.task_context(task_id)
if (repr(current) != context_fingerprint or current.interrupted or current.phase != 'retry' or stop_event.is_set() or cancel_event.is_set()
or (execution_enabled is not None and not execution_enabled.is_set())):
raise ValueError('retry_gate_changed')
# Consume before entering a service mutation. A crash or changed error
# code must never buy another replay of the same authorized run.
budget_path.parent.mkdir(parents=True, exist_ok=True)
try:
with budget_path.open('x', encoding='utf8') as stream:
json.dump({'incident_id': incident_id, 'task_id': task_id, 'run_id': run_id, 'attempts': 1}, stream)
stream.flush()
os.fsync(stream.fileno())
except FileExistsError:
gates['retry_budget_available'] = False
write_json(evidence.directory / 'gates.json', gates)
raise ValueError('retry_budget_spent')
update('retrying', attempts=1)
record['action'] = 'retry_failed'
write_json(state_path, record)
if cancel_event.is_set() or stop_event.is_set() or (execution_enabled is not None and not execution_enabled.is_set()):
record['action'] = 'none'
raise ValueError('retry_gate_changed')
self.service.prepare_failed_quick_run(task_id)
prepared = self.service.task_context(task_id)
p = prepared.progress
expected = (str(p.next_project_path), p.next_old_part_number, p.next_new_part_number,
'part_label' if prepared.task.copy_part_number_to_value else 'preserve')
if (prepared.interrupted or not p.next_project_path or stop_event.is_set() or cancel_event.is_set()
or (execution_enabled is not None and not execution_enabled.is_set())):
raise ValueError('retry_execution_gate_changed')
outcome = self.service.execute_quick_run_queue(task_id, expected_item=expected, stop_event=stop_event)
update('verifying')
current = self.service.task_context(task_id)
p = current.progress
verification = {'queue_complete': p.queue_complete, 'failed_items': p.failed_items,
'saved_items': p.saved_items, 'completed_items': p.completed_items,
'interrupted': current.interrupted, 'paused': outcome.paused}
write_json(evidence.directory / 'verification.json', verification)
record['verification'] = verification
if cancel_event.is_set():
return cancelled()
if p.queue_complete and not p.failed_items and not current.interrupted and not outcome.paused:
+7 -1
View File
@@ -27,6 +27,10 @@ def catalog(service, task_id=None):
'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}
if context.task.target_plan_mode:
from .impact import execution_impact
report = execution_impact(service, [task_id])
result['detail'].update(targets=report['rows'], omitted_targets=report['omitted_row_count'])
return result
@@ -99,11 +103,13 @@ 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'}:
if op not in {'select', 'copy', 'update', 'archive', 'import_bom'}:
raise TaskCenterError('assistant_operation', '不支持此任务操作。')
context = _context(service, raw.get('task_id'))
if context.task.status is TaskStatus.DELETED:
raise TaskCenterError('assistant_deleted', '任务已归档,请先在回收站恢复。')
if op == 'import_bom':
service._editable_rules(context.task.task_id, lambda: None)
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 开关和已有料号规则。')