feat(dsh): harden health decisions and issue transport

This commit is contained in:
阿白叔 committed 2026-10-31 09:50:35 +08:00
1 parent 736b582bc1
commit eee4e6bde9
18 files changed
+592 -11

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
import json
import pytest
from dx_productivity.dsh.decision_log import DecisionLog
def _row(incident='a' * 24, outcome='pending_issue'):
return {'incident_id': incident, 'trigger': 'execution_failed', 'evidence_refs': ['dsh/incidents/x/gates.json'],
'gates': {'execution_authorized': True, 'retry_budget_available': False},
'candidate_action': 'none', 'authorized_scope': {'task_ids': ['task-1']}, 'outcome': outcome,
'human_takeover': False}
def test_decision_log_is_hash_linked_and_survives_restart(tmp_path):
store = DecisionLog(tmp_path)
first = store.append(_row())
second = DecisionLog(tmp_path).append(_row('b' * 24, 'resolved'))
assert first['sequence'] == 1
assert second['previous_hash'] == first['record_hash']
assert DecisionLog(tmp_path).verify()['valid'] is True
assert [row['sequence'] for row in DecisionLog(tmp_path).list()] == [1, 2]
def test_decision_log_detects_tampering_and_bounds_text(tmp_path):
store = DecisionLog(tmp_path)
store.append(_row())
path = tmp_path / 'dsh' / 'decisions.jsonl'
raw = path.read_text(encoding='utf8').replace('execution_failed', 'x' * 5000)
path.write_text(raw, encoding='utf8')
assert DecisionLog(tmp_path).verify()['valid'] is False
with pytest.raises(ValueError, match='incident_id'):
store.append(_row('bad'))
+42
View File
@@ -0,0 +1,42 @@
import json
from pathlib import Path
from dx_productivity.dsh.health import HealthStore
class _Service:
_workers = set()
def test_health_snapshot_reports_unconfigured_provider_and_local_stores(tmp_path, monkeypatch):
monkeypatch.delenv('DSH_API_BASE', raising=False)
value = HealthStore(tmp_path).snapshot(_Service())
checks = {row['name']: row for row in value['checks']}
assert value['status'] == 'degraded'
assert checks['provider']['status'] == 'degraded'
assert checks['provider']['code'] == 'provider_unconfigured'
assert checks['stores']['status'] == 'ok'
def test_health_snapshot_marks_active_worker_and_static_issue_token(tmp_path, monkeypatch):
class Busy(_Service):
_workers = {object()}
provider = tmp_path / 'dsh' / 'provider.json'
provider.parent.mkdir(parents=True)
provider.write_text(json.dumps({'base_url': 'https://example.test/v1', 'default_model': 'm'}), encoding='utf8')
monkeypatch.setattr('dx_productivity.dsh.health.load_bootstrap', lambda: {'token': 'secret', 'username': 'u', 'scopes': ['write:issue'], 'server': 'https://git.test', 'repository': 'o/r'})
value = HealthStore(tmp_path).snapshot(Busy())
checks = {row['name']: row for row in value['checks']}
assert checks['execution']['status'] == 'degraded'
assert checks['execution']['code'] == 'worker_active'
assert checks['issue_credentials']['code'] == 'credential_rotation_required'
assert 'secret' not in json.dumps(value)
def test_health_snapshot_reports_stale_ticket_cache(tmp_path):
cache = tmp_path / 'dsh' / 'ticket-cache'
cache.mkdir(parents=True)
value = HealthStore(tmp_path).snapshot(_Service())
checks = {row['name']: row for row in value['checks']}
assert checks['tickets']['status'] == 'ok'
+3
View File
@@ -53,6 +53,9 @@ def test_verified_repair_runs_once_and_duplicate_does_not_repeat(tmp_path):
assert second['incident_id'] == first['incident_id']
assert service.calls == ['prepare', 'execute']
assert first['verification']['failed_items'] == 0
decisions = (tmp_path / 'dsh' / 'decisions.jsonl').read_text(encoding='utf8').splitlines()
assert decisions
assert json.loads(decisions[-1])['incident_id'] == first['incident_id']
def test_uncertain_results_never_replay_even_when_model_requests_retry(tmp_path):
+46
View File
@@ -0,0 +1,46 @@
import json
from dx_productivity.dsh.issue_transport import IssueTransport
TARGET = {'server': 'https://git.test', 'repository': 'owner/repo'}
def test_transport_uses_short_lived_broker_credential_without_caching_token(tmp_path, monkeypatch):
config = tmp_path / 'issue-config.json'
config.write_text(json.dumps({**TARGET, 'broker_url': 'https://broker.test/exchange', 'instance_id': 'machine-1'}), encoding='utf8')
monkeypatch.setattr('dx_productivity.dsh.issue_transport._post_broker', lambda *args, **kwargs: {'token': 'short-secret', 'expires_in': 120})
value = IssueTransport(config).credentials(TARGET)
assert value['source'] == 'broker'
assert value['headers']['Authorization'] == 'token short-secret'
assert value['rotation_required'] is False
cache = list(tmp_path.rglob('*'))
assert all('short-secret' not in p.read_text(encoding='utf8', errors='ignore') for p in cache if p.is_file())
def test_transport_marks_bootstrap_fallback_for_rotation(tmp_path, monkeypatch):
config = tmp_path / 'issue-config.json'
config.write_text(json.dumps(TARGET), encoding='utf8')
monkeypatch.setattr('dx_productivity.dsh.issue_transport.load_bootstrap', lambda: {**TARGET, 'token': 'static-secret', 'username': 'u', 'scopes': ['write:issue']})
value = IssueTransport(config).credentials(TARGET)
assert value['source'] == 'prefilled_issue_token'
assert value['rotation_required'] is True
def test_transport_rejects_target_before_broker_or_credentials(tmp_path, monkeypatch):
config = tmp_path / 'issue-config.json'
config.write_text(json.dumps({**TARGET, 'broker_url': 'https://broker.test/exchange'}), encoding='utf8')
monkeypatch.setattr('dx_productivity.dsh.issue_transport._post_broker', lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('network called')))
value = IssueTransport(config).credentials({'server': 'https://evil.test', 'repository': 'owner/repo'})
assert value['source'] == 'invalid_target'
assert 'headers' not in value
def test_git_publisher_connection_prefers_broker_transport(tmp_path, monkeypatch):
from dx_productivity.dsh.git_issues import GitIssuePublisher
config = tmp_path / 'issue-config.json'
config.write_text(json.dumps({**TARGET, 'broker_url': 'https://broker.test/exchange'}), encoding='utf8')
monkeypatch.setattr('dx_productivity.dsh.issue_transport._post_broker', lambda *args, **kwargs: {'token': 'ephemeral', 'expires_in': 60})
_, headers, source = GitIssuePublisher(config).connection()
assert headers == {'Authorization': 'token ephemeral'}
assert source == 'broker'
+12
View File
@@ -68,6 +68,18 @@ def test_history_read_busy_state_is_published_and_rejection_is_visible(ui, monke
assert view.operations['busy'] is False
def test_operations_context_publishes_health_and_decision_timeline(ui, monkeypatch, qtbot):
view = setup_view(ui, monkeypatch)
controller = ui.window._dsh_operations
controller.decisions.append({'incident_id': 'a' * 24, 'trigger': 'worker_error',
'evidence_refs': [], 'gates': {}, 'candidate_action': 'none',
'authorized_scope': {}, 'outcome': 'pending_issue'})
controller.refresh()
qtbot.waitUntil(lambda: controller.worker is None, timeout=5000)
assert 'health' in view.operations and isinstance(view.operations['health']['checks'], list)
assert view.operations['decisions'][0]['incident_id'] == 'a' * 24
def test_stopping_generation_does_not_request_pause_of_confirmed_task(ui, monkeypatch):
view = setup_view(ui, monkeypatch); ctl=ui.window._dsh_lifecycle
task_id=ui.tasks[0].task_id; ui.window._begin_run(task_id)