mtkit 1.16.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mtkit/evolve.py ADDED
@@ -0,0 +1,142 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Self-evolution support: deterministic backup/rollback for tool self-modification.
4
+
5
+ Backup dir: <project>/.mtkit-work/backup/<timestamp>/
6
+ - backup: snapshot file contents under the backup dir, manifest maps original -> backup
7
+ - restore: restore a file from its most recent backup via manifest lookup (overwrite)
8
+ - list/prune: inspect and clean old backups
9
+
10
+ Self-iteration protocol requires: backup before modifying, restore when verification fails.
11
+ """
12
+ import json
13
+ import os
14
+ import shutil
15
+ from datetime import datetime
16
+
17
+ BACKUP_DIR_NAME = "backup"
18
+ WORK_DIR_NAME = ".mtkit-work"
19
+ _MANIFEST_NAME = "manifest.json"
20
+
21
+
22
+ def _find_workdir(start_dir=None):
23
+ """Find .mtkit-work upward from start_dir, fallback to cwd/.mtkit-work."""
24
+ current = os.path.abspath(start_dir or os.getcwd())
25
+ while True:
26
+ candidate = os.path.join(current, WORK_DIR_NAME)
27
+ if os.path.isdir(candidate):
28
+ return candidate
29
+ parent = os.path.dirname(current)
30
+ if parent == current:
31
+ break
32
+ current = parent
33
+ return os.path.join(os.getcwd(), WORK_DIR_NAME)
34
+
35
+
36
+ def _backup_root(workdir=None):
37
+ return os.path.join(workdir or _find_workdir(), BACKUP_DIR_NAME)
38
+
39
+
40
+ def backup_files(files, workdir=None):
41
+ """Snapshot file contents into a new timestamped backup dir, return backup dir path."""
42
+ if not files:
43
+ raise ValueError("缺少待备份文件(backup 需要至少一个文件参数)")
44
+ root = _backup_root(workdir)
45
+ stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
46
+ backup_dir = os.path.join(root, stamp)
47
+ # same-second collision: append a sequence suffix
48
+ suffix = 1
49
+ while os.path.isdir(backup_dir):
50
+ backup_dir = os.path.join(root, "%s-%d" % (stamp, suffix))
51
+ suffix += 1
52
+ os.makedirs(backup_dir, exist_ok=True)
53
+ manifest = {"created_at": stamp, "files": []}
54
+ for index, path in enumerate(files):
55
+ if not os.path.isfile(path):
56
+ raise ValueError("文件不存在: %s" % path)
57
+ basename = os.path.basename(path)
58
+ # same-name files get a sequence suffix, manifest keeps the mapping
59
+ target_name = basename if index == 0 or basename not in [f["backup_name"] for f in manifest["files"]] else "%s-%d" % (basename, index)
60
+ target = os.path.join(backup_dir, target_name)
61
+ shutil.copy2(path, target)
62
+ manifest["files"].append({"original": path, "backup": target, "backup_name": target_name})
63
+ with open(os.path.join(backup_dir, _MANIFEST_NAME), "w", encoding="utf-8") as fp:
64
+ json.dump(manifest, fp, ensure_ascii=False, indent=2)
65
+ return backup_dir
66
+
67
+
68
+ def _read_manifest(backup_dir):
69
+ path = os.path.join(backup_dir, _MANIFEST_NAME)
70
+ if not os.path.isfile(path):
71
+ return None
72
+ with open(path, "r", encoding="utf-8-sig") as fp:
73
+ return json.load(fp)
74
+
75
+
76
+ def restore_file(path, workdir=None):
77
+ """Restore a file from its most recent backup via manifest lookup (overwrite)."""
78
+ root = _backup_root(workdir)
79
+ if not os.path.isdir(root):
80
+ raise ValueError("未找到备份: %s" % path)
81
+ stamps = sorted(
82
+ (d for d in os.listdir(root) if os.path.isdir(os.path.join(root, d))),
83
+ reverse=True,
84
+ )
85
+ for stamp in stamps:
86
+ backup_dir = os.path.join(root, stamp)
87
+ manifest = _read_manifest(backup_dir) or {}
88
+ for entry in manifest.get("files") or []:
89
+ if os.path.normpath(entry.get("original") or "") == os.path.normpath(path):
90
+ backup_path = entry["backup"]
91
+ if os.path.isfile(backup_path):
92
+ directory = os.path.dirname(os.path.abspath(path))
93
+ if not os.path.isdir(directory):
94
+ os.makedirs(directory, exist_ok=True)
95
+ shutil.copy2(backup_path, path)
96
+ return backup_path
97
+ # fallback: same basename without manifest mapping
98
+ basename = os.path.basename(path)
99
+ fallback = os.path.join(backup_dir, basename)
100
+ if os.path.isfile(fallback):
101
+ directory = os.path.dirname(os.path.abspath(path))
102
+ if not os.path.isdir(directory):
103
+ os.makedirs(directory, exist_ok=True)
104
+ shutil.copy2(fallback, path)
105
+ return fallback
106
+ raise ValueError("未找到备份: %s" % path)
107
+
108
+
109
+ def list_backups(workdir=None):
110
+ """List backup snapshots (stamp -> files)."""
111
+ root = _backup_root(workdir)
112
+ if not os.path.isdir(root):
113
+ return []
114
+ results = []
115
+ for stamp in sorted(os.listdir(root), reverse=True):
116
+ backup_dir = os.path.join(root, stamp)
117
+ if not os.path.isdir(backup_dir):
118
+ continue
119
+ manifest = _read_manifest(backup_dir) or {}
120
+ files = [entry.get("original") for entry in manifest.get("files") or []]
121
+ if not files:
122
+ files = sorted(
123
+ name for name in os.listdir(backup_dir)
124
+ if os.path.isfile(os.path.join(backup_dir, name))
125
+ )
126
+ results.append({"stamp": stamp, "files": files})
127
+ return results
128
+
129
+
130
+ def prune_backups(keep=10, workdir=None):
131
+ """Remove oldest backup snapshots, keeping the most recent N."""
132
+ root = _backup_root(workdir)
133
+ if not os.path.isdir(root):
134
+ return 0
135
+ stamps = sorted(
136
+ d for d in os.listdir(root) if os.path.isdir(os.path.join(root, d))
137
+ )
138
+ removed = 0
139
+ for stamp in stamps[:-keep] if keep > 0 else stamps:
140
+ shutil.rmtree(os.path.join(root, stamp), ignore_errors=True)
141
+ removed += 1
142
+ return removed
@@ -0,0 +1,17 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ 提取层:从输入素材中抽取结构化事实,供用例生成使用。
4
+
5
+ - docx_loader :技术方案 .docx 解析(章节/段落/表格/功能点)
6
+ - xmind_loader:历史用例 .xmind 解析(骨架提取/风格样例)
7
+ - code_facts :代码仓库扫描(接口清单/SQL 字典/存储过程)
8
+ """
9
+ from .docx_loader import load_docx
10
+ from .xmind_loader import extract_style_sample, load_xmind_tree, skeleton_from_hist
11
+
12
+ __all__ = [
13
+ "load_docx",
14
+ "load_xmind_tree",
15
+ "skeleton_from_hist",
16
+ "extract_style_sample",
17
+ ]