agent-project-ops 0.0.0-stage → 1.6.0
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.
- package/CHANGELOG.md +60 -0
- package/LICENSE +21 -0
- package/README.md +149 -3
- package/SECURITY.md +42 -0
- package/VERSION +1 -0
- package/docs/development.md +98 -0
- package/docs/dsh.md +108 -0
- package/docs/entrypoints.md +62 -0
- package/docs/roadmap.md +27 -0
- package/docs/third-party.md +38 -0
- package/package.json +35 -6
- package/scripts/check.py +216 -0
- package/scripts/install.py +131 -0
- package/scripts/status.py +81 -0
- package/skills/agent-project-ops/SKILL.md +122 -0
- package/skills/agent-project-ops/assets/AGENTS.template.md +68 -0
- package/skills/agent-project-ops/assets/GLOBAL-AGENTS.template.md +55 -0
- package/skills/agent-project-ops/assets/HANDOFF.template.md +30 -0
- package/skills/agent-project-ops/assets/WHEEL-MANIFEST.template.json +25 -0
- package/skills/agent-project-ops/assets/WRITING-STYLE.template.md +45 -0
- package/skills/agent-project-ops/references/archetypes.md +126 -0
- package/skills/agent-project-ops/references/maintenance.md +76 -0
- package/skills/agent-project-ops/references/memory.md +65 -0
- package/skills/agent-project-ops/references/principles.md +81 -0
- package/skills/agent-project-ops/references/wheels.md +87 -0
- package/skills/agent-project-ops/references/writing.md +75 -0
- package/skills/agent-project-ops/scripts/agent_doctor.py +448 -0
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""agent_doctor(实验版 / MVP 8 项):只读三态体检。
|
|
3
|
+
|
|
4
|
+
用法:
|
|
5
|
+
python doctor.py --root <项目根> [--vault-root <解析根>] [--json] [--strict]
|
|
6
|
+
python doctor.py --self-test
|
|
7
|
+
|
|
8
|
+
检查:C1 token 预算 / C3 标题 / C5 链接 / C6 索引计数 / C10 敏感信息 /
|
|
9
|
+
C15 全局副本一致 / C16 安全边界 / C17 项目级轮子。
|
|
10
|
+
只报不改;判断项用 --todo 写文件。
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import re
|
|
18
|
+
import subprocess
|
|
19
|
+
import sys
|
|
20
|
+
import tempfile
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
PASS, WARN, FAIL, UNVER = "PASS", "WARN", "FAIL", "UNVERIFIED"
|
|
24
|
+
PLACEHOLDERS = {"文件夹/文件", "另一篇笔记", "再一篇", "...", "xxx", "路径", "文件名"}
|
|
25
|
+
FORBIDDEN = ["rm -rf", "rm -r", "rmdir /s", "rd /s", "del /s", "Remove-Item -Recurse"]
|
|
26
|
+
SENSITIVE_NAME = re.compile(r"(口令|密码|passw|secret|credential|\.env$|auth\.json$|api[_-]?key|private[_-]?key|access[_-]?key)", re.I)
|
|
27
|
+
SENSITIVE_BODY = {
|
|
28
|
+
"private_ip": re.compile(r"\b(?:10\.\d{1,3}|192\.168|172\.(?:1[6-9]|2\d|3[01]))\.\d{1,3}\.\d{1,3}\b"),
|
|
29
|
+
"api_key": re.compile(r"\bsk-[A-Za-z0-9_\-]{12,}"),
|
|
30
|
+
"github_token": re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})"),
|
|
31
|
+
"aws_access_key": re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
|
|
32
|
+
"slack_token": re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,}"),
|
|
33
|
+
"google_api_key": re.compile(r"\bAIza[0-9A-Za-z_\-]{35}\b"),
|
|
34
|
+
"assign_secret": re.compile(r"(?i)\b(password|passwd|pwd|secret|api[_-]?key|private[_-]?key|access[_-]?key)\s*[:=]\s*\S{6,}"),
|
|
35
|
+
}
|
|
36
|
+
POLICY = re.compile(r"(不要|勿|禁止|不得|never|do not|don't|no )", re.I)
|
|
37
|
+
|
|
38
|
+
results: list[tuple[str, str, str]] = []
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def add(level: str, name: str, detail: str = "") -> None:
|
|
42
|
+
results.append((level, name, detail))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def est_tokens(text: str) -> int:
|
|
46
|
+
cjk = len(re.findall(r"[\u4e00-\u9fff]", text))
|
|
47
|
+
ascii_chars = len(re.findall(r"[A-Za-z0-9_]", text))
|
|
48
|
+
words = len(re.findall(r"[A-Za-z0-9_]+", text))
|
|
49
|
+
return int(cjk + max(ascii_chars / 4, words * 1.3))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
SKIP_DIRS = {".git", "__pycache__", "node_modules", "sources", "备份", "archive", "旧&废稿"}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def under_symlink(p: Path, root: Path) -> bool:
|
|
56
|
+
cur = p
|
|
57
|
+
while cur != root and cur != cur.parent:
|
|
58
|
+
if cur.is_symlink() or (hasattr(cur, "is_junction") and cur.is_junction()):
|
|
59
|
+
return True
|
|
60
|
+
cur = cur.parent
|
|
61
|
+
return False
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def md_files(root: Path) -> list[Path]:
|
|
65
|
+
out = []
|
|
66
|
+
for p in root.rglob("*.md"):
|
|
67
|
+
if p.is_symlink() or under_symlink(p, root) or any(part in SKIP_DIRS for part in p.parts):
|
|
68
|
+
continue
|
|
69
|
+
if ".agent" in p.parts and "sources" in p.parts:
|
|
70
|
+
continue
|
|
71
|
+
out.append(p)
|
|
72
|
+
return out
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def strip_fences(text: str) -> str:
|
|
76
|
+
return re.sub(r"(?ms)^```.*?^```", "", text)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def check_c1(root: Path, stop: Path | None = None) -> None:
|
|
80
|
+
chain, cur = [], root.resolve()
|
|
81
|
+
stop = stop.resolve() if stop else None
|
|
82
|
+
while True:
|
|
83
|
+
f = cur / "AGENTS.md"
|
|
84
|
+
if f.exists():
|
|
85
|
+
chain.append(f)
|
|
86
|
+
if cur.parent == cur or (stop and cur == stop) or (cur / ".git").exists():
|
|
87
|
+
break
|
|
88
|
+
cur = cur.parent
|
|
89
|
+
if len(chain) > 6:
|
|
90
|
+
break
|
|
91
|
+
if not chain:
|
|
92
|
+
add(WARN, "C1 常驻预算", "未找到 AGENTS.md")
|
|
93
|
+
return
|
|
94
|
+
total = sum(est_tokens(f.read_text(encoding="utf-8", errors="replace")) for f in chain)
|
|
95
|
+
names = " + ".join(f.name for f in chain)
|
|
96
|
+
if total > 5000:
|
|
97
|
+
add(FAIL, "C1 常驻预算", f"{total} tokens > 5000({names});删/并/拆后再跑")
|
|
98
|
+
elif total > 2000:
|
|
99
|
+
add(WARN, "C1 常驻预算", f"{total} tokens > 2000({names});删/并/拆后再跑")
|
|
100
|
+
else:
|
|
101
|
+
add(PASS, "C1 常驻预算", f"{total} tokens({names})")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def check_c3(root: Path) -> None:
|
|
105
|
+
glued, dups = [], []
|
|
106
|
+
for f in md_files(root):
|
|
107
|
+
text = strip_fences(f.read_text(encoding="utf-8", errors="replace"))
|
|
108
|
+
seen = {}
|
|
109
|
+
for i, line in enumerate(text.splitlines(), 1):
|
|
110
|
+
s = line.strip()
|
|
111
|
+
if re.match(r"^#{1,4}\s", s):
|
|
112
|
+
if re.search(r"^#{1,4}\s.*#{1,4}\s", s):
|
|
113
|
+
glued.append(f"{f.relative_to(root)}:{i}")
|
|
114
|
+
if s in seen and len(s) > 3:
|
|
115
|
+
dups.append(f"{f.relative_to(root)}:{i}(首次 L{seen[s]})")
|
|
116
|
+
seen.setdefault(s, i)
|
|
117
|
+
if glued:
|
|
118
|
+
add(FAIL, "C3 标题", "粘连:" + "; ".join(glued[:3]))
|
|
119
|
+
elif dups:
|
|
120
|
+
add(WARN, "C3 标题", "重复标题:" + "; ".join(dups[:3]))
|
|
121
|
+
else:
|
|
122
|
+
add(PASS, "C3 标题", "无粘连/重复标题")
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def build_index(vault: Path) -> dict[str, list[Path]]:
|
|
126
|
+
idx: dict[str, list[Path]] = {}
|
|
127
|
+
for p in vault.rglob("*"):
|
|
128
|
+
if not p.is_file() or any(part in {".git", "node_modules", "__pycache__"} for part in p.parts):
|
|
129
|
+
continue
|
|
130
|
+
idx.setdefault(p.name, []).append(p)
|
|
131
|
+
idx.setdefault(p.stem, []).append(p)
|
|
132
|
+
return idx
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def resolve_link(link: str, root: Path, vault: Path, idx: dict[str, list[Path]]) -> bool:
|
|
136
|
+
for base in (root, vault):
|
|
137
|
+
if (base / link).exists() or (base / (link + ".md")).exists():
|
|
138
|
+
return True
|
|
139
|
+
name = Path(link).name
|
|
140
|
+
return bool(idx.get(name) or idx.get(Path(link).stem))
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def check_c5(root: Path, vault: Path) -> None:
|
|
144
|
+
idx = build_index(vault)
|
|
145
|
+
broken, total = [], 0
|
|
146
|
+
for f in md_files(root):
|
|
147
|
+
text = strip_fences(f.read_text(encoding="utf-8", errors="replace"))
|
|
148
|
+
for m in re.findall(r"!?\[\[([^\]]+)\]\]", text):
|
|
149
|
+
link = m.split("|")[0].split("#")[0].strip()
|
|
150
|
+
if (not link or link in PLACEHOLDERS or link.startswith("http") or "{{" in link
|
|
151
|
+
or any(x in link for x in ("...", "xxx", "类文件", "示例", "你的", "foo", "bar"))):
|
|
152
|
+
continue
|
|
153
|
+
total += 1
|
|
154
|
+
if not resolve_link(link, root, vault, idx):
|
|
155
|
+
broken.append(f"{f.relative_to(root)} -> {link}")
|
|
156
|
+
if broken:
|
|
157
|
+
add(FAIL, "C5 链接", f"{len(broken)}/{total} 断链:{'; '.join(broken[:3])}")
|
|
158
|
+
else:
|
|
159
|
+
add(PASS, "C5 链接", f"{total} 条链接均可解析")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def check_c6(root: Path) -> None:
|
|
163
|
+
checks = []
|
|
164
|
+
for f in md_files(root):
|
|
165
|
+
if f.parent != root and not re.search(r"(索引|目录|生词本)", f.name):
|
|
166
|
+
continue
|
|
167
|
+
text = f.read_text(encoding="utf-8", errors="replace")
|
|
168
|
+
m = (re.search(r"共\s*(\d+)\s*(篇|词|条)", text)
|
|
169
|
+
or re.search(r"(?m)^>?\s*(\d+)\s*(词|篇|条)\s*·", text))
|
|
170
|
+
if not m:
|
|
171
|
+
continue
|
|
172
|
+
declared = int(m.group(1))
|
|
173
|
+
unit = m.group(2) if m.lastindex and m.lastindex >= 2 else None
|
|
174
|
+
if not unit:
|
|
175
|
+
continue
|
|
176
|
+
if unit == "篇":
|
|
177
|
+
base = root / "笔记"
|
|
178
|
+
actual = len(list(base.glob("*.md"))) if base.exists() else len([p for p in root.glob("*.md") if p.name != f.name])
|
|
179
|
+
elif unit == "词":
|
|
180
|
+
base = root / "分类"
|
|
181
|
+
actual = len(re.findall(r"(?m)^### ", "\n".join(p.read_text(encoding="utf-8", errors="replace") for p in base.glob("*.md")))) if base.exists() else 0
|
|
182
|
+
else:
|
|
183
|
+
actual = len(list(root.rglob("*.md")))
|
|
184
|
+
checks.append((declared == actual, f"{f.name}: 声明 {declared}{unit} / 实际 {actual}"))
|
|
185
|
+
if not checks:
|
|
186
|
+
add(UNVER, "C6 索引计数", "未找到「共 N 篇/词/条」标记")
|
|
187
|
+
elif all(c[0] for c in checks):
|
|
188
|
+
add(PASS, "C6 索引计数", checks[0][1])
|
|
189
|
+
else:
|
|
190
|
+
add(FAIL, "C6 索引计数", "; ".join(c[1] for c in checks if not c[0]))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def scrub(s: str) -> str:
|
|
194
|
+
s = re.sub(r"sk-[A-Za-z0-9_\-]{6,}", "sk-***", s)
|
|
195
|
+
s = re.sub(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", "x.x.x.x", s)
|
|
196
|
+
return re.sub(r"(?i)(password|token|secret)\s*[:=]\s*\S+", r"\1=***", s)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def git_tracked(root: Path, rel: str) -> bool | None:
|
|
200
|
+
try:
|
|
201
|
+
out = subprocess.run(["git", "-c", "core.quotepath=false", "ls-files", "--", rel], cwd=root,
|
|
202
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=20)
|
|
203
|
+
if out.returncode != 0:
|
|
204
|
+
return None
|
|
205
|
+
return bool(out.stdout.strip())
|
|
206
|
+
except Exception:
|
|
207
|
+
return None
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def check_c10(root: Path, vault: Path) -> None:
|
|
211
|
+
hard, soft = [], []
|
|
212
|
+
skip = {".git", "__pycache__", "node_modules", ".cache", "sessions", "web-search-cache", "dist", "build"}
|
|
213
|
+
for f in root.rglob("*"):
|
|
214
|
+
if not f.is_file() or f.is_symlink() or under_symlink(f, root) or any(part in skip for part in f.parts):
|
|
215
|
+
continue
|
|
216
|
+
rel = str(f.relative_to(root))
|
|
217
|
+
if f.name == "auth.json":
|
|
218
|
+
continue
|
|
219
|
+
if SENSITIVE_NAME.search(f.name):
|
|
220
|
+
tracked = git_tracked(root, rel)
|
|
221
|
+
(hard if tracked else soft).append(rel)
|
|
222
|
+
for f in md_files(root):
|
|
223
|
+
text = strip_fences(f.read_text(encoding="utf-8", errors="replace"))
|
|
224
|
+
for name, pat in SENSITIVE_BODY.items():
|
|
225
|
+
for m in pat.finditer(text):
|
|
226
|
+
line_start = text.rfind(chr(10), 0, m.start()) + 1
|
|
227
|
+
line = text[line_start:text.find(chr(10), m.end())]
|
|
228
|
+
if POLICY.search(line):
|
|
229
|
+
continue
|
|
230
|
+
val = m.group(0).split(":", 1)[-1].split("=", 1)[-1].strip()
|
|
231
|
+
if val.startswith(("--", "<", "{{", "***")) or any(x in val.lower() for x in ("example", "your", "xxx", "...")):
|
|
232
|
+
continue
|
|
233
|
+
hard.append(f"{f.relative_to(root)}:{text[:m.start()].count(chr(10)) + 1}({name})")
|
|
234
|
+
if hard:
|
|
235
|
+
add(FAIL, "C10 敏感信息", "; ".join(hard[:5]))
|
|
236
|
+
elif soft:
|
|
237
|
+
add(WARN, "C10 敏感信息", "本地敏感文件(未跟踪):" + "; ".join(soft[:5]))
|
|
238
|
+
else:
|
|
239
|
+
add(PASS, "C10 敏感信息", "无敏感文件名/内容")
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def body_hash(p: Path) -> str:
|
|
243
|
+
lines = p.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
244
|
+
body = "\n".join(line for line in lines if not line.startswith("<!--"))
|
|
245
|
+
return hashlib.sha256(body.encode("utf-8")).hexdigest()
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def check_c15(a: Path | None, b: Path | None) -> None:
|
|
249
|
+
if not a or not b or not a.exists() or not b.exists():
|
|
250
|
+
add(UNVER, "C15 全局副本", "未提供两份全局文件")
|
|
251
|
+
elif body_hash(a) == body_hash(b):
|
|
252
|
+
add(PASS, "C15 全局副本", "两份正文一致")
|
|
253
|
+
else:
|
|
254
|
+
add(FAIL, "C15 全局副本", "两份正文不一致")
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def check_c16(root: Path) -> None:
|
|
258
|
+
agents = root / "AGENTS.md"
|
|
259
|
+
text = agents.read_text(encoding="utf-8", errors="replace") if agents.exists() else ""
|
|
260
|
+
missing = [s for s in FORBIDDEN if s not in text]
|
|
261
|
+
a = PASS if not missing else WARN
|
|
262
|
+
detail = "硬禁区齐全" if not missing else "缺:" + ", ".join(missing[:3])
|
|
263
|
+
# tracked sensitive files
|
|
264
|
+
try:
|
|
265
|
+
out = subprocess.run(["git", "-c", "core.quotepath=false", "ls-files"], cwd=root,
|
|
266
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30)
|
|
267
|
+
tracked = out.stdout.splitlines() if out.returncode == 0 else None
|
|
268
|
+
except Exception:
|
|
269
|
+
tracked = None
|
|
270
|
+
if tracked is None:
|
|
271
|
+
b = UNVER
|
|
272
|
+
bd = "无 git,无法判断跟踪状态"
|
|
273
|
+
else:
|
|
274
|
+
bad = [x for x in tracked if SENSITIVE_NAME.search(Path(x).name)]
|
|
275
|
+
b = FAIL if bad else PASS
|
|
276
|
+
bd = f"跟踪敏感文件 {len(bad)} 个" if bad else "无敏感文件被跟踪"
|
|
277
|
+
# backup/rollback
|
|
278
|
+
has_git = any((cur / ".git").exists() for cur in [root, *root.parents][:6])
|
|
279
|
+
c = PASS if has_git or (root / ".agent" / "备份").exists() or (root / "_backup").exists() else WARN
|
|
280
|
+
cd = "有回滚(git/备份)" if c == PASS else "未发现 git/备份目录"
|
|
281
|
+
level = FAIL if FAIL in (a, b, c) else (UNVER if UNVER in (a, b, c) else (WARN if WARN in (a, b, c) else PASS))
|
|
282
|
+
add(level, "C16 安全边界", f"{detail};{bd};{cd}")
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def check_c17(root: Path) -> None:
|
|
286
|
+
"""项目级轮子:有 .agent/tools/ 就必须有可复现清单与 gitignore。"""
|
|
287
|
+
tools = root / ".agent" / "tools"
|
|
288
|
+
if not tools.exists() or not any(tools.iterdir()):
|
|
289
|
+
add(PASS, "C17 项目级轮子", "无项目级工具目录")
|
|
290
|
+
return
|
|
291
|
+
lock = root / ".agent" / "tools.lock.json"
|
|
292
|
+
if not lock.exists():
|
|
293
|
+
add(WARN, "C17 项目级轮子", "有 .agent/tools/ 但缺 .agent/tools.lock.json")
|
|
294
|
+
return
|
|
295
|
+
try:
|
|
296
|
+
data = json.loads(lock.read_text(encoding="utf-8-sig"))
|
|
297
|
+
except Exception as e:
|
|
298
|
+
add(FAIL, "C17 项目级轮子", f"lockfile 无法解析:{e}")
|
|
299
|
+
return
|
|
300
|
+
entries = data.get("tools") or []
|
|
301
|
+
if not entries:
|
|
302
|
+
add(WARN, "C17 项目级轮子", "lockfile 没有 tools 条目")
|
|
303
|
+
return
|
|
304
|
+
missing, bad = [], []
|
|
305
|
+
for t in entries:
|
|
306
|
+
name = t.get("name", "?")
|
|
307
|
+
for k in ("source", "commit", "license", "sha256", "scope"):
|
|
308
|
+
if not t.get(k):
|
|
309
|
+
missing.append(f"{name}:{k}")
|
|
310
|
+
for rel, digest in (t.get("sha256") or {}).items():
|
|
311
|
+
f = tools / rel
|
|
312
|
+
if not f.exists():
|
|
313
|
+
bad.append(f"{name}:{rel} 缺失")
|
|
314
|
+
elif hashlib.sha256(f.read_bytes()).hexdigest() != str(digest).lower():
|
|
315
|
+
bad.append(f"{name}:{rel} sha256 不符")
|
|
316
|
+
gi = root / ".gitignore"
|
|
317
|
+
ignored = gi.exists() and ".agent/tools/" in gi.read_text(encoding="utf-8", errors="replace")
|
|
318
|
+
if missing or bad:
|
|
319
|
+
add(FAIL, "C17 项目级轮子", ";".join((missing + bad)[:5]))
|
|
320
|
+
elif not ignored:
|
|
321
|
+
add(WARN, "C17 项目级轮子", "lockfile 有,但 .gitignore 未忽略 .agent/tools/")
|
|
322
|
+
else:
|
|
323
|
+
add(PASS, "C17 项目级轮子", f"{len(entries)} 个工具,sha256/gitignore 均通过")
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def run(root: Path, vault: Path, ga: Path | None, gb: Path | None, todo: Path | None,
|
|
327
|
+
as_json: bool = False) -> int:
|
|
328
|
+
for fn in (lambda: check_c1(root, vault), lambda: check_c3(root), lambda: check_c5(root, vault),
|
|
329
|
+
lambda: check_c6(root), lambda: check_c10(root, vault),
|
|
330
|
+
lambda: check_c15(ga, gb), lambda: check_c16(root), lambda: check_c17(root)):
|
|
331
|
+
fn()
|
|
332
|
+
fails = sum(1 for r in results if r[0] == FAIL)
|
|
333
|
+
warns = sum(1 for r in results if r[0] == WARN)
|
|
334
|
+
unver = sum(1 for r in results if r[0] == UNVER)
|
|
335
|
+
summary = {"pass": len(results) - fails - warns - unver, "warn": warns, "fail": fails,
|
|
336
|
+
"unverified": unver}
|
|
337
|
+
if as_json:
|
|
338
|
+
print(json.dumps({"results": [{"level": lv, "name": nm, "detail": dt} for lv, nm, dt in results],
|
|
339
|
+
"summary": summary}, ensure_ascii=False, indent=2))
|
|
340
|
+
else:
|
|
341
|
+
for level, name, detail in results:
|
|
342
|
+
print(f"[{level:10s}] {name}: {detail}")
|
|
343
|
+
print(f"\nPASS {summary['pass']} WARN {warns} FAIL {fails} UNVERIFIED {unver}")
|
|
344
|
+
if todo:
|
|
345
|
+
todo.write_text("# todo(需要人判断)\n\n" + "\n".join(
|
|
346
|
+
f"- [{lv}] {nm}: {dt}" for lv, nm, dt in results if lv in (WARN, UNVER)) + "\n", encoding="utf-8")
|
|
347
|
+
return 1 if fails else 0
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def self_test() -> int:
|
|
351
|
+
ok = True
|
|
352
|
+
with tempfile.TemporaryDirectory() as td:
|
|
353
|
+
root = Path(td)
|
|
354
|
+
(root / "AGENTS.md").write_text("长" * 2500, encoding="utf-8")
|
|
355
|
+
(root / "00 索引.md").write_text("共 5 篇\n\n[[笔记/甲]]\n[[笔记/缺失]]\n[[文件夹/文件]]\n", encoding="utf-8")
|
|
356
|
+
(root / "笔记").mkdir()
|
|
357
|
+
(root / "笔记" / "甲.md").write_text("# 甲\n\n## 现状## 现状\n", encoding="utf-8")
|
|
358
|
+
(root / "配置.md").write_text("sk-test-abcdef0123456789\nghp_" + "a" * 30 + "\n", encoding="utf-8")
|
|
359
|
+
global results
|
|
360
|
+
results = []
|
|
361
|
+
run(root, root, None, None, None)
|
|
362
|
+
got = {nm: lv for lv, nm, _ in results}
|
|
363
|
+
expect = {"C1 常驻预算": WARN, "C3 标题": FAIL, "C5 链接": FAIL, "C6 索引计数": FAIL,
|
|
364
|
+
"C10 敏感信息": FAIL, "C15 全局副本": UNVER}
|
|
365
|
+
for k, v in expect.items():
|
|
366
|
+
if got.get(k) != v:
|
|
367
|
+
print(f"SELFTEST MISMATCH {k}: got {got.get(k)} want {v}")
|
|
368
|
+
ok = False
|
|
369
|
+
c10_detail = next((d for _, n, d in results if n == "C10 敏感信息"), "")
|
|
370
|
+
if "github_token" not in c10_detail:
|
|
371
|
+
print("SELFTEST MISMATCH C10: github_token prefix not detected")
|
|
372
|
+
ok = False
|
|
373
|
+
results = []
|
|
374
|
+
clean = root / "clean"
|
|
375
|
+
clean.mkdir()
|
|
376
|
+
(clean / "AGENTS.md").write_text("禁止 rm -rf / Remove-Item -Recurse / del /s\n", encoding="utf-8")
|
|
377
|
+
(clean / "00 索引.md").write_text("共 1 篇\n\n[[笔记/甲]]\n", encoding="utf-8")
|
|
378
|
+
(clean / "笔记").mkdir()
|
|
379
|
+
(clean / "笔记" / "甲.md").write_text("# 甲\n\n不要记录口令。\n", encoding="utf-8")
|
|
380
|
+
(clean / ".agent" / "备份").mkdir(parents=True)
|
|
381
|
+
run(clean, clean, None, None, None)
|
|
382
|
+
got = {nm: lv for lv, nm, _ in results}
|
|
383
|
+
for k, v in {"C3 标题": PASS, "C5 链接": PASS, "C6 索引计数": PASS,
|
|
384
|
+
"C10 敏感信息": PASS, "C15 全局副本": UNVER}.items():
|
|
385
|
+
if got.get(k) != v:
|
|
386
|
+
print(f"SELFTEST MISMATCH clean {k}: got {got.get(k)} want {v}")
|
|
387
|
+
ok = False
|
|
388
|
+
import hashlib as _h
|
|
389
|
+
wheel = root / "wheel"
|
|
390
|
+
(wheel / ".agent" / "tools").mkdir(parents=True)
|
|
391
|
+
(wheel / ".agent" / "tools" / "x.py").write_text("print(1)", encoding="utf-8")
|
|
392
|
+
results = []
|
|
393
|
+
run(wheel, wheel, None, None, None)
|
|
394
|
+
if next((lv for lv, nm, _ in results if nm == "C17 项目级轮子"), None) != WARN:
|
|
395
|
+
print("SELFTEST MISMATCH C17: missing lockfile should WARN")
|
|
396
|
+
ok = False
|
|
397
|
+
digest = _h.sha256((wheel / ".agent" / "tools" / "x.py").read_bytes()).hexdigest()
|
|
398
|
+
(wheel / ".agent" / "tools.lock.json").write_text(json.dumps({"tools": [{
|
|
399
|
+
"name": "x", "source": "local", "commit": "1", "license": "MIT",
|
|
400
|
+
"sha256": {"x.py": digest}, "scope": "read-only"}]}), encoding="utf-8")
|
|
401
|
+
(wheel / ".gitignore").write_text(".agent/tools/", encoding="utf-8")
|
|
402
|
+
results = []
|
|
403
|
+
run(wheel, wheel, None, None, None)
|
|
404
|
+
if next((lv for lv, nm, _ in results if nm == "C17 项目级轮子"), None) != PASS:
|
|
405
|
+
print("SELFTEST MISMATCH C17: valid lock should PASS")
|
|
406
|
+
ok = False
|
|
407
|
+
(wheel / ".agent" / "tools" / "x.py").write_text("print(2)", encoding="utf-8")
|
|
408
|
+
results = []
|
|
409
|
+
run(wheel, wheel, None, None, None)
|
|
410
|
+
if next((lv for lv, nm, _ in results if nm == "C17 项目级轮子"), None) != FAIL:
|
|
411
|
+
print("SELFTEST MISMATCH C17: sha mismatch should FAIL")
|
|
412
|
+
ok = False
|
|
413
|
+
|
|
414
|
+
print("SELFTEST", "OK" if ok else "FAILED")
|
|
415
|
+
return 0 if ok else 1
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def main() -> int:
|
|
419
|
+
ap = argparse.ArgumentParser()
|
|
420
|
+
ap.add_argument("--root")
|
|
421
|
+
ap.add_argument("--vault-root")
|
|
422
|
+
ap.add_argument("--global-a")
|
|
423
|
+
ap.add_argument("--global-b")
|
|
424
|
+
ap.add_argument("--todo")
|
|
425
|
+
ap.add_argument("--json", action="store_true")
|
|
426
|
+
ap.add_argument("--strict", action="store_true")
|
|
427
|
+
ap.add_argument("--self-test", action="store_true")
|
|
428
|
+
a = ap.parse_args()
|
|
429
|
+
if a.self_test:
|
|
430
|
+
return self_test()
|
|
431
|
+
if not a.root:
|
|
432
|
+
ap.error("--root 或 --self-test")
|
|
433
|
+
root = Path(a.root).resolve()
|
|
434
|
+
vault = Path(a.vault_root).resolve() if a.vault_root else root
|
|
435
|
+
ga = Path(a.global_a) if a.global_a else None
|
|
436
|
+
gb = Path(a.global_b) if a.global_b else None
|
|
437
|
+
code = run(root, vault, ga, gb, Path(a.todo) if a.todo else None, as_json=a.json)
|
|
438
|
+
if a.strict and any(r[0] == WARN for r in results):
|
|
439
|
+
code = 1
|
|
440
|
+
return code
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
if __name__ == "__main__":
|
|
444
|
+
try:
|
|
445
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
446
|
+
except Exception:
|
|
447
|
+
pass
|
|
448
|
+
sys.exit(main())
|