Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(tests): 提前识别受限工具执行环境

longmeidao2d6fdef79f79
diff --git a/.claude/skills/peach-shell-commands/SKILL.md b/.claude/skills/peach-shell-commands/SKILL.md
index a1405846e..eb2c85376 100644
--- a/.claude/skills/peach-shell-commands/SKILL.md
+++ b/.claude/skills/peach-shell-commands/SKILL.md
@@ -5,10 +5,10 @@ description: 在写 PowerShell 或 Bash 命令、拼多行内容、用 rg 或 Py
# 命令与路径的形态
-最后复核:2026-09-08
+最后复核:2026-09-20
证据来源:`tests/test_agent_worktree.py` 与 `tests/test_scripts.py` 里临时目录 `.resolve()`
和正斜杠路径的注释、`scripts/test.ps1` 与 `scripts/test.sh` 的编码约定、Git 历史里被
-heredoc 转义损坏的那几次补丁。
+heredoc 转义损坏的那几次补丁,以及 `scripts/test_runner.py` 的外部工具预检。
## 何时使用
@@ -25,6 +25,19 @@ heredoc 转义损坏的那几次补丁。
- Python CLI 加 `-X utf8`;PowerShell 读 UTF-8 日志显式加 `-Encoding utf8`。编码要在输出端
固定,只给读取端指定编码挡不住乱码。
+## Windows Codex 沙箱
+
+- `windows.sandbox = "elevated"` 是隔离模式,不是管理员权限。项目测试、npm/PyInstaller 构建、
+ Git common directory 写入需要正常 PowerShell 权限时,从第一次调用就用受控提权和窄命令前缀;
+ 不先在沙箱里制造一次 `WinError 5`。
+- `_winapi.CreateProcess` 或 `.git/**/index.lock` 返回拒绝访问时,原样重跑统一入口;不拆成单测、
+ 不改断言、不跳过用例。`scripts/test.ps1` 会在分片前报告无法启动的外部工具。
+- `danger-full-access` 是取消隔离,不是“提权沙箱”。除非用户明确要求承担全局风险,否则保留沙箱,
+ 只给当前项目入口所需的命令授权。
+- Windows 全量测试若外套 `resource_run.py`,给 `scripts/test.ps1` 传 `-Jobs 1`;外层 Job Object
+ 与入口的四路并发叠加会让 Git Bash、Python 和临时 Git 进程出现 I/O 或进程创建错误。
+ npm/PyInstaller、FFmpeg 与媒体批处理仍按资源预算使用外层守卫。
+
## 多行内容一律落盘
多行内容用写入工具或脚本文件落盘,再让命令读那个文件,不要用 heredoc。反斜杠会被吃掉一层,
diff --git a/.claude/skills/peach-worktree/SKILL.md b/.claude/skills/peach-worktree/SKILL.md
index 191395e9e..1167afebd 100644
--- a/.claude/skills/peach-worktree/SKILL.md
+++ b/.claude/skills/peach-worktree/SKILL.md
@@ -5,19 +5,20 @@ description: 在用户说并行、工作树、暂存、提交、ready、集成
# 并行 worktree 与提交边界
-最后复核:2026-09-19
-证据来源:`docs/HANDOFF.md`「并行智能体与 Git 工作树」、`README.md`、ADR-0015、ADR-0017、2026-09-19 本机会话工具记录。
+最后复核:2026-09-20
+证据来源:`docs/HANDOFF.md`「并行智能体与 Git 工作树」、`README.md`、ADR-0015、ADR-0017、本机工作树与沙箱工具记录。
## 是否委派与何时使用
-
单一功能域、局部改动或预计 30 分钟内完成的任务,由协调者在自己的隔离工作树直接完成;只有任务可独立并行、需要隔离环境,或长跑过程能明确缩短总耗时才委派。
默认最多一个工作者;多个工作者只用于彼此无依赖的任务。委派只传目标、相关文件、边界和验收命令,不转交完整对话。
协调者只在完成、阻塞或至少五分钟的检查点读取状态,不做分钟级轮询,也不重复工作者完成的搜索、浏览器检查和测试。
任何会写入当前机器 `peach-app` 的代码任务都使用隔离工作树。主目录只做集成,不做并行编辑;worktree 本机重建,不跨机器复制目录。
## 流程
-
1. 协调者在主目录创建隔离工作树:`& .\.venv\Scripts\python.exe -X utf8 scripts\agent_worktree.py create --agent claude --task <task>`。它建在 `peach-worktrees/`,Codex 和 Claude 共用这一个目录。**不要用 Claude Code 内置的工作树机制(`.claude/worktrees/`)**:它在分支被集成后会被回收,目录却留在原地。
+ Windows Codex 对 `create`/`ready`/`integrate`/`prune --apply`、`git add` 与 `git commit`
+ 从第一次调用就按 `peach-shell-commands` 的沙箱规则使用受控提权;它们会写主检出的
+ Git common directory,工作树目录可写不代表 `.git/worktrees/**` 可写。
2. 工作者只在自己的工作树内编辑。`create` 自动锁定工作树,成功集成后解锁;不复制 `.venv`;用 `uv sync --locked --all-extras` 创建自己的测试环境。
3. 测试在当前工作树根目录运行:Windows `& .\scripts\test.ps1`,macOS/Linux `./scripts/test.sh`。默认 `auto` 按改动文件取影响域并集;文档及无改动检查 `checks`,未知影响面、共享测试设施和实际依赖选 `full`。域清单唯一真相在 `scripts/test_runner.py`;局部调试可显式选域。
diff --git a/docs/TESTING.md b/docs/TESTING.md
index d40923213..9f0475be0 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -66,11 +66,15 @@ macOS 按影响域验证:
显式全量用 Windows `-Scope full` 或 macOS 首参数 `full`。入口优先当前工作树环境、核对源码位置,并记录慢测试。依赖、代码在测试中变化会使证据失效;完成安装和编辑后再启动最终验证。
+正式入口会在创建测试分片前探测 PATH 中的外部工具。工具路径存在但当前权限不能启动时,
+入口以一条环境结论退出,不把同一个 `CreateProcess` 权限错误散落到多个用例。Windows Codex
+任务应让整条 `scripts/test.ps1` 通过受控提权在正常 PowerShell 权限下运行;不改单测、不跳过用例。
+
## 记录的环境身份
记录只在「代码、环境、范围」三项都匹配时可复用,环境那一项由 `scripts/test_evidence.py`
的 `environment()` 算成一个摘要:解释器与已安装包、平台、`PEACH_*` 等环境变量、前端
-`node_modules` 锁,以及 node/npm/git/ffmpeg/ffprobe/openssl 六个外部工具。
+`node_modules` 锁,以及 uv/node/npm/git/ffmpeg/ffprobe/openssl 七个外部工具。
工具身份取它**自报的版本**,不取 PATH 解析到的路径与文件字节。同一套 Git 安装在
PowerShell 里解析到 `Git\cmd\git.exe`、在 Git Bash 里解析到 `Git\mingw64\bin\git.exe`,
diff --git a/scripts/test_evidence.py b/scripts/test_evidence.py
index d80298b46..b2a27b645 100644
--- a/scripts/test_evidence.py
+++ b/scripts/test_evidence.py
@@ -82,6 +82,7 @@ def python_identity(executable: str, stamp: int) -> dict:
#: 就报「缺少有效测试记录」,而回到工作树跑 `auto` 又说「复用记录」,两句查的是两个键。
#: 探针只用最短的那条:`openssl version -a` 会连 OPENSSLDIR 一起打出来,那又是路径。
TOOL_PROBES: tuple[tuple[str, tuple[str, ...]], ...] = (
+ ("uv", ("--version",)),
("node", ("--version",)),
("npm", ("--version",)),
("git", ("--version",)),
@@ -105,7 +106,8 @@ def tool_identity(executable: str, stamp: int, probe: tuple[str, ...]) -> str:
return digest([done.returncode, done.stdout.strip(), done.stderr.strip()])
-def environment(root: Path) -> str:
+def tool_identities() -> dict[str, str | None]:
+ """PATH 上外部工具的可执行身份;存在但启动受限时明确记作 unspawnable。"""
tools = {}
for name, probe in TOOL_PROBES:
executable = shutil.which(name)
@@ -120,6 +122,17 @@ def environment(root: Path) -> str:
except OSError:
stamp = 0
tools[name] = tool_identity(executable, stamp, probe)
+ return tools
+
+
+def unspawnable_tools() -> tuple[str, ...]:
+ """返回能解析到路径、但当前进程权限无法启动的外部工具。"""
+ return tuple(name for name, identity in tool_identities().items()
+ if identity == "unspawnable")
+
+
+def environment(root: Path) -> str:
+ tools = tool_identities()
# 同一个目录可在 sys.path 中出现多次;依赖身份取集合,版本变化仍改变指纹。
python = interpreter(root)
identity = python_identity(str(python), python.stat().st_mtime_ns)
@@ -128,7 +141,7 @@ def environment(root: Path) -> str:
if d.metadata.get("Name", "").casefold() != "peach"})
node_lock = root / "frontend/node_modules/.package-lock.json"
return digest({
- "schema": 4, "python": identity["version"], "executable": str(python),
+ "schema": 5, "python": identity["version"], "executable": str(python),
"platform": platform.platform(), "packages": installed, "tools": tools,
"node_modules": hashlib.sha256(node_lock.read_bytes()).hexdigest() if node_lock.exists() else None,
"flags": {k: v for k, v in os.environ.items()
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index c264cf004..0c14d901b 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -487,6 +487,21 @@ def run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,
return passed, count, timings
+def environment_preflight(timings: Path | None = None) -> None:
+ """外部工具若被执行权限挡住,在创建测试分片前给出一条可操作的结论。"""
+ blocked = test_evidence.unspawnable_tools()
+ if not blocked:
+ return
+ names = "、".join(blocked)
+ print(f"Peach 测试环境无法启动 PATH 中的工具:{names}。"
+ "Windows Codex 任务请让 scripts/test.ps1 通过受控提权在正常 PowerShell 权限下运行;"
+ "其他环境请先修复这些工具的执行权限。不要改单测或跳过用例。", flush=True)
+ if timings is not None:
+ timings.write_text(json.dumps({"success": False, "count": 0, "timings": []}),
+ encoding="utf-8")
+ raise SystemExit(3)
+
+
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser()
# `--scope` 可重复:本机并行的父进程把 `auto` 算出来的几个域原样交给每个分片子进程。
@@ -507,6 +522,7 @@ def main(argv: list[str] | None = None) -> int:
if args.list_scopes:
print("\n".join(("full", "auto", *SCOPES)))
return 0
+ environment_preflight(args.timings)
requested: tuple[str, ...] = tuple(dict.fromkeys(args.scopes or ("auto",)))
if "auto" in requested and len(requested) > 1:
parser.error("auto 不能与别的域同时指定")
diff --git a/tests/test_test_evidence.py b/tests/test_test_evidence.py
index 576970b07..b72452a0a 100644
--- a/tests/test_test_evidence.py
+++ b/tests/test_test_evidence.py
@@ -160,6 +160,15 @@ class VerificationTests(unittest.TestCase):
with mock.patch.object(evidence.shutil, "which", return_value=None):
self.assertNotEqual(evidence.environment(self.repo), broken)
+ def test_unspawnable_tools_names_every_resolved_tool_blocked_by_permissions(self):
+ """入口需要工具名来给出一条明确结论,不能等测试分片各自抛 CreateProcess。"""
+ with mock.patch.object(evidence.shutil, "which", side_effect=lambda name: f"/tools/{name}"), \
+ mock.patch.object(evidence, "tool_identity",
+ side_effect=lambda executable, stamp, probe:
+ "unspawnable" if executable.endswith(("uv", "git")) else "ok"), \
+ mock.patch.object(evidence.Path, "stat", return_value=mock.Mock(st_mtime_ns=1)):
+ self.assertEqual(evidence.unspawnable_tools(), ("uv", "git"))
+
def test_commit_metadata_preserves_content_record(self):
worker, _ = self.worker()
state = self.certify(worker)
diff --git a/tests/test_test_planning.py b/tests/test_test_planning.py
index aca2f6018..29be2ede3 100644
--- a/tests/test_test_planning.py
+++ b/tests/test_test_planning.py
@@ -15,6 +15,16 @@ from support.ledger import fresh_ledger
class TestPlanningTests(unittest.TestCase):
+ def test_unspawnable_tools_stop_before_any_test_shard_starts(self):
+ output = io.StringIO()
+ with patch.object(runner.test_evidence, 'unspawnable_tools', return_value=('uv',)), \
+ patch.object(runner, 'build_suite', side_effect=AssertionError('环境不成立时不应加载测试')), \
+ contextlib.redirect_stdout(output):
+ with self.assertRaisesRegex(SystemExit, '3'):
+ runner.main(['--scope', 'checks'])
+ self.assertIn('uv', output.getvalue())
+ self.assertIn('正常 PowerShell 权限', output.getvalue())
+
def test_dependency_changes_require_full_but_tool_version_does_not(self):
source = '[project]\nrequires-python=">=3.12"\ndependencies=["demo==1"]\n[tool.uv]\nrequired-version="==1"\n'
for replacement, expected in ((source.replace('==1"\n', '==2"\n'), ('packaging',)),