from dataclasses import replace import json import pytest from dx_productivity.dsh.impact import execution_impact from dx_productivity.trial_task_center.errors import TaskCenterError from dx_productivity.trial_task_center.logging_setup import configure_logging from dx_productivity.trial_task_center.service import TaskCenterService from dx_productivity.trial_task_center.store import TaskStore from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow from dx_productivity.trial_task_center.task_queue import _plan_hash @pytest.fixture def setup(tmp_path): store = TaskStore(tmp_path / 'tasks.db') service = TaskCenterService(store, configure_logging(tmp_path / 'data')) paths = [] for name in ('exact', 'mapping'): path = tmp_path / name / 'board.prj' path.parent.mkdir() path.write_text('project fixture', encoding='utf-8') paths.append(path) tasks = [] for index, path in enumerate(paths): task = store.create_task(path.parent.name) project = store.sync_projects(task.task_id, path.parent, (path,))[0] store.set_project_selected(project.project_id, True) tasks.append(store.bind_project_task(task.task_id, project.project_id, f'g{index}', 0)) targets = tuple(ComponentTarget(paths[0], 'MAIN', '1', f'u{i}', f'R{i}', 'OLD', f'V{i}') for i in range(1, 4)) store.record_target_inventory(tasks[0].task_id, targets) rows = (TargetPlanRow(targets[0], True, 'NEW', target_cell='CELL-X'), TargetPlanRow(targets[1], True, 'NEW', True, 'CUSTOM', False), TargetPlanRow(targets[2], False, 'NEW2')) store.replace_target_plan(tasks[0].task_id, rows) store.add_rule(tasks[1].task_id, 'M-OLD', 'M-NEW', target_cell='CELL-M') store.add_rule(tasks[1].task_id, 'OFF', 'OFF-NEW', enabled=False) store.set_copy_part_number_to_value(tasks[1].task_id, True) yield service, store, tasks, paths store.close() def test_exact_target_plan_reports_saved_identities_policies_and_enabled_count(setup): service, store, tasks, paths = setup task_id = tasks[0].task_id before = store._connection.total_changes project_before = paths[0].read_bytes() result = execution_impact(service, [task_id]) assert result['coverage'] == 'exact' assert result['component_count'] == result['known_component_count'] == 2 assert result['enabled_scope'] == 2 assert result['total_rows'] == result['returned_rows'] == 3 first, custom, disabled = result['rows'] assert (first['sheet'], first['schematic_name'], first['refdes'], first['uid']) == ('1', 'MAIN', 'R1', 'u1') assert first['project'].casefold() == str(paths[0]).casefold() assert (first['old_part_number'], first['new_part_number']) == ('OLD', 'NEW') assert first['old_value'] == 'V1' assert first['value_policy'] == 'preserve' assert first['proposed_value'] is None assert first['target_cell'] == first['target_cell_policy'] == 'CELL-X' assert first['nc_policy'] == 'sync' assert custom['value_policy'] == 'custom' and custom['proposed_value'] == 'CUSTOM' assert custom['nc_policy'] == 'preserve' assert disabled['enabled'] is False and disabled['component_count'] == 0 assert result['plan_hashes'][task_id] == _plan_hash(service.for_project_task(task_id), task_id) assert result['cad_connection_checked'] is False assert store._connection.total_changes == before assert paths[0].read_bytes() == project_before json.dumps(result) def test_mapping_mode_never_invents_component_count_or_matches(setup): service, _, tasks, _ = setup result = execution_impact(service, [tasks[1].task_id]) assert result['coverage'] == 'mapping_only' assert result['component_count'] is None assert result['known_component_count'] == 0 assert result['enabled_scope'] == 1 assert result['total_rows'] == 2 row = result['rows'][0] assert row['component_count'] is None assert row['mapping_scope'] == {'old_part_number': 'M-OLD', 'new_part_number': 'M-NEW'} assert row['value_policy'] == 'part_label' assert row['old_value'] is row['proposed_value'] is None assert row['uid'] is row['refdes'] is row['sheet'] is None assert row['target_cell_policy'] == 'CELL-M' def test_pending_bom_preflight_reports_requested_scope_without_claiming_real_uids(setup, tmp_path): from dx_productivity.trial_task_center.bom_plan import write_bom_template from dx_productivity.dsh.task_lifecycle import preflight service, _, tasks, paths = setup task_id = tasks[1].task_id source = write_bom_template(tmp_path / 'pending.xlsx', ({ 'project_path': str(paths[1]), 'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': 'R1,R2', 'enabled': True, },)) report = service.import_bom_drafts(task_id, (source,)) assert report.deferred impact = execution_impact(service, [task_id]) assert impact['coverage'] == 'pending_bom' assert impact['component_count'] is None assert impact['enabled_scope'] == 2 assert impact['rows'][0]['uid'] is None assert impact['rows'][0]['requested_refdes'] == ['R1', 'R2'] preview = preflight(service, [task_id]) assert preview['ready'], preview assert preview['tasks'][0]['enabled_rules'] == 2 assert preview['tasks'][0]['verification_pending'] is True def test_copy_label_target_value_is_unknown_and_custom_override_stays_known(setup): service, store, tasks, _ = setup store.set_copy_part_number_to_value(tasks[0].task_id, True) result = execution_impact(service, [tasks[0].task_id]) assert result['rows'][0]['value_policy'] == 'part_label' assert result['rows'][0]['proposed_value'] is None assert result['rows'][1]['value_policy'] == 'custom' assert result['rows'][1]['proposed_value'] == 'CUSTOM' def test_limit_applies_globally_but_hash_and_totals_cover_omitted_scope(setup): service, store, tasks, _ = setup ids = [task.task_id for task in tasks] report = execution_impact(service, ids, limit=1) assert report['coverage'] == 'mixed' and report['component_count'] is None assert report['known_component_count'] == 2 assert report['enabled_scope'] == 3 assert report['truncated'] is True assert report['total_rows'] == 5 and report['returned_rows'] == 1 assert report['omitted_row_count'] == 4 assert report['tasks'][1]['returned_rows'] == 0 assert report['tasks'][1]['omitted_row_count'] == 2 assert report['full_fingerprint'] == execution_impact(service, ids)['full_fingerprint'] assert report['fingerprint'] == execution_impact(service, ids)['fingerprint'] rows = store.list_target_plan(ids[0]) store.replace_target_plan(ids[0], rows[:2] + (replace(rows[2], new_part_number='CHANGED'),)) changed = execution_impact(service, ids, limit=1) assert changed['rows'] == report['rows'] assert changed['full_fingerprint'] != report['full_fingerprint'] assert changed['plan_hashes'] != report['plan_hashes'] def test_empty_saved_target_plan_is_exact_zero_without_mapping_fallback(setup): service, store, tasks, _ = setup task_id = tasks[1].task_id store.record_target_inventory(task_id, ()) result = execution_impact(service, [task_id]) assert result['coverage'] == 'exact' assert result['component_count'] == 0 and result['rows'] == [] @pytest.mark.parametrize('task_ids', [(), [], 't1', ['t1', 't1'], [['x']], [None], [''], ['x' * 129], ['x'] * 21]) def test_invalid_scope_is_rejected_before_service_access(task_ids): with pytest.raises(TaskCenterError) as caught: execution_impact(object(), task_ids) assert caught.value.code == 'assistant_task_scope' @pytest.mark.parametrize('limit', [0, -1, True, 1.1, '1', 101, None]) def test_limit_is_strict_and_bounded_before_service_access(limit): with pytest.raises(TaskCenterError) as caught: execution_impact(object(), ['t1'], limit=limit) assert caught.value.code == 'assistant_impact_limit' def test_valid_unknown_task_id_retains_service_not_found_error(setup): service, _, _, _ = setup with pytest.raises(TaskCenterError) as caught: execution_impact(service, ['missing']) assert caught.value.code == 'unknown_task' def test_saved_plan_hash_errors_are_not_replaced_with_synthetic_hashes(setup, monkeypatch): service, _, tasks, _ = setup def fail(_task_id): raise TaskCenterError('controlled_read_error', 'cannot read frozen plan') monkeypatch.setattr(service, 'for_project_task', fail) with pytest.raises(TaskCenterError) as caught: execution_impact(service, [tasks[0].task_id]) assert caught.value.code == 'controlled_read_error' @pytest.mark.parametrize('task_default', [False, True]) @pytest.mark.parametrize('mode', ['inherit', 'preserve', 'part_label', 'part_number', 'custom']) def test_per_item_value_policy_matches_saved_execution_mode(setup, task_default, mode): service, store, tasks, _ = setup task_id = tasks[0].task_id rows = store.list_target_plan(task_id) item = replace(rows[0], value_mode=mode, custom_value_enabled=False, custom_value='CUSTOM') store.replace_target_plan(task_id, (item, *rows[1:])) store.set_copy_part_number_to_value(task_id, task_default) result = execution_impact(service, [task_id])['rows'][0] effective = ('part_label' if task_default else 'preserve') if mode == 'inherit' else mode assert result['value_mode'] == mode assert result['value_policy'] == effective assert result['proposed_value'] == {'preserve': None, 'part_label': None, 'part_number': 'NEW', 'custom': 'CUSTOM'}[effective] def test_catalog_exposes_bounded_saved_item_value_policies(setup): from dx_productivity.dsh.task_lifecycle import catalog service, store, tasks, paths = setup task_id = tasks[1].task_id targets = tuple(ComponentTarget(paths[1], 'MAIN', '1', f'uid{i}', f'R{i}', 'OLD', 'ORIGINAL') for i in range(105)) store.record_target_inventory(task_id, targets) store.replace_target_plan(task_id, tuple(TargetPlanRow(target, True, 'NEW', value_mode='part_number') for target in targets)) detail = catalog(service, task_id)['detail'] assert detail['targets_count'] == 105 assert len(detail['targets']) == 100 and detail['omitted_targets'] == 5 assert detail['targets'][0]['value_mode'] == 'part_number' assert detail['targets'][0]['proposed_value'] == 'NEW' assert detail['targets'][0]['uid'] == 'uid0'