Files
Neo-ZQYY/scripts/ops/clean_session_logs.py

95 lines
3.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""清理 docs/audit/session_logs/ 下的旧会话日志文件。
保留:
- _session_index.json重置为空 entries
- _system_prompts/ 目录
删除:
- full_session_*.mdv1 旧格式)
- session_*.mdv1 旧格式)
- 2026-02/ 目录v2 新格式)
- 2026-03/ 目录v2 新格式)
"""
import json
import shutil
import time
from pathlib import Path
from _env_paths import ensure_repo_root
ensure_repo_root()
BASE = Path("docs/audit/session_logs")
def main():
if not BASE.exists():
raise RuntimeError(f"目录不存在: {BASE}")
stats = {
"full_session_md": 0,
"session_md": 0,
"v2_dirs_removed": [],
"v2_files_in_dirs": 0,
}
# 1. 删除 full_session_*.md
for f in sorted(BASE.glob("full_session_*.md")):
f.unlink()
stats["full_session_md"] += 1
# 2. 删除 session_*.md
for f in sorted(BASE.glob("session_*.md")):
f.unlink()
stats["session_md"] += 1
# 3. 删除 v2 日期目录(匹配所有 YYYY-MM 格式的目录)
import re
date_dirs = sorted([d for d in BASE.iterdir() if d.is_dir() and re.match(r"\d{4}-\d{2}$", d.name)])
for d in date_dirs:
if d.exists() and d.is_dir():
# 先删除所有文件
files = sorted(d.rglob("*"), reverse=True)
for f in files:
if f.is_file():
try:
f.unlink()
stats["v2_files_in_dirs"] += 1
except PermissionError:
print(f" ⚠ 无法删除(文件被锁定): {f}")
# 再从深到浅删除空目录
time.sleep(0.2)
dirs = sorted([x for x in d.rglob("*") if x.is_dir()], reverse=True)
for dd in dirs:
try:
dd.rmdir()
except OSError:
print(f" ⚠ 无法删除目录(非空/锁定): {dd}")
try:
d.rmdir()
stats["v2_dirs_removed"].append(d.name)
except OSError:
print(f" ⚠ 无法删除顶层目录: {d}")
stats["v2_dirs_removed"].append(f"{d.name}(部分)")
# 4. 重置 _session_index.json
idx = BASE / "_session_index.json"
if idx.exists():
idx.write_text(json.dumps({"version": 2, "entries": {}}, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"✓ _session_index.json 已重置为空 entries")
else:
print(f"⚠ _session_index.json 不存在,跳过")
# 打印统计
print(f"\n=== 清理统计 ===")
print(f" full_session_*.md 删除: {stats['full_session_md']}")
print(f" session_*.md 删除: {stats['session_md']}")
print(f" v2 目录删除: {', '.join(stats['v2_dirs_removed']) or ''}")
print(f" v2 目录内文件: {stats['v2_files_in_dirs']}")
total = stats["full_session_md"] + stats["session_md"] + stats["v2_files_in_dirs"]
print(f" 总计删除文件: {total}")
print(f"\n保留: _session_index.json, _system_prompts/")
if __name__ == "__main__":
main()