diff --git a/tools/restore-structs-from-transcript.py b/tools/restore-structs-from-transcript.py new file mode 100644 index 0000000..5f1cd2d --- /dev/null +++ b/tools/restore-structs-from-transcript.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""从 transcript 里取回某个结构体的**最终版定义**,做块级替换。 + +背景(2026-11-09): + 工作区被 `git reset --hard` 抹掉后,从 transcript 重建时出现了**链式依赖**: + 一条 Edit 的 `old_string` 依赖另一条更早的 Edit 的结果, + 精确重放会失配 ⇒ 结构体少了字段 ⇒ 编译报错。 + + 与其继续追链,不如**直接取最终版**: + transcript 里每一次 Edit 的 `new_string` 都带着「那一刻的文件片段」, + 所以只要按时间顺序找**最后一个**包含该结构体完整定义的 `new_string`, + 抽出来整块替换即可。 + +用法: + python3 tools/restore-structs-from-transcript.py \ + --file crates/mpc-tee/src/reconciler.rs \ + --struct PlacedSession --struct PendingSession +""" +import argparse +import json +import os +import sys + + +def iter_calls(path): + with open(path, "r", encoding="utf-8", errors="replace") as fh: + for line in fh: + line = line.strip() + if not line.startswith("{"): + continue + try: + obj = json.loads(line) + except ValueError: + continue + if obj.get("type") != "function_call": + continue + args = obj.get("arguments") + if isinstance(args, str): + try: + args = json.loads(args) + except ValueError: + continue + if isinstance(args, dict): + yield obj.get("timestamp", 0), obj.get("name", ""), args + + +def extract_struct(text, name): + """抽出 `struct { ... }` 整块(大括号配平)。找不到返回 None。""" + i = text.find("struct %s {" % name) + if i < 0: + return None + j = text.index("{", i) + depth = 0 + k = j + while k < len(text): + if text[k] == "{": + depth += 1 + elif text[k] == "}": + depth -= 1 + if depth == 0: + return text[i:k + 1] + k += 1 + return None + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("transcript", nargs="+") + ap.add_argument("--file", required=True, help="要修复的仓库内文件") + ap.add_argument("--struct", action="append", required=True, dest="structs") + ap.add_argument("--repo", default=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + args = ap.parse_args() + + repo = os.path.abspath(args.repo) + target = os.path.abspath(args.file) + if not target.startswith(repo + os.sep): + print("目标不在仓库内: %s" % target, file=sys.stderr) + return 2 + + events = [] + for t in args.transcript: + for ts, name, inp in iter_calls(t): + if name in ("Edit", "Write") and inp.get("file_path") == target: + events.append((ts, name, inp)) + events.sort(key=lambda e: e[0]) + + # 每个结构体取「时间上最后一个能抽到完整定义的片段」 + final = {} + for ts, name, inp in events: + blob = inp.get("content", "") if name == "Write" else inp.get("new_string", "") + for st in args.structs: + seg = extract_struct(blob, st) + if seg: + final[st] = seg + + missing = [s for s in args.structs if s not in final] + if missing: + print("transcript 里找不到这些结构体的完整定义: %s" % ", ".join(missing), file=sys.stderr) + return 3 + + cur = open(target, encoding="utf-8").read() + changed = [] + for st in args.structs: + old_seg = extract_struct(cur, st) + if old_seg is None: + print("当前文件里找不到 struct %s" % st, file=sys.stderr) + return 4 + if old_seg == final[st]: + continue + cur = cur.replace(old_seg, final[st], 1) + changed.append(st) + + open(target, "w", encoding="utf-8").write(cur) + if changed: + print("已替换结构体: %s" % ", ".join(changed)) + else: + print("结构体已是最终版,无需改动") + return 0 + + +if __name__ == "__main__": + sys.exit(main())