from copy import deepcopy from types import SimpleNamespace import pytest from app.modules.work_assistant.personnel_profile import ( DETAIL_SECTIONS, normalize_scope, resolve, ) def candidate(): value={section:[] for section in DETAIL_SECTIONS} value['findings']=[dict(key='fit',status='attention',headline='尚未达到职责要求',finding='任务未完成。',action='',basis=[{'excerpt_id':'e1'}])] value['duties']=[dict(topic='归档',record='已提交',assessment='待复核',action='',basis=[{'excerpt_id':'e1'}])] return value def test_missing_duties_does_not_discard_work_or_invent_a_role_assessment(): original=candidate() original['directions']=[{'topic':'完成报告修订','record':'本人反馈已修订','activity_id':'e2','basis':[{'excerpt_id':'e2'}]}] before=deepcopy(original) normalized=normalize_scope(original,False) assert normalized['duties']==original['duties'] assert normalized['findings']==original['findings'] assert normalized['directions']==original['directions'] assert original==before assert normalize_scope(original,True)==original def test_numeric_business_task_id_is_resolved_to_the_same_original_task(): value=candidate() value['progress']=[dict(task_id='13934',basis=[{'excerpt_id':'e2'}])] excerpts={'e1':{'evidence_id':'task-13934','quote':'原任务要求'},'e2':{'evidence_id':'feedback-7','quote':'已提交初稿'}} result=resolve(value,excerpts) assert result['progress'][0]['task_id']=='task-13934' assert {ref['evidence_id'] for ref in result['progress'][0]['basis']}=={'task-13934','feedback-7'} value['progress'][0]['task_id']='99999' with pytest.raises(ValueError,match=r'progress\[0\].*关联事项片段不存在'): resolve(value,excerpts) def test_copied_link_field_and_whitespace_typo_do_not_change_claims_or_citations(): value=candidate() value['development']=[dict(topic='报告复核',record='已修订',assessment='建议复核同类报告',action='',activity_id='e2',**{'basi s':[{'excerpt_id':'e2'}]})] result=normalize_scope(value,True) assert result['development'][0]==dict(topic='报告复核',record='已修订',assessment='建议复核同类报告',action='',basis=[{'excerpt_id':'e2'}]) def test_large_profile_reserves_context_for_output_without_removing_material(monkeypatch): from app.modules.work_assistant import model_gateway,model_capacity from app.modules.work_assistant.model_dispatch import reserved_turn monkeypatch.setattr(model_gateway,'get_settings',lambda:SimpleNamespace(direct_llm_api_key='test',work_assistant_model_control_url='')) monkeypatch.setattr(model_gateway,'_model_client',lambda:None) monkeypatch.setattr(model_capacity,'request_tokens',lambda messages,output,client:27919+128) seen={} def complete(instruction,content,schema,**kwargs): seen.update(kwargs);seen['content']=content return {'ok':True} monkeypatch.setattr(model_gateway,'_complete_json',complete) token=reserved_turn.set({}) payload={'evidence':['完整原文']} try: assert model_gateway.complete_json('核对',payload,{},max_tokens=5500,fit_context=True)=={'ok':True} assert seen['max_tokens']==4593 assert seen['content'] is payload model_gateway.complete_json('核对',payload,{},max_tokens=5500) assert seen['max_tokens']==5500 finally:reserved_turn.reset(token) def test_invalid_link_reaches_targeted_repair_instead_of_crashing_again(): from app.modules.work_assistant.personnel_profile import ProfileRequest,review_profile,KEYS,material entry=ProfileRequest(person_id='1',name='测试',department_id='1',department='测试部',posts='工程师',begin='2026-11-01',end='2026-11-18',coverage=[],limits=[],evidence=[ dict(id='task-7',kind='task',subject='报告修订',actor_id='',at='',relation='requirement',content='修订报告。'), dict(id='feedback-8',kind='feedback',subject='报告修订',actor_id='1',at='',relation='self',content='已修订报告。')]) value={section:[] for section in DETAIL_SECTIONS} value['findings']=[dict(key=key,status='review_required' if key=='assignment' else 'insufficient',headline='建议承担报告修订',finding='本期报告已修订。',action='',basis=[{'excerpt_id':'e2'}]) for key in KEYS] value['directions']=[dict(topic='报告修订',record='已修订报告',assessment='修订已反馈',action='',basis=[{'excerpt_id':'e2'}],activity_id='e99999')] class RepairReached(Exception):pass def invoke(instruction,payload,schema,**kwargs): if 'repair_sections' in payload: assert payload['repair_sections']==['directions'] assert payload['repair_slots']=={'directions':[0]} raise RepairReached() return deepcopy(value) with pytest.raises(RepairReached):review_profile(entry,invoke=invoke) def test_headline_keeps_the_recorded_action_without_adding_initiative(): value=candidate() value['findings']=[dict(key='attitude',headline='主动推进客户拜访',finding='本人反馈协调了客户拜访。',basis=[{'excerpt_id':'e1'}])] excerpts={'e1':{'evidence_id':'feedback-1','quote':'协调了客户拜访。'}} result=resolve(value,excerpts) assert result['findings'][0]['headline']=='推进客户拜访' assert result['findings'][0]['finding']==value['findings'][0]['finding'] excerpts['e1']['quote']='主动协调了客户拜访。' assert resolve(value,excerpts)['findings'][0]['headline']=='主动推进客户拜访' value['findings'][0]['headline']='主动性强' excerpts['e1']['quote']='协调了客户拜访。' assert resolve(value,excerpts)['findings'][0]['headline']=='主动性强' def test_recent_repair_preserves_the_actual_stage_and_specific_error(monkeypatch): from app.modules.work_assistant import personnel_profile as profile entry=profile.ProfileRequest(person_id='1',name='测试',department_id='1',department='测试部',posts='工程师',begin='2026-11-01',end='2026-11-18',coverage=[],limits=[],evidence=[ dict(id='feedback-8',kind='feedback',subject='报告修订',actor_id='1',at='',relation='self',content='已梳理问题并开始部分修改,待资料确认,预计明日完成初稿。')]) value={section:[] for section in DETAIL_SECTIONS} value['findings']=[dict(key=key,status='review_required' if key=='assignment' else 'insufficient',headline='报告修订',finding='已完成整改。',action='',basis=[{'excerpt_id':'e1'}]) for key in profile.KEYS] problem='recent:原文仅开始部分修改,不能写已完成整改。' def reject(entry, resolved):raise ValueError(problem) monkeypatch.setattr(profile,'validate',reject) monkeypatch.setattr(profile,'grounding_errors',lambda *args:[]) class RepairReached(Exception):pass def invoke(instruction,payload,schema,**kwargs): if 'repair_keys' in payload: assert payload['repair_keys']==['recent'] assert payload['validation_feedback']==problem assert '待资料确认' in str(payload) assert '已完成整改' not in str(payload['previous_rows']) raise RepairReached() return deepcopy(value) with pytest.raises(RepairReached):profile.review_profile(entry,invoke=invoke) def test_fact_check_distinguishes_next_steps_and_keeps_past_claims_visible(): from app.modules.work_assistant import personnel_profile as profile entry=profile.ProfileRequest(person_id='1',name='测试',department_id='1',department='测试部',posts='工程师',begin='2026-11-01',end='2026-11-18',coverage=[],limits=[],evidence=[ dict(id='feedback-8',kind='feedback',subject='报告签字',actor_id='1',at='',relation='self',content='报告复审已完成,后续提交领导签字。')]) data,excerpts=profile.material(entry) candidate={section:[] for section in DETAIL_SECTIONS} candidate['findings']=[dict(key='recent',status='supported',headline='报告复审',finding='本人反馈已完成复审,待提交签字。',action='跟进验收材料签字流程',basis=[excerpts['e1']])] calls=[] def invoke(instruction,payload,schema,**kwargs): calls.append(deepcopy(payload['candidate']['findings'][0])) return {'issues':[]} profile.grounding_errors(profile.pack_material(data),candidate,invoke,120,excerpts) assert calls[0]['action']==candidate['findings'][0]['action'] assert '下一步' in calls[0]['action_type'] candidate['findings'][0]['action']='已完成领导签字' profile.grounding_errors(profile.pack_material(data),candidate,invoke,120,excerpts) assert calls[1]['action']=='已完成领导签字' assert 'action_type' not in candidate['findings'][0] def test_malformed_model_json_retries_are_bounded_and_checkpointed(): import json from app.modules.work_assistant import personnel_profile as profile entry=profile.ProfileRequest(person_id='1',name='测试',department_id='1',department='测试部',posts='工程师',begin='2026-11-01',end='2026-11-18',coverage=[],limits=[],evidence=[profile.Evidence(id='task',kind='task',subject='报告提交',actor_id='',at='2026-11-01',relation='requirement',content='提交测试报告。')]) saved=[] def malformed(*args,**kwargs):raise json.JSONDecodeError('missing object','{',1) for expected in (1,2): with pytest.raises(profile.JobDeferred): profile.review_profile(entry,invoke=malformed,checkpoint=saved[-1] if saved else None,save_checkpoint=saved.append) assert saved[-1]['format_failures']==expected assert saved[-1]['candidate'] is None with pytest.raises(profile.JobDeferred): profile.review_profile(entry,invoke=malformed,checkpoint=saved[-1],save_checkpoint=saved.append) assert saved[-1]['split_generation'] for _ in range(2): with pytest.raises(profile.JobDeferred): profile.review_profile(entry,invoke=malformed,checkpoint=saved[-1],save_checkpoint=saved.append) with pytest.raises(json.JSONDecodeError): profile.review_profile(entry,invoke=malformed,checkpoint=saved[-1],save_checkpoint=saved.append)