#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 第三本账征集线审计:条目刀与落盘之间开不开口子(macOS / IDBots 本机语料) 判据(征集件 pin://89ee3f45f7c753da1096757b069f6a6f98445ce7aac1ef5533dae13da197f9c8i0 原文): 取所有含非空 truncation_points 的落盘回执;若落盘正文的码点数等于 Σkept_chars, 且其 utf8 字节数等于 Σcut_at_bytes,记「闭合」;否则记「违例」, 并记缺口字符数(正数表示盘上更短)。 单位按征集线 12-02 修正:kept_chars 比对单位 = UTF-16 码元(回执条目 unit 字段亦证实)。 unit 混合口径:unit=utf16-char 条目按 UTF-16 码元比;unit=rune 条目按 Unicode 码点比; 字节一律 utf8(cut_at_bytes 与单位无关)。 方法要点(避开已知陷阱): * 回执行只认「行首前缀 35 字符 + 严格 json.loads + 顶层键齐备」且位于 块之外者;块内前缀一律记为正文引用,不入帧。 * 禁止任何正则抓 JSON;解析失败即记 unparseable,绝不补救。 * 落盘正文 = 该 pin 明细头之后第一个内容块的原文(块行标记法提取)。 * 帧 = 回执行 sha256 去重;同一帧多实例逐一判定,结论不一致记 anomaly。 输出 report.json(确定性:排序键、无时间戳),复跑 sha256 逐位相同。 """ import hashlib import json import os from collections import Counter, defaultdict ROOT = os.path.expanduser('~/Library/Application Support/IDBots/dsh-sessions') PREFIX = '- RECEIPT read_metaweb_pins_batch: ' OPEN_LINE = '' CLOSE_LINE = '' RECEIPT_KEYS = ('requested', 'returned', 'bytes_written', 'truncation_points') def walk_files(): out = [] for dp, dn, fn in os.walk(ROOT): for f in fn: if 'read_metaweb_pins_batch' in f and f.endswith('.txt'): out.append(os.path.join(dp, f)) return sorted(out) def content_block_spans(text): """行级扫描 ... ,返回块 span 列表。""" spans = [] pos = 0 start = None opens = closes = 0 for line in text.split('\n'): if line == OPEN_LINE: opens += 1 if start is None: start = pos elif line == CLOSE_LINE: closes += 1 if start is not None: spans.append((start, pos + len(CLOSE_LINE))) start = None pos += len(line) + 1 if start is not None: spans.append((start, len(text))) return spans, opens, closes def in_spans(i, spans): return any(a <= i < b for a, b in spans) def body_of_block(text, span): """块 span 内的正文:开标签行尾 + 1 到闭标签行首 - 1。""" a, b = span body_start = a + len(OPEN_LINE) + 1 body_end = b - len(CLOSE_LINE) - 1 if body_end < body_start: return '' return text[body_start:body_end] def find_sheet_header(text, pin_id, spans): """在内容块之外找 'Pin :' 行首位置;找不到返回 None。""" pat = 'Pin ' + pin_id + ':' i = 0 while True: i = text.find(pat, i) if i < 0: return None at_line_start = (i == 0) or (text[i - 1] == '\n') if at_line_start and not in_spans(i, spans): return i i += 1 def next_header_pos(text, start, spans): """start 之后下一个顶层 'Pin :' 行首(块外);无则 None。""" i = start while True: i = text.find('\nPin ', i) if i < 0: return None pos = i + 1 if not in_spans(pos, spans): return pos i = pos def disk_body(text, pin_id, spans): """该 pin 的落盘正文:明细头与下一明细头之间的第一个内容块;无块/无明细头 → ''。""" h = find_sheet_header(text, pin_id, spans) if h is None: return '' nh = next_header_pos(text, h + 5 + len(pin_id) + 1, spans) limit = len(text) if nh is None else nh for a, b in spans: if h < a < limit: return body_of_block(text, (a, b)) return '' def measures(body): return { 'utf16_units': len(body.encode('utf-16-le')) // 2, 'codepoints': len(body), 'utf8_bytes': len(body.encode('utf-8')), 'astral': any(ord(c) > 0xFFFF for c in body), } def judge_instance(text, receipt, spans): """按判据逐帧判定(Σ 口径),并附逐条目差值诊断。""" tps = receipt.get('truncation_points') or [] sum_claim_chars = sum_disk_chars = sum_claim_bytes = sum_disk_bytes = 0 entry_diffs = [] astral_bodies = 0 for tp in tps: unit = tp.get('unit') kept = tp.get('kept_chars', 0) cab = tp.get('cut_at_bytes', 0) body = disk_body(text, tp.get('pin_id', ''), spans) m = measures(body) if m['astral']: astral_bodies += 1 disk_chars = m['codepoints'] if unit == 'rune' else m['utf16_units'] sum_claim_chars += kept sum_disk_chars += disk_chars sum_claim_bytes += cab sum_disk_bytes += m['utf8_bytes'] if disk_chars != kept or m['utf8_bytes'] != cab: entry_diffs.append({ 'pin_id': tp.get('pin_id', ''), 'reason': tp.get('reason', ''), 'unit': unit, 'kept_chars': kept, 'disk_chars': disk_chars, 'cut_at_bytes': cab, 'disk_bytes': m['utf8_bytes'], }) closed = (sum_disk_chars == sum_claim_chars) and (sum_disk_bytes == sum_claim_bytes) gap = sum_claim_chars - sum_disk_chars return { 'closed': closed, 'gap': gap, 'claim_chars': sum_claim_chars, 'disk_chars': sum_disk_chars, 'claim_bytes': sum_claim_bytes, 'disk_bytes': sum_disk_bytes, 'entry_diffs': entry_diffs, 'astral_bodies': astral_bodies, 'tp_count': len(tps), } def main(): files = walk_files() file_shas = {} instances = [] # 每条真实回执行一个实例 body_quote_occurrences = 0 prefix_occurrences_total = 0 unparseable_outside = [] tag_unbalanced_files = [] read_errors = [] for path in files: try: raw = open(path, 'rb').read() except OSError as e: read_errors.append({'file': path, 'error': str(e)}) continue file_shas[path] = hashlib.sha256(raw).hexdigest() try: text = raw.decode('utf-8') except UnicodeDecodeError as e: read_errors.append({'file': path, 'error': 'utf8 decode: ' + str(e)}) continue spans, opens, closes = content_block_spans(text) if opens != closes: tag_unbalanced_files.append({'file': path, 'opens': opens, 'closes': closes}) i = 0 while True: i = text.find(PREFIX, i) if i < 0: break prefix_occurrences_total += 1 at_line_start = (i == 0) or (text[i - 1] == '\n') if at_line_start and not in_spans(i, spans): nl = text.find('\n', i) line = text[i:] if nl < 0 else text[i:nl] raw_json = line[len(PREFIX):] ok = False try: receipt = json.loads(raw_json) ok = isinstance(receipt, dict) and all(k in receipt for k in RECEIPT_KEYS) except (ValueError, RecursionError): ok = False if ok: instances.append({ 'file': path, 'line': line, 'line_sha': hashlib.sha256(line.encode('utf-8')).hexdigest(), 'receipt': receipt, }) else: unparseable_outside.append({'file': path, 'detail': raw_json[:120]}) else: body_quote_occurrences += 1 i += 1 # 帧去重:回执行 sha256 by_sha = defaultdict(list) for inst in instances: by_sha[inst['line_sha']].append(inst) frames_with_tp = 0 frames_no_tp = 0 closed_frames = 0 violation_frames = 0 anomalies = [] gap_values = Counter() unit_counter = Counter() reason_counter = Counter() astral_frame_bodies = 0 rune_entry_frames = 0 violations = [] for sha, insts in sorted(by_sha.items()): verdicts = [] for inst in insts: text = open(inst['file'], 'rb').read().decode('utf-8') spans, _, _ = content_block_spans(text) verdicts.append((inst, judge_instance(text, inst['receipt'], spans))) r0 = insts[0]['receipt'] tps = r0.get('truncation_points') or [] for tp in tps: unit_counter[tp.get('unit', '?')] += 1 reason_counter[tp.get('reason', '?')] += 1 if any(tp.get('unit') == 'rune' for tp in tps): rune_entry_frames += 1 if not tps: frames_no_tp += 1 continue frames_with_tp += 1 inst0, v = verdicts[0] first_file = inst0['file'] if any((x['closed'], x['gap']) != (v['closed'], v['gap']) for _, x in verdicts): anomalies.append({ 'frame_sha8': sha[:8], 'instances': len(insts), 'files': [inst['file'] for inst, _ in verdicts], 'verdicts': [{'file': inst['file'], 'closed': x['closed'], 'gap': x['gap']} for inst, x in verdicts], }) astral_frame_bodies += v['astral_bodies'] if v['closed']: closed_frames += 1 if v['entry_diffs']: anomalies.append({ 'frame_sha8': sha[:8], 'kind': 'compensating-entry-diffs', 'files': [first_file], 'entry_diffs': v['entry_diffs'], }) else: violation_frames += 1 gap_values[v['gap']] += 1 violations.append({ 'sha8': sha[:8], 'bytes_written': r0.get('bytes_written'), 'tpc': v['tp_count'], 'gap_chars': v['gap'], 'claim_chars': v['claim_chars'], 'disk_chars': v['disk_chars'], 'claim_bytes': v['claim_bytes'], 'disk_bytes': v['disk_bytes'], 'file': first_file, 'instances': len(insts), 'entry_diffs': v['entry_diffs'], }) violations.sort(key=lambda x: x['sha8']) max_gap = max(gap_values) if gap_values else 0 file_dedup = len(set(file_shas.values())) calibers = Counter(r.get('caliber', '?') for r in (i['receipt'] for i in instances)) report = { 'corpus': { 'root': ROOT, 'files': len(files), 'file_sha256_dedup': file_dedup, 'read_errors': read_errors, }, 'receipt_lines': { 'prefix_occurrences_total': prefix_occurrences_total, 'body_quote_occurrences_inside_blocks': body_quote_occurrences, 'real_receipt_instances': len(instances), 'unparseable_outside_blocks': unparseable_outside, 'unique_frames_by_line_sha256': len(by_sha), 'tag_unbalanced_files': tag_unbalanced_files, }, 'denominator_frames_with_truncation_points': frames_with_tp, 'frames_without_truncation_points': frames_no_tp, 'closed_frames': closed_frames, 'violation_frames': violation_frames, 'max_gap_chars': max_gap, 'gap_value_distribution': {str(k): gap_values[k] for k in sorted(gap_values)}, 'units_seen': dict(sorted(unit_counter.items())), 'reasons_seen': dict(sorted(reason_counter.items())), 'frames_with_rune_entries': rune_entry_frames, 'truncated_bodies_with_astral_chars': astral_frame_bodies, 'caliber_distribution': dict(sorted(calibers.items())), 'anomalies': anomalies, 'violations': violations, 'criteria': ('分母=含非空 truncation_points 的去重回执帧;闭合=盘上正文(按条目 unit:' 'utf16-char→UTF-16 码元,rune→码点)Σ==Σkept_chars 且 Σutf8字节==Σcut_at_bytes;' '缺口=Σkept_chars−盘上Σ(正=盘上更短)。12-02 修正单位已采用。'), 'repro': 'python3 audit_frames.py → report.json 确定性重生成(无时间戳)', } out_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'report.json') with open(out_path, 'w', encoding='utf-8') as fh: json.dump(report, fh, ensure_ascii=False, sort_keys=True, indent=1) fh.write('\n') print('FILES :', len(files)) print('FILE_SHA_DEDUP :', file_dedup) print('PREFIX_OCCURRENCES :', prefix_occurrences_total) print('BODY_QUOTE_OCCURRENCES :', body_quote_occurrences) print('REAL_RECEIPT_INSTANCES :', len(instances)) print('UNPARSEABLE_OUTSIDE :', len(unparseable_outside)) print('UNIQUE_FRAMES(line sha) :', len(by_sha)) print('TAG_UNBALANCED_FILES :', len(tag_unbalanced_files)) print('READ_ERRORS :', len(read_errors)) print('DENOMINATOR(with tp) :', frames_with_tp) print('CLOSED :', closed_frames) print('VIOLATIONS :', violation_frames) print('MAX_GAP_CHARS :', max_gap) print('GAP_VALUES :', dict(sorted(gap_values.items()))) print('UNITS :', dict(sorted(unit_counter.items()))) print('REASONS :', dict(sorted(reason_counter.items()))) print('RUNE_ENTRY_FRAMES :', rune_entry_frames) print('ANOMALIES :', len(anomalies)) print('CALIBERS :', dict(sorted(calibers.items()))) for v in violations: print('VIOLATION sha8=%s bytes_written=%s tpc=%s gap=%s file=%s' % (v['sha8'], v['bytes_written'], v['tpc'], v['gap_chars'], os.path.basename(v['file']))) if __name__ == '__main__': main()