"""Read-only stage inventory; snapshots are evidence, never a new training freeze."""
from collections import Counter,defaultdict
from contextlib import closing
from copy import deepcopy
from datetime import datetime,timezone
import csv
import io
import json
from pathlib import Path
import re
import sys

import numpy as np

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.mask_model_training_data import read,write,jsonl,require,sha
from pallet.cluster_targets import digest
from pallet.mask_class_note_integration import snapshot_db
from pallet.mask_template_refined import readonly
from pallet.pallet_description_review import SETS,validate_description
from pallet.pallet_description_simple import initial_description
from pallet.pallet_description_data import ROOT as TRAINING
from pallet.pose_review_geometry import polygon_value

OUT=PROJECT/'outputs/pallet_dataset_stage_summary_20261107_v1'
ANOMALY_WORDS=('遮挡','视野','视角','质量','缺失','损坏','断裂')


def text_structure(text):
    """Only index explicit structure words; never generate a replacement description."""
    result={};match=re.search(r'([234])\s*支腿',text)
    if match:result['legs']=int(match[1])
    if '上下横梁' in text:result['beams']=2
    elif '上横梁' in text:result['beams']=1
    materials=[v for v in ('塑料','木质','金属') if v in text]
    if len(materials)==1:result['material']=materials[0]
    return result


def geometry_changed(a,b):
    aa=np.asarray(a,dtype=float);bb=np.asarray(b,dtype=float)
    return aa.shape!=bb.shape or not np.allclose(aa,bb,atol=1e-6,rtol=0)


def attributes_for(info):
    match=re.fullmatch(r'([234])legs-([12])beams-(.*)',info['parent']);require(match,'Unknown class parent')
    return dict(legs=int(match[1]),beams=int(match[2]),material=match[3])


def summarize(records):
    c=Counter();actions=Counter();classes=Counter();parents=Counter();fields=Counter();K=Counter();splits=Counter();notes=[]
    for r in records:
        c['targets']+=1;actions[r['action']]+=1;classes[r['class_id']]+=1;parents[r['class_parent']]+=1;K[len(r['polygon'])]+=1;splits[r['original_split']]+=1
        d=r['description'];fields[json.dumps([d['legs'],d['beams'],d['material']],ensure_ascii=False)]+=1
        for k in ('has_review','class_changed','polygon_changed','polygon_exact_changed','vertex_count_changed','description_text_changed','description_fields_changed',
            'class_attribute_conflict','text_attribute_conflict','text_class_conflict','invalid_polygon','wrong_K','blank_structure_text',
            'observation_nonempty','structure_text_anomaly_hint','note_anomaly_hint','any_anomaly_hint','attributes_unknown','new_joint_correct','text_batch_ever','attributes_batch_ever','geometry_previously_completed'):
            c[k]+=bool(r[k])
        if r['observation_nonempty']:notes.append(dict(mode=r['mode'],target_key=r['target_key'],class_id=r['class_id'],observation=d['observation']))
    return dict(**c,unique_original_images=len({r['image_sha256'] for r in records}),unique_frames=len({r['frame_id'] for r in records}),
        components=len({r['component'] for r in records}),saved_actions=dict(actions),current_class_counts=dict(sorted(classes.items())),
        parent_counts=dict(sorted(parents.items())),selected_attribute_combinations=dict(fields),vertex_counts=dict(sorted(K.items())),
        inherited_formal_split_target_counts=dict(splits),observation_examples=notes,
        never_saved_class_counts=dict(sorted(Counter(r['class_id'] for r in records if not r['has_review']).items())),
        draft_class_counts=dict(sorted(Counter(r['class_id'] for r in records if r['action']=='draft').items())),
        class_attribute_conflicts_by_action=dict(Counter(r['action'] for r in records if r['class_attribute_conflict'])))


def main():
    require(not OUT.exists(),'Preserve existing stage inventory');OUT.mkdir(mode=0o700);(OUT/'snapshots').mkdir(mode=0o700)
    begun=datetime.now(timezone.utc).isoformat();datasets={};issues=[];all_records=[];sources={}
    classes=read(TRAINING/'classes.json');active_classes=sorted(int(k) for k,c in classes.items() if c['train_enabled'] and int(k)!=149)
    components=read(TRAINING/'private/components.json')['by_target'];frozen={r['target_key']:r for r in jsonl(TRAINING/'private/training.jsonl')}
    for mode,s in SETS.items():
        folder=OUT/'snapshots'/mode;folder.mkdir(mode=0o700);start=datetime.now(timezone.utc).isoformat()
        snapshot_db(s['reviews']/'mask_reviews.sqlite3',folder/'mask_reviews.sqlite3')
        with closing(readonly(folder/'mask_reviews.sqlite3')) as db:
            metadata=dict(db.execute('SELECT key,value FROM metadata'));current={k:json.loads(raw) for k,raw in db.execute('SELECT target_key,payload FROM reviews')}
            events=[(i,k,rev,json.loads(raw)) for i,k,rev,raw in db.execute('SELECT id,target_key,revision,payload FROM events ORDER BY id')]
            batch_table=db.execute("SELECT name FROM sqlite_master WHERE name='structure_batches'").fetchone()
            batch_receipts=db.execute('SELECT count(*) FROM structure_batches').fetchone()[0] if batch_table else 0
        props=jsonl(s['root']/'proposals.jsonl');bykey={p['target_key']:p for p in props}
        require(len(props)==len(bykey),'Duplicate target in task')
        require(read(s['root']/'classes.json')==classes,'Task/training taxonomy definitions differ')
        require(set(current)<=set(bykey),'Unknown target in review store');require(metadata['formal_manifest_sha256']==digest(s['root']/'manifest.json') and metadata['namespace']==s['namespace'],'Store/task metadata mismatch')
        latest={};event_kinds=Counter();text_ever=set();attributes_ever=set()
        for _,key,rev,value in events:
            require(value['revision']==rev and value['target_key']==key and rev==latest.get(key,{}).get('revision',0)+1,'Event identity/revision mismatch');latest[key]=value;event_kinds[value['event_kind']]+=1
            if value['event_kind']=='human_batch_structure_text_confirmation':text_ever.add(key)
            if value['event_kind']=='human_batch_structure_attributes_confirmation':attributes_ever.add(key)
        require(latest==current,'History/current records disagree')
        records=[]
        for p in props:
            key=p['target_key'];v=current.get(key);effective=v or p;cls=effective['class_id'];info=classes[str(cls)]
            require(info['train_enabled'],'Unresolved target entered live normal classes')
            if v:require(v['binding']==metadata['formal_manifest_sha256'] and v['source_binding']==sha(p),'Live review source binding differs')
            description=deepcopy(v['description'] if v else initial_description(p));validate_description(description)
            poly=deepcopy(effective['polygon']);invalid=None
            try:polygon_value(poly,*p['source']['size'])
            except ValueError as error:invalid=str(error)
            expected=attributes_for(info);explicit=text_structure(description['text']);unknown=lambda value:value is None or value=='无法判断'
            class_conflicts={k:dict(selected=description[k],class_definition=value) for k,value in expected.items() if not unknown(description[k]) and description[k]!=value}
            text_conflicts={k:dict(selected=description[k],text_explicit=value) for k,value in explicit.items() if not unknown(description[k]) and description[k]!=value}
            text_class_conflicts={k:dict(text_explicit=value,class_definition=expected[k]) for k,value in explicit.items() if expected[k]!=value}
            initial=initial_description(p);note=v.get('note','') if v else ''
            record=dict(mode=mode,target_key=key,image_sha256=p['image_sha256'],frame_id=p['source']['frame_id'],component=components.get(key,p['source']['group_id']),
                original_split=p['source']['split'],original_class_id=p['class_id'],class_id=cls,class_parent=info['parent'],expected_K=info['K'],polygon=poly,
                has_review=bool(v),revision=v['revision'] if v else 0,action=v['action'] if v else 'never_saved',geometry_previously_completed=p['geometry_previously_completed'],
                class_changed=cls!=p['class_id'],polygon_changed=geometry_changed(poly,p['polygon']),polygon_exact_changed=poly!=p['polygon'],vertex_count_changed=len(poly)!=len(p['polygon']),
                description=description,note=note,description_source='latest_saved_review' if v else 'initial_model_draft_with_optional_original_human_note',
                description_text_changed=description['text']!=initial['text'],description_fields_changed=any(description[k]!=initial[k] for k in ('legs','beams','material')),
                class_attribute_conflict=bool(class_conflicts),text_attribute_conflict=bool(text_conflicts),text_class_conflict=bool(text_class_conflicts),
                invalid_polygon=bool(invalid),wrong_K=len(poly)!=info['K'],blank_structure_text=not description['text'].strip(),
                observation_nonempty=bool(description['observation'].strip()),structure_text_anomaly_hint=any(t in description['text'] for t in ANOMALY_WORDS),
                note_anomaly_hint=any(t in note for t in ANOMALY_WORDS),attributes_unknown=any(unknown(description[k]) for k in ('legs','beams','material')),
                new_joint_correct=bool(v and v['action']=='correct'),text_batch_ever=key in text_ever,attributes_batch_ever=key in attributes_ever,
                observation_status=v.get('observation_status') if v else ('described' if description['observation'].strip() else 'normal'),
                latest_event_kind=v['event_kind'] if v else None)
            record['any_anomaly_hint']=record['observation_nonempty'] or record['structure_text_anomaly_hint'] or record['note_anomaly_hint']
            if any((class_conflicts,text_conflicts,text_class_conflicts,invalid,record['wrong_K'],not v,v and v['action']!='correct')):
                issues.append(dict(mode=mode,target_key=key,class_id=cls,revision=record['revision'],action=record['action'],class_attribute_conflicts=class_conflicts,
                    text_attribute_conflicts=text_conflicts,text_class_conflicts=text_class_conflicts,invalid_polygon=invalid,wrong_K=record['wrong_K'],
                    stored_in_browser_cannot_be_observed=True,description=description,not_automatically_wrong_or_rejected=True))
            records.append(record)
        report=summarize(records);report.update(events=len(events),batch_receipts=batch_receipts,event_kind_counts=dict(event_kinds),
            latest_record_event_kinds=dict(Counter(v['event_kind'] for v in current.values())),latest_saved_at=max((v['updated_at'] for v in current.values()),default=None),
            snapshot_started_at=start,snapshot_finished_at=datetime.now(timezone.utc).isoformat(),task_binding=metadata['formal_manifest_sha256'],
            snapshot_sha256=digest(folder/'mask_reviews.sqlite3'),history_current_and_source_binding_verified=True)
        datasets[mode]=report;all_records.extend(records)
        sources[mode]=dict(task_manifest_sha256=digest(s['root']/'manifest.json'),proposals_sha256=digest(s['root']/'proposals.jsonl'),
            classes_sha256=digest(s['root']/'classes.json'),runtime=read(s['managed']/'public_access.json'),active_presentation=read(s['managed']/'simple_policy.json'))
    combined=summarize(all_records)
    require(set(combined['current_class_counts'])<=set(active_classes),'Live class not in canonical taxonomy')
    old_images={r['image_sha256'] for r in all_records if r['mode']=='existing'};new_images={r['image_sha256'] for r in all_records if r['mode']=='new'}
    require(not old_images&new_images and len({r['target_key'] for r in all_records})==len(all_records),'New/old duplicate target or image')
    per_class=[]
    for cls in active_classes:
        rs=[r for r in all_records if r['class_id']==cls];old=[r for r in rs if r['mode']=='existing'];new=[r for r in rs if r['mode']=='new']
        per_class.append(dict(class_id=cls,attributes=classes[str(cls)]['attributes_text'],parent=classes[str(cls)]['parent'],K=classes[str(cls)]['K'],
            existing_targets=len(old),new_targets=len(new),total_targets=len(rs),distinct_images=len({r['image_sha256'] for r in rs}),
            saved_correct=sum(r['action']=='correct' for r in rs),saved_draft=sum(r['action']=='draft' for r in rs),never_saved=sum(not r['has_review'] for r in rs),
            class_attribute_conflicts=sum(r['class_attribute_conflict'] for r in rs),text_attribute_conflicts=sum(r['text_attribute_conflict'] for r in rs),
            fresh_image_goal=100,fresh_image_shortfall=max(0,100-len({r['image_sha256'] for r in new})),
            saved_correct_new_shortfall=max(0,100-len({r['image_sha256'] for r in new if r['action']=='correct'}))))
    require(sum(r['total_targets'] for r in per_class)==combined['targets'],'Per-class total mismatch')
    changed_pairs=Counter((r['mode'],r['original_class_id'],r['class_id']) for r in all_records if r['class_changed'])
    splits=defaultdict(set)
    for r in all_records:splits[r['component']].add(r['original_split'])
    model_receipt=read(TRAINING/'run_v1_bfloat16/training_complete.json');vlm_receipt=read(TRAINING/'vlm_run_v2_format_repair/training_complete.json')
    parent_rows=[]
    for parent in sorted({r['class_parent'] for r in all_records}):
        rs=[r for r in all_records if r['class_parent']==parent]
        parent_rows.append(dict(parent=parent,existing=sum(r['mode']=='existing' for r in rs),new=sum(r['mode']=='new' for r in rs),total=len(rs)))
    report=dict(state='read_only_stage_inventory_not_training_freeze',started_at=begun,finished_at=datetime.now(timezone.utc).isoformat(),
        user_stage_statement='现已完成新数据标注和老数据语义标注和部分标签更新',user_declared_completed=True,no_correct_events_fabricated=True,
        datasets=datasets,combined=combined,formal_detection_base=read(PROJECT/'configs/active_formal_dataset.json')['summary'],
        effective_nonempty_classes=len(combined['current_class_counts']),canonical_classes=len(active_classes),archived_train_enabled_classes=sum(c['train_enabled'] for c in classes.values()),
        class149_merge={'149':148},class149_current_targets=combined['current_class_counts'].get(149,0),class130_current_targets=combined['current_class_counts'].get(130,0),
        per_class=per_class,per_parent=parent_rows,source_bindings=sources,
        fresh_quota=dict(classes=len(active_classes),goal=100*len(active_classes),allocated_targets=datasets['new']['targets'],
            shortfall=sum(r['fresh_image_shortfall'] for r in per_class),full_classes=[r['class_id'] for r in per_class if r['new_targets']>=100],
            partial_classes=[r['class_id'] for r in per_class if 0<r['new_targets']<100],zero_classes=[r['class_id'] for r in per_class if not r['new_targets']],
            over100_classes={r['class_id']:r['new_targets'] for r in per_class if r['new_targets']>100},not_a_new_candidate_capacity_audit=True),
        class_transitions=[dict(mode=m,from_class=a,to_class=b,targets=n) for (m,a,b),n in sorted(changed_pairs.items())],
        small_classes=[r for r in per_class if r['distinct_images']<20],
        frozen_training=dict(targets=len(frozen),distinct_images=len({r['image_sha256'] for r in frozen.values()}),classes=41,
            dataset_manifest_sha256=digest(TRAINING/'dataset_manifest.json'),current_frozen_class_labels_disagree_with_latest=sum(r['mode']=='existing' and r['class_id']!=frozen[r['target_key']]['class_id'] for r in all_records),
            current_frozen_polygons_disagree_with_latest=sum(r['mode']=='existing' and geometry_changed(r['polygon'],frozen[r['target_key']]['polygon']) for r in all_records),
            full_pool_model_sha256=model_receipt['full_pool'],vlm_adapter_sha256=vlm_receipt['adapter_sha256'],
            current_round_new_targets_not_in_that_training=len([r for r in all_records if r['mode']=='new']),no_new_training_started=True),
        split_warnings=dict(components_spanning_inherited_formal_splits=sum(len(v)>1 for v in splits.values()),
            component_mapping_is_prior_version_not_new_split=True,old_split_names_not_independent_test_guarantee=True),
        production_annotation_POSTs=0,production_database_writes=0,application_or_models_changed=False)
    write(OUT/'summary.json',report);write(OUT/'effective_inventory.jsonl',all_records,lines=True);write(OUT/'issues.jsonl',issues,lines=True)
    write(OUT/'class_transitions.json',report['class_transitions']);write(OUT/'per_parent.json',parent_rows)
    stream=io.StringIO();writer=csv.DictWriter(stream,fieldnames=list(per_class[0]));writer.writeheader();writer.writerows(per_class);(OUT/'per_class.csv').write_text(stream.getvalue())
    (OUT/'REPORT.md').write_text(markdown(report))
    write(OUT/'integrity.json',dict(state='stage_inventory_complete',summary_sha256=digest(OUT/'summary.json'),
        files={n:digest(OUT/n) for n in ('effective_inventory.jsonl','issues.jsonl','class_transitions.json','per_parent.json','per_class.csv','REPORT.md')},
        code_sha256=digest(__file__),no_live_annotation_writes=True,no_training_dataset_freeze=True,no_training=True,no_commit_or_push=True))
    print(json.dumps(dict(state=report['state'],combined=combined,datasets={m:{k:v for k,v in data.items() if k not in ('observation_examples','current_class_counts','selected_attribute_combinations')} for m,data in datasets.items()},fresh_quota=report['fresh_quota'],small_classes=report['small_classes']),ensure_ascii=False))


def markdown(r):
    old=r['datasets']['existing'];new=r['datasets']['new'];c=r['combined'];q=r['fresh_quota'];f=r['frozen_training']
    lines=['# 最新数据集阶段汇总与现状分析（2026-11-07）','',f"快照完成（UTC）：{r['finished_at']}。这是只读分析快照，不是新训练集冻结，不修改任何标注或完成事件。",'',
        '用户已声明本轮新数据标注、旧数据语义标注及部分标签更新完成。本报告保留该声明，同时分别列出服务器实际动作、默认正常策略和当前有效数据，不把批量确认或未保存内容伪装成逐图correct事件。','',
        '## 1. 数据规模','', '| 项目 | 已有数据 | 本轮新图 | 合计 |','|---|---:|---:|---:|']
    for label,key in [('目标数','targets'),('不同原图（SHA-256去重）','unique_original_images'),('有本轮服务器记录','has_review'),('correct记录','new_joint_correct'),('改类目标（相对本轮初始化）','class_changed'),('轮廓变化目标（1e-6像素容差）','polygon_changed'),('结构文字变化','description_text_changed'),('三项结构字段变化','description_fields_changed')]:
        lines.append(f"| {label} | {old.get(key,0)} | {new.get(key,0)} | {c.get(key,0)} |")
    lines+=['',f"当前有效非空细类{r['effective_nonempty_classes']}个；149已归入148，冻结训练类表仍保留{r['archived_train_enabled_classes']}个训练类和2个隔离类的历史定义。分类定义大类{len(r['per_parent'])}种。",'',
        f"原检测正式库仍为{r['formal_detection_base']['frames']:,}帧、{r['formal_detection_base']['boxes']:,}框，不能与本轮精细轮廓／语义库存相加。目标数不等于原图数；新旧图像跨批SHA去重交集为0，合计多出的{c['targets']-c['unique_original_images']}个目标来自同图多目标。",'',
        '## 2. 用户完成声明与服务器保存口径','']
    for mode,label in [('new','新图'),('existing','已有数据')]:
        data=r['datasets'][mode];a=data['saved_actions']
        lines.append(f"- {label}：correct {a.get('correct',0)}，draft {a.get('draft',0)}，defer {a.get('defer',0)}，本轮无服务器保存 {a.get('never_saved',0)}；历史事件{data['events']:,}条、批次回执{data['batch_receipts']}个。")
        lines.append(f"  - 无本轮保存的类别分布：{data['never_saved_class_counts']}；draft类别分布：{data['draft_class_counts']}。")
    lines+=['','草稿不等于用户尚未做过复核：批量描述操作故意不晋升类别／几何完成。已有数据可按默认正常规则无需逐条提交；本轮无保存也不等于旧几何未标注。浏览器未同步的本机草稿不可由服务器核验。用户完成声明可在下一次冻结时作为明确的批次依据，但必须保留原始动作和来源，不补造历史。','',
        '## 3. 结构与语义质量','',f"- 多边形有效性错误{c['invalid_polygon']}；与当前类K不符{c['wrong_K']}。实际点数分布：{json.dumps(c['vertex_counts'],ensure_ascii=False)}。点数／合法性通过不等于物理槽位、mask贴合和姿态尺度精度已验收。",
        f"- 三项结构选项与当前类别定义有显式冲突{c['class_attribute_conflict']}项：新图{new['class_attribute_conflict']}，已有{old['class_attribute_conflict']}；结构文字显式字段与选项不一致{c['text_attribute_conflict']}项，与类别定义不一致{c['text_class_conflict']}项。",
        f"- 冲突来源按服务器动作区分：新图{new['class_attribute_conflicts_by_action']}；已有{old['class_attribute_conflicts_by_action']}。未保存初始化不是已确认的人工语义记录，应与人工修改分开处理。",
        '- 上述是字段语义冲突，不是自动判错。需明确“完整结构”与“图像可见部件”的标注口径；不应把遮挡造成的少腿数直接当改类依据，也不能用类模板静默覆盖人工内容。问题索引见`issues.jsonl`。',
        f"- 异常文本框非空{c['observation_nonempty']}项，结构描述含遮挡／出视野／视角／画质／缺失等关键词{c['structure_text_anomaly_hint']}项，备注含此类关键词{c['note_anomaly_hint']}项；三处并集{c['any_anomaly_hint']}个目标。关键词只是检索线索，不等于已核验的异常正例数量。",
        '- 异常往往写在结构文字中。不能只看异常框是否为空，就将所有空框图当作可靠正常训练负例；需要保留字段来源并索引全部人工文字。当前“空描述默认正常”是应用规则，不是模型正常检测成绩。','',
        '## 4. 类别与长尾','', '| Class | 类别定义 | K | 已有 | 新图 | 总目标 | 不同原图 | 新图100缺口 |','|---|---|---:|---:|---:|---:|---:|---:|']
    for row in r['per_class']:lines.append(f"| {row['class_id']} | {row['attributes']} | {row['K']} | {row['existing_targets']} | {row['new_targets']} | {row['total_targets']} | {row['distinct_images']} | {row['fresh_image_shortfall']} |")
    lines+=['',f"少于20张不同原图的细类：{', '.join('Class'+str(v['class_id'])+'='+str(v['distinct_images']) for v in r['small_classes'])}。这些类不适合单独声称稳定准确率，保留细类ID，可在同结构大类内共享监督。",'',
        '### 大类分布','', '| 类别定义大类 | 已有 | 新图 | 合计 |','|---|---:|---:|---:|']
    for row in r['per_parent']:lines.append(f"| {row['parent']} | {row['existing']} | {row['new']} | {row['total']} |")
    lines+=['',f"按当前40细类重新统计每类100张本轮不同新图：目标{q['goal']}，当前{q['allocated_targets']}；逐类缺口合计{q['shortfall']}。达到100张的类：{q['full_classes']}；部分满足{len(q['partial_classes'])}类，0张{len(q['zero_classes'])}类。超过100的类：{q['over100_classes']}，不能把多出来的图充抵别类。",
        '这只重算本轮已分配且最新改类后的新图，不是剩余候选可用容量的新审计；也不能把改类后的“新图”与既有数据混算补满新图目标。','',
        '## 5. 训练／模型版本','',f"- 最近冻结训练数据仍为{f['targets']}目标／{f['distinct_images']}张图／41类；本轮{f['current_round_new_targets_not_in_that_training']}个新图目标尚未进入该模型训练。",
        f"- 已有池中{f['current_frozen_class_labels_disagree_with_latest']}个当前类别、{f['current_frozen_polygons_disagree_with_latest']}个当前轮廓与该冻结训练记录不同。最新语义修订及149→148也未追溯改写旧模型或旧训练标签。",
        f"- 现用分类／轮廓权重SHA-256：`{f['full_pool_model_sha256']}`；描述LoRA适配器：`{f['vlm_adapter_sha256']}`。",
        '- 历史组件留出细类89.09%、大类98.99%、mask IoU中位0.8690只对应旧冻结任务／划分；不能当作40类最新标签下的新评估成绩。',
        '- VLM原生诊断为96图、697次生成：4B遮挡检出5/9，但全黑图5/9仍断言有托盘；无法可靠承担标签自动验收。语义监督的主来源应是本轮人工记录，不是模型原文。','',
        '## 6. 下一阶段建议','',
        '1. 先生成独立的新版本训练冻结／导出：合并最新两库记录，应用149→148；保留本次用户完成声明、逐条原动作及原几何来源，不从旧proposals直接当最终标签。',
        '2. 对字段冲突和本轮无服务器保存记录做有界核对；优先核验少量明确矛盾，不要求已默认正常的全部旧图重复逐张确认。',
        '3. 语义任务拆分结构标签与逐图观察；异常描述集中索引，但不得靠关键词或空异常框自动制造损坏／正常GT。',
        f"4. 按同图与采集关联分量重建划分。当前继承原检测train／val／test标签，{r['split_warnings']['components_spanning_inherited_formal_splits']}个既有分量跨这些split；这不是本次训练泄漏结论，但原split名不能当独立盲测承诺。",
        '5. 再重训分类／轮廓并按新40类标签重新评估；轻量VLM先检查格式、结构一致和异常负例质量，再决定是否微调。保留现模型作为对照，不覆盖旧权重。','',
        '本次仅统计与分析，没有修改标注、补写完成事件、冻结新训练集、重训模型或晋升GT／机器人资格。']
    return '\n'.join(lines)+'\n'


if __name__=='__main__':main()
