#!/usr/bin/env python3"""@ の取り込みを、エージェントへ渡す前に展開して監査する。base="file" … 取り込み元ファイルからの相対(ネストすると基準が動く)base="root" … プロジェクトルート固定(どこに書いても同じ意味になる)"""import sys, re, os, jsonLIMIT = 24_000 # 1ファイルの上限(展開後の UTF-8 バイト数・2026年11月時点の公式ドキュメント)# 行全体が取り込みのときだけ展開する。本文中の @mention やメールアドレスを巻き込まないため。# 8月に書いた「@path」と、リンク形式の「@[label](path)」の両方を受ける。INCLUDE = re.compile( r'^([ \t]*)@(?:\[[^\]]*\]\(([^)\s]+)\)|([A-Za-z0-9_./\-]+\.(?:md|txt|json)))[ \t]*$')HEADING = re.compile(r'^#{1,6} ')class Cycle(Exception): passdef expand(path, root, base="root", stack=None, stat=None, depth=0, max_depth=16): if stack is None: stack = [] stat = {"count": {}, "missing": []} real = os.path.realpath(os.path.join(root, path)) # realpath で正規化してから比較する。シンボリックリンクや ../ を挟んだ # 別表記の同一ファイルを、別物として通してしまわないため。 if real in stack: chain = [os.path.relpath(p, root) for p in stack[stack.index(real):]] raise Cycle(" -> ".join(chain + [os.path.relpath(real, root)])) if depth > max_depth: raise Cycle(f"{max_depth} 段を超えました: {os.path.relpath(real, root)}") # 見つからないときに空を返さない。規約が黙って消えるのがいちばん危ない。 # 存在しないファイルを「読んだファイル」に数えないよう、数えるのは確認の後。 if not os.path.isfile(real): stat["missing"].append(path) return f"<!-- MISSING INCLUDE: {path} -->\n", stat stat["count"][real] = stat["count"].get(real, 0) + 1 out = [] for line in open(real, encoding="utf-8"): m = INCLUDE.match(line) if not m: out.append(line) continue indent, target = m.group(1), m.group(2) or m.group(3) anchor = "" if base == "root" else os.path.dirname(os.path.relpath(real, root)) child, stat = expand(os.path.normpath(os.path.join(anchor, target)), root, base, stack + [real], stat, depth + 1, max_depth) # 取り込み元のインデントを子側にも伝播させる。箇条書きの途中で # 取り込んだときに、階層が崩れないようにするため。 out.extend(indent + l if l.strip() else l for l in child.splitlines(keepends=True)) return "".join(out), statdef cut_point(text, limit=LIMIT): """上限で切られるとしたら、どの見出しの途中で切れ、どの見出しが丸ごと落ちるか。""" used, current, cut_inside, dropped, in_code = 0, None, None, [], False for line in text.splitlines(keepends=True): if line.lstrip().startswith("```"): in_code = not in_code is_head = bool(not in_code and HEADING.match(line)) if used >= limit: if is_head: dropped.append(line.strip()) elif cut_inside is None and not dropped: cut_inside = current continue if is_head: current = line.strip() used += len(line.encode("utf-8")) if used > limit and cut_inside is None: cut_inside = current return {"cut_inside": cut_inside, "dropped": dropped}def audit(entry, root, base="root"): try: text, stat = expand(entry, root, base) except Cycle as e: return {"entry": entry, "ok": False, "error": f"循環参照: {e}"} size = len(text.encode("utf-8")) result = { "entry": entry, "ok": True, "base": base, "bytes": size, "files": len(stat["count"]), "missing": stat["missing"], "duplicated": {os.path.relpath(p, root): n for p, n in stat["count"].items() if n > 1}, } if size > LIMIT: result["ok"] = False result["over"] = size - LIMIT result.update(cut_point(text)) return resultif __name__ == "__main__": root, base = sys.argv[1], sys.argv[2] bad = False for entry in sys.argv[3:]: r = audit(entry, root, base) bad |= not r["ok"] or bool(r.get("missing")) print(json.dumps(r, ensure_ascii=False)) sys.exit(1 if bad else 0)