"""Annual talent panels generated from PMS evidence, with durable per-panel recovery.""" from copy import deepcopy import hashlib import json import re import unicodedata from decimal import Decimal from typing import Literal from pydantic import BaseModel, ConfigDict, Field from .model_gateway import ModelOutputInvalid, ModelUnavailable from .review_jobs import JobDeferred from .personnel_history import read_history DIMENSIONS = ('execution', 'quality', 'problem_solving', 'collaboration', 'management', 'learning') DIMENSION_NAMES = dict(zip(DIMENSIONS, ('执行交付', '成果质量', '问题处理', '协作沟通', '管理履职', '学习改进'))) PANEL_REVISION = 14 QUALITY_REVISION = 3 COHERENCE_FIELDS=('assessment','fulfilled','shortfalls','trajectory','pending','example','title') SOURCE_TIME_NOTE=('严格区分记录发生时间与关联任务日期:review.at是检查发生时间,feedback.at是反馈提交时间,subject中的日期可能是关联任务日期。' '例如11月20日检查11月17日的任务,报告写“11月20日该任务被检查指出……”是在写检查日期,完全正确,不得误读为任务属于11月20日。' '同一task_id在多个日期被催办或检查,是同一事项的持续或跟踪记录;不能仅凭多条检查就要求把一个逾期事件改称多个逾期事件。' '概括“部分任务完成”并不否认所引任务合格;希望补更多正面细节或列全任务属于表达偏好,不是事实错误。') def _claim_spans(value): if isinstance(value,list):return [json.dumps(value,ensure_ascii=False)] # Keep exact text and its field context, while separating independently # stated project outcomes instead of attributing one outcome to all tasks. return [part for part in re.split(r'(?<=[。;])',value) if part.strip()] def _mentioned_task_ids(text): """Recognize explicit task references without treating dates as IDs.""" ids=set() for match in re.finditer(r'(?:任务(?:编号)?[::]?\s*|task-)(\d{3,})(?!\d)',text): number=match.group(1) if re.fullmatch(r'(?:19|20)\d{2}',number) and re.match(r'\s*(?:年|[-/.]\d{1,2}(?:[-/.]\d{1,2})?)',text[match.end():]): continue ids.add(number) return ids def _measure_tokens(text, chinese=True): """Compare quantities, not spelling: 5名 and 5人 describe the same count. Do not equate unrelated units (项/个/次) or infer totals from name lists. """ text=unicodedata.normalize('NFKC',text) digits={'零':0,'〇':0,'一':1,'二':2,'两':2,'三':3,'四':4,'五':5,'六':6,'七':7,'八':8,'九':9} def value(raw): if re.fullmatch(r'\d+(?:\.\d+)?',raw):return str(Decimal(raw).normalize()) total=section=number=0 for char in raw: if char in digits:number=digits[char] elif char=='万':total+=(section+number)*10000;section=number=0 else:section+=(number or 1)*{'十':10,'百':100,'千':1000}[char];number=0 return str(Decimal(total+section+number).normalize()) number=r'[0-9]+(?:\.[0-9]+)?'+(r'|[零〇一二两三四五六七八九十百千万]+' if chinese else '') return {(value(raw),'人' if unit=='名' else unit):raw+unit for raw,unit in re.findall(r'(? (20000 if entry.profile_kind == 'history' else 11500) or len(selected) >= (80 if entry.profile_kind == 'history' else 36): continue selected.append(source.model_dump()) size += len(source.content) ids.add(key) return {'profile_kind':entry.profile_kind,'management_applicable':entry.management_applicable,'person': {'id': entry.person_id, 'name': entry.name, 'posts': entry.posts, 'department': entry.department}, 'available_posts': entry.available_posts, 'period': [entry.begin, entry.end], 'summary': core.get('findings', []), 'evidence': selected, 'limits': entry.limits, 'coverage': {'selected': len(selected), 'available': len(entry.evidence)}} DIMENSION_TERMS = { 'execution': ('完成','交付','提交','进度','逾期','落实'), 'quality': ('合格','验收','质量','缺陷','附件','评审'), 'problem_solving': ('问题','处理','解决','排查','整改','修复','异常','原因'), 'collaboration': ('协同','协调','沟通','配合','对接','共同','一起','会议'), 'management': ('组织','分工','检查','督办','跟踪','统筹','台账','计划','汇总'), 'learning': ('学习','复盘','培训','改进','优化','梳理','研究','总结'), } def _dimension_sources(entry,key): """Retrieve candidate work, not conclusions, across the complete received pool.""" candidates=[source.model_dump() for source in entry.evidence if _performance_source(source.model_dump())] if key=='management': candidates=[source for source in candidates if source['relation']=='self' or source['kind']=='deliverable'] def score(source): text=source.get('subject','')+' '+source['content'] return sum(term in text for term in DIMENSION_TERMS[key]) related=[source for source in candidates if score(source)>0] ranked=sorted(related or candidates,key=lambda source:(score(source),source.get('at','')),reverse=True) selected=[];size=0 for source in ranked: if len(selected)>=12 or size+len(source['content'])>11000:continue selected.append(source);size+=len(source['content']) return selected,{'searched':len(entry.evidence),'related':len(related),'reviewed':len(selected)} def _anchor_quote(quote, content): """Return the literal source span; never repair or replace substantive characters.""" if quote in content: return quote # Models often punctuate a cropped sentence or flatten a line-separated list. # Anchor the unchanged words, then restore the exact original punctuation. cropped = quote.strip().rstrip('。.!!??;;,,') if not cropped: return None if cropped in content: return cropped def indexed(text): return [(char, index) for index, char in enumerate(text) if not re.match(r'[\s;;]', char)] original = indexed(content) needle = ''.join(char for char, _ in indexed(cropped)) haystack = ''.join(char for char, _ in original) offset = haystack.find(needle) if needle else -1 if offset < 0: return None span = content[original[offset][1]:original[offset + len(needle) - 1][1] + 1] return span if len(span) <= 180 else None def _citation_catalog(material): """Person-scoped literal excerpts: generation selects handles instead of retyping evidence.""" excerpts = [] for source in material['evidence']: content = source['content'] for start in range(0, len(content), 140): quote = content[start:start + 160] if quote.strip(): excerpts.append({'excerpt_id': f'c{len(excerpts) + 1}', 'evidence_id': source['id'], 'quote': quote}) return excerpts def _resolve_citations(value, group, catalog): value = deepcopy(value) by_id = {row['excerpt_id']: row for row in catalog} for row in value.get(group, []): for index, ref in enumerate(row.get('basis', [])): if 'excerpt_id' not in ref: continue # Older in-flight responses still undergo exact source validation. source = by_id.get(ref['excerpt_id']) if source is None or set(ref) != {'excerpt_id'}: raise ModelOutputInvalid('引用片段不属于本人的本轮资料') row['basis'][index] = {key: source[key] for key in ('evidence_id', 'quote')} return value def _cited_sources(rows, sources, margin=100): """Bound verification context around every cited span; the stored originals stay intact.""" quotes={} for row in rows: for ref in row.get('basis',[]):quotes.setdefault(ref['evidence_id'],[]).append(ref['quote']) result=[] for source in sources: if source['id'] not in quotes:continue content=source['content'];intervals=[] for quote in quotes[source['id']]: start=content.find(quote) if start>=0:intervals.append((max(0,start-margin),min(len(content),start+len(quote)+margin))) if margin and source.get('kind')=='task': # A requirement quote near the start must not hide the recorded # completion state/time at the tail and turn completed work into a gap. start=content.find(';计划期限:') if start<0:start=content.find('统计截止时的完成登记:') if start>=0:intervals.append((start,len(content))) merged=[] for start,end in sorted(intervals): if merged and start<=merged[-1][1]:merged[-1]=(merged[-1][0],max(end,merged[-1][1])) else:merged.append((start,end)) if merged:result.append({**source,'at_meaning':{'review':'检查发生时间','feedback':'反馈提交时间','log':'日志记录时间'}.get(source.get('kind'),'来源记录时间'), 'content':'\n【同一原文的另一引用位置】\n'.join(content[a:b] for a,b in merged)}) return result def _attach_task_requirements(value, material, keys=None): """Link explicitly named requirements to exact tasks before independent review. This is source resolution, never proof that the task was performed. Only requirement/pending fields are resolved; the verifier still checks every claim. """ sources={source['id']:source for source in material['evidence']} tasks={} for source in material['evidence']: if source['kind']=='task' and source['id'].startswith('task-'): tasks.setdefault(str(source.get('task_id') or source['id'][5:].split(':')[0]),source) for row in value.get('abilities',[]): if keys and row.get('key') not in keys:continue needed=set().union(*(_mentioned_task_ids(row.get(field,'')) for field in ('requirement','pending'))) cited={str(sources.get(ref.get('evidence_id'),{}).get('task_id','')) for ref in row.get('basis',[])} for task_id in sorted(needed-cited): source=tasks.get(task_id) if source and source['content'].strip() and len(row['basis'])<12: ref={'evidence_id':source['id'],'quote':source['content'][:180]} if ref not in row['basis']:row['basis'].append(ref) return value def unverified_shortfall(text): """Missing registration is an evidence gap, not proof of nonperformance.""" return bool(re.search(r'尚未核到|未核到.*(?:完成|登记)|未见.*(?:完成登记|验收记录)|暂无.*(?:完成记录|验收记录)|未找到.*(?:完成记录|附件)|未到.*(?:期限|截止)|等待.*(?:反馈|回复|审批)|未明确.*(?:是否|完成)',text)) def _duty_quality_errors(rows, full_history): errors=[] for row in rows: key=row['key'] if row['shortfalls'] and row['shortfalls'] in {row['fulfilled'],row['label'],row['title']}: errors.append(f'{key} 的不足只是重复标签或履职描述;请写明确的职责要求与实际差距,不能把正常履行归为不足。') elif row['shortfalls'] and unverified_shortfall(row['shortfalls']): errors.append(f'{key}.shortfalls 只有未核到登记、资料缺口或等待状态,不能认定未履职。' '移入pending并明确需核实的事项,shortfalls只写直接原文证实的实际未履行或不合格;' '同步修正title、assessment、trajectory和attainment。') elif full_history and row['attainment'] in {'partial','unmet'} and not row['shortfalls'].strip(): errors.append(f'{key} 降低达成状态必须写出有原文依据的具体职责差距;没有确证不足时,按实际履行证据限定判断或标为待核实。') return errors def _validate(value, group, material): model = Capabilities if group == 'abilities' else Guidance parsed = model.model_validate(value).model_dump() rows = parsed[group] expected = tuple(key for key in DIMENSIONS if key!='management' or material.get('management_applicable') is not False) if group == 'abilities' else GUIDANCE_KEYS if tuple(row['key'] for row in rows) != expected: raise ModelOutputInvalid('模块维度或顺序不完整') if group=='abilities': for row in rows: if row['pending'].strip() and not row['shortfalls'].strip() and row['attainment'] in {'partial','unmet'}: # Abstain instead of repeatedly asking the model to reconcile an # unsupported negative rating. Never upgrade it to "met" by rule. # Keep all observed work and citations for independent fact review. row.update(status='insufficient',attainment='unknown') errors=_duty_quality_errors(rows,material.get('full_history')) if errors:raise ModelOutputInvalid('\n'.join(errors)) sources = {e['id']: e for e in material['evidence']} for row in rows: key, status = row['key'], row['status'] if key != 'development' and (row['career_path'] or row['career_note']): raise ModelOutputInvalid(f'{key} 不得包含岗位路径') if row['career_path']: current = {p.strip() for p in re.split(r'[,,、;;/]', material['person']['posts'])} seen = set() for step in row['career_path']: if (status != 'review_required' or step['post'] not in material.get('available_posts', []) or step['post'] in current or step['post'] in seen or not step['reason'].strip() or not step['prerequisite'].strip()): raise ModelOutputInvalid('development 岗位路径未通过目录与依据校验') seen.add(step['post']) recommendation = key in RECOMMENDATIONS allowed = ('review_required', 'insufficient') if recommendation else (*OBSERVATIONS, 'insufficient') if status not in allowed: raise ModelOutputInvalid(f'{key} 的评价状态与模块不符') if group == 'abilities' and status == 'insufficient' and (material.get('profile_kind')!='history' or not row['basis']): row.update(label='依据不足', title=f'{DIMENSION_NAMES[key]}材料待补充', assessment=f'本期资料不足以判断该维度,可补充{MISSING_EVIDENCE[key]}。', example='', action='', basis=[], attainment='unknown') elif group == 'abilities' and status == 'insufficient': row['attainment']='unknown' if group == 'abilities': allowed_attainment = {'insufficient': {'unknown'}, 'supported': {'met','partial'}, 'attention': {'partial','unmet'}} if row['attainment'] not in allowed_attainment[status]: raise ModelOutputInvalid(f'{key} 的attainment与工作表现状态不一致;合格为met,存在明确改进点为partial,未执行或不达标为unmet,依据不足为unknown') if recommendation and status == 'review_required' and not row['action'].strip(): raise ModelOutputInvalid(f'{key} 缺少具体实践及验收成果') if recommendation and status=='review_required' and material.get('full_history') and material.get('positive_ability_ids'): if not any(ref['evidence_id'] in material['positive_ability_ids'] for ref in row['basis']): raise ModelOutputInvalid(f'{key} 请从已体现的专业工作与优势出发规划发展培养;现有不足另由整改模块处理,不以缺附件作为培养主线') if recommendation and material.get('full_history') and re.search(r'(?:附件|交付物|成果物|材料).{0,8}(?:自检|自查|完整|核对|检查|提交|上传)|(?:自检|自查).{0,8}(?:交付|附件|材料)',row['title']): raise ModelOutputInvalid(f'{key} 的培养目标仍是现岗材料整改;请选择有工作依据的专业知识、技术方法或更完整职责,附件自检只能作为辅助步骤') if key=='learning_plan' and material.get('full_history'): steps=(row.get('plan') or {}).get('steps',[]) deliverable=(row.get('plan') or {}).get('deliverable','') if re.search(r'附件|清单|交叉复核单|复核确认单',deliverable) and re.search(r'齐全|完整|无遗漏|无缺失|已.*提交',deliverable) and not re.search(r'运行|功能|模型|方案|分析报告|研究报告|测试结果|实测|性能|业务指标|设计成果',deliverable): raise ModelOutputInvalid('learning_plan 的验收成果仅证明附件材料齐全,仍属于整改。请基于本人已核验的交付、问题处理或学习事例,明确专业知识方法的学习、实际业务实践及能力验证成果,不再以附件清单作为培养主线') if steps and all(re.search(r'清单|附件|文档|打包|提交|完整',step) and not re.search(r'设计|实现|演练|实验|模拟|研究|分析|测试|调试|建模|测算|访谈|谈判|策划|评估|案例',step) for step in steps): raise ModelOutputInvalid('learning_plan 的全部步骤仍只是整理清单、补齐附件和复核材料,不能充当培养。请从已核验优势选择相关专业方向,安排知识方法学习与实际业务实践,明确要练习的专业能力;材料整理只能是辅助步骤') if recommendation and status == 'insufficient' and (row['example'] or row['action'] or row['basis']): raise ModelOutputInvalid(f'{key} 依据不足时只说明缺少的材料') actual = False quoted_sources = [] quoted_subjects = [] quoted_task_ids=set() for ref in row['basis']: source = sources.get(ref['evidence_id']) quote = _anchor_quote(ref['quote'], source['content']) if source else None if not quote or not quote.strip(): raise ModelOutputInvalid(f"{row['key']} 的引用 {ref['evidence_id']} 未匹配原文;" f"请重新选择连续原句,不改写:{ref['quote'][:100]}") ref['quote'] = quote quoted_sources.append(source['content']) quoted_subjects.append(source.get('subject','')) if source.get('task_id'):quoted_task_ids.add(str(source['task_id'])) if source['id'].startswith('task-'):quoted_task_ids.add(source['id'][5:].split(':')[0]) quoted_task_ids.update(re.findall(r'任务编号[::]\s*(\d+)',source['content'])) if group == 'abilities' and status == 'attention' and source['kind']=='deliverable' and re.search(r'未找到附件文件|正文未读取|读取失败|无法读取|不支持.*格式',source['content']): raise ModelOutputInvalid(f'{key} 不得用服务未读取到附件作为员工不足的依据;这是系统资料可读性限制,不证明本人未提交。只保留检查原文明确记载的实际问题,并修正所有相应标题、结论和变化趋势') actual |= _performance_source(source) fact_fields = ('assessment', 'example') if recommendation else ('label', 'title', 'assessment', 'example', 'fulfilled', 'shortfalls', 'trajectory', 'requirement', 'pending') # Fields are independent statements. Joining a title ending in “任务” # to an assessment beginning “2026...” invented a task ID and blocked # immutable, already-verified leadership summaries on every retry. factual_text = '\n'.join(row[field] for field in fact_fields) mentioned_tasks=set().union(*(_mentioned_task_ids(row[field]) for field in fact_fields)) if material.get('full_history') and mentioned_tasks-quoted_task_ids: raise ModelOutputInvalid(f'{key} 的事实涉及任务 {", ".join(sorted(mentioned_tasks-quoted_task_ids))},' '但本模块basis没有引用对应任务或同任务反馈。补上准确原文引用,或删去无对应依据的具体断言;requirement、pending也必须有相应引用。') source_text = re.sub(r'\s+', '', '\n'.join(quoted_sources)) for claim in ('多数', '整体稳定', '总体稳定', '一贯', '始终', '长期保持', '全流程'): if claim in factual_text and claim not in source_text: raise ModelOutputInvalid(f'{key} 的“{claim}”超出所引事例范围,请限定为具体检查或所引记录') # A referenced record's title is part of its source (e.g. “补充5个 # 合同评审材料”). This only establishes the stated quantity; task # requirements still cannot prove completion or replace fact review. source_measures=_measure_tokens(source_text+'\n'+'\n'.join(quoted_subjects)) for quantity,measure in _measure_tokens(factual_text,chinese=False).items(): if quantity not in source_measures: raise ModelOutputInvalid(f'{key} 的数量 {measure} 未被本模块引用记录支持,不可从其他任务拼接或扩写') if (status != 'insufficient' or row['basis']) and not actual: raise ModelOutputInvalid(f'{key} 需要本人实际工作、成果原文或针对本人的检查评价;' '若确实没有应为 insufficient,岗位和计划要求不能作为实际表现或培养建议的唯一依据') return parsed def resume_cached_talent(entry,result): """Recheck finished history reports under current guards, retaining valid panels. Reading resumes through the per-record history cache; no ready result is exempt from new provenance guards merely because it predates a hotfix. """ if not entry.full_history or not result.get('talent'):return None report=result['talent'];core={k:v for k,v in result.items() if k!='talent'} material={**_material(entry,core),'full_history':True,'evidence':[s.model_dump() for s in entry.evidence]} material['positive_ability_ids']={ref['evidence_id'] for row in report['abilities'] if row['status']=='supported' for ref in row['basis']} failures={} for group in ('abilities','guidance'): try:report[group]=_validate({group:report[group]},group,material)[group] except ValueError as exc:failures[group]=str(exc) if report.get('leadership',{}).get('assembly_revision')!=2: failures['leadership']='Reassemble verified facts with both important work and grounded shortcomings.' from .personnel_role_fit import REVISION as ROLE_REVISION, SYNTHESIS_REVISION, validate_role_fit role = report.get('role_fit', {}) try: if role.get('state') != 'verified' or role.get('revision') != ROLE_REVISION or role.get('synthesis_revision') != SYNTHESIS_REVISION: raise ModelOutputInvalid('岗位职责与胜任分析待生成') validate_role_fit(role, entry) except (ValueError, KeyError, TypeError) as exc: failures['role_fit'] = str(exc) if not failures: report['quality_revision']=QUALITY_REVISION return None dimensions=[row['key'] for row in report['abilities']] talent={'source_hash':hashlib.sha256(json.dumps(entry.review_input(),ensure_ascii=False,sort_keys=True).encode()).hexdigest(), 'panel_revision':PANEL_REVISION,'verification_revision':2,'core':core, 'parts':{g:{g:deepcopy(report[g])} for g in ('abilities','guidance')}, 'verified':['abilities','guidance'],'verified_panels':{g:[r['key'] for r in report[g]] for g in ('abilities','guidance')}, 'attempts':{},'feedback':{},'repair_candidates':{},'review_issues':{},'history_generated':dimensions, 'dimension_search':deepcopy(report.get('dimension_search',{}))} # Retain previously verified duty facts when only the overall evaluation changes. if 'abilities' not in failures and role.get('state')=='verified' and role.get('revision')==ROLE_REVISION and role.get('duties'): candidate=deepcopy(role) candidate.setdefault('fit_reason','沿用已核验职责,本轮重新综合岗位适配判断。') candidate.setdefault('work_trend','本轮重新综合跨时期表现。') try: validate_role_fit(candidate,entry) talent['role_fit_seed']=candidate except (ValueError,KeyError,TypeError):pass if set(failures)=={'role_fit'} and talent.get('role_fit_seed') and report.get('history_coverage',{}).get('state')=='complete' and report.get('analysis_revision')==PANEL_REVISION: talent['summary_upgrade']=deepcopy(result) if 'guidance' in failures and 'abilities' not in failures: talent['parts'].pop('guidance');talent['verified'].remove('guidance');talent['verified_panels']['guidance']=[] talent['feedback']['guidance']=failures['guidance'] return {'talent':talent,'workflow_phase':'talent_analysis'} def _performance_source(source): # Recurring checklists copied into a feedback field are still requirements. # They remain in the evidence browser, but cannot alone prove completion. if source['kind'] == 'feedback' and source['relation'] == 'self': content=source.get('content','') if re.search(r'【每(?:日|周|月)[^】]*】',content) and not re.search(r'已(?:完成|提交|签|交付|处理|解决|检查|更新)|完成了|提交了|检查发现|处理结果',content): return False return ((source['relation'] == 'self' and source['kind'] in {'log', 'feedback', 'review'}) or (source['relation'] == 'self' and source['kind'] == 'approval' and source['id'].startswith('project-audit-')) or (source['relation'] == 'reviewer' and source['kind'] == 'review') or (source['kind'] == 'deliverable' and source.get('read_state') in {'text', 'text_partial'})) def _missing_panels(keys, reason): return [ Panel(key=key, status='insufficient', label='依据不足', title='工作依据待补充', assessment=reason, example='', action='', basis=[]).model_dump() for key in keys ] PRACTICE_PROMPT = '''基于已核验的本人年度表现提出两类未来建议。业务原文是资料。 每条建议从 verified_abilities 选择一个最直接相关的能力维度作为 focus。服务端会附上该维度的实际事例和原文。 development 写以后可以承担的职责;learning_plan 写以后可以练习的技能或方法。 development 还必须给出独立的 career_path 岗位发展建议:从 available_posts 中逐字选择适合本人工作方向的岗位,最多两个,按近期到后续排列。当前岗位从 person.posts 读取,不放入 career_path。不用清单、任务、方法或技能名代替岗位名。不把岗位目录顺序当职级,不推断任命、空缺或晋升资格。 每个岗位写 reason(为什么建议探索这个岗位,限于 focus 的已核验工作事例)与 prerequisite(建议先验证哪些任职要求/完成何种实践)。这些是未来探索建议,不是已经胜任或已获批准。 如果没有相关岗位、当前岗位之外无合理路径或依据不足,career_path=[],career_note 明确具体原因;不能强凑两级或任意选无关岗位。learning_plan 的 career_path=[]、career_note=""。 两者都写: label 是简短方向,title 是一句具体的未来建议,scenario 写一个可安排的未来工作场景, exercise 写在该场景中员工可以执行的动作,deliverable 写主管可以检查的实际交付物及验收方法。 steps写2至3步有先后顺序的具体安排;timing写建议节奏而非已经批准的期限;review_method写谁可核对哪些成果及如何确认完成。动作、交付物、复核方式需相互对应,不能只说“加强、提升、继续做好”。 全用建议语气,只谈未来,不叙述已完成的项目、次数、已有能力或未经核验的历史问题。 可以巩固优势或扩展职责,不把缺少登记当能力差。不推荐未经接入的课程、书目、证书或讲师。 优先安排与目标方向相符的完整工作实践,明确要验证的专业能力和可检查的实际成果;文档和表格可作为辅助产物,不能代替岗位实践本身。不预设系统有未提供的功能或组织有已批准的培训资源。 根据要求的 key 生成建议,只返回 schema 要求的 JSON。''' PRACTICE_PROMPT += ''' development和learning_plan必须明确target_direction:建议探索的岗位或专业方向,如结合本人真实工作选择的软件工程、测试质量、项目交付等具体方向,不能直接套示例。 两类建议服务于同一合理发展方向。development说明可逐步承担哪类更完整的职责,learning_plan说明为该方向补充哪些知识、方法与实践,以及如何验证任职准备。 “补附件、自查清单、按时反馈、修复某个问题”属于现岗整改,不能单独作为职业发展或培养目标。不得把整改动作换个名称冒充培养。 当前岗位未配置或目录没有合适的下一岗时,可以提出有实际工作依据的专业方向,career_path保持空并说明不是公司既定职级;不要因此不给发展建议。 培养场景可建议承担一个范围清晰的完整工作单元并由主管复核;避免无依据的晋升承诺。 ''' def _compose_guidance(value, abilities, requested, include_overview, strict_plan=False, available_posts=(), current_posts="", direction_required=False): observed = {row['key']: row for row in abilities if row['status'] in OBSERVATIONS} drafts = PracticeGuidance.model_validate(value).model_dump()['guidance'] if tuple(row['key'] for row in drafts) != tuple(requested): raise ModelOutputInvalid('实践建议模块不完整或顺序无效') recommendations = [] for draft in drafts: key = draft['key'] anchor = observed.get(draft['focus']) if anchor is None: raise ModelOutputInvalid(f'{key} 未关联已核验的本人能力事例') if direction_required and anchor['status']!='supported' and any(row['status']=='supported' for row in observed.values()): raise ModelOutputInvalid(f'{key} 请从已体现的专业工作与优势出发规划发展培养;现有不足另由整改模块处理,不以缺附件作为培养主线') if any(not draft[field].strip() for field in ('label', 'title', 'scenario', 'exercise', 'deliverable')): raise ModelOutputInvalid(f'{key} 缺少工作场景、练习或验收成果') if direction_required and not draft['target_direction'].strip(): raise ModelOutputInvalid(f'{key} 必须明确目标岗位或专业方向,不能用现岗整改代替培养') if strict_plan and (len(draft['steps'])<2 or any(not step.strip() or len(step)>100 for step in draft['steps']) or not draft['timing'].strip() or not draft['review_method'].strip()): raise ModelOutputInvalid(f'{key} 必须明确至少两个工作步骤、建议节奏和复核方式') action = '。'.join(label + draft[field].strip().rstrip('。') for field, label in (('scenario', '建议场景:'), ('exercise', '实践行动:'), ('deliverable', '验收成果:'))) + '。' steps=draft['steps'] or [draft['exercise']] if draft['steps']:action+='具体安排:'+';'.join(steps)+'。' if draft['timing']:action+='建议周期:'+draft['timing']+'。' if draft['review_method']:action+='复核方式:'+draft['review_method']+'。' career = draft['career_path'] if key != 'development' and career: raise ModelOutputInvalid('learning_plan 不得包含岗位发展路径') if key != 'development': # This field is not rendered/used for training. Ignore explanatory # notes such as "not a promotion path" instead of regenerating both # otherwise valid recommendations forever. draft['career_note']='' current = {p.strip() for p in re.split(r'[,,、;;/]', current_posts) if p.strip()} seen = set() for step in career: if (step['post'] not in available_posts or step['post'] in current or step['post'] in seen or not step['reason'].strip() or not step['prerequisite'].strip()): raise ModelOutputInvalid('development 岗位必须来自系统目录,不得重复当前岗位或以任务代替岗位') seen.add(step['post']) if key == 'development' and available_posts and not career and not draft['career_note'].strip(): raise ModelOutputInvalid('development 未提供岗位路径时须说明具体原因') if key == 'development' and not career and not draft['career_note']: draft['career_note'] = '暂缺可供核验的岗位目录,岗位发展建议待补充。' recommendations.append({**anchor, 'key': key, 'status': 'review_required', 'target_direction':draft['target_direction'], 'career_path': career, 'career_note': draft['career_note'], 'label': draft['label'], 'title': draft['title'], 'action': action, 'plan':{'scenario':draft['scenario'],'steps':steps,'deliverable':draft['deliverable'], 'timing':draft['timing'],'review_method':draft['review_method']}}) if not include_overview: return {'guidance': recommendations} primary = next((row for row in observed.values() if row['status'] == 'supported'), next(iter(observed.values()))) focus = next((row for row in observed.values() if row['status'] == 'attention' and row is not primary), None) assessment, basis = primary['assessment'], primary['basis'] if focus: combined = list({(ref['evidence_id'], ref['quote']): ref for ref in [*basis, *focus['basis']]}.values()) summary = assessment + '\n\n' + focus['assessment'] if len(combined) <= 6 and len(summary) <= 500: assessment, basis = summary, combined experience = {**primary, 'key': 'experience', 'title': '工作事例', 'action': ''} performance = {**primary, 'key': 'performance', 'title': primary['title'], 'assessment': assessment, 'basis': basis, 'example': '', 'action': ''} return {'guidance': [experience, performance, *recommendations]} def review_annual_talent(entry, *, core_review, invoke, checkpoint=None, save_checkpoint=None, staged=False, history_cache=None): dimensions=tuple(key for key in DIMENSIONS if key!='management' or entry.management_applicable is not False) if any(source.relation == 'self' and source.actor_id != entry.person_id for source in entry.evidence): raise ModelOutputInvalid('本人记录归属不符') fingerprint = hashlib.sha256(json.dumps(entry.review_input(), ensure_ascii=False, sort_keys=True).encode()).hexdigest() saved = deepcopy(checkpoint or {}) talent = deepcopy(saved.get('talent', {})) if talent.get('source_hash') != fingerprint: talent = {'source_hash': fingerprint, 'parts': {}, 'verified': [], 'attempts': {}, 'feedback': {}} for field in ('review_issues','repair_candidates','verified_panels','attempts','feedback'): talent.setdefault(field,{}) if talent.get('panel_revision') != PANEL_REVISION: # Rebuild the report's overview and recommendations around the verified capabilities. talent['verified'] = [] talent.update(panel_revision=PANEL_REVISION, attempts={}, feedback={}) talent['parts'] = {key: value for key, value in talent.get('parts', {}).items() if key in talent.get('verified', [])} talent['review_issues'] = {} talent['repair_candidates'] = {} talent['verified_panels'] = {} talent['dimension_search'] = {} talent.pop('history_generated',None) talent.pop('leadership',None) talent.pop('coherent', None) if entry.profile_kind == 'history' and talent.get('verification_revision') != 2: talent.update(verification_revision=2, verified=[], verified_panels={}, review_issues={}, attempts={}) talent.pop('coherent', None) core = talent.get('core') if core is None and entry.profile_kind == 'history': # The portrait is the report. Do not run the retired five-finding annual # analysis first and then generate the same judgements a second time. core = {'profile_scope': 'history', 'analysis_version': 'personnel-history-v1', 'annual_assessment_version': 2} talent['core'] = core def persist(): saved['talent'] = deepcopy(talent) saved['workflow_phase'] = 'talent_analysis' if save_checkpoint: save_checkpoint(deepcopy(saved)) provider = invoke def invoke(instruction, payload, schema, **options): stage = payload.get('generation_part','verify') if payload.get('repair_fields'):stage+=':fields:'+','.join(payload['repair_fields']) elif payload.get('repair_keys'):stage+=':panels:'+','.join(payload['repair_keys']) if 'duty_index' in payload:stage+=':duty:'+str(payload['duty_index']) if 'candidate' in payload: stage += ':' + ','.join(row['key'] for rows in payload['candidate'].values() for row in rows) budgets = talent.setdefault('output_budgets',{}) base = options.get('max_tokens',3200) options['max_tokens'] = max(base,budgets.get(stage,base)) if entry.profile_kind == 'history': options['fit_context'] = True from .bid_progress import stream_observer observer_token=stream_observer.set(stream_observer.get() or (lambda raw:None)) if entry.profile_kind=='history' else None try: result=provider(instruction,payload,schema,**options) budgets.pop(stage,None) return result except ModelUnavailable as exc: if entry.full_history and payload.get('generation_part')=='role_duties' and exc.reason in {'direct_timeout','direct_deadline','direct_output_truncated','gateway_output_truncated'}: # A long six-duty response cannot fit every model time slice. # Continue with a short outline and individually saved duties. talent.setdefault('role_fit',{})['split_duties']=True persist() raise ModelUnavailable('role_fit_retry',retryable=True,retry_after=2) from exc if entry.profile_kind == 'history' and exc.reason in {'direct_output_truncated','gateway_output_truncated'}: budgets[stage] = min(16000,options['max_tokens'] + max(1600,options['max_tokens']//2)) persist() raise ModelUnavailable('annual_output_retry',retryable=True,retry_after=30) from exc raise finally: if observer_token is not None:stream_observer.reset(observer_token) if entry.full_history and talent.get('summary_upgrade'): # This checkpoint is created only after validation of unchanged source # material and all existing panels. Upgrade just the overall evaluation. from .personnel_role_fit import role_fit result=deepcopy(talent['summary_upgrade']) old=result['talent'] selection={row['key']:row.get('basis',[]) for row in [*old['abilities'],*old['guidance']]} old['role_fit']=role_fit(entry,selection,old['abilities'],talent,invoke,persist,staged) old['quality_revision']=QUALITY_REVISION return result if core is None: def save_core(value): saved.clear() saved.update(value) if save_checkpoint: save_checkpoint(deepcopy(saved)) core = core_review(entry, invoke=invoke, checkpoint=checkpoint, save_checkpoint=save_core, staged=staged) if core.get('assessment_status') == 'partial' or not entry.evidence: return core talent['core'] = core persist() if staged: raise JobDeferred() history_selection={};history_coverage={} if entry.full_history: try: history_selection,history_coverage=read_history(entry,dimensions,talent,invoke,persist,staged,cache=history_cache) except ModelOutputInvalid as exc: talent['history_feedback']=str(exc)[:1000] persist() raise ModelUnavailable('history_read_retry',retryable=True,retry_after=30) from exc material = _material(entry, core) validation_material={**material,'full_history':entry.full_history,'evidence':[source.model_dump() for source in entry.evidence]} validation_material['positive_ability_ids']={ref['evidence_id'] for row in talent.get('parts',{}).get('abilities',{}).get('abilities',[]) if row['status']=='supported' for ref in row['basis']} all_actual_sources=[source for source in validation_material['evidence'] if _performance_source(source)] actual_sources = [source for source in material['evidence'] if _performance_source(source)] if not actual_sources: actual_sources = [source.model_dump() for source in entry.evidence if _performance_source(source.model_dump())][:12] material['evidence'].extend(actual_sources) material['coverage']['selected'] = len(material['evidence']) if 'abilities' in talent['verified']: try: talent['parts']['abilities'] = _validate(talent['parts']['abilities'], 'abilities', validation_material) except ValueError as exc: invalid_keys = [key for key in dimensions if re.search(r'(?= 3: # Keep verified core/neighbor panels. A rejected panel must not become # a cached "ready" partial report that can never acquire talent data. talent['attempts'][group] = 0 rounds=talent.setdefault('retry_rounds',{}) rounds[group]=rounds.get(group,0)+1 persist() raise ModelUnavailable('annual_panel_retry', retryable=True,retry_after=min(300,30*2**min(4,rounds[group]-1))) if group=='abilities' and entry.full_history and not talent.get('repair_candidates',{}).get(group): generated=talent.setdefault('history_generated',[]) pending=next((key for key in dimensions if key not in generated),None) if pending: previous=talent['parts'].pop(group,{'abilities':_missing_panels(dimensions,'历史资料待逐维度综合分析。')}) if not history_selection.get(pending): for row in previous['abilities']: if row['key']==pending: row.update(title=DIMENSION_NAMES[pending]+'尚无充分依据', assessment='已分批审阅全部可读历史资料,尚未形成足以判断本维度的事例;不能据此认定员工未履职。') generated.append(pending) talent['parts'][group]=previous talent.setdefault('dimension_search',{})[pending]={'state':'complete','searched':len(entry.evidence),'reviewed':0} persist() if staged:raise JobDeferred() return review_annual_talent(entry,core_review=core_review,invoke=provider,checkpoint=saved,save_checkpoint=save_checkpoint,staged=staged,history_cache=history_cache) talent.setdefault('repair_candidates',{})[group]={'candidate':previous,'keys':[pending],'history_initial':True} if group=='abilities' and entry.profile_kind=='history' and not entry.full_history and group in talent['parts'] and group not in talent['verified']: searches=talent.setdefault('dimension_search',{}) missing=next((row for row in talent['parts'][group][group] if row['status']=='insufficient' and searches.get(row['key'],{}).get('state')!='complete'),None) if missing: key=missing['key'];selected,counts=_dimension_sources(entry,key) searches[key]={**counts,'state':'complete' if not selected else 'reviewing'} if selected: previous=talent['parts'].pop(group) talent.setdefault('repair_candidates',{})[group]={'candidate':previous,'keys':[key], 'search_key':key,'search_ids':[source['id'] for source in selected]} talent['feedback'][group]=(DIMENSION_NAMES[key]+'需要专项分析。已从完整收到的本人材料中重新检索相关动作,' '请逐条判断实际事例,不要因为不是管理岗、没有问题标题或没有单独协作成果就直接判材料不足。' '管理履职只对管理岗位分析组织、分工、检查、跟踪与团队管理职责;普通员工不分析此维度。' '协作包含有明确对象和动作的对接;问题处理须说明问题及处理动作。' '若只有局部事例,可以保留insufficient/unknown,但须写出有限观察、具体事例及真实引用;完全无相关事实才说明缺口。') persist() raise JobDeferred() if group not in talent['parts']: enum = dimensions if group == 'abilities' else GUIDANCE_KEYS verified_abilities = talent['parts'].get('abilities', {}).get('abilities', []) observed_ids = {ref['evidence_id'] for row in verified_abilities if row['status'] in OBSERVATIONS for ref in row['basis']} sources = [source for source in all_actual_sources if source['id'] in observed_ids] if group == 'guidance' else actual_sources if not sources: reason = ('本期还没有已核验且能作为综合判断或培养建议依据的工作表现,待补充本人记录、成果或主管检查。' if group == 'guidance' else '本期缺少可核验的本人工作记录、成果原文或主管检查,暂无法判断此项表现。') talent['parts'][group] = {group: _missing_panels(enum, reason)} talent['verified'].append(group) persist() continue group_material = {**material, 'summary': [], 'verified_abilities': verified_abilities, 'evidence': sources} catalog = _citation_catalog(group_material) if group == 'abilities' else [] repair = talent.get('repair_candidates', {}).get(group) repair_keys = repair['keys'] if repair else None remaining_repairs=[] if group=='abilities' and entry.full_history and repair_keys and len(repair_keys)>1: # Each repaired dimension is durable. A long multi-dimension # response must not time out and restart the entire repair set. remaining_repairs=repair_keys[1:] repair_keys=repair_keys[:1] if group=='abilities' and repair and repair.get('search_ids'): sources=[source for source in all_actual_sources if source['id'] in repair['search_ids']] group_material={**group_material,'evidence':sources} catalog=_citation_catalog(group_material) if group == 'abilities' and repair and repair.get('attempt',0) >= 2: disputed = {ref['evidence_id'] for row in repair['candidate']['abilities'] if row['key'] in repair_keys for ref in row['basis']} alternatives = [source for source in sources if source['id'] not in disputed] if alternatives: # Repeated ambiguous-source disputes must not cycle forever. # Keep accepted panels, and ask for a clearer independent case. sources = alternatives group_material = {**group_material, 'evidence': sources} catalog = _citation_catalog(group_material) if group=='abilities' and entry.full_history and repair_keys: chosen=[row for key in repair_keys for row in history_selection.get(key,[])] ids={row['evidence_id'] for row in chosen} sources=[source for source in validation_material['evidence'] if source['id'] in ids] group_material={**group_material,'evidence':sources,'history_coverage':history_coverage} catalog=[{'excerpt_id':f'c{i+1}','evidence_id':row['evidence_id'],'quote':row['quote']} for i,row in enumerate(chosen)] group_material['history_signals']=[{'excerpt_id':f'c{i+1}','signal':row['signal'],'at':row['at']} for i,row in enumerate(chosen)] # Task registration often survives reduction without its actual # feedback. Rejoin that same task's performance evidence before # asking the model to judge it, rather than repeatedly rejecting # a task-only draft. Keep the originals and their ownership. task_ids={s['task_id'] for s in sources if s.get('task_id')} related=[s for s in all_actual_sources if s.get('task_id') in task_ids and s['id'] not in ids] related.sort(key=lambda s:(s.get('at',''),s['id'])) joined=[];per_task={} for source in reversed(related): task=source['task_id'] if per_task.get(task,0)>=2:continue joined.append(source);per_task[task]=per_task.get(task,0)+1 if len(joined)>=12:break sources+=joined;group_material['evidence']=sources for source in joined: for offset in range(0,min(len(source['content']),480),160): quote=source['content'][offset:offset+160] if quote.strip():catalog.append({'excerpt_id':f'c{len(catalog)+1}','evidence_id':source['id'],'quote':quote}) if group == 'guidance': requested = [key for key in RECOMMENDATIONS if not repair or key in repair_keys] if repair and not requested: repair = None requested = list(RECOMMENDATIONS) if repair: repair_keys = requested schema = PracticeGuidance.model_json_schema() properties = schema['$defs']['PracticeDraft']['properties'] schema['$defs']['PracticeDraft']['required'] += ['steps','timing','review_method','career_path','career_note','target_direction'] properties['target_direction']['minLength']=2 properties['steps'].update(minItems=2,items={'type':'string','minLength':2,'maxLength':100}) properties['timing']['minLength']=2;properties['review_method']['minLength']=2 if entry.available_posts: schema['$defs']['CareerStep']['properties']['post']['enum'] = entry.available_posts else: properties['career_path']['maxItems'] = 0 properties['key']['enum'] = requested properties['focus']['enum'] = [row['key'] for row in verified_abilities if row['status'] in OBSERVATIONS] if entry.full_history and any(row['status']=='supported' for row in verified_abilities): properties['focus']['enum']=[row['key'] for row in verified_abilities if row['status']=='supported'] schema['properties']['guidance'].update(minItems=len(requested), maxItems=len(requested)) instruction = PRACTICE_PROMPT payload = {**group_material, 'requested_keys': requested} if entry.full_history: # Recommendations are future actions. Historical facts are inherited, # unchanged, from the verified focus panel in _compose_guidance. payload['verified_abilities']=[{field:row[field] for field in ('key','status','label','assessment','fulfilled','shortfalls')} for row in verified_abilities if row['key'] in properties['focus']['enum']] payload['evidence']=[] else: schema = model.model_json_schema() properties = schema['$defs']['Panel']['properties'] properties['key']['enum'] = repair_keys or list(enum) properties['status']['enum'] = [*OBSERVATIONS, 'insufficient'] properties['career_path']['maxItems']=0 properties['career_note']['enum']=[''] schema['$defs']['Panel']['required'].append('attainment') if entry.full_history: schema['$defs']['Panel']['required'] += ['fulfilled','shortfalls','trajectory','requirement','pending'] schema['$defs']['Reference'] = {'type': 'object', 'properties': { 'excerpt_id': {'type': 'string', 'enum': [row['excerpt_id'] for row in catalog]}}, 'required': ['excerpt_id'], 'additionalProperties': False} if repair: schema['properties'][group].update(minItems=len(repair_keys), maxItems=len(repair_keys)) instruction = PROMPT.replace('年度','全历史') if entry.profile_kind == 'history' else PROMPT instruction += '\n本轮仅生成以下维度:'+','.join(repair_keys or dimensions)+'。不得生成未要求的管理履职。' if entry.full_history: instruction += ('\n此前已分批阅读全部可读历史资料。当前 citations 是跨时期综合保留的代表原文,history_signals 是待核验索引,不是结论。' '综合早期、中期、近期的岗位要求、实际履行、检查评价及整改情况,不能只描述最近工作;不把旧岗位责任直接套到当前岗位。' 'fulfilled 明确哪些职责/事项做到位;shortfalls 明确哪些有原文支持的要求未落实或结果不合格;trajectory 说明不足是否有后续改进或尚无复核。' '每一项使用本模块basis覆盖的真实事例和日期。正反事实并存时必须两面呈现,不让一个supported/attention状态抹掉另一面。' '没有明确问题时shortfalls留空,没有合格或履行依据时fulfilled留空;不能为了填满而制造不足或把资料缺失当不履职。' '后续做得好不自动证明旧问题已整改,须有同一事项关联记录。无跨时期证据时明确只限可核验的时期,不得泛称长期稳定。' '各字段完整陈述事实及来源限定,不重复堆叠任务编号。assessment概括整个已核验范围内的履职情况,而不是只复述最新一项。') instruction += ('\n面向管理者说明职责有没有履行:requirement写所引具体任务或当时职责要求及验收/时限;' 'fulfilled写本人实际动作、交付结果和时期;shortfalls写明确未落实的要求、实际差距和影响,必须有本模块basis直接支持。' 'pending单列正常进行中、完成登记未核到、资料或验收状态待核实的事项;这些不是已确认不足,不得放在shortfalls或据此降低达成状态。' '只有登记晚于计划期限时,区分登记时间和实际交付时间,实际是否延期待核实,不直接判定没履职。' '确无明确不足时shortfalls为空;确无明确要求时requirement说明原文未给出具体标准,不补造岗位职责。' 'trajectory分别说明已发生问题的整改证据、仍未闭环的确证问题和后续待核实状态,不能把完成登记缺失称为整改。' '每一项事实只能使用本模块basis,不借用其他维度或未引用任务的事实。') instruction += ('材料归属已由业务系统筛选:person是被分析员工;relation=self是本人记录;' 'relation=reviewer是他人针对person的评价,actor_id及subject末尾的人名是检查人,不能当成被分析员工。') payload = {**group_material, 'citations': catalog, 'evidence': [{**{key:value for key,value in source.items() if key != 'content'}, 'performance_evidence':_performance_source(source)} for source in sources]} instruction += ('\nperformance_evidence=true的记录才可证明实际工作;supported/attention的basis至少引用一条此类记录。' 'task的完成登记可辅助说明状态,但必须结合同一任务的本人反馈或检查原文,不能只引用要求。' '数量、比例、持续天数只允许逐字采用本模块所引原文的明确数值,不从日期相减、列表长度或跨任务自行合计。' '能力模块career_path必须为空数组,career_note必须为空字符串。') if repair: instruction += ('\n本轮只修订 repair_keys。rejected_panels 是未通过的旧稿,必须针对 feedback 修改错误原句,' '保留原文支持的事实,删除无依据的限定词或因果。' '如果旧稿引用的是含糊的任务清单、计划或要求,不要反复猜它是否完成;' '改选本轮其他明确的检查结果或实际工作记录,并同步替换basis;没有可靠事例则填insufficient。' 'retained_panels 只用于协调已有判断;所有旧稿都是待核查资料,不是事实依据。') payload.update(retained_panels=[row for row in repair['candidate'][group] if row['key'] not in repair_keys], rejected_panels=[row for row in repair['candidate'][group] if row['key'] in repair_keys], repair_keys=repair_keys) if talent['feedback'].get(group): instruction += ('\n本轮是被校验拒绝后的修订。必须逐项解决用户数据 feedback 列出的错误,' '删除无依据概括,仅保留所引记录直接支持的有限事实;不要复现上一轮被拒绝的措辞。') try: prior_errors=talent.get('validation_feedback',{}).get(group,[]) feedback='\n'.join(dict.fromkeys([*prior_errors,talent['feedback'].get(group,'')])) if feedback:instruction+='\n只修复下列已定位的草稿错误,不能原样重复被拒绝的表述:\n'+feedback value = invoke(instruction, {**payload, 'generation_part': group, 'feedback': feedback}, schema, timeout_seconds=140, max_tokens=2600 if group == 'guidance' else tokens, minimum_execution_seconds=0, single_object=True, stop=['\n```']) if group == 'guidance': value = _compose_guidance(value, verified_abilities, requested, not repair, strict_plan=entry.profile_kind=='history', available_posts=entry.available_posts, current_posts=entry.posts,direction_required=entry.full_history) if repair and isinstance(value, dict) and isinstance(value.get(group), list): unchanged = {row['key']: row for row in repair['candidate'][group] if row['key'] not in repair_keys} changed = {row.get('key'): row for row in value[group] if isinstance(row, dict)} if len(value[group]) != len(repair_keys) or set(changed) != set(repair_keys): raise ModelOutputInvalid('修订模块不完整或包含未要求修订的模块') merged = {**unchanged, **changed} value[group] = [deepcopy(merged[key]) for key in enum] value=_resolve_citations(value,group,catalog) if group=='abilities' and entry.full_history: value=_attach_task_requirements(value,validation_material,repair_keys) talent['parts'][group] = _validate(value, group, validation_material) if remaining_repairs: repair['candidate']=deepcopy(talent['parts'].pop(group)) repair['keys']=remaining_repairs verified=talent.setdefault('verified_panels',{}).get(group,[]) talent['verified_panels'][group]=[key for key in verified if key not in [*repair_keys,*remaining_repairs]] persist() raise JobDeferred() talent.get('validation_feedback',{}).pop(group,None) if repair: # A repair can expand after another invalid panel is discovered. # Every rewritten panel must be independently verified again. verified=talent.setdefault('verified_panels',{}).get(group,[]) talent['verified_panels'][group]=[key for key in verified if key not in repair_keys] if entry.full_history and group=='abilities' and repair and repair.get('history_initial'): for key in repair_keys: if key not in talent.setdefault('history_generated',[]):talent['history_generated'].append(key) talent.setdefault('dimension_search',{})[key]={'state':'complete','searched':len(entry.evidence),'reviewed':len(history_selection.get(key,[]))} talent['repair_candidates'].pop(group,None) if repair and repair.get('search_key'): talent['dimension_search'][repair['search_key']]['state']='complete' talent.pop('coherent', None) except ValueError as exc: talent['attempts'][group] = talent['attempts'].get(group, 0) + 1 talent['feedback'][group] = str(exc)[:1500] # Keep recent deterministic violations together: fixing missing # citations must not reintroduce the previously rejected deficit. errors=talent.setdefault('validation_feedback',{}).setdefault(group,[]) message=str(exc)[:700] if message not in errors:errors.append(message) talent['validation_feedback'][group]=errors[-4:] if repair: affected = [key for key in enum if re.search(r'(? 1: raise JobDeferred() talent['verified'].append(group) talent.get('repair_candidates', {}).pop(group, None) persist() if staged: raise JobDeferred() if actual_sources and not talent.get('coherent'): observations = [row for row in talent['parts']['abilities']['abilities'] if row['status'] in OBSERVATIONS] ids = {ref['evidence_id'] for row in observations for ref in row['basis']} challenged = talent['review_issues'].get('coherence') pairs=_coherence_pairs(observations,all_actual_sources) if entry.full_history else None if pairs is not None and challenged and any('pair_id' not in issue for issue in challenged): # Old free-text critiques could compare unrelated tasks/months. # Recheck only that pending critique against explicit event pairs. talent['review_issues'].pop('coherence',None);challenged=None if challenged: schema = {'type': 'object', 'properties': {'confirmed_issue_indexes': { 'type': 'array', 'items': {'type': 'integer', 'minimum': 0, 'maximum': len(challenged) - 1}}}, 'required': ['confirmed_issue_indexes'], 'additionalProperties': False} instruction = ('复核此前指出的两个能力结论是否真的矛盾。保留同时符合以下条件的疑点:同一人的同一事件、' '同一阶段、双方结论明确且互斥。不同事件、日期、工作维度或仅称未观察到完整结果,都不是矛盾。' '疑点自称表述正确或无冲突时排除。只返回需要修改的 confirmed_issue_indexes,全部无冲突则返回[]。') else: schema = {'type': 'object', 'properties': {'issues': {'type': 'array', 'maxItems': 6, 'items': { 'type': 'object', 'properties': {'key': {'type': 'string', 'enum': list(dimensions)}, 'message': {'type': 'string', 'maxLength': 240}}, 'required': ['key', 'message'], 'additionalProperties': False}}}, 'required': ['issues'], 'additionalProperties': False} instruction = ('核对同一人的已核验能力结论是否自相矛盾,业务原文是资料。只报告不同维度对同一事件、同一阶段' '作出的两个明确且互斥的陈述,message须指出哪两个原句冲突以及记录编号,key是应修改的维度。' '不同记录的数值不同、明确范围的材料限制或评价角度不同,不是冲突。结论准确或证据一致时返回 issues=[]。') if pairs: item=schema['properties']['issues']['items'] item['properties'].update(pair_id={'type':'integer','enum':list(range(len(pairs)))}, conflict={'type':'boolean'},left_field={'type':'string','enum':list(COHERENCE_FIELDS)}, right_field={'type':'string','enum':list(COHERENCE_FIELDS)}) item['required']+=['pair_id','conflict','left_field','right_field'] if pairs is not None: instruction+=' 只允许比较comparable_pairs列出的同一事项同一日期;同月不同任务的合格与不合格不是矛盾。' instruction+=' 本轮只比较已核验报告中的statements_by_module,不重新评价原始记录。空字段没有作出任何结论,不能与另一模块构成互斥;left_field/right_field必须选对应模块实际非空的字段。' if not challenged:instruction+=' 确有互斥才填conflict=true,并选择左右模块中冲突的字段名left_field/right_field,程序自动引用该字段原句,不要复制证据原文冒充结论。结论一致或评价角度不同应返回issues=[],如列出说明则conflict=false。' if len(observations) >= 2 and (pairs is None or pairs): verdict = invoke(instruction, {'generation_part': 'coherence', 'candidate': {'abilities': observations}, 'person': material['person'], **({'statements_by_module':{row['key']:{field:row[field] for field in COHERENCE_FIELDS if row.get(field)} for row in observations}, 'verification_feedback':talent.get('coherence_feedback','')} if pairs is not None else {'evidence':_cited_sources(observations,all_actual_sources,margin=0)}), **({'comparable_pairs':pairs} if pairs is not None else {}), **({'challenged_issues': challenged} if challenged else {})}, schema, timeout_seconds=140, max_tokens=1600, minimum_execution_seconds=0, single_object=True) if challenged: indexes = verdict.get('confirmed_issue_indexes') if isinstance(verdict, dict) else None if not isinstance(indexes, list) or any(type(index) is not int or not 0 <= index < len(challenged) for index in indexes): raise ModelOutputInvalid('年度画像一致性疑点复核结果无效') issues = [challenged[index] for index in sorted(set(indexes))] else: issues = verdict.get('issues') if isinstance(verdict, dict) else None if not isinstance(issues, list) or any(not isinstance(issue, dict) or issue.get('key') not in dimensions or not isinstance(issue.get('message'), str) for issue in issues): raise ModelOutputInvalid('年度画像一致性核验结果无效') if pairs is not None: by_key={row['key']:row for row in observations} try: issues=[resolved for issue in issues if (resolved:=_coherence_issue(issue,pairs,by_key)) is not None] except ModelOutputInvalid as exc: talent['coherence_feedback']=str(exc)+'。请重新核验statements_by_module,选择相应模块非空的实际原句字段;没有两句互斥结论就返回issues=[],不得将原始资料的差异当成报告说过的话。' persist() raise ModelUnavailable('annual_panel_retry',retryable=True,retry_after=30) from exc talent.pop('coherence_feedback',None) if issues: talent['review_issues']['coherence'] = issues persist() raise JobDeferred() talent['review_issues'].pop('coherence', None) if issues: talent['repair_candidates']['abilities'] = {'candidate': talent['parts'].pop('abilities'), 'keys': list(dict.fromkeys(issue['key'] for issue in issues))} talent['parts'].pop('guidance') talent['verified'] = [] if entry.profile_kind == 'history': rejected = {issue['key'] for issue in issues} talent.setdefault('verified_panels', {})['abilities'] = [key for key in talent['verified_panels'].get('abilities', []) if key not in rejected] talent['verified_panels']['guidance'] = [] talent['repair_candidates'].pop('guidance', None) talent['attempts'].pop('guidance', None) talent['feedback']['abilities'] = '\n'.join(issue['key'] + ': ' + issue['message'] for issue in issues) talent['attempts']['abilities'] = talent['attempts'].get('abilities', 0) + 1 persist() raise JobDeferred() talent['coherent'] = True persist() if staged and len(observations)>=2 and (pairs is None or pairs): # The next model call belongs to a new leased time slice. Two # individually bounded calls can otherwise exceed the 180s lease. raise JobDeferred() leadership=None if entry.full_history: from .personnel_leadership import leadership_brief def validate_point(point): # Use the same factual/ownership/number guards as other portrait panels. rows=deepcopy(talent['parts']['guidance']['guidance']) rows[0]=Panel(key='experience',status='supported',label='主要工作',title=point['title'], assessment=point['assessment'],example='',action='',basis=point['basis']).model_dump() _validate({'guidance':rows},'guidance',validation_material) actual_ids={row['id'] for row in all_actual_sources} leadership=leadership_brief(entry,{key:[row for row in rows if row['evidence_id'] in actual_ids] for key,rows in history_selection.items()},talent,invoke,persist,staged,validate_point, verified_abilities=talent['parts']['abilities']['abilities']) result = deepcopy(core) result['talent'] = {'version': 1, 'analysis_revision': PANEL_REVISION, 'quality_revision':QUALITY_REVISION, **talent['parts']['abilities'], **talent['parts']['guidance'], 'coverage': material['coverage'],'dimension_search':talent.get('dimension_search',{}), 'dimensions':list(dimensions),'management_applicable':entry.management_applicable, 'history_coverage':history_coverage} if leadership is not None:result['talent']['leadership']=leadership if entry.full_history: from .personnel_role_fit import role_fit result['talent']['role_fit'] = role_fit(entry, history_selection, talent['parts']['abilities']['abilities'], talent, invoke, persist, staged) return result