Compare commits
57 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b94aa597ca | |||
| 841a2e0ae6 | |||
| 4d31d074ad | |||
| 29f725fb95 | |||
| 3a757e3376 | |||
| 5b9a693fda | |||
| 9b2d0a28d8 | |||
| 3a18a27dc6 | |||
| c2eb207bd2 | |||
| ffa7cbd63e | |||
| baed23d02a | |||
| 9ba9b3da0f | |||
| 0c9a530390 | |||
| 5fef8247fc | |||
| 2fcf16627d | |||
| 706c553778 | |||
| db92baf3a7 | |||
| fbf0ca8cd8 | |||
| 8d48d2d335 | |||
| d7ebb6ee85 | |||
| 19aac17a0a | |||
| 125bfe0c23 | |||
| 57879cffdd | |||
| 4814bc1026 | |||
| 7be8b9c3d9 | |||
| f8e490e9b5 | |||
| 95946d4278 | |||
| af6e139d30 | |||
| 93341b3c69 | |||
| 0eefc52b44 | |||
| 8390706df8 | |||
| d3b6732d40 | |||
| ab29598a9a | |||
| c9faedc39d | |||
| f05ac24c57 | |||
| de194370e6 | |||
| 299f6dd9b2 | |||
| 558c6facc2 | |||
| 32da57d19b | |||
| 51f7c2e60c | |||
| 544cbcca32 | |||
| a35cc916cb | |||
| 5ba1d8e3d6 | |||
| 0ec8ea81d8 | |||
| 824049f774 | |||
| 1100eec884 | |||
| cf78d0cab2 | |||
| 86ce602b28 | |||
| 130dcc36c5 | |||
| fd13dad2b0 | |||
| 38c4c7f91d | |||
| 147b63aae6 | |||
| 94c66bc695 | |||
| 2917708b10 | |||
| f469c8f5f5 | |||
| 44cee4be91 | |||
| 146182c1b9 |
@@ -60,11 +60,20 @@ AGENTS.md # 本文档
|
||||
| [note-style](skills/note-style/README.md) | 把材料整理成可长期查阅的知识笔记 |
|
||||
| [orc](skills/orc/README.md) | 把开发、发版、DEB / Docker 意图编排成阶段,按档位分发给对应 skill |
|
||||
| [pouch](skills/pouch/README.md) | 创建、校验、安装和维护 builtin skill |
|
||||
| [previewer](skills/previewer/README.md) | 通过 Tailscale Serve 将静态文件暴露为 tailnet 内 HTTP 预览 |
|
||||
| [pr-ship](skills/pr-ship/README.md) | 把已有 PR 从检查、合并推进到回归、构建和部署 |
|
||||
| [releaser](skills/releaser/README.md) | 给已准备好的 commit 发版本:更新说明、tag、可选 Forge Release |
|
||||
| [ship](skills/ship/README.md) | short-ship / long-ship / pr-ship 共用的交付记录格式 |
|
||||
| [short-ship](skills/short-ship/README.md) | 范围清楚的单次变更:小功能、文案、已确认 bug,一直交到停点 |
|
||||
| [long-ship](skills/long-ship/README.md) | 复杂需求:specifier PRD 批准后拆任务、集成回归并交付 |
|
||||
| [specifier](skills/specifier/README.md) | 把复杂需求整理成多轮评审的 HTML PRD,批准后交给 long-ship |
|
||||
| [delivery-loop](skills/delivery-loop/README.md) | 三个交付入口共用的验证到部署状态机 |
|
||||
| [manage-release](skills/manage-release/README.md) | 已弃用:`releaser` 的旧名兼容占位,不含流程 |
|
||||
| [bugfix-ship](skills/bugfix-ship/README.md) | 已弃用:`short-ship` 的旧名兼容占位,不含流程 |
|
||||
| [requirement-flow](skills/requirement-flow/README.md) | 已弃用:`long-ship` 的旧名兼容占位,不含流程 |
|
||||
|
||||
改名后旧名保留一个纯占位 skill,避免已装软链悬空和旧项目 `.pouch.yaml` 失效。确认没有
|
||||
项目再按 `manage-release` 启用后,删除 `skills/manage-release/` 即可,不丢任何内容。
|
||||
项目再按旧名启用后,删除对应占位目录即可,不丢任何内容。
|
||||
|
||||
|
||||
新建 skill:优先 `pouch create`;或复制 `skills/_template/` → `skills/<name>/`,编辑 `SKILL.md` 和 `README.md`,在本仓库 commit。
|
||||
@@ -88,11 +97,13 @@ builder 与 deployer 的项目接入走各自 skill 的「初始化」模式(
|
||||
| Source | 来源 |
|
||||
| --- | --- |
|
||||
| waza | [https://github.com/tw93/Waza](https://github.com/tw93/Waza) |
|
||||
| taste-skill | [https://github.com/Leonxlnx/taste-skill](https://github.com/Leonxlnx/taste-skill) |
|
||||
|
||||
|
||||
```bash
|
||||
pouch fetch waza
|
||||
pouch add waza/think -g
|
||||
pouch add taste-skill/taste-skill -g
|
||||
```
|
||||
|
||||
### 自定义仓库(Custom Sources)
|
||||
@@ -235,6 +246,7 @@ pouch sync
|
||||
| `pouch add <name> [-g]` | 项目或全局安装(symlink) |
|
||||
| `pouch remove <name> [-g]` | 移除 symlink |
|
||||
| `pouch catalog add` / `pouch fetch` | 管理和拉取 catalog source |
|
||||
| `pouch update` | 更新 pouch 自身和已拉取的 catalog / custom source |
|
||||
|
||||
|
||||
### 草稿与健康检查
|
||||
@@ -344,7 +356,7 @@ Claude Code 对 symlink 支持不稳定:可能无法发现 skill,或写入
|
||||
| 项目启用 | `pouch add <name>` 或 `pouch enable <name>` | 项目目录 |
|
||||
| 看状态 | `pouch status` | 任意 |
|
||||
| 装社区 skill | `npx skills add owner/repo -g -y` | 任意 |
|
||||
| 更新外部 skill | `pouch fetch <name>` | 任意 |
|
||||
| 更新外部 skill | `pouch fetch <name>` 或日常命令自动更新 | 任意 |
|
||||
|
||||
|
||||
---
|
||||
|
||||
@@ -96,8 +96,17 @@ AGENTS.md # 详细规范与架构说明
|
||||
| [note-style](skills/note-style/README.md) | 把材料整理成可长期查阅的知识笔记 |
|
||||
| [orc](skills/orc/README.md) | 把开发、发版、DEB / Docker 意图编排成阶段,按档位分发给对应 skill |
|
||||
| [pouch](skills/pouch/README.md) | 创建、校验、安装和维护 builtin skill |
|
||||
| [previewer](skills/previewer/README.md) | 用 Node 渲染 HTML/静态文件,并通过 Tailscale 返回访问 IP 和 HTTP 预览 |
|
||||
| [pr-ship](skills/pr-ship/README.md) | 把已有 PR 从检查、合并推进到回归、构建和部署 |
|
||||
| [releaser](skills/releaser/README.md) | 给已准备好的 commit 发版本:更新说明、tag、可选 Forge Release |
|
||||
| [ship](skills/ship/README.md) | short-ship / long-ship / pr-ship 共用的交付记录格式 |
|
||||
| [short-ship](skills/short-ship/README.md) | 范围清楚的单次变更:小功能、文案、已确认 bug |
|
||||
| [long-ship](skills/long-ship/README.md) | 复杂需求:PRD 批准后拆任务、集成回归并交付 |
|
||||
| [specifier](skills/specifier/README.md) | 把复杂需求整理成多轮评审的 HTML PRD,批准后交给 long-ship |
|
||||
| [delivery-loop](skills/delivery-loop/README.md) | 三个交付入口共用的验证到部署状态机 |
|
||||
| [manage-release](skills/manage-release/README.md) | 已弃用:`releaser` 的旧名兼容占位,不含流程 |
|
||||
| [bugfix-ship](skills/bugfix-ship/README.md) | 已弃用:`short-ship` 的旧名兼容占位,不含流程 |
|
||||
| [requirement-flow](skills/requirement-flow/README.md) | 已弃用:`long-ship` 的旧名兼容占位,不含流程 |
|
||||
|
||||
|
||||
ACK 是包含规范、模板与校验脚本的完整 Skill。安装后可初始化当前项目状态:
|
||||
@@ -164,6 +173,8 @@ pouch remove ack
|
||||
```bash
|
||||
pouch fetch waza
|
||||
pouch add waza/think -g
|
||||
pouch add taste-skill/taste-skill -g # 只要核心 frontend skill
|
||||
pouch add taste-skill -g # 或装整个 Taste Skill collection
|
||||
```
|
||||
|
||||
接入团队自己的本地目录或 Git 仓库:
|
||||
|
||||
@@ -29,3 +29,13 @@ waza:
|
||||
- engineering
|
||||
- workflow
|
||||
- skill-collection
|
||||
|
||||
taste-skill:
|
||||
repo: https://github.com/Leonxlnx/taste-skill.git
|
||||
ref: main
|
||||
path: skills
|
||||
description: Taste Skill collection for anti-slop frontend, redesign, image generation, brand kits, and output enforcement.
|
||||
tags:
|
||||
- frontend
|
||||
- design
|
||||
- skill-collection
|
||||
|
||||
@@ -49,7 +49,7 @@ pouch status
|
||||
pouch doctor
|
||||
```
|
||||
|
||||
软链异常就 `pouch doctor --fix`。更新 pouch 自身:`pouch update`(在 `~/.pouch` 里 `git pull`)。
|
||||
软链异常就 `pouch doctor --fix`。日常用 pouch 命令时会按间隔自动更新自身和已拉取的外部 source;要立刻更新就 `pouch update`。
|
||||
|
||||
## 把要用的 skill 装上
|
||||
|
||||
|
||||
+32
-2
@@ -65,7 +65,7 @@ pouch bootstrap
|
||||
| 命令 | 说明 |
|
||||
|------|------|
|
||||
| `pouch bootstrap` | 将本项目的 `pouch` skill 全局安装到所有 Agent |
|
||||
| `pouch update` | 在 `~/.pouch` 执行 `git pull`,更新 pouch 自身 |
|
||||
| `pouch update` | 更新 pouch 自身,以及已拉取的 catalog / custom source |
|
||||
| `pouch init <name> [--project DIR]` | 使用 builtin skill 自带模板初始化项目状态(目前用于 ack) |
|
||||
|
||||
### Skill 安装
|
||||
@@ -105,6 +105,33 @@ collection 会自动发现下一层所有含 `SKILL.md` 的目录;`pouch add <
|
||||
安装全部,`pouch select` 则展开为 `<name>/<skill>` 供分别勾选。同一
|
||||
`repo` 与 `ref` 共享一份 Git checkout。
|
||||
|
||||
预置 collection 示例:
|
||||
|
||||
```bash
|
||||
pouch add waza/think -g
|
||||
pouch add taste-skill/taste-skill -g
|
||||
pouch add taste-skill -g # 安装 Taste Skill 全部子 skill
|
||||
```
|
||||
|
||||
### 自动更新
|
||||
|
||||
日常执行 `pouch list`、`pouch add`、`pouch status` 等命令时,pouch 会按间隔
|
||||
顺带更新自身和已经 clone 过的 catalog / custom Git source,不必单独跑
|
||||
`pouch fetch` 或 `pouch update`。默认每 24 小时最多自动更新一次;网络失败或
|
||||
工作区不干净时跳过,不打断当前命令。`pouch add <catalog>` 在安装前会再刷新
|
||||
该来源,以便拿到最新子 skill。
|
||||
|
||||
在 `~/.config/pouch/config.yaml` 里关闭或改间隔:
|
||||
|
||||
```yaml
|
||||
auto_update:
|
||||
enabled: true
|
||||
interval: 24h # 也可用 1d、60m、3600
|
||||
```
|
||||
|
||||
本次跳过:`pouch --no-auto-update list`,或设置环境变量 `POUCH_NO_AUTO_UPDATE=1`。
|
||||
立刻更新全部:`pouch update`。
|
||||
|
||||
### 交互式批量安装
|
||||
|
||||
```bash
|
||||
@@ -222,6 +249,8 @@ pouch/
|
||||
├── paths.py # 路径常量与 Agent 目标
|
||||
├── skills.py # builtin/catalog/custom 统一解析
|
||||
├── catalog.py # catalog.yaml 读写与 Skill 发现
|
||||
├── config.py # 用户配置与自动更新设定
|
||||
├── auto_update.py # 命令执行时顺带更新 pouch 与已拉取 source
|
||||
├── sources.py # custom source 配置、发现与 Git 管理
|
||||
├── project.py # .pouch.yaml 管理
|
||||
├── symlinks.py # 软链创建/检查/修复
|
||||
@@ -238,7 +267,8 @@ pouch/
|
||||
| `SKILLS_DIR` | `~/.pouch/skills/` | builtin skill 目录 |
|
||||
| `CATALOG_FILE` | `~/.pouch/catalog.yaml` | 预置 Skill 来源目录 |
|
||||
| `CATALOG_CACHE_DIR` | `~/.local/share/pouch/externals/` | catalog checkout 缓存;按 repo/ref 共享 |
|
||||
| `CONFIG_FILE` | `~/.config/pouch/config.yaml` | custom source 配置 |
|
||||
| `CONFIG_FILE` | `~/.config/pouch/config.yaml` | custom source 与 auto_update 配置 |
|
||||
| `STATE_FILE` | `~/.local/share/pouch/state.yaml` | 自动更新时间戳 |
|
||||
| `SOURCES_DIR` | `~/.local/share/pouch/sources/` | custom Git source 默认 checkout |
|
||||
|
||||
## 注意事项
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
"""在日常命令里顺带更新 pouch 自身和已拉取的外部 source。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
|
||||
from pouch import yaml_io
|
||||
from pouch.catalog import catalog_checkout_path, load_catalog
|
||||
from pouch.config import load_auto_update_settings
|
||||
from pouch.paths import POUCH_HOME, STATE_FILE
|
||||
from pouch.sources import load_sources, source_checkout
|
||||
|
||||
GIT_TIMEOUT_SECONDS = 20
|
||||
_SKIP_COMMANDS = {"update", "publish"}
|
||||
_TRUTHY = {"1", "true", "yes", "on"}
|
||||
_refreshed_paths: set[str] = set()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UpdateResult:
|
||||
name: str
|
||||
status: str
|
||||
detail: str = ""
|
||||
|
||||
@property
|
||||
def changed(self) -> bool:
|
||||
return self.status == "updated"
|
||||
|
||||
|
||||
def _print_err(msg: str) -> None:
|
||||
print(msg, file=sys.stderr)
|
||||
|
||||
|
||||
def _run_git(
|
||||
repo: Path,
|
||||
*args: str,
|
||||
check: bool = False,
|
||||
timeout: int = GIT_TIMEOUT_SECONDS,
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run(
|
||||
["git", "-C", str(repo), *args],
|
||||
check=check,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
def _is_git_repo(path: Path) -> bool:
|
||||
if not path.is_dir():
|
||||
return False
|
||||
try:
|
||||
result = _run_git(path, "rev-parse", "--is-inside-work-tree")
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return False
|
||||
return result.returncode == 0 and result.stdout.strip() == "true"
|
||||
|
||||
|
||||
def _working_tree_dirty(path: Path) -> bool:
|
||||
result = _run_git(path, "status", "--porcelain")
|
||||
return result.returncode != 0 or bool(result.stdout.strip())
|
||||
|
||||
|
||||
def _head_sha(path: Path) -> str:
|
||||
result = _run_git(path, "rev-parse", "HEAD")
|
||||
return result.stdout.strip() if result.returncode == 0 else ""
|
||||
|
||||
|
||||
def refresh_git_checkout(
|
||||
path: Path,
|
||||
ref: str | None = None,
|
||||
*,
|
||||
name: str,
|
||||
strict: bool = False,
|
||||
allow_dirty: bool = False,
|
||||
) -> UpdateResult:
|
||||
key = str(path.resolve()) if path.exists() else str(path)
|
||||
if key in _refreshed_paths:
|
||||
return UpdateResult(name, "current")
|
||||
if not _is_git_repo(path):
|
||||
_refreshed_paths.add(key)
|
||||
result = UpdateResult(name, "skipped", "不是 git 仓库")
|
||||
if strict:
|
||||
raise SystemExit(f"{name} 不是 git 仓库: {path}")
|
||||
return result
|
||||
if not allow_dirty and _working_tree_dirty(path):
|
||||
_refreshed_paths.add(key)
|
||||
result = UpdateResult(name, "skipped", "工作区不干净")
|
||||
if strict:
|
||||
raise SystemExit(f"{name} 工作区不干净,拒绝更新: {path}")
|
||||
return result
|
||||
|
||||
before = _head_sha(path)
|
||||
commands: list[tuple[str, ...]] = [("fetch", "--all", "--tags")]
|
||||
if ref:
|
||||
commands.append(("checkout", ref))
|
||||
commands.append(("pull", "--ff-only"))
|
||||
try:
|
||||
for command in commands:
|
||||
ran = _run_git(path, *command, check=strict)
|
||||
if ran.returncode != 0:
|
||||
detail = (ran.stderr or ran.stdout or "git 失败").strip()
|
||||
return UpdateResult(name, "failed", detail)
|
||||
except subprocess.CalledProcessError as exc:
|
||||
detail = ((exc.stderr or exc.stdout or str(exc))).strip()
|
||||
if strict:
|
||||
raise SystemExit(f"更新 {name} 失败: {detail}") from exc
|
||||
return UpdateResult(name, "failed", detail)
|
||||
except subprocess.TimeoutExpired:
|
||||
result = UpdateResult(name, "failed", "git 超时")
|
||||
if strict:
|
||||
raise SystemExit(f"更新 {name} 超时: {path}") from None
|
||||
return result
|
||||
except OSError as exc:
|
||||
result = UpdateResult(name, "failed", str(exc))
|
||||
if strict:
|
||||
raise SystemExit(f"更新 {name} 失败: {exc}") from exc
|
||||
return result
|
||||
|
||||
after = _head_sha(path)
|
||||
_refreshed_paths.add(key)
|
||||
if before and after and before != after:
|
||||
return UpdateResult(name, "updated", after[:8])
|
||||
return UpdateResult(name, "current")
|
||||
|
||||
|
||||
def update_pouch_home(*, strict: bool = False) -> UpdateResult:
|
||||
return refresh_git_checkout(
|
||||
POUCH_HOME,
|
||||
name="pouch",
|
||||
strict=strict,
|
||||
allow_dirty=strict,
|
||||
)
|
||||
|
||||
|
||||
def update_cloned_catalogs(*, strict: bool = False) -> list[UpdateResult]:
|
||||
results: list[UpdateResult] = []
|
||||
seen: set[Path] = set()
|
||||
for name, entry in load_catalog().items():
|
||||
repo = str(entry.get("repo", ""))
|
||||
if repo.startswith("~"):
|
||||
continue
|
||||
dest = catalog_checkout_path(name, entry)
|
||||
resolved = dest.resolve() if dest.exists() else dest
|
||||
if resolved in seen or not dest.is_dir():
|
||||
continue
|
||||
seen.add(resolved)
|
||||
results.append(
|
||||
refresh_git_checkout(
|
||||
dest,
|
||||
str(entry.get("ref", "main") or "main"),
|
||||
name=f"catalog:{name}",
|
||||
strict=strict,
|
||||
)
|
||||
)
|
||||
return results
|
||||
|
||||
|
||||
def update_custom_sources(*, strict: bool = False) -> list[UpdateResult]:
|
||||
results: list[UpdateResult] = []
|
||||
for name, entry in load_sources().items():
|
||||
if entry.get("local_path"):
|
||||
continue
|
||||
checkout = source_checkout(name, entry)
|
||||
if not checkout.is_dir():
|
||||
continue
|
||||
results.append(
|
||||
refresh_git_checkout(
|
||||
checkout,
|
||||
str(entry.get("ref", "main") or "main"),
|
||||
name=f"custom:{name}",
|
||||
strict=strict,
|
||||
)
|
||||
)
|
||||
return results
|
||||
|
||||
|
||||
def run_updates(*, strict_pouch: bool = False) -> list[UpdateResult]:
|
||||
results = [update_pouch_home(strict=strict_pouch)]
|
||||
results.extend(update_cloned_catalogs(strict=False))
|
||||
results.extend(update_custom_sources(strict=False))
|
||||
return results
|
||||
|
||||
|
||||
def load_state(path: Path | None = None) -> dict[str, Any]:
|
||||
path = path or STATE_FILE
|
||||
if not path.is_file():
|
||||
return {}
|
||||
data = yaml_io.safe_load(path.read_text(encoding="utf-8")) or {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def save_state(data: dict[str, Any], path: Path | None = None) -> None:
|
||||
path = path or STATE_FILE
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(
|
||||
yaml_io.safe_dump(data, allow_unicode=True, sort_keys=False),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def record_auto_update(path: Path | None = None) -> None:
|
||||
state = load_state(path)
|
||||
state["last_auto_update"] = datetime.now(timezone.utc).isoformat()
|
||||
save_state(state, path)
|
||||
|
||||
|
||||
def _interval_elapsed(state: dict[str, Any], interval_seconds: int) -> bool:
|
||||
if interval_seconds <= 0:
|
||||
return True
|
||||
raw = state.get("last_auto_update")
|
||||
if not raw:
|
||||
return True
|
||||
try:
|
||||
last = datetime.fromisoformat(str(raw))
|
||||
except ValueError:
|
||||
return True
|
||||
if last.tzinfo is None:
|
||||
last = last.replace(tzinfo=timezone.utc)
|
||||
elapsed = (datetime.now(timezone.utc) - last).total_seconds()
|
||||
return elapsed >= interval_seconds
|
||||
|
||||
|
||||
def _env_disabled() -> bool:
|
||||
return os.environ.get("POUCH_NO_AUTO_UPDATE", "").strip().lower() in _TRUTHY
|
||||
|
||||
|
||||
def _acquire_lock(path: Path) -> Any | None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
lock_file = path.open("a+")
|
||||
except OSError:
|
||||
return None
|
||||
try:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except OSError:
|
||||
lock_file.close()
|
||||
return None
|
||||
return lock_file
|
||||
|
||||
|
||||
def _release_lock(lock_file: Any | None) -> None:
|
||||
if lock_file is None:
|
||||
return
|
||||
try:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
lock_file.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def reset_refresh_cache() -> None:
|
||||
_refreshed_paths.clear()
|
||||
|
||||
|
||||
def report_results(results: Iterable[UpdateResult], *, prefix: str = "[pouch]") -> None:
|
||||
changed = [item.name for item in results if item.changed]
|
||||
failed = [item for item in results if item.status == "failed"]
|
||||
if changed:
|
||||
_print_err(f"{prefix} 已自动更新: {', '.join(changed)}")
|
||||
for item in failed:
|
||||
detail = f": {item.detail}" if item.detail else ""
|
||||
_print_err(f"{prefix} 更新 {item.name} 失败,已跳过{detail}")
|
||||
|
||||
|
||||
def maybe_auto_update(*, command: str | None = None, disabled: bool = False) -> list[UpdateResult]:
|
||||
if disabled or command in _SKIP_COMMANDS or _env_disabled():
|
||||
return []
|
||||
if not POUCH_HOME.is_dir():
|
||||
return []
|
||||
|
||||
settings = load_auto_update_settings()
|
||||
if not settings.enabled:
|
||||
return []
|
||||
state = load_state()
|
||||
if not _interval_elapsed(state, settings.interval_seconds):
|
||||
return []
|
||||
|
||||
lock_file = _acquire_lock(STATE_FILE.with_name("auto-update.lock"))
|
||||
if lock_file is None:
|
||||
return []
|
||||
try:
|
||||
# 拿到锁后再读一次,避免并发重复拉取。
|
||||
state = load_state()
|
||||
if not _interval_elapsed(state, settings.interval_seconds):
|
||||
return []
|
||||
results = run_updates(strict_pouch=False)
|
||||
record_auto_update()
|
||||
report_results(results)
|
||||
return results
|
||||
except Exception as exc: # noqa: BLE001 — 自动更新不得打断用户命令
|
||||
_print_err(f"[pouch] 自动更新失败,已跳过: {exc}")
|
||||
return []
|
||||
finally:
|
||||
_release_lock(lock_file)
|
||||
+85
-16
@@ -58,6 +58,7 @@ from pouch.skills import (
|
||||
validate_skill_dir,
|
||||
validate_skill_name,
|
||||
)
|
||||
from pouch.auto_update import maybe_auto_update, record_auto_update, refresh_git_checkout, run_updates
|
||||
from pouch.sources import (
|
||||
discover_source_skills,
|
||||
fetch_source,
|
||||
@@ -250,15 +251,33 @@ def _collect_skill_names(positional: list[str] | None, flagged: list[str] | None
|
||||
return names
|
||||
|
||||
|
||||
def _ensure_source_fetched(name: str, source: str | None = None) -> None:
|
||||
def _ensure_source_fetched(
|
||||
name: str,
|
||||
source: str | None = None,
|
||||
*,
|
||||
refresh: bool = False,
|
||||
) -> None:
|
||||
name, source = split_skill_spec(name, source)
|
||||
catalog = load_catalog()
|
||||
sources = load_sources()
|
||||
if source in sources:
|
||||
root = source_skills_root(source, sources[source])
|
||||
entry = sources[source]
|
||||
root = source_skills_root(source, entry)
|
||||
if not root.is_dir():
|
||||
_print(f"拉取 source: {source}")
|
||||
fetch_source(source, sources[source])
|
||||
fetch_source(source, entry)
|
||||
elif refresh and not entry.get("local_path"):
|
||||
result = refresh_git_checkout(
|
||||
source_checkout(source, entry),
|
||||
str(entry.get("ref", "main") or "main"),
|
||||
name=f"custom:{source}",
|
||||
)
|
||||
if result.status == "updated":
|
||||
_err(f"[pouch] 已更新 custom:{source}")
|
||||
elif result.status == "failed":
|
||||
_err(
|
||||
f"[pouch] 更新 custom:{source} 失败,使用本地缓存: {result.detail}"
|
||||
)
|
||||
return
|
||||
|
||||
catalog_name = (
|
||||
@@ -274,7 +293,11 @@ def _ensure_source_fetched(name: str, source: str | None = None) -> None:
|
||||
source in (None, "catalog", catalog_name)
|
||||
or source == f"catalog:{catalog_name}"
|
||||
):
|
||||
_ensure_catalog_fetched(catalog_name, catalog[catalog_name])
|
||||
_ensure_catalog_fetched(
|
||||
catalog_name,
|
||||
catalog[catalog_name],
|
||||
refresh=refresh,
|
||||
)
|
||||
return
|
||||
|
||||
if source not in (None, "catalog"):
|
||||
@@ -283,17 +306,31 @@ def _ensure_source_fetched(name: str, source: str | None = None) -> None:
|
||||
if name not in catalog:
|
||||
return
|
||||
|
||||
_ensure_catalog_fetched(name, catalog[name])
|
||||
_ensure_catalog_fetched(name, catalog[name], refresh=refresh)
|
||||
|
||||
|
||||
def _ensure_catalog_fetched(name: str, entry: dict[str, object]) -> None:
|
||||
def _ensure_catalog_fetched(
|
||||
name: str,
|
||||
entry: dict[str, object],
|
||||
*,
|
||||
refresh: bool = False,
|
||||
) -> None:
|
||||
path = catalog_skill_path(name, entry)
|
||||
repo = catalog_repo(entry)
|
||||
ref = str(entry.get("ref", "main") or "main")
|
||||
dest = catalog_checkout_path(name, entry)
|
||||
if dest.is_dir() and (dest / ".git").exists() and refresh and not str(entry.get("repo", "")).startswith("~"):
|
||||
result = refresh_git_checkout(dest, ref, name=f"catalog:{name}")
|
||||
if result.status == "updated":
|
||||
_err(f"[pouch] 已更新 catalog:{name}")
|
||||
elif result.status == "failed":
|
||||
_err(f"[pouch] 更新 catalog:{name} 失败,使用本地缓存: {result.detail}")
|
||||
if (path / "SKILL.md").is_file() or discover_catalog_skills(name, entry):
|
||||
return
|
||||
|
||||
if (path / "SKILL.md").is_file() or discover_catalog_skills(name, entry):
|
||||
return
|
||||
|
||||
repo = catalog_repo(entry)
|
||||
ref = entry.get("ref", "main")
|
||||
dest = catalog_checkout_path(name, entry)
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
if dest.exists():
|
||||
raise SystemExit(
|
||||
@@ -334,14 +371,17 @@ def _expand_install_request(
|
||||
catalog = load_catalog()
|
||||
sources = load_sources()
|
||||
if source in sources:
|
||||
_ensure_source_fetched(name, source, refresh=True)
|
||||
return [(name, source)]
|
||||
if source == "catalog" and name in catalog:
|
||||
_ensure_catalog_fetched(name, catalog[name], refresh=True)
|
||||
available = _catalog_skill_names(name, catalog[name])
|
||||
root = catalog_skill_path(name, catalog[name])
|
||||
if (root / "SKILL.md").is_file():
|
||||
return [(name, "catalog")]
|
||||
return [(skill_name, f"catalog:{name}") for skill_name in available]
|
||||
if source in catalog:
|
||||
_ensure_catalog_fetched(source, catalog[source], refresh=True)
|
||||
available = _catalog_skill_names(source, catalog[source])
|
||||
if name not in available:
|
||||
raise SystemExit(
|
||||
@@ -349,13 +389,14 @@ def _expand_install_request(
|
||||
)
|
||||
return [(name, f"catalog:{source}")]
|
||||
if source is None and name in catalog:
|
||||
_ensure_catalog_fetched(name, catalog[name], refresh=True)
|
||||
available = _catalog_skill_names(name, catalog[name])
|
||||
root = catalog_skill_path(name, catalog[name])
|
||||
if (root / "SKILL.md").is_file():
|
||||
return [(name, f"catalog:{name}")]
|
||||
return [(skill_name, f"catalog:{name}") for skill_name in available]
|
||||
if source is None and name in sources:
|
||||
_ensure_source_fetched(name, name)
|
||||
_ensure_source_fetched(name, name, refresh=True)
|
||||
available = discover_source_skills(name, sources[name])
|
||||
if not available:
|
||||
raise SystemExit(f"custom source {name!r} 中没有可安装的 skill")
|
||||
@@ -375,7 +416,7 @@ def _install_skill(
|
||||
source: str | None = None,
|
||||
) -> str:
|
||||
name, source = split_skill_spec(name, source)
|
||||
_ensure_source_fetched(name, source)
|
||||
_ensure_source_fetched(name, source, refresh=True)
|
||||
skill_path, resolved_source = resolve_skill_source(name, source=source)
|
||||
links = [
|
||||
(target, agent_skill_dir(target, project_root=project_root) / name)
|
||||
@@ -540,7 +581,23 @@ def cmd_update(args: argparse.Namespace) -> None:
|
||||
del args
|
||||
ensure_pouch_home()
|
||||
_print(f"更新 pouch: {POUCH_HOME}")
|
||||
subprocess.run(["git", "-C", str(POUCH_HOME), "pull"], check=True)
|
||||
results = run_updates()
|
||||
record_auto_update()
|
||||
labels = {
|
||||
"updated": "已更新",
|
||||
"current": "已是最新",
|
||||
"skipped": "跳过",
|
||||
"failed": "失败",
|
||||
}
|
||||
for item in results:
|
||||
extra = f"({item.detail})" if item.detail else ""
|
||||
line = f"{labels.get(item.status, item.status)} {item.name}{extra}"
|
||||
if item.status == "failed":
|
||||
_err(line)
|
||||
else:
|
||||
_print(line)
|
||||
if any(item.status == "failed" for item in results):
|
||||
raise SystemExit("部分来源更新失败")
|
||||
|
||||
|
||||
def _installed_links(
|
||||
@@ -640,7 +697,7 @@ def cmd_add(args: argparse.Namespace) -> None:
|
||||
elif source == "catalog":
|
||||
names = list(load_catalog())
|
||||
else:
|
||||
_ensure_source_fetched("", source)
|
||||
_ensure_source_fetched("", source, refresh=True)
|
||||
names = list_custom_skills(source)[source]
|
||||
else:
|
||||
names = list_builtin_skills()
|
||||
@@ -662,7 +719,7 @@ def cmd_add(args: argparse.Namespace) -> None:
|
||||
original_links: list[tuple[Path, str | None]] = []
|
||||
for skill_name, source in requests:
|
||||
validate_skill_name(skill_name)
|
||||
_ensure_source_fetched(skill_name, source)
|
||||
_ensure_source_fetched(skill_name, source, refresh=True)
|
||||
resolve_skill_source(skill_name, source=source)
|
||||
for target in targets:
|
||||
link = agent_skill_dir(target, project_root=project_root) / skill_name
|
||||
@@ -1122,7 +1179,7 @@ def cmd_sync(args: argparse.Namespace) -> None:
|
||||
for entry in iter_manifest_skills(data):
|
||||
name = entry["name"]
|
||||
source = entry.get("source")
|
||||
_ensure_source_fetched(name, source)
|
||||
_ensure_source_fetched(name, source, refresh=True)
|
||||
skill_path, _ = resolve_manifest_skill(entry)
|
||||
skill_targets = targets
|
||||
if entry.get("targets"):
|
||||
@@ -1702,6 +1759,11 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
description="自研 Agent Skills 安装与管理 CLI(接口对齐 Vercel skills)",
|
||||
)
|
||||
parser.add_argument("--version", action="version", version=f"pouch {__version__}")
|
||||
parser.add_argument(
|
||||
"--no-auto-update",
|
||||
action="store_true",
|
||||
help="本次跳过自动更新 pouch 与已拉取的 source",
|
||||
)
|
||||
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
@@ -1711,7 +1773,10 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
)
|
||||
p_bootstrap.set_defaults(func=cmd_bootstrap)
|
||||
|
||||
p_update = sub.add_parser("update", help="通过 git pull 更新 pouch 自身")
|
||||
p_update = sub.add_parser(
|
||||
"update",
|
||||
help="更新 pouch 自身以及已拉取的 catalog / custom source",
|
||||
)
|
||||
p_update.set_defaults(func=cmd_update)
|
||||
|
||||
p_list = sub.add_parser("list", help="列出所有 source 中的 skill")
|
||||
@@ -1845,6 +1910,10 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
def main(argv: list[str] | None = None) -> None:
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
maybe_auto_update(
|
||||
command=getattr(args, "command", None),
|
||||
disabled=bool(getattr(args, "no_auto_update", False)),
|
||||
)
|
||||
args.func(args)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""用户级 pouch 配置(~/.config/pouch/config.yaml)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pouch import yaml_io
|
||||
from pouch.paths import CONFIG_FILE
|
||||
|
||||
DEFAULT_AUTO_UPDATE_INTERVAL = "24h"
|
||||
_INTERVAL_UNITS = {
|
||||
"s": 1,
|
||||
"m": 60,
|
||||
"h": 3600,
|
||||
"d": 86400,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AutoUpdateSettings:
|
||||
enabled: bool = True
|
||||
interval_seconds: int = 24 * 3600
|
||||
|
||||
|
||||
def load_user_config(path: Path | None = None) -> dict[str, Any]:
|
||||
path = path or CONFIG_FILE
|
||||
if not path.is_file():
|
||||
return {}
|
||||
data = yaml_io.safe_load(path.read_text(encoding="utf-8")) or {}
|
||||
if not isinstance(data, dict):
|
||||
raise SystemExit(f"pouch 配置格式错误: {path}")
|
||||
return data
|
||||
|
||||
|
||||
def save_user_config(data: dict[str, Any], path: Path | None = None) -> None:
|
||||
path = path or CONFIG_FILE
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(
|
||||
yaml_io.safe_dump(data, allow_unicode=True, sort_keys=False),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def parse_interval(value: Any) -> int:
|
||||
if value is None or value is True:
|
||||
return AutoUpdateSettings().interval_seconds
|
||||
if isinstance(value, bool):
|
||||
raise ValueError(f"无效的自动更新间隔: {value!r}")
|
||||
if isinstance(value, int):
|
||||
if value < 0:
|
||||
raise ValueError(f"无效的自动更新间隔: {value!r}")
|
||||
return value
|
||||
text = str(value).strip().lower()
|
||||
if not text:
|
||||
return AutoUpdateSettings().interval_seconds
|
||||
if text.isdigit():
|
||||
return int(text)
|
||||
unit = text[-1]
|
||||
amount = text[:-1]
|
||||
if unit in _INTERVAL_UNITS and amount.isdigit():
|
||||
return int(amount) * _INTERVAL_UNITS[unit]
|
||||
raise ValueError(f"无效的自动更新间隔: {value!r}(例如 24h、1d、60m、3600)")
|
||||
|
||||
|
||||
def load_auto_update_settings(
|
||||
config: dict[str, Any] | None = None,
|
||||
path: Path | None = None,
|
||||
) -> AutoUpdateSettings:
|
||||
if config is None:
|
||||
config = load_user_config(path)
|
||||
raw = config.get("auto_update", True)
|
||||
if raw is False:
|
||||
return AutoUpdateSettings(enabled=False)
|
||||
if raw is True or raw is None:
|
||||
return AutoUpdateSettings()
|
||||
if not isinstance(raw, dict):
|
||||
return AutoUpdateSettings()
|
||||
enabled = raw.get("enabled", True)
|
||||
if enabled is False:
|
||||
return AutoUpdateSettings(enabled=False)
|
||||
try:
|
||||
interval = parse_interval(raw.get("interval", DEFAULT_AUTO_UPDATE_INTERVAL))
|
||||
except ValueError as exc:
|
||||
raise SystemExit(str(exc)) from exc
|
||||
return AutoUpdateSettings(enabled=bool(enabled), interval_seconds=interval)
|
||||
@@ -45,11 +45,18 @@ CONFIG_FILE = _first_existing_file(
|
||||
HOME / ".config" / "skiff" / "config.yaml",
|
||||
default=HOME / ".config" / "pouch" / "config.yaml",
|
||||
)
|
||||
DATA_DIR = _first_existing_dir(
|
||||
HOME / ".local" / "share" / "pouch",
|
||||
HOME / ".local" / "share" / "skiff",
|
||||
default=HOME / ".local" / "share" / "pouch",
|
||||
)
|
||||
SOURCES_DIR = _first_existing_dir(
|
||||
DATA_DIR / "sources",
|
||||
HOME / ".local" / "share" / "pouch" / "sources",
|
||||
HOME / ".local" / "share" / "skiff" / "sources",
|
||||
default=HOME / ".local" / "share" / "pouch" / "sources",
|
||||
)
|
||||
STATE_FILE = DATA_DIR / "state.yaml"
|
||||
|
||||
AGENT_GLOBAL: dict[str, Path] = {
|
||||
"cursor": HOME / ".cursor" / "skills",
|
||||
|
||||
+6
-13
@@ -6,7 +6,7 @@ import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pouch import yaml_io
|
||||
from pouch.config import load_user_config, save_user_config
|
||||
from pouch.paths import CONFIG_FILE, SOURCES_DIR
|
||||
|
||||
RESERVED_SOURCES = {"builtin", "catalog", "owned", "registry"}
|
||||
@@ -21,27 +21,20 @@ def validate_source_name(name: str) -> None:
|
||||
|
||||
|
||||
def load_sources(path: Path | None = None) -> dict[str, dict[str, Any]]:
|
||||
path = path or CONFIG_FILE
|
||||
if not path.is_file():
|
||||
return {}
|
||||
data = yaml_io.safe_load(path.read_text(encoding="utf-8")) or {}
|
||||
if not isinstance(data, dict):
|
||||
raise SystemExit(f"pouch 配置格式错误: {path}")
|
||||
data = load_user_config(path)
|
||||
raw = data.get("sources", {})
|
||||
if raw is None:
|
||||
return {}
|
||||
if not isinstance(raw, dict):
|
||||
raise SystemExit(f"pouch 配置 sources 格式错误: {path}")
|
||||
raise SystemExit(f"pouch 配置 sources 格式错误: {path or CONFIG_FILE}")
|
||||
return {str(name): entry for name, entry in raw.items() if isinstance(entry, dict)}
|
||||
|
||||
|
||||
def save_sources(sources: dict[str, dict[str, Any]], path: Path | None = None) -> None:
|
||||
path = path or CONFIG_FILE
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(
|
||||
yaml_io.safe_dump({"sources": sources}, allow_unicode=True, sort_keys=False),
|
||||
encoding="utf-8",
|
||||
)
|
||||
data = load_user_config(path)
|
||||
data["sources"] = sources
|
||||
save_user_config(data, path)
|
||||
|
||||
|
||||
def source_checkout(name: str, entry: dict[str, Any]) -> Path:
|
||||
|
||||
+9
-1
@@ -59,6 +59,10 @@ def _parse_scalar(raw: str) -> Any:
|
||||
return True
|
||||
if lower == "false":
|
||||
return False
|
||||
if raw == "[]":
|
||||
return []
|
||||
if raw == "{}":
|
||||
return {}
|
||||
if raw.isdigit() or (raw.startswith("-") and raw[1:].isdigit()):
|
||||
return int(raw)
|
||||
return raw
|
||||
@@ -196,7 +200,11 @@ def _dump(data: Any, indent: int = 0) -> str:
|
||||
return f"{pad}{{}}\n"
|
||||
lines: list[str] = []
|
||||
for key, value in data.items():
|
||||
if isinstance(value, (dict, list)):
|
||||
if isinstance(value, list) and not value:
|
||||
lines.append(f"{pad}{key}: []")
|
||||
elif isinstance(value, dict) and not value:
|
||||
lines.append(f"{pad}{key}: {{}}")
|
||||
elif isinstance(value, (dict, list)):
|
||||
if isinstance(value, list) and value and all(isinstance(x, str) for x in value):
|
||||
lines.append(f"{pad}{key}:")
|
||||
for item in value:
|
||||
|
||||
+27
-7
@@ -18,8 +18,8 @@ ACK 是显式调用的 Agent Skill,用三种独立角色跑工程协作闭环
|
||||
| --- | --- | --- |
|
||||
| 初始化 | `/ack 初始化` | 生成并补全 `.pouch/ack/`;缺项按统一格式列出 |
|
||||
| 检查 | `/ack 检查配置` | 只读校验,默认不改文件;测试环境缺 deployer 时转交 |
|
||||
| 做需求 | `/ack 处理这个需求:…` | 产品文档 + 拆任务 → 你确认 → 三角色闭环 |
|
||||
| 修 bug | `/ack 修这个 bug:…` 或处理飞书收件 | 短描述 + 验收 → 你确认(飞书须你点「已确认」)→ 同一闭环 |
|
||||
| 做需求 | `/ack 处理这个需求:…` | 先建 ship 记录;复杂需求走 specifier / long-ship,小改动走 short-ship |
|
||||
| 修 bug | `/ack 修这个 bug:…` 或处理飞书收件 | 短描述 + 验收 → 你确认(飞书须你点「已确认」)→ 缺陷板闭环,交付链接 short-ship |
|
||||
| 交付配置 | 说明怎么布测试环境 / 怎么发版 | 写入同一份 `delivery.yaml`;测试环境绑定 deployer |
|
||||
| 运行测试环境 | `/ack 重新布测试环境` | 内部加载 deployer,布 `.pouch/deployer/<env>` |
|
||||
| 运行版本发布 | `/ack 发布一个版本` | 按 `intents.release`;stable/生产仍要单独批准 |
|
||||
@@ -37,7 +37,8 @@ pouch add ack -g # 全局
|
||||
## 使用前准备
|
||||
|
||||
- 项目是 Git 仓库。
|
||||
- 自动拉起 Developer / Test worker 时需要 Orca,以及项目里配置好的 Codex、Cursor、Grok 或 OMP。
|
||||
- 自动拉起 Developer / Test worker 时需要 Orca,以及项目里配置好的 Codex、Cursor、Grok、OMP 或 Pi。
|
||||
- 使用 Pi 时需安装 `pi`;默认模型用 `agents.yaml` 中 `cli: pi`、`model: null` 表示。
|
||||
- 布测试环境需要同时安装 [deployer](../deployer/README.md),并准备好 SSH 和目标机器的 Docker Compose。
|
||||
- 飞书收 bug 是可选的,要在 `project.md` 里配置 `bugIntake`。
|
||||
- 不要 `pouch init builder` 或 `pouch init deployer`。测试环境和发版直接对 `/ack` 说;缺 deployer 时 ACK 会转去它的初始化。
|
||||
@@ -54,15 +55,24 @@ pouch init ack --project ~/code/my-app
|
||||
```text
|
||||
.pouch/ack/
|
||||
├── project.md
|
||||
├── tasks.yaml
|
||||
├── tasks.yaml # 项目配置与 taskStore 指针
|
||||
├── task-records/ # 追加式任务/执行记录
|
||||
├── knowledge.yaml
|
||||
├── delivery.yaml # 默认 enabled: false
|
||||
└── regression.yaml # 默认 cases: []
|
||||
├── regression.yaml # 默认 cases: []
|
||||
└── agents.yaml # 可选:临时覆盖 Developer/Test 的 CLI、模型和权限
|
||||
```
|
||||
|
||||
不会把 ACK Skill 复制进项目。规范、模板和脚本始终从已安装的 Skill 目录读取。
|
||||
|
||||
旧项目如果只有 `project.md` 和 `tasks.yaml`,不要重跑初始化。说 `/ack 检查配置`,授权后再补空的 `knowledge.yaml` 等缺件。
|
||||
旧项目如果只有 `project.md` 和 `tasks.yaml`,不要重跑初始化。说 `/ack 检查配置`,授权后再补空的 `knowledge.yaml` 等缺件;需要消除单文件冲突时,先运行 `scripts/migrate_tasks.py` 的 dry-run。
|
||||
|
||||
任务状态追加示例:
|
||||
|
||||
```bash
|
||||
python3 <ack-skill-dir>/scripts/record_task.py .pouch/ack/tasks.yaml \
|
||||
--task-id T-001 --task-json /tmp/T-001.json --parent EV-T-001-initial
|
||||
```
|
||||
|
||||
## 使用示例
|
||||
|
||||
@@ -94,10 +104,20 @@ pouch init ack --project ~/code/my-app
|
||||
/ack 处理这个需求:…。任务验证通过后执行 review profile。
|
||||
```
|
||||
|
||||
临时调整角色启动方式时直接说明意图,例如:
|
||||
|
||||
```text
|
||||
/ack 让这个项目的 dev agent 用 pi 默认模型,test agent 用 cursor-agent auto 模型
|
||||
```
|
||||
|
||||
ACK 会在 `.pouch/ack/agents.yaml` 保存结构化覆盖配置。它存在时优先于
|
||||
`tasks.yaml.project.orchestration`;删除后自动回退。配置 hash 会绑定启动计划和 receipt,
|
||||
修改后必须重新审阅并生成 plan。
|
||||
|
||||
## Agent 会做什么
|
||||
|
||||
1. 初始化或检查 `.pouch/ack/`,缺项按统一格式列出;不从 README/CI 猜测并启用交付或知识。
|
||||
2. 做需求:先写产品文档、任务拆分和可观测验收;修 bug 只写短说明、复现和验收。你确认后再派 Developer 和独立 Test。
|
||||
2. 做需求:规格和任务写到 `.pouch/ship/<id>/`;修 bug 只写短说明、复现和验收,落缺陷板。你确认后再派 Developer 和独立 Test。
|
||||
3. 需要测试环境时加载 deployer,不自己编 compose,也不把本地 `npm run dev` 当成测试环境。
|
||||
4. 任务 `verified` 后提议把本轮黑盒路径写入回归目录,你确认后才写。
|
||||
5. 发版读同一份 `delivery.yaml`。默认最多停在 `validation_ready` 或 `review_ready`;稳定发布或生产部署必须再经过对应批准。
|
||||
|
||||
+64
-16
@@ -8,10 +8,24 @@ description: >-
|
||||
|
||||
# ACK 项目协作入口
|
||||
|
||||
项目只在 `.pouch/ack/` 保存 `project.md`、`tasks.yaml`、`knowledge.yaml`、
|
||||
`delivery.yaml` 和 `regression.yaml`。不要复制 Skill 内容,不要修改 `AGENTS.md`、
|
||||
项目只在 `.pouch/ack/` 保存 `project.md`、`tasks.yaml`、`task-records/`、`knowledge.yaml`、
|
||||
`delivery.yaml`、`regression.yaml`,以及可选的 `agents.yaml` 角色启动覆盖配置。
|
||||
不要复制 Skill 内容,不要修改项目的 `AGENTS.md`、
|
||||
`CLAUDE.md`。
|
||||
|
||||
执行位置和 profile 选择可以统一写在项目根 `.pouch/agent.yaml` 的 `ack.<name>` binding:
|
||||
`location` 提供 Orca environment/host/project/path,`profile` 提供 cli/model/
|
||||
`reasoningEffort`/permission。ACK 的 `agents.yaml` 或 tasks orchestration 仍保留其
|
||||
`profileVersion`、`modelAllowlist`、fingerprint/receipt 字段,并由 ACK adapter 做兼容
|
||||
映射;不要为了接入 common runtime 删除旧 receipt 或绕过 launcher。远程 ACK worker
|
||||
必须先按 binding 精确定位 worktree,不能把本机目录当远程目录。
|
||||
|
||||
固定配置文件为 `.pouch/ack/project.md`、`.pouch/ack/tasks.yaml`;任务执行记录从
|
||||
`.pouch/ack/task-records/` 追加读取。旧项目没有 `taskStore` 时仍兼容直接读取
|
||||
`tasks.yaml`。固定状态文件为 `.pouch/ack/project.md`、`.pouch/ack/tasks.yaml`、
|
||||
`.pouch/ack/knowledge.yaml`、`.pouch/ack/delivery.yaml` 和
|
||||
`.pouch/ack/regression.yaml`。
|
||||
|
||||
开始时解析当前 `SKILL.md` 所在目录为 `<ack-skill-dir>`。优先
|
||||
`git rev-parse --show-toplevel` 作为项目根。
|
||||
|
||||
@@ -19,22 +33,32 @@ description: >-
|
||||
|
||||
- 初始化、接入 ACK:执行「初始化」。
|
||||
- 检查配置是否完整:执行「检查」。
|
||||
- 做需求、修 bug 或继续任务:执行「工作」。修 bug 不写大 PRD。
|
||||
- 临时调整 Developer/Test 的 CLI 或模型:执行「角色启动配置维护」。
|
||||
- 做需求、修 bug 或继续任务:执行「工作」。修 bug 不写大 PRD。新功能和小改动的执行记录写
|
||||
`.pouch/ship/`,不要写进缺陷任务板。
|
||||
- 增改关闭交付、说明怎么布测试环境或发版:执行「交付配置维护」。
|
||||
- 部署或重布测试环境:执行「运行测试环境」(加载 deployer,不复制 compose)。
|
||||
- 部署或重布测试环境:执行「运行测试环境」(加载 deployer skill 的「初始化」或运行流程,不复制 compose)。
|
||||
- 发布版本:执行「运行版本发布」。回归:执行「运行回归」。
|
||||
- 任务板使用 Orca 时,编排命令见 [orca-adapter.md](references/orca-adapter.md)。
|
||||
|
||||
## 边界
|
||||
|
||||
- 不覆盖已有 `.pouch/ack`;除用户确认的任务或 delivery profile 外,不擅自提交、推送、创建终端、新 worktree、发布或部署。
|
||||
- 不覆盖已有 `.pouch/ack`;除用户确认的任务、agents profile 或 delivery profile 外,不擅自提交、推送、创建终端、新 worktree、发布或部署。
|
||||
- 不猜测命令、地址、worker handle 或模型名;无法确定写 `n/a`。
|
||||
- `agents.yaml` 是可选的临时角色启动覆盖;存在时优先于 `tasks.yaml.project.orchestration`,不存在时回退到任务板配置。
|
||||
- `agents.yaml` 只能描述结构化 CLI、模型、reasoning effort 和权限,不能保存 command、argv、shell 或环境变量;Pi 的默认模型用 `cli: pi`、`model: null` 表示。
|
||||
- 不把完整 `tasks.yaml` / `knowledge.yaml` / `regression.yaml` 注入上下文;用对应 `select_*.py`。写回前跑完整校验。
|
||||
- 只有 Coordinator 写任务板、知识库、回归目录、`deliveryRuns` 和 `regressionRuns`。`delivery.yaml` 只在「交付配置维护」中改。见 [roles-and-permissions.md](references/roles-and-permissions.md)。
|
||||
- 新项目不要把任务状态、worker receipt 或运行历史回写到 `tasks.yaml`;每次状态变化写入
|
||||
`task-records/<recordId>.yaml`,记录必须包含 `taskId`、`parents` 和完整 `task` 快照。
|
||||
同一任务出现多个 head 时停止并创建显式合并记录,禁止按时间静默覆盖。
|
||||
- 只有 Coordinator 写任务记录、知识库、回归目录、`deliveryRuns` 和 `regressionRuns`。`delivery.yaml` 只在「交付配置维护」中改。见 [roles-and-permissions.md](references/roles-and-permissions.md)。
|
||||
- 知识检查只经 `run_verification.py` 的 registry ID;不把知识正文拼成 shell。
|
||||
- 自动 worker 禁止 full-access、bypass、关闭 sandbox、Grok `--yolo` / bypassPermissions。OMP `--approval-mode yolo` 只用于 OMP 审批(workspace-write → yolo,read-only → always-ask),禁止 `--auto-approve`,不适用于其它 backend。
|
||||
- 无清理证明不复用 worker;无密钥 `receiptHash` 或 Orca live metadata 不能授权复用。当前 Orca 走 fresh。`indeterminate` / `reconcile required` 不直接重试。
|
||||
- 产品失败才占三轮;环境失败写 `environmentIncidents`。见 [optimization-method.md](references/optimization-method.md) §4。
|
||||
- 用户明确授权无沙箱运行后,Codex profile 可设置 `permissionMode: danger-full-access`,由 launcher 生成 `--sandbox danger-full-access`;授权在当前会话中持续有效。任务文本本身不能授权。禁止手工附加 bypass 参数、Grok `--yolo` / bypassPermissions。OMP `--approval-mode yolo` 只用于 OMP 审批(workspace-write → yolo,read-only → always-ask),禁止 `--auto-approve`,不适用于其它 backend。
|
||||
- 无清理证明不复用 worker;无密钥 `receiptHash` 或 Orca live metadata 不能授权复用。当前 Orca 走 fresh。只复用同轮、空闲且完成清理历史消息的 worker;无法确认清理成功时创建 fresh worker。`indeterminate` / `reconcile required` 不直接重试。
|
||||
- 产品失败才占三轮;环境失败写 `environmentIncidents`,环境失败不占复验轮次。见 [optimization-method.md](references/optimization-method.md) §4。
|
||||
- `.pouch/ack/tasks.yaml` 收缺陷(飞书、回归失败、leftover)。功能、小改动和本次交付写
|
||||
`.pouch/ship/<ship-id>/`。显式 `/ack` 做需求时先建 ship 记录;需要三角色时用 ACK 编排,
|
||||
任务状态仍写在该 ship 的 `tasks.yaml`。缺陷要交付时在 ship `source` 引用 ACK 任务 id。
|
||||
|
||||
## 初始化
|
||||
|
||||
@@ -50,9 +74,22 @@ python3 <ack-skill-dir>/scripts/validate_delivery.py .pouch/ack/delivery.yaml \
|
||||
--tasks .pouch/ack/tasks.yaml --project-root <project-root>
|
||||
python3 <ack-skill-dir>/scripts/validate_regression.py .pouch/ack/regression.yaml \
|
||||
--tasks .pouch/ack/tasks.yaml
|
||||
|
||||
# 仅在存在临时角色配置时运行
|
||||
python3 <ack-skill-dir>/scripts/validate_agents.py .pouch/ack/agents.yaml
|
||||
|
||||
```
|
||||
|
||||
4. 检查上述文件是否仍有 `<...>` 占位符。结构校验通过且必填项目事实完整才称「完成」。除非用户明确要求,不提交、不推送。
|
||||
4. 检查上述文件是否仍有 `<...>` 占位符;没有真实任务时使用 `tasks: []`。结构校验通过且必填项目事实完整才称「完成」。除非用户明确要求,不提交、不推送。
|
||||
旧项目迁移前先预览 `python3 <ack-skill-dir>/scripts/migrate_tasks.py .pouch/ack/tasks.yaml`,确认后再加 `--apply`。
|
||||
|
||||
追加任务状态时使用完整快照 JSON,不修改已有记录:
|
||||
|
||||
```bash
|
||||
python3 <ack-skill-dir>/scripts/record_task.py .pouch/ack/tasks.yaml \
|
||||
--task-id <task-id> --task-json <task-snapshot.json> \
|
||||
--parent <previous-record-id> --kind task.snapshot
|
||||
```
|
||||
|
||||
```text
|
||||
## ack 初始化:完成 | 部分完成 | 阻塞
|
||||
@@ -65,18 +102,29 @@ python3 <ack-skill-dir>/scripts/validate_regression.py .pouch/ack/regression.yam
|
||||
|
||||
## 检查
|
||||
|
||||
只读,不自动修复。核对清单见 [adoption-checklist.md](references/adoption-checklist.md)。用 `select_tasks.py` 看配置;跑与「初始化」相同的四个校验器。对比 `VERSION` 与 `ackVersion`(旧 `kitVersion` 仍可读);从 `0.10.0` 起 `project.orchestration` 与 `workerReceipts` 必须同时存在。旧项目可无 delivery/regression,存在或被引用时必须校验。若有 `bugIntake` 再跑 `feishu_bug_intake.py check`。若测试环境走 deployer,只读跑其 `check.py`;未通过列入待配置,不要复制 compose 或静默初始化 deployer。用同一报告格式,标题改为 `## ack 检查:…`。
|
||||
只读,不自动修复。核对清单见 [adoption-checklist.md](references/adoption-checklist.md)。用 `select_tasks.py` 看配置;跑与「初始化」相同的四个校验器;存在 `agents.yaml` 时再跑 `validate_agents.py`。对比 `VERSION` 与 `ackVersion`(旧 `kitVersion` 仍可读);从 `0.10.0` 起 `project.orchestration` 与 `workerReceipts` 必须同时存在。旧项目可无 delivery/regression,存在或被引用时必须校验。若有 `bugIntake` 再跑 `feishu_bug_intake.py check`。若测试环境走 deployer,只读跑其 `check.py`;未通过列入待配置,不要复制 compose 或静默初始化 deployer。用同一报告格式,标题改为 `## ack 检查:…`。
|
||||
|
||||
## 工作
|
||||
|
||||
1. `.pouch/ack` 不存在:停止并建议先 `/ack` 初始化;不要静默初始化。
|
||||
2. 读 `project.md`;用 `select_tasks.py`(已知任务加 `--task-id`)和 `select_knowledge.py` 取当前任务相关 `active` 条目。超预算时缩小选择,不回退为完整 yaml。
|
||||
3. 新需求或尚未确认的计划:读 [kickoff.md](references/kickoff.md)。修 bug 写短问题说明、复现和可观测验收,不写大 PRD。
|
||||
4. 用户已确认后按 [closed-loop.md](references/closed-loop.md) 执行。当前会话担任 Coordinator,不亲自写代码或跑测试。
|
||||
2. 读 `project.md`;若存在 `agents.yaml`,先用 `validate_agents.py` 校验并读取其 `defaults`;用 `select_tasks.py`(已知任务加 `--task-id`)和 `select_knowledge.py` 取当前任务相关 `active` 条目。超预算时缩小选择,不回退为完整 yaml。
|
||||
3. 新需求或尚未确认的计划:读 [kickoff.md](references/kickoff.md)。范围清楚的小改动转
|
||||
`short-ship`;复杂需求转 `specifier` / `long-ship`。修 bug 写短问题说明、复现和可观测
|
||||
验收,不写大 PRD;要交付时链接 `short-ship`。
|
||||
4. 用户已确认后,先读取并按 [closed-loop.md](references/closed-loop.md) 执行;使用 Orca 时同时读取 [orca-adapter.md](references/orca-adapter.md)。当前会话担任 Coordinator,不亲自写代码或跑测试;worker profile 按 `agents.yaml`(若存在)否则按任务板配置选择。
|
||||
这不是 fire-and-forget:Coordinator 不得在 `launch` / `dispatch` 后只回复“已派发”并结束当前会话。每个任务都必须在同一轮持续执行默认 60 秒窗口的 `check --wait`,并按 60–120 秒节奏运行 `worker_probe.py`,直到 Developer 回报 `worker_done` 或 `escalation`;随后写回 `fixed_by_dev`,主动派发 Test,并继续等待 `retest_result`。只有完成 Test 终检、重试/`leftover` 决策、回归决定和 worker 回收后,才可以结束本轮 ACK。
|
||||
5. 存在 `project.bugIntake` 时先完成「飞书收件」。创建或更换 worker 走「启动 worker」。若 `intents.testEnvironment` 已启用,派 Test 前先走「运行测试环境」。
|
||||
6. 知识 `verification.ref` 只经 `run_verification.py`。不把 `worker_done` 或 Test 自报成功当作完成。环境失败先有界恢复并报告 `userAction`;三轮产品失败记 `leftover`。
|
||||
7. 任务 `verified` 且改了可见行为或 API 后,转入「运行回归」收获用例。若本次计划含交付,再走对应交付模式;默认最多到 `validation_ready` 或 `review_ready`。
|
||||
8. 整轮完成后 `reclaim_workers.py` 先 dry-run 再 `--apply`,只回收仅属于 `verified` 任务的 worker。关闭结果不确定则记录,不伪报。
|
||||
8. 整轮任务完成后 `reclaim_workers.py` 先 dry-run 再 `--apply`,回收所有只属于 `verified` 任务的 worker 终端,并核对关闭回执;仍关联未完成任务的 worker 不设置 TTL。关闭结果不确定则记录,不伪报。
|
||||
|
||||
不能停在“任务已 `verified` 却声称整轮 ACK 已结束”:必须完成回归决定和 worker 回收。
|
||||
|
||||
## 角色启动配置维护
|
||||
|
||||
用户明确说「让这个项目的 dev agent 用 pi 默认模型、test agent 用 cursor-agent auto」等临时调整时,创建或更新 `.pouch/ack/agents.yaml`。配置文件形状见 [agents.template.yaml](templates/agents.template.yaml) 和 [agents.example.yaml](examples/agents.example.yaml),只写结构化 profile,不写自由命令。
|
||||
|
||||
存在 `agents.yaml` 时,ACK 的 `profile-hash`、`plan`、`launch` 和 receipt 全部绑定该文件的 hash;修改配置后必须重新 plan,旧 fingerprint 不能继续启动。删除该文件即可回退到 `tasks.yaml.project.orchestration`。配置本身不代表提交、推送、发布或部署授权。
|
||||
|
||||
## 飞书收件
|
||||
|
||||
@@ -84,7 +132,7 @@ python3 <ack-skill-dir>/scripts/validate_regression.py .pouch/ack/regression.yam
|
||||
|
||||
## 启动 worker
|
||||
|
||||
只使用 `scripts/launch_worker.py plan|launch`。不得直接 `orca terminal create --command`,不得拼接自由 command、argv、executable、env 或 cwd。读 [model-routing.md](references/model-routing.md)。先审阅 `plan.launchFingerprint`,再作为 `launch --expected-launch-fingerprint` 传入。派发文案用 [prompt-templates.md](references/prompt-templates.md)。派发后 terminal read 确认已开始;卡在审批、未回车或额度限制按环境失败处理。等待期间用 `scripts/worker_probe.py`,不盲等 `worker_done`。
|
||||
只使用 `scripts/launch_worker.py plan|launch`。不得直接 `orca terminal create --command`,不得拼接自由 command、argv、executable、env 或 cwd。读 [model-routing.md](references/model-routing.md)。先审阅 `plan.launchFingerprint`,再作为 `launch --expected-launch-fingerprint` 传入。派发文案用 [prompt-templates.md](references/prompt-templates.md)。派发后 terminal read 确认已开始;卡在审批、未回车或额度限制按环境失败处理。等待期间用 `scripts/worker_probe.py`,不盲等 `worker_done`。收到无错误的 `worker_done` / Test 复测结果后,按 [orca-adapter.md](references/orca-adapter.md) 用 `reclaim_workers.py --completed-task-id ... --completed-role ... --apply` 关闭对应 Orca terminal;失败、escalation 或环境异常不关闭。
|
||||
|
||||
## 交付配置维护
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
0.19.0
|
||||
0.20.0
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# Example .pouch/ack/agents.yaml for a temporary routing choice.
|
||||
profileVersion: 1
|
||||
mode: "orca"
|
||||
modelAllowlist:
|
||||
pi:
|
||||
developer:
|
||||
standard: [null]
|
||||
strong: [null]
|
||||
cursor-agent:
|
||||
test:
|
||||
standard: ["auto"]
|
||||
profiles:
|
||||
pi-dev-default:
|
||||
role: "developer"
|
||||
cli: "pi"
|
||||
tier: "standard"
|
||||
model: null
|
||||
reasoningEffort: "medium"
|
||||
permissionMode: "workspace-write"
|
||||
pi-dev-strong:
|
||||
role: "developer"
|
||||
cli: "pi"
|
||||
tier: "strong"
|
||||
model: null
|
||||
reasoningEffort: "high"
|
||||
permissionMode: "workspace-write"
|
||||
cursor-test-auto:
|
||||
role: "test"
|
||||
cli: "cursor-agent"
|
||||
tier: "standard"
|
||||
model: "auto"
|
||||
reasoningEffort: null
|
||||
permissionMode: "workspace-write"
|
||||
defaults:
|
||||
developer: "pi-dev-default"
|
||||
test: "cursor-test-auto"
|
||||
developerUpgraded: "pi-dev-strong"
|
||||
@@ -1,10 +1,10 @@
|
||||
# notes-web Agent 协作协议(示例,项目覆盖层)
|
||||
|
||||
> 本项目基于 ack v0.19.0。
|
||||
> 本项目基于 ack v0.20.0。
|
||||
> 通用规范由 `/ack` 从 Skill 自身的 `references/` 读取,本文件只填项目差异。
|
||||
> 覆盖层文件放在 `.pouch/ack/project.md`,不占用 `AGENTS.md`。
|
||||
> ACK 不会自动修改 `AGENTS.md`、`CLAUDE.md` 或其它 Agent 指令文件。
|
||||
> `.pouch/ack/` 只保存 `project.md`、`tasks.yaml`、`knowledge.yaml`、`delivery.yaml`
|
||||
> `.pouch/ack/` 只保存 `project.md`、`tasks.yaml`、`task-records/`、`knowledge.yaml`、`delivery.yaml`
|
||||
> 与 `regression.yaml`。
|
||||
|
||||
## 项目概览
|
||||
@@ -13,7 +13,8 @@
|
||||
- 技术栈:`TypeScript + React (Vite) + Go`
|
||||
- 运行命令:`npm run dev`(前端)、`go run ./server`(后端)
|
||||
- Base URL:`http://localhost:5173`
|
||||
- 任务板:`.pouch/ack/tasks.yaml`
|
||||
- 任务板配置:`.pouch/ack/tasks.yaml`
|
||||
- 任务记录:`.pouch/ack/task-records/<recordId>.yaml`
|
||||
- 项目知识:`.pouch/ack/knowledge.yaml`
|
||||
- 交付契约:`.pouch/ack/delivery.yaml`
|
||||
- 回归目录:`.pouch/ack/regression.yaml`
|
||||
@@ -33,8 +34,9 @@
|
||||
|
||||
## Worker 路由
|
||||
|
||||
结构化配置位于 `.pouch/ack/tasks.yaml` 的 `project.orchestration`,启动记录位于顶层
|
||||
`workerReceipts`。本项目默认使用:
|
||||
结构化配置默认位于 `.pouch/ack/tasks.yaml` 的 `project.orchestration`;存在
|
||||
`.pouch/ack/agents.yaml` 时以后者为准。启动记录位于顶层 `workerReceipts`。
|
||||
本项目默认使用:
|
||||
|
||||
| 角色 | profile ID | 档位 |
|
||||
|------|------------|------|
|
||||
@@ -42,8 +44,8 @@
|
||||
| Test | `codex-test-standard` | standard |
|
||||
| Developer 升级 | `codex-dev-strong` | strong |
|
||||
|
||||
项目如改用 Cursor 或 Grok,应修改结构化 profile、allowlist 和 defaults,再运行
|
||||
任务板校验。本文件不保存或拼接 worker shell 命令。
|
||||
项目如临时改用 Pi、Cursor 或 Grok,应修改 `agents.yaml` 的结构化 profile、allowlist
|
||||
和 defaults,再运行对应校验。本文件不保存或拼接 worker shell 命令。
|
||||
|
||||
## 路径权限
|
||||
|
||||
@@ -56,7 +58,8 @@
|
||||
| `**/*_test.go`、`web/**/*.test.tsx` | Read-only | Read-only | R/W | 单元测试 |
|
||||
| `config/*.example.*` | Read-only | Read-only | R/W | 可提交配置模板 |
|
||||
| `.env`、`config/local.*` | Read-only | Read-only | Read-only | 本地私有配置 |
|
||||
| `tasks.yaml` | R/W | Read-only | Read-only | 只有 Coordinator 写 |
|
||||
| `tasks.yaml` | R/W | Read-only | Read-only | 稳定项目配置;任务状态见 `task-records/` |
|
||||
| `task-records/` | R/W | Read-only | Read-only | 只有 Coordinator 追加 |
|
||||
| `knowledge.yaml` | R/W | Read-only | Read-only | 只有 Coordinator 写;Developer/Test 通过回报提名或验证 |
|
||||
| `regression.yaml` | R/W | Read-only | Read-only | 只有 Coordinator 写;Test 通过 regressionCandidates 提名 |
|
||||
| `delivery.yaml` | 仅显式维护时 R/W | Read-only | Read-only | 项目交付能力,不是执行授权 |
|
||||
@@ -100,7 +103,7 @@ path/args。
|
||||
worker;持久化 receipt 只作审计。仅同轮空闲、身份匹配并可信清理历史消息后复用;
|
||||
整轮结束回收 verified 任务终端,blocked/failed/leftover 终端保留且不设 TTL。
|
||||
- `worker_done` 与复测报告都不等于完成,必须 Test 独立复测 + Coordinator 终检后才能 `verified`。
|
||||
- 只有 Coordinator 写 `tasks.yaml` 和 `knowledge.yaml`;Test 与 Developer 只读。
|
||||
- 只有 Coordinator 写 `task-records/` 和 `knowledge.yaml`;Test 与 Developer 只读。
|
||||
- Coordinator 只派发按 scope 命中并显式写入 `knowledgeRefs` 的 `active` 知识;
|
||||
`candidate` 不派发,知识库不全量注入。
|
||||
- Developer 回报 `knowledgeApplied` 与 `knowledgeCandidates`,Test 回报
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
version: 1
|
||||
updatedAt: "2026-07-06T09:40:00+08:00"
|
||||
source: "Coordinator (PM) Agent"
|
||||
ackVersion: "0.19.0"
|
||||
ackVersion: "0.20.0"
|
||||
project:
|
||||
name: "notes-web"
|
||||
baseUrl: "http://localhost:5173"
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
|
||||
- [ ] ACK Skill 已全局安装或安装到当前项目。
|
||||
- [ ] 已运行 `pouch init ack --project <project-root>`。
|
||||
- [ ] `.pouch/ack/` 只包含项目自己的 `project.md`、`tasks.yaml`、`knowledge.yaml`、
|
||||
- [ ] `.pouch/ack/` 只包含项目自己的 `project.md`、`tasks.yaml`、`task-records/`、`knowledge.yaml`、
|
||||
默认关闭的 `delivery.yaml` 与空的 `regression.yaml`。
|
||||
- [ ] 旧项目缺少 `knowledge.yaml` 时,只补空文件及缺失的
|
||||
`project.knowledgeFile` 指针,没有重跑初始化或覆盖其它项目状态。
|
||||
- [ ] 项目中没有 ACK Skill 的复制目录或 `kit`、`framework` 软链接。
|
||||
- [ ] `tasks.yaml` 使用 `ackVersion` 记录 ACK Skill 版本。
|
||||
- [ ] 若存在 `.pouch/ack/agents.yaml`,已运行 `validate_agents.py`;它优先于任务板
|
||||
`project.orchestration`,且只包含结构化 profile,不包含自由 command/argv/env。
|
||||
|
||||
## 项目覆盖层
|
||||
|
||||
@@ -24,7 +26,9 @@
|
||||
- [ ] 技术栈、运行、构建、单测和集成测试命令均来自项目证据。
|
||||
- [ ] Coordinator、Developer、Test 的模型档位和升级规则已明确。
|
||||
- [ ] `project.orchestration` 使用受支持的 profileVersion,模型都命中项目
|
||||
allowlist,默认 profile 与角色/档位一致。
|
||||
allowlist,默认 profile 与角色/档位一致。
|
||||
- [ ] `agents.yaml`(若存在)使用受支持的 profileVersion,Pi 默认模型使用
|
||||
`cli: pi` + `model: null`,配置 hash 会绑定启动 plan/fingerprint/receipt。
|
||||
- [ ] `allowedWorktrees` 已废弃(v0.19 起),新任务板不配置;worker 默认在
|
||||
`--project-root` 工作,其它 worktree 由 launcher 按同 git 仓库且已注册约束放行。
|
||||
- [ ] `tasks.yaml` 不需要保存 `repoPath` 或 `devWorktree`;项目状态从当前
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
本文件定义**与具体编排工具无关**的三角色协作闭环。运行时调度可以用 Orca(见 `orca-adapter.md`),也可以手动跑(见下方「手动模式」)。
|
||||
|
||||
原则:调度消息只是运行时载体,任务结论必须回写到 `tasks.yaml`;已经验证且可跨
|
||||
原则:调度消息只是运行时载体,任务结论必须追加到 `task-records/`(由读取层
|
||||
materialize 成任务视图);已经验证且可跨
|
||||
任务使用的项目经验必须由 Coordinator 回写到 `knowledge.yaml`。不要把消息当最终记录。
|
||||
角色定义见 `roles-and-permissions.md`:Coordinator 只编排、Test 只验证、
|
||||
Developer 只实现。
|
||||
@@ -15,12 +16,12 @@ Developer 只实现。
|
||||
|
||||
| 抽象动作 | 含义 | Orca 实现 | 手动实现 |
|
||||
|----------|------|-----------|----------|
|
||||
| `prepare(task)` | Coordinator 把任务和验收信号写进 `tasks.yaml`,按 scope 推荐知识并确认显式 `knowledgeRefs` | 同左 | 同左 |
|
||||
| `prepare(task)` | Coordinator 把任务和验收信号写进 `task-records/`,按 scope 推荐知识并确认显式 `knowledgeRefs` | 同左 | 同左 |
|
||||
| `dispatch(task, developer)` | 把修复任务连同上下文交给 Developer | `orca orchestration dispatch` | 复制 prompt 到 Developer 终端/会话 |
|
||||
| `dispatch(task, test)` | 把复测任务连同验收信号交给 Test | `orca orchestration dispatch` | 复制 prompt 到 Test 终端/会话 |
|
||||
| `wait()` | 等待 `worker_done` / `retest_result` / `escalation` / `decision_gate` | `orca orchestration check --wait` | 人工等待回报 |
|
||||
| `gate(task)` | Coordinator 读 Test 证据、`knowledgeChecks` 并对齐原始意图(不重测) | 同左 | 同左 |
|
||||
| `writeback(task, result)` | Coordinator 把任务结果写回 `tasks.yaml`,把验证通过的跨任务经验按权限写入 `knowledge.yaml` | 同左 | 同左 |
|
||||
| `writeback(task, result)` | Coordinator 把任务结果追加到 `task-records/`,把验证通过的跨任务经验按权限写入 `knowledge.yaml` | 同左 | 同左 |
|
||||
|
||||
派发用的 prompt 见 `prompt-templates.md`。状态流转见 `roles-and-permissions.md` §「任务状态机」。**独立复测由 Test 执行,不是 Coordinator**;Coordinator 只做读证据的终检。
|
||||
|
||||
@@ -30,14 +31,14 @@ Developer 只实现。
|
||||
|
||||
```text
|
||||
Coordinator 发现或读取 open 任务
|
||||
-> prepare:写/补全 tasks.yaml 验收信号
|
||||
-> prepare:写/补全 task-records/ 中的任务验收信号
|
||||
-> 从 knowledge.yaml 按 scope 推荐 active 知识,Coordinator 确认固定 revision 的 knowledgeRefs
|
||||
-> 为新轮次生成稳定 attemptId(<task-id>-A<round>),Developer 与 Test 共用
|
||||
-> 决定 worktree:当前 worktree 起子 agent,还是新建隔离 worktree(见下节「子任务放哪」)
|
||||
-> 解析安全 profile:机器配置只读 tasks.yaml.project.orchestration
|
||||
-> 解析安全 profile:机器配置只读 agents.yaml(存在时),否则读取 tasks.yaml.project.orchestration
|
||||
-> 运行 launcher plan 并审阅 launchFingerprint
|
||||
-> 检查同轮空闲 worker;可信清理历史消息成功才复用,否则带 expected fingerprint 启动 fresh worker
|
||||
-> 把本次 task/attempt receipt 写回 tasks.yaml(见 orca-adapter.md)
|
||||
-> 把本次 task/attempt receipt 追加到 task-records/(见 orca-adapter.md)
|
||||
-> dispatch 给 Developer(--to <worker handle>)
|
||||
-> 确认 Developer 已开始执行(terminal read 确认任务注入;未开始按环境失败处理)
|
||||
-> wait:滚动 check --wait + 定期 worker_probe(识别审批/未回车/额度停滞)
|
||||
@@ -133,7 +134,7 @@ python3 <ack-skill-dir>/scripts/launch_worker.py launch \
|
||||
- 适合:串行闭环、一次一个 Developer 任务、小改动、Test 要复测的正是 Developer 改的那棵树。
|
||||
- 优点:单一服务实例、无跨 worktree 对齐困扰、开销小。
|
||||
- 风险:多个 agent 同时改同一棵树会互相踩(半构建状态、git 冲突)。
|
||||
- 记录:`launch` 成功后把 receipt 追加到权威 `tasks.yaml.workerReceipts`,并把
|
||||
- 记录:`launch` 成功后把 receipt 追加到当前任务记录的 `workerReceipts`,并把
|
||||
`receipt.id` 写入 `dispatch.<role>.receiptId`、把 `profileId` 写入
|
||||
`dispatch.<role>.profileId`、把本轮稳定 ID 写入 `dispatch.<role>.attemptId`;
|
||||
receipt 的 task/role/profile/attempt 必须与当前 dispatch 完全一致,不能只记录
|
||||
@@ -173,9 +174,10 @@ python3 <ack-skill-dir>/scripts/launch_worker.py launch \
|
||||
| 要保持基线分支干净 | 新 worktree(feature 分支)|
|
||||
| 小改动、追求快 | 当前 worktree |
|
||||
|
||||
**项目状态(SSOT)只落一处**:无论开几个 worktree,`tasks.yaml`、
|
||||
**项目配置 SSOT 只落一处**:无论开几个 worktree,`tasks.yaml`、
|
||||
`knowledge.yaml`、可选 `delivery.yaml` 和可选 `regression.yaml` 都只认一个权威
|
||||
副本(通常在基线/协调所在 worktree)。Coordinator 单写任务、知识、回归目录、
|
||||
副本(通常在基线/协调所在 worktree)。任务执行状态追加到
|
||||
`.pouch/ack/task-records/<recordId>.yaml`;Coordinator 单写任务记录、知识、回归目录、
|
||||
`deliveryRuns` 与 `regressionRuns`;交付能力只在显式配置维护时修改。`project.orchestration`、顶层 `workerReceipts` 和任务 dispatch 也只写入这个
|
||||
副本;不要每个 worktree 各留一份会分叉的项目状态。profile 解析、launcher 与
|
||||
receipt 规则见 `model-routing.md` 和 `orca-adapter.md`。
|
||||
@@ -190,20 +192,20 @@ v0.10 的 full-access 授权与撤销机制仍是 Deferred;launcher 遇到 ful
|
||||
|
||||
没有编排工具时,闭环不变,只是 `dispatch` / `wait` 由人工承担:
|
||||
|
||||
1. Coordinator 在 `tasks.yaml` 写好任务和验收信号。
|
||||
1. Coordinator 在 `task-records/` 写入包含完整任务快照的初始记录和验收信号。
|
||||
2. 从 `knowledge.yaml` 推荐相关 active 知识,Coordinator 确认固定 revision 的
|
||||
`knowledgeRefs`;用 `prompt-templates.md` §1 的初始派发模板生成 prompt,
|
||||
手动发给 Developer(另一个会话/终端/人)。
|
||||
3. Developer 完成后按 worker_done 模板回报。
|
||||
4. Coordinator 写回 `fixed_by_dev`,用 `prompt-templates.md` §3 的复测派发模板把任务发给 Test。
|
||||
5. Test 独立复测后按复测报告模板回报证据和 `knowledgeChecks`。
|
||||
6. Coordinator 做终检并回写 `tasks.yaml`:通过 `verified`,不过 `failed_retest`。
|
||||
6. Coordinator 做终检并追加新记录:通过 `verified`,不过 `failed_retest`。
|
||||
7. 产品失败则用「复测失败再派发模板」重新发给 Developer,最多累计三轮有效产品
|
||||
复验;环境失败写入 `dispatch.environmentIncidents`,恢复环境后重新派发 Test,
|
||||
不派 Developer、不消耗产品轮次。
|
||||
|
||||
手动模式下同样遵守:worker_done / 复测报告都不等于最终结论、只有 Coordinator
|
||||
写 `tasks.yaml` 和 `knowledge.yaml`、三轮失败留档。若本次确认计划还包含交付,所有
|
||||
写 `task-records/` 和 `knowledge.yaml`、三轮失败留档。若本次确认计划还包含交付,所有
|
||||
选中任务 `verified` 后由 Coordinator 继续按 `delivery.md` 执行并写 `deliveryRuns`。
|
||||
|
||||
手动交给用户已打开的会话不等于产生 ACK receipt。该会话可以完成本次显式 handoff,
|
||||
@@ -233,7 +235,7 @@ actual:
|
||||
snapshot evidence:
|
||||
```
|
||||
|
||||
Test 只回传证据,不写 `tasks.yaml` 或 `knowledge.yaml`;由 Coordinator 落盘。
|
||||
Test 只回传证据,不写 `task-records/` 或 `knowledge.yaml`;由 Coordinator 追加落盘。
|
||||
每条适用的显式 `knowledgeRef` 还应报告 `passed`、`failed` 或
|
||||
`not_applicable` 及证据。
|
||||
|
||||
@@ -277,7 +279,8 @@ worktreePath:
|
||||
|
||||
## 结果回写
|
||||
|
||||
Coordinator 回写 `tasks.yaml` 时按状态填写(字段结构见 `templates/tasks.schema.json`):
|
||||
Coordinator 追加任务记录时按状态填写(记录内的 `task` 字段结构见
|
||||
`templates/tasks.schema.json`):
|
||||
|
||||
```yaml
|
||||
# 通过(Test 复测 + Coordinator 终检)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
本文件定义可选的 `verified -> validation_ready/review_ready/released` 交付阶段。开发、独立复测和
|
||||
Coordinator 终检仍由 ACK 原有闭环负责;只有选中的任务全部 `verified` 后才能进入
|
||||
交付。项目配置位于 `.pouch/ack/delivery.yaml`,运行证据写入
|
||||
`.pouch/ack/tasks.yaml.deliveryRuns`。
|
||||
任务记录的 `deliveryRuns`(读取时 materialize 到任务视图)。
|
||||
|
||||
## 1. 配置与授权不是一回事
|
||||
|
||||
@@ -78,7 +78,7 @@ intents:
|
||||
口头「发版」不能代替 stable/production 的 `approval` 步骤。
|
||||
- 对应 intent 为 `null` 或交付未启用:停止,请用户说明怎么做,按「交付配置维护」
|
||||
写入同一文件后再执行。不猜测 Makefile、镜像仓库或发布通道。
|
||||
- 用户触发的 intent 运行写入 `tasks.yaml.deliveryRuns`,`intent` 填
|
||||
- 用户触发的 intent 运行追加到任务记录的 `deliveryRuns`,`intent` 填
|
||||
`testEnvironment` 或 `release`,`taskIds` 可为空。测试环境 run 的 `profile` 记
|
||||
`deployer-<env>`。绑定任务的常规交付 run 不填 `intent`,仍只能引用
|
||||
`verified` 任务。
|
||||
@@ -114,12 +114,15 @@ intents:
|
||||
PR/MR。普通任务使用项目已确认的 Forge 流程;只有本次是版本发布生命周期且用户
|
||||
明确要求时才调用独立的 `releaser`。没有对应能力或认证时标记 blocked,不用
|
||||
带 token 的临时 curl 兜底。remote 与 base branch 必须来自该步骤,不能临时猜测。
|
||||
- `build`:调用 artifact 的 build entrypoint。DEB 必须记录包名、版本、架构和
|
||||
SHA-256;OCI image 必须记录完整引用、platform 和 digest。产物必须绑定当前 source
|
||||
revision,不能在目标机器重新拉源码构建。
|
||||
- `build`:对当前 source revision 调用已安装的 `builder` `obtain.sh --sha <revision>`,
|
||||
不要假定本机 `make`。`BUILD_VENUE=ci` 时监听该 SHA 的流水线;没有流水线或 job 失败
|
||||
则本步 `failed`。DEB 必须记录包名、版本、架构和 SHA-256;OCI image 必须记录完整
|
||||
引用、platform 和 digest。产物必须绑定当前 source revision,不能在目标机器重新拉
|
||||
源码构建。
|
||||
- `publish`:验证 artifact/destination 类型兼容,上传精确产物。DEB 与 Docker 均可使用
|
||||
已安装的 `builder`;Docker 轨道保持显式触发——只有用户明确点名(builder / 发布镜像)
|
||||
时才加载,否则必须走契约中已审查的 upload entrypoint。项目入口只接受
|
||||
时才加载,否则必须走契约中已审查的 upload entrypoint。`BUILD_VENUE=ci` 且 obtain
|
||||
已带回 registry digest 时,本步只复核,不再本机 push。项目入口只接受
|
||||
刚校验的精确 artifact。preview/staging 使用不可覆盖的 commit/PR 标识,不隐式使用
|
||||
`latest`。既没有可用 skill 也没有 upload 入口时标记 blocked。
|
||||
- `deploy`:把同一不可变 artifact 交给 environment 的 deploy entrypoint;获取目标
|
||||
|
||||
@@ -103,6 +103,9 @@ pouch init ack --project <project-root>
|
||||
- `allowedWorktrees` 已废弃(v0.19 起),新任务板不生成该字段;worker 默认在
|
||||
`--project-root` 工作。模型 allowlist、profiles 和 defaults 使用项目实际允许值。
|
||||
不要把完整启动命令、`extraArgs`、`env` 或任意 executable 写进任务板。
|
||||
- `.pouch/ack/agents.yaml` 是可选的临时 worker 路由覆盖;存在时优先于任务板中的
|
||||
`project.orchestration`。它必须使用结构化 profile;Pi 默认模型写成 `cli: pi`、
|
||||
`model: null`,不能写自由命令。
|
||||
- 非服务项目的 `baseUrl` 写为 `n/a`。
|
||||
- 没有真实任务时使用 `tasks: []`,不要保留或虚构示例任务。
|
||||
|
||||
@@ -152,6 +155,8 @@ python3 <ack-skill-dir>/scripts/validate_delivery.py .pouch/ack/delivery.yaml \
|
||||
--tasks .pouch/ack/tasks.yaml --project-root <project-root>
|
||||
python3 <ack-skill-dir>/scripts/validate_regression.py .pouch/ack/regression.yaml \
|
||||
--tasks .pouch/ack/tasks.yaml
|
||||
# 存在临时角色配置时
|
||||
python3 <ack-skill-dir>/scripts/validate_agents.py .pouch/ack/agents.yaml
|
||||
```
|
||||
|
||||
同时确认:
|
||||
@@ -164,6 +169,8 @@ python3 <ack-skill-dir>/scripts/validate_regression.py .pouch/ack/regression.yam
|
||||
- Developer 与 Test 的验证命令可执行。
|
||||
- `project.orchestration` 的 profile/allowlist/defaults 通过校验,自动模式只允许
|
||||
`read-only` 或 `workspace-write`;旧任务板未迁移时保持手动模式。
|
||||
- 若存在 `agents.yaml`,其 profile/allowlist/defaults 也通过校验,且启动配置 hash
|
||||
会绑定 plan、fingerprint 和 receipt。
|
||||
- 顶层 `workerReceipts` 和 `dispatch.developer/test` 的 task/role/profile/attempt
|
||||
引用一致;`receiptId` 与 `attemptId` 同时为空或同时填写。持久 receipt 只作审计,
|
||||
不能单独授权复用旧终端;复用还需要空闲状态、身份匹配和可信历史清理证明。
|
||||
|
||||
@@ -4,14 +4,18 @@
|
||||
用户确认后的三角色闭环、飞书收件、启动 worker、交付和回归由 `SKILL.md` 按条件加载,
|
||||
不要在本文件开头预读其它规范。
|
||||
|
||||
复杂需求的规格和任务写在 `.pouch/ship/<ship-id>/`(specifier + long-ship)。ACK 任务板
|
||||
只收缺陷。显式 `/ack` 做功能需求时也先建 ship 记录,不要把功能任务写成 `type: bug`。
|
||||
|
||||
---
|
||||
|
||||
## 前提:谁是 Coordinator
|
||||
|
||||
**你(发起编排的强模型会话)就是 Coordinator (PM) / 产品。** 你负责写文档、拆任务、
|
||||
编排、终检,**不亲自写代码、不亲自跑测试**。开发和测试是另起的 worker agent;
|
||||
具体 CLI、模型、reasoning effort 和执行模式的机器事实源是
|
||||
`.pouch/ack/tasks.yaml` 的 `project.orchestration`。`.pouch/ack/project.md` 只解释项目
|
||||
具体 CLI、模型、reasoning effort 和执行模式的机器事实源优先是
|
||||
`.pouch/ack/agents.yaml`,不存在时回退到 `.pouch/ack/tasks.yaml` 的
|
||||
`project.orchestration`。`.pouch/ack/project.md` 只解释项目
|
||||
差异,不能提供另一套启动命令。
|
||||
|
||||
---
|
||||
@@ -32,7 +36,7 @@
|
||||
2. 写产品文档到 docs/(PRD / 交互 / 验收),把需求拆成任务,每个任务的验收写成可观测信号(可见文本 / API 结果 / 交互结果)。
|
||||
3. 按任务 scope 从 knowledge.yaml 推荐 active 知识,确认后把固定 revision 的
|
||||
knowledgeRefs 写入任务;不要派发 candidate 或全量知识库。
|
||||
4. 把任务写进 .pouch/ack/tasks.yaml(只有你写),校验 tasks.yaml 和 knowledge.yaml。
|
||||
4. 把任务作为完整快照追加到 `.pouch/ack/task-records/`(只有你写),校验任务视图和 knowledge.yaml。
|
||||
5. 先把「产品文档 + 任务拆分 + 验收信号 + 适用知识引用」给我确认;若启用了交付,
|
||||
同时列明本次 profile、目标、停止点与审批步骤。不要急着派发或交付。
|
||||
6. 我确认后,按 ack 闭环循环:先用 `scripts/launch_worker.py` 校验结构化
|
||||
@@ -40,7 +44,7 @@
|
||||
只有历史消息已可信清理并取得新会话身份才复用,否则审阅 plan 后用 expected
|
||||
fingerprint 创建 fresh worker;
|
||||
dispatch 开发 → worker_done → 若 intents.testEnvironment 已启用则先用 deployer 拉起测试环境 →
|
||||
dispatch 测试独立复测 → 你读证据终检 → 回写 tasks.yaml;
|
||||
dispatch 测试独立复测 → 你读证据终检 → 追加 task-records;
|
||||
每个任务最多三轮有效产品复验,三轮不过记 leftover 并升级我复盘;环境失败单独
|
||||
记录、恢复并告诉我下一步,不占产品复验轮次。
|
||||
7. 所选任务都 verified 后,按 SKILL.md「运行回归」给出新增/更新/退役/无回归,确认后写入
|
||||
@@ -65,8 +69,8 @@ python3 <ack-skill-dir>/scripts/validate_tasks.py .pouch/ack/tasks.yaml
|
||||
python3 <ack-skill-dir>/scripts/validate_knowledge.py .pouch/ack/knowledge.yaml --tasks .pouch/ack/tasks.yaml
|
||||
```
|
||||
|
||||
`project.orchestration` 是 worker profile 的机器 SSOT;未知字段、非 allowlist 模型、
|
||||
不匹配的角色/档位和非安全权限必须在派发前 fail closed。
|
||||
有效 worker routing(`agents.yaml` 优先,否则 `project.orchestration`)是 profile 的机器
|
||||
SSOT;未知字段、非 allowlist 模型、不匹配的角色/档位和非安全权限必须在派发前 fail closed。
|
||||
|
||||
读取任务上下文使用:
|
||||
|
||||
@@ -96,7 +100,7 @@ python3 <ack-skill-dir>/scripts/select_tasks.py .pouch/ack/tasks.yaml \
|
||||
|
||||
## 第 3 步:审阅并启动 worker
|
||||
|
||||
先读 `tasks.yaml.project.orchestration` 的结构化 profiles。历史 receipt 或既有 Orca
|
||||
先读有效 routing(`agents.yaml` 优先,否则 `tasks.yaml.project.orchestration`)的结构化 profiles。历史 receipt 或既有 Orca
|
||||
terminal 不能单独授权复用。复用候选必须属于同一轮 ACK、处于空闲状态,且角色、
|
||||
profile、worktree 与启动身份仍完全匹配;还必须通过受信后端清理历史消息并取得可核对
|
||||
的新会话身份。当前 Orca 接口缺少该清理证明,所以 Orca 派发仍创建 fresh worker。
|
||||
@@ -196,7 +200,7 @@ Coordinator 最后标记整轮任务完成后,用 `scripts/reclaim_workers.py`
|
||||
## 一句话
|
||||
|
||||
产品文档 + 验收信号写在前(你,强模型)→ 确认显式 `knowledgeRefs` → 从
|
||||
`tasks.yaml.project.orchestration` 解析安全 profile → 审阅 plan 并用 expected
|
||||
有效 routing(`agents.yaml` 优先,否则 `tasks.yaml.project.orchestration`)解析安全 profile → 审阅 plan 并用 expected
|
||||
fingerprint 启动 fresh DEV/TEST → dispatch / 复测 / 终检循环 → 任务结论落
|
||||
`tasks.yaml` → 可选收获回归用例到 `regression.yaml` → 可选 delivery profile
|
||||
到审核点,验证后的跨任务知识由 Coordinator 落 `knowledge.yaml` → 整轮完成后回收
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 模型路由(稳定核心)
|
||||
|
||||
本文件是**三角色默认模型档位、升级规则和 worker profile 选择规则**的单一规范源。
|
||||
本文件是**三角色默认模型档位、升级规则和 worker profile 选择规则**的规范源。
|
||||
目标是在不牺牲质量的前提下降低 token 和模型成本:把昂贵的强模型留给需要判断的
|
||||
工作,把机械执行交给较弱模型。
|
||||
|
||||
@@ -64,23 +64,32 @@ profile 升级时不得复用旧 worker,Test 也不得使用 Developer 的强
|
||||
|
||||
## 结构化 worker profile
|
||||
|
||||
### 机器事实源
|
||||
### 机器事实源与项目临时覆盖
|
||||
|
||||
worker 路由的机器可读事实只保存在 `.pouch/ack/tasks.yaml` 的
|
||||
`project.orchestration`。`project.md` 可以解释项目为何选某个档位,但不能另写一份
|
||||
完整启动命令或覆盖机器配置。字段结构以 `templates/tasks.schema.json` 为准。
|
||||
worker 路由的机器可读事实默认保存在 `.pouch/ack/tasks.yaml` 的
|
||||
`project.orchestration`。项目需要临时调整角色 CLI 或模型时,可以在同一目录增加
|
||||
`.pouch/ack/agents.yaml`;它使用与 `project.orchestration` 相同的结构,且优先级更高。
|
||||
删除该文件即回退到任务板配置。`project.md` 只能解释项目为何选某个档位,不能另写一份
|
||||
完整启动命令或覆盖机器配置。字段结构以 `templates/tasks.schema.json` 和
|
||||
`templates/agents.schema.json` 为准。
|
||||
|
||||
`agents.yaml` 的配置 hash 会进入 profile-hash、launch plan、fingerprint 和 receipt。
|
||||
因此修改临时配置后必须重新审阅 plan;旧 fingerprint 不会被接受。
|
||||
|
||||
每个 profile 明确声明:
|
||||
|
||||
- `role`:`developer` 或 `test`;
|
||||
- `cli`:受支持的 Agent CLI(`codex`、`cursor-agent`、`grok`、`omp`);
|
||||
- `cli`:受支持的 Agent CLI(`codex`、`cursor-agent`、`grok`、`omp`、`pi`);
|
||||
- `tier`:角色模型档位;
|
||||
- `model`:项目 allowlist 中的精确模型 ID;
|
||||
- `model`:项目 allowlist 中的精确模型 ID;Pi 可用 `null` 表示其默认模型;
|
||||
- `reasoningEffort`:CLI 支持时显式声明;
|
||||
- `permissionMode`:只允许 `read-only` 或 `workspace-write`。
|
||||
- `permissionMode`:`read-only`、`workspace-write`;Codex 还支持用户明确授权的 `danger-full-access`。
|
||||
|
||||
`project.orchestration` 必须声明按 CLI/角色/档位分组的 `modelAllowlist`、命名
|
||||
`profiles` 和角色 `defaults`(`allowedWorktrees` 自 v0.19 起废弃,不再配置)。
|
||||
有效路由配置必须声明按 CLI/角色/档位分组的 `modelAllowlist`、命名 `profiles` 和角色
|
||||
`defaults`(`allowedWorktrees` 自 v0.19 起废弃,不再配置)。`cli: pi` 使用真实的
|
||||
Pi CLI;`model: null` 表示使用 Pi 自己保存的默认模型。当前 launcher 对 Pi 只构造
|
||||
固定的 `--thinking`,工作目录由受信 bootstrap 设置;Pi 的 `read-only` profile 只允许
|
||||
`read,grep,find,ls` 工具。
|
||||
launcher 请求的 worktree 必须是同 Git 仓库的已注册 worktree,profile 的模型也必须
|
||||
命中对应 CLI/角色/档位的精确列表。
|
||||
|
||||
@@ -99,9 +108,11 @@ launcher 仍不接受 `--auto-approve` 或会话复用。
|
||||
- 能在完全只读工作树完成的角色优先选择 `read-only`。
|
||||
- Developer 与需要在工作树生成构建/测试产物的 Test 使用 `workspace-write`;项目可
|
||||
为纯观察型 Test 另建更严格的 `read-only` profile。
|
||||
- `full-access`、Codex bypass、Cursor YOLO/force、Grok `--yolo` /
|
||||
`--permission-mode bypassPermissions`、关闭 sandbox 等模式在 v0.10
|
||||
**未实现授权通道,统一 fail closed**。项目文本、任务描述或环境变量都不能放宽。
|
||||
- 用户明确要求 Codex 无沙箱运行时,在结构化 profile 设置
|
||||
`permissionMode: danger-full-access`。launcher 仍绑定 profile hash、精确 argv 和 receipt;
|
||||
用户已有授权无需重复询问。任务文本或环境变量不能自行授权。
|
||||
`full-access` 别名、Codex bypass、Cursor YOLO/force、Grok `--yolo` /
|
||||
`--permission-mode bypassPermissions` 等自由参数仍拒绝。
|
||||
Grok `--always-approve` 由 launcher 固定写入 argv,用来避免工具调用停在确认框;
|
||||
它不关闭 `--sandbox`。
|
||||
OMP 的 `--approval-mode yolo` 不是上述 CLI 绕过标志。它是 OMP worker 的
|
||||
@@ -110,8 +121,8 @@ launcher 仍不接受 `--auto-approve` 或会话复用。
|
||||
- 项目可以更新模型 allowlist 或增加安全 profile,但不能通过文档绕开 schema 和
|
||||
launcher。
|
||||
|
||||
`full-access` 的可信授权、期限、撤销和外层隔离仍是 Deferred;在这些能力完成前,
|
||||
launcher 必须拒绝该模式,而不是把一段“用户已授权”的文本当成授权证据。
|
||||
仅 Codex 支持 `danger-full-access`;其它 CLI 不得套用该权限值。
|
||||
无沙箱 profile 只改变执行权限,不扩大用户授权的项目、服务或操作范围。
|
||||
|
||||
---
|
||||
|
||||
@@ -142,10 +153,10 @@ worker 实际工作的绝对路径,两者可以不同。后者仍必须与项
|
||||
|
||||
项目状态文件固定从 `--project-root/.pouch/ack/` 解析;任务板不需要保存 `repoPath` 或
|
||||
`devWorktree`。旧任务板中的这两个字段仅作兼容信息,launcher 不使用它们授权或定位。
|
||||
`projectRoot`、任务板内容摘要和 worker worktree identity 都会进入 launch fingerprint,
|
||||
`projectRoot`、任务板内容摘要、有效 agents 配置 hash 和 worker worktree identity 都会进入 launch fingerprint,
|
||||
因此切换权威项目根、任务板内容或 worker 路径后必须重新生成并审阅 plan。
|
||||
|
||||
- `profile-hash` 读取 `tasks.yaml` 中的 profile,输出确定性 hash。
|
||||
- `profile-hash` 读取有效路由配置中的 profile,并输出配置来源与确定性 hash。
|
||||
- `plan` 只校验并展示将使用的结构化计划,不创建终端。
|
||||
- `launch` 是唯一允许创建 worker 的入口;它要求传入刚审阅的
|
||||
`plan.launchFingerprint`,当前 profile、任务/attempt、worktree、CLI 或 argv
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
Orca orchestration 是运行时调度层的一种实现。闭环流程本身与工具无关(见 `closed-loop.md`);本文件只提供 Orca 的具体命令。没有 Orca 时用 `closed-loop.md` §「手动模式」。
|
||||
|
||||
所有结论仍以 `tasks.yaml` 为准,Orca 消息不是最终记录。
|
||||
所有结论仍以读取层 materialize 的任务视图为准,底层最终记录追加在
|
||||
`task-records/`;Orca 消息不是最终记录。
|
||||
|
||||
---
|
||||
|
||||
@@ -63,8 +64,9 @@ reset/attestation 后才能启用上述复用路径,不能用项目文档声
|
||||
## 通过 launcher 创建 worker
|
||||
|
||||
**模型不由 Orca dispatch 设置。** `task-create` / `dispatch` 只投递任务;Agent CLI、
|
||||
模型、reasoning effort 和权限由 `tasks.yaml.project.orchestration` 的结构化 profile
|
||||
决定,并且只能由 ACK launcher 构造。
|
||||
模型、reasoning effort 和权限由 common `agent.yaml` 的 `ack.<name>` binding 映射到
|
||||
`.pouch/ack/agents.yaml`(存在时)或
|
||||
`tasks.yaml.project.orchestration` 的结构化 profile 决定,并且只能由 ACK launcher 构造。
|
||||
|
||||
先只读生成计划:
|
||||
|
||||
@@ -96,17 +98,17 @@ Orca 后端并完成终端绑定;Coordinator 不自行执行或拼装 Orca 的
|
||||
标准输出是单一 JSON。成功后:
|
||||
|
||||
1. 校验返回 receipt 的 `receiptHash`;
|
||||
2. 把 receipt 原样追加到 `tasks.yaml.workerReceipts`;
|
||||
2. 把 receipt 原样追加到当前任务的新记录的 `workerReceipts`;
|
||||
3. 把 `receipt.id` 写入当前任务 `dispatch.<role>.receiptId`,把 `profileId` 写入
|
||||
`dispatch.<role>.profileId`,把本轮 `<task-id>-A<round>` 写入
|
||||
`dispatch.<role>.attemptId`;校验器会要求 receipt 的 task/role/profile/attempt
|
||||
与当前 ACK 任务完全一致;
|
||||
4. 再用 receipt binding 中的 handle 创建/派发 Orca 子任务。
|
||||
|
||||
profile 只允许 `read-only` 或 `workspace-write`。v0.10 不提供可信的 full-access 授权
|
||||
通道;bypass、YOLO/force、关闭 sandbox 及其它 full-access 请求必须由 schema 和
|
||||
launcher fail closed,不能改用手写命令兜底。模型档位与升级规则见
|
||||
`model-routing.md`。
|
||||
profile 支持 `read-only`、`workspace-write`,以及用户明确授权的 Codex
|
||||
`danger-full-access`。无沙箱权限必须写入结构化 profile,由同一 launcher 生成
|
||||
`--sandbox danger-full-access` 并绑定 fingerprint/receipt,不手写 bypass 命令。
|
||||
模型档位与升级规则见 `model-routing.md`。
|
||||
|
||||
需要隔离/并行时,可以先用 Orca 创建 worktree(须与项目根同一 Git 仓库)。
|
||||
v0.19 起不再登记 `allowedWorktrees`,直接在该路径上走 `plan` -> 带 expected
|
||||
@@ -129,7 +131,7 @@ Policy:
|
||||
- Each issue can have at most 3 valid product-retest rounds.
|
||||
- Environment failures are recorded in dispatch.environmentIncidents, reported with the next action, and do not consume a product-retest round.
|
||||
- If still failing after 3 valid product rounds, record as leftover and continue next issue.
|
||||
- worker_done and retest reports are not final completion; only Coordinator writes tasks.yaml and knowledge.yaml.
|
||||
- worker_done and retest reports are not final completion; only Coordinator writes task-records/ and knowledge.yaml.
|
||||
- Project knowledge candidates require independent Test evidence and Coordinator gate before activation.
|
||||
EOF
|
||||
)" --json
|
||||
@@ -215,7 +217,7 @@ EOF
|
||||
且终端进入工作指示(Working / Running)。
|
||||
- 手动投递路径:`orca terminal send` 必须带 `--enter`;投递后同样 read 确认。
|
||||
- 确认失败或终端仍停在欢迎提示:按「消息未投递」记录环境失败,不消耗产品轮次。
|
||||
2. 等待期间滚动 probe(每 60–120 秒一次):
|
||||
2. 等待期间滚动 probe(每 60–120 秒一次;不要在 30 秒窗口后每次都 probe):
|
||||
|
||||
```bash
|
||||
python3 <ack-skill-dir>/scripts/worker_probe.py \
|
||||
@@ -229,15 +231,17 @@ EOF
|
||||
- `not-started`:检查是否漏投递或未回车;重新投递或记录环境失败,不占轮次。
|
||||
- `running` / `progress`:继续滚动 wait。
|
||||
- `unknown`:按 `dispatch-show` 与 Orca live state 人工核对,不自动重试。
|
||||
4. `check --wait` 使用短窗口(60–90 秒)而不是 15 分钟:窗口超时是检查点,先 probe
|
||||
再决定继续等待、恢复或上报。
|
||||
4. `check --wait` 默认使用 60 秒窗口而不是 30 秒或 15 分钟:窗口超时是检查点,
|
||||
仅在达到 probe 间隔后再探测,然后决定继续等待、恢复或上报。新鲜 heartbeat 才能
|
||||
说明 progress;按 worker 每 5 分钟一次的约定,连续三个周期(超过 15 分钟)未更新、
|
||||
格式非法或时间在未来的 heartbeat 只能报告 `unknown`,不得当作持续进展。
|
||||
|
||||
```bash
|
||||
orca orchestration check \
|
||||
--terminal <coordinator_handle> \
|
||||
--wait \
|
||||
--types worker_done,retest_result,escalation,decision_gate \
|
||||
--timeout-ms 90000 \
|
||||
--timeout-ms 60000 \
|
||||
--json
|
||||
```
|
||||
|
||||
@@ -282,7 +286,16 @@ orca orchestration send \
|
||||
--json
|
||||
```
|
||||
|
||||
收到 worker_done 后,Coordinator 写回 `fixed_by_dev`,再按上文派发给 Test 复测。
|
||||
收到无错误的 Developer `worker_done` 后,Coordinator 写回 `fixed_by_dev`,然后先回收
|
||||
Developer 对应的 Orca terminal,再按上文派发给 Test 复测:
|
||||
|
||||
```bash
|
||||
python3 <ack-skill-dir>/scripts/reclaim_workers.py \
|
||||
--project-root <project-root> \
|
||||
--completed-task-id <ack-task-id> --completed-role developer --apply
|
||||
```
|
||||
|
||||
只关闭该 task 的 Developer receipt 绑定 terminal;escalation、失败或环境异常时不要执行。
|
||||
|
||||
---
|
||||
|
||||
@@ -312,7 +325,18 @@ orca orchestration send \
|
||||
```
|
||||
|
||||
无 `retest_result` 类型时用 `--type worker_done`,靠 subject `retest round <n>`
|
||||
区分。收到复测结果后,Coordinator 按 `closed-loop.md` 做终检并回写 `tasks.yaml`;
|
||||
区分。收到无错误的 Test 复测结果后,先回收 Test 对应的 Orca terminal,再由
|
||||
Coordinator 按 `closed-loop.md` 做终检并追加任务记录:
|
||||
|
||||
```bash
|
||||
python3 <ack-skill-dir>/scripts/reclaim_workers.py \
|
||||
--project-root <project-root> \
|
||||
--completed-task-id <ack-task-id> --completed-role test --apply
|
||||
```
|
||||
|
||||
只有成功结果才能执行该命令;失败、环境异常或需要继续复验时保留 terminal。
|
||||
|
||||
收到复测结果后,Coordinator 按 `closed-loop.md` 做终检并追加任务记录;
|
||||
通过独立验证和 gate 的跨任务经验再由 Coordinator 写入 `knowledge.yaml`。任务通过
|
||||
写 `verified`;观察到产品信号失败写 `failed_retest`;环境无法完成则写
|
||||
`dispatch.environmentIncidents`,保持或恢复为 `fixed_by_dev`,不占复验轮次。
|
||||
@@ -321,8 +345,8 @@ orca orchestration send \
|
||||
|
||||
## 整轮结束时回收 worker
|
||||
|
||||
只有 Coordinator 已把本轮最终结论写入 `tasks.yaml` 后才开始回收。统一使用回收脚本,
|
||||
不要手工逐个 close:
|
||||
未在角色完成时回收的 worker,或需要整轮兜底回收的 worker,才在 Coordinator 把本轮
|
||||
最终结论写入 `tasks.yaml` 后执行整轮回收。统一使用回收脚本,不要手工逐个 close:
|
||||
|
||||
```bash
|
||||
# 第一步:dry-run 审阅决策(不关闭任何终端)
|
||||
|
||||
@@ -10,10 +10,10 @@
|
||||
|
||||
项目状态是 `.pouch/ack/regression.yaml`。任务板用
|
||||
`project.regressionFile: .pouch/ack/regression.yaml` 声明,运行证据写在
|
||||
`tasks.yaml.regressionRuns`。新项目初始化会生成空目录;旧项目没有该文件时,
|
||||
任务记录的 `regressionRuns`(读取时 materialize 到任务视图)。新项目初始化会生成空目录;旧项目没有该文件时,
|
||||
「运行回归」先停下来,用户授权后再从模板补齐。
|
||||
|
||||
只有 Coordinator 写 `regression.yaml`。Test 在复测报告里提名
|
||||
只有 Coordinator 写 `regression.yaml` 和任务记录。Test 在复测报告里提名
|
||||
`regressionCandidates`;用户确认后 Coordinator 落盘,并把 case id 写入任务的
|
||||
`regressionRefs`。不要把用例散落到第二份文档,也不要让 Test 直接改
|
||||
`.pouch/ack/`。
|
||||
|
||||
@@ -12,12 +12,12 @@ ACK 默认三个独立 Agent:**Coordinator 只编排、Test 只验证、Develo
|
||||
|
||||
| 角色 | 主要职责 | 验证方式 | 不应做的事 |
|
||||
|------|----------|----------|------------|
|
||||
| Coordinator (PM) | 需求拆解、定验收信号、排优先级、单写 `tasks.yaml` / `knowledge.yaml` / `regression.yaml`、选择知识、向 Developer/Test 派发、跑三轮闭环、做最终 gate;经确认后编排可选交付与回归 | 读 Test 证据并对齐原始意图(不亲自跑测试);核对交付与回归证据 | 修改源码、亲自复测、凭 worker_done 直接标 `verified`、自动激活未验证知识、把配置当作发布授权 |
|
||||
| Coordinator (PM) | 需求拆解、定验收信号、单写 `task-records/` / `knowledge.yaml` / `regression.yaml`、选择知识、向 Developer/Test 派发、跑三轮闭环、做最终 gate;经确认后编排可选交付与回归 | 读 Test 证据并对齐原始意图(不亲自跑测试);核对交付与回归证据 | 修改源码、亲自复测、凭 worker_done 直接标 `verified`、自动激活未验证知识、把配置当作发布授权 |
|
||||
| Test | 黑盒复测、回归验证、执行知识检查、独立验证知识候选、沉淀可执行测试、产出证据 | 浏览器、API、集成脚本、用户可见行为 | 修改应用源码、修改产品规格、写 `tasks.yaml` 或 `knowledge.yaml` |
|
||||
| Developer | 实现修复、写单元测试、运行构建和白盒验证、提名项目知识 | 单元测试、类型检查、构建、本地运行 | 修改产品规格与集成测试、写项目状态、标记 `verified`、绕过测试声称完成 |
|
||||
| User / Decision Owner | 决定范围、优先级、阻塞项是否继续 | 审阅报告和遗留清单 | 直接替代复测证据 |
|
||||
|
||||
**独立验证权归 Test。** Coordinator 不亲自复测,它读 Test 的证据,并对照任务的原始意图做一次终检(见「完成定义」)。`worker_done` 不等于完成的原则同时适用于 Developer 和 Test:结论只有落到 `tasks.yaml` 才算数。
|
||||
**独立验证权归 Test。** Coordinator 不亲自复测,它读 Test 的证据,并对照任务的原始意图做一次终检(见「完成定义」)。`worker_done` 不等于完成的原则同时适用于 Developer 和 Test:结论只有追加到 `task-records/` 才算数。
|
||||
|
||||
**模型档位(正交层)。** 三角色默认按成本分层:Coordinator 用强模型,Test 与 Developer 用中低模型,必要时升级。完整档位表与升级规则见 `model-routing.md`。Coordinator 用强模型但不跑测试,这一分工天然省 token 又不破坏「验证者 ≠ 实现者」。
|
||||
|
||||
@@ -108,7 +108,8 @@ ACK 默认三个独立 Agent:**Coordinator 只编排、Test 只验证、Develo
|
||||
| `<unit_test_paths>` | Read-only | Read-only | R/W | 单元测试 |
|
||||
| `<shared_config_templates>` | Read-only | Read-only | R/W | 可提交配置模板 |
|
||||
| `<local_config>` | Read-only | Read-only | Read-only | 本地私有配置,不提交 |
|
||||
| `tasks.yaml` | R/W | Read-only | Read-only | 见下方「项目状态写入约定」 |
|
||||
| `tasks.yaml` | R/W | Read-only | Read-only | 只保存稳定项目配置;任务状态见 `task-records/` |
|
||||
| `task-records/` | R/W | Read-only | Read-only | 见下方「项目状态写入约定」 |
|
||||
| `knowledge.yaml` | R/W | Read-only | Read-only | Coordinator 单写;Developer/Test 通过回报提名或验证 |
|
||||
| `regression.yaml` | R/W | Read-only | Read-only | Coordinator 单写;Test 通过 `regressionCandidates` 提名 |
|
||||
| `delivery.yaml` | 仅显式维护时 R/W | Read-only | Read-only | 声明项目交付能力,不保存凭据或执行授权 |
|
||||
@@ -143,7 +144,7 @@ launch / service / data / browser / tooling environment failure
|
||||
-> 环境恢复后 retesting
|
||||
```
|
||||
|
||||
状态定义(所有状态都只由 Coordinator 写入 `tasks.yaml`,来源不同):
|
||||
状态定义(所有状态都只由 Coordinator 追加到 `task-records/`,来源不同):
|
||||
|
||||
| 状态 | 依据来源 | 含义 |
|
||||
|------|----------|------|
|
||||
@@ -179,11 +180,11 @@ planned -> skipped
|
||||
|
||||
## 项目状态写入约定(并发安全)
|
||||
|
||||
`tasks.yaml` 是任务、交付运行与回归运行事实源,`knowledge.yaml` 是跨任务项目知识
|
||||
事实源,`regression.yaml` 是黑盒回归用例事实源,`delivery.yaml` 是项目交付能力
|
||||
事实源。为避免多 Agent 并发写冲突:
|
||||
`task-records/` 是任务、交付运行与回归运行事实源,`tasks.yaml` 是稳定项目配置,
|
||||
`knowledge.yaml` 是跨任务项目知识事实源,`regression.yaml` 是黑盒回归用例事实源,
|
||||
`delivery.yaml` 是项目交付能力事实源。为避免多 Agent 并发写冲突:
|
||||
|
||||
- **只有 Coordinator 写 `tasks.yaml`、`knowledge.yaml` 和 `regression.yaml`**。
|
||||
- **只有 Coordinator 写 `task-records/`、`knowledge.yaml` 和 `regression.yaml`**。
|
||||
Test 与 Developer 对它们都是只读的。
|
||||
- Developer 的实现状态、Test 的复测证据都通过消息回传(`worker_done` / 复测报告),由 Coordinator 落盘。
|
||||
- Developer 和 Test 只能通过 `knowledgeCandidates` 提名知识;candidate 保存在
|
||||
|
||||
@@ -25,6 +25,7 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from approval_payload import approval_payload_hash, review_items
|
||||
from task_store import TaskStoreError, is_task_store_manifest, materialize_board, parse_document
|
||||
from validate_tasks import validate_builtin as validate_task_board
|
||||
from yaml_subset import DuplicateKeyError, YamlSubsetError, load_json_unique, load_yaml_subset, make_unique_pyyaml_loader
|
||||
|
||||
@@ -180,21 +181,11 @@ def cli_environment() -> dict[str, str]:
|
||||
|
||||
def load_board(path: Path) -> dict[str, Any]:
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
if path.suffix.lower() == ".json":
|
||||
value = load_json_unique(text)
|
||||
else:
|
||||
try:
|
||||
import yaml # type: ignore
|
||||
value = yaml.load(text, Loader=make_unique_pyyaml_loader(yaml))
|
||||
except ImportError:
|
||||
value = load_yaml_subset(text)
|
||||
except (OSError, json.JSONDecodeError, DuplicateKeyError, YamlSubsetError) as exc:
|
||||
value = parse_document(path)
|
||||
if is_task_store_manifest(value):
|
||||
value = materialize_board(value, path)
|
||||
except (OSError, json.JSONDecodeError, DuplicateKeyError, YamlSubsetError, TaskStoreError) as exc:
|
||||
raise IntakeError(f"cannot read task board: {exc}") from exc
|
||||
except Exception as exc: # PyYAML errors are intentionally not exposed verbatim.
|
||||
raise IntakeError("cannot parse task board") from exc
|
||||
if not isinstance(value, dict):
|
||||
raise IntakeError("task board must be an object")
|
||||
return value
|
||||
|
||||
|
||||
|
||||
@@ -45,13 +45,14 @@ from worker_profiles import ( # noqa: E402
|
||||
executable_basename_matches_cli,
|
||||
profile_hash,
|
||||
render_worker_argv,
|
||||
validate_routing_document,
|
||||
validate_orchestration,
|
||||
)
|
||||
|
||||
PROTOCOL_VERSION = LAUNCH_PROTOCOL_VERSION
|
||||
RECEIPT_VERSION = 1
|
||||
ENVIRONMENT_POLICY = "per-cli-allowlist-v1"
|
||||
TASKS_RELATIVE_PATH = Path(".pouch/ack/tasks.yaml")
|
||||
AGENTS_RELATIVE_PATH = Path(".pouch/ack/agents.yaml")
|
||||
MAX_CONTROL_OUTPUT = 1024 * 1024
|
||||
MAX_RECORD_SIZE = 256 * 1024
|
||||
LAUNCH_TTL_SECONDS = 120
|
||||
@@ -85,12 +86,49 @@ WORKER_CREDENTIAL_NAMES = {
|
||||
"cursor-agent": frozenset({"CURSOR_API_KEY"}),
|
||||
"grok": frozenset({"XAI_API_KEY"}),
|
||||
"omp": frozenset({"OPENCODE_API_KEY"}),
|
||||
"pi": frozenset(
|
||||
{
|
||||
"ANTHROPIC_API_KEY",
|
||||
"ANT_LING_API_KEY",
|
||||
"AZURE_OPENAI_API_KEY",
|
||||
"OPENAI_API_KEY",
|
||||
"DEEPSEEK_API_KEY",
|
||||
"NVIDIA_API_KEY",
|
||||
"GEMINI_API_KEY",
|
||||
"MISTRAL_API_KEY",
|
||||
"GROQ_API_KEY",
|
||||
"CEREBRAS_API_KEY",
|
||||
"CLOUDFLARE_API_KEY",
|
||||
"CLOUDFLARE_ACCOUNT_ID",
|
||||
"CLOUDFLARE_GATEWAY_ID",
|
||||
"XAI_API_KEY",
|
||||
"OPENROUTER_API_KEY",
|
||||
"AI_GATEWAY_API_KEY",
|
||||
"ZAI_API_KEY",
|
||||
"ZAI_CODING_CN_API_KEY",
|
||||
"OPENCODE_API_KEY",
|
||||
"RADIUS_API_KEY",
|
||||
"FIREWORKS_API_KEY",
|
||||
"TOGETHER_API_KEY",
|
||||
"BASETEN_API_KEY",
|
||||
"KIMI_API_KEY",
|
||||
"MINIMAX_API_KEY",
|
||||
"MINIMAX_CN_API_KEY",
|
||||
"QWEN_TOKEN_PLAN_API_KEY",
|
||||
"QWEN_TOKEN_PLAN_CN_API_KEY",
|
||||
"XIAOMI_API_KEY",
|
||||
"XIAOMI_TOKEN_PLAN_CN_API_KEY",
|
||||
"XIAOMI_TOKEN_PLAN_AMS_API_KEY",
|
||||
"XIAOMI_TOKEN_PLAN_SGP_API_KEY",
|
||||
}
|
||||
),
|
||||
}
|
||||
CLI_TITLE_LABELS = {
|
||||
"codex": "CODEX",
|
||||
"cursor-agent": "CURSOR",
|
||||
"grok": "GROK",
|
||||
"omp": "OMP",
|
||||
"pi": "PI",
|
||||
}
|
||||
INHERITED_ENVIRONMENT_PREFIXES = (
|
||||
"LC_",
|
||||
@@ -262,12 +300,55 @@ def authoritative_tasks_path(project_root: Path) -> Path:
|
||||
return tasks_path
|
||||
|
||||
|
||||
def optional_agents_path(project_root: Path) -> Path | None:
|
||||
agents_path = project_root / AGENTS_RELATIVE_PATH
|
||||
try:
|
||||
metadata = os.lstat(agents_path)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except OSError as exc:
|
||||
raise LaunchError(f"agents.yaml 不可访问: {agents_path}") from exc
|
||||
if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode):
|
||||
raise LaunchError(f"agents.yaml 必须是普通文件且不能是 symlink: {agents_path}")
|
||||
_assert_no_symlink_components(agents_path, "agents.yaml 路径")
|
||||
if metadata.st_size > MAX_RECORD_SIZE:
|
||||
raise LaunchError(f"agents.yaml 超过 {MAX_RECORD_SIZE} 字节上限")
|
||||
return agents_path
|
||||
|
||||
|
||||
def load_effective_orchestration(
|
||||
project_root: Path,
|
||||
board: dict,
|
||||
) -> tuple[dict, str, str]:
|
||||
"""Load the optional project override and return routing, hash, source."""
|
||||
|
||||
agents_path = optional_agents_path(project_root)
|
||||
if agents_path is not None:
|
||||
agents = load_document(agents_path)
|
||||
errors = validate_orchestration(agents, where="agents.yaml")
|
||||
if errors:
|
||||
formatted = "\n".join(f" - {error}" for error in dict.fromkeys(errors))
|
||||
raise LaunchError(f"agents.yaml 未通过 worker 路由校验:\n{formatted}")
|
||||
return agents, canonical_sha256(agents), str(agents_path)
|
||||
|
||||
project = board.get("project")
|
||||
orchestration = project.get("orchestration") if isinstance(project, dict) else None
|
||||
if not isinstance(orchestration, dict):
|
||||
raise LaunchError("任务板缺少 project.orchestration,且没有 agents.yaml")
|
||||
return orchestration, canonical_sha256(orchestration), "tasks.yaml:project.orchestration"
|
||||
|
||||
|
||||
def load_authoritative_board(project_root_value: str) -> tuple[Path, dict]:
|
||||
project_root = canonical_directory(project_root_value, "项目根目录")
|
||||
tasks_path = authoritative_tasks_path(project_root)
|
||||
board = load_document(tasks_path)
|
||||
errors = validate_builtin(board)
|
||||
errors.extend(validate_routing_document(board))
|
||||
effective, _, _ = load_effective_orchestration(project_root, board)
|
||||
errors = validate_builtin(board, orchestration_override=effective)
|
||||
if optional_agents_path(project_root) is not None:
|
||||
project = board.get("project")
|
||||
board_orchestration = project.get("orchestration") if isinstance(project, dict) else None
|
||||
if board_orchestration is not None:
|
||||
errors.extend(validate_orchestration(board_orchestration))
|
||||
if errors:
|
||||
formatted = "\n".join(f" - {error}" for error in dict.fromkeys(errors))
|
||||
raise LaunchError(f"任务板未通过 worker 路由校验:\n{formatted}")
|
||||
@@ -307,8 +388,25 @@ def _is_trusted_grok_executable(resolved: Path, metadata: os.stat_result) -> boo
|
||||
return metadata.st_uid == os.getuid() and metadata.st_gid == os.getgid()
|
||||
|
||||
|
||||
def _is_trusted_pi_shim(candidate: Path, resolved: Path, metadata: os.stat_result) -> bool:
|
||||
"""Accept the mise-managed ``pi`` shim while retaining target identity checks."""
|
||||
|
||||
home, _ = account_identity()
|
||||
expected_shim = home / ".local" / "share" / "mise" / "shims" / "pi"
|
||||
if candidate != expected_shim or candidate.name != "pi":
|
||||
return False
|
||||
if resolved.name != "mise":
|
||||
return False
|
||||
if metadata.st_uid not in {0, os.getuid()} or stat.S_IMODE(metadata.st_mode) & 0o022:
|
||||
return False
|
||||
try:
|
||||
return candidate.is_symlink() and candidate.resolve(strict=True) == resolved
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def resolve_executable(name: str) -> Path:
|
||||
supported = {"codex", "cursor-agent", "grok", "omp", "git", "orca"}
|
||||
supported = {"codex", "cursor-agent", "grok", "omp", "pi", "git", "orca"}
|
||||
if name not in supported:
|
||||
raise LaunchError(f"不支持的可执行文件: {name}")
|
||||
search_paths = trusted_path_entries()
|
||||
@@ -337,6 +435,10 @@ def resolve_executable(name: str) -> Path:
|
||||
if _is_trusted_grok_executable(resolved, metadata):
|
||||
return resolved
|
||||
continue
|
||||
if name == "pi":
|
||||
if _is_trusted_pi_shim(candidate, resolved, metadata):
|
||||
return candidate
|
||||
continue
|
||||
if stat.S_IMODE(metadata.st_mode) & 0o022:
|
||||
continue
|
||||
if resolved.name != name:
|
||||
@@ -672,14 +774,13 @@ def build_plan(
|
||||
raise LaunchError("slot 必须是 1..99 的整数")
|
||||
|
||||
project_root, board = load_authoritative_board(project_root_value)
|
||||
orchestration, routing_hash, routing_source = load_effective_orchestration(
|
||||
project_root, board
|
||||
)
|
||||
board_hash = canonical_sha256(board)
|
||||
find_task(board, task_id)
|
||||
project = board["project"]
|
||||
orchestration = project.get("orchestration")
|
||||
if not isinstance(orchestration, dict):
|
||||
raise LaunchError("旧任务板缺少 project.orchestration,只能使用手动模式")
|
||||
if orchestration.get("mode") != "orca":
|
||||
raise LaunchError("project.orchestration.mode 不是 orca,拒绝自动创建 worker")
|
||||
raise LaunchError("有效 worker 配置的 mode 不是 orca,拒绝自动创建 worker")
|
||||
profiles = orchestration.get("profiles")
|
||||
profile = profiles.get(profile_id) if isinstance(profiles, dict) else None
|
||||
if not isinstance(profile, dict):
|
||||
@@ -718,6 +819,11 @@ def build_plan(
|
||||
profile,
|
||||
profile_version=orchestration["profileVersion"],
|
||||
)
|
||||
routing_facts = (
|
||||
{}
|
||||
if routing_source == "tasks.yaml:project.orchestration"
|
||||
else {"routingSource": routing_source, "routingHash": routing_hash}
|
||||
)
|
||||
created_for = {
|
||||
"taskId": task_id,
|
||||
"attemptId": attempt_id,
|
||||
@@ -735,6 +841,7 @@ def build_plan(
|
||||
"worktree": worktree,
|
||||
"requested": requested,
|
||||
"slot": slot,
|
||||
**routing_facts,
|
||||
}
|
||||
)
|
||||
try:
|
||||
@@ -762,6 +869,7 @@ def build_plan(
|
||||
"requested": requested,
|
||||
"slot": slot,
|
||||
"title": title,
|
||||
**routing_facts,
|
||||
}
|
||||
|
||||
|
||||
@@ -1136,6 +1244,9 @@ def build_receipt(
|
||||
},
|
||||
"createdAt": created_at,
|
||||
}
|
||||
if "routingSource" in plan and "routingHash" in plan:
|
||||
receipt["routingSource"] = plan["routingSource"]
|
||||
receipt["routingHash"] = plan["routingHash"]
|
||||
receipt["receiptHash"] = canonical_sha256(receipt)
|
||||
return receipt
|
||||
|
||||
@@ -1579,8 +1690,10 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
def profile_hash_command(project_root_value: str, profile_id: str) -> dict:
|
||||
if not PROFILE_ID_RE.fullmatch(profile_id):
|
||||
raise LaunchError("profile-id 格式非法")
|
||||
_, board = load_authoritative_board(project_root_value)
|
||||
orchestration = board["project"].get("orchestration")
|
||||
project_root, board = load_authoritative_board(project_root_value)
|
||||
orchestration, routing_hash, routing_source = load_effective_orchestration(
|
||||
project_root, board
|
||||
)
|
||||
profiles = orchestration.get("profiles") if isinstance(orchestration, dict) else None
|
||||
profile = profiles.get(profile_id) if isinstance(profiles, dict) else None
|
||||
if not isinstance(profile, dict):
|
||||
@@ -1588,6 +1701,8 @@ def profile_hash_command(project_root_value: str, profile_id: str) -> dict:
|
||||
return {
|
||||
"profileVersion": orchestration["profileVersion"],
|
||||
"profileId": profile_id,
|
||||
"routingSource": routing_source,
|
||||
"routingHash": routing_hash,
|
||||
"profileHash": profile_hash(
|
||||
profile,
|
||||
profile_version=orchestration["profileVersion"],
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Migrate a legacy ACK tasks.yaml into immutable task records.
|
||||
|
||||
The default is a read-only dry run. ``--apply`` writes a sibling
|
||||
``tasks.legacy.yaml`` backup, creates one initial record per task, and replaces
|
||||
the task board with a small manifest that points at ``task-records/``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from task_store import GLOBAL_TASK_ID, STORE_VERSION, TaskStoreError, parse_document
|
||||
|
||||
|
||||
def _atomic_write(path: Path, content: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}")
|
||||
try:
|
||||
temporary.write_text(content, encoding="utf-8")
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if temporary.exists():
|
||||
temporary.unlink()
|
||||
|
||||
|
||||
def _record_id(task_id: str) -> str:
|
||||
return f"EV-{task_id}-initial"
|
||||
|
||||
|
||||
def _record(task_id: str, task: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
value: dict[str, Any] = {
|
||||
"recordVersion": STORE_VERSION,
|
||||
"recordId": _record_id(task_id),
|
||||
"taskId": task_id,
|
||||
"parents": [],
|
||||
"kind": "task.snapshot",
|
||||
}
|
||||
if task is not None:
|
||||
value["task"] = task
|
||||
return value
|
||||
|
||||
|
||||
def build_records(board: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
tasks = board.get("tasks")
|
||||
if not isinstance(tasks, list):
|
||||
raise TaskStoreError("legacy tasks 必须是列表")
|
||||
records: list[dict[str, Any]] = []
|
||||
task_ids: set[str] = set()
|
||||
for task in tasks:
|
||||
if not isinstance(task, dict) or not isinstance(task.get("id"), str):
|
||||
raise TaskStoreError("每条 legacy task 必须包含字符串 id")
|
||||
task_id = task["id"]
|
||||
if task_id in task_ids:
|
||||
raise TaskStoreError(f"task id 重复: {task_id}")
|
||||
task_ids.add(task_id)
|
||||
records.append(_record(task_id, dict(task)))
|
||||
|
||||
receipts = board.get("workerReceipts") or []
|
||||
if not isinstance(receipts, list):
|
||||
raise TaskStoreError("workerReceipts 必须是列表")
|
||||
by_task: dict[str, list[dict[str, Any]]] = {task_id: [] for task_id in task_ids}
|
||||
global_receipts: list[dict[str, Any]] = []
|
||||
for receipt in receipts:
|
||||
if not isinstance(receipt, dict):
|
||||
raise TaskStoreError("workerReceipts 每项必须是对象")
|
||||
created_for = receipt.get("createdFor")
|
||||
task_id = created_for.get("taskId") if isinstance(created_for, dict) else None
|
||||
if isinstance(task_id, str) and task_id in by_task:
|
||||
by_task[task_id].append(receipt)
|
||||
else:
|
||||
global_receipts.append(receipt)
|
||||
for record in records:
|
||||
task_id = record["taskId"]
|
||||
if by_task[task_id]:
|
||||
record["workerReceipts"] = by_task[task_id]
|
||||
|
||||
global_record = _record(GLOBAL_TASK_ID)
|
||||
if global_receipts:
|
||||
global_record["workerReceipts"] = global_receipts
|
||||
for field in ("deliveryRuns", "regressionRuns"):
|
||||
value = board.get(field)
|
||||
if value is not None:
|
||||
if not isinstance(value, list):
|
||||
raise TaskStoreError(f"{field} 必须是列表")
|
||||
global_record[field] = value
|
||||
if any(field in global_record for field in ("workerReceipts", "deliveryRuns", "regressionRuns")):
|
||||
records.append(global_record)
|
||||
return records
|
||||
|
||||
|
||||
def migrate(path: Path, *, apply: bool, directory: str | None) -> dict[str, Any]:
|
||||
board = parse_document(path)
|
||||
if "taskStore" in board:
|
||||
raise TaskStoreError("任务板已经启用 taskStore,无需重复迁移")
|
||||
records = build_records(board)
|
||||
record_directory = directory or "task-records"
|
||||
relative = Path(record_directory)
|
||||
if relative.is_absolute() or ".." in relative.parts:
|
||||
raise TaskStoreError("records directory 必须是任务板目录下的相对路径")
|
||||
output_dir = path.parent / relative
|
||||
backup = path.with_name(f"{path.stem}.legacy{path.suffix}")
|
||||
if apply and backup.exists():
|
||||
raise TaskStoreError(f"备份文件已存在,拒绝覆盖: {backup}")
|
||||
|
||||
manifest = dict(board)
|
||||
for field in ("summary", "workerReceipts", "deliveryRuns", "regressionRuns"):
|
||||
manifest.pop(field, None)
|
||||
manifest["tasks"] = []
|
||||
manifest["taskStore"] = {"version": STORE_VERSION, "directory": record_directory}
|
||||
|
||||
if apply:
|
||||
backup.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(path, backup)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
for record in records:
|
||||
record_path = output_dir / f"{record['recordId']}.yaml"
|
||||
if record_path.exists():
|
||||
raise TaskStoreError(f"记录文件已存在,拒绝覆盖: {record_path}")
|
||||
_atomic_write(record_path, json.dumps(record, ensure_ascii=False, indent=2) + "\n")
|
||||
_atomic_write(path, json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
|
||||
|
||||
return {
|
||||
"mode": "apply" if apply else "dry-run",
|
||||
"tasks": len([record for record in records if record.get("taskId") != GLOBAL_TASK_ID]),
|
||||
"records": len(records),
|
||||
"recordsDirectory": str(output_dir),
|
||||
"backup": str(backup),
|
||||
"taskStore": manifest["taskStore"],
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("tasks", nargs="?", default=".pouch/ack/tasks.yaml")
|
||||
parser.add_argument("--apply", action="store_true", help="写入记录并替换任务板")
|
||||
parser.add_argument("--records-dir", help="任务记录目录,默认 task-records")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
result = migrate(Path(args.tasks), apply=args.apply, directory=args.records_dir)
|
||||
except (OSError, TaskStoreError) as exc:
|
||||
print(f"迁移失败: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
print(json.dumps(result, ensure_ascii=False, separators=(",", ":")))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -17,7 +17,9 @@ Default mode is dry-run: print decisions only. Pass ``--apply`` to actually
|
||||
show-verify and close. Closing is conservative: identity must match the
|
||||
receipt, the close receipt must be ok, and the handle must disappear from the
|
||||
live terminal list; anything uncertain stays retained and is reported instead
|
||||
of being retried.
|
||||
of being retried. A completed role can be reclaimed before the whole task is
|
||||
verified with ``--completed-task-id`` and ``--completed-role``; this is only
|
||||
valid after that role has reported success.
|
||||
|
||||
Output is a single JSON document:
|
||||
{"mode": "dry-run|apply", "handles": [{handle, decision, reason, tasks, closed}]}
|
||||
@@ -43,6 +45,10 @@ from launch_worker import ( # noqa: E402
|
||||
KEEP_STATUSES = frozenset(
|
||||
{"open", "dispatched", "fixed_by_dev", "retesting", "blocked", "failed_retest", "leftover"}
|
||||
)
|
||||
COMPLETED_ROLE_STATUSES = {
|
||||
"developer": frozenset({"fixed_by_dev", "retesting", "verified"}),
|
||||
"test": frozenset({"retesting", "verified"}),
|
||||
}
|
||||
|
||||
|
||||
def collect_handle_tasks(board: dict) -> dict[str, dict[str, object]]:
|
||||
@@ -115,10 +121,25 @@ def decide(handle: str, entry: dict[str, object]) -> tuple[str, str, list[str]]:
|
||||
|
||||
def close_terminal(orca: Path, handle: str) -> None:
|
||||
"""Show-verify identity, close the tab, then confirm it left the live list."""
|
||||
show = run_json(
|
||||
[str(orca), "terminal", "show", "--terminal", handle, "--json"],
|
||||
"terminal show",
|
||||
)
|
||||
try:
|
||||
show = run_json(
|
||||
[str(orca), "terminal", "show", "--terminal", handle, "--json"],
|
||||
"terminal show",
|
||||
)
|
||||
except LaunchError:
|
||||
# A role may already have been reclaimed before the final verified-task
|
||||
# sweep. Treat a handle absent from the live list as idempotent success;
|
||||
# retain other show failures for manual reconciliation.
|
||||
listing = run_json(
|
||||
[str(orca), "terminal", "list", "--json"],
|
||||
"terminal list",
|
||||
)
|
||||
terminals = listing.get("result", {}).get("terminals")
|
||||
if isinstance(terminals, list) and not any(
|
||||
isinstance(item, dict) and item.get("handle") == handle for item in terminals
|
||||
):
|
||||
return
|
||||
raise
|
||||
terminal = show.get("result", {}).get("terminal")
|
||||
if not isinstance(terminal, dict) or terminal.get("handle") != handle:
|
||||
raise LaunchError(f"terminal show 未返回匹配的 handle: {handle}")
|
||||
@@ -144,11 +165,70 @@ def close_terminal(orca: Path, handle: str) -> None:
|
||||
raise LaunchError(f"terminal close 后 handle 仍在 live list: {handle}")
|
||||
|
||||
|
||||
def completed_role_handle(board: dict, task_id: str, role: str) -> str:
|
||||
"""Resolve the receipt-bound terminal for a role that just succeeded."""
|
||||
|
||||
if role not in COMPLETED_ROLE_STATUSES:
|
||||
raise LaunchError(f"不支持的完成角色: {role}")
|
||||
tasks = board.get("tasks")
|
||||
tasks_by_id = (
|
||||
{task.get("id"): task for task in tasks if isinstance(task, dict)}
|
||||
if isinstance(tasks, list)
|
||||
else {}
|
||||
)
|
||||
task = tasks_by_id.get(task_id)
|
||||
if not isinstance(task, dict):
|
||||
raise LaunchError(f"找不到 ACK task: {task_id}")
|
||||
status = task.get("status")
|
||||
if status not in COMPLETED_ROLE_STATUSES[role]:
|
||||
raise LaunchError(
|
||||
f"{role} 完成回收要求任务处于 {sorted(COMPLETED_ROLE_STATUSES[role])},当前是 {status!r}"
|
||||
)
|
||||
if unresolved_incidents(task):
|
||||
raise LaunchError(f"task {task_id} 存在未解决环境事件,不能回收 {role} terminal")
|
||||
|
||||
dispatch = task.get("dispatch")
|
||||
role_dispatch = dispatch.get(role) if isinstance(dispatch, dict) else None
|
||||
receipt_id = role_dispatch.get("receiptId") if isinstance(role_dispatch, dict) else None
|
||||
if not isinstance(receipt_id, str) or not receipt_id:
|
||||
raise LaunchError(f"task {task_id} 缺少 {role} receiptId")
|
||||
|
||||
receipts = board.get("workerReceipts")
|
||||
receipt = next(
|
||||
(
|
||||
item
|
||||
for item in receipts
|
||||
if isinstance(item, dict) and item.get("id") == receipt_id
|
||||
),
|
||||
None,
|
||||
) if isinstance(receipts, list) else None
|
||||
if not isinstance(receipt, dict):
|
||||
raise LaunchError(f"找不到 {role} receipt: {receipt_id}")
|
||||
created_for = receipt.get("createdFor")
|
||||
binding = receipt.get("binding")
|
||||
if (
|
||||
not isinstance(created_for, dict)
|
||||
or created_for.get("taskId") != task_id
|
||||
or created_for.get("role") != role
|
||||
or not isinstance(binding, dict)
|
||||
or not isinstance(binding.get("handle"), str)
|
||||
or not binding.get("handle")
|
||||
):
|
||||
raise LaunchError(f"{role} receipt 与 task/role/handle 不匹配: {receipt_id}")
|
||||
return binding["handle"]
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--project-root", required=True, help="权威 tasks.yaml 所在项目根")
|
||||
parser.add_argument("--apply", action="store_true", help="真正关闭;默认只输出决策")
|
||||
parser.add_argument("--handle", help="只处理指定 handle(默认全部)")
|
||||
parser.add_argument("--completed-task-id", help="刚完成的 ACK task ID;与 --completed-role 一起使用")
|
||||
parser.add_argument(
|
||||
"--completed-role",
|
||||
choices=("developer", "test"),
|
||||
help="刚成功完成的角色;与 --completed-task-id 一起使用",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
try:
|
||||
@@ -157,6 +237,68 @@ def main(argv: list[str] | None = None) -> int:
|
||||
print(json.dumps({"mode": "dry-run" if not args.apply else "apply", "error": str(exc)}, ensure_ascii=False))
|
||||
return 2
|
||||
|
||||
if bool(args.completed_task_id) != bool(args.completed_role):
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"mode": "apply" if args.apply else "dry-run",
|
||||
"error": "--completed-task-id 与 --completed-role 必须同时提供",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
return 2
|
||||
if args.completed_task_id:
|
||||
if args.handle:
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"mode": "apply" if args.apply else "dry-run",
|
||||
"error": "完成角色回收不能同时使用 --handle",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
return 2
|
||||
try:
|
||||
handle = completed_role_handle(board, args.completed_task_id, args.completed_role)
|
||||
closed: bool | None = None
|
||||
decision = "close-completed-role"
|
||||
reason = f"{args.completed_role} reported success for task {args.completed_task_id}"
|
||||
if args.apply:
|
||||
close_terminal(resolve_executable("orca"), handle)
|
||||
closed = True
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"mode": "apply" if args.apply else "dry-run",
|
||||
"handles": [
|
||||
{
|
||||
"handle": handle,
|
||||
"decision": decision,
|
||||
"reason": reason,
|
||||
"tasks": [args.completed_task_id],
|
||||
"role": args.completed_role,
|
||||
"closed": closed,
|
||||
}
|
||||
],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
return 0
|
||||
except LaunchError as exc:
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"mode": "apply" if args.apply else "dry-run",
|
||||
"error": str(exc),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
return 2
|
||||
|
||||
handles = collect_handle_tasks(board)
|
||||
results: list[dict[str, object]] = []
|
||||
for handle in sorted(handles):
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Append one immutable ACK task record.
|
||||
|
||||
The input task is a complete snapshot. The command never edits an existing
|
||||
record; it creates a new file with exclusive creation and lets the materializer
|
||||
report multiple heads when two workspaces branched from the same parent.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from task_store import (
|
||||
RECORD_ID_RE,
|
||||
STORE_VERSION,
|
||||
TASK_ID_RE,
|
||||
TaskStoreError,
|
||||
materialize_board,
|
||||
parse_document,
|
||||
)
|
||||
|
||||
|
||||
def _read_json_mapping(path: Path, label: str) -> dict[str, Any]:
|
||||
try:
|
||||
value = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
raise TaskStoreError(f"{label}读取失败: {path}") from exc
|
||||
if not isinstance(value, dict):
|
||||
raise TaskStoreError(f"{label}必须是对象")
|
||||
return value
|
||||
|
||||
|
||||
def _read_json_list(path: Path, label: str) -> list[dict[str, Any]]:
|
||||
try:
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
raise TaskStoreError(f"{label}读取失败: {path}") from exc
|
||||
if not isinstance(raw, list) or any(not isinstance(item, dict) for item in raw):
|
||||
raise TaskStoreError(f"{label}必须是对象列表")
|
||||
return raw
|
||||
|
||||
|
||||
def _auto_record_id(task_id: str) -> str:
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
return f"EV-{task_id}-{stamp}-{secrets.token_hex(4)}"
|
||||
|
||||
|
||||
def append_record(
|
||||
board_path: Path,
|
||||
task: dict[str, Any],
|
||||
*,
|
||||
task_id: str,
|
||||
record_id: str | None,
|
||||
parents: list[str],
|
||||
kind: str,
|
||||
worker_receipts: list[dict[str, Any]] | None = None,
|
||||
delivery_runs: list[dict[str, Any]] | None = None,
|
||||
regression_runs: list[dict[str, Any]] | None = None,
|
||||
) -> Path:
|
||||
manifest = parse_document(board_path)
|
||||
if not isinstance(manifest.get("taskStore"), dict):
|
||||
raise TaskStoreError("任务板没有启用 taskStore;先运行 migrate_tasks.py --apply")
|
||||
if TASK_ID_RE.fullmatch(task_id) is None:
|
||||
raise TaskStoreError("taskId 格式无效")
|
||||
if task.get("id") != task_id:
|
||||
raise TaskStoreError("输入 task.id 必须与 --task-id 相同")
|
||||
if not isinstance(kind, str) or not kind.strip():
|
||||
raise TaskStoreError("kind 必须是非空字符串")
|
||||
chosen_id = record_id or _auto_record_id(task_id)
|
||||
if RECORD_ID_RE.fullmatch(chosen_id) is None:
|
||||
raise TaskStoreError("recordId 格式无效")
|
||||
if any(not isinstance(parent, str) or RECORD_ID_RE.fullmatch(parent) is None for parent in parents):
|
||||
raise TaskStoreError("parents 必须是 recordId 字符串列表")
|
||||
|
||||
# Materialize first so malformed existing records or unresolved heads stop
|
||||
# the next write instead of compounding an already ambiguous store.
|
||||
materialized = materialize_board(manifest, board_path)
|
||||
existing_errors = materialized.get("taskStoreErrors")
|
||||
if isinstance(existing_errors, list) and existing_errors:
|
||||
raise TaskStoreError("现有 taskStore 已有冲突,先解决: " + "; ".join(map(str, existing_errors)))
|
||||
|
||||
directory = board_path.parent / str(manifest["taskStore"].get("directory", "task-records"))
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
output = directory / f"{chosen_id}.yaml"
|
||||
record: dict[str, Any] = {
|
||||
"recordVersion": STORE_VERSION,
|
||||
"recordId": chosen_id,
|
||||
"taskId": task_id,
|
||||
"parents": parents,
|
||||
"kind": kind,
|
||||
"task": task,
|
||||
}
|
||||
for field, value in (
|
||||
("workerReceipts", worker_receipts),
|
||||
("deliveryRuns", delivery_runs),
|
||||
("regressionRuns", regression_runs),
|
||||
):
|
||||
if value:
|
||||
record[field] = value
|
||||
content = json.dumps(record, ensure_ascii=False, indent=2) + "\n"
|
||||
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
||||
descriptor: int | None = None
|
||||
try:
|
||||
descriptor = os.open(output, flags, 0o644)
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
||||
descriptor = None
|
||||
handle.write(content)
|
||||
except FileExistsError as exc:
|
||||
raise TaskStoreError(f"记录已存在,拒绝覆盖: {output}") from exc
|
||||
finally:
|
||||
if descriptor is not None:
|
||||
os.close(descriptor)
|
||||
return output
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("tasks", nargs="?", default=".pouch/ack/tasks.yaml")
|
||||
parser.add_argument("--task-id", required=True)
|
||||
parser.add_argument("--task-json", type=Path, required=True, help="完整 task 快照 JSON")
|
||||
parser.add_argument("--record-id")
|
||||
parser.add_argument("--parent", action="append", default=[])
|
||||
parser.add_argument("--kind", default="task.snapshot")
|
||||
parser.add_argument("--worker-receipts-json", type=Path)
|
||||
parser.add_argument("--delivery-runs-json", type=Path)
|
||||
parser.add_argument("--regression-runs-json", type=Path)
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
task = _read_json_mapping(args.task_json, "task")
|
||||
output = append_record(
|
||||
Path(args.tasks), task, task_id=args.task_id,
|
||||
record_id=args.record_id, parents=args.parent, kind=args.kind,
|
||||
worker_receipts=(
|
||||
_read_json_list(args.worker_receipts_json, "worker receipt")
|
||||
if args.worker_receipts_json else None
|
||||
),
|
||||
delivery_runs=(
|
||||
_read_json_list(args.delivery_runs_json, "delivery run")
|
||||
if args.delivery_runs_json else None
|
||||
),
|
||||
regression_runs=(
|
||||
_read_json_list(args.regression_runs_json, "regression run")
|
||||
if args.regression_runs_json else None
|
||||
),
|
||||
)
|
||||
except (OSError, TaskStoreError) as exc:
|
||||
print(f"追加任务记录失败: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
print(output)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,249 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Merge-friendly ACK task records.
|
||||
|
||||
``tasks.yaml`` remains the small project manifest. When it contains a
|
||||
``taskStore`` mapping, task state is materialized from immutable record files
|
||||
under the configured directory. Legacy boards without that mapping keep
|
||||
their original single-file behavior.
|
||||
|
||||
Records are complete task snapshots rather than patches. A later record
|
||||
names its parent record(s), so a concurrent edit produces multiple heads and
|
||||
is reported as a semantic merge conflict instead of being silently resolved
|
||||
by file order or timestamps.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from yaml_subset import (
|
||||
DuplicateKeyError,
|
||||
YamlSubsetError,
|
||||
load_json_unique,
|
||||
load_yaml_subset,
|
||||
make_unique_pyyaml_loader,
|
||||
)
|
||||
|
||||
|
||||
STORE_VERSION = 1
|
||||
GLOBAL_TASK_ID = "__project__"
|
||||
TASK_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
||||
RECORD_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$")
|
||||
RECORD_SUFFIXES = {".yaml", ".yml", ".json"}
|
||||
|
||||
|
||||
class TaskStoreError(ValueError):
|
||||
"""A malformed task store or record."""
|
||||
|
||||
|
||||
def parse_document(path: Path) -> dict[str, Any]:
|
||||
"""Parse one YAML/JSON mapping without importing the validator."""
|
||||
|
||||
try:
|
||||
content = path.read_text(encoding="utf-8")
|
||||
except OSError as exc:
|
||||
raise TaskStoreError(f"读取失败: {path}: {exc}") from exc
|
||||
|
||||
try:
|
||||
if path.suffix.lower() == ".json":
|
||||
value = load_json_unique(content)
|
||||
else:
|
||||
try:
|
||||
import yaml # type: ignore
|
||||
except ImportError:
|
||||
value = load_yaml_subset(content)
|
||||
else:
|
||||
value = yaml.load(
|
||||
content,
|
||||
Loader=make_unique_pyyaml_loader(yaml),
|
||||
)
|
||||
except (json.JSONDecodeError, DuplicateKeyError, YamlSubsetError) as exc:
|
||||
raise TaskStoreError(f"解析失败: {path}: {exc}") from exc
|
||||
except Exception as exc: # PyYAML errors are intentionally bounded.
|
||||
raise TaskStoreError(f"解析失败: {path}") from exc
|
||||
|
||||
if not isinstance(value, dict):
|
||||
raise TaskStoreError(f"{path}: 顶层必须是对象(mapping)")
|
||||
return value
|
||||
|
||||
|
||||
def _record_directory(manifest: dict[str, Any], manifest_path: Path) -> Path:
|
||||
config = manifest.get("taskStore")
|
||||
if not isinstance(config, dict):
|
||||
raise TaskStoreError("taskStore 必须是对象")
|
||||
version = config.get("version", STORE_VERSION)
|
||||
if version != STORE_VERSION:
|
||||
raise TaskStoreError(f"不支持 taskStore.version={version!r}")
|
||||
directory = config.get("directory", "task-records")
|
||||
if not isinstance(directory, str) or not directory.strip():
|
||||
raise TaskStoreError("taskStore.directory 必须是非空相对路径")
|
||||
relative = Path(directory)
|
||||
if relative.is_absolute() or ".." in relative.parts:
|
||||
raise TaskStoreError("taskStore.directory 必须位于任务板目录下")
|
||||
return manifest_path.parent / relative
|
||||
|
||||
|
||||
def _record_paths(directory: Path) -> list[Path]:
|
||||
if not directory.exists():
|
||||
return []
|
||||
if directory.is_symlink() or not directory.is_dir():
|
||||
raise TaskStoreError(f"taskStore.directory 不是普通目录: {directory}")
|
||||
paths: list[Path] = []
|
||||
for path in sorted(directory.iterdir(), key=lambda item: item.name):
|
||||
if path.name.startswith("."):
|
||||
continue
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise TaskStoreError(f"任务记录必须是普通文件: {path}")
|
||||
if path.suffix.lower() in RECORD_SUFFIXES:
|
||||
paths.append(path)
|
||||
return paths
|
||||
|
||||
|
||||
def _unique_collection(
|
||||
records: list[dict[str, Any]],
|
||||
field: str,
|
||||
errors: list[str],
|
||||
) -> list[dict[str, Any]]:
|
||||
result: list[dict[str, Any]] = []
|
||||
by_id: dict[str, dict[str, Any]] = {}
|
||||
for record in records:
|
||||
values = record.get(field)
|
||||
if values is None:
|
||||
continue
|
||||
if not isinstance(values, list):
|
||||
errors.append(f"{field} 必须是列表")
|
||||
continue
|
||||
for index, item in enumerate(values):
|
||||
if not isinstance(item, dict):
|
||||
errors.append(f"{field}[{index}] 必须是对象")
|
||||
continue
|
||||
item_id = item.get("id")
|
||||
if not isinstance(item_id, str) or not item_id:
|
||||
errors.append(f"{field}[{index}].id 必须是非空字符串")
|
||||
continue
|
||||
previous = by_id.get(item_id)
|
||||
if previous is not None and previous != item:
|
||||
errors.append(f"{field} 出现相同 id 的不同记录: {item_id}")
|
||||
continue
|
||||
if previous is None:
|
||||
by_id[item_id] = item
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
|
||||
def materialize_board(manifest: dict[str, Any], manifest_path: Path) -> dict[str, Any]:
|
||||
"""Return a board-shaped view from a manifest and immutable records."""
|
||||
|
||||
directory = _record_directory(manifest, manifest_path)
|
||||
paths = _record_paths(directory)
|
||||
# This permits a staged rollout: a freshly initialized board has an empty
|
||||
# store and the legacy empty ``tasks: []`` field until its first record.
|
||||
if not paths:
|
||||
return manifest
|
||||
|
||||
errors: list[str] = []
|
||||
records: list[dict[str, Any]] = []
|
||||
by_record_id: dict[str, dict[str, Any]] = {}
|
||||
for path in paths:
|
||||
record = parse_document(path)
|
||||
where = str(path.relative_to(manifest_path.parent))
|
||||
version = record.get("recordVersion", STORE_VERSION)
|
||||
record_id = record.get("recordId")
|
||||
task_id = record.get("taskId")
|
||||
parents = record.get("parents", [])
|
||||
if version != STORE_VERSION:
|
||||
errors.append(f"{where}: 不支持 recordVersion={version!r}")
|
||||
if not isinstance(record_id, str) or RECORD_ID_RE.fullmatch(record_id) is None:
|
||||
errors.append(f"{where}: recordId 格式无效")
|
||||
elif record_id in by_record_id:
|
||||
errors.append(f"{where}: recordId 重复: {record_id}")
|
||||
if not isinstance(task_id, str) or (
|
||||
task_id != GLOBAL_TASK_ID and TASK_ID_RE.fullmatch(task_id) is None
|
||||
):
|
||||
errors.append(f"{where}: taskId 格式无效")
|
||||
if not isinstance(parents, list) or any(
|
||||
not isinstance(parent, str) or RECORD_ID_RE.fullmatch(parent) is None
|
||||
for parent in parents
|
||||
):
|
||||
errors.append(f"{where}: parents 必须是 recordId 字符串列表")
|
||||
task = record.get("task")
|
||||
if task_id != GLOBAL_TASK_ID and not isinstance(task, dict):
|
||||
errors.append(f"{where}: 非全局记录必须包含 task 对象")
|
||||
if isinstance(record_id, str) and record_id not in by_record_id:
|
||||
by_record_id[record_id] = record
|
||||
records.append(record)
|
||||
|
||||
for record in records:
|
||||
record_id = record.get("recordId")
|
||||
task_id = record.get("taskId")
|
||||
if not isinstance(record_id, str) or not isinstance(task_id, str):
|
||||
continue
|
||||
for parent in record.get("parents", []):
|
||||
if parent not in by_record_id:
|
||||
errors.append(f"{record_id}: 引用了不存在的 parent: {parent}")
|
||||
elif by_record_id[parent].get("taskId") != task_id:
|
||||
errors.append(f"{record_id}: parent 必须属于同一个 taskId")
|
||||
|
||||
task_records: dict[str, list[dict[str, Any]]] = {}
|
||||
for record in records:
|
||||
task_id = record.get("taskId")
|
||||
if isinstance(task_id, str) and task_id != GLOBAL_TASK_ID:
|
||||
task_records.setdefault(task_id, []).append(record)
|
||||
|
||||
tasks: list[dict[str, Any]] = []
|
||||
for task_id in sorted(task_records):
|
||||
items = task_records[task_id]
|
||||
referenced = {
|
||||
parent
|
||||
for item in items
|
||||
for parent in item.get("parents", [])
|
||||
if isinstance(parent, str)
|
||||
}
|
||||
heads = [
|
||||
item for item in items
|
||||
if isinstance(item.get("recordId"), str)
|
||||
and item["recordId"] not in referenced
|
||||
]
|
||||
if len(heads) != 1:
|
||||
errors.append(
|
||||
f"task {task_id}: 发现 {len(heads)} 个未合并 head,必须创建同时引用全部 head 的合并记录"
|
||||
)
|
||||
continue
|
||||
task = heads[0].get("task")
|
||||
if isinstance(task, dict):
|
||||
tasks.append(task)
|
||||
|
||||
result = dict(manifest)
|
||||
result["tasks"] = tasks
|
||||
result["workerReceipts"] = _unique_collection(records, "workerReceipts", errors)
|
||||
for field in ("deliveryRuns", "regressionRuns"):
|
||||
if field in manifest or any(field in record for record in records):
|
||||
result[field] = _unique_collection(records, field, errors)
|
||||
result["summary"] = {
|
||||
"open": [task["id"] for task in tasks if task.get("status") == "open"],
|
||||
"verified": [task["id"] for task in tasks if task.get("status") == "verified"],
|
||||
"failedRetest": [task["id"] for task in tasks if task.get("status") == "failed_retest"],
|
||||
"leftovers": [task["id"] for task in tasks if task.get("status") == "leftover"],
|
||||
}
|
||||
if errors:
|
||||
result["taskStoreErrors"] = errors
|
||||
else:
|
||||
result.pop("taskStoreErrors", None)
|
||||
return result
|
||||
|
||||
|
||||
def is_task_store_manifest(value: object) -> bool:
|
||||
return isinstance(value, dict) and "taskStore" in value
|
||||
|
||||
|
||||
__all__ = [
|
||||
"GLOBAL_TASK_ID",
|
||||
"STORE_VERSION",
|
||||
"TaskStoreError",
|
||||
"is_task_store_manifest",
|
||||
"materialize_board",
|
||||
"parse_document",
|
||||
]
|
||||
Executable
+51
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate an optional ACK .pouch/ack/agents.yaml routing override."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from validate_tasks import load_document, validate_with_schema
|
||||
from worker_profiles import validate_orchestration
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="校验 ACK agents.yaml 结构")
|
||||
parser.add_argument("agents", nargs="?", default="agents.yaml", help="agents.yaml 路径")
|
||||
parser.add_argument("--schema", help="agents.schema.json 路径(默认自动探测)")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
agents_path = Path(args.agents)
|
||||
if not agents_path.is_file() or agents_path.is_symlink():
|
||||
sys.stderr.write(f"agents.yaml 必须是普通文件且不能是 symlink: {agents_path}\n")
|
||||
return 2
|
||||
|
||||
data = load_document(agents_path)
|
||||
schema_path = Path(args.schema) if args.schema else (
|
||||
Path(__file__).resolve().parent.parent / "templates" / "agents.schema.json"
|
||||
)
|
||||
errors = validate_orchestration(data, where="agents.yaml")
|
||||
mode = "内置语义规则"
|
||||
try:
|
||||
import jsonschema # type: ignore # noqa: F401
|
||||
|
||||
if schema_path.is_file():
|
||||
errors = validate_with_schema(data, schema_path) + errors
|
||||
mode = f"schema ({schema_path.name}) + 内置语义规则"
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
if errors:
|
||||
sys.stderr.write(f"agents.yaml 校验失败({mode}),共 {len(errors)} 项:\n")
|
||||
for error in dict.fromkeys(errors):
|
||||
sys.stderr.write(f" - {error}\n")
|
||||
return 1
|
||||
|
||||
sys.stdout.write(f"agents.yaml 校验通过({mode}):{agents_path}\n")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -22,15 +22,7 @@ import sys
|
||||
from pathlib import Path, PurePosixPath
|
||||
from typing import Any
|
||||
|
||||
from yaml_subset import (
|
||||
DuplicateKeyError,
|
||||
YamlSubsetError,
|
||||
load_json_unique,
|
||||
load_yaml_subset,
|
||||
make_unique_pyyaml_loader,
|
||||
)
|
||||
|
||||
|
||||
from task_store import TaskStoreError, is_task_store_manifest, materialize_board, parse_document
|
||||
ID_RE = re.compile(r"^[a-z][a-z0-9-]{0,63}$")
|
||||
RELATIVE_PATH_RE = re.compile(r"^[A-Za-z0-9._/*?+-]+$")
|
||||
PLATFORM_RE = re.compile(r"^[a-z0-9]+/[A-Za-z0-9._-]+$")
|
||||
@@ -162,36 +154,12 @@ def _reject_unknown(
|
||||
|
||||
def _load_document(path: Path, label: str) -> dict[str, Any]:
|
||||
try:
|
||||
content = path.read_text(encoding="utf-8")
|
||||
except OSError as exc:
|
||||
data = parse_document(path)
|
||||
if is_task_store_manifest(data):
|
||||
data = materialize_board(data, path)
|
||||
except TaskStoreError as exc:
|
||||
sys.stderr.write(f"{label}读取失败: {exc}\n")
|
||||
raise SystemExit(1)
|
||||
|
||||
if path.suffix.lower() == ".json":
|
||||
try:
|
||||
data = load_json_unique(content)
|
||||
except (json.JSONDecodeError, DuplicateKeyError) as exc:
|
||||
sys.stderr.write(f"{label} JSON 解析失败: {exc}\n")
|
||||
raise SystemExit(1)
|
||||
else:
|
||||
try:
|
||||
import yaml # type: ignore
|
||||
except ImportError:
|
||||
try:
|
||||
data = load_yaml_subset(content)
|
||||
except YamlSubsetError as exc:
|
||||
sys.stderr.write(f"{label} YAML 子集解析失败: {exc}\n")
|
||||
raise SystemExit(1)
|
||||
else:
|
||||
try:
|
||||
data = yaml.load(content, Loader=make_unique_pyyaml_loader(yaml))
|
||||
except yaml.YAMLError as exc: # type: ignore
|
||||
sys.stderr.write(f"{label} YAML 解析失败: {exc}\n")
|
||||
raise SystemExit(1)
|
||||
|
||||
if not isinstance(data, dict):
|
||||
sys.stderr.write(f"{label}顶层必须是对象(mapping)\n")
|
||||
raise SystemExit(1)
|
||||
return data
|
||||
|
||||
|
||||
|
||||
@@ -21,15 +21,7 @@ import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from yaml_subset import (
|
||||
DuplicateKeyError,
|
||||
YamlSubsetError,
|
||||
load_json_unique,
|
||||
load_yaml_subset,
|
||||
make_unique_pyyaml_loader,
|
||||
)
|
||||
|
||||
|
||||
from task_store import TaskStoreError, is_task_store_manifest, materialize_board, parse_document
|
||||
ID_RE = re.compile(r"^REG-[A-Za-z0-9][A-Za-z0-9-]*$")
|
||||
TASK_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
||||
RELATIVE_PATH_RE = re.compile(r"^[A-Za-z0-9._/-]+$")
|
||||
@@ -75,36 +67,12 @@ def _reject_unknown(
|
||||
|
||||
def load_yaml(path: Path, label: str) -> dict[str, Any]:
|
||||
try:
|
||||
content = path.read_text(encoding="utf-8")
|
||||
except OSError as exc:
|
||||
data = parse_document(path)
|
||||
if is_task_store_manifest(data):
|
||||
data = materialize_board(data, path)
|
||||
except TaskStoreError as exc:
|
||||
sys.stderr.write(f"{label}读取失败: {exc}\n")
|
||||
raise SystemExit(1)
|
||||
|
||||
if path.suffix.lower() == ".json":
|
||||
try:
|
||||
data = load_json_unique(content)
|
||||
except (json.JSONDecodeError, DuplicateKeyError) as exc:
|
||||
sys.stderr.write(f"{label} JSON 解析失败: {exc}\n")
|
||||
raise SystemExit(1)
|
||||
else:
|
||||
try:
|
||||
import yaml # type: ignore
|
||||
except ImportError:
|
||||
try:
|
||||
data = load_yaml_subset(content)
|
||||
except YamlSubsetError as exc:
|
||||
sys.stderr.write(f"{label} YAML 子集解析失败: {exc}\n")
|
||||
raise SystemExit(1)
|
||||
else:
|
||||
try:
|
||||
data = yaml.load(content, Loader=make_unique_pyyaml_loader(yaml))
|
||||
except yaml.YAMLError as exc: # type: ignore
|
||||
sys.stderr.write(f"{label} YAML 解析失败: {exc}\n")
|
||||
raise SystemExit(1)
|
||||
|
||||
if not isinstance(data, dict):
|
||||
sys.stderr.write(f"{label}顶层必须是对象(mapping)\n")
|
||||
raise SystemExit(1)
|
||||
return data
|
||||
|
||||
|
||||
|
||||
@@ -25,13 +25,8 @@ import sys
|
||||
from pathlib import Path
|
||||
|
||||
from approval_payload import approval_payload_hash
|
||||
from yaml_subset import (
|
||||
DuplicateKeyError,
|
||||
YamlSubsetError,
|
||||
load_json_unique,
|
||||
load_yaml_subset,
|
||||
make_unique_pyyaml_loader,
|
||||
)
|
||||
from task_store import TaskStoreError, is_task_store_manifest, materialize_board, parse_document
|
||||
from worker_profiles import validate_orchestration
|
||||
from worker_profiles import validate_routing_document
|
||||
|
||||
STATUS_ENUM = {
|
||||
@@ -242,38 +237,12 @@ def _nonempty_string(value: object) -> bool:
|
||||
|
||||
def load_document(path: Path) -> dict:
|
||||
try:
|
||||
content = path.read_text(encoding="utf-8")
|
||||
except OSError as exc:
|
||||
data = parse_document(path)
|
||||
if is_task_store_manifest(data):
|
||||
data = materialize_board(data, path)
|
||||
except TaskStoreError as exc:
|
||||
sys.stderr.write(f"任务板读取失败: {exc}\n")
|
||||
raise SystemExit(1)
|
||||
|
||||
if path.suffix.lower() == ".json":
|
||||
try:
|
||||
data = load_json_unique(content)
|
||||
except (json.JSONDecodeError, DuplicateKeyError) as exc:
|
||||
sys.stderr.write(f"JSON 解析失败: {exc}\n")
|
||||
raise SystemExit(1)
|
||||
else:
|
||||
try:
|
||||
import yaml # type: ignore
|
||||
except ImportError:
|
||||
try:
|
||||
data = load_yaml_subset(content)
|
||||
except YamlSubsetError as exc:
|
||||
sys.stderr.write(f"YAML 子集解析失败: {exc}\n")
|
||||
raise SystemExit(1)
|
||||
else:
|
||||
try:
|
||||
data = yaml.load(
|
||||
content,
|
||||
Loader=make_unique_pyyaml_loader(yaml),
|
||||
)
|
||||
except yaml.YAMLError as exc: # type: ignore
|
||||
sys.stderr.write(f"YAML 解析失败: {exc}\n")
|
||||
raise SystemExit(1)
|
||||
if not isinstance(data, dict):
|
||||
sys.stderr.write("任务板顶层必须是对象(mapping)\n")
|
||||
raise SystemExit(1)
|
||||
return data
|
||||
|
||||
|
||||
@@ -894,8 +863,17 @@ def validate_with_schema(data: dict, schema_path: Path) -> list[str]:
|
||||
return errors
|
||||
|
||||
|
||||
def validate_builtin(data: dict) -> list[str]:
|
||||
def validate_builtin(
|
||||
data: dict,
|
||||
*,
|
||||
orchestration_override: dict | None = None,
|
||||
) -> list[str]:
|
||||
errors: list[str] = []
|
||||
store_errors = data.get("taskStoreErrors")
|
||||
if isinstance(store_errors, list):
|
||||
for error in store_errors:
|
||||
if isinstance(error, str) and error.strip():
|
||||
errors.append(f"taskStore: {error}")
|
||||
project_intake_workflow = "read-only-v1"
|
||||
|
||||
def validate_string_fields(
|
||||
@@ -1044,6 +1022,8 @@ def validate_builtin(data: dict) -> list[str]:
|
||||
if "ackVersion" in data and version_match is None:
|
||||
errors.append("ackVersion 必须是合法 SemVer(例如 0.10.0)")
|
||||
routing_required = (
|
||||
orchestration_override is not None
|
||||
or
|
||||
(isinstance(project, dict) and "orchestration" in project)
|
||||
or "workerReceipts" in data
|
||||
or (
|
||||
@@ -1053,7 +1033,12 @@ def validate_builtin(data: dict) -> list[str]:
|
||||
)
|
||||
)
|
||||
if routing_required:
|
||||
errors.extend(validate_routing_document(data))
|
||||
errors.extend(
|
||||
validate_routing_document(
|
||||
data,
|
||||
orchestration_override=orchestration_override,
|
||||
)
|
||||
)
|
||||
|
||||
if "summary" in data:
|
||||
summary = data["summary"]
|
||||
@@ -1415,7 +1400,27 @@ def main(argv: list[str] | None = None) -> int:
|
||||
sys.stderr.write(f"找不到指定的 schema 文件: {schema_path}\n")
|
||||
return 2
|
||||
|
||||
errors = validate_builtin(data)
|
||||
agents_path = tasks_path.with_name("agents.yaml")
|
||||
agents = None
|
||||
if agents_path.is_symlink():
|
||||
errors = ["agents.yaml 不能是 symlink"]
|
||||
agents = None
|
||||
elif agents_path.is_file():
|
||||
agents = load_document(agents_path)
|
||||
if not isinstance(agents, dict):
|
||||
errors = ["agents.yaml 顶层必须是对象(mapping)"]
|
||||
agents = None
|
||||
else:
|
||||
errors = validate_orchestration(agents, where="agents.yaml")
|
||||
else:
|
||||
errors = []
|
||||
|
||||
errors.extend(validate_builtin(data, orchestration_override=agents))
|
||||
if agents is not None:
|
||||
project = data.get("project")
|
||||
board_orchestration = project.get("orchestration") if isinstance(project, dict) else None
|
||||
if board_orchestration is not None:
|
||||
errors.extend(validate_orchestration(board_orchestration))
|
||||
mode = "内置语义规则"
|
||||
try:
|
||||
import jsonschema # type: ignore # noqa: F401
|
||||
|
||||
@@ -13,7 +13,7 @@ import sys
|
||||
|
||||
MIGRATION_MESSAGE = (
|
||||
"ACK v0.10 已停用自由 worker command 校验器;请在 "
|
||||
".pouch/ack/tasks.yaml 的 project.orchestration 中声明 profile,并仅调用 "
|
||||
".pouch/ack/agents.yaml(优先)或 .pouch/ack/tasks.yaml 的 project.orchestration 中声明 profile,并仅调用 "
|
||||
"scripts/launch_worker.py profile-hash|plan|launch。"
|
||||
)
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ Output (single JSON document on stdout):
|
||||
"status": "running | progress | stall | not-started | unknown",
|
||||
"stallReason": "<label> | null",
|
||||
"heartbeatAt": "<value> | null",
|
||||
"heartbeatAgeSeconds": "<number> | null",
|
||||
"evidence": "<bounded terminal tail>"
|
||||
}
|
||||
|
||||
@@ -29,6 +30,7 @@ import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -36,6 +38,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from launch_worker import ( # noqa: E402
|
||||
LaunchError,
|
||||
parse_timestamp,
|
||||
resolve_executable,
|
||||
run_json,
|
||||
utc_now,
|
||||
@@ -53,48 +56,113 @@ WORKING_PATTERN = re.compile(r"(?i)working|•working|running|执行中|正在")
|
||||
IDLE_TAIL_PATTERN = re.compile(r"(?i)welcome to|type help|fish, the friendly|>\\s*$")
|
||||
|
||||
MAX_EVIDENCE_CHARS = 500
|
||||
HEARTBEAT_INTERVAL_SECONDS = 5 * 60
|
||||
HEARTBEAT_MAX_AGE_SECONDS = HEARTBEAT_INTERVAL_SECONDS * 3
|
||||
|
||||
|
||||
def classify(tail: str | list[str], heartbeat: object) -> dict[str, object]:
|
||||
def heartbeat_age_seconds(
|
||||
heartbeat: object, now: datetime | None = None
|
||||
) -> tuple[float | None, str | None]:
|
||||
"""Return heartbeat age and a diagnostic for malformed/stale timestamps."""
|
||||
|
||||
if heartbeat is None:
|
||||
return None, None
|
||||
try:
|
||||
heartbeat_at = parse_timestamp(heartbeat, "last_heartbeat_at")
|
||||
except LaunchError:
|
||||
return None, "invalid-heartbeat"
|
||||
|
||||
current = now if now is not None else utc_now()
|
||||
age = (current - heartbeat_at).total_seconds()
|
||||
if age < -60:
|
||||
return None, "future-heartbeat"
|
||||
return max(age, 0.0), None
|
||||
|
||||
|
||||
def _result(
|
||||
*,
|
||||
status: str,
|
||||
stall_reason: str | None,
|
||||
heartbeat: object,
|
||||
heartbeat_age: float | None,
|
||||
evidence: str,
|
||||
) -> dict[str, object]:
|
||||
return {
|
||||
"status": status,
|
||||
"stallReason": stall_reason,
|
||||
"heartbeatAt": heartbeat,
|
||||
"heartbeatAgeSeconds": heartbeat_age,
|
||||
"evidence": evidence[:MAX_EVIDENCE_CHARS],
|
||||
}
|
||||
|
||||
|
||||
def classify(
|
||||
tail: str | list[str],
|
||||
heartbeat: object,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, object]:
|
||||
if isinstance(tail, list):
|
||||
tail = "\n".join(tail)
|
||||
heartbeat_age, heartbeat_error = heartbeat_age_seconds(heartbeat, now)
|
||||
for label, pattern in STALL_PATTERNS:
|
||||
if pattern.search(tail):
|
||||
return {
|
||||
"status": "stall",
|
||||
"stallReason": label,
|
||||
"heartbeatAt": heartbeat,
|
||||
"evidence": tail[:MAX_EVIDENCE_CHARS],
|
||||
}
|
||||
if heartbeat:
|
||||
return {
|
||||
"status": "progress",
|
||||
"stallReason": None,
|
||||
"heartbeatAt": heartbeat,
|
||||
"evidence": tail[:MAX_EVIDENCE_CHARS],
|
||||
}
|
||||
return _result(
|
||||
status="stall",
|
||||
stall_reason=label,
|
||||
heartbeat=heartbeat,
|
||||
heartbeat_age=heartbeat_age,
|
||||
evidence=tail,
|
||||
)
|
||||
if heartbeat_error:
|
||||
return _result(
|
||||
status="unknown",
|
||||
stall_reason=heartbeat_error,
|
||||
heartbeat=heartbeat,
|
||||
heartbeat_age=heartbeat_age,
|
||||
evidence=tail,
|
||||
)
|
||||
if heartbeat_age is not None and heartbeat_age <= HEARTBEAT_MAX_AGE_SECONDS:
|
||||
return _result(
|
||||
status="progress",
|
||||
stall_reason=None,
|
||||
heartbeat=heartbeat,
|
||||
heartbeat_age=heartbeat_age,
|
||||
evidence=tail,
|
||||
)
|
||||
if heartbeat_age is not None:
|
||||
return _result(
|
||||
status="unknown",
|
||||
stall_reason="stale-heartbeat",
|
||||
heartbeat=heartbeat,
|
||||
heartbeat_age=heartbeat_age,
|
||||
evidence=tail,
|
||||
)
|
||||
if WORKING_PATTERN.search(tail):
|
||||
return {
|
||||
"status": "running",
|
||||
"stallReason": None,
|
||||
"heartbeatAt": None,
|
||||
"evidence": tail[:MAX_EVIDENCE_CHARS],
|
||||
}
|
||||
return _result(
|
||||
status="running",
|
||||
stall_reason=None,
|
||||
heartbeat=heartbeat,
|
||||
heartbeat_age=heartbeat_age,
|
||||
evidence=tail,
|
||||
)
|
||||
# No heartbeat and no working marker: the terminal may still be sitting at
|
||||
# a welcome/idle prompt (task never started) or have unclassified output.
|
||||
if IDLE_TAIL_PATTERN.search(tail) or not tail.strip():
|
||||
return {
|
||||
"status": "not-started",
|
||||
"stallReason": None,
|
||||
"heartbeatAt": None,
|
||||
"evidence": tail[:MAX_EVIDENCE_CHARS],
|
||||
}
|
||||
return {
|
||||
"status": "unknown",
|
||||
"stallReason": None,
|
||||
"heartbeatAt": None,
|
||||
"evidence": tail[:MAX_EVIDENCE_CHARS],
|
||||
}
|
||||
return _result(
|
||||
status="not-started",
|
||||
stall_reason=None,
|
||||
heartbeat=heartbeat,
|
||||
heartbeat_age=heartbeat_age,
|
||||
evidence=tail,
|
||||
)
|
||||
return _result(
|
||||
status="unknown",
|
||||
stall_reason=None,
|
||||
heartbeat=heartbeat,
|
||||
heartbeat_age=heartbeat_age,
|
||||
evidence=tail,
|
||||
)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
@@ -126,6 +194,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
"status": "unknown",
|
||||
"stallReason": None,
|
||||
"heartbeatAt": None,
|
||||
"heartbeatAgeSeconds": None,
|
||||
"evidence": f"probe failed: {type(exc).__name__}: {exc}",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
|
||||
@@ -24,14 +24,15 @@ LAUNCH_PROTOCOL_VERSION = 1
|
||||
MAX_ROUNDS = 3
|
||||
|
||||
ROLES = frozenset({"developer", "test"})
|
||||
CLIS = frozenset({"codex", "cursor-agent", "grok", "omp"})
|
||||
CLIS = frozenset({"codex", "cursor-agent", "grok", "omp", "pi"})
|
||||
TIERS = frozenset({"standard", "strong"})
|
||||
REASONING_EFFORTS = frozenset({"low", "medium", "high", "xhigh"})
|
||||
PERMISSION_MODES = frozenset({"read-only", "workspace-write"})
|
||||
PERMISSION_MODES = frozenset({"read-only", "workspace-write", "danger-full-access"})
|
||||
ORCHESTRATION_MODES = frozenset({"orca", "manual"})
|
||||
DEFAULT_KEYS = frozenset({"developer", "test", "developerUpgraded"})
|
||||
CLI_REQUIRES_REASONING_EFFORT = frozenset({"codex", "grok", "omp"})
|
||||
CLI_REQUIRES_NULL_REASONING_EFFORT = frozenset({"cursor-agent"})
|
||||
CLI_ALLOWS_DEFAULT_MODEL = frozenset({"pi"})
|
||||
|
||||
|
||||
def _cli_choice_text() -> str:
|
||||
@@ -95,7 +96,9 @@ RECEIPT_FIELDS = frozenset(
|
||||
"receiptHash",
|
||||
}
|
||||
)
|
||||
RECEIPT_CONTEXT_FIELDS = frozenset({"projectRoot", "boardHash"})
|
||||
RECEIPT_CONTEXT_FIELDS = frozenset(
|
||||
{"projectRoot", "boardHash", "routingSource", "routingHash"}
|
||||
)
|
||||
CREATED_FOR_FIELDS = frozenset({"taskId", "attemptId", "role"})
|
||||
WORKTREE_FIELDS = frozenset(
|
||||
{
|
||||
@@ -247,12 +250,16 @@ def validate_profile(profile: Any, *, where: str = "profile") -> list[str]:
|
||||
errors.append(f"{where}.cli: must be {_cli_choice_text()}")
|
||||
if not isinstance(tier, str) or tier not in TIERS:
|
||||
errors.append(f"{where}.tier: must be standard/strong")
|
||||
if not isinstance(model, str) or MODEL_ID_RE.fullmatch(model) is None:
|
||||
errors.append(f"{where}.model: must be a safe model ID")
|
||||
if not (isinstance(cli, str) and cli in CLI_ALLOWS_DEFAULT_MODEL and model is None) and (
|
||||
not isinstance(model, str) or MODEL_ID_RE.fullmatch(model) is None
|
||||
):
|
||||
errors.append(f"{where}.model: must be a safe model ID or null for Pi default")
|
||||
if not isinstance(permission, str) or permission not in PERMISSION_MODES:
|
||||
errors.append(
|
||||
f"{where}.permissionMode: must be read-only/workspace-write"
|
||||
f"{where}.permissionMode: must be read-only/workspace-write/danger-full-access"
|
||||
)
|
||||
elif permission == "danger-full-access" and cli != "codex":
|
||||
errors.append(f"{where}.permissionMode: danger-full-access requires Codex")
|
||||
if isinstance(cli, str) and cli in CLI_REQUIRES_REASONING_EFFORT:
|
||||
if not isinstance(effort, str) or effort not in REASONING_EFFORTS:
|
||||
label = "Codex" if cli == "codex" else "Grok"
|
||||
@@ -265,6 +272,10 @@ def validate_profile(profile: Any, *, where: str = "profile") -> list[str]:
|
||||
and effort is not None
|
||||
):
|
||||
errors.append(f"{where}.reasoningEffort: Cursor requires null")
|
||||
elif isinstance(cli, str) and cli == "pi" and (
|
||||
not isinstance(effort, str) or effort not in REASONING_EFFORTS
|
||||
):
|
||||
errors.append(f"{where}.reasoningEffort: Pi requires low/medium/high/xhigh")
|
||||
|
||||
if role == "test" and tier != "standard":
|
||||
errors.append(f"{where}.tier: Test may only use standard")
|
||||
@@ -312,15 +323,22 @@ def _validate_model_allowlist(value: Any, where: str) -> list[str]:
|
||||
if not isinstance(models, list) or not models:
|
||||
errors.append(f"{tier_where}: must be a non-empty model list")
|
||||
continue
|
||||
seen: set[str] = set()
|
||||
seen: set[object] = set()
|
||||
for index, model in enumerate(models):
|
||||
item_where = f"{tier_where}[{index}]"
|
||||
if not isinstance(model, str) or MODEL_ID_RE.fullmatch(model) is None:
|
||||
errors.append(f"{item_where}: must be a safe model ID")
|
||||
elif model in seen:
|
||||
if model is None and cli in CLI_ALLOWS_DEFAULT_MODEL:
|
||||
model_key: object = ("default",)
|
||||
elif not isinstance(model, str) or MODEL_ID_RE.fullmatch(model) is None:
|
||||
errors.append(
|
||||
f"{item_where}: must be a safe model ID or null for Pi default"
|
||||
)
|
||||
continue
|
||||
else:
|
||||
model_key = model
|
||||
if model_key in seen:
|
||||
errors.append(f"{item_where}: duplicate model {model!r}")
|
||||
else:
|
||||
seen.add(model)
|
||||
seen.add(model_key)
|
||||
return errors
|
||||
|
||||
|
||||
@@ -329,7 +347,7 @@ def _allowed_models(
|
||||
cli: Any,
|
||||
role: Any,
|
||||
tier: Any,
|
||||
) -> list[str] | None:
|
||||
) -> list[Any] | None:
|
||||
if not isinstance(allowlist, dict):
|
||||
return None
|
||||
roles = allowlist.get(cli)
|
||||
@@ -519,6 +537,19 @@ def render_worker_argv(
|
||||
"--no-session",
|
||||
]
|
||||
|
||||
if cli == "pi":
|
||||
# Pi's omitted --model selects its configured startup default. Its
|
||||
# cwd is supplied by the trusted bootstrap process, because Pi has no
|
||||
# --cwd flag. Read-only profiles are restricted to observation tools;
|
||||
# workspace-write profiles use Pi's normal editing tool set.
|
||||
argv = [executable]
|
||||
if model is not None:
|
||||
argv.extend(["--model", model])
|
||||
argv.extend(["--thinking", profile["reasoningEffort"]])
|
||||
if permission == "read-only":
|
||||
argv.extend(["--tools", "read,grep,find,ls"])
|
||||
return argv
|
||||
|
||||
if cli != "grok":
|
||||
raise ValueError(f"unsupported cli: {cli}")
|
||||
grok_permission = "plan" if permission == "read-only" else "acceptEdits"
|
||||
@@ -597,8 +628,10 @@ def _validate_requested(value: Any, where: str) -> list[str]:
|
||||
if not isinstance(tier, str) or tier not in TIERS:
|
||||
errors.append(f"{where}.tier: must be standard/strong")
|
||||
model = value.get("model")
|
||||
if not isinstance(model, str) or MODEL_ID_RE.fullmatch(model) is None:
|
||||
errors.append(f"{where}.model: must be a safe model ID")
|
||||
if not (isinstance(cli, str) and cli in CLI_ALLOWS_DEFAULT_MODEL and model is None) and (
|
||||
not isinstance(model, str) or MODEL_ID_RE.fullmatch(model) is None
|
||||
):
|
||||
errors.append(f"{where}.model: must be a safe model ID or null for Pi default")
|
||||
effort = value.get("reasoningEffort")
|
||||
if isinstance(cli, str) and cli in CLI_REQUIRES_REASONING_EFFORT and (
|
||||
not isinstance(effort, str) or effort not in REASONING_EFFORTS
|
||||
@@ -611,8 +644,14 @@ def _validate_requested(value: Any, where: str) -> list[str]:
|
||||
and effort is not None
|
||||
):
|
||||
errors.append(f"{where}.reasoningEffort: Cursor requires null")
|
||||
if isinstance(cli, str) and cli == "pi" and (
|
||||
not isinstance(effort, str) or effort not in REASONING_EFFORTS
|
||||
):
|
||||
errors.append(f"{where}.reasoningEffort: Pi requires low/medium/high/xhigh")
|
||||
if not isinstance(permission, str) or permission not in PERMISSION_MODES:
|
||||
errors.append(f"{where}.permissionMode: must be read-only/workspace-write")
|
||||
errors.append(f"{where}.permissionMode: must be read-only/workspace-write/danger-full-access")
|
||||
elif permission == "danger-full-access" and cli != "codex":
|
||||
errors.append(f"{where}.permissionMode: danger-full-access requires Codex")
|
||||
executable = value.get("executable")
|
||||
if not _is_absolute_safe_path(executable):
|
||||
errors.append(f"{where}.executable: must be a safe absolute path")
|
||||
@@ -697,6 +736,16 @@ def validate_worker_receipt(
|
||||
not isinstance(board_hash, str) or SHA256_RE.fullmatch(board_hash) is None
|
||||
):
|
||||
errors.append(f"{where}.boardHash: must be a canonical sha256 hex digest")
|
||||
routing_source = receipt.get("routingSource")
|
||||
routing_hash = receipt.get("routingHash")
|
||||
if (routing_source is None) != (routing_hash is None):
|
||||
errors.append(f"{where}: routingSource and routingHash must be present together")
|
||||
if routing_source is not None and not _is_nonempty_text(routing_source, max_length=512):
|
||||
errors.append(f"{where}.routingSource: must be non-empty single-line text")
|
||||
if routing_hash is not None and (
|
||||
not isinstance(routing_hash, str) or SHA256_RE.fullmatch(routing_hash) is None
|
||||
):
|
||||
errors.append(f"{where}.routingHash: must be a canonical sha256 hex digest")
|
||||
|
||||
version = receipt.get("receiptVersion")
|
||||
if version != RECEIPT_VERSION or isinstance(version, bool):
|
||||
@@ -818,6 +867,9 @@ def validate_worker_receipt(
|
||||
if project_root is not None and board_hash is not None:
|
||||
facts["projectRoot"] = project_root
|
||||
facts["boardHash"] = board_hash
|
||||
if routing_source is not None and routing_hash is not None:
|
||||
facts["routingSource"] = routing_source
|
||||
facts["routingHash"] = routing_hash
|
||||
expected_fingerprint = canonical_sha256(facts)
|
||||
except ValueError:
|
||||
errors.append(f"{where}.launchFingerprint: cannot hash launch facts")
|
||||
@@ -1006,17 +1058,30 @@ def _validate_dispatch_links(
|
||||
return errors
|
||||
|
||||
|
||||
def validate_routing_document(data: Any) -> list[str]:
|
||||
"""Validate routing and receipts embedded in an ACK tasks document."""
|
||||
def validate_routing_document(
|
||||
data: Any,
|
||||
*,
|
||||
orchestration_override: dict[str, Any] | None = None,
|
||||
) -> list[str]:
|
||||
"""Validate routing and receipts in an ACK tasks document.
|
||||
|
||||
``orchestration_override`` is the optional project-local agents.yaml
|
||||
routing document. The task board remains the state source, while the
|
||||
override becomes the effective profile source for receipt checks.
|
||||
"""
|
||||
|
||||
if not isinstance(data, dict):
|
||||
return ["<root>: must be an object"]
|
||||
project = data.get("project")
|
||||
if not isinstance(project, dict):
|
||||
return ["project: must be an object"]
|
||||
if "orchestration" not in project:
|
||||
if "orchestration" not in project and orchestration_override is None:
|
||||
return ["project.orchestration: is required"]
|
||||
orchestration = project.get("orchestration")
|
||||
orchestration = (
|
||||
orchestration_override
|
||||
if orchestration_override is not None
|
||||
else project.get("orchestration")
|
||||
)
|
||||
errors = validate_orchestration(orchestration)
|
||||
|
||||
task_ids: set[str] = set()
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$id": "https://git.yumee.top/laily/pouch/skills/ack/templates/agents.schema.json",
|
||||
"title": "ACK project agent routing override",
|
||||
"description": "Optional .pouch/ack/agents.yaml. It has the same routing shape as project.orchestration.",
|
||||
"type": "object",
|
||||
"required": ["profileVersion", "mode", "modelAllowlist", "profiles", "defaults"],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"profileVersion": {"type": "integer", "const": 1},
|
||||
"mode": {"type": "string", "enum": ["orca", "manual"]},
|
||||
"modelAllowlist": {"$ref": "#/definitions/modelAllowlist"},
|
||||
"profiles": {
|
||||
"type": "object",
|
||||
"propertyNames": {"$ref": "#/definitions/profileId"},
|
||||
"additionalProperties": {"$ref": "#/definitions/workerProfile"}
|
||||
},
|
||||
"defaults": {"$ref": "#/definitions/defaults"}
|
||||
},
|
||||
"definitions": {
|
||||
"profileId": {"type": "string", "pattern": "^[a-z][a-z0-9-]{1,63}$"},
|
||||
"model": {
|
||||
"oneOf": [
|
||||
{"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._:/+@-]{0,127}$"},
|
||||
{"type": "null", "description": "仅 pi 使用 null 表示默认模型"}
|
||||
]
|
||||
},
|
||||
"modelList": {"type": "array", "minItems": 1, "uniqueItems": true, "items": {"$ref": "#/definitions/model"}},
|
||||
"modelTierAllowlist": {
|
||||
"type": "object",
|
||||
"minProperties": 1,
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"standard": {"$ref": "#/definitions/modelList"},
|
||||
"strong": {"$ref": "#/definitions/modelList"}
|
||||
}
|
||||
},
|
||||
"modelRoleAllowlist": {
|
||||
"type": "object",
|
||||
"minProperties": 1,
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"developer": {"$ref": "#/definitions/modelTierAllowlist"},
|
||||
"test": {"$ref": "#/definitions/modelTierAllowlist"}
|
||||
}
|
||||
},
|
||||
"modelAllowlist": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"codex": {"$ref": "#/definitions/modelRoleAllowlist"},
|
||||
"cursor-agent": {"$ref": "#/definitions/modelRoleAllowlist"},
|
||||
"grok": {"$ref": "#/definitions/modelRoleAllowlist"},
|
||||
"omp": {"$ref": "#/definitions/modelRoleAllowlist"},
|
||||
"pi": {"$ref": "#/definitions/modelRoleAllowlist"}
|
||||
}
|
||||
},
|
||||
"workerProfile": {
|
||||
"type": "object",
|
||||
"required": ["role", "cli", "tier", "model", "reasoningEffort", "permissionMode"],
|
||||
"additionalProperties": false,
|
||||
"allOf": [{"if": {"properties": {"permissionMode": {"const": "danger-full-access"}}, "required": ["permissionMode"]}, "then": {"properties": {"cli": {"const": "codex"}}, "required": ["cli"]}}],
|
||||
"properties": {
|
||||
"role": {"type": "string", "enum": ["developer", "test"]},
|
||||
"cli": {"type": "string", "enum": ["codex", "cursor-agent", "grok", "omp", "pi"]},
|
||||
"tier": {"type": "string", "enum": ["standard", "strong"]},
|
||||
"model": {"$ref": "#/definitions/model"},
|
||||
"reasoningEffort": {"type": ["string", "null"], "enum": ["low", "medium", "high", "xhigh", null]},
|
||||
"permissionMode": {"type": "string", "enum": ["read-only", "workspace-write", "danger-full-access"]}
|
||||
}
|
||||
},
|
||||
"defaults": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["developer", "test"],
|
||||
"properties": {
|
||||
"developer": {"$ref": "#/definitions/profileId"},
|
||||
"test": {"$ref": "#/definitions/profileId"},
|
||||
"developerUpgraded": {"$ref": "#/definitions/profileId"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
# Optional project-local worker routing override.
|
||||
# Save as .pouch/ack/agents.yaml when a temporary role/CLI/model selection is needed.
|
||||
# This file intentionally has the same shape as tasks.yaml.project.orchestration.
|
||||
profileVersion: 1
|
||||
mode: "orca"
|
||||
modelAllowlist:
|
||||
pi:
|
||||
developer:
|
||||
standard: [null]
|
||||
strong: [null]
|
||||
cursor-agent:
|
||||
test:
|
||||
standard: ["auto"]
|
||||
profiles:
|
||||
pi-dev-standard:
|
||||
role: "developer"
|
||||
cli: "pi"
|
||||
tier: "standard"
|
||||
model: null
|
||||
reasoningEffort: "medium"
|
||||
permissionMode: "workspace-write"
|
||||
pi-dev-strong:
|
||||
role: "developer"
|
||||
cli: "pi"
|
||||
tier: "strong"
|
||||
model: null
|
||||
reasoningEffort: "high"
|
||||
permissionMode: "workspace-write"
|
||||
cursor-test-standard:
|
||||
role: "test"
|
||||
cli: "cursor-agent"
|
||||
tier: "standard"
|
||||
model: "auto"
|
||||
reasoningEffort: null
|
||||
permissionMode: "workspace-write"
|
||||
defaults:
|
||||
developer: "pi-dev-standard"
|
||||
test: "cursor-test-standard"
|
||||
developerUpgraded: "pi-dev-strong"
|
||||
@@ -8,8 +8,8 @@
|
||||
> 若希望 Agent 自动加载,可由项目维护者自行在 `AGENTS.md` 中引用本文件;ACK
|
||||
> 不会自动修改 `AGENTS.md`、`CLAUDE.md` 或其它 Agent 指令文件。
|
||||
> 无论叫什么,都在 `tasks.yaml` 的 `project.overlayFile` 记录实际路径。
|
||||
> `.pouch/ack/` 只保存本项目的 `project.md`、`tasks.yaml`、`knowledge.yaml`、默认关闭的
|
||||
> `delivery.yaml` 与空的 `regression.yaml`,
|
||||
> `.pouch/ack/` 只保存本项目的 `project.md`、`tasks.yaml`、`task-records/`、`knowledge.yaml`、默认关闭的
|
||||
> `delivery.yaml`、空的 `regression.yaml`,以及可选的 `agents.yaml` 角色启动覆盖,
|
||||
> 不复制或链接 Skill。
|
||||
|
||||
## 项目概览
|
||||
@@ -18,10 +18,12 @@
|
||||
- 技术栈:`<tech_stack>`
|
||||
- 运行命令:`<run_command>`
|
||||
- Base URL:`<base_url>`
|
||||
- 任务板:`.pouch/ack/tasks.yaml`
|
||||
- 任务板配置:`.pouch/ack/tasks.yaml`
|
||||
- 任务记录:`.pouch/ack/task-records/<recordId>.yaml`(追加式)
|
||||
- 项目知识:`.pouch/ack/knowledge.yaml`
|
||||
- 交付契约:`.pouch/ack/delivery.yaml`(默认关闭)
|
||||
- 回归目录:`.pouch/ack/regression.yaml`
|
||||
- 角色启动覆盖(可选):`.pouch/ack/agents.yaml`
|
||||
- 覆盖层文件:`<overlay_file_path>`(默认 `.pouch/ack/project.md`)
|
||||
|
||||
## 通用规范(由 ACK Skill 按需读取)
|
||||
@@ -39,8 +41,8 @@
|
||||
## Worker 路由
|
||||
|
||||
机器可校验的模型、reasoning effort、权限模式、默认 profile、允许 worktree 和启动
|
||||
receipt 全部以 `.pouch/ack/tasks.yaml` 的 `project.orchestration` 与顶层
|
||||
`workerReceipts` 为准。本文件不保存可执行 worker 命令。
|
||||
receipt 以 `.pouch/ack/agents.yaml`(存在时)或 `.pouch/ack/tasks.yaml` 的
|
||||
`project.orchestration` 与顶层 `workerReceipts` 为准。本文件不保存可执行 worker 命令。
|
||||
|
||||
默认 profile:
|
||||
|
||||
@@ -67,7 +69,8 @@ receipt 全部以 `.pouch/ack/tasks.yaml` 的 `project.orchestration` 与顶层
|
||||
| `<unit_test_paths>` | Read-only | Read-only | R/W | 单元测试 |
|
||||
| `<shared_config_templates>` | Read-only | Read-only | R/W | 可提交配置模板 |
|
||||
| `<local_config_paths>` | Read-only | Read-only | Read-only | 本地私有配置 |
|
||||
| `tasks.yaml` | R/W | Read-only | Read-only | 只有 Coordinator 写 |
|
||||
| `tasks.yaml` | R/W | Read-only | Read-only | 稳定项目配置;任务状态见 `task-records/` |
|
||||
| `task-records/` | R/W | Read-only | Read-only | 只有 Coordinator 追加 |
|
||||
| `knowledge.yaml` | R/W | Read-only | Read-only | 只有 Coordinator 写;Developer/Test 通过回报提名或验证 |
|
||||
| `regression.yaml` | R/W | Read-only | Read-only | 只有 Coordinator 写;Test 通过 regressionCandidates 提名 |
|
||||
| `delivery.yaml` | 仅显式维护时 R/W | Read-only | Read-only | 项目交付能力,不是执行授权 |
|
||||
@@ -116,7 +119,7 @@ Skill 的 `scripts/run_verification.py` 执行,不直接拼接 path/args。检
|
||||
- 复用仅限同轮空闲、身份匹配且历史消息可信清理的 worker;否则重新 plan/launch。
|
||||
- 整轮结束后回收只属于 verified 任务的终端;blocked/failed/leftover 终端保留且不设 TTL。
|
||||
- `worker_done` 与复测报告都不等于完成。必须 Test 独立复测 + Coordinator 终检后才能 `verified`。
|
||||
- 只有 Coordinator 写 `tasks.yaml`、`knowledge.yaml` 和 `regression.yaml`;
|
||||
- 只有 Coordinator 写 `task-records/`、`knowledge.yaml` 和 `regression.yaml`;
|
||||
Developer 与 Test 都只读,通过消息回报。
|
||||
- Coordinator 只派发按 scope 命中并显式写入 `knowledgeRefs` 的 `active` 知识;
|
||||
`candidate` 不派发,知识库不全量注入。
|
||||
|
||||
@@ -115,6 +115,25 @@
|
||||
"statusReference": {
|
||||
"type": "object"
|
||||
},
|
||||
"taskStore": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"version",
|
||||
"directory"
|
||||
],
|
||||
"properties": {
|
||||
"version": {
|
||||
"type": "integer",
|
||||
"const": 1
|
||||
},
|
||||
"directory": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "相对 tasks.yaml 的不可变任务记录目录"
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
},
|
||||
"workerReceipts": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
@@ -591,8 +610,16 @@
|
||||
"minItems": 1,
|
||||
"uniqueItems": true,
|
||||
"items": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:/+@-]{0,127}$"
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:/+@-]{0,127}$"
|
||||
},
|
||||
{
|
||||
"type": "null",
|
||||
"description": "仅 Pi 使用 null 表示其配置的默认模型"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"modelTierAllowlist": {
|
||||
@@ -633,6 +660,12 @@
|
||||
},
|
||||
"grok": {
|
||||
"$ref": "#/definitions/modelRoleAllowlist"
|
||||
},
|
||||
"omp": {
|
||||
"$ref": "#/definitions/modelRoleAllowlist"
|
||||
},
|
||||
"pi": {
|
||||
"$ref": "#/definitions/modelRoleAllowlist"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -647,6 +680,7 @@
|
||||
"permissionMode"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"allOf": [{"if": {"properties": {"permissionMode": {"const": "danger-full-access"}}, "required": ["permissionMode"]}, "then": {"properties": {"cli": {"const": "codex"}}, "required": ["cli"]}}],
|
||||
"properties": {
|
||||
"role": {
|
||||
"type": "string",
|
||||
@@ -661,7 +695,8 @@
|
||||
"codex",
|
||||
"cursor-agent",
|
||||
"grok",
|
||||
"omp"
|
||||
"omp",
|
||||
"pi"
|
||||
]
|
||||
},
|
||||
"tier": {
|
||||
@@ -672,8 +707,16 @@
|
||||
]
|
||||
},
|
||||
"model": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:/+@-]{0,127}$"
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:/+@-]{0,127}$"
|
||||
},
|
||||
{
|
||||
"type": "null",
|
||||
"description": "仅 Pi 使用 null 表示其配置的默认模型"
|
||||
}
|
||||
]
|
||||
},
|
||||
"reasoningEffort": {
|
||||
"type": [
|
||||
@@ -692,7 +735,8 @@
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"read-only",
|
||||
"workspace-write"
|
||||
"workspace-write",
|
||||
"danger-full-access"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -853,6 +897,7 @@
|
||||
"environmentPolicy"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"allOf": [{"if": {"properties": {"permissionMode": {"const": "danger-full-access"}}, "required": ["permissionMode"]}, "then": {"properties": {"cli": {"const": "codex"}}, "required": ["cli"]}}],
|
||||
"properties": {
|
||||
"cli": {
|
||||
"type": "string",
|
||||
@@ -860,7 +905,8 @@
|
||||
"codex",
|
||||
"cursor-agent",
|
||||
"grok",
|
||||
"omp"
|
||||
"omp",
|
||||
"pi"
|
||||
]
|
||||
},
|
||||
"tier": {
|
||||
@@ -871,8 +917,16 @@
|
||||
]
|
||||
},
|
||||
"model": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:/+@-]{0,127}$"
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:/+@-]{0,127}$"
|
||||
},
|
||||
{
|
||||
"type": "null",
|
||||
"description": "仅 Pi 使用 null 表示其配置的默认模型"
|
||||
}
|
||||
]
|
||||
},
|
||||
"reasoningEffort": {
|
||||
"type": [
|
||||
@@ -891,7 +945,8 @@
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"read-only",
|
||||
"workspace-write"
|
||||
"workspace-write",
|
||||
"danger-full-access"
|
||||
]
|
||||
},
|
||||
"executable": {
|
||||
@@ -1018,6 +1073,13 @@
|
||||
"boardHash": {
|
||||
"$ref": "#/definitions/sha256"
|
||||
},
|
||||
"routingSource": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"routingHash": {
|
||||
"$ref": "#/definitions/sha256"
|
||||
},
|
||||
"slot": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
|
||||
@@ -3,6 +3,10 @@ version: 1
|
||||
updatedAt: "<YYYY-MM-DDTHH:mm:ss+TZ>"
|
||||
source: "Coordinator (PM) Agent"
|
||||
ackVersion: "<接入时的 ack skill 版本>"
|
||||
# 任务板只保存项目配置;执行记录追加到 task-records/,避免多个工作区共同改写本文件。
|
||||
taskStore:
|
||||
version: 1
|
||||
directory: "task-records"
|
||||
project:
|
||||
name: "<project_name>"
|
||||
baseUrl: "<base_url>"
|
||||
@@ -29,6 +33,7 @@ project:
|
||||
# attachments: "<field_id>"
|
||||
# updatedAt: "<field_id>"
|
||||
orchestration:
|
||||
# 可选:临时角色路由写到 .pouch/ack/agents.yaml;存在时由 launcher 优先读取。
|
||||
# worker 默认在 --project-root(权威状态目录)工作;不再配置 allowedWorktrees 白名单
|
||||
# (v0.19 起废弃)。需要隔离 worktree 时由 Coordinator 在派发时显式指定。
|
||||
profileVersion: 1
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# agent-runtime
|
||||
|
||||
统一维护项目的 Agent profile、Orca 执行环境、worktree 和跨 session terminal。它让
|
||||
`builder.android`、`builder.ios` 等 binding 成为可配置路由,而不是写死在 skill 代码里的
|
||||
枚举。
|
||||
|
||||
## 什么时候使用
|
||||
|
||||
- 给不同 builder/tester/ACK 绑定不同机器、项目目录、Agent CLI 或模型。
|
||||
- 创建远程 Mac/本地 worktree,并需要后续 session 继续查看构建。
|
||||
- 检查 `.pouch/agent.yaml` 是否能被所有 adapter 安全读取。
|
||||
|
||||
## 使用前准备
|
||||
|
||||
- 项目根已有 `.pouch/agent.yaml`。
|
||||
- 远程 environment 已通过 Orca 配对,且 project/worktree 已存在或被明确创建。
|
||||
- 机器路径、project id/name 和模型信息由使用者确认;配置不包含凭据。
|
||||
|
||||
## 使用示例
|
||||
|
||||
```text
|
||||
把 builder.android 绑定到本地 app,把 builder.ios 绑定到 macmini,创建 iOS worktree,
|
||||
然后让 builder 继续使用同一个 session 构建。
|
||||
```
|
||||
|
||||
## Agent 会做什么
|
||||
|
||||
1. 校验并解析通用配置。
|
||||
2. 按 environment、host、project、绝对 path 精确定位 Orca worktree。
|
||||
3. 按需要创建持久 terminal,并记录可显式恢复的 run receipt。
|
||||
|
||||
不会自动复用旧 terminal、执行配置中的自由 shell、读取 secrets 或上传产物。
|
||||
|
||||
## 如何判断完成
|
||||
|
||||
- `agent.py validate` 通过。
|
||||
- 每个 binding 能唯一解析到目标 worktree,或明确报告需创建/登记的环境。
|
||||
- session 可用 run id 查询、attach 和 stop。
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
name: agent-runtime
|
||||
description: >-
|
||||
维护项目通用 Agent 运行配置、环境绑定、Orca worktree 与跨 session terminal;
|
||||
适用于 builder.android、builder.ios、tester.test、ack.dev 等可扩展绑定。
|
||||
不负责具体构建、测试或 ACK 闭环。
|
||||
---
|
||||
|
||||
# Agent Runtime:统一环境、Agent 与工作区
|
||||
|
||||
本 skill 是 builder、tester、ACK 和 iOS tester 共用的配置层。每个 Git 项目在自己的
|
||||
根目录维护 `.pouch/agent.yaml`;父仓库与 submodule 各自拥有配置,不跨仓库继承。机器
|
||||
专属覆盖放 `.pouch/agent.local.yaml`,运行记录放 `.pouch/agent/runs/`,两者都不提交。
|
||||
|
||||
## 配置模型
|
||||
|
||||
- `locations`:执行环境、Orca project、目标机器上的绝对路径;不放模型和命令。
|
||||
- `profiles`:CLI、模型、reasoning effort、权限和档位;不放路径和 secrets。
|
||||
- `bindings`:任意安全的 `namespace.name`,绑定一个 adapter、location、profile 和
|
||||
adapter 目标。`builder.android`、`builder.ios`、`builder.harmony` 不需要修改代码即可并存。
|
||||
- `adapter` 目前允许 `builder`、`tester`、`ack`。adapter 的具体执行规则仍由对应 skill
|
||||
负责;本层只提供解析、worktree 和 session 生命周期。
|
||||
- `reasoningEffort` 是规范字段;不要新增 `effect`、自由 `command`、`argv`、`shell`、
|
||||
`env` 或 token 字段。
|
||||
|
||||
完整字段、合并和安全规则见 [references/config.md](references/config.md)。需要实际解析或
|
||||
创建工作区时使用 `scripts/agent.py`,不要手工拼接 Orca JSON:
|
||||
|
||||
```bash
|
||||
python3 <skill-dir>/scripts/agent.py validate --root <project-root>
|
||||
python3 <skill-dir>/scripts/agent.py show --root <project-root> --binding builder.android
|
||||
python3 <skill-dir>/scripts/agent.py worktree resolve --root <project-root> --binding builder.ios
|
||||
python3 <skill-dir>/scripts/agent.py worktree create --root <project-root> \
|
||||
--binding builder.ios --name writes-ios --base main
|
||||
```
|
||||
|
||||
## Session
|
||||
|
||||
`builder` 绑定可通过统一入口创建持久 terminal;返回的 run 记录包含 binding、profile
|
||||
hash、环境、worktree、terminal handle 和 source commit。跨 session 只能显式 `status`、
|
||||
`attach`、`stop` 或 `resume`,不能自动复用不明 terminal。tester 的每轮 terminal 仍然
|
||||
是临时的,ACK 仍然必须走其带 fingerprint/receipt 的 launcher。
|
||||
|
||||
```bash
|
||||
python3 <skill-dir>/scripts/agent.py run start --root <project-root> --binding builder.android
|
||||
python3 <skill-dir>/scripts/agent.py run status --root <project-root> --run <run-id>
|
||||
python3 <skill-dir>/scripts/agent.py run attach --root <project-root> --run <run-id>
|
||||
python3 <skill-dir>/scripts/agent.py run resume --root <project-root> --run <run-id>
|
||||
python3 <skill-dir>/scripts/agent.py run stop --root <project-root> --run <run-id>
|
||||
```
|
||||
|
||||
`run start` 只为 builder 生成受控的 make 命令;tester/ACK 的执行入口仍由对应 skill
|
||||
适配器提供。环境、项目或精确 worktree 缺失时 fail closed,并报告需要补的字段。
|
||||
|
||||
## 验证
|
||||
|
||||
- `python3 <skill-dir>/scripts/agent.py validate --root <project-root>` 通过。
|
||||
- remote binding 必须能按 `environment + host + path + project` 精确找到 Orca worktree。
|
||||
- 新 binding 只增加配置和对应 adapter 支持,不复制一套 skill 或修改固定枚举。
|
||||
@@ -0,0 +1,4 @@
|
||||
interface:
|
||||
display_name: "Agent Runtime"
|
||||
short_description: "统一 Agent 环境、worktree、profile 与跨 session 运行配置"
|
||||
default_prompt: "Use $agent-runtime to validate shared agent config, resolve or create a worktree, or inspect a persistent session."
|
||||
@@ -0,0 +1,73 @@
|
||||
# Agent Runtime 配置
|
||||
|
||||
## 文件与合并
|
||||
|
||||
提交 `.pouch/agent.yaml`。若存在 `.pouch/agent.local.yaml`,按 mapping 深度合并;local
|
||||
文件只能覆盖同名字段,不能增加未声明的顶层结构。合并后的配置必须再次完整校验。
|
||||
|
||||
```yaml
|
||||
schemaVersion: 1
|
||||
locations:
|
||||
local-app:
|
||||
environment: local
|
||||
host: local
|
||||
project: git:git.yumee.top/bloggarden/app
|
||||
path: /home/ace/code/draft2/blogger/app
|
||||
remote-ios:
|
||||
environment: macmini
|
||||
host: runtime:14b6d8ce-4528-49f4-8d46-56b266a5ad69
|
||||
project: git:git.yumee.top/bloggarden/app
|
||||
path: /Users/laily/workrepo/bloggarden-app
|
||||
profiles:
|
||||
android-builder:
|
||||
role: build
|
||||
cli: codex
|
||||
tier: standard
|
||||
model: gpt-5
|
||||
reasoningEffort: medium
|
||||
permissionMode: workspace-write
|
||||
ios-builder:
|
||||
role: build
|
||||
cli: codex
|
||||
tier: strong
|
||||
model: gpt-5
|
||||
reasoningEffort: high
|
||||
permissionMode: workspace-write
|
||||
bindings:
|
||||
builder.android:
|
||||
adapter: builder
|
||||
location: local-app
|
||||
profile: android-builder
|
||||
makefile: makefile.builder
|
||||
target: android
|
||||
session:
|
||||
lifecycle: persistent
|
||||
builder.ios:
|
||||
adapter: builder
|
||||
location: remote-ios
|
||||
profile: ios-builder
|
||||
makefile: makefile.builder
|
||||
target: ios
|
||||
session:
|
||||
lifecycle: persistent
|
||||
```
|
||||
|
||||
## 字段原则
|
||||
|
||||
- binding、location、profile ID 只允许小写字母、数字和 `-`,binding 用一个或多个点
|
||||
分隔;ID 是路由名,不是任意 shell 文本。
|
||||
- `environment: local` 使用当前 Orca runtime;远程环境使用已保存的名称。`host` 必须
|
||||
是 `local` 或 `runtime:<environment-id>`,由 Orca 查询结果证明,不能凭主机名猜测。
|
||||
- `project` 必须是 Orca project id 或精确 display name;`path` 必须是目标机器上的绝对
|
||||
路径。解析 worktree 时四者必须同时匹配,标题、分支和 basename 不能消歧。
|
||||
- `profile` 的 CLI 只能来自 ACK/tester 共同 allowlist:`codex`、`cursor-agent`、`grok`、
|
||||
`omp`、`pi`。`model` 为安全模型 ID 或 null;`reasoningEffort` 为 `low|medium|high|xhigh`
|
||||
或 null;权限只允许 `read-only|workspace-write`。
|
||||
- builder 的 `target` 只能是 make target 名;`makefile` 只能是项目内相对文件名。脚本、
|
||||
远端命令、环境变量和凭据由 builder/Orca adapter 提供,不能写入此配置。
|
||||
- `session.lifecycle` 为 `persistent` 或 `ephemeral`。persistent 只表示允许显式跨
|
||||
session attach/resume,不表示自动复用旧 terminal。
|
||||
|
||||
旧版 `.pouch/tester/local.yaml` 和 `.pouch/ack/agents.yaml` 继续兼容。迁移时应让它们
|
||||
由 adapter 从 common profile/location 生成或覆盖,不能删除旧 receipt、fingerprint 或
|
||||
tester 的每轮 terminal 清理语义。
|
||||
Executable
+490
@@ -0,0 +1,490 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate and execute the shared project Agent runtime contract.
|
||||
|
||||
The command surface is deliberately small. It never evaluates project text as
|
||||
shell, and it only creates builder sessions from a fixed make invocation.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
try:
|
||||
import yaml
|
||||
except ImportError as exc: # pragma: no cover - dependency is checked at runtime
|
||||
raise SystemExit("需要 PyYAML: python3 -m pip install pyyaml") from exc
|
||||
|
||||
|
||||
CLI_NAMES = {"codex", "cursor-agent", "grok", "omp", "pi"}
|
||||
ADAPTERS = {"builder", "tester", "ack"}
|
||||
EFFORTS = {None, "low", "medium", "high", "xhigh"}
|
||||
PERMISSIONS = {"read-only", "workspace-write"}
|
||||
TIERS = {"standard", "strong"}
|
||||
LIFECYCLES = {"persistent", "ephemeral"}
|
||||
ID_RE = re.compile(r"^[a-z][a-z0-9-]{1,63}$")
|
||||
BINDING_RE = re.compile(r"^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)+$")
|
||||
TARGET_RE = re.compile(r"^[A-Za-z0-9_.-]{1,96}$")
|
||||
MODEL_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/+@-]{0,127}$")
|
||||
MAKEFILE_RE = re.compile(r"^[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*$")
|
||||
FORBIDDEN_KEYS = {"command", "argv", "shell", "env", "environmentVariables", "token", "secret", "password"}
|
||||
|
||||
|
||||
class ConfigError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class UniqueLoader(yaml.SafeLoader):
|
||||
pass
|
||||
|
||||
|
||||
def _construct_mapping(loader: UniqueLoader, node: yaml.MappingNode, deep: bool = False) -> dict[str, Any]:
|
||||
mapping: dict[str, Any] = {}
|
||||
for key_node, value_node in node.value:
|
||||
key = loader.construct_object(key_node, deep=deep)
|
||||
if not isinstance(key, str):
|
||||
raise ConfigError("YAML mapping key 必须是字符串")
|
||||
if key in mapping:
|
||||
raise ConfigError(f"YAML 存在重复键: {key}")
|
||||
mapping[key] = loader.construct_object(value_node, deep=deep)
|
||||
return mapping
|
||||
|
||||
|
||||
UniqueLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _construct_mapping)
|
||||
|
||||
|
||||
def load_yaml(path: Path) -> dict[str, Any]:
|
||||
try:
|
||||
value = yaml.load(path.read_text(encoding="utf-8"), Loader=UniqueLoader)
|
||||
except (OSError, yaml.YAMLError) as exc:
|
||||
raise ConfigError(f"无法读取 {path}: {exc}") from exc
|
||||
if value is None:
|
||||
return {}
|
||||
if not isinstance(value, dict):
|
||||
raise ConfigError(f"{path} 顶层必须是 mapping")
|
||||
return value
|
||||
|
||||
|
||||
def deep_merge(base: dict[str, Any], override: dict[str, Any], where: str = "root") -> dict[str, Any]:
|
||||
result = copy.deepcopy(base)
|
||||
for key, value in override.items():
|
||||
if key not in result:
|
||||
raise ConfigError(f"{where}: local 配置不能增加未声明字段 {key!r}")
|
||||
if isinstance(result[key], dict) and isinstance(value, dict):
|
||||
result[key] = deep_merge(result[key], value, f"{where}.{key}")
|
||||
else:
|
||||
result[key] = copy.deepcopy(value)
|
||||
return result
|
||||
|
||||
|
||||
def text(value: Any, where: str) -> str:
|
||||
if not isinstance(value, str) or not value.strip() or any(ord(c) < 32 for c in value):
|
||||
raise ConfigError(f"{where}: 必须是非空文本")
|
||||
return value
|
||||
|
||||
|
||||
def safe_id(value: Any, where: str) -> str:
|
||||
value = text(value, where)
|
||||
if not ID_RE.fullmatch(value):
|
||||
raise ConfigError(f"{where}: ID 只能使用小写字母、数字和连字符")
|
||||
return value
|
||||
|
||||
|
||||
def safe_binding_id(value: Any, where: str) -> str:
|
||||
value = text(value, where)
|
||||
if not BINDING_RE.fullmatch(value):
|
||||
raise ConfigError(f"{where}: binding 必须是 namespace.name 形式")
|
||||
return value
|
||||
|
||||
|
||||
def safe_path(value: Any, where: str) -> str:
|
||||
value = text(value, where)
|
||||
path = Path(value)
|
||||
if not path.is_absolute() or value == os.path.sep or ".." in path.parts or os.path.normpath(value) != value:
|
||||
raise ConfigError(f"{where}: 必须是规范绝对路径")
|
||||
return value
|
||||
|
||||
|
||||
def validate(config: dict[str, Any]) -> None:
|
||||
if config.get("schemaVersion") != 1:
|
||||
raise ConfigError("schemaVersion 必须为 1")
|
||||
for key in ("locations", "profiles", "bindings"):
|
||||
if not isinstance(config.get(key), dict) or not config[key]:
|
||||
raise ConfigError(f"{key}: 必须是非空 mapping")
|
||||
locations = config["locations"]
|
||||
for location_id, location in locations.items():
|
||||
safe_id(location_id, f"locations.{location_id}")
|
||||
if not isinstance(location, dict):
|
||||
raise ConfigError(f"locations.{location_id}: 必须是 mapping")
|
||||
for required in ("environment", "project", "path"):
|
||||
if required not in location:
|
||||
raise ConfigError(f"locations.{location_id}: 缺少 {required}")
|
||||
environment = text(location["environment"], f"locations.{location_id}.environment")
|
||||
if environment != "local" and not ID_RE.fullmatch(environment):
|
||||
raise ConfigError(f"locations.{location_id}.environment: 必须是 local 或安全环境名")
|
||||
text(location["project"], f"locations.{location_id}.project")
|
||||
safe_path(location["path"], f"locations.{location_id}.path")
|
||||
host = location.get("host")
|
||||
if host is not None:
|
||||
host = text(host, f"locations.{location_id}.host")
|
||||
if host != "local" and not re.fullmatch(r"runtime:[0-9a-f-]{16,}", host):
|
||||
raise ConfigError(f"locations.{location_id}.host: 必须是 local 或 runtime:<environment-id>")
|
||||
profiles = config["profiles"]
|
||||
for profile_id, profile in profiles.items():
|
||||
safe_id(profile_id, f"profiles.{profile_id}")
|
||||
if not isinstance(profile, dict):
|
||||
raise ConfigError(f"profiles.{profile_id}: 必须是 mapping")
|
||||
for required in ("cli", "model", "reasoningEffort", "permissionMode"):
|
||||
if required not in profile:
|
||||
raise ConfigError(f"profiles.{profile_id}: 缺少 {required}")
|
||||
if profile["cli"] not in CLI_NAMES:
|
||||
raise ConfigError(f"profiles.{profile_id}.cli: 不支持 {profile['cli']!r}")
|
||||
if profile["model"] is not None and MODEL_RE.fullmatch(str(profile["model"])) is None:
|
||||
raise ConfigError(f"profiles.{profile_id}.model: 不是安全模型 ID")
|
||||
if profile["reasoningEffort"] not in EFFORTS:
|
||||
raise ConfigError(f"profiles.{profile_id}.reasoningEffort: 不支持该值")
|
||||
if profile["permissionMode"] not in PERMISSIONS:
|
||||
raise ConfigError(f"profiles.{profile_id}.permissionMode: 不支持该值")
|
||||
if profile.get("tier", "standard") not in TIERS:
|
||||
raise ConfigError(f"profiles.{profile_id}.tier: 必须是 standard/strong")
|
||||
for binding_id, binding in config["bindings"].items():
|
||||
safe_binding_id(binding_id, f"bindings.{binding_id}")
|
||||
if not isinstance(binding, dict):
|
||||
raise ConfigError(f"bindings.{binding_id}: 必须是 mapping")
|
||||
for required in ("adapter", "location", "profile"):
|
||||
if required not in binding:
|
||||
raise ConfigError(f"bindings.{binding_id}: 缺少 {required}")
|
||||
if binding["adapter"] not in ADAPTERS:
|
||||
raise ConfigError(f"bindings.{binding_id}.adapter: 不支持 {binding['adapter']!r}")
|
||||
location_id = safe_id(binding["location"], f"bindings.{binding_id}.location")
|
||||
profile_id = safe_id(binding["profile"], f"bindings.{binding_id}.profile")
|
||||
if location_id not in locations or profile_id not in profiles:
|
||||
raise ConfigError(f"bindings.{binding_id}: location/profile 引用不存在")
|
||||
if binding["adapter"] == "builder":
|
||||
makefile = text(binding.get("makefile", "makefile.builder"), f"bindings.{binding_id}.makefile")
|
||||
if Path(makefile).is_absolute() or ".." in Path(makefile).parts or MAKEFILE_RE.fullmatch(makefile) is None:
|
||||
raise ConfigError(f"bindings.{binding_id}.makefile: 必须是项目内相对路径")
|
||||
target = text(binding.get("target"), f"bindings.{binding_id}.target")
|
||||
if TARGET_RE.fullmatch(target) is None:
|
||||
raise ConfigError(f"bindings.{binding_id}.target: 不是安全 make target")
|
||||
session = binding.get("session", {})
|
||||
if not isinstance(session, dict) or session.get("lifecycle", "ephemeral") not in LIFECYCLES:
|
||||
raise ConfigError(f"bindings.{binding_id}.session.lifecycle: 必须是 persistent/ephemeral")
|
||||
scan_forbidden(config)
|
||||
|
||||
|
||||
def scan_forbidden(value: Any, where: str = "root") -> None:
|
||||
if isinstance(value, dict):
|
||||
for key, child in value.items():
|
||||
if key in FORBIDDEN_KEYS:
|
||||
raise ConfigError(f"{where}: 禁止配置字段 {key!r}")
|
||||
scan_forbidden(child, f"{where}.{key}")
|
||||
elif isinstance(value, list):
|
||||
for index, child in enumerate(value):
|
||||
scan_forbidden(child, f"{where}[{index}]")
|
||||
|
||||
|
||||
def load_config(root: Path) -> dict[str, Any]:
|
||||
path = root / ".pouch" / "agent.yaml"
|
||||
if not path.is_file():
|
||||
raise ConfigError(f"缺少 {path},请先创建项目通用 Agent 配置")
|
||||
config = load_yaml(path)
|
||||
local_path = root / ".pouch" / "agent.local.yaml"
|
||||
if local_path.is_file():
|
||||
config = deep_merge(config, load_yaml(local_path))
|
||||
validate(config)
|
||||
return config
|
||||
|
||||
|
||||
def binding(config: dict[str, Any], binding_id: str) -> dict[str, Any]:
|
||||
if binding_id not in config["bindings"]:
|
||||
raise ConfigError(f"不存在 binding: {binding_id}")
|
||||
value = copy.deepcopy(config["bindings"][binding_id])
|
||||
value["id"] = binding_id
|
||||
value["locationId"] = value["location"]
|
||||
value["location"] = copy.deepcopy(config["locations"][value["locationId"]])
|
||||
value["profileId"] = value["profile"]
|
||||
value["profile"] = copy.deepcopy(config["profiles"][value["profileId"]])
|
||||
return value
|
||||
|
||||
|
||||
def orca_json(args: list[str], environment: str | None = None) -> dict[str, Any]:
|
||||
command = ["orca", *args]
|
||||
if environment and environment != "local":
|
||||
command.extend(["--environment", environment])
|
||||
command.append("--json")
|
||||
proc = subprocess.run(command, capture_output=True, text=True, check=False)
|
||||
raw = (proc.stdout or "").strip()
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
detail = (proc.stderr or raw or str(exc)).strip()
|
||||
raise ConfigError(f"Orca 没有返回 JSON: {' '.join(command)}\n{detail}") from exc
|
||||
if not data.get("ok"):
|
||||
error = data.get("error") or {}
|
||||
raise ConfigError(f"{' '.join(command)}: {error.get('message') or error.get('code') or 'unknown error'}")
|
||||
result = data.get("result")
|
||||
return result if isinstance(result, dict) else {}
|
||||
|
||||
|
||||
def environment_id(name: str) -> str:
|
||||
if name == "local":
|
||||
return "local"
|
||||
result = orca_json(["environment", "list"])
|
||||
for item in result.get("environments", []):
|
||||
if isinstance(item, dict) and item.get("name") == name:
|
||||
return str(item.get("id"))
|
||||
raise ConfigError(f"找不到已保存 Orca environment: {name}")
|
||||
|
||||
|
||||
def location_host(location: dict[str, Any]) -> str:
|
||||
host = location.get("host")
|
||||
if host:
|
||||
return str(host)
|
||||
if location["environment"] == "local":
|
||||
return "local"
|
||||
return f"runtime:{environment_id(str(location['environment']))}"
|
||||
|
||||
|
||||
def worktree_for(binding_value: dict[str, Any]) -> dict[str, Any]:
|
||||
location = binding_value["location"]
|
||||
environment = str(location["environment"])
|
||||
project_ids = {str(location["project"])}
|
||||
projects = orca_json(["project", "list"], environment).get("projects", [])
|
||||
for project in projects:
|
||||
if not isinstance(project, dict):
|
||||
continue
|
||||
if str(project.get("id")) == str(location["project"]) or str(project.get("displayName")) == str(location["project"]):
|
||||
project_ids.update(str(repo_id) for repo_id in project.get("sourceRepoIds", []) if repo_id)
|
||||
result = orca_json(["worktree", "list"], environment)
|
||||
candidates = []
|
||||
for item in result.get("worktrees", []):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
item_project_ids = {str(item.get("projectId")), str(item.get("repoId"))}
|
||||
if not project_ids.intersection(item_project_ids):
|
||||
continue
|
||||
if str(item.get("path")) != str(location["path"]):
|
||||
continue
|
||||
expected_host = location_host(location)
|
||||
# A routed remote runtime stamps its own worktrees with hostId=local;
|
||||
# the environment name/ID is the remote-machine discriminator.
|
||||
if location["environment"] == "local" and expected_host == "local" and str(item.get("hostId")) != "local":
|
||||
continue
|
||||
candidates.append(item)
|
||||
if len(candidates) != 1:
|
||||
if not candidates:
|
||||
raise ConfigError(
|
||||
f"找不到精确 worktree: environment={environment}, host={location_host(location)}, "
|
||||
f"project={location['project']}, path={location['path']};先创建或登记该 worktree"
|
||||
)
|
||||
raise ConfigError(f"binding 匹配到多个 worktree: {len(candidates)}")
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def project_root_commit(root: Path) -> str | None:
|
||||
proc = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True, check=False)
|
||||
return proc.stdout.strip() if proc.returncode == 0 else None
|
||||
|
||||
|
||||
def run_dir(root: Path) -> Path:
|
||||
path = root / ".pouch" / "agent" / "runs"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def run_path(root: Path, run_id: str) -> Path:
|
||||
if not re.fullmatch(r"run_[0-9a-f]{16,64}", run_id):
|
||||
raise ConfigError("run id 格式无效")
|
||||
return run_dir(root) / f"{run_id}.json"
|
||||
|
||||
|
||||
def cmd_validate(args: argparse.Namespace) -> int:
|
||||
config = load_config(Path(args.root).resolve())
|
||||
print(json.dumps({"ok": True, "schemaVersion": config["schemaVersion"], "bindings": sorted(config["bindings"])}, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_show(args: argparse.Namespace) -> int:
|
||||
config = load_config(Path(args.root).resolve())
|
||||
value = binding(config, args.binding)
|
||||
print(json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_worktree_resolve(args: argparse.Namespace) -> int:
|
||||
root = Path(args.root).resolve()
|
||||
value = binding(load_config(root), args.binding)
|
||||
worktree = worktree_for(value)
|
||||
print(json.dumps({"binding": args.binding, "worktree": worktree}, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_worktree_create(args: argparse.Namespace) -> int:
|
||||
root = Path(args.root).resolve()
|
||||
value = binding(load_config(root), args.binding)
|
||||
location = value["location"]
|
||||
try:
|
||||
existing = worktree_for(value)
|
||||
except ConfigError as exc:
|
||||
if "找不到精确 worktree" not in str(exc):
|
||||
raise
|
||||
existing = None
|
||||
if existing:
|
||||
print(json.dumps({"created": False, "binding": args.binding, "worktree": existing}, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
host = location_host(location)
|
||||
command = ["worktree", "create", "--project", str(location["project"]), "--host", host, "--name", args.name, "--no-parent"]
|
||||
if args.base:
|
||||
command.extend(["--base-branch", args.base])
|
||||
result = orca_json(command, str(location["environment"]))
|
||||
print(json.dumps({"created": True, "binding": args.binding, "result": result, "next": "将返回 worktree 的 path 写回 location.path 后再运行 resolve"}, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def make_command(value: dict[str, Any]) -> str:
|
||||
# Replace the shell so terminal wait observes the make exit code instead
|
||||
# of waiting forever on the interactive shell after make returns.
|
||||
return f"exec make -f {value.get('makefile', 'makefile.builder')} {value['target']}"
|
||||
|
||||
|
||||
def cmd_run_start(args: argparse.Namespace) -> int:
|
||||
root = Path(args.root).resolve()
|
||||
value = binding(load_config(root), args.binding)
|
||||
if value["adapter"] != "builder":
|
||||
raise ConfigError(f"run start 目前只为 builder 提供受控 make session;{value['adapter']} 请走对应 skill adapter")
|
||||
if value.get("session", {}).get("lifecycle", "ephemeral") != "persistent":
|
||||
raise ConfigError(f"binding {args.binding} 不是 persistent session")
|
||||
worktree = worktree_for(value)
|
||||
environment = str(value["location"]["environment"])
|
||||
result = orca_json(["terminal", "create", "--worktree", f"id:{worktree['id']}", "--command", make_command(value), "--title", args.binding], environment)
|
||||
terminal = result.get("terminal") or result
|
||||
handle = terminal.get("handle") or result.get("handle")
|
||||
if not handle:
|
||||
raise ConfigError("Orca terminal create 没有返回 handle")
|
||||
run_id = "run_" + uuid.uuid4().hex
|
||||
record = {
|
||||
"schemaVersion": 1,
|
||||
"id": run_id,
|
||||
"binding": args.binding,
|
||||
"adapter": value["adapter"],
|
||||
"profileId": value["profileId"],
|
||||
"profileHash": hashlib.sha256(json.dumps(value["profile"], sort_keys=True).encode()).hexdigest(),
|
||||
"environment": environment,
|
||||
"project": value["location"]["project"],
|
||||
"path": value["location"]["path"],
|
||||
"worktreeId": worktree["id"],
|
||||
"terminalHandle": handle,
|
||||
"command": make_command(value),
|
||||
"sourceCommit": project_root_commit(root),
|
||||
"createdAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"status": "started",
|
||||
}
|
||||
run_path(root, run_id).write_text(json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps(record, ensure_ascii=False, indent=2))
|
||||
if args.wait_ms:
|
||||
wait = orca_json(["terminal", "wait", "--terminal", handle, "--for", "exit", "--timeout-ms", str(args.wait_ms)], environment)
|
||||
record["wait"] = wait
|
||||
record["status"] = "completed" if wait.get("exited") or wait.get("status") == "exited" else "waited"
|
||||
run_path(root, run_id).write_text(json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps(wait, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def load_run(root: Path, run_id: str) -> dict[str, Any]:
|
||||
path = run_path(root, run_id)
|
||||
if not path.is_file():
|
||||
raise ConfigError(f"找不到 run 记录: {run_id}")
|
||||
value = json.loads(path.read_text(encoding="utf-8"))
|
||||
if not isinstance(value, dict):
|
||||
raise ConfigError(f"run 记录无效: {run_id}")
|
||||
return value
|
||||
|
||||
|
||||
def cmd_run_status(args: argparse.Namespace) -> int:
|
||||
root = Path(args.root).resolve()
|
||||
record = load_run(root, args.run)
|
||||
result = orca_json(["terminal", "show", "--terminal", record["terminalHandle"]], record.get("environment"))
|
||||
print(json.dumps({"run": record, "terminal": result}, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_run_attach(args: argparse.Namespace) -> int:
|
||||
root = Path(args.root).resolve()
|
||||
record = load_run(root, args.run)
|
||||
result = orca_json(["terminal", "read", "--terminal", record["terminalHandle"]], record.get("environment"))
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_run_resume(args: argparse.Namespace) -> int:
|
||||
"""Explicitly reattach to a recorded terminal; never search for another one."""
|
||||
|
||||
root = Path(args.root).resolve()
|
||||
record = load_run(root, args.run)
|
||||
result = orca_json(["terminal", "show", "--terminal", record["terminalHandle"]], record.get("environment"))
|
||||
print(json.dumps({"resumed": True, "run": record, "terminal": result}, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_run_stop(args: argparse.Namespace) -> int:
|
||||
root = Path(args.root).resolve()
|
||||
record = load_run(root, args.run)
|
||||
result = orca_json(["terminal", "close", "--terminal", record["terminalHandle"]], record.get("environment"))
|
||||
record["status"] = "stopped"
|
||||
record["stoppedAt"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
run_path(root, args.run).write_text(json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps({"run": record, "close": result}, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def parser() -> argparse.ArgumentParser:
|
||||
root_parent = argparse.ArgumentParser(add_help=False)
|
||||
root_parent.add_argument("--root", default=".")
|
||||
parser = argparse.ArgumentParser(description="共享 Agent 配置、worktree 和 session 运行时")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
validate_parser = sub.add_parser("validate", parents=[root_parent])
|
||||
validate_parser.set_defaults(func=cmd_validate)
|
||||
show = sub.add_parser("show", parents=[root_parent])
|
||||
show.add_argument("--binding", required=True)
|
||||
show.set_defaults(func=cmd_show)
|
||||
wt = sub.add_parser("worktree")
|
||||
wt_sub = wt.add_subparsers(dest="worktree_command", required=True)
|
||||
resolve = wt_sub.add_parser("resolve", parents=[root_parent])
|
||||
resolve.add_argument("--binding", required=True)
|
||||
resolve.set_defaults(func=cmd_worktree_resolve)
|
||||
create = wt_sub.add_parser("create", parents=[root_parent])
|
||||
create.add_argument("--binding", required=True)
|
||||
create.add_argument("--name", required=True)
|
||||
create.add_argument("--base", default="")
|
||||
create.set_defaults(func=cmd_worktree_create)
|
||||
run = sub.add_parser("run")
|
||||
run_sub = run.add_subparsers(dest="run_command", required=True)
|
||||
start = run_sub.add_parser("start", parents=[root_parent])
|
||||
start.add_argument("--binding", required=True)
|
||||
start.add_argument("--wait-ms", type=int, default=0)
|
||||
start.set_defaults(func=cmd_run_start)
|
||||
for name, func in (("status", cmd_run_status), ("attach", cmd_run_attach), ("resume", cmd_run_resume), ("stop", cmd_run_stop)):
|
||||
item = run_sub.add_parser(name, parents=[root_parent])
|
||||
item.add_argument("--run", required=True)
|
||||
item.set_defaults(func=func)
|
||||
return parser
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
parsed = parser().parse_args()
|
||||
raise SystemExit(parsed.func(parsed))
|
||||
except ConfigError as exc:
|
||||
print(f"environment-fail: {exc}", file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
@@ -0,0 +1,51 @@
|
||||
# android-tester
|
||||
|
||||
在 Android 真机或 Debian Linux Android 模拟器上执行测试;每次先检查环境,最后生成可追溯的测试结果。
|
||||
|
||||
## 什么时候使用
|
||||
|
||||
- 「检查 Android 真机测试环境」
|
||||
- 「检查 Debian Android 模拟器环境」
|
||||
- 「用真机跑 Android smoke」
|
||||
- 「用 AVD 跑 Android full」
|
||||
- 「安装 Debian 上的 Android 模拟器」
|
||||
- 「查看本次 Android 测试结果」
|
||||
|
||||
## 使用前准备
|
||||
|
||||
- 项目已有 `.pouch/tester/` 和测试用例。
|
||||
- 真机:开启 USB 调试并在设备上授权当前电脑。
|
||||
- 模拟器:准备支持虚拟化的 Debian amd64 主机;首次使用可让 skill 安装 KVM、SDK
|
||||
Command-line Tools、Platform-Tools、Emulator 和指定系统镜像。
|
||||
- 需要安装或启动应用时,提供 APK、包名和启动组件,或提供项目自己的测试命令。
|
||||
- 安装模式会使用 sudo、apt 和用户组变更;运行前会先展示变更范围。
|
||||
|
||||
## 使用示例
|
||||
|
||||
```text
|
||||
检查 Android 真机环境,然后跑 smoke 测试
|
||||
```
|
||||
|
||||
```text
|
||||
在 Debian 上安装 Android 模拟器,使用项目需要的 Android API 创建 AVD
|
||||
```
|
||||
|
||||
```text
|
||||
用 Pixel_API_35 模拟器跑 Android full,失败时保留 logcat 和截图
|
||||
```
|
||||
|
||||
## Agent 会做什么
|
||||
|
||||
1. 明确选择真机或模拟器,不在两者之间自动切换。
|
||||
2. 先检查 ADB、KVM、AVD、设备授权、启动状态和项目测试配置。
|
||||
3. 模拟器路径可在 Debian amd64 上安装主机依赖和 Android SDK 模拟器组件。
|
||||
4. 执行 `.pouch/tester/` 中命中的 Android 用例。
|
||||
5. 生成 YAML 运行快照、CSV 成绩单,失败时附带 logcat 和截图。
|
||||
|
||||
安装、安装 APK、清数据和修改设备设置都属于有副作用的操作,必须得到明确授权。
|
||||
|
||||
## 如何判断完成
|
||||
|
||||
- 环境检查有明确的通过项和阻塞项。
|
||||
- 每条用例都有 `pass`、`fail`、`environment-fail`、`skipped` 或 `not-run` 结果。
|
||||
- 运行记录位于 `.pouch/tester/runs/`,且 YAML 与 CSV 的 run id 一致。
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
name: android-tester
|
||||
description: >-
|
||||
检查并运行 Android 真机或模拟器测试;支持 Debian amd64 上安装
|
||||
Android Emulator、KVM 依赖、SDK 工具和 AVD。触发词:Android 测试、安卓测试、
|
||||
真机测试、Android 模拟器、AVD、ADB、安装安卓模拟器、检查 Android 环境。
|
||||
---
|
||||
|
||||
# Android Tester
|
||||
|
||||
项目根是 `git rev-parse --show-toplevel`。本 skill 复用项目已有的
|
||||
`.pouch/tester/` 用例和运行记录,不创建第二套测试目录。
|
||||
|
||||
## 模式路由
|
||||
|
||||
- 用户要求安装或配置 Android 模拟器:先读 `references/install-debian.md`。
|
||||
- 用户要求检查环境:先读 `references/environment.md`,再按目标读 `device.md` 或
|
||||
`emulator.md`。
|
||||
- 用户要求用真机测试:目标固定为 `device`,读 `device.md`。
|
||||
- 用户要求用模拟器测试:目标固定为 `emulator`,读 `emulator.md`。
|
||||
- 用户要求报告结果或复盘失败:读 `references/reporting.md`。
|
||||
|
||||
## 全局硬规则
|
||||
|
||||
- 每次运行测试前必须重新检查环境;检查失败记为 `environment-fail`,不伪装成产品失败。
|
||||
- 真机与模拟器必须由用户明确选择,禁止自动 fallback。
|
||||
- 运行范围和结果语义遵循 `tester`:默认 smoke、默认 readonly,使用
|
||||
`pass/fail/environment-fail/skipped/not-run`。
|
||||
- 不自动构建 APK;只使用项目提供的测试命令或已有 APK。
|
||||
- 安装 APK、清除数据、授予权限、修改设备设置属于 mutating,必须有明确授权。
|
||||
- 不自动清空真机、重启真机、创建或删除未知 AVD。
|
||||
- Debian 安装模式只接受 `ID=debian` 且 `amd64/x86_64`;Ubuntu、其他发行版、ARM
|
||||
主机必须停止并说明不在第一版范围内。
|
||||
- 没有 `.pouch/tester/catalog.yaml` 时,不静默初始化,提示用户先初始化 `tester`。
|
||||
|
||||
## 运行顺序
|
||||
|
||||
1. 解析测试范围和目标模式。
|
||||
2. 检查 `.pouch/tester/`、本地配置和工具链。
|
||||
3. 检查真机或模拟器目标是否可用。
|
||||
4. 必要时只启动本轮自己创建的模拟器会话。
|
||||
5. 按 tester 用例顺序执行测试。
|
||||
6. 失败时采集 logcat 和截图,生成 YAML/CSV 运行记录。
|
||||
7. 按 `references/reporting.md` 输出结果,并执行目标会话的安全收尾。
|
||||
|
||||
## 安装安全边界
|
||||
|
||||
安装模式会运行 `apt`、修改用户组、下载 Android SDK 文件并可能创建 AVD。只有用户
|
||||
明确要求安装时才执行;执行前先列出包、下载目录、SDK 镜像和需要重新登录的事项。
|
||||
不要把 sudo 密码、账号或第三方 token 写入文件或输出。
|
||||
|
||||
## 验证
|
||||
|
||||
- `pouch check android-tester` 通过。
|
||||
- Debian 安装后 `kvm-ok` 和 `emulator -accel-check` 通过。
|
||||
- 真机和模拟器各完成一条 readonly smoke 用例,并分别生成运行快照和成绩单。
|
||||
@@ -0,0 +1,34 @@
|
||||
# Android 真机路径
|
||||
|
||||
## 环境检查
|
||||
|
||||
按顺序执行并记录:
|
||||
|
||||
```bash
|
||||
adb start-server
|
||||
adb devices -l
|
||||
adb -s <serial> shell getprop ro.product.model
|
||||
adb -s <serial> shell getprop ro.build.version.sdk
|
||||
adb -s <serial> shell getprop sys.boot_completed
|
||||
```
|
||||
|
||||
规则:
|
||||
|
||||
- 没有设备:`environment-fail`。
|
||||
- `unauthorized`:提示用户在手机上授权,不自动绕过。
|
||||
- `offline`:停止,不把它当作产品失败。
|
||||
- 有多台设备但没有 `ANDROID_SERIAL`:停止,不猜设备。
|
||||
- `sys.boot_completed` 不是 `1`:等待有限时间,超时记 `environment-fail`。
|
||||
|
||||
## 执行
|
||||
|
||||
- 复用用户指定序列号,整轮测试不切换设备。
|
||||
- 只执行选中的 `driver: mobile` 用例。
|
||||
- 不自动安装 APK;安装必须有 APK、包名和明确的 mutating 授权。
|
||||
- 测试失败时收集目标设备的 logcat 尾部和当前屏幕截图。
|
||||
|
||||
## 收尾
|
||||
|
||||
- 不关机、不重启、不清除应用数据。
|
||||
- 停止由本轮启动的 ADB server 之前要确认没有其他测试会话依赖它。
|
||||
- 设备保留原状态,并在结果中记录。
|
||||
@@ -0,0 +1,33 @@
|
||||
# Android 模拟器路径
|
||||
|
||||
## 环境检查
|
||||
|
||||
执行:
|
||||
|
||||
```bash
|
||||
emulator -accel-check
|
||||
emulator -list-avds
|
||||
```
|
||||
|
||||
必须同时满足:
|
||||
|
||||
- KVM 可用。
|
||||
- 指定 AVD 存在。
|
||||
- AVD 的 system image 与 x86_64 主机匹配。
|
||||
- 没有被 VirtualBox、VMware 或 Docker 等外层虚拟化阻断。
|
||||
|
||||
## 启动与等待
|
||||
|
||||
- 如果目标 AVD 已运行,检查序列号和 AVD 名称后复用。
|
||||
- 如果没有运行,启动用户指定的 AVD,不创建替代 AVD。
|
||||
- 使用 ADB 等待设备出现,并等待 `sys.boot_completed=1`。
|
||||
- 启动失败、启动超时或 KVM 失效都记为 `environment-fail`。
|
||||
- 无桌面服务器时可使用 `-no-window -no-audio`,但必须先确认测试不需要可视化交互。
|
||||
|
||||
## 执行与收尾
|
||||
|
||||
- 一轮测试只绑定一个 AVD。
|
||||
- 需要安装 APK 或清数据时按 mutating 规则处理。
|
||||
- 测试失败时保存 logcat、模拟器信息和截图。
|
||||
- 只关闭本轮由 skill 启动且配置为临时会话的模拟器。
|
||||
- 不删除 AVD、不修改系统镜像、不覆盖用户已有配置。
|
||||
@@ -0,0 +1,45 @@
|
||||
# Android 通用环境检查
|
||||
|
||||
本文件只读检查,不安装软件、不修改设备。
|
||||
|
||||
## 项目检查
|
||||
|
||||
1. 确认项目根目录。
|
||||
2. 确认 `.pouch/tester/catalog.yaml` 存在且 `validate` 通过。
|
||||
3. 只选择 `driver: mobile` 的用例。
|
||||
4. 读取 `.pouch/tester/local.yaml`;缺少 Android 目标配置时停止,不猜目标。
|
||||
|
||||
推荐的本地配置字段:
|
||||
|
||||
```yaml
|
||||
ANDROID_TARGET_MODE: device
|
||||
ANDROID_SERIAL: ""
|
||||
ANDROID_AVD: ""
|
||||
ANDROID_PACKAGE: ""
|
||||
ANDROID_APK: ""
|
||||
ANDROID_ACTIVITY: ""
|
||||
```
|
||||
|
||||
## 主机检查
|
||||
|
||||
- `uname -m` 必须是 `x86_64`。
|
||||
- `adb` 必须可执行。
|
||||
- 模拟器路径还必须有 `emulator`、`sdkmanager` 和 KVM。
|
||||
- 记录 Android SDK 根目录、工具版本和当前用户。
|
||||
|
||||
未安装工具属于 `environment-fail`。不要在普通测试运行中顺手安装;安装只能进入
|
||||
明确的 Debian 安装模式。
|
||||
|
||||
## 运行前报告
|
||||
|
||||
先报告:
|
||||
|
||||
```text
|
||||
目标: 真机 | 模拟器
|
||||
项目测试目录: 已找到 | 缺失
|
||||
ADB: 通过 | 缺失
|
||||
模拟器工具链: 通过 | 缺失 | 不适用
|
||||
KVM: 通过 | 缺失 | 不适用
|
||||
目标设备: 已解析 | 未解析
|
||||
结论: 可执行 | environment-fail
|
||||
```
|
||||
@@ -0,0 +1,95 @@
|
||||
# Debian 安装 Android 模拟器
|
||||
|
||||
只支持 Debian amd64/x86_64。不要在 Ubuntu、其他发行版、ARM 主机或嵌套虚拟机中执行
|
||||
本流程。Android 官方 Linux 模拟器依赖 KVM;Android SDK Command-line Tools 提供
|
||||
`sdkmanager`,Emulator 和 Platform-Tools 作为 SDK 包安装。
|
||||
|
||||
## 1. 检查并确认变更
|
||||
|
||||
读取 `/etc/os-release`,必须满足:
|
||||
|
||||
```bash
|
||||
test "$(. /etc/os-release && printf '%s' "$ID")" = debian
|
||||
test "$(dpkg --print-architecture)" = amd64
|
||||
```
|
||||
|
||||
安装前向用户展示:
|
||||
|
||||
- 将通过 apt 安装的 Debian 包。
|
||||
- Android SDK 目录,默认 `~/Android/Sdk`。
|
||||
- 要下载的 Emulator、Platform-Tools、Command-line Tools 和 system image。
|
||||
- 会把当前用户加入 `kvm`、`libvirt` 组,通常需要重新登录。
|
||||
- 是否创建 AVD,以及 AVD 名称、API、镜像和设备 profile。
|
||||
|
||||
没有明确安装请求或用户未确认这些变更时,只输出检查结果,不执行 sudo、apt 或下载。
|
||||
|
||||
## 2. 安装 Debian 主机依赖
|
||||
|
||||
在用户确认后安装:
|
||||
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install cpu-checker qemu-kvm libvirt-daemon-system \
|
||||
libvirt-clients bridge-utils curl ca-certificates unzip
|
||||
sudo usermod -aG kvm,libvirt "$USER"
|
||||
```
|
||||
|
||||
检查:
|
||||
|
||||
```bash
|
||||
kvm-ok
|
||||
ls -l /dev/kvm
|
||||
```
|
||||
|
||||
若没有硬件虚拟化或 `/dev/kvm`,停止并报告安装失败。不要降级为极慢的软件模拟。
|
||||
|
||||
## 3. 安装 Android SDK 工具
|
||||
|
||||
优先使用 Android 官方 Linux Command-line Tools。若机器已有 `sdkmanager`,复用现有
|
||||
SDK 根目录;否则从 Android 官方下载页获取 Linux Command-line Tools,解压为:
|
||||
|
||||
```text
|
||||
~/Android/Sdk/cmdline-tools/latest/
|
||||
```
|
||||
|
||||
安装并接受 SDK 许可后,执行:
|
||||
|
||||
```bash
|
||||
sdkmanager --install \
|
||||
"platform-tools" \
|
||||
"emulator" \
|
||||
"cmdline-tools;latest"
|
||||
```
|
||||
|
||||
系统镜像由项目的 compile/target SDK 和用户明确选择的 API 决定。安装前先用
|
||||
`sdkmanager --list` 查找可用的 `google_apis;x86_64` 镜像,不猜一个不可用的版本。
|
||||
|
||||
## 4. 创建 AVD
|
||||
|
||||
只有用户明确要求创建 AVD 时执行。优先使用当前 SDK 提供的 Android CLI;兼容环境可
|
||||
使用 `avdmanager` 创建一个明确命名、明确 API 和明确 x86_64 镜像的 AVD。创建后运行:
|
||||
|
||||
```bash
|
||||
emulator -list-avds
|
||||
emulator -accel-check
|
||||
emulator @<已确认的AVD名称>
|
||||
```
|
||||
|
||||
`<已确认的AVD名称>` 只表示用户已经选择的实际名称,不允许由 skill 静默猜测。
|
||||
|
||||
## 5. 安装完成报告
|
||||
|
||||
报告必须包含:
|
||||
|
||||
- Debian 版本和架构。
|
||||
- apt 安装包及结果。
|
||||
- SDK 根目录和工具版本。
|
||||
- 已安装的 system image。
|
||||
- AVD 名称和配置。
|
||||
- KVM 检查结果。
|
||||
- 是否需要重新登录。
|
||||
- 下一步是运行模拟器检查,还是直接执行测试。
|
||||
|
||||
安装 Android Studio 不是本模式的必要条件;该流程安装的是可由命令行运行的 Emulator
|
||||
工具链。参考:[Android 安装文档](https://developer.android.com/studio/install)、
|
||||
[KVM 加速文档](https://developer.android.com/studio/run/emulator-acceleration)。
|
||||
@@ -0,0 +1,29 @@
|
||||
# Android 结果报告
|
||||
|
||||
每轮运行都生成 `.pouch/tester/runs/<run-id>.yaml` 和同名 `.csv`。附加证据放在同名
|
||||
目录中,不覆盖已有 run。
|
||||
|
||||
对话报告格式:
|
||||
|
||||
```text
|
||||
## android-tester 运行:完成 | 部分完成 | 阻塞
|
||||
|
||||
路径: 真机 | 模拟器
|
||||
目标: 序列号/型号/API 或 AVD/API
|
||||
环境: 通过项;阻塞项
|
||||
计数: pass=N fail=N environment-fail=N skipped=N not-run=N
|
||||
失败: 用例 id + 一句证据
|
||||
跳过: 用例 id + 原因
|
||||
证据: logcat / 截图目录
|
||||
快照: .pouch/tester/runs/<run-id>.yaml
|
||||
成绩单: .pouch/tester/runs/<run-id>.csv
|
||||
下一步: 一句话
|
||||
```
|
||||
|
||||
判定规则:
|
||||
|
||||
- 工具缺失、设备不可用、启动超时:`environment-fail`。
|
||||
- 产品断言不满足:`fail`。
|
||||
- 风险未授权、用例主动不跑:`skipped`。
|
||||
- 失败即停后没有轮到的用例:`not-run`。
|
||||
- 不能把 ADB 命令退出码为 0 直接当成产品通过,必须对照用例的 `expected`。
|
||||
@@ -0,0 +1,24 @@
|
||||
# bugfix-ship(已弃用)
|
||||
|
||||
`bugfix-ship` 已改名为 [short-ship](../short-ship/README.md)。本目录只是兼容占位,
|
||||
让旧项目里的 `.pouch.yaml`、已经装好的旧软链和旧说法不至于失效;真正的说明和流程都在
|
||||
`short-ship/`。
|
||||
|
||||
## 使用示例
|
||||
|
||||
```text
|
||||
使用 bugfix-ship,修复这个线上回归并部署到测试环境。
|
||||
```
|
||||
|
||||
Agent 命中后会立刻转到 `short-ship`,按同一套规则执行。新请求建议直接用新名。
|
||||
|
||||
## 迁移
|
||||
|
||||
```bash
|
||||
pouch add short-ship # 新名,当前项目
|
||||
pouch add short-ship -g # 新名,全局
|
||||
```
|
||||
|
||||
- 旧软链保持有效,不需要先删除。
|
||||
- 各项目 `.pouch.yaml` 里的 `bugfix-ship` 可以分批改成 `short-ship`。
|
||||
- 确认没有项目再按旧名启用后,删除本目录即可;它是纯占位,删除不丢内容。
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
name: bugfix-ship
|
||||
description: >-
|
||||
【已弃用,兼容占位】bugfix-ship 已改名为 short-ship。命中本 skill 时不要在此执行任何
|
||||
流程,直接读取 ../short-ship/SKILL.md 并按其执行。小需求、小改动、修 bug、改文案、
|
||||
加按钮、修复后发 PR 或部署都属于 short-ship。
|
||||
---
|
||||
|
||||
# bugfix-ship(已弃用)
|
||||
|
||||
本 skill 已改名为 [short-ship](../short-ship/SKILL.md)。这里只是兼容占位,**没有流程内容**。
|
||||
|
||||
- 用户提到 `bugfix-ship`、`/bugfix-ship` 或 `$bugfix-ship` 时:读取
|
||||
[../short-ship/SKILL.md](../short-ship/SKILL.md),按其内容与授权边界执行,不要在本目录
|
||||
里寻找步骤、references 或 templates。
|
||||
- 本目录不保留 `references/` 和 `templates/`,正文只有一份,在 `short-ship/`。
|
||||
- 旧项目 `.pouch.yaml` 里仍写 `bugfix-ship` 也能正常安装,软链不会悬空;方便时改成
|
||||
`short-ship`。
|
||||
- 确认没有项目再按旧名启用后,可以直接删除本目录。
|
||||
@@ -5,6 +5,9 @@
|
||||
[references/contract.md](references/contract.md),`scripts/check.py` 是契约的
|
||||
可执行校验器。
|
||||
|
||||
构建执行位置使用共享 `.pouch/agent.yaml` 的任意 `builder.<name>` binding 配置;本地
|
||||
Android、远程 Mac iOS 或未来其它平台都可以各自绑定 environment/project/path/profile。
|
||||
|
||||
## 什么时候使用
|
||||
|
||||
- "用 builder 初始化这个项目"
|
||||
@@ -12,6 +15,7 @@
|
||||
- "把 1.2.3 发布到包仓库 / 镜像仓库 / File Browser"
|
||||
- "检查这个项目的 makefile.builder 是否符合 builder 契约"
|
||||
- "看看项目现在的发布流程"
|
||||
- "看这个 SHA 的 CI 构建 / obtain"
|
||||
|
||||
只构建不上传时明确说明即可;上传永远需要你显式授权。
|
||||
|
||||
@@ -38,13 +42,19 @@ pouch add builder -g # 全局
|
||||
`templates/makefile.builder` 写出项目根 `makefile.builder`,并列出缺的发布配置。
|
||||
不改用户已有的 `Makefile` 或 `.env`。
|
||||
|
||||
配置跟随 `makefile.builder` 所在的 Git 根。如果 APK/IPA 位于 Git submodule,
|
||||
就在 submodule 内配置 `.env.builder` 和 `.pouch/builder/`;父仓库只固定 submodule commit
|
||||
并负责上层编排。
|
||||
|
||||
1. `makefile.builder` 目标:`help/build/clean/version` + 条件 `deb/docker/push*`,
|
||||
变量 `ARCHES/ARCH/VERSION/DIST_DIR/PROJECT_NAME`。
|
||||
以及 `obtain` / `venue`。变量 `ARCHES/ARCH/VERSION/DIST_DIR/PROJECT_NAME/BUILD_VENUE/CI_STATUS_SCRIPT`。
|
||||
`VERSION` 通过 `include <builder>/scripts/version.mk` 从 Git 推导。
|
||||
多架构清单是 `ARCHES`,见下方「多架构」。
|
||||
2. 运行 `python3 -I -S <builder>/scripts/check.py . --ready` 直到构建项 PASS。
|
||||
缺发布键只挡住上传,不挡住构建。
|
||||
3. 在项目根 `.env.builder` 配置发布环境变量(不要写进 `.env`):
|
||||
3. 在项目根 `.env.builder` 配置发布环境变量(不要写进 `.env`)。项目内 APK/IPA
|
||||
分发脚本的路径写在 `makefile.builder` 的 `COPY_SCRIPT`,脚本接收产物路径作为位置参数;
|
||||
未配置项目脚本时使用 `COPY_DEST` 的本地目录或容器目录后备逻辑:
|
||||
|
||||
```text
|
||||
DEB_SERVER_URL=https://deb.example.com
|
||||
@@ -53,13 +63,19 @@ DEB_TOKEN=<token> # 只放 .env.builder 或密钥系统,不进 git
|
||||
DOCKER_REGISTRY=registry.example.com
|
||||
COPY_DEST=file-server:/srv
|
||||
COPY_AS=latest.apk
|
||||
# COPY_SCRIPT= # 仅外部/临时脚本覆盖;项目内脚本写 makefile.builder
|
||||
```
|
||||
|
||||
`BUILD_VENUE=ci` 写在 `makefile.builder`:产物由 CI 构建。初始化时确认查询命令(tea / glab / gh / curl),写成 `.pouch/builder/ci-status.sh`。`make -f makefile.builder obtain`(或 `push-docker`)执行该脚本等待流水线并 inspect registry,不在本机 `docker push`。
|
||||
|
||||
4. 日常发布就是两条命令:
|
||||
`make -f makefile.builder deb && make -f makefile.builder push-deb`、
|
||||
`make -f makefile.builder push-docker`。
|
||||
写了 `ARCHES=amd64 arm64` 时,这两条会打出并上传两个 DEB;镜像一次推多平台。
|
||||
|
||||
跨机器或需要继续查看的构建先用 `agent-runtime` 精确解析 binding 和 Orca worktree;
|
||||
builder 只在授权后执行对应 `makefile.builder` target,不自动上传。
|
||||
|
||||
## 多架构
|
||||
|
||||
项目要发哪些 CPU 架构,写在**已提交的** `makefile.builder` 里,不要写进
|
||||
@@ -179,7 +195,7 @@ detached HEAD 用 `detached`,CI 可注入 `BUILD_BRANCH` / `CI_COMMIT_BRANCH`
|
||||
|
||||
## Agent 会做什么
|
||||
|
||||
1. 初始化:探测 DEB / Docker / Android / iOS / copy 轨道,写出 `makefile.builder` 和 `.env.builder` 骨架,按仓库证据填 `ARCHES`(不默认双架构),不改你已有的 `Makefile` 或 `.env`。
|
||||
1. 初始化:探测 DEB / Docker / Android / iOS / copy 轨道,写出 `makefile.builder` 和 `.env.builder` 骨架,确认 `BUILD_VENUE`;选 ci 时生成 `.pouch/builder/ci-status.sh`。按仓库证据填 `ARCHES`(不默认双架构),不改你已有的 `Makefile` 或 `.env`。
|
||||
2. 检查:只跑 `scripts/check.py --ready`,不改文件。
|
||||
3. 构建:走 `make -f makefile.builder`;只获构建授权时不走会自动上传的目标。
|
||||
4. 发布:先校验产物,再上传。缺发布键、未授权、或可能覆盖同版本时停下问你。
|
||||
@@ -205,9 +221,13 @@ Docker 只有你点名镜像时才走。token 不会写进输出、提交或回
|
||||
| `scripts/upload_deb.sh` | 上传 `.deb` 到 HTTP 包仓库(multipart package/token/repository_name) |
|
||||
| `scripts/publish_docker.sh` | buildx 构建 + 推送镜像,远端 digest 验证 |
|
||||
| `scripts/verify_deb.sh` | 核对包元数据、内容与 SHA-256 |
|
||||
| `scripts/copy_artifact.sh` | 把产物拷到 `COPY_DEST`(本地目录或 `container:/dir`) |
|
||||
| `scripts/copy_artifact.sh` | 按 `COPY_SCRIPT` 分发产物,未配置时拷到 `COPY_DEST` |
|
||||
| `scripts/obtain.sh` | 对精确 SHA 拿到产物;`BUILD_VENUE=ci` 时等流水线再 inspect |
|
||||
| `scripts/wait_ci.sh` | 轮询项目 `CI_STATUS_SCRIPT`,只等该 SHA,不触发 |
|
||||
| `scripts/init_ci_status.sh` | 初始化时把 tea/glab/gh/curl 模板拷到 `.pouch/builder/ci-status.sh` |
|
||||
| `templates/ci-status/` | tea / glab / gh / curl 查询脚本模板;契约见 [ci-status.md](references/ci-status.md) |
|
||||
| `templates/makefile.android.builder` | Android APK + copy 轨道骨架 |
|
||||
| `templates/makefile.ios.builder` | iOS IPA + copy 轨道骨架 |
|
||||
|
||||
环境变量契约、脚本解析顺序(`$BUILDER_SKILL_DIR` → `~/.pouch/skills/builder/scripts/`)、
|
||||
环境变量契约、脚本解析顺序(`$BUILDER_SKILL_DIR` → `~/.pouch` → `~/.agents`)、
|
||||
脏工作树策略等完整规则见 contract.md。
|
||||
|
||||
+36
-8
@@ -2,16 +2,30 @@
|
||||
name: builder
|
||||
description: >-
|
||||
初始化或检查 makefile.builder 契约,再构建或发布 deb/镜像/Android APK/iOS IPA,
|
||||
或把产物拷到目录/容器。触发词:初始化 builder、检查 makefile.builder、构建/发布
|
||||
deb、推送 apt、构建/发布 Docker 镜像、打 APK/IPA、拷到 File Browser、make push。
|
||||
或把产物拷到目录/容器。产物可在本机或 CI 上构建;拿到产物用 obtain。触发词:初始化
|
||||
builder、检查 makefile.builder、构建/发布 deb、推送 apt、构建/发布 Docker 镜像、
|
||||
打 APK/IPA、拷到 File Browser、make push、看构建、监听 CI、obtain。
|
||||
未授权不上传。Docker 仅用户点名镜像时才走。
|
||||
---
|
||||
|
||||
# Builder:DEB / Docker / Android / iOS 构建发布
|
||||
|
||||
**make 管构建,skill 脚本管发布,本 SKILL.md 只留脚本做不了的决策。**
|
||||
项目状态是根目录 `makefile.builder` 与发布用 `.env.builder`,不要创建
|
||||
`.pouch/builder/`,不要改用户的 `Makefile` / `makefile` / `.env`。
|
||||
项目状态是**当前 builder 项目根**的 `makefile.builder` 与 `.env.builder`;项目自定义分发脚本放在
|
||||
同一项目根的 `.pouch/builder/`,不要改用户的 `Makefile` / `makefile` / `.env`。如果父仓库包含
|
||||
submodule,submodule 是独立 builder 项目:它的 `makefile.builder`、`.env.builder` 和
|
||||
`.pouch/builder/` 必须放在 submodule 内,父仓库只负责调用或固定 submodule commit。
|
||||
|
||||
配置来源原则:项目要构建什么、发布哪些轨道、使用哪个已提交的分发脚本,放在
|
||||
`makefile.builder`;本机路径和工具链覆盖放在被忽略的 `.pouch/builder/local.mk`;凭据、
|
||||
发布目标和本轮别名放在被忽略的 `.env.builder`。`COPY_SCRIPT` 若指向项目内
|
||||
`.pouch/builder/` 的脚本,优先写入 `makefile.builder`,这样迁移项目时配置与脚本一起进入 Git。
|
||||
|
||||
构建执行位置、Agent CLI、模型、推理强度和 session 生命周期由共享 `agent-runtime` 的
|
||||
`.pouch/agent.yaml` 管理。`builder.<name>` 是可自由增加的 binding:可以指向本地
|
||||
worktree,也可以指向已配对的远程 Mac/其它构建机;不要把远程主机、模型或 terminal 参数
|
||||
硬编码进 `makefile.builder`。跨机器或跨 session 时先读 `agent-runtime`,构建目标仍只能
|
||||
由 `makefile.builder` 提供。
|
||||
|
||||
开始时解析当前 `SKILL.md` 所在目录,记为 `<skill-dir>`。优先
|
||||
`git rev-parse --show-toplevel` 解析项目根。
|
||||
@@ -21,17 +35,20 @@ description: >-
|
||||
- 初始化、接入 builder,或还没有 `makefile.builder`:执行「初始化」。
|
||||
- 检查契约或发布配置:执行「检查」。
|
||||
- 构建、发布、上传:执行「工作流」。不要静默初始化。
|
||||
- 看构建、监听 CI、ACK/short-ship/long-ship 要产物:执行「拿到产物」。不要当成第五条轨道。
|
||||
- 指定 `builder.<name>`、远程构建机或跨 session:先读共享 `agent-runtime`。
|
||||
- 不适用:本地安装/卸载 DEB;RPM/语言包;从零设计打包体系(先出方案);普通编码与 Dockerfile 编辑。
|
||||
- 改本 skill 自身:契约先改 `scripts/check.py`,再同步 [contract.md](references/contract.md) 与 templates;不在生产上传上试脚本。
|
||||
|
||||
## 初始化
|
||||
|
||||
1. 确认项目根。探测 `makefile.builder`、`.env.builder`、用户 Makefile(只当抄配方的证据,不改)、`Dockerfile`、`debian/`。`.env.builder` 只看键是否存在且非空,不读、不打印值。不要读取用户 `.env`。
|
||||
1. 确认项目根。优先以包含目标 `makefile.builder` 的仓库根为准;若目标位于 submodule,则以 submodule 根为准,不向父仓库回溯配置。探测 `makefile.builder`、`.env.builder`、用户 Makefile(只当抄配方的证据,不改)、`Dockerfile`、`debian/`。`.env.builder` 只看键是否存在且非空,不读、不打印值。不要读取用户 `.env`。
|
||||
2. 判定轨道:有 Dockerfile → docker;有 deb 信号或用户要打 deb → deb;`app.config.ts` / `assembleRelease` / `.apk` → android;`ios/` / `xcodebuild` / `.ipa` → ios;用户要拷到目录或容器 → copy。可多轨道。都不清则问。不要猜测 registry、token、COPY_DEST 或仓库名。
|
||||
3. 没有 `makefile.builder`:按轨道拷模板。deb/docker 用 `templates/makefile.builder`;仅 android 用 `templates/makefile.android.builder`;仅 ios 用 `templates/makefile.ios.builder`。按轨道删掉未使用的 deb/docker/push* 段,把 `build` 的 TODO 换成仓库里已有的真实编译命令(可从用户 Makefile 抄配方,但不要 `include` 或递归调用它),且配方必须使用 `$(ARCH)`。Android/iOS 的 `ARCHES` 是构建机 ISA(fat APK/IPA 仍只留本机一项)。按 [contract.md](references/contract.md) 填 `ARCHES`:`debian/control` / CI matrix / 用户点名的子集;否则只写本机(`x86_64`→`amd64`,`aarch64`→`arm64`)。不要默认双架构;看不出交叉编法时只留一项并说明。`include` builder 的 `scripts/version.mk`。多产物把 `push` 改成 `push: push-deb push-docker push-copy` 的子集。不要改用户 Makefile。
|
||||
4. 已有 `makefile.builder`:跑检查;按 FAIL 给出修补说明。不覆盖 `build`。用户明确要求按契约改时再加 `ARCHES`,并确认配方里有 `$(ARCH)`。不要调用 create-makefile(版本规则冲突)。
|
||||
5. 没有 `.env.builder`:把 `<skill-dir>/templates/env.builder` 拷到项目根(注释键,不含值)。缺发布键时在报告里给出可粘贴示例,并把 `.env.builder` 加入 `.gitignore`,不要提交。
|
||||
6. 运行 `python3 -I -S <skill-dir>/scripts/check.py <project-dir> --ready`。结构校验通过且当前轨道能构建才称「完成」;只缺发布键是「部分完成」。契约 FAIL 或轨道工具缺失是「阻塞」。除非用户明确要求,不提交、不推送、不上传。
|
||||
6. 确认 `BUILD_VENUE`:`local` 或 `ci`,不要猜。选 `ci` 时读 [ci-status.md](references/ci-status.md),确认查询命令(`tea` / `glab` / `gh` / `curl`),执行 `<skill-dir>/scripts/init_ci_status.sh --root <project-dir> --kind <kind>`,在 `makefile.builder` 写入 `BUILD_VENUE=ci` 和 `CI_STATUS_SCRIPT=.pouch/builder/ci-status.sh`。用户给了自定义查询命令时,把命令写进同一份脚本并保持 `STATUS=` 输出契约。
|
||||
7. 运行 `python3 -I -S <skill-dir>/scripts/check.py <project-dir> --ready`。结构校验通过且当前轨道能构建才称「完成」;只缺发布键是「部分完成」。契约 FAIL 或轨道工具缺失是「阻塞」。除非用户明确要求,不提交、不推送、不上传。
|
||||
|
||||
```text
|
||||
## builder 初始化:完成 | 部分完成 | 阻塞
|
||||
@@ -50,6 +67,7 @@ DEB_TOKEN=
|
||||
DOCKER_REGISTRY=registry.example.com
|
||||
COPY_DEST=file-server:/srv
|
||||
COPY_AS=latest.apk
|
||||
# 外部/临时脚本才放这里;项目内脚本优先在 makefile.builder 设置 COPY_SCRIPT
|
||||
```
|
||||
|
||||
## 检查
|
||||
@@ -62,7 +80,17 @@ COPY_AS=latest.apk
|
||||
|
||||
1. 跑 `check.py <project-dir>`;需要工具链与发布键时加 `--ready`;要实构 deb 时加 `--build`。契约 FAIL 或轨道工具缺失:停下,转入「初始化」,不要绕过校验,不要改用户 Makefile。只缺发布键:允许构建,禁止上传。未接契约的存量项目按 contract.md §6 发现已有入口,上传仍用 builder 脚本;成功交付一次后引导迁到 `makefile.builder`。
|
||||
2. 仅当用户明确要求发布、上传或提交时才上传。不猜测生产端点;不把 token 写入输出、文件、提交或回复;不用 `set -x` 跑含凭据的命令。可能覆盖同版本时先问。脏工作树默认拒绝发布;用户明确接受时设 `ALLOW_UNCOMMITTED=1` 并注明未提交修改。
|
||||
3. 构建:用户指定了架构才传 `ARCH=`;否则不要传,让 makefile 按 `ARCHES` 展开(`make -s -f makefile.builder arches`)。`make -f makefile.builder build` 始终单架构;DEB 用 `make -f makefile.builder deb`。版本按契约从 Git 祖先稳定 tag 推导,不要调用 releaser,不要用全仓库最新 tag。仅获构建授权时不要走会自动上传的目标。脚本含 `rm -rf` 时先确认为受限构建目录。
|
||||
3. 构建:用户指定了架构才传 `ARCH=`;否则不要传,让 makefile 按 `ARCHES` 展开(`make -s -f makefile.builder arches`)。`make -f makefile.builder build` 始终单架构;DEB 用 `make -f makefile.builder deb`。版本按契约从 Git 祖先稳定 tag 推导,不要调用 releaser,不要用全仓库最新 tag。仅获构建授权时不要走会自动上传的目标。脚本含 `rm -rf` 时先确认为受限构建目录。若通过 `builder.<name>` 执行,先精确解析 `environment + host + project + path` 对应的 worktree;远程 binding 不能 fallback 到本机。持久 session 只显式 attach/resume,不能按标题复用旧 terminal。
|
||||
4. DEB 上传前:对每个包 `verify_deb.sh <exact-package-path.deb> <version> <arch>`。多个包时不凭文件时间猜测。镜像轨道由 `publish_docker.sh` 自带远端 inspect。
|
||||
5. 发布优先 `make -f makefile.builder push[-deb|-docker|-copy]`,或直接调 `upload_deb.sh` / `publish_docker.sh` / `copy_artifact.sh`。未指定 `ARCH=` 时 `push-deb` 上传清单里每一个 `.deb`。拷贝轨道要 `COPY_DEST`(本地目录或 `container:/dir`);`COPY_AS` 给第一份文件额外名字。脚本缺环境变量时加载 `.env.builder`(shell 显式值优先),不读 `.env`。不把 token 当命令行参数;不把脚本复制进项目。多平台镜像只能走 `publish_docker.sh`,不能拆进 make;不要把项目架构清单写进 `.env.builder`。`build` 里禁止 `docker cp`。
|
||||
5. 发布优先 `make -f makefile.builder push[-deb|-docker|-copy]`,或直接调 `upload_deb.sh` / `publish_docker.sh` / `copy_artifact.sh` / `obtain.sh`。`BUILD_VENUE=ci` 时 `push-docker` 就是 obtain。未指定 `ARCH=` 时 `push-deb` 上传清单里每一个 `.deb`。拷贝轨道至少配置 `COPY_DEST`(本地目录或 `container:/dir`)或 `COPY_SCRIPT`(项目内脚本优先在 `makefile.builder` 设置;同时配置时命令行/环境值优先)。自定义脚本按 `FILE [FILE ...]` 接收产物路径,自行完成重命名、上传、远端校验和通知;相对路径按项目根解析,`BUILDER_PROJECT_ROOT` 提供项目根。`COPY_AS` 只由内置 `COPY_DEST` 路径处理。脚本缺环境变量时加载 `.env.builder`(shell 显式值优先),不读 `.env`。不要把 token 当命令行参数;脚本可随项目放在 `.pouch/builder/` 下。多平台镜像只能走 `publish_docker.sh`,不能拆进 make;不要把项目架构清单写进 `.env.builder`。`build` 里禁止 `docker cp`。
|
||||
6. 发布成功不能只看「curl/push 已执行」。要有退出码、HTTP 成功或远端 digest;索引异步时报告「上传已接受,索引尚待更新」。最终回复给出包名/镜像引用、版本、架构、SHA-256 或 digest、源 commit、工作区状态和未完成项。
|
||||
|
||||
## 拿到产物
|
||||
|
||||
调用方是 short-ship、long-ship、ACK(delivery-loop 的 `artifact_built`),或用户要看 CI 构建。
|
||||
按 [obtain.md](references/obtain.md) 执行 `scripts/obtain.sh --sha <commit>`。
|
||||
|
||||
- `BUILD_VENUE=local`:当前 HEAD 必须是该 SHA,跑 makefile 的 docker/deb。
|
||||
- `BUILD_VENUE=ci`:`wait_ci.sh` 轮询项目的 `CI_STATUS_SCRIPT`,再 inspect `version.sh --docker` 的镜像 tag。不触发流水线,不本机 push。缺脚本则停下,回到初始化。
|
||||
- 失败(无流水线、job 失败、digest 不对)必须原样返回给调用方,不得标 `artifact_built`。
|
||||
- 合进默认分支若项目不跑 CI,这是正确失败;预览用 `dev/*`,正式用 tag。
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# CI 状态查询脚本
|
||||
|
||||
`BUILD_VENUE=ci` 时,流水线状态由**项目脚本**查询。builder 只轮询这份脚本,
|
||||
不在 skill 里猜 gh / glab / tea / curl。
|
||||
|
||||
## 初始化
|
||||
|
||||
选 `ci` 后确认查询方式,再生成脚本:
|
||||
|
||||
```bash
|
||||
<skill-dir>/scripts/init_ci_status.sh --root <project> --kind tea|glab|gh|curl
|
||||
```
|
||||
|
||||
写出 `.pouch/builder/ci-status.sh`(可执行、进 git)。`makefile.builder` 写:
|
||||
|
||||
```makefile
|
||||
BUILD_VENUE ?= ci
|
||||
CI_STATUS_SCRIPT ?= .pouch/builder/ci-status.sh
|
||||
```
|
||||
|
||||
相对路径只能在 `.pouch/builder/` 下。凭据仍放 `.env.builder`(如 `GITEA_TOKEN`),
|
||||
不要写进脚本参数或日志。
|
||||
|
||||
用户给了自定义命令时,把该命令写进同一份脚本,输出必须符合下方契约。
|
||||
|
||||
## 调用
|
||||
|
||||
```bash
|
||||
.pouch/builder/ci-status.sh --sha <40-character-sha>
|
||||
```
|
||||
|
||||
只查询、不触发流水线。`BUILDER_PROJECT_ROOT` 是项目根。
|
||||
|
||||
## 输出
|
||||
|
||||
退出 0 且 stdout 含 `STATUS=` 键值(可多行或同一行):
|
||||
|
||||
| STATUS | 含义 |
|
||||
| --- | --- |
|
||||
| `empty` | 该 SHA 还没有流水线 |
|
||||
| `running` | 已出现、尚未结束 |
|
||||
| `success` | 该 SHA 的流水线成功 |
|
||||
| `failed` | 失败、取消或超时 |
|
||||
| `error` | 查询本身失败(鉴权、CLI 缺失) |
|
||||
|
||||
可选:`ID=`、`PIPELINE=`(URL)、`JOBS=`。
|
||||
|
||||
| 退出码 | 含义 |
|
||||
| --- | --- |
|
||||
| 0 | 已查出状态(含 empty/running/failed) |
|
||||
| 2 | 用法错误 |
|
||||
| 3 | 无法查询(缺 CLI、未登录、被拒绝) |
|
||||
|
||||
`wait_ci.sh` 按这份输出轮询:`empty` 超过出现窗口记 `no_pipeline`;
|
||||
`success` 才继续 obtain;`failed` 原样失败。
|
||||
@@ -4,8 +4,17 @@
|
||||
check.py,本文档跟随。所有接入项目按同一套 make 目标、产物形状和环境变量执行,
|
||||
builder 脚本只做发布,不做项目特定的构建逻辑。
|
||||
|
||||
配置边界按 Git 项目根生效:`makefile.builder` 所在仓库就是 builder 项目根。
|
||||
如果父仓库通过 submodule 引入另一个项目,submodule 的构建、`.env.builder` 和
|
||||
`.pouch/builder/` 分发脚本属于 submodule;父仓库不得替它承载这些配置。
|
||||
|
||||
分工原则:**make 管构建(项目内、确定性),skill 脚本管发布(跨项目 SSOT),
|
||||
Agent 只保留授权判断和歧义处理。**
|
||||
Agent 只保留授权判断和歧义处理。** 构建在哪台机器执行、使用哪个 CLI/model 和
|
||||
session 如何保存,由共享 `agent-runtime` 的 binding 决定;makefile 不能承载主机或
|
||||
Agent 选择。
|
||||
|
||||
`builder.android`、`builder.ios`、`builder.harmony` 都是合法的可配置 binding。新增平台
|
||||
只增加 binding 和对应 make target,不改 builder skill 的固定枚举。
|
||||
|
||||
契约文件固定为项目根 `makefile.builder`,调用方式:
|
||||
|
||||
@@ -40,16 +49,20 @@ make -f makefile.builder <target>
|
||||
| `ios` | 有 iOS IPA 的项目 | 可与 `build` 相同。产出 `$(DIST_DIR)/<name>_<version>_<arch>.ipa`;只构建不上传 |
|
||||
| `arches` | 可选(新模板必备) | 打印一行空格分隔的 `ARCHES`;无此目标视为存量 makefile,隐式单架构 |
|
||||
| `push-deb` | 同时有多种发布轨道的项目 | 仅调 builder 的 `upload_deb.sh`。未指定 `ARCH=` 时上传 `ARCHES` 中每一项对应的 `.deb`;指定了则只上传那一个 |
|
||||
| `push-docker` | 同时有多种发布轨道的项目 | 仅调 builder 的 `publish_docker.sh` |
|
||||
| `push-copy` | 同时有多种发布轨道的项目 | 仅调 builder 的 `copy_artifact.sh` |
|
||||
| `push-docker` | 同时有多种发布轨道的项目 | `BUILD_VENUE=local` 时仅调 `publish_docker.sh`;`ci` 时仅调 `obtain.sh` |
|
||||
| `push-copy` | 同时有多种发布轨道的项目 | 仅调 builder 的 `copy_artifact.sh`;由它按配置选择内置拷贝或自定义脚本 |
|
||||
| `push` | 单一产物类型时必备;多产物项目为聚合 | 依序调用对应 push-* 或直接调脚本;是发布的唯一 make 入口 |
|
||||
| `obtain` | 有产物的项目 | 调用 `obtain.sh`,对精确 commit SHA 拿到已存在的产物。`BUILD_VENUE=ci` 时轮询 `CI_STATUS_SCRIPT` 再 inspect,不在本机 `docker push` |
|
||||
| `venue` | 可选(新模板必备) | 打印一行 `BUILD_VENUE`(`local` 或 `ci`) |
|
||||
|
||||
规则:
|
||||
|
||||
1. 项目有 DEB 产物的判据:`makefile.builder` 配方引用 `dpkg-deb`/`debuild` 或产出 `.deb`。
|
||||
1. 项目有 DEB 产物的判据:`makefile.builder` 配方以独立命令调用 `dpkg-deb`/`debuild` 或产出 `.deb`;
|
||||
不能把 `xcodebuild` 中包含的字符误判成 `debuild`。
|
||||
有镜像的判据:项目根存在 `Dockerfile`。
|
||||
Android 判据:配方产出 `.apk` / `.aab`。iOS 判据:配方产出 `.ipa`。
|
||||
拷贝发布判据:配方调用 `copy_artifact.sh`。
|
||||
拷贝发布判据:配方调用 `copy_artifact.sh`。`copy_artifact.sh` 是稳定入口,具体分发可由
|
||||
`COPY_SCRIPT` 接管。
|
||||
2. 多于一种发布轨道必须拆 `push-deb` / `push-docker` / `push-copy`,`push` 依序聚合;
|
||||
单轨道项目一个 `push` 即可。
|
||||
3. `docker` 目标只能本地构建。多平台镜像无法拆成"make 构建 + 单独推送"
|
||||
@@ -62,8 +75,15 @@ make -f makefile.builder <target>
|
||||
|
||||
## 2. 变量
|
||||
|
||||
配置来源按变量的稳定性分层:`makefile.builder` 是项目构建与发布轨道的可迁移事实,
|
||||
包括 `ARCHES`、产物命名、目标和项目内 `COPY_SCRIPT`;`.pouch/builder/local.mk` 是
|
||||
不提交的机器工具链覆盖;`.env.builder` 是不提交的凭据、发布端点、目标目录和本轮别名。
|
||||
命令行/环境变量可以覆盖前两者,但不应把项目契约依赖在本机环境上。
|
||||
|
||||
| 变量 | 默认 | 说明 |
|
||||
|------|------|------|
|
||||
| `BUILD_VENUE` | `local` | 产物在哪构建:`local` 本机 make;`ci` 由项目 CI 流水线构建。这不是新轨道。写在 `makefile.builder` 并提交。`ci` 时 `push-docker` 委托 `obtain.sh`(等流水线 + inspect),不跑 `publish_docker.sh` |
|
||||
| `CI_STATUS_SCRIPT` | `.pouch/builder/ci-status.sh` | `BUILD_VENUE=ci` 时必填。项目内查询该 SHA 流水线状态的可执行脚本,相对路径只能在 `.pouch/builder/`。初始化时按 tea / glab / gh / curl 生成,契约见 [ci-status.md](ci-status.md) |
|
||||
| `ARCHES` | `amd64` | 本项目要发布的架构清单,空格分隔,子集只能是 `amd64` `arm64`。写在 `makefile.builder` 里并提交;不要放进 `.env.builder`。缺省或无 `arches` 目标时视为单架构 `amd64`。不要默认写成双架构 |
|
||||
| `ARCH` | `$(firstword $(ARCHES))` | 这一次构建的架构。必须落在 `ARCHES` 里;非法值必须 `$(error)` 并提示合法值。命令行/环境传入时只构建/上传这一项 |
|
||||
| `VERSION` | `` (空) | 为空时按「版本号」节从 Git 祖先稳定 tag 推导;禁止 `sort -V` 取全局最新 |
|
||||
@@ -139,10 +159,25 @@ include $(HOME)/.pouch/skills/builder/scripts/version.mk
|
||||
|
||||
| 变量 | 必填 | 说明 |
|
||||
|---|---|---|
|
||||
| `COPY_DEST` | 是 | 本地目录,或 Docker 目标 `container:/absolute/dir`(`docker cp`) |
|
||||
| `COPY_DEST` | 与 `COPY_SCRIPT` 至少配置一个 | 内置后备目标:本地目录,或 Docker 目标 `container:/absolute/dir`(`docker cp`) |
|
||||
| `COPY_SCRIPT` | 与 `COPY_DEST` 至少配置一个 | 项目内 `.pouch/builder/` 脚本的路径优先写在 `makefile.builder` 并提交;也可用绝对路径或环境/.env.builder 覆盖;必须是可执行文件,同时配置时优先于 `COPY_DEST` |
|
||||
| `COPY_AS` | 否 | 第一份文件的额外 basename,逗号或空格分隔 |
|
||||
|
||||
`copy_artifact.sh FILE [FILE ...]` 把已构建文件拷到 `COPY_DEST`,校验目标存在后打印 SHA-256。不读 `.env`。脏工作树默认拒绝,`ALLOW_UNCOMMITTED=1` 放行。
|
||||
`copy_artifact.sh FILE [FILE ...]` 是 APK/IPA 等产物的统一分发入口。不读 `.env`,脏工作树默认拒绝,
|
||||
`ALLOW_UNCOMMITTED=1` 放行。
|
||||
|
||||
未配置 `COPY_SCRIPT` 时,入口把文件拷到 `COPY_DEST`,校验目标存在后打印 SHA-256。
|
||||
配置 `COPY_SCRIPT=.pouch/builder/publish-apk.sh` 时(项目内脚本通常由 `makefile.builder` 传入),入口按项目根解析、先校验每个文件存在,然后直接执行:
|
||||
|
||||
```text
|
||||
/absolute/path/to/publish-script FILE [FILE ...]
|
||||
```
|
||||
|
||||
相对路径只允许位于项目的 `.pouch/builder/` 下;绝对路径仍支持外部脚本。不经过 shell 字符串求值,
|
||||
不把 token 放进参数。脚本通过位置参数接收原始产物绝对路径,自行负责重命名、上传、远端校验和通知;
|
||||
当前项目根以 `BUILDER_PROJECT_ROOT` 环境变量提供。
|
||||
脚本返回非零即视为分发失败;成功后入口只报告脚本成功和本地 SHA-256,不宣称远端已校验。
|
||||
`--dry-run` 只打印将调用的脚本与文件,不执行自定义脚本。
|
||||
|
||||
### Docker 轨道
|
||||
|
||||
@@ -155,6 +190,8 @@ include $(HOME)/.pouch/skills/builder/scripts/version.mk
|
||||
|
||||
`PLATFORMS` 优先级(高 → 低):用户这轮 `--platform` 或已 export 的 `PLATFORMS` → 命令行 `ARCH=` 映射的 `linux/$(ARCH)`(由 `push-docker` 传入)→ `.env.builder` 的 `PLATFORMS` → `makefile.builder` 的 `ARCHES` → `linux/amd64`。
|
||||
|
||||
`BUILD_VENUE=ci` 时 Docker 发布路径是 `obtain.sh`:`wait_ci.sh` 只轮询 `CI_STATUS_SCRIPT`,只认 **该 commit SHA**。没有流水线、job 失败、超时、或 Harbor inspect 不到 `version.sh --docker` 算出的 tag,一律非零退出。不触发流水线。查询命令在初始化时写成项目脚本,运行时不再猜测 gh / glab / tea / curl。合进默认分支若项目声明不构建,这是正确失败;调用方应打 tag 或推送到项目会构建的 ref(例如 `dev/*`)。CI job 若已经 `docker push`,obtain 成功即视为产物已在 registry,不要再本机 push 一次。
|
||||
|
||||
配置来源优先级:shell 已显式设置的值 > 项目根 `.env.builder` > 失败并询问用户。
|
||||
`.env.builder` 由 builder 脚本加载(不回显任何值);当前 shell 已设置的值优先。
|
||||
不要读取或改写用户 `.env`。空值视为未配置。不要提交 `.env.builder`。
|
||||
@@ -170,6 +207,7 @@ push 目标与 `version.sh` 定位 builder 脚本时按以下顺序,命中即
|
||||
|
||||
1. `$BUILDER_SKILL_DIR/scripts/`(特殊安装位置)
|
||||
2. `$HOME/.pouch/skills/builder/scripts/`(标准 clone 位)
|
||||
3. `$HOME/.agents/skills/builder/scripts/`(本机 agent 安装位)
|
||||
|
||||
两个位置都不可用时必须失败并提示:设置 `BUILDER_SKILL_DIR`,或把 pouch 仓库
|
||||
clone 到 `~/.pouch`。
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# 拿到产物(obtain)
|
||||
|
||||
Builder 的交付入口是 **按精确 Git commit 拿到产物**,不是「在哪台机器编译」。
|
||||
docker / deb / android / ios / copy 仍是轨道;`BUILD_VENUE` 只说明构建发生在本机还是 CI。
|
||||
|
||||
## 谁来调用
|
||||
|
||||
- `short-ship` / `long-ship` 和 ACK 走到 delivery-loop 的 `artifact_built` 时。
|
||||
- 用户说「看构建」「监听 CI」「拿到镜像」时。
|
||||
- `make -f makefile.builder obtain` 或 `push-docker`(`BUILD_VENUE=ci`)。
|
||||
|
||||
代码必须已经推到远端(`ci` 时流水线由 git ref 触发)。Builder 不代替 releaser 打 tag,也不创建分支。
|
||||
|
||||
## 命令
|
||||
|
||||
```bash
|
||||
<builder>/scripts/obtain.sh --sha <full-sha> [--branch <name>] [--root <project>] [--timeout 1200]
|
||||
```
|
||||
|
||||
成功打印:
|
||||
|
||||
```text
|
||||
ARTIFACT=harbor.example.com/ns/name:1.4.2
|
||||
DIGEST=sha256:…
|
||||
SHA=<full-sha>
|
||||
VENUE=ci
|
||||
TAG=1.4.2
|
||||
```
|
||||
|
||||
镜像 tag 对该 SHA 跑 `version.sh --docker`(可 `--branch` 注入 `CI_COMMIT_BRANCH`),禁止 `git describe`。
|
||||
|
||||
## 退出码
|
||||
|
||||
| 码 | 含义 | 调用方 |
|
||||
|---|---|---|
|
||||
| 0 | 产物已核验 | `artifact_built` 完成 |
|
||||
| 1 | 该 SHA 无流水线、job 失败、超时、inspect 失败 | 标 `failed`,不得 publish/deploy |
|
||||
| 2 | 用法或配置错误 | 标 `blocked` |
|
||||
| 3 | 项目 CI 状态脚本无法查询 | 停;回到初始化补 `CI_STATUS_SCRIPT`,或用**已打开且已登录**的同 host Orca tab 查流水线。禁止新开未登录页 |
|
||||
|
||||
## `ci` 规则
|
||||
|
||||
- 只认该 SHA 的 pipeline,不认默认分支「最新一次绿」。
|
||||
- 不触发流水线。
|
||||
- 查询命令是项目 `.pouch/builder/ci-status.sh`(`CI_STATUS_SCRIPT`),初始化时按 tea / glab / gh / curl 写好。凭据仍放 `.env.builder`。
|
||||
- job 变绿不够,docker 轨道必须 inspect 到 digest。
|
||||
- 合进 `main` 若项目不构建,`no_pipeline` 是正确失败。预览走项目会构建的 ref(如 `dev/*`),正式走 tag。
|
||||
|
||||
## Agent
|
||||
|
||||
1. 固化 source revision 为完整 SHA。
|
||||
2. 跑 `obtain.sh --sha <sha>`。
|
||||
3. 退出 0:记录 ARTIFACT/DIGEST/SHA。`venue=ci` 且 job 已 push 时,`published` 视为已满足,不要本机再 `publish_docker.sh`。
|
||||
4. 退出 1/2:停止 delivery-loop,报告 pipeline URL 或 `no_pipeline`。
|
||||
5. 退出 3:先说明 CLI 身份不对;只有已有同 host 登录 tab 时才用来读 pipeline。
|
||||
+233
-16
@@ -41,7 +41,13 @@ SECRET_PATTERNS = (
|
||||
)
|
||||
FLOATING_TAGS = (":latest", ":stable")
|
||||
DEB_SHAPE = re.compile(r"^[^_\s]+_[^_\s]+_[^_\s]+\.deb$")
|
||||
VALID_SCRIPT_NAMES = ("upload_deb.sh", "publish_docker.sh", "copy_artifact.sh")
|
||||
VALID_SCRIPT_NAMES = (
|
||||
"upload_deb.sh",
|
||||
"publish_docker.sh",
|
||||
"copy_artifact.sh",
|
||||
"obtain.sh",
|
||||
"wait_ci.sh",
|
||||
)
|
||||
BUILDER_MAKEFILE = "makefile.builder"
|
||||
BUILDER_ENV = ".env.builder"
|
||||
|
||||
@@ -228,7 +234,8 @@ def check_build_has_no_upload(report: Report, project: Path) -> None:
|
||||
|
||||
|
||||
def detect_deb_project(recipe_all: str, project: Path) -> bool:
|
||||
return ".deb" in recipe_all or "dpkg-deb" in recipe_all or "debuild" in recipe_all or any(project.glob("debian/*"))
|
||||
has_deb_command = re.search(r"(?<![A-Za-z0-9_-])(?:dpkg-deb|debuild)(?![A-Za-z0-9_-])", recipe_all)
|
||||
return ".deb" in recipe_all or has_deb_command is not None or any(project.glob("debian/*"))
|
||||
|
||||
|
||||
def check_deb_recipe(report: Report, project: Path, built_deb: Path | None) -> None:
|
||||
@@ -301,7 +308,11 @@ def check_mobile_recipe(
|
||||
report: Report, project: Path, *, kind: str, number: int, ext: str
|
||||
) -> None:
|
||||
target = "build"
|
||||
dry = run_make(project, "build")
|
||||
if kind == "ios":
|
||||
ios_probe = run_make(project, "ios")
|
||||
if not has_no_rule(ios_probe):
|
||||
target = "ios"
|
||||
dry = run_make(project, target)
|
||||
text = chr(10).join(clean_make_output(dry))
|
||||
problems = []
|
||||
if dry.returncode != 0:
|
||||
@@ -349,6 +360,9 @@ SCRIPT_RESOLVE_SNIPPETS = tuple(
|
||||
"$$HOME/.skills/skills/builder/scripts",
|
||||
"$HOME/.skills/skills/builder/scripts",
|
||||
"~/.skills/skills/builder/scripts",
|
||||
"$$HOME/.agents/skills/builder/scripts",
|
||||
"$HOME/.agents/skills/builder/scripts",
|
||||
"~/.agents/skills/builder/scripts",
|
||||
)
|
||||
for name in VALID_SCRIPT_NAMES
|
||||
)
|
||||
@@ -374,7 +388,12 @@ def check_push_delegates(
|
||||
missing = []
|
||||
inline = []
|
||||
thin = []
|
||||
builder_names = ("upload_deb.sh", "publish_docker.sh", "copy_artifact.sh")
|
||||
builder_names = (
|
||||
"upload_deb.sh",
|
||||
"publish_docker.sh",
|
||||
"copy_artifact.sh",
|
||||
"obtain.sh",
|
||||
)
|
||||
for target in targets:
|
||||
dry = run_make(project, target)
|
||||
if has_no_rule(dry):
|
||||
@@ -442,7 +461,7 @@ def check_secrets_and_tags(report: Report, project: Path) -> None:
|
||||
|
||||
DEB_ENV_KEYS = ("DEB_SERVER_URL", "DEB_TOKEN", "DEB_REPOSITORY")
|
||||
DOCKER_ENV_KEYS = ("DOCKER_REGISTRY",)
|
||||
COPY_ENV_KEYS = ("COPY_DEST",)
|
||||
COPY_ENV_KEYS = ("COPY_DEST", "COPY_SCRIPT")
|
||||
ENV_KEY_LINE = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)=(.*)$")
|
||||
|
||||
|
||||
@@ -469,16 +488,186 @@ def env_file_keys(project: Path) -> set[str]:
|
||||
return keys
|
||||
|
||||
|
||||
def key_present(key: str, env_keys: set[str]) -> bool:
|
||||
return bool(os.environ.get(key)) or key in env_keys
|
||||
def env_file_values(project: Path) -> dict[str, str]:
|
||||
"""Return nonempty `.env.builder` values for internal validation only."""
|
||||
path = project / BUILDER_ENV
|
||||
values: dict[str, str] = {}
|
||||
if not path.is_file():
|
||||
return values
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except OSError:
|
||||
return values
|
||||
for raw in text.splitlines():
|
||||
stripped = raw.strip()
|
||||
if not stripped or stripped.startswith("#"):
|
||||
continue
|
||||
match = ENV_KEY_LINE.match(stripped)
|
||||
if not match:
|
||||
continue
|
||||
value = match.group(2).strip().strip("'\"")
|
||||
if value:
|
||||
values[match.group(1)] = value
|
||||
return values
|
||||
|
||||
|
||||
MAKE_ASSIGNMENT = re.compile(
|
||||
r"^([A-Za-z_][A-Za-z0-9_]*)\s*(?:\?=|:=|=)\s*(.*?)\s*$"
|
||||
)
|
||||
|
||||
|
||||
def makefile_values(project: Path) -> dict[str, str]:
|
||||
"""Return nonempty top-level make variable values for contract checks."""
|
||||
path = project / BUILDER_MAKEFILE
|
||||
values: dict[str, str] = {}
|
||||
if not path.is_file():
|
||||
return values
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except OSError:
|
||||
return values
|
||||
for raw in text.splitlines():
|
||||
match = MAKE_ASSIGNMENT.match(raw)
|
||||
if not match:
|
||||
continue
|
||||
value = re.split(r"\s+#", match.group(2), maxsplit=1)[0].strip()
|
||||
if value:
|
||||
values[match.group(1)] = value
|
||||
return values
|
||||
|
||||
|
||||
def key_present(
|
||||
key: str, env_keys: set[str], make_values: dict[str, str] | None = None
|
||||
) -> bool:
|
||||
return bool(os.environ.get(key)) or key in env_keys or bool((make_values or {}).get(key))
|
||||
|
||||
|
||||
def configured_value(
|
||||
key: str,
|
||||
env_values: dict[str, str],
|
||||
make_values: dict[str, str] | None = None,
|
||||
) -> str:
|
||||
"""Read a configured value without ever printing it."""
|
||||
return os.environ.get(key, "") or env_values.get(key, "") or (make_values or {}).get(key, "")
|
||||
|
||||
|
||||
def resolve_builder_local_script(project: Path, script: str) -> tuple[Path | None, str | None]:
|
||||
"""Resolve a project script; relative paths must stay under .pouch/builder/."""
|
||||
configured = Path(script).expanduser()
|
||||
if configured.is_absolute():
|
||||
return configured, None
|
||||
try:
|
||||
resolved = (project / configured).resolve()
|
||||
allowed_root = (project / ".pouch" / "builder").resolve()
|
||||
resolved.relative_to(allowed_root)
|
||||
except ValueError:
|
||||
return None, "relative script must be under .pouch/builder/"
|
||||
return resolved, None
|
||||
|
||||
|
||||
def resolve_copy_script(project: Path, script: str) -> tuple[Path | None, str | None]:
|
||||
path, error = resolve_builder_local_script(project, script)
|
||||
if error:
|
||||
return None, "relative COPY_SCRIPT must be under .pouch/builder/"
|
||||
return path, None
|
||||
|
||||
|
||||
def check_copy_script(
|
||||
report: Report,
|
||||
project: Path,
|
||||
env_values: dict[str, str],
|
||||
make_values: dict[str, str],
|
||||
) -> None:
|
||||
script = configured_value("COPY_SCRIPT", env_values, make_values)
|
||||
if not script:
|
||||
return
|
||||
path, resolve_error = resolve_copy_script(project, script)
|
||||
problems = []
|
||||
if resolve_error:
|
||||
problems.append(resolve_error)
|
||||
elif path is not None and not path.is_file():
|
||||
problems.append("COPY_SCRIPT does not point to a file")
|
||||
elif path is not None and not os.access(path, os.X_OK):
|
||||
problems.append("COPY_SCRIPT is not executable")
|
||||
report.add(
|
||||
FAIL if problems else PASS,
|
||||
14,
|
||||
"COPY_SCRIPT 可执行且路径明确",
|
||||
"\n".join(problems) if problems else "configured custom copy script is executable",
|
||||
)
|
||||
|
||||
|
||||
def read_venue(project: Path) -> str:
|
||||
env = (os.environ.get("BUILD_VENUE") or "").strip()
|
||||
if env in ("local", "ci"):
|
||||
return env
|
||||
result = run_make(project, "venue")
|
||||
if not has_no_rule(result):
|
||||
echoed = parse_dry_echo(result)
|
||||
if echoed in ("local", "ci"):
|
||||
return echoed
|
||||
cleaned = "\n".join(clean_make_output(result)).strip()
|
||||
if cleaned in ("local", "ci"):
|
||||
return cleaned
|
||||
raw = makefile_values(project).get("BUILD_VENUE", "local")
|
||||
raw = re.split(r"\s+#", raw, maxsplit=1)[0].strip()
|
||||
return raw or "local"
|
||||
|
||||
|
||||
def check_ci_status_script(
|
||||
report: Report,
|
||||
project: Path,
|
||||
env_values: dict[str, str],
|
||||
make_values: dict[str, str],
|
||||
) -> None:
|
||||
if read_venue(project) != "ci":
|
||||
report.add(SKIP, 15, "CI_STATUS_SCRIPT 可执行", "BUILD_VENUE is not ci")
|
||||
return
|
||||
script = configured_value("CI_STATUS_SCRIPT", env_values, make_values)
|
||||
problems = []
|
||||
if not script:
|
||||
problems.append("BUILD_VENUE=ci requires CI_STATUS_SCRIPT")
|
||||
path = None
|
||||
resolve_error = None
|
||||
else:
|
||||
path, resolve_error = resolve_builder_local_script(project, script)
|
||||
if resolve_error:
|
||||
problems.append(resolve_error)
|
||||
elif path is not None and not path.is_file():
|
||||
problems.append("CI_STATUS_SCRIPT does not point to a file")
|
||||
elif path is not None and not os.access(path, os.X_OK):
|
||||
problems.append("CI_STATUS_SCRIPT is not executable")
|
||||
report.add(
|
||||
FAIL if problems else PASS,
|
||||
15,
|
||||
"CI_STATUS_SCRIPT 可执行",
|
||||
"\n".join(problems) if problems else f"ci status script: {script}",
|
||||
)
|
||||
|
||||
|
||||
def check_ready_toolchain(
|
||||
report: Report, *, deb_project: bool, docker_project: bool, copy_project: bool = False
|
||||
report: Report,
|
||||
project: Path | None = None,
|
||||
*,
|
||||
deb_project: bool,
|
||||
docker_project: bool,
|
||||
copy_project: bool = False,
|
||||
) -> None:
|
||||
lines = [f"make: {'found' if shutil.which('make') else 'MISSING'}"]
|
||||
venue = read_venue(project) if project is not None else "local"
|
||||
lines = [
|
||||
f"make: {'found' if shutil.which('make') else 'MISSING'}",
|
||||
f"BUILD_VENUE: {venue}",
|
||||
]
|
||||
problems = []
|
||||
if docker_project:
|
||||
if venue not in ("local", "ci"):
|
||||
problems.append("BUILD_VENUE must be local or ci")
|
||||
if docker_project and venue == "ci":
|
||||
docker_ok = shutil.which("docker") is not None
|
||||
lines.append(
|
||||
f"docker: {'found' if docker_ok else 'optional for inspect; obtain fails without it'}"
|
||||
)
|
||||
lines.append("CI status: project CI_STATUS_SCRIPT (tea/glab/gh/curl)")
|
||||
elif docker_project:
|
||||
docker_ok = shutil.which("docker") is not None
|
||||
lines.append(f"docker: {'found' if docker_ok else 'MISSING (blocks docker track)'}")
|
||||
if not docker_ok:
|
||||
@@ -516,6 +705,8 @@ def check_ready_env_keys(
|
||||
copy_project: bool = False,
|
||||
) -> None:
|
||||
env_keys = env_file_keys(project)
|
||||
env_values = env_file_values(project)
|
||||
make_values = makefile_values(project)
|
||||
lines = []
|
||||
missing: list[str] = []
|
||||
if not deb_project and not docker_project and not copy_project:
|
||||
@@ -531,7 +722,7 @@ def check_ready_env_keys(
|
||||
lines.append("DEB_*: skipped (no deb track)")
|
||||
if docker_project:
|
||||
for key in DOCKER_ENV_KEYS:
|
||||
found = key_present(key, env_keys)
|
||||
found = key_present(key, env_keys, make_values)
|
||||
lines.append(f"{key}: {'present' if found else 'MISSING'}")
|
||||
if not found:
|
||||
missing.append(key)
|
||||
@@ -539,18 +730,28 @@ def check_ready_env_keys(
|
||||
lines.append("DOCKER_*: skipped (no docker track)")
|
||||
if copy_project:
|
||||
for key in COPY_ENV_KEYS:
|
||||
found = key_present(key, env_keys)
|
||||
found = key_present(key, env_keys, make_values)
|
||||
lines.append(f"{key}: {'present' if found else 'MISSING'}")
|
||||
if not found:
|
||||
missing.append(key)
|
||||
if "COPY_SCRIPT" in make_values and "COPY_SCRIPT" not in env_keys and not os.environ.get("COPY_SCRIPT"):
|
||||
lines[-1] += " (makefile.builder)"
|
||||
if not any(key_present(key, env_keys, make_values) for key in COPY_ENV_KEYS):
|
||||
missing.append("COPY_DEST or COPY_SCRIPT")
|
||||
check_copy_script(report, project, env_values, make_values)
|
||||
else:
|
||||
lines.append("COPY_*: skipped (no copy track)")
|
||||
if missing:
|
||||
if "COPY_DEST or COPY_SCRIPT" in missing:
|
||||
config_hints = [
|
||||
" COPY_DEST= # local/container destination, or",
|
||||
" COPY_SCRIPT=.pouch/builder/publish-apk.sh # choose one",
|
||||
]
|
||||
else:
|
||||
config_hints = [f" {key}=" for key in missing]
|
||||
lines.extend(
|
||||
[
|
||||
"",
|
||||
f"blocks publish, not build. Put keys in the environment or {BUILDER_ENV}:",
|
||||
*[f" {key}=" for key in missing],
|
||||
*config_hints,
|
||||
f"Do not commit {BUILDER_ENV}. Do not put these keys in `.env`. Never print values.",
|
||||
]
|
||||
)
|
||||
@@ -567,6 +768,7 @@ def check_script_paths(report: Report) -> None:
|
||||
home = Path(os.environ.get("HOME", ""))
|
||||
candidates.append(home / ".pouch" / "skills" / "builder" / "scripts")
|
||||
candidates.append(home / ".skills" / "skills" / "builder" / "scripts")
|
||||
candidates.append(home / ".agents" / "skills" / "builder" / "scripts")
|
||||
found = next((c for c in candidates if c.is_dir() and any((c / n).is_file() for n in VALID_SCRIPT_NAMES)), None)
|
||||
if found:
|
||||
report.add(PASS, 9, "builder 脚本路径可达", str(found))
|
||||
@@ -646,10 +848,16 @@ def main(argv: list[str] | None = None) -> int:
|
||||
report.add(SKIP, number, title, detail)
|
||||
docker_project = detect_docker_project(project)
|
||||
deb_project = any(project.glob("debian/*"))
|
||||
check_ready_toolchain(report, deb_project=deb_project, docker_project=docker_project)
|
||||
check_ready_toolchain(
|
||||
report,
|
||||
project,
|
||||
deb_project=deb_project,
|
||||
docker_project=docker_project,
|
||||
)
|
||||
check_ready_env_keys(
|
||||
report, project, deb_project=deb_project, docker_project=docker_project
|
||||
)
|
||||
check_ci_status_script(report, project, env_file_values(project), makefile_values(project) if (project / BUILDER_MAKEFILE).is_file() else {})
|
||||
print()
|
||||
print(f"RESULT: FAILED ({report.failures} check(s) failed)")
|
||||
return 1
|
||||
@@ -671,6 +879,8 @@ def main(argv: list[str] | None = None) -> int:
|
||||
"push-deb",
|
||||
"push-docker",
|
||||
"push-copy",
|
||||
"obtain",
|
||||
"venue",
|
||||
):
|
||||
result = run_make(project, target)
|
||||
if result.returncode == 0:
|
||||
@@ -732,6 +942,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
if args.ready:
|
||||
check_ready_toolchain(
|
||||
report,
|
||||
project,
|
||||
deb_project=deb_project,
|
||||
docker_project=docker_project,
|
||||
copy_project=copy_project,
|
||||
@@ -743,6 +954,12 @@ def main(argv: list[str] | None = None) -> int:
|
||||
docker_project=docker_project,
|
||||
copy_project=copy_project,
|
||||
)
|
||||
check_ci_status_script(
|
||||
report,
|
||||
project,
|
||||
env_file_values(project),
|
||||
makefile_values(project),
|
||||
)
|
||||
|
||||
total_fail = report.failures
|
||||
print()
|
||||
|
||||
@@ -6,12 +6,17 @@ usage() {
|
||||
Usage:
|
||||
COPY_DEST=/path/or/container:/dir \
|
||||
copy_artifact.sh FILE [FILE ...]
|
||||
COPY_SCRIPT=.pouch/builder/publish-apk.sh \
|
||||
copy_artifact.sh FILE [FILE ...]
|
||||
|
||||
Copy built artifacts to COPY_DEST. Dest is a local directory, or a Docker
|
||||
copy target `container:/absolute/dir` (docker cp). Does not read `.env`.
|
||||
Copy built artifacts using COPY_SCRIPT when configured; otherwise copy to
|
||||
COPY_DEST. COPY_DEST is a local directory or a Docker copy target
|
||||
`container:/absolute/dir` (docker cp). Does not read `.env`.
|
||||
|
||||
Environment (project root .env.builder; shell values win):
|
||||
COPY_DEST Required. Local dir or container:/dir
|
||||
COPY_DEST Optional fallback. Local dir or container:/dir
|
||||
COPY_SCRIPT Optional .pouch/builder/ relative path or absolute
|
||||
executable. Receives FILE paths as positional args.
|
||||
COPY_AS Optional. Extra basenames for the first file
|
||||
(comma or space separated)
|
||||
ALLOW_UNCOMMITTED=1 Publish despite a dirty working tree
|
||||
@@ -58,14 +63,20 @@ while (($#)); do
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ -z "$dest" || $# -eq 0 ]]; then
|
||||
echo "Error: COPY_DEST and at least one file are required." >&2
|
||||
echo "Set them in the environment or the project root .env.builder." >&2
|
||||
if [[ -z "$dest" && -z "${COPY_SCRIPT:-}" || $# -eq 0 ]]; then
|
||||
if [[ $# -eq 0 ]]; then
|
||||
echo "Error: at least one file is required." >&2
|
||||
else
|
||||
echo "Error: set COPY_DEST or COPY_SCRIPT." >&2
|
||||
fi
|
||||
echo "Set the value in the environment or the project root .env.builder." >&2
|
||||
usage >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [[ -n "$project_root" ]] && git -C "$project_root" rev-parse HEAD >/dev/null 2>&1; then
|
||||
# Refresh Git's cached stat data after build tools rewrite tracked files.
|
||||
git -C "$project_root" update-index -q --refresh 2>/dev/null || true
|
||||
if [[ ${ALLOW_UNCOMMITTED:-0} != 1 ]] && ! git -C "$project_root" diff-index --quiet HEAD -- 2>/dev/null; then
|
||||
echo "Error: working tree has uncommitted changes; refusing to publish." >&2
|
||||
echo "Commit first, or set ALLOW_UNCOMMITTED=1 to publish anyway." >&2
|
||||
@@ -73,6 +84,63 @@ if [[ -n "$project_root" ]] && git -C "$project_root" rev-parse HEAD >/dev/null
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -n "${COPY_SCRIPT:-}" ]]; then
|
||||
copy_script=$COPY_SCRIPT
|
||||
if [[ "$copy_script" != /* ]]; then
|
||||
relative_script=${copy_script#./}
|
||||
if [[ "$relative_script" != .pouch/builder/* || -z "$project_root" ]]; then
|
||||
echo "Error: relative COPY_SCRIPT must be under .pouch/builder/." >&2
|
||||
exit 2
|
||||
fi
|
||||
copy_script="$project_root/$relative_script"
|
||||
fi
|
||||
if [[ ! -f "$copy_script" ]]; then
|
||||
echo "Error: COPY_SCRIPT is not a file: $copy_script" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ ! -x "$copy_script" ]]; then
|
||||
echo "Error: COPY_SCRIPT is not executable: $copy_script" >&2
|
||||
exit 2
|
||||
fi
|
||||
artifact_args=()
|
||||
for src in "$@"; do
|
||||
if [[ ! -f "$src" ]]; then
|
||||
echo "Error: not a file: $src" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ "$src" == /* ]]; then
|
||||
artifact_args+=("$src")
|
||||
else
|
||||
artifact_args+=("$PWD/$src")
|
||||
fi
|
||||
done
|
||||
if $dry_run; then
|
||||
printf 'custom copy script:'
|
||||
printf ' %q' "$copy_script" "${artifact_args[@]}"
|
||||
printf '\n'
|
||||
exit 0
|
||||
fi
|
||||
export BUILDER_PROJECT_ROOT=${project_root:-}
|
||||
if "$copy_script" "${artifact_args[@]}"; then
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
for src in "${artifact_args[@]}"; do
|
||||
sha256sum -- "$src"
|
||||
done
|
||||
fi
|
||||
echo "copy_artifact: custom script completed for $# file(s)"
|
||||
exit 0
|
||||
else
|
||||
status=$?
|
||||
echo "Error: COPY_SCRIPT failed with exit code $status." >&2
|
||||
exit "$status"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -z "$dest" ]]; then
|
||||
echo "Error: COPY_DEST is required when COPY_SCRIPT is not configured." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
is_docker_dest() {
|
||||
local d=$1
|
||||
[[ "$d" != /* && "$d" != ./* && "$d" != ../* && "$d" != ~* ]] \
|
||||
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Copy a CI status template into the project.
|
||||
# Usage: init_ci_status.sh --root DIR --kind tea|glab|gh|curl
|
||||
|
||||
usage() {
|
||||
echo "Usage: init_ci_status.sh --root DIR --kind tea|glab|gh|curl" >&2
|
||||
}
|
||||
|
||||
root=
|
||||
kind=
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
--root) [[ $# -ge 2 ]] || { usage; exit 2; }; root=$2; shift 2 ;;
|
||||
--kind) [[ $# -ge 2 ]] || { usage; exit 2; }; kind=$2; shift 2 ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
*) usage; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ -z "$root" || -z "$kind" ]]; then
|
||||
usage
|
||||
exit 2
|
||||
fi
|
||||
case "$kind" in
|
||||
tea|glab|gh|curl) ;;
|
||||
*) echo "Error: --kind must be tea, glab, gh, or curl" >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||
src=$script_dir/../templates/ci-status/${kind}.sh
|
||||
if [[ ! -f "$src" ]]; then
|
||||
echo "Error: missing template: $src" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
dest=$root/.pouch/builder/ci-status.sh
|
||||
mkdir -p "$(dirname "$dest")"
|
||||
cp "$src" "$dest"
|
||||
chmod +x "$dest"
|
||||
echo "$dest"
|
||||
Executable
+197
@@ -0,0 +1,197 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Obtain a verified artifact for an exact git commit.
|
||||
# Build may have happened locally or in CI; this script only reports identity
|
||||
# after the artifact exists. Does not print tokens.
|
||||
#
|
||||
# Usage:
|
||||
# obtain.sh [--sha SHA] [--branch NAME] [--root DIR] [--timeout SEC]
|
||||
#
|
||||
# BUILD_VENUE (makefile.builder, default local):
|
||||
# local HEAD must be SHA; run `make -f makefile.builder docker` or `deb`
|
||||
# ci wait for this SHA via the project CI_STATUS_SCRIPT, then inspect the image
|
||||
#
|
||||
# Exit:
|
||||
# 0 artifact verified; prints ARTIFACT= / DIGEST= / SHA= / VENUE=
|
||||
# 1 no pipeline, job failed, inspect failed
|
||||
# 2 usage / config
|
||||
# 3 CI status script cannot query (ci venue)
|
||||
|
||||
usage() {
|
||||
sed -n '2,20p' "$0"
|
||||
}
|
||||
|
||||
sha=
|
||||
branch=
|
||||
root=
|
||||
timeout_sec=1200
|
||||
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
--sha) sha=$2; shift 2 ;;
|
||||
--branch) branch=$2; shift 2 ;;
|
||||
--root) root=$2; shift 2 ;;
|
||||
--timeout) timeout_sec=$2; shift 2 ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
*) echo "Error: unknown argument: $1" >&2; usage >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ -z "$root" ]]; then
|
||||
root=$(git rev-parse --show-toplevel 2>/dev/null || true)
|
||||
fi
|
||||
if [[ -z "$root" ]]; then
|
||||
echo "Error: --root must be a git project" >&2
|
||||
exit 2
|
||||
fi
|
||||
cd "$root"
|
||||
|
||||
if [[ -z "$sha" ]]; then
|
||||
sha=$(git rev-parse HEAD)
|
||||
else
|
||||
sha=$(git rev-parse "$sha")
|
||||
fi
|
||||
|
||||
# Load .env.builder without printing values; shell values win. Do not read `.env`.
|
||||
if [[ -f "$root/.env.builder" ]]; then
|
||||
while IFS='=' read -r key value; do
|
||||
key=${key%%[[:space:]]*}
|
||||
[[ -z "$key" || "$key" == \#* ]] && continue
|
||||
if [[ -n "${!key:-}" ]]; then
|
||||
continue
|
||||
fi
|
||||
value=${value%\"}; value=${value#\"}; value=${value%\'}; value=${value#\'}
|
||||
[[ -z "$value" ]] && continue
|
||||
printf -v "$key" '%s' "$value"
|
||||
export "$key"
|
||||
done < <(grep -v '^[[:space:]]*$' "$root/.env.builder")
|
||||
fi
|
||||
|
||||
script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||
version_sh=$script_dir/version.sh
|
||||
wait_ci=$script_dir/wait_ci.sh
|
||||
|
||||
venue=${BUILD_VENUE:-}
|
||||
registry=${DOCKER_REGISTRY:-}
|
||||
repository=${DOCKER_REPOSITORY:-}
|
||||
if [[ -f "$root/makefile.builder" ]]; then
|
||||
if [[ -z "$venue" ]]; then
|
||||
venue=$(make -s -C "$root" -f makefile.builder venue 2>/dev/null || true)
|
||||
fi
|
||||
if [[ -z "$registry" ]]; then
|
||||
registry=$(make -s -C "$root" -f makefile.builder print-DOCKER_REGISTRY 2>/dev/null || true)
|
||||
fi
|
||||
if [[ -z "$repository" ]]; then
|
||||
repository=$(make -s -C "$root" -f makefile.builder print-DOCKER_REPOSITORY 2>/dev/null || true)
|
||||
fi
|
||||
fi
|
||||
venue=${venue:-local}
|
||||
|
||||
docker_tag_for_sha() {
|
||||
local tmp tag
|
||||
tmp=$(mktemp -d "${TMPDIR:-/tmp}/builder-obtain.XXXXXX")
|
||||
git -C "$root" worktree add --detach "$tmp" "$sha" >/dev/null
|
||||
if [[ -n "$branch" ]]; then
|
||||
tag=$(CI_COMMIT_BRANCH="$branch" "$version_sh" -C "$tmp" --docker)
|
||||
else
|
||||
tag=$("$version_sh" -C "$tmp" --docker)
|
||||
fi
|
||||
git -C "$root" worktree remove --force "$tmp" >/dev/null
|
||||
printf '%s' "$tag"
|
||||
}
|
||||
|
||||
inspect_image() {
|
||||
local image=$1 out digest
|
||||
if ! command -v docker >/dev/null 2>&1; then
|
||||
echo "Error: docker is required to inspect $image" >&2
|
||||
exit 1
|
||||
fi
|
||||
out=$(docker buildx imagetools inspect "$image" 2>/dev/null \
|
||||
|| docker manifest inspect "$image" 2>/dev/null \
|
||||
|| true)
|
||||
if [[ -z "$out" ]]; then
|
||||
echo "Error: cannot inspect $image" >&2
|
||||
exit 1
|
||||
fi
|
||||
digest=$(printf '%s\n' "$out" | awk '/^Digest:/ {print $2; exit}')
|
||||
if [[ -z "$digest" ]]; then
|
||||
digest=$(python3 -c 'import json,sys
|
||||
try:
|
||||
d=json.load(sys.stdin)
|
||||
except Exception:
|
||||
sys.exit(0)
|
||||
print(d.get("digest") or "")' <<<"$out")
|
||||
fi
|
||||
if [[ -z "$digest" ]]; then
|
||||
echo "Error: inspect of $image had no digest" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s' "$digest"
|
||||
}
|
||||
|
||||
case "$venue" in
|
||||
ci)
|
||||
"$wait_ci" --sha "$sha" --root "$root" --timeout "$timeout_sec"
|
||||
if [[ ! -x "$version_sh" ]]; then
|
||||
echo "Error: version.sh not found: $version_sh" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ -z "$registry" || -z "$repository" ]]; then
|
||||
echo "Error: DOCKER_REGISTRY and DOCKER_REPOSITORY are required to inspect the CI image" >&2
|
||||
exit 2
|
||||
fi
|
||||
tag=$(docker_tag_for_sha)
|
||||
image="${registry}/${repository}:${tag}"
|
||||
digest=$(inspect_image "$image")
|
||||
echo "ARTIFACT=$image"
|
||||
echo "DIGEST=$digest"
|
||||
echo "SHA=$sha"
|
||||
echo "VENUE=ci"
|
||||
echo "TAG=$tag"
|
||||
;;
|
||||
local)
|
||||
head=$(git rev-parse HEAD)
|
||||
if [[ "$head" != "$sha" ]]; then
|
||||
echo "Error: local obtain requires HEAD=$sha (HEAD is $head)" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ ! -f "$root/makefile.builder" ]]; then
|
||||
echo "Error: no makefile.builder" >&2
|
||||
exit 2
|
||||
fi
|
||||
if make -s -C "$root" -f makefile.builder -n docker >/dev/null 2>&1; then
|
||||
make -C "$root" -f makefile.builder docker
|
||||
if [[ -n "${IMAGE_TAG:-}" ]]; then
|
||||
tag=$IMAGE_TAG
|
||||
elif [[ -x "$version_sh" ]]; then
|
||||
tag=$("$version_sh" --docker)
|
||||
else
|
||||
echo "Error: cannot derive IMAGE_TAG" >&2
|
||||
exit 2
|
||||
fi
|
||||
name=$(make -s -C "$root" -f makefile.builder print-PROJECT_NAME 2>/dev/null || basename "$root")
|
||||
image="${name}:${tag}"
|
||||
if [[ -n "$registry" && -n "$repository" ]]; then
|
||||
image="${registry}/${repository}:${tag}"
|
||||
fi
|
||||
echo "ARTIFACT=$image"
|
||||
echo "DIGEST=local"
|
||||
echo "SHA=$sha"
|
||||
echo "VENUE=local"
|
||||
echo "TAG=$tag"
|
||||
elif make -s -C "$root" -f makefile.builder -n deb >/dev/null 2>&1; then
|
||||
make -C "$root" -f makefile.builder deb
|
||||
echo "ARTIFACT=deb"
|
||||
echo "SHA=$sha"
|
||||
echo "VENUE=local"
|
||||
else
|
||||
echo "Error: local venue has no docker or deb target" >&2
|
||||
exit 2
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
echo "Error: BUILD_VENUE must be local or ci (got ${venue})" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -170,6 +170,7 @@ fi
|
||||
# Dirty-tree gate: publishing uncommitted content requires explicit opt-in.
|
||||
if [[ "$mode" == push && "$dry_run" == false && -n "$project_root" ]] \
|
||||
&& git -C "$project_root" rev-parse HEAD >/dev/null 2>&1; then
|
||||
git -C "$project_root" update-index -q --refresh 2>/dev/null || true
|
||||
if [[ ${ALLOW_UNCOMMITTED:-0} != 1 ]] && ! git -C "$project_root" diff-index --quiet HEAD -- 2>/dev/null; then
|
||||
echo "Error: working tree has uncommitted changes; refusing to publish." >&2
|
||||
echo "Commit first, or set ALLOW_UNCOMMITTED=1 to publish anyway." >&2
|
||||
|
||||
@@ -69,6 +69,7 @@ fi
|
||||
|
||||
# Dirty-tree gate: publishing uncommitted content requires explicit opt-in.
|
||||
if [[ -n "$project_root" ]] && git -C "$project_root" rev-parse HEAD >/dev/null 2>&1; then
|
||||
git -C "$project_root" update-index -q --refresh 2>/dev/null || true
|
||||
if [[ ${ALLOW_UNCOMMITTED:-0} != 1 ]] && ! git -C "$project_root" diff-index --quiet HEAD -- 2>/dev/null; then
|
||||
echo "Error: working tree has uncommitted changes; refusing to publish." >&2
|
||||
echo "Commit first, or set ALLOW_UNCOMMITTED=1 to publish anyway." >&2
|
||||
|
||||
Executable
+184
@@ -0,0 +1,184 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Poll the project CI status script until the exact SHA finishes.
|
||||
# Does not trigger a pipeline. Does not print tokens.
|
||||
#
|
||||
# Usage:
|
||||
# wait_ci.sh --sha SHA [--root DIR] [--timeout SEC]
|
||||
#
|
||||
# The project script is CI_STATUS_SCRIPT (makefile.builder, default
|
||||
# .pouch/builder/ci-status.sh). See references/ci-status.md.
|
||||
|
||||
usage() {
|
||||
sed -n '2,14p' "$0"
|
||||
}
|
||||
|
||||
sha=
|
||||
root=
|
||||
timeout_sec=1200
|
||||
poll_sec=${BUILDER_CI_POLL_SEC:-10}
|
||||
appear_sec=${BUILDER_CI_APPEAR_SEC:-90}
|
||||
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
--sha) [[ $# -ge 2 ]] || { echo "Error: --sha needs a value" >&2; exit 2; }; sha=$2; shift 2 ;;
|
||||
--root) [[ $# -ge 2 ]] || { echo "Error: --root needs a value" >&2; exit 2; }; root=$2; shift 2 ;;
|
||||
--timeout) [[ $# -ge 2 ]] || { echo "Error: --timeout needs a value" >&2; exit 2; }; timeout_sec=$2; shift 2 ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
*) echo "Error: unknown argument: $1" >&2; usage >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ -z "$root" ]]; then
|
||||
root=$(git rev-parse --show-toplevel 2>/dev/null || true)
|
||||
fi
|
||||
if [[ -z "$root" || ! -d "$root/.git" && ! -f "$root/.git" ]]; then
|
||||
echo "Error: --root must be a git project" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ -z "$sha" ]]; then
|
||||
echo "Error: --sha is required" >&2
|
||||
exit 2
|
||||
fi
|
||||
sha=$(git -C "$root" rev-parse "$sha")
|
||||
|
||||
if [[ -f "$root/.env.builder" ]]; then
|
||||
while IFS='=' read -r key value; do
|
||||
key=${key%%[[:space:]]*}
|
||||
[[ -z "$key" || "$key" == \#* ]] && continue
|
||||
[[ "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue
|
||||
if [[ -n "${!key:-}" ]]; then
|
||||
continue
|
||||
fi
|
||||
value=${value%\"}; value=${value#\"}; value=${value%\'}; value=${value#\'}
|
||||
[[ -z "$value" ]] && continue
|
||||
printf -v "$key" '%s' "$value"
|
||||
export "$key"
|
||||
done < <(grep -v '^[[:space:]]*$' "$root/.env.builder")
|
||||
fi
|
||||
|
||||
resolve_status_script() {
|
||||
local configured=${CI_STATUS_SCRIPT:-}
|
||||
if [[ -z "$configured" && -f "$root/makefile.builder" ]]; then
|
||||
configured=$(make -s --no-print-directory -C "$root" -f makefile.builder print-CI_STATUS_SCRIPT 2>/dev/null | tail -n 1 || true)
|
||||
fi
|
||||
configured=${configured:-.pouch/builder/ci-status.sh}
|
||||
local path
|
||||
if [[ "$configured" == /* ]]; then
|
||||
path=$configured
|
||||
else
|
||||
path=$root/$configured
|
||||
case "$configured" in
|
||||
.pouch/builder/*) ;;
|
||||
*)
|
||||
echo "Error: relative CI_STATUS_SCRIPT must be under .pouch/builder/: $configured" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
if [[ ! -f "$path" ]]; then
|
||||
echo "Error: CI status script missing: $path" >&2
|
||||
echo "Run builder init with BUILD_VENUE=ci to write .pouch/builder/ci-status.sh" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ ! -x "$path" ]]; then
|
||||
echo "Error: CI status script is not executable: $path" >&2
|
||||
exit 2
|
||||
fi
|
||||
printf '%s' "$path"
|
||||
}
|
||||
|
||||
parse_status() {
|
||||
python3 -c '
|
||||
import sys
|
||||
text = sys.stdin.read()
|
||||
values = {}
|
||||
for raw in text.replace("\n", " ").split():
|
||||
if "=" in raw:
|
||||
key, value = raw.split("=", 1)
|
||||
values[key.upper()] = value
|
||||
print(values.get("STATUS", "error").lower())
|
||||
print(values.get("ID", "-"))
|
||||
print(values.get("PIPELINE", "-"))
|
||||
print(values.get("JOBS", ""))
|
||||
'
|
||||
}
|
||||
|
||||
status_script=$(resolve_status_script)
|
||||
export BUILDER_PROJECT_ROOT=$root
|
||||
|
||||
query() {
|
||||
local out err rc
|
||||
err=$(mktemp)
|
||||
set +e
|
||||
out=$(BUILDER_PROJECT_ROOT="$root" "$status_script" --sha "$sha" 2>"$err")
|
||||
rc=$?
|
||||
set -e
|
||||
if [[ $rc -ne 0 ]]; then
|
||||
echo "Error: CI status script exited $rc" >&2
|
||||
sed '/token/Id; /Bearer/d; /Authorization/Id' "$err" >&2
|
||||
rm -f "$err"
|
||||
if [[ $rc -eq 2 ]]; then
|
||||
exit 2
|
||||
fi
|
||||
exit 3
|
||||
fi
|
||||
rm -f "$err"
|
||||
printf '%s' "$out"
|
||||
}
|
||||
|
||||
started=$(date +%s)
|
||||
first_seen=0
|
||||
empty_since=$started
|
||||
|
||||
while true; do
|
||||
now=$(date +%s)
|
||||
if (( now - started > timeout_sec )); then
|
||||
echo "FAIL reason=timeout sha=$sha" >&2
|
||||
exit 1
|
||||
fi
|
||||
raw=$(query)
|
||||
mapfile -t fields < <(printf '%s' "$raw" | parse_status)
|
||||
st=${fields[0]:-error}
|
||||
pid=${fields[1]:--}
|
||||
url=${fields[2]:--}
|
||||
jobs_s=${fields[3]:-}
|
||||
|
||||
case "$st" in
|
||||
empty)
|
||||
if (( now - empty_since >= appear_sec )); then
|
||||
echo "FAIL reason=no_pipeline sha=$sha" >&2
|
||||
echo "This SHA has no CI pipeline. Tag or push a ref the project actually builds." >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep "$poll_sec"
|
||||
continue
|
||||
;;
|
||||
error)
|
||||
echo "Error: unexpected CI status response" >&2
|
||||
echo "$raw" | sed '/token/Id; /Bearer/d; /Authorization/Id' >&2
|
||||
exit 3
|
||||
;;
|
||||
success)
|
||||
echo "OK pipeline=$url sha=$sha id=$pid jobs=$jobs_s"
|
||||
exit 0
|
||||
;;
|
||||
failed|failure|canceled|cancelled|skipped)
|
||||
echo "FAIL reason=job_${st} sha=$sha pipeline=$url jobs=$jobs_s" >&2
|
||||
exit 1
|
||||
;;
|
||||
running|pending|queued|waiting|in_progress|created|preparing)
|
||||
if [[ "$first_seen" -eq 0 ]]; then
|
||||
echo "Watching pipeline $pid status=$st $url" >&2
|
||||
first_seen=1
|
||||
fi
|
||||
empty_since=$now
|
||||
sleep "$poll_sec"
|
||||
;;
|
||||
*)
|
||||
empty_since=$now
|
||||
sleep "$poll_sec"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
Executable
+99
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Query Gitea Actions for an exact SHA via curl. Output STATUS= keys.
|
||||
# Auth: GITEA_TOKEN in the environment or .env.builder. GITEA_API_URL optional.
|
||||
|
||||
sha=
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
--sha) sha=$2; shift 2 ;;
|
||||
*) echo "Usage: ci-status.sh --sha SHA" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
[[ -n "$sha" ]] || { echo "Usage: ci-status.sh --sha SHA" >&2; exit 2; }
|
||||
|
||||
if ! command -v curl >/dev/null 2>&1; then
|
||||
echo "Error: curl is required" >&2
|
||||
exit 3
|
||||
fi
|
||||
|
||||
root=${BUILDER_PROJECT_ROOT:-$(git rev-parse --show-toplevel)}
|
||||
origin=$(git -C "$root" remote get-url origin 2>/dev/null || true)
|
||||
[[ -n "$origin" ]] || { echo "Error: no origin remote" >&2; exit 3; }
|
||||
|
||||
read -r host path base <<<"$(WAIT_CI_ORIGIN=$origin python3 -c '
|
||||
import os, re
|
||||
url = os.environ["WAIT_CI_ORIGIN"].strip()
|
||||
url = re.sub(r"^git@([^:]+):", r"ssh://git@\1/", url)
|
||||
url = re.sub(r"^ssh://git@([^/]+):", r"ssh://git@\1/", url)
|
||||
if re.match(r"^https?://", url):
|
||||
m = re.match(r"^(https?)://([^/]+)(?:/(.*))?$", url)
|
||||
scheme, host, path = (m.group(1), m.group(2), m.group(3) or "") if m else ("", "", "")
|
||||
else:
|
||||
m = re.match(r"^ssh://git@([^/]+)/(.+)$", url)
|
||||
scheme, host, path = ("https", m.group(1), m.group(2)) if m else ("", "", "")
|
||||
path = re.sub(r"\.git$", "", path)
|
||||
print(host, path, (scheme or "https") + "://" + host)
|
||||
')"
|
||||
api=${GITEA_API_URL:-$base/api/v1}
|
||||
api=${api%/}
|
||||
[[ "$api" == */api/v1 ]] || api+=/api/v1
|
||||
repo=$(WAIT_CI_PATH=$path python3 -c 'import os,urllib.parse; print(urllib.parse.quote(os.environ["WAIT_CI_PATH"], safe="/"))')
|
||||
|
||||
gitea_curl() {
|
||||
if [[ -n "${GITEA_TOKEN:-}" ]]; then
|
||||
curl -fsS --retry 2 --connect-timeout 10 --max-time 30 \
|
||||
--config <(printf 'header = "Authorization: token %s"\n' "$GITEA_TOKEN") "$1"
|
||||
else
|
||||
curl -fsS --retry 2 --connect-timeout 10 --max-time 30 "$1"
|
||||
fi
|
||||
}
|
||||
|
||||
set +e
|
||||
runs=$(gitea_curl "${api}/repos/${repo}/actions/runs?head_sha=${sha}&limit=20&page=1")
|
||||
rc=$?
|
||||
set -e
|
||||
if [[ $rc -ne 0 ]]; then
|
||||
echo "Error: curl cannot read Gitea Actions for $path" >&2
|
||||
exit 3
|
||||
fi
|
||||
|
||||
python3 -c '
|
||||
import json, sys
|
||||
sha = sys.argv[1]
|
||||
try:
|
||||
data = json.loads(sys.stdin.read())
|
||||
except json.JSONDecodeError:
|
||||
print("STATUS=error")
|
||||
raise SystemExit(0)
|
||||
if isinstance(data, dict) and data.get("message") and not (data.get("workflow_runs") or data.get("runs")):
|
||||
print("STATUS=error")
|
||||
raise SystemExit(0)
|
||||
runs = data.get("workflow_runs", data.get("runs", [])) if isinstance(data, dict) else data
|
||||
if not isinstance(runs, list) or not runs:
|
||||
print("STATUS=empty")
|
||||
raise SystemExit(0)
|
||||
matched = []
|
||||
for run in runs:
|
||||
head = run.get("head_sha") or run.get("headSha") or (run.get("head_commit") or {}).get("id")
|
||||
if head and head.lower() == sha.lower() and (run.get("id") or run.get("database_id")):
|
||||
matched.append(run)
|
||||
if not matched:
|
||||
print("STATUS=empty")
|
||||
raise SystemExit(0)
|
||||
run = matched[0]
|
||||
run_id = run.get("id") or run.get("database_id")
|
||||
url = run.get("html_url") or run.get("web_url") or run.get("url") or "-"
|
||||
status = str(run.get("status") or "").lower()
|
||||
conclusion = str(run.get("conclusion") or run.get("result") or "").lower()
|
||||
if conclusion in ("failure", "failed", "cancelled", "canceled", "skipped", "timed_out"):
|
||||
state = "failed"
|
||||
elif status in ("completed", "success") and conclusion in ("", "success", "succeeded"):
|
||||
state = "success"
|
||||
elif status == "completed" and conclusion:
|
||||
state = "failed"
|
||||
else:
|
||||
state = "running"
|
||||
print("STATUS=%s ID=%s PIPELINE=%s" % (state, run_id, url))
|
||||
' "$sha" <<<"$runs"
|
||||
Executable
+66
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Query GitHub Actions for an exact SHA via gh. Output STATUS= keys.
|
||||
|
||||
sha=
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
--sha) sha=$2; shift 2 ;;
|
||||
*) echo "Usage: ci-status.sh --sha SHA" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
[[ -n "$sha" ]] || { echo "Usage: ci-status.sh --sha SHA" >&2; exit 2; }
|
||||
|
||||
if ! command -v gh >/dev/null 2>&1; then
|
||||
echo "Error: gh is required" >&2
|
||||
exit 3
|
||||
fi
|
||||
|
||||
root=${BUILDER_PROJECT_ROOT:-$(git rev-parse --show-toplevel)}
|
||||
origin=$(git -C "$root" remote get-url origin 2>/dev/null || true)
|
||||
[[ -n "$origin" ]] || { echo "Error: no origin remote" >&2; exit 3; }
|
||||
repo=$(WAIT_CI_ORIGIN=$origin python3 -c '
|
||||
import os, re
|
||||
url = os.environ["WAIT_CI_ORIGIN"].strip()
|
||||
url = re.sub(r"^git@([^:]+):", r"ssh://git@\1/", url)
|
||||
url = re.sub(r"^ssh://git@([^/]+):", r"ssh://git@\1/", url)
|
||||
if re.match(r"^https?://", url):
|
||||
m = re.match(r"^https?://[^/]+(?:/(.*))?$", url)
|
||||
path = m.group(1) if m else ""
|
||||
else:
|
||||
m = re.match(r"^ssh://git@[^/]+/(.+)$", url)
|
||||
path = m.group(1) if m else ""
|
||||
print(re.sub(r"\.git$", "", path or ""))
|
||||
')
|
||||
|
||||
set +e
|
||||
raw=$(gh run list --repo "$repo" --commit "$sha" --limit 20 --json databaseId,status,conclusion,url,headSha)
|
||||
rc=$?
|
||||
set -e
|
||||
if [[ $rc -ne 0 ]]; then
|
||||
echo "Error: gh cannot list runs for $repo" >&2
|
||||
exit 3
|
||||
fi
|
||||
|
||||
python3 -c '
|
||||
import json, sys
|
||||
try:
|
||||
data = json.loads(sys.stdin.read())
|
||||
except json.JSONDecodeError:
|
||||
print("STATUS=error")
|
||||
raise SystemExit(0)
|
||||
if not data:
|
||||
print("STATUS=empty")
|
||||
raise SystemExit(0)
|
||||
r = data[0]
|
||||
status = str(r.get("status") or "").lower()
|
||||
conc = str(r.get("conclusion") or "").lower()
|
||||
if status == "completed" and conc == "success":
|
||||
state = "success"
|
||||
elif status == "completed":
|
||||
state = "failed"
|
||||
else:
|
||||
state = "running"
|
||||
print("STATUS=%s ID=%s PIPELINE=%s" % (state, r.get("databaseId") or "-", r.get("url") or "-"))
|
||||
' <<<"$raw"
|
||||
Executable
+71
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Query GitLab CI for an exact SHA via glab. Output STATUS= keys.
|
||||
|
||||
sha=
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
--sha) sha=$2; shift 2 ;;
|
||||
*) echo "Usage: ci-status.sh --sha SHA" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
[[ -n "$sha" ]] || { echo "Usage: ci-status.sh --sha SHA" >&2; exit 2; }
|
||||
|
||||
if ! command -v glab >/dev/null 2>&1; then
|
||||
echo "Error: glab is required" >&2
|
||||
exit 3
|
||||
fi
|
||||
|
||||
root=${BUILDER_PROJECT_ROOT:-$(git rev-parse --show-toplevel)}
|
||||
origin=$(git -C "$root" remote get-url origin 2>/dev/null || true)
|
||||
[[ -n "$origin" ]] || { echo "Error: no origin remote" >&2; exit 3; }
|
||||
path=$(WAIT_CI_ORIGIN=$origin python3 -c '
|
||||
import os, re
|
||||
url = os.environ["WAIT_CI_ORIGIN"].strip()
|
||||
url = re.sub(r"^git@([^:]+):", r"ssh://git@\1/", url)
|
||||
url = re.sub(r"^ssh://git@([^/]+):", r"ssh://git@\1/", url)
|
||||
if re.match(r"^https?://", url):
|
||||
m = re.match(r"^https?://[^/]+(?:/(.*))?$", url)
|
||||
path = m.group(1) if m else ""
|
||||
else:
|
||||
m = re.match(r"^ssh://git@[^/]+/(.+)$", url)
|
||||
path = m.group(1) if m else ""
|
||||
print(re.sub(r"\.git$", "", path or ""))
|
||||
')
|
||||
encoded=$(WAIT_CI_PATH=$path python3 -c 'import os,urllib.parse; print(urllib.parse.quote(os.environ["WAIT_CI_PATH"], safe=""))')
|
||||
|
||||
set +e
|
||||
raw=$(glab api "projects/${encoded}/pipelines?sha=${sha}&per_page=20")
|
||||
rc=$?
|
||||
set -e
|
||||
if [[ $rc -ne 0 ]]; then
|
||||
echo "Error: glab cannot list pipelines for $path" >&2
|
||||
exit 3
|
||||
fi
|
||||
|
||||
python3 -c '
|
||||
import json, sys
|
||||
try:
|
||||
data = json.loads(sys.stdin.read())
|
||||
except json.JSONDecodeError:
|
||||
print("STATUS=error")
|
||||
raise SystemExit(0)
|
||||
if isinstance(data, dict) and data.get("message"):
|
||||
print("STATUS=error")
|
||||
raise SystemExit(0)
|
||||
if not isinstance(data, list) or not data:
|
||||
print("STATUS=empty")
|
||||
raise SystemExit(0)
|
||||
p = data[0]
|
||||
st = str(p.get("status") or "").lower()
|
||||
if st in ("success", "passed"):
|
||||
state = "success"
|
||||
elif st in ("failed", "canceled", "cancelled", "skipped"):
|
||||
state = "failed"
|
||||
elif st in ("",):
|
||||
state = "empty"
|
||||
else:
|
||||
state = "running"
|
||||
print("STATUS=%s ID=%s PIPELINE=%s" % (state, p.get("id") or "-", p.get("web_url") or "-"))
|
||||
' <<<"$raw"
|
||||
Executable
+80
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Query Gitea Actions for an exact SHA via tea. Output STATUS= keys.
|
||||
|
||||
sha=
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
--sha) sha=$2; shift 2 ;;
|
||||
*) echo "Usage: ci-status.sh --sha SHA" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
[[ -n "$sha" ]] || { echo "Usage: ci-status.sh --sha SHA" >&2; exit 2; }
|
||||
|
||||
if ! command -v tea >/dev/null 2>&1; then
|
||||
echo "Error: tea is required" >&2
|
||||
exit 3
|
||||
fi
|
||||
|
||||
root=${BUILDER_PROJECT_ROOT:-$(git rev-parse --show-toplevel)}
|
||||
origin=$(git -C "$root" remote get-url origin 2>/dev/null || true)
|
||||
[[ -n "$origin" ]] || { echo "Error: no origin remote" >&2; exit 3; }
|
||||
path=$(WAIT_CI_ORIGIN=$origin python3 -c '
|
||||
import os, re
|
||||
url = os.environ["WAIT_CI_ORIGIN"].strip()
|
||||
url = re.sub(r"^git@([^:]+):", r"ssh://git@\1/", url)
|
||||
url = re.sub(r"^ssh://git@([^/]+):", r"ssh://git@\1/", url)
|
||||
if re.match(r"^https?://", url):
|
||||
m = re.match(r"^https?://[^/]+(?:/(.*))?$", url)
|
||||
path = m.group(1) if m else ""
|
||||
else:
|
||||
m = re.match(r"^ssh://git@[^/]+/(.+)$", url)
|
||||
path = m.group(1) if m else ""
|
||||
print(re.sub(r"\.git$", "", path or ""))
|
||||
')
|
||||
[[ -n "$path" ]] || { echo "Error: cannot parse origin" >&2; exit 3; }
|
||||
|
||||
set +e
|
||||
runs=$(tea api "repos/${path}/actions/runs?head_sha=${sha}&limit=20")
|
||||
rc=$?
|
||||
set -e
|
||||
if [[ $rc -ne 0 ]]; then
|
||||
echo "Error: tea cannot read Actions for $path" >&2
|
||||
exit 3
|
||||
fi
|
||||
|
||||
python3 -c '
|
||||
import json, sys
|
||||
sha = sys.argv[1]
|
||||
try:
|
||||
data = json.loads(sys.stdin.read())
|
||||
except json.JSONDecodeError:
|
||||
print("STATUS=error")
|
||||
raise SystemExit(0)
|
||||
if isinstance(data, dict) and data.get("message") and not (data.get("workflow_runs") or data.get("runs")):
|
||||
print("STATUS=error")
|
||||
raise SystemExit(0)
|
||||
runs = data.get("workflow_runs", data.get("runs", [])) if isinstance(data, dict) else data
|
||||
if not isinstance(runs, list) or not runs:
|
||||
print("STATUS=empty")
|
||||
raise SystemExit(0)
|
||||
matched = [run for run in runs if str(run.get("head_sha") or run.get("headSha") or "").lower() == sha.lower()]
|
||||
if not matched:
|
||||
print("STATUS=empty")
|
||||
raise SystemExit(0)
|
||||
run = matched[0]
|
||||
run_id = run.get("id") or run.get("database_id") or "-"
|
||||
url = run.get("html_url") or run.get("web_url") or run.get("url") or "-"
|
||||
status = str(run.get("status") or "").lower()
|
||||
conclusion = str(run.get("conclusion") or run.get("result") or "").lower()
|
||||
if conclusion in ("failure", "failed", "cancelled", "canceled", "skipped", "timed_out"):
|
||||
state = "failed"
|
||||
elif status in ("completed", "success") and conclusion in ("", "success", "succeeded"):
|
||||
state = "success"
|
||||
elif status == "completed" and conclusion:
|
||||
state = "failed"
|
||||
else:
|
||||
state = "running"
|
||||
print("STATUS=%s ID=%s PIPELINE=%s" % (state, run_id, url))
|
||||
' "$sha" <<<"$runs"
|
||||
@@ -11,5 +11,8 @@
|
||||
# DOCKER_REPOSITORY=
|
||||
# IMAGE_TAG=
|
||||
# PLATFORMS= # optional override; project ARCHES lives in makefile.builder
|
||||
# COPY_DEST= # local dir, or docker dest container:/absolute/dir
|
||||
# GITEA_API_URL= # optional for the curl CI status script
|
||||
# GITEA_TOKEN= # optional token for private Gitea repositories
|
||||
# COPY_DEST= # fallback: local dir, or docker dest container:/absolute/dir
|
||||
# COPY_SCRIPT= # external/temporary executable override; project-local paths belong in makefile.builder
|
||||
# COPY_AS= # optional extra basenames for the first file
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# Builder 契约文件。放到项目根,用 `make -f makefile.builder <target>`。
|
||||
# Android 轨道:build 产出 dist/<name>_<version>_<arch>.apk,push 走 copy_artifact.sh。
|
||||
# copy_artifact.sh 会按 COPY_SCRIPT 分发;未配置时回退到 COPY_DEST。
|
||||
# ARCHES 是构建机 ISA;APK 可含多 ABI。不要把这些目标写进用户 Makefile。
|
||||
|
||||
ARCHES ?= amd64
|
||||
@@ -35,7 +36,7 @@ help:
|
||||
@echo " make -f makefile.builder version - 打印规范版本"
|
||||
@echo " make -f makefile.builder arches - 打印架构清单"
|
||||
@echo " make -f makefile.builder clean - 删除 $(DIST_DIR)"
|
||||
@echo " make -f makefile.builder push - copy_artifact.sh 拷到 COPY_DEST"
|
||||
@echo " make -f makefile.builder push - copy_artifact.sh 分发 APK"
|
||||
|
||||
version:
|
||||
@echo $(VERSION)
|
||||
|
||||
@@ -8,6 +8,10 @@
|
||||
|
||||
ARCHES ?= amd64
|
||||
ARCH ?= $(firstword $(ARCHES))
|
||||
# local: make docker/deb on this machine. ci: obtain.sh polls
|
||||
# CI_STATUS_SCRIPT for an exact SHA, then inspects the artifact. Not a track.
|
||||
BUILD_VENUE ?= local
|
||||
CI_STATUS_SCRIPT ?= .pouch/builder/ci-status.sh
|
||||
ifeq ($(strip $(ARCHES)),)
|
||||
$(error ARCHES must not be empty)
|
||||
endif
|
||||
@@ -28,13 +32,16 @@ DIST_DIR ?= dist
|
||||
|
||||
ifneq ($(BUILDER_SKILL_DIR),)
|
||||
include $(BUILDER_SKILL_DIR)/scripts/version.mk
|
||||
else
|
||||
BUILDER_SCRIPTS := $(BUILDER_SKILL_DIR)/scripts
|
||||
else ifneq ($(wildcard $(HOME)/.pouch/skills/builder/scripts/version.mk),)
|
||||
include $(HOME)/.pouch/skills/builder/scripts/version.mk
|
||||
BUILDER_SCRIPTS := $(HOME)/.pouch/skills/builder/scripts
|
||||
else
|
||||
include $(HOME)/.agents/skills/builder/scripts/version.mk
|
||||
BUILDER_SCRIPTS := $(HOME)/.agents/skills/builder/scripts
|
||||
endif
|
||||
|
||||
BUILDER_SCRIPTS := $(or $(BUILDER_SKILL_DIR),$(HOME)/.pouch/skills/builder)/scripts
|
||||
|
||||
.PHONY: help version arches clean build deb docker push push-deb push-docker
|
||||
.PHONY: help version arches venue clean build deb docker obtain push push-deb push-docker
|
||||
|
||||
help:
|
||||
@echo "$(PROJECT_NAME) $(VERSION)"
|
||||
@@ -45,6 +52,7 @@ help:
|
||||
@echo " make -f makefile.builder clean - 删除 $(DIST_DIR)"
|
||||
@echo " make -f makefile.builder deb - 打 DEB(按 ARCHES;只构建不上传)"
|
||||
@echo " make -f makefile.builder docker - 本地单平台镜像"
|
||||
@echo " make -f makefile.builder obtain - 按 BUILD_VENUE 拿到产物"
|
||||
@echo " make -f makefile.builder push / push-deb / push-docker"
|
||||
|
||||
version:
|
||||
@@ -53,6 +61,12 @@ version:
|
||||
arches:
|
||||
@echo $(ARCHES)
|
||||
|
||||
venue:
|
||||
@echo $(BUILD_VENUE)
|
||||
|
||||
print-%:
|
||||
@echo $($*)
|
||||
|
||||
clean:
|
||||
rm -rf $(DIST_DIR)
|
||||
|
||||
@@ -83,7 +97,13 @@ docker:
|
||||
push-deb:
|
||||
$(BUILDER_SCRIPTS)/upload_deb.sh $(foreach a,$(_PUSH_DEB_ARCHES),$(DIST_DIR)/$(PROJECT_NAME)_$(VERSION)_$(a).deb)
|
||||
|
||||
ifdef _ARCH_FROM_FILE
|
||||
obtain:
|
||||
$(BUILDER_SCRIPTS)/obtain.sh
|
||||
|
||||
ifeq ($(BUILD_VENUE),ci)
|
||||
push-docker:
|
||||
$(BUILDER_SCRIPTS)/obtain.sh
|
||||
else ifdef _ARCH_FROM_FILE
|
||||
push-docker:
|
||||
$(BUILDER_SCRIPTS)/publish_docker.sh
|
||||
else
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# Builder 契约文件。放到项目根,用 `make -f makefile.builder <target>`。
|
||||
# iOS 轨道:build 产出 dist/<name>_<version>_<arch>.ipa,push 走 copy_artifact.sh。
|
||||
# copy_artifact.sh 会按 COPY_SCRIPT 分发;未配置时回退到 COPY_DEST。
|
||||
# ARCHES 是构建机 ISA。不要把这些目标写进用户 Makefile。
|
||||
|
||||
ARCHES ?= arm64
|
||||
@@ -35,7 +36,7 @@ help:
|
||||
@echo " make -f makefile.builder version - 打印规范版本"
|
||||
@echo " make -f makefile.builder arches - 打印架构清单"
|
||||
@echo " make -f makefile.builder clean - 删除 $(DIST_DIR)"
|
||||
@echo " make -f makefile.builder push - copy_artifact.sh 拷到 COPY_DEST"
|
||||
@echo " make -f makefile.builder push - copy_artifact.sh 分发 IPA"
|
||||
|
||||
version:
|
||||
@echo $(VERSION)
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# delivery-loop
|
||||
|
||||
供其他交付类 skill 复用的状态机,统一处理验证、PR、合并、回归、构建和部署的顺序与安全门。
|
||||
|
||||
## 什么时候使用
|
||||
|
||||
通常由 `$short-ship`、`$pr-ship` 或 `$long-ship` 派发的 worker 读取,不需要单独调用。
|
||||
入口主会话不要把本 skill 读进自己的上下文。
|
||||
|
||||
```text
|
||||
按 delivery-loop 把当前 ship 推进到 review_ready。
|
||||
```
|
||||
|
||||
## 使用前准备
|
||||
|
||||
- 入口已绑定 ship id 时,同时安装 `ship`,证据指针写进该记录。
|
||||
- 项目已有有效的 ACK delivery profile 或等价交付配置。
|
||||
- 已明确任务的目标分支、测试范围和允许的停止点。
|
||||
- 需要外部写入时,当前请求已经授权对应动作。
|
||||
|
||||
## Agent 会做什么
|
||||
|
||||
按配置推进任务,逐阶段记录验证证据;遇到缺配置、失败或高风险变更时停止,不自动猜测。
|
||||
|
||||
## 如何判断完成
|
||||
|
||||
最终报告会明确停在 PR、合并、回归、产物或部署中的哪一状态,并给出可复核证据。
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
name: delivery-loop
|
||||
description: >-
|
||||
为修复、PR 和需求任务提供可配置的验证、发 PR、合并、回归、构建、发布与部署状态机。
|
||||
仅作为 short-ship、pr-ship、long-ship 的共享执行规则使用。
|
||||
---
|
||||
|
||||
# Delivery Loop:共享交付状态机
|
||||
|
||||
这是三个交付入口共用的内部规则,不直接替用户选择生产发布,也不替项目保存环境事实。
|
||||
|
||||
## 使用方式
|
||||
|
||||
由 `short-ship` / `long-ship` / `pr-ship` **派出来的 worker** 读取本 skill 和
|
||||
`references/state-machine.md`。入口主会话不要读取或执行本 skill。
|
||||
|
||||
入口决定任务类型、停止点和派哪一步;本 skill 负责该步的阶段要求、证据和安全门。
|
||||
|
||||
## 不可违反的规则
|
||||
|
||||
- 复用现有 `hunt`、`tester`、`check`、`builder`、`deployer`、`releaser` 和
|
||||
`orchestration` 能力;不要在本 skill 里复制它们的实现。`artifact_built` 只调用
|
||||
builder `obtain.sh`,不要在本 skill 里 poll GitLab/GitHub。
|
||||
- 先读取项目的 delivery profile、分支策略和当前工作树,再决定可执行的停止点。
|
||||
- `stopAt` 未配置或与用户目标冲突时停止并报告缺口,不猜测是否应合并或部署。
|
||||
- 提交、推送、合并、打 tag、发布产物和生产部署都必须同时满足项目配置与当前请求的授权。
|
||||
- 不绕过审核、CI、测试失败、脏工作树、冲突、未确认的迁移或不可回滚的外部变更。
|
||||
- 每个阶段都保存可复核证据;没有证据不得把阶段标为完成。入口已绑定 `ship-id` 时,把
|
||||
指针写入 `.pouch/ship/<id>/current.yaml` 的 `evidence`(规则见 ship `record.md`);
|
||||
缺指针则该阶段未完成。
|
||||
- 失败时保留现场和回滚信息,不用重试掩盖失败,不伪造发布或部署成功。
|
||||
|
||||
## 结果
|
||||
|
||||
完成时返回状态机最终状态、停止点、变更 commit、PR/tag、测试与回归证据、产物摘要、部署
|
||||
目标和回滚指针。若停在中间状态,明确下一步和阻塞原因。
|
||||
@@ -0,0 +1,6 @@
|
||||
interface:
|
||||
display_name: "Delivery Loop"
|
||||
short_description: "Shared delivery state machine for workflow skills"
|
||||
default_prompt: "Use $delivery-loop to inspect a delivery workflow state and its safe stopping point."
|
||||
policy:
|
||||
allow_implicit_invocation: false
|
||||
@@ -0,0 +1,62 @@
|
||||
# Delivery Loop 状态机
|
||||
|
||||
## 状态
|
||||
|
||||
```text
|
||||
change_ready -> verified -> pr_opened -> merged -> regression_passed -> artifact_built -> published -> deployed
|
||||
```
|
||||
|
||||
入口可以从已有状态开始,但不能跳过本次变更所需的验证。内部里程碑可以更细,但项目
|
||||
Ship 配置使用以下 canonical `stopAt`:
|
||||
|
||||
- `develop_verified`:开发阶段验证完成,包含单元测试、新增功能集成测试和静态检查;不等于完整回归。
|
||||
- `review_ready`:PR/MR 已创建,等待审核。
|
||||
- `release_ready`:PR 已合并且完整回归通过,映射内部 `regression_passed`;不表示已发布或部署。
|
||||
- `released`:产物已构建并发布,映射内部 `published`。
|
||||
- `deployed`:目标环境实际部署完成,映射内部 `deployed`。
|
||||
|
||||
旧记录可继续使用 `verified`(`develop_verified` 的别名)和 `validation_ready`
|
||||
(`release_ready` 的别名);新记录应使用 canonical 名称。
|
||||
|
||||
入口 skill 的自然语言停止点映射如下:
|
||||
|
||||
| 用户目标 | Ship stopAt | 必要内部里程碑 |
|
||||
| --- | --- | --- |
|
||||
| 只做开发验证 | `develop_verified` | `verified` |
|
||||
| 发 PR | `review_ready` | `pr_opened`,必要时预览构建/测试 |
|
||||
| 合并后完整回归 | `release_ready` | `merged`、`regression_passed` |
|
||||
| 构建并发布产物 | `released` | `merged`、`regression_passed`、`artifact_built`、`published` |
|
||||
| 实际部署 | `deployed` | `merged`、`regression_passed`、`artifact_built`、`published`、`deployed` |
|
||||
|
||||
## 每个阶段的要求
|
||||
|
||||
- `change_ready`:记录基线 commit、工作树、目标分支、任务范围和风险。
|
||||
- `verified`:开发阶段根因或需求验收明确;任务相关单元测试、新增功能集成测试和静态检查通过。
|
||||
- `pr_opened`:提交说明、测试证据、风险和回滚信息已写入 PR;不能把草稿 PR 当 `review_ready`。
|
||||
- `merged`:目标分支的合并 commit 已确认,不能只确认源分支 commit。
|
||||
- `regression_passed`:以合并 commit 执行项目规定的完整回归;失败则回到修复或停止。
|
||||
回归 worker 必须先发现项目及其子项目的 tester catalog(使用
|
||||
`catalog.py roots --root <project-root>`),逐个测试根执行并记录独立快照;父仓库
|
||||
没有 catalog 不能遮蔽有 catalog 的 `app` 子项目。任一发现的测试根未执行或无证据,
|
||||
不得把阶段标为 `regression_passed`。还必须执行项目 profile 或
|
||||
`.pouch/ack/project.md` 声明的项目原生测试套件,并为每个套件记录命令和结果;任一
|
||||
测试面缺少结果时都不能通过回归。
|
||||
- `artifact_built`:对**合并后的精确 commit SHA** 调用 builder `obtain.sh`。`BUILD_VENUE=ci` 时监听该 SHA 的流水线并 inspect 产物,不在本机重新编译。无流水线、job 失败或 digest 对不上则本阶段失败,不得进入 `published`。项目若声明默认分支不构建,合进 `main` 会 `no_pipeline`:预览推 `dev/*`,正式打 tag。
|
||||
- `published`:镜像/APK 等外部分发位置可复核,记录 digest 或文件校验和。`venue=ci` 且 CI 已经 push 到 registry 时,obtain 成功即同时满足本阶段,不要再本机 `publish_docker.sh`。
|
||||
- `deployed`:目标服务运行在预期版本,健康检查和关键路径验证通过。
|
||||
|
||||
## 配置和授权
|
||||
|
||||
读取项目自己的 delivery 配置,不把命令、主机、秘密复制到通用 skill。优先使用 ACK
|
||||
的 `delivery.yaml`、builder/deployer/tester 契约和项目版本策略;缺失时停止在最近的安全状态。
|
||||
|
||||
生产部署必须同时满足:项目 profile 允许、目标明确、构建来源已固定、回归证据完整、当前
|
||||
请求覆盖生产部署。没有这些条件时只能报告,而不能用“用户之前说过发布”替代当前授权。
|
||||
|
||||
## 证据账本
|
||||
|
||||
至少记录:基线和最终 commit、工作树状态、测试命令及结果、黑盒/真机证据、PR/MR URL、
|
||||
合并 commit、tag、产物路径与摘要、部署节点/服务、健康检查、失败项和回滚指针。
|
||||
|
||||
已绑定 ship 记录时,上述证据以指针写入该 ship 的 `current.yaml`,不要另建一份账本。
|
||||
阶段与字段对应见 ship `references/record.md`。
|
||||
+13
-10
@@ -5,19 +5,20 @@
|
||||
支持三种用法:
|
||||
|
||||
- **独立配置中心**:一个专门的 Git 仓库管所有机器的所有 Compose 服务(如 app00)
|
||||
- **项目内 Compose 环境**:在普通项目里放 `.pouch/deployer/{prod,test,dev}/`,
|
||||
把这个项目的生产/测试/开发环境用 rsync + docker compose 部署
|
||||
- **项目内 Compose 环境**:在普通项目里放 `.pouch/deployer/{prod,test,dev}/`;测试环境在本机
|
||||
触发 Compose,正式环境委派给本机 `~/code/app00` 项目的 Agent terminal,非正式远程环境才用
|
||||
rsync + docker compose
|
||||
- **Argo CD / GitOps**:项目里放 `.pouch/deployer/argocd.yaml`;Agent 改 GitOps 并开 MR,
|
||||
你合并后由 Argo CD 同步。仓库既可以只写 Git 地址(部署时浅 clone),也可以指定本机已有目录。
|
||||
|
||||
## 什么时候使用
|
||||
|
||||
- 给新项目初始化 deployer:检查缺什么,引导补 `.pouch/deployer/`
|
||||
- 想用一套固定流程把本地改好的 Docker Compose 配置发到某台服务器
|
||||
- 想用一套固定流程更新测试环境,或把正式部署委派给本机 `~/code/app00` 的 Agent
|
||||
- 要升级某个服务的镜像版本、重启服务、看远程容器状态和日志
|
||||
- 有编译好的 .deb 包要装到某台机器上(scp 上传安装,或从 URL 直接拉)
|
||||
- 新加一个服务、把服务从一台机器挪到另一台、或下线旧服务
|
||||
- 想给当前项目加 prod/test/dev 三套远程环境并随时部署其中一套
|
||||
- 想给当前项目加 prod/test/dev 三套环境并随时部署其中一套
|
||||
- ACK 说「重新布测试环境」或跑回归前要先拉起 `.pouch/deployer/test`
|
||||
- 需要一张「哪台机器跑哪些服务」的清单
|
||||
- 镜像要进 Kubernetes,走 Argo CD:改 GitOps、开 MR、合并后部署
|
||||
@@ -33,7 +34,7 @@ pouch add deployer -g # 全局
|
||||
|
||||
## 使用前准备
|
||||
|
||||
- Compose:本机 Python 3、`ssh`;有 `rsync` 更好,没有则 sync 用 `scp` 兜底;目标机器 Docker Compose v2;`~/.ssh/config` 免密(或 agent)
|
||||
- Compose:本机 Python 3、Docker Compose v2;测试只需本机 Docker,非正式远程环境才需要 `ssh`/`rsync`(无 rsync 时 sync 用 `scp` 兜底)
|
||||
- 知道每个 Compose 服务的运行时数据放在哪(这些目录不能被同步覆盖)
|
||||
- Argo CD:能 clone/push GitOps 仓库(SSH 或已登录的 HTTPS),并能开 MR(GitLab `glab` / GitHub `gh` / Gitea `tea`)。本机不必长期放一份 GitOps checkout。
|
||||
|
||||
@@ -72,8 +73,9 @@ GitOps 我已经 clone 在 ../infra-gitops,用那个目录开 MR
|
||||
|
||||
1. 读服务/环境目录(及共享的父目录)的 `_config.yaml`,确定目标机器和远程路径;
|
||||
项目内布局从 `.pouch/deployer/` 自动发现,无需额外配置
|
||||
2. 目标是本机且镜像已在本机 docker:不 sync、不 SSH,在该环境目录直接 `docker compose`
|
||||
3. 否则用 skill 自带脚本把本地目录同步到远程(优先 rsync,没有则 scp;自动排除 `data/`、`_data/`),再远程 `docker compose`(启动 / 重建 / 升级 / 重启)
|
||||
2. 测试目标是本机且镜像已在本机 docker:不 sync、不 SSH,在该环境目录直接 `docker compose`
|
||||
3. 正式目标:在本机 `~/code/app00` 创建 fresh Agent terminal,由该 Agent 执行 app00 的正式入口;当前 Agent 不直接 SSH
|
||||
4. 其它非正式远程目标:用 skill 自带脚本把本地目录同步到远程(优先 rsync,没有则 scp;自动排除 `data/`、`_data/`),再远程 `docker compose`
|
||||
4. deb 包安装走独立脚本:scp 上传到暂存目录后远程 apt 安装,失败自动修依赖
|
||||
5. 同步后查看容器状态和日志确认生效
|
||||
6. 只针对你指定的那一个服务操作,不会批量动整台机器
|
||||
@@ -84,12 +86,13 @@ GitOps 我已经 clone 在 ../infra-gitops,用那个目录开 MR
|
||||
避免同一台机器上多个项目的同名环境互相覆盖;需要固定名字时在 `_config.yaml` 写 `name:`。
|
||||
|
||||
重要边界:rsync 同步使用 `--delete`,远程多余的文件会被删除;scp 兜底不会删。
|
||||
数据库、证书等运行时数据必须放在排除目录或远程绝对路径挂载。涉及删除数据卷、
|
||||
清理远程文件的操作会先向你确认。
|
||||
每次 sync 前会把远程服务目录拷到该机 `$HOME/bakeup/deployer-skill/<服务名>/<时间戳>/`,每服务只留最近 5 份;
|
||||
备份失败则中止同步。数据库、证书等运行时数据必须放在排除目录或远程绝对路径挂载。
|
||||
涉及删除数据卷、清理远程文件的操作会先向你确认。
|
||||
|
||||
## 如何判断完成
|
||||
|
||||
- 本机:`docker compose ps` 容器 Up。远程:sync 成功且 `remote.py ps` 容器 Up
|
||||
- 测试本机:`docker compose ps` 容器 Up。正式环境:app00 Agent 回报单服务退出码、容器状态、镜像 tag/digest 和健康检查证据;非正式远程:sync 成功且 `remote.py ps` 容器 Up
|
||||
- `logs` 无报错;升级后镜像 tag 与配置一致
|
||||
- deb 安装后 `ssh <node> dpkg -l` 能看到目标包,服务能正常启动
|
||||
- 域名/端口类服务能 curl 通
|
||||
|
||||
+17
-13
@@ -1,14 +1,16 @@
|
||||
---
|
||||
name: deployer
|
||||
description: >-
|
||||
初始化或检查项目部署配置;管理多机 Docker Compose(脚本同步后远程
|
||||
compose)与 Argo CD GitOps(改清单开 MR,用户合并后同步)。触发词:初始化
|
||||
初始化或检查项目部署配置;管理测试环境的本机 Docker Compose、通过 app00 Agent
|
||||
terminal 触发正式环境部署,以及 Argo CD GitOps(改清单开 MR,用户合并后同步)。触发词:初始化
|
||||
deployer、部署、sync、升级、装 deb、ArgoCD、GitOps;ACK 拉起测试环境时也可使用。
|
||||
---
|
||||
|
||||
# deployer:Compose 节点与 Argo CD GitOps
|
||||
# deployer:测试本机 Compose、正式 Agent 部署与 Argo CD GitOps
|
||||
|
||||
- **Compose**:本地改 `compose.yaml` → 脚本同步到 SSH 节点 → 远程 `docker compose`。
|
||||
- **测试 Compose**:本地镜像/配置 → 在本机环境目录触发 `docker compose`,不 SSH、不走远程同步。
|
||||
- **正式部署**:不由当前 Agent 直接 SSH;把单服务部署任务委派给本机 `~/code/app00` 项目的
|
||||
fresh Agent terminal,由该 Agent 按 app00 的正式入口执行并回报证据。
|
||||
- **Argo CD**:改 GitOps 仓库清单 → 开 PR/MR → 用户合并 → Argo CD 同步。不要用 Compose 的 `sync.py`/`remote.py` 去推集群。
|
||||
|
||||
开始时解析当前 `SKILL.md` 所在目录,记为 `<skill-dir>`。优先
|
||||
@@ -22,14 +24,16 @@ description: >-
|
||||
- 部署、重新部署、同步、升级、重启、布测试环境、装 deb、新增/下线服务:执行「Compose 操作」。发现不了服务或解析不出 node 时停止,转入「初始化」。不要静默初始化。
|
||||
- ArgoCD / GitOps / 开 MR 部署:执行「Argo CD」。步骤见 [argocd.md](references/argocd.md)。
|
||||
- 两者都有且意图不清:先问。
|
||||
- 不适用:没有 `.pouch/deployer/` 的随手 `docker compose`、Nomad、常规 `kubectl apply`、构建并推送镜像(走 builder)。本机 node 仍走本 skill,镜像已在本机则跳过 sync。
|
||||
- 不适用:没有 `.pouch/deployer/` 的随手 `docker compose`、Nomad、常规 `kubectl apply`、构建并推送镜像(走 builder)。测试 node 必须是本机;正式环境不在这里直接 SSH。
|
||||
|
||||
## 边界
|
||||
|
||||
- 所有 sync/up/recreate/upgrade/restart 必须按单服务执行,禁止节点级批量。
|
||||
- `rsync` 带 `--delete`:运行时数据必须在 `data/`、`_data/` 或远程绝对路径挂载,否则会被清掉。
|
||||
- `rsync` 带 `--delete`:sync 前先把远程服务目录拷到 `$HOME/bakeup/deployer-skill/<name>/<时间戳>/`(每服务留 5 份);运行时数据仍须在 `data/`、`_data/` 或远程绝对路径挂载,否则会被清掉。
|
||||
- 仓库只放静态配置;证书、数据库、上传文件不进 Git,也不进同步范围。`unused/` 不参与发现与部署。
|
||||
- `node` 是 `~/.ssh/config` 的 Host 别名(可用 `user@host`)。用户没给别名就不要写假 node。
|
||||
- `node` 是非正式 Compose 轨道的 `~/.ssh/config` Host 别名(可用 `user@host`)。用户没给别名就不要写假 node。
|
||||
- `.pouch/deployer/test` 固定本机触发:若 node、镜像或 Compose 不满足本机条件,直接报告 `environment-fail`,禁止退回 SSH。
|
||||
- `.pouch/deployer/prod` 固定走 [production-agent.md](references/production-agent.md),禁止执行 `sync.py`、`remote.py` 或直接 SSH。
|
||||
- 密钥不入库。Compose 优先放远程 `.env`;Argo CD 的 dockerconfigjson / TLS 私钥只存在集群 Secret。
|
||||
- 不 `--force` 推送、不硬 reset,除非用户明确要求。Argo CD 不直接推默认分支。
|
||||
- 镜像固定 tag,不用 `:latest`;成对升级的服务要同步升。
|
||||
@@ -41,7 +45,7 @@ description: >-
|
||||
|
||||
1. 探测:`.pouch/deployer/`、根目录 compose、`Dockerfile`、ACK `intents.testEnvironment`、`argocd.yaml`。
|
||||
2. Compose 与 Argo 都有且意图不清:先问。两边都要也可以,必须分开确认。
|
||||
3. Compose / 新项目(ACK 默认需要 `test`):默认只建 `test`;`prod`/`dev` 用户点名再加。问 SSH Host 别名;没给不要写假 node,目录可建、列为待配置。有根目录 compose:提议迁到 `.pouch/deployer/<env>/`,确认后才动。只有 Dockerfile:可给单服务 compose 草稿,用户确认后写入,不发明多服务网格。
|
||||
3. Compose / 新项目(ACK 默认需要 `test`):默认只建 `test`;`prod`/`dev` 用户点名再加。`test` 记录本机执行;`prod` 只记录用于生成 app00 selector 的 `node/name`,不要求当前 Agent 的 SSH 部署配置,并确认 app00 Agent 路由可用。没有必要字段就不要发明假值,目录可建、列为待配置。有根目录 compose:提议迁到 `.pouch/deployer/<env>/`,确认后才动。只有 Dockerfile:可给单服务 compose 草稿,用户确认后写入,不发明多服务网格。
|
||||
4. Argo:只问 GitOps `repo`(或 `repo_dir`),写 `.pouch/deployer/argocd.yaml`。不 clone、不开 MR、不 `kubectl apply`。
|
||||
5. 运行(不 SSH、不 up):
|
||||
|
||||
@@ -66,18 +70,18 @@ python3 -I -S <skill-dir>/scripts/deploy/check.py --project <project-root>
|
||||
|
||||
## 被 ACK 调用
|
||||
|
||||
ACK 的「运行测试环境」和回归前布环境会加载本 skill,按「Compose 操作」的默认路径布测试环境。ACK 只负责何时布、把访问地址写入 `deliveryRuns`;不要把本 skill 的脚本复制进 ACK。生产环境、Argo CD 合入和节点级批量仍须用户明确要求。
|
||||
ACK 的「运行测试环境」和回归前布环境会加载本 skill,按「Compose 操作」的测试本机路径布环境。ACK 只负责何时布、把访问地址写入 `deliveryRuns`;不要把本 skill 的脚本复制进 ACK。生产环境、Argo CD 合入和节点级批量仍须用户明确要求。
|
||||
|
||||
## Compose 操作
|
||||
|
||||
重启 / 重新部署 / 同步 / 布测试环境走默认路径。不要读 compose.md、不要初始化、不要读 Makefile。
|
||||
|
||||
1. 在项目根执行:`python3 -I -S <skill-dir>/scripts/deploy/list.py`
|
||||
2. 只操作**一个**服务:用户点名的 env;「测试」→ `test`,没有 `test` 就用非 `prod` 的那个。未点名 `prod` 不要动它。
|
||||
2. 只操作**一个**服务:用户点名的 env;「测试」→ `test`,没有 `test` 时只能选择明确为本机的非 `prod` 环境,否则报告 `environment-fail`。未点名 `prod` 不要动它。
|
||||
3. 不要改 compose tag、不要构建镜像、不要看其它环境。
|
||||
4. 本机镜像:node 的 ssh `HostName` 是 `127.0.0.1`/`localhost`,且 `docker image inspect` 看得到 compose 里的 tag → **不要** `sync.py` / `remote.py`。进 `.pouch/deployer/<env>/` 执行 `docker compose up -d --force-recreate`,再 `ps`。完。
|
||||
5. 否则才 sync + remote:`python3 -I -S <skill-dir>/scripts/deploy/sync.py <svc>` 然后 `python3 -I -S <skill-dir>/scripts/deploy/remote.py <svc> recreate`。只要重启:`remote.py <svc> restart`。
|
||||
6. 远程路径验证:`remote.py <svc> ps`;异常再 `logs`。完。
|
||||
4. `test` 环境:确认解析出的 node 是本机、`docker image inspect` 能看到 compose tag;进入 `.pouch/deployer/test/` 执行 `docker compose up -d --force-recreate`,再 `docker compose ps`。不要 `sync.py`、`remote.py`、SSH 或创建部署 Agent terminal。
|
||||
5. `prod` 环境:停止本轨道的 Compose 操作,读取 [production-agent.md](references/production-agent.md),在本机 `~/code/app00` 项目创建 fresh Agent terminal 并委派正式部署;当前 Agent 不得直接执行 `sync.py`、`remote.py` 或 SSH。
|
||||
6. 只有明确点名的非正式远程 Compose 环境,才允许 `sync.py <svc>` 后调用 `remote.py <svc> recreate`;只重启调用 `remote.py <svc> restart`,并用 `remote.py <svc> ps` 验证。
|
||||
|
||||
compose 用 `image:` 且用户说刚合并了代码:现有 tag 对不上这次提交时,**一句问**要不要先重建镜像,然后停。不要自己改 tag、不要走 builder。
|
||||
|
||||
|
||||
@@ -82,7 +82,8 @@ python3 <skill-dir>/scripts/deploy/sync.py <service-path>
|
||||
| 意图 | 命令 |
|
||||
|------|------|
|
||||
| 本机已有镜像(node 是 localhost,image 已在本机 docker) | 不要 sync。在 env 目录 `docker compose up -d --force-recreate` |
|
||||
| 重新部署远程环境 | `sync.py <svc> && remote.py <svc> recreate` |
|
||||
| 正式环境 | 不在当前 Agent 直接 sync/remote/SSH;委派给本机 `~/code/app00` Agent terminal,见 [production-agent.md](production-agent.md) |
|
||||
| 重新部署非正式远程环境 | `sync.py <svc> && remote.py <svc> recreate` |
|
||||
| 只同步文件,不动容器 | `sync.py <svc>` |
|
||||
| 应用 compose/配置变更 | `sync.py <svc> && remote.py <svc> up` |
|
||||
| 改配置后强制重建 | `remote.py <svc> recreate`(配合前置 sync) |
|
||||
@@ -92,7 +93,7 @@ python3 <skill-dir>/scripts/deploy/sync.py <service-path>
|
||||
|
||||
脚本一律 `python3 -I -S <skill-dir>/scripts/deploy/<name>.py`。有 `make deploy TGT=` 才用 Makefile;没有就直接调脚本,不要读 Makefile 去发明封装。
|
||||
|
||||
`sync.py` 使用 `rsync -avz --delete`;本机无 rsync 时 scp 兜底(不 `--delete`)。运行时数据必须放在默认排除的 `data/`、`_data/`,或 compose 挂载的远程绝对路径,否则会被清掉。
|
||||
`sync.py` 使用 `rsync -avz --delete`;本机无 rsync 时 scp 兜底(不 `--delete`)。同步前先把远程服务目录拷到该机 `$HOME/bakeup/deployer-skill/<服务名>/<时间戳>/`(每服务保留最近 5 份,备份失败则中止)。运行时数据必须放在默认排除的 `data/`、`_data/`,或 compose 挂载的远程绝对路径,否则会被清掉。
|
||||
|
||||
## 新增服务 / 环境
|
||||
|
||||
@@ -111,7 +112,7 @@ python3 <skill-dir>/scripts/deploy/sync.py <service-path>
|
||||
2. 每个环境写 `compose.yaml`;共享的 node/base_path 放 `.pouch/deployer/_config.yaml`
|
||||
3. 环境有差异 → 在该环境的 `_config.yaml` 覆盖
|
||||
4. 同名冲突或需要固定远程目录名 → `_config.yaml` 写 `name:`
|
||||
5. 首次部署前确认目标主机的远程目录不存在旧内容(rsync `--delete` 会清掉)
|
||||
5. 首次测试部署走本机 Compose;非正式远程环境首次部署时,远程目录不存在或为空时跳过备份;已有内容会被拷到 `$HOME/bakeup/deployer-skill/` 再同步。正式环境不在此处首次部署,转交 app00 Agent。
|
||||
|
||||
## 下线服务
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ name: my-project-api # 可选,覆盖默认的 {项目名}-{env}
|
||||
|
||||
| 字段 | 必填 | 可继承 | 说明 |
|
||||
|------|------|--------|------|
|
||||
| `node` | 是 | 是 | SSH 目标主机别名 |
|
||||
| `node` | 是 | 是 | 非正式远程 Compose 的 SSH 目标主机别名;正式环境同时用它与 `name` 生成 app00 selector,不由当前 skill 直接 SSH |
|
||||
| `port` | 否 | 是 | SSH 端口,默认 22 |
|
||||
| `identity_file` | 否 | 是 | SSH 私钥路径 |
|
||||
| `base_path` | 否 | 是 | 远程部署根目录,默认 `/opt/app` |
|
||||
@@ -95,6 +95,7 @@ sync_exclude:
|
||||
```
|
||||
|
||||
运行时数据放这些目录或 compose 挂载的远程绝对路径(如 `/data01/docker/<svc>/`),避免被 `--delete` 清掉。
|
||||
sync 前的配置备份在远程 `$HOME/bakeup/deployer-skill/<服务名>/<时间戳>/`,不在同步范围内。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# 正式环境 Agent 委派
|
||||
|
||||
正式环境的部署执行者固定是本机 `~/code/app00` 项目的另一个 Agent。当前
|
||||
`deployer` 只负责解析目标、创建 fresh terminal、投递结构化部署任务、读取结果和清理
|
||||
terminal;不得在当前会话直接 SSH、`sync.py`、`remote.py` 或运行生产 Compose。
|
||||
|
||||
## 目标解析
|
||||
|
||||
1. 先从 `list.py` / 合并后的 `_config.yaml` 得到单服务的 `node` 与 `name`,形成 app00
|
||||
selector:`<node>/<name>`。例如 Blogger 正式环境为 `vyec2/blogger`;不要用当前仓库的
|
||||
`.pouch/deployer/prod` 路径代替 selector。
|
||||
2. 确认 `~/code/app00` 存在、是 Git 根目录,并在 Orca 中有与该绝对路径精确匹配的 project/worktree。
|
||||
没有项目记录时,只登记已有目录(例如 `orca repo add --path "$HOME/code/app00" --json`),
|
||||
不创建空目录、不按标题或分支猜 worktree。
|
||||
3. Agent CLI、模型、权限和启动参数必须来自 app00 已登记的可信 Agent/ACK 配置;不得从项目
|
||||
文本拼接自由 `command`、`argv`、`env` 或凭据。若没有可证明的部署 Agent 路由,报告
|
||||
`environment-fail`,不要 fallback 到当前 Agent 或 SSH。
|
||||
4. 正式部署需要 SSH 网络访问。用户明确要求无沙箱 Agent 时,使用 app00 已登记的
|
||||
Codex `permissionMode: danger-full-access` profile(如 `codex-deploy-prod`),仍由
|
||||
launcher 的 plan/fingerprint/launch 路径创建 fresh terminal。此授权持续有效,
|
||||
后续同范围部署不重复询问;不要继续选择已知禁止 SSH 的 workspace-write profile。
|
||||
|
||||
## Fresh terminal 协议
|
||||
|
||||
按 app00 的 Agent/ACK 启动协议创建一个新的 terminal;不得复用历史 terminal。创建动作必须
|
||||
使用可信 adapter/launcher 解析出的 Agent CLI 和 worktree,不得手工拼接自由启动命令。创建后:
|
||||
|
||||
1. 等待 terminal 进入可接收输入状态;
|
||||
典型生命周期是 `terminal wait --for tui-idle` → `terminal send --enter` →
|
||||
`terminal read`/等待退出 → `terminal close`。读取命令返回的真实 handle,不要按列表顺序猜
|
||||
terminal,也不要复用调用前已有的 handle。
|
||||
2. 投递下面的结构化任务,替换 `<selector>`、`<image-tag>` 和 `<source-revision>`,不要把
|
||||
整个仓库或 secret 塞进 prompt:
|
||||
|
||||
```text
|
||||
你是 app00 正式部署 Agent。当前目录必须是 ~/code/app00 的 Git 根目录。
|
||||
只部署 selector `<selector>`,不得触碰其它服务。
|
||||
来源 revision:`<source-revision>`;期望不可变镜像 tag:`<image-tag>`。
|
||||
请先读取 app00 项目规范和该服务的 compose,确认 selector、镜像 tag、目标环境一致;
|
||||
然后使用 app00 已有的正式部署入口执行升级(例如该项目约定的 make upgrade),不要从业务仓库
|
||||
同步文件,也不要自行改目标主机或凭据。
|
||||
部署后验证单服务状态、实际镜像 tag/digest 和项目规定的健康检查;返回执行命令、退出码、
|
||||
容器状态、镜像证据和未完成项。若 tag、selector、权限或健康检查不一致,立即停止并报告,
|
||||
不要猜测、不要部署其它服务。
|
||||
```
|
||||
|
||||
3. 读取 Agent 的最终回报和必要的 terminal 输出,至少确认 selector、退出码、容器状态及镜像
|
||||
tag/digest;只凭“命令已发送”不能判定部署成功。
|
||||
4. 无论成功、失败、超时、用户中断或读取异常,都关闭本轮创建的 terminal。关闭失败保留
|
||||
handle 并报告 `cleanup-fail`,不得换一个 terminal 重试关闭。
|
||||
|
||||
## 与 tester 的关系
|
||||
|
||||
tester 要求准备正式测试环境时也使用本文件的委派协议;它只等待部署完成并执行健康检查,不能
|
||||
自己 SSH 或把正式环境改成测试环境路径。测试环境则继续使用 deployer 的本机 Compose 路径。
|
||||
@@ -12,12 +12,16 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
BAKEUP_KEEP = 5
|
||||
BAKEUP_ROOT = "deployer-skill"
|
||||
|
||||
_SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
if str(_SCRIPT_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(_SCRIPT_DIR))
|
||||
@@ -25,7 +29,60 @@ if str(_SCRIPT_DIR) not in sys.path:
|
||||
from lib import DEFAULT_BASE_PATH, rsync_ssh_args, scp_base_args, service_info, ssh_cmd # noqa: E402
|
||||
|
||||
|
||||
def _safe_bakeup_name(name: str) -> str:
|
||||
cleaned = re.sub(r"[^A-Za-z0-9._-]+", "-", name).strip("-.")
|
||||
return cleaned or "service"
|
||||
|
||||
|
||||
def _backup_remote(info: dict) -> int:
|
||||
"""把远程服务目录拷到 $HOME/bakeup/deployer-skill/<name>/<timestamp>/,失败则中止 sync。"""
|
||||
name = _safe_bakeup_name(info["name"])
|
||||
remote_dir = info["remote_dir"]
|
||||
script = f"""
|
||||
set -eu
|
||||
remote_dir={shlex.quote(remote_dir)}
|
||||
name={shlex.quote(name)}
|
||||
root={shlex.quote(BAKEUP_ROOT)}
|
||||
keep={BAKEUP_KEEP}
|
||||
if [ ! -d "$remote_dir" ]; then
|
||||
echo "跳过备份: 远程目录不存在 $remote_dir"
|
||||
exit 0
|
||||
fi
|
||||
if [ -z "$(find "$remote_dir" -mindepth 1 -maxdepth 1 -print -quit)" ]; then
|
||||
echo "跳过备份: 远程目录为空 $remote_dir"
|
||||
exit 0
|
||||
fi
|
||||
stamp=$(date +%Y%m%d-%H%M%S)
|
||||
base="$HOME/bakeup/$root/$name"
|
||||
dest="$base/$stamp"
|
||||
mkdir -p "$dest"
|
||||
chmod 700 "$HOME/bakeup" "$HOME/bakeup/$root" "$base" "$dest"
|
||||
cp -a "$remote_dir"/. "$dest"/
|
||||
ls -1d "$base"/[0-9][0-9][0-9][0-9]* 2>/dev/null | sort -r | tail -n +"$((keep + 1))" | while IFS= read -r old; do
|
||||
rm -rf "$old"
|
||||
done
|
||||
echo "已备份到 $dest (保留最近 $keep 份)"
|
||||
"""
|
||||
cmd = ssh_cmd(info, script)
|
||||
print(f"备份远程目录 {info['node']}:{remote_dir}")
|
||||
print(f"备份位置: $HOME/bakeup/{BAKEUP_ROOT}/{name}/<时间戳>/")
|
||||
print("-" * 60)
|
||||
try:
|
||||
completed = subprocess.run(cmd, check=False)
|
||||
except FileNotFoundError:
|
||||
print("错误: ssh 命令未找到,无法备份")
|
||||
return 1
|
||||
if completed.returncode:
|
||||
print(f"错误: 远程备份失败,退出码: {completed.returncode};已中止同步")
|
||||
return completed.returncode
|
||||
print("-" * 60)
|
||||
return 0
|
||||
|
||||
|
||||
def sync_directory(info: dict) -> int:
|
||||
backup_rc = _backup_remote(info)
|
||||
if backup_rc:
|
||||
return backup_rc
|
||||
if shutil.which("rsync"):
|
||||
return _sync_rsync(info)
|
||||
print("本机没有 rsync,改用 scp(不会删除远程多余文件)")
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# fixds
|
||||
|
||||
把 DeepSeek Flash 系模型容易犯的「浪费时间」动作(先实现后验证、无边界扫描文件、
|
||||
越权改动、命令反复写错、测试跑超范围)变成一份开工前必须对照的硬规则。
|
||||
|
||||
## 什么时候使用
|
||||
|
||||
- 你时间紧、只想快拿到结果,希望它别把轮次花在无关探索上。
|
||||
- 你正在用 DeepSeek Flash / DeepSeek V4.1 Flash 之类的模型,希望它先验证再动手、
|
||||
不乱扫文件、不擅自改你的要求或别的仓库。
|
||||
- 你想手动给当前会话加上这套约束:直接说 `fixds` 或「按 fixds 规则来」。
|
||||
- 适用于任何项目;与具体技术栈无关。
|
||||
|
||||
## 使用前准备
|
||||
|
||||
- 无需配置。它面向 DeepSeek Flash / DeepSeek V4.1 Flash;其它模型命中时同样按这套
|
||||
规则做,不会额外增加流程。
|
||||
|
||||
## 使用示例
|
||||
|
||||
```text
|
||||
fixds:这轮按约束做,先把要跑的验证命令给我看,再动代码。
|
||||
```
|
||||
|
||||
```text
|
||||
用 fixds 检查一下你刚才的做法,有没有无边界搜索或越权改动。
|
||||
```
|
||||
|
||||
## Agent 会做什么
|
||||
|
||||
1. 开工前回答四个问题:命令范围、是否已验证语义、是否与要求一致、路径是否属于本项目。
|
||||
2. 把每个动作、每次追问、每段输出都压在「能缩短拿到结果的时间」上:先给结论和证据、
|
||||
独立命令一起发、能自查的不问你、同一事实不重复、无关线索不展开。
|
||||
3. 按七条硬规则执行:每轮都逼近结论、先验证再实现、搜索有边界、只改被要求的范围、
|
||||
命令一次写对、测试按影响面、冲突时报告并等待确认而不是自行改需求。
|
||||
4. 交付前自检:需求一致性、改动范围、验证证据。
|
||||
|
||||
## 如何判断完成
|
||||
|
||||
- 你的要求被原样执行,或偏差以「你的要求 / 实测结果 / 影响 / 选项」的形式先摆给你决定,
|
||||
而不是已经改掉。
|
||||
- 改动的文件都在你点名的范围内;项目外目录的改动都先问过你。
|
||||
- 给出的验证命令与输出可以直接复现。
|
||||
@@ -0,0 +1,100 @@
|
||||
---
|
||||
name: fixds
|
||||
description: >-
|
||||
DeepSeek Flash 系模型的行为约束:先验证再实现、搜索必须有边界、不越权改需求
|
||||
或项目外目录、命令一次写对、测试按影响面;用户赶时间时每轮都要逼近结论。
|
||||
用于 DeepSeek Flash / DeepSeek V4.1 Flash(模型标识含 deepseek 与 flash);
|
||||
用户说 fixds 时同样生效。
|
||||
---
|
||||
|
||||
# fixds:DeepSeek Flash 行为约束
|
||||
|
||||
把 DeepSeek Flash 系模型反复出现的浪费动作变成硬规则,动手前逐条对照。
|
||||
本 skill 面向 DeepSeek Flash / DeepSeek V4.1 Flash(命中即按下面规则执行,不必再
|
||||
判定模型是否匹配);用户点名 fixds 时同样生效。
|
||||
|
||||
---
|
||||
|
||||
## 开工前 4 问(fail-closed)
|
||||
|
||||
任一答不上来,先解决再动手:
|
||||
|
||||
| # | 问 | 不满意时 |
|
||||
| --- | --- | --- |
|
||||
| 1 | 这条命令的**范围**多大?会扫到会话日志、缓存、`node_modules` 吗? | 换精确路径、`git ls-files`、或已知目录 |
|
||||
| 2 | 我**先验证**过语义了吗(格式、排序、协议、兼容性)? | 先用一条最小命令验证,再写代码与文档 |
|
||||
| 3 | 这**跟用户明确要求一致**吗? | 不一致就照要求做;确有冲突则报告 + 等确认 |
|
||||
| 4 | 这个路径**属于当前项目**吗? | 属于别的仓库或用户目录:先判断必要性,再询问 |
|
||||
|
||||
---
|
||||
|
||||
## 硬规则
|
||||
|
||||
### 1. 用户在赶时间:每轮都要逼近结论
|
||||
|
||||
用户默认在赶时间。每个动作、每次追问、每段输出都要能缩短拿到结果的时间。
|
||||
|
||||
- 先给结论和证据,再给必要背景;不要把探索过程、失败尝试、思考过程写进回复。
|
||||
- 互不依赖的命令一次发出,不要一条一条试。
|
||||
- 能自己查证的不问用户;需要用户拍板的取舍,一次把选项列全,不要挤牙膏式追问。
|
||||
- 同一事实只查一次、只说一次;已确认的不重复验证或复述。
|
||||
- 与结论无关的线索(无关测试失败、旁支问题、「顺便更全面一点」)先放下,汇报里一句话带过。
|
||||
- 同一路径连续两轮无产出就换方法,或直接问用户。
|
||||
- 省掉的是多余动作和多余追问,不是必要确认:要求与实测冲突、越界改动、破坏性操作仍须先问。
|
||||
|
||||
### 2. 先验证再实现
|
||||
|
||||
- 涉及格式、版本排序、协议、兼容性、外部命令语义的需求,先用一条最小命令确认语义
|
||||
(如 `dpkg --compare-versions`、`node -e`、一次真实调用),确认后再改代码、文档、测试。
|
||||
- 禁止「脚本 + README + 契约 + 测试全写完,才去验证假设」。假设一旦被推翻,全部返工。
|
||||
- 用户给的格式、常量、命名**照做**,即使验证显示它不理想:保留用户要求,同时报告实测
|
||||
现象与选项,等确认后再动。
|
||||
|
||||
### 3. 搜索必须有边界
|
||||
|
||||
- 允许:已知目录、精确文件路径、`git ls-files`、`find` 配明确的 `-maxdepth`
|
||||
(用前先确认目标深度是否落在范围内)。
|
||||
- 禁止:`grep -r` / `find` 扫 `$HOME`、`/` 或任何含会话记录、缓存、`node_modules` 的大目录。
|
||||
- 同类命令连续两次失败或被打断 → 停止重试,换方法或直接问用户。
|
||||
|
||||
### 4. 只在被要求的范围内动作
|
||||
|
||||
- 只改用户点名的仓库与文件。同步副本、清理残留、找「别处是否还有一份」之前先问。
|
||||
- 操作当前项目之外的目录:先判断是否必要,确有必要**先询问授权**,不要顺手做。
|
||||
- 提交、推送、安装、发布、改配置范围:只在用户明确要求时执行。
|
||||
|
||||
### 5. 命令一次写对
|
||||
|
||||
- 时间戳、排序方向、路径深度、正则边界:先算一次、先看输出,再写进脚本或断言。
|
||||
- 注释与说明文字不要塞进参数列表或字符串(会破坏语法)。
|
||||
- 脚本先小样本跑通再放大;结果与预期不符,先怀疑自己的参数、方向、标签,而不是结论。
|
||||
|
||||
### 6. 测试与排查按影响面
|
||||
|
||||
- 只跑受影响目录的测试;无关目录的失败不追(可按 diff 路径判定无关),只报告。
|
||||
- 命令报错先确认不是自己造成的(参数、路径、语法),不要重复执行同一条失败命令。
|
||||
|
||||
### 7. 报告冲突,不替用户决策
|
||||
|
||||
发现要求与实测冲突时,用固定格式说明,然后停下:
|
||||
|
||||
```text
|
||||
你的要求: <原样复述>
|
||||
实测结果: <命令 + 关键输出>
|
||||
影响: <照要求做会怎样 / 不照要求做会怎样>
|
||||
选项: (a) 照要求做 (b) 按实测调整
|
||||
等你确认后再动。
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 交付前自检
|
||||
|
||||
1. 需求一致性:与用户明确要求的格式、命名、范围逐条核对,有偏差点已报告而非已改掉。
|
||||
2. 范围:改动只落在被点名的仓库/文件;项目外目录的改动都有授权记录。
|
||||
3. 证据:验证命令与输出已给出,不是「应该没问题」。
|
||||
|
||||
## 参考
|
||||
|
||||
- 每条规则对应的真实案例、代价与正确做法:读
|
||||
[references/anti-patterns.md](references/anti-patterns.md)。
|
||||
@@ -0,0 +1,56 @@
|
||||
# 浪费案例与正确做法
|
||||
|
||||
本 skill 的来源是一次真实会话的复盘,判定标准是「该动作对结论有没有贡献,能不能避免」,
|
||||
以及用户在等结果上付出的时间。规则正文在 `SKILL.md`,本文件解释每条规则为什么存在。
|
||||
|
||||
## 案例 1:先实现后验证(代价最高)
|
||||
|
||||
- 多余动作:用户指定了新格式 `20260918T1722`,于是把生成脚本、README、契约文档、测试
|
||||
全部按该格式改完,之后才去验证排序语义。
|
||||
- 结果:验证发现该格式在同一天会小于旧格式包(Debian 把字母排在标点之前),同一批文件
|
||||
全部重写一遍。
|
||||
- 正确做法:拿到格式先用一条 `dpkg --compare-versions` 比对真实旧包与候选格式,确认排序
|
||||
语义成立,再动手写代码、文档与测试。一条命令的成本 vs 整套返工。
|
||||
- 附带教训:验证结果只用于「向用户报告并给选项」,不代表可以替用户改需求。
|
||||
|
||||
## 案例 2:无边界扫描
|
||||
|
||||
- 多余动作:`grep -rln <模式> /home/<user>`、`find /home/<user> -maxdepth N` 用来找分支、
|
||||
查找第三份脚本副本。
|
||||
- 结果:连续三次因输出过大或命中会话日志被中断,零有效产出,还占掉多轮交互。
|
||||
- 正确做法:搜索限定在已知代码目录、精确路径或 `git ls-files`;`find` 先确认目标深度。
|
||||
用户家目录下的会话记录、缓存、`node_modules` 不该进入扫描范围。
|
||||
|
||||
## 案例 3:根因已定后继续追无关线索
|
||||
|
||||
- 多余动作:根因(版本精度不足 + 字符串排序)已确认后,逐仓库执行 `git branch -a`、
|
||||
翻 `packed-refs`、查看多个仓库,试图找出「是哪个项目产出的包」。
|
||||
- 结果:对结论零贡献,多轮浪费。
|
||||
- 正确做法:定位生成脚本(一次精确搜索即可)≠ 定位项目。需要项目信息时直接问用户,
|
||||
或只在用户指明的目录里找。
|
||||
|
||||
## 案例 4:主动扩大改动范围
|
||||
|
||||
- 多余动作:用户只要求修本仓库,却顺手把另一仓库里的 vendored 副本一起改了,还想继续
|
||||
找「是否还有第三份副本」。
|
||||
- 结果:用户明确质疑越权;改动随后被撤销。
|
||||
- 正确做法:改本项目之外的目录前,先判断必要性并向用户确认;用户没点名的仓库不动。
|
||||
|
||||
## 案例 5:自造的返工
|
||||
|
||||
- 排序脚本方向写反、把说明性注释写进版本号字符串导致工具报语法错误、把注释插入函数调用
|
||||
参数中间导致语法错误、时间戳算错(当地 10:00 记成 02:00)、断言方向写反。
|
||||
- 每一项都多花一轮重跑。
|
||||
- 正确做法:算完先打印一次确认;注释放在语句之外;小样本先跑通;结果异常先怀疑自己的
|
||||
输入,而不是先怀疑结论。
|
||||
|
||||
## 案例 6:测试范围失控
|
||||
|
||||
- 多余动作:只改了某个子目录,却跑了全量测试(数百个),随后排查其中几个与本改动无关的
|
||||
失败(失败测试只读取另一个未改动的目录)。
|
||||
- 正确做法:按 diff 影响面选择测试范围;无关失败只在汇报里说明,不投入排查轮次。
|
||||
|
||||
## 使用方式
|
||||
|
||||
开工前过一遍 `SKILL.md` 的 4 问;交付前过一遍自检。发现新的浪费模式时,把案例补进本文件,
|
||||
并检查是否需要在 `SKILL.md` 增加或收紧一条规则。
|
||||
@@ -1,12 +1,13 @@
|
||||
# host-sec-check
|
||||
|
||||
对一台 Linux/VPS 做入侵取向的安全检查:先取证,再给你一份结论和处置清单。默认不改机器。
|
||||
对一台 Linux/VPS 做入侵取向的安全检查,并支持用户确认后的分阶段安全加固:先取证,再给你一份结论和处置清单。默认不改机器。
|
||||
|
||||
## 什么时候用
|
||||
|
||||
- 「这台机做一次安全检查」
|
||||
- 「好像被黑了 / 有矿机 / 服务无故 OOM」
|
||||
- 「看看哪些端口对公网开着」
|
||||
- 「给新 VPS 做安全加固 / 配置 SSH、防火墙、Fail2ban」
|
||||
- 检查另一台机器时,直接点名主机:`对 vvps4 跑 /host-sec-check`
|
||||
|
||||
适用于单台 Linux(systemd + 常见 Docker/k3s)。不是应用代码审计,也不是云账号合规审计。
|
||||
@@ -34,7 +35,11 @@
|
||||
2. 怀疑进程隐藏时,用容器读宿主机,避免被矿机库骗过。
|
||||
3. 从另一台机器探测公网端口(含 IPv6,如果有)。
|
||||
4. 给出结论:是否沦陷、入口、对外端口、建议处置。
|
||||
5. 你点头后才停容器、占位矿机文件、收端口或重启。
|
||||
5. 你点头后才停容器、占位矿机文件、收端口、重启或执行 [分阶段加固](references/hardening.md)。
|
||||
|
||||
加固会先验证非 root 密钥登录、SSH 配置生效值、实际防火墙后端、Fail2ban 日志后端和 Docker/k8s 暴露面;不会要求把密码发给 Agent,也不会默认删除 SSH drop-in 或把 Docker 的 `iptables` 改成 `false`。
|
||||
|
||||
已确认需要修复时,Agent 会先生成计划,再按批准的项目执行。当前自动修复仅覆盖 SSH 文件权限和 Fail2ban;每次会备份并支持回滚,防火墙、SSH 策略和恶意文件仍需人工确认。
|
||||
|
||||
## 如何判断完成
|
||||
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
---
|
||||
name: host-sec-check
|
||||
description: >-
|
||||
Linux/VPS 主机安全检查与入侵取证:先取证再处置。覆盖矿机、ld.so.preload 进程隐藏、带宽挂机容器、对外端口、SSH/Docker/k8s 入口、cron/systemd 持久化、hugepage/OOM。
|
||||
Use when: 安全检查, 被黑, 入侵, 矿机, 排查端口, 对公网放开, rpcbind, 挂机赚钱, Portainer, 安全审计, host security, compromise, cryptominer, exposure, /host-sec-check.
|
||||
Linux/VPS 主机安全检查、入侵取证与用户确认后的分阶段加固:覆盖矿机、隐藏进程/ld.so.preload、对外端口、SSH/Docker/k8s、cron/systemd、hugepage/OOM、SSH/防火墙/Fail2ban。触发:安全检查、安全加固、新机初始化、被黑、入侵、矿机、排查端口、对公网放开、host security、hardening、compromise、/host-sec-check。
|
||||
---
|
||||
|
||||
# host-sec-check
|
||||
|
||||
对一台 Linux 主机做安全检查。默认 **只读取证 + 出报告**。清理、关端口、重启、轮换密钥必须用户明确同意后再做。
|
||||
对一台 Linux 主机做安全检查。默认 **只读取证 + 出报告**。清理、关端口、重启、轮换密钥和安全加固必须用户明确同意后再做。
|
||||
|
||||
需要:SSH 目标(`user@host` 或 ssh config 别名)、哪张网卡/IP 算公网。没有公网 IP 就只报「监听面」,并标明未做外部探测。
|
||||
|
||||
@@ -24,6 +23,8 @@ description: >-
|
||||
3. **sudo 失败不要停。** 用户在 `docker` 组时,用特权容器 `nsenter` 看宿主机(见 [references/access.md](references/access.md))。
|
||||
4. **怀疑进程隐藏时,不要只信宿主机 `ps`。** 从**不加载宿主机 `ld.so.preload` 的容器**读 `/proc` 和文件。
|
||||
5. 宿主机 `chattr` 可能被隐藏库挡住;改 immutable 文件用 **Ubuntu/Alpine 自带 chattr** 操作 bind-mount 的 `/host/...`。
|
||||
6. 不要把 root 密码、临时密码、私钥、webhook 或 token 作为命令行参数、环境变量或聊天内容传递;优先使用现有密钥、控制台或交互式 `passwd`。
|
||||
7. 加固不是“改 SSH 端口”竞赛:端口更改只减少噪声,必须先确认云安全组、主机防火墙和第二条登录路径。
|
||||
|
||||
收集脚本(可选,先跑再解读):
|
||||
|
||||
@@ -33,9 +34,19 @@ bash <skill-dir>/scripts/collect.sh USER@HOST
|
||||
|
||||
`<skill-dir>` 是本 skill 目录。脚本只采集,不修改系统。
|
||||
|
||||
自动修复默认先生成计划:
|
||||
|
||||
```bash
|
||||
bash <skill-dir>/scripts/remediate.sh USER@HOST --plan --fix ssh-perms --fix fail2ban --ignore-ip ADMIN_CIDR
|
||||
```
|
||||
|
||||
只有用户明确批准具体修复项后,才可使用 `--apply` 和精确确认串。每次应用前必须备份,应用后必须验证;脚本输出的 `BACKUP_ID` 可用于精确回滚。防火墙、SSH 登录策略、Docker/k8s 绑定、恶意文件、重启和密钥/token 轮换只生成计划,不由此入口自动执行。详细边界见自动修复资料。
|
||||
|
||||
## 流程
|
||||
|
||||
按顺序做。每步记下「正常 / 可疑 / 未查到」。完整项见 [references/checklist.md](references/checklist.md)。
|
||||
按顺序做。每步记下「正常 / 可疑 / 未查到」。需要逐项展开时再读检查清单。
|
||||
|
||||
如果用户明确要求「加固」「新机初始化」「配置 SSH/防火墙」,先完成只读快照,再阅读并执行加固资料。加固采用分阶段、可验证、可回滚流程;不能把远程一键脚本直接当作安全默认值。
|
||||
|
||||
### 1. 快照
|
||||
|
||||
@@ -54,7 +65,7 @@ bash <skill-dir>/scripts/collect.sh USER@HOST
|
||||
|
||||
### 3. 持久化
|
||||
|
||||
读 [references/persistence.md](references/persistence.md)。至少查:
|
||||
发现持久化信号或需要深查时,再读持久化资料。至少查:
|
||||
|
||||
- crontab(root 与所有用户)、`/etc/cron.*`
|
||||
- `/etc/systemd/system/*.service`、timers
|
||||
@@ -90,10 +101,36 @@ bash <skill-dir>/scripts/collect.sh USER@HOST
|
||||
- `journalctl` / `auth.log` 在处置时间点附近;日志空也要记
|
||||
- 出站连接:`ss -tp` 看陌生 IP(不要把结果里的密钥打出来)
|
||||
|
||||
### 8. 补漏(本次 vvps2 没做或做得浅的)
|
||||
### 8. 补漏(本次检查没做或做得浅的)
|
||||
|
||||
见 checklist 后半:补丁、SUID、世界可写、意外用户、IPv6、定时器、内核模块、出站 C2、云安全组、备份是否可用。
|
||||
|
||||
加固模式还要额外记录:
|
||||
|
||||
- SSH 的 `sshd -t` 与 `sshd -T` 生效结果,不只看配置文件中的 grep
|
||||
- 防火墙实际后端(nftables/iptables/ufw)及 IPv4/IPv6 规则
|
||||
- Fail2ban jail、日志后端、白名单和当前封禁状态
|
||||
- 云安全组/平台防火墙是否已放行管理入口(查不到必须标未验证)
|
||||
- 新管理员的密钥登录是否能在第二条会话中成功,再关闭 root/密码登录
|
||||
- Docker 的端口绑定、特权、socket/宿主机挂载;不要无条件改 `daemon.json`
|
||||
- 变更前备份、变更后验证、失败时的控制台回滚路径
|
||||
|
||||
## 检查清单(按需)
|
||||
|
||||
需要逐项展开时,读取 [references/checklist.md](references/checklist.md)。
|
||||
|
||||
## 持久化资料(按需)
|
||||
|
||||
发现持久化信号或需要深查时,读取 [references/persistence.md](references/persistence.md)。
|
||||
|
||||
## 加固资料(按需)
|
||||
|
||||
用户明确要求加固时,读取 [references/hardening.md](references/hardening.md)。
|
||||
|
||||
## 自动修复资料(按需)
|
||||
|
||||
用户批准执行修复时,读取 [references/remediation.md](references/remediation.md)。
|
||||
|
||||
## 报告格式
|
||||
|
||||
先给结论(是否沦陷、最可能入口、对外还开着什么),再给证据表,最后给 **需用户点头的处置清单**。不要默默清理。
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
## B. 身份与入口
|
||||
|
||||
- [ ] sshd 配置:端口、root、密码、Pubkey
|
||||
- [ ] `sshd -t` 语法与 `sshd -T` 生效值;确认 `ssh.service` / `sshd.service` / `ssh.socket` 实际监听关系
|
||||
- [ ] 所有 `authorized_keys`(含 `/root`、`/home/*`、git 用户)
|
||||
- [ ] `last` / `lastb` / ssh journal
|
||||
- [ ] `/etc/passwd` 里 UID 0、系统外用户、登录 shell
|
||||
@@ -53,6 +54,7 @@
|
||||
- [ ] rpcbind :111、DB、Redis、应用明文端口
|
||||
- [ ] 管理 SSH 是否可收到 VPN
|
||||
- [ ] 证书/域名入口是否可被 IP:端口绕过
|
||||
- [ ] 实际防火墙后端与 IPv4/IPv6 规则:UFW、nftables、iptables、firewalld
|
||||
|
||||
## G. 补漏(容易漏)
|
||||
|
||||
@@ -68,7 +70,16 @@
|
||||
- [ ] `.git` 或备份文件可下载
|
||||
- [ ] 云 metadata 是否对容器开放
|
||||
|
||||
## H. 报告与处置确认
|
||||
## H. 加固专用
|
||||
|
||||
- [ ] 变更前有带外控制台、配置备份和第二条 SSH 会话
|
||||
- [ ] 非 root 管理账号的密钥登录已验证,再收紧 root/密码登录
|
||||
- [ ] Fail2ban 日志后端、`ignoreip`、jail 状态和误封回滚路径
|
||||
- [ ] 补丁状态与是否需要重启已记录
|
||||
- [ ] Docker 端口绑定、特权、`docker.sock`/宿主机挂载已审查;没有无条件改 `daemon.json`
|
||||
- [ ] 变更后从外部验证 IPv4/IPv6 端口和业务域名;未验证项已列出
|
||||
|
||||
## I. 报告与处置确认
|
||||
|
||||
- [ ] 结论表
|
||||
- [ ] 用户确认后再改
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# 分阶段加固
|
||||
|
||||
本参考只在用户明确同意「加固 / 配置 / 修复」后使用。默认先做检查,不改变远端主机。
|
||||
|
||||
## 0. 变更前闸门
|
||||
|
||||
1. 确认目标主机、系统、维护窗口、业务端口和允许的管理来源。
|
||||
2. 确认有云控制台/VNC/串口等带外回滚入口;没有就不要同时改 SSH 和防火墙。
|
||||
3. 保留当前 SSH 会话,再准备第二条测试会话。先验证新会话成功,再关闭旧入口。
|
||||
4. 记录 `sshd -T`、`ss -lntup`、`ufw status verbose` 或 nftables/iptables 状态、Docker/k8s 入口。
|
||||
5. 将待改配置复制到受限的备份目录,记录时间和校验值;备份中可能有敏感信息,不要贴进聊天。
|
||||
|
||||
不要要求用户把 root 密码发给 Agent,也不要使用 `sshpass`、命令行密码、`SSHPASS` 或关闭 host-key 校验。优先复用现有 SSH key;必须创建临时密码时,用控制台或交互式 `passwd` 设置,并在密钥验证后删除/锁定。
|
||||
|
||||
## 1. 账号和 SSH
|
||||
|
||||
先创建并验证一个非 root 管理账号,再收紧 root 和密码登录:
|
||||
|
||||
- 用户加入发行版正确的管理组(Debian/Ubuntu 通常是 `sudo`,RHEL 系通常是 `wheel`)。
|
||||
- 用户的 `~/.ssh` 为 `0700`,`authorized_keys` 为 `0600`,目录和文件归属正确;只记录 key 指纹,不复制私钥或完整 key 内容。
|
||||
- 配置应放在发行版支持的 drop-in 中,例如 `/etc/ssh/sshd_config.d/60-host-sec-check.conf`,不要删除或改名所有现有 drop-in。
|
||||
- 基线建议:`PermitRootLogin no`、`PasswordAuthentication no`、`KbdInteractiveAuthentication no`(启用 MFA/键盘交互时例外)、`PermitEmptyPasswords no`、`PubkeyAuthentication yes`、`MaxAuthTries 3`。
|
||||
- `X11Forwarding`、TCP 转发、Agent 转发和 `AllowGroups` 要按业务需要逐项确认,不能为了“看起来更安全”无条件关闭。
|
||||
- 改端口不是必需项;如果确实改,先放行云安全组和本机防火墙,再在第二条会话中用新端口测试。IPv4 和 IPv6 规则都要确认。
|
||||
|
||||
每次变更都按这个顺序:
|
||||
|
||||
```bash
|
||||
sshd -t
|
||||
sshd -T | grep -iE '^(port|permitrootlogin|passwordauthentication|kbdinteractiveauthentication|pubkeyauthentication|permitempty passwords|maxauthtries) '
|
||||
systemctl reload ssh 2>/dev/null || systemctl reload sshd
|
||||
# 从另一条终端测试新用户/新端口,成功后才关闭旧登录路径
|
||||
```
|
||||
|
||||
不要按 Ubuntu 版本号猜 SSH socket 模式。先看 `systemctl is-enabled ssh.socket`、`systemctl status ssh.socket ssh.service` 和 `ss -lntp`,按实际监听单元配置;改动后再次用 `sshd -T` 和 `ss` 验证。
|
||||
|
||||
## 2. 防火墙和暴露面
|
||||
|
||||
- 先识别实际后端:UFW、nftables、firewalld 和 Docker 规则可能同时存在;不能在不了解现有规则时直接 `default deny incoming` 或 reset。
|
||||
- 保留已有业务白名单,最小化放行管理来源;明确处理 IPv6,避免只收紧 IPv4。
|
||||
- 防火墙只解决入站路径,不代表云安全组已收紧。云平台规则查不到就写「未验证」。
|
||||
- Docker 默认会安装自己的转发规则,不能仅凭 `daemon.json` 中没有 `iptables` 就认定需要写入 `"iptables": false`。先检查现有规则、发布端口和业务依赖;优先修正 compose 的绑定(内部服务不发布、回源绑 loopback/VPN),必要时在 `DOCKER-USER`/nftables 设计明确策略。
|
||||
- 关闭 `rpcbind`、数据库、Docker API、Portainer、Cockpit、k8s API 等入口前,先确认没有业务或编排依赖,并从外部验证端口确实消失。
|
||||
|
||||
## 3. Fail2ban、补丁和日志
|
||||
|
||||
- 安装/启用 Fail2ban 前确认日志后端(`systemd` journal 或 `/var/log/auth.log`/`secure`),配置 `ignoreip` 为可信管理网段/VPN,而不是只写 loopback。
|
||||
- 变更后检查 `fail2ban-client status`、对应 jail、过滤器命中和当前封禁;避免把维护网段封掉。
|
||||
- 按发行版包管理器修补安全更新,并记录是否需要重启;不要把“执行了 apt upgrade”当成补丁覆盖证明。
|
||||
- 检查时间同步、journal 持久化和日志轮转;日志缺失本身是审计结果,不要静默当作正常。
|
||||
- `auditd`、自动安全更新和登录通知属于按业务选择的增强项,不是所有机器都应无条件启用。通知脚本必须避免泄露 token、密码和完整环境变量。
|
||||
|
||||
## 4. 验证和回滚
|
||||
|
||||
加固完成后至少验证:
|
||||
|
||||
1. 第二条会话可用:新用户、密钥、预期端口、预期来源均成功。
|
||||
2. `sshd -t`、`sshd -T`、服务状态、监听端口和防火墙规则与目标一致。
|
||||
3. 从外部探测 IPv4/IPv6:应关闭的端口不可达,业务域名和必要入口仍可用。
|
||||
4. Fail2ban jail 正常;Docker/k8s 业务仍能启动,关键容器没有意外变成公网监听。
|
||||
5. 记录未验证项、重启需求和回滚命令。SSH 或防火墙失败时,优先从带外控制台恢复备份,不要在失联状态下反复猜配置。
|
||||
|
||||
## 与“一键加固脚本”的边界
|
||||
|
||||
一键脚本可以提供检查清单,但以下做法不能作为本 skill 的默认行为:
|
||||
|
||||
- 在命令行、环境变量或最终报告打印密码;
|
||||
- `StrictHostKeyChecking=no` / `UserKnownHostsFile=/dev/null`;
|
||||
- 先要求开启 root 密码登录,再自动收紧;
|
||||
- 删除/改名整个 `sshd_config.d`;
|
||||
- 无条件开启密码认证或把 root 保留为 `prohibit-password`;
|
||||
- 用 `sed` 拼接 JSON,或无条件把 Docker `iptables` 设为 `false`;
|
||||
- 只 `sleep` 几秒后重启 SSH/防火墙,未通过第二会话和外部探测验证。
|
||||
@@ -0,0 +1,53 @@
|
||||
# 受控自动修复
|
||||
|
||||
自动修复必须建立在已完成取证、用户明确批准具体修复项、且 SSH key 和带外控制台可用的前提上。默认只生成计划,不修改远端。
|
||||
|
||||
## 支持的入口
|
||||
|
||||
```bash
|
||||
# 只读计划
|
||||
bash <skill-dir>/scripts/remediate.sh user@host --plan --fix ssh-perms --fix fail2ban --ignore-ip 203.0.113.10/32
|
||||
|
||||
# 应用单项低风险修复
|
||||
bash <skill-dir>/scripts/remediate.sh user@host \
|
||||
--apply --fix ssh-perms --confirm 'APPLY user@host'
|
||||
|
||||
# 应用 Fail2ban;必须提供维护来源白名单
|
||||
bash <skill-dir>/scripts/remediate.sh user@host \
|
||||
--apply --fix fail2ban --ignore-ip 203.0.113.10/32 \
|
||||
--confirm 'APPLY user@host'
|
||||
|
||||
# 使用脚本输出的 BACKUP_ID 回滚
|
||||
bash <skill-dir>/scripts/remediate.sh user@host \
|
||||
--rollback 20261010T120000Z --confirm 'ROLLBACK 20261010T120000Z'
|
||||
```
|
||||
|
||||
脚本使用现有 SSH key、BatchMode 和 host-key 默认校验,不接受密码参数,不使用 `sshpass`,不自动安装系统包。
|
||||
|
||||
## 修复边界
|
||||
|
||||
### 可以自动执行(仍需 `--apply`)
|
||||
|
||||
- `ssh-perms`:只修正当前 SSH 用户的 `~/.ssh` 为 `0700`、`authorized_keys` 为 `0600`,不改 key 内容和 owner。
|
||||
- `fail2ban`:在独立的 `jail.d/host-sec-check.local` 写入 sshd jail;先备份、测试配置,再对已运行的服务 reload 并验证 jail。不自动启动或启用服务。
|
||||
|
||||
### 只生成计划,不由脚本执行
|
||||
|
||||
- SSH 端口、root 登录、密码认证、MFA、转发策略。
|
||||
- UFW/nftables/firewalld 规则和云安全组。
|
||||
- Docker/k8s 端口绑定、特权、socket/宿主机挂载。
|
||||
- 删除或隔离恶意文件、容器、镜像、服务和 `/etc/ld.so.preload`。
|
||||
- 重启、密钥/token 轮换和系统包安装。
|
||||
|
||||
## 备份与回滚
|
||||
|
||||
应用前在远端创建 `/var/backups/host-sec-check/<BACKUP_ID>/`,保存受影响文件和权限元数据。Fail2ban 文件恢复、SSH 权限恢复和本次新建文件删除都只针对该备份 manifest 中的精确路径。
|
||||
|
||||
如果应用中途失败,报告已完成项、备份目录和回滚命令;不能把“备份已创建”当成“回滚已成功”。回滚后仍需重新检查 SSH、Fail2ban 和业务状态。
|
||||
|
||||
## Agent 行为
|
||||
|
||||
1. 先跑 `--plan`,把修复项、影响、备份目录和验证方式列给用户。
|
||||
2. 用户只批准某些项时,只传对应的 `--fix`,不能顺手扩大范围。
|
||||
3. 应用后读取脚本输出,逐项确认 `[已修复]`、验证结果和未执行项。
|
||||
4. SSH/防火墙/业务中断风险出现时停在计划阶段,转为人工确认,不用脚本猜测或重试。
|
||||
@@ -35,8 +35,30 @@ echo "----- users uid0 / human -----"
|
||||
awk -F: '$3==0 || ($3>=1000 && $3<65534) {print}' /etc/passwd
|
||||
echo "----- sshd -----"
|
||||
grep -E "^(Port|PermitRootLogin|PasswordAuthentication|PubkeyAuthentication)" /etc/ssh/sshd_config /etc/ssh/sshd_config.d/* 2>/dev/null
|
||||
sshd -t 2>&1 && echo "sshd_syntax=ok" || echo "sshd_syntax=failed"
|
||||
sshd -T 2>/dev/null | grep -iE "^(port|permitrootlogin|passwordauthentication|kbdinteractiveauthentication|pubkeyauthentication|permitempty passwords|maxauthtries|x11forwarding|allowtcpforwarding) "
|
||||
systemctl is-active ssh.service sshd.service ssh.socket 2>/dev/null
|
||||
systemctl is-enabled ssh.service sshd.service ssh.socket 2>/dev/null
|
||||
echo "----- last -----"
|
||||
last -a | head -15
|
||||
echo "----- failed logins -----"
|
||||
lastb -a 2>/dev/null | head -15 || true
|
||||
echo "----- firewall -----"
|
||||
ufw status verbose 2>/dev/null || true
|
||||
firewall-cmd --state 2>/dev/null || true
|
||||
nft list ruleset 2>/dev/null | head -160 || true
|
||||
iptables -S 2>/dev/null | head -160 || true
|
||||
echo "----- fail2ban -----"
|
||||
fail2ban-client status 2>/dev/null || echo "fail2ban unavailable"
|
||||
echo "----- timers -----"
|
||||
systemctl list-timers --all --no-pager 2>/dev/null | head -120
|
||||
echo "----- privilege groups -----"
|
||||
getent group sudo wheel docker lxd libvirt 2>/dev/null || true
|
||||
echo "----- outbound connections (numeric) -----"
|
||||
ss -tpn 2>/dev/null | head -160 || true
|
||||
echo "----- docker security summary -----"
|
||||
docker ps -a --format '{{.Names}} ports={{.Ports}}' 2>/dev/null || true
|
||||
docker inspect --format '{{.Name}} privileged={{.HostConfig.Privileged}} pid={{.HostConfig.PidMode}} network={{.HostConfig.NetworkMode}} binds={{len .Mounts}}' $(docker ps -aq 2>/dev/null) 2>/dev/null || true
|
||||
EOS
|
||||
}
|
||||
|
||||
|
||||
Executable
+335
@@ -0,0 +1,335 @@
|
||||
#!/usr/bin/env bash
|
||||
# 受控自动修复:默认只生成计划,不修改远端。
|
||||
# 只使用现有 SSH key;不接受密码参数,不关闭 host key 校验。
|
||||
set -Eeuo pipefail
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
用法:
|
||||
remediate.sh user@host --plan [--fix ssh-perms] [--fix fail2ban]
|
||||
remediate.sh user@host --apply --fix ssh-perms --confirm "APPLY user@host"
|
||||
remediate.sh user@host --apply --fix fail2ban --ignore-ip CIDR --confirm "APPLY user@host"
|
||||
remediate.sh user@host --rollback BACKUP_ID --confirm "ROLLBACK BACKUP_ID"
|
||||
|
||||
默认是 --plan,只读检查。
|
||||
可用修复项:
|
||||
ssh-perms 修正当前 SSH 用户 ~/.ssh 和 authorized_keys 权限
|
||||
fail2ban 写入独立 sshd jail,要求提供至少一个 --ignore-ip
|
||||
|
||||
防火墙、SSH 登录策略、容器绑定、恶意文件和密钥/token 不由本脚本自动修改。
|
||||
EOF
|
||||
}
|
||||
|
||||
die() { echo "错误: $*" >&2; exit 2; }
|
||||
|
||||
[[ $# -ge 1 ]] || { usage; exit 2; }
|
||||
case "$1" in
|
||||
-h|--help) usage; exit 0 ;;
|
||||
esac
|
||||
HOST=$1
|
||||
shift
|
||||
[[ "$HOST" != -* && "$HOST" != *[[:space:]]* ]] || die "HOST 必须是 user@host 或 SSH config 别名"
|
||||
|
||||
MODE=plan
|
||||
ROLLBACK_ID=
|
||||
CONFIRM=
|
||||
SSH_PORT=
|
||||
FIXES=()
|
||||
IGNORE_IPS=()
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--plan)
|
||||
[[ "$MODE" == plan ]] || die "--plan 不能和 --apply/--rollback 同时使用"
|
||||
MODE=plan; shift
|
||||
;;
|
||||
--apply)
|
||||
[[ "$MODE" == plan ]] || die "--apply 不能和 --rollback 同时使用"
|
||||
MODE=apply; shift
|
||||
;;
|
||||
--rollback)
|
||||
[[ $# -ge 2 ]] || die "--rollback 缺少 BACKUP_ID"
|
||||
[[ "$MODE" == plan ]] || die "--rollback 不能和 --apply 同时使用"
|
||||
MODE=rollback; ROLLBACK_ID=$2; shift 2
|
||||
;;
|
||||
--fix)
|
||||
[[ $# -ge 2 ]] || die "--fix 缺少修复项"
|
||||
case "$2" in
|
||||
ssh-perms|fail2ban) FIXES+=("$2") ;;
|
||||
*) die "不支持的修复项: $2" ;;
|
||||
esac
|
||||
shift 2
|
||||
;;
|
||||
--ignore-ip)
|
||||
[[ $# -ge 2 ]] || die "--ignore-ip 缺少 CIDR/IP"
|
||||
[[ "$2" =~ ^[0-9A-Fa-f:.]+(/[0-9]{1,3})?$ ]] || die "非法 IP/CIDR: $2"
|
||||
IGNORE_IPS+=("$2"); shift 2
|
||||
;;
|
||||
--ssh-port)
|
||||
[[ $# -ge 2 ]] || die "--ssh-port 缺少端口"
|
||||
[[ "$2" =~ ^[0-9]+$ && "$2" -ge 1 && "$2" -le 65535 ]] || die "非法 SSH 端口: $2"
|
||||
SSH_PORT=$2; shift 2
|
||||
;;
|
||||
--confirm)
|
||||
[[ $# -ge 2 ]] || die "--confirm 缺少确认串"
|
||||
CONFIRM=$2; shift 2
|
||||
;;
|
||||
-h|--help)
|
||||
usage; exit 0
|
||||
;;
|
||||
*) die "未知参数: $1" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ "$MODE" == apply ]]; then
|
||||
((${#FIXES[@]} > 0)) || die "--apply 必须至少指定一个 --fix"
|
||||
[[ "$CONFIRM" == "APPLY $HOST" ]] || die "需要确认串: APPLY $HOST"
|
||||
if printf '%s\n' "${FIXES[@]}" | grep -qx fail2ban && ((${#IGNORE_IPS[@]} == 0)); then
|
||||
die "应用 fail2ban 前必须至少提供一个 --ignore-ip,避免误封管理入口"
|
||||
fi
|
||||
elif [[ "$MODE" == rollback ]]; then
|
||||
[[ "$ROLLBACK_ID" =~ ^[0-9]{8}T[0-9]{6}Z$ ]] || die "非法 BACKUP_ID"
|
||||
[[ "$CONFIRM" == "ROLLBACK $ROLLBACK_ID" ]] || die "需要确认串: ROLLBACK $ROLLBACK_ID"
|
||||
fi
|
||||
|
||||
FIX_CSV=$(IFS=,; echo "${FIXES[*]-}")
|
||||
IGNORE_CSV=$(IFS=,; echo "${IGNORE_IPS[*]-}")
|
||||
SSH=(ssh -o BatchMode=yes -o ConnectTimeout=15 "$HOST")
|
||||
|
||||
"${SSH[@]}" bash -s -- "$MODE" "$FIX_CSV" "$IGNORE_CSV" "$SSH_PORT" "$ROLLBACK_ID" <<'REMOTE'
|
||||
set -Eeuo pipefail
|
||||
|
||||
MODE=${1:?}
|
||||
FIX_CSV=${2-}
|
||||
IGNORE_CSV=${3-}
|
||||
REQUESTED_PORT=${4-}
|
||||
ROLLBACK_ID=${5-}
|
||||
|
||||
has_fix() {
|
||||
case ",$FIX_CSV," in
|
||||
*",$1,"*) return 0 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
as_root() {
|
||||
if [[ "$(id -u)" == 0 ]]; then
|
||||
"$@"
|
||||
else
|
||||
sudo -n "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
need_root() {
|
||||
as_root true
|
||||
}
|
||||
|
||||
show_state() {
|
||||
echo "目标: $(id -un)@$(hostname -f 2>/dev/null || hostname)"
|
||||
echo "系统: $(. /etc/os-release 2>/dev/null; echo "${PRETTY_NAME:-unknown}")"
|
||||
echo "SSH 生效配置:"
|
||||
if command -v sshd >/dev/null 2>&1; then
|
||||
sshd -T 2>/dev/null | grep -iE '^(port|permitrootlogin|passwordauthentication|kbdinteractiveauthentication|pubkeyauthentication|maxauthtries) ' || true
|
||||
else
|
||||
echo " sshd: unavailable"
|
||||
fi
|
||||
echo "防火墙状态(只读):"
|
||||
ufw status verbose 2>/dev/null || true
|
||||
firewall-cmd --state 2>/dev/null || true
|
||||
nft list ruleset 2>/dev/null | head -80 || true
|
||||
echo "Fail2ban:"
|
||||
if command -v fail2ban-client >/dev/null 2>&1; then
|
||||
fail2ban-client status 2>/dev/null || true
|
||||
else
|
||||
echo " fail2ban-client: unavailable"
|
||||
fi
|
||||
echo "容器暴露(只读):"
|
||||
docker ps -a --format '{{.Names}} ports={{.Ports}}' 2>/dev/null || true
|
||||
}
|
||||
|
||||
find_ssh_port() {
|
||||
if [[ -n "$REQUESTED_PORT" ]]; then
|
||||
printf '%s\n' "$REQUESTED_PORT"
|
||||
else
|
||||
sshd -T 2>/dev/null | awk '$1 == "port" { print $2; exit }' || true
|
||||
fi
|
||||
}
|
||||
|
||||
print_plan() {
|
||||
show_state
|
||||
echo
|
||||
echo "修复计划(默认不执行):"
|
||||
if has_fix ssh-perms; then
|
||||
current_user=$(id -un)
|
||||
home=$(getent passwd "$current_user" | awk -F: '{print $6}')
|
||||
echo "- ssh-perms: 检查并修正 $home/.ssh=0700、$home/.ssh/authorized_keys=0600"
|
||||
fi
|
||||
if has_fix fail2ban; then
|
||||
port=$(find_ssh_port)
|
||||
echo "- fail2ban: 写入 /etc/fail2ban/jail.d/host-sec-check.local,SSH 端口=${port:-未识别}"
|
||||
if [[ -n "$IGNORE_CSV" ]]; then
|
||||
echo " ignoreip: $IGNORE_CSV"
|
||||
else
|
||||
echo " 阻断: --apply 前必须提供 --ignore-ip"
|
||||
fi
|
||||
fi
|
||||
echo "- firewall/SSH 策略/Docker 绑定/恶意文件: 只报告,不由脚本自动修改"
|
||||
}
|
||||
|
||||
backup_root=
|
||||
manifest=
|
||||
modes=
|
||||
|
||||
record_manifest() {
|
||||
local state=$1 path=$2
|
||||
as_root sh -c 'printf "%s %s\\n" "$1" "$2" >> "$3"' _ "$state" "$path" "$manifest"
|
||||
}
|
||||
|
||||
record_mode() {
|
||||
local mode path=$1
|
||||
mode=$(stat -c '%a' "$path")
|
||||
as_root sh -c 'printf "%s %s\\n" "$1" "$2" >> "$3"' _ "$mode" "$path" "$modes"
|
||||
}
|
||||
|
||||
backup_file() {
|
||||
local path=$1 dest
|
||||
dest="$backup_root$path"
|
||||
if [[ -e "$path" || -L "$path" ]]; then
|
||||
as_root install -d -m 0700 "$(dirname "$dest")"
|
||||
as_root cp -a -- "$path" "$dest"
|
||||
record_manifest present "$path"
|
||||
else
|
||||
record_manifest absent "$path"
|
||||
fi
|
||||
}
|
||||
|
||||
start_backup() {
|
||||
local id
|
||||
id=$(date -u +%Y%m%dT%H%M%SZ)
|
||||
backup_root="/var/backups/host-sec-check/$id"
|
||||
manifest="$backup_root/MANIFEST"
|
||||
modes="$backup_root/MODES"
|
||||
as_root install -d -m 0700 /var/backups/host-sec-check
|
||||
as_root mkdir -m 0700 "$backup_root"
|
||||
as_root install -m 0600 /dev/null "$manifest"
|
||||
as_root install -m 0600 /dev/null "$modes"
|
||||
echo "备份: $backup_root"
|
||||
}
|
||||
|
||||
apply_ssh_perms() {
|
||||
local user home ssh_dir auth
|
||||
user=$(id -un)
|
||||
home=$(getent passwd "$user" | awk -F: '{print $6}')
|
||||
[[ -n "$home" && "$home" != / ]] || { echo "[跳过] 无法识别当前用户 home"; return 1; }
|
||||
ssh_dir="$home/.ssh"
|
||||
auth="$ssh_dir/authorized_keys"
|
||||
if [[ -d "$ssh_dir" ]]; then
|
||||
record_mode "$ssh_dir"
|
||||
as_root chmod 700 "$ssh_dir"
|
||||
echo "[已修复] $ssh_dir mode=0700"
|
||||
else
|
||||
echo "[未修改] $ssh_dir 不存在"
|
||||
fi
|
||||
if [[ -f "$auth" ]]; then
|
||||
record_mode "$auth"
|
||||
as_root chmod 600 "$auth"
|
||||
echo "[已修复] $auth mode=0600"
|
||||
else
|
||||
echo "[未修改] $auth 不存在"
|
||||
fi
|
||||
}
|
||||
|
||||
apply_fail2ban() {
|
||||
local port ignore_line path=/etc/fail2ban/jail.d/host-sec-check.local
|
||||
command -v fail2ban-client >/dev/null 2>&1 || { echo "[阻断] 未安装 fail2ban-client;不自动安装系统包" >&2; return 1; }
|
||||
port=$(find_ssh_port)
|
||||
[[ "$port" =~ ^[0-9]+$ ]] || { echo "[阻断] 无法识别 SSH 端口" >&2; return 1; }
|
||||
as_root systemctl is-active --quiet fail2ban || { echo "[阻断] fail2ban 未运行;不自动启动服务" >&2; return 1; }
|
||||
ignore_line="127.0.0.1/8 ::1"
|
||||
IFS=, read -r -a extra_ips <<< "$IGNORE_CSV"
|
||||
for ip in "${extra_ips[@]}"; do
|
||||
[[ -n "$ip" ]] && ignore_line+=" $ip"
|
||||
done
|
||||
backup_file "$path"
|
||||
as_root install -d -m 0755 /etc/fail2ban/jail.d
|
||||
as_root tee "$path" >/dev/null <<EOF
|
||||
# Managed by host-sec-check. Backup: $backup_root
|
||||
[sshd]
|
||||
enabled = true
|
||||
backend = systemd
|
||||
filter = sshd
|
||||
port = $port
|
||||
ignoreip = $ignore_line
|
||||
maxretry = 5
|
||||
findtime = 10m
|
||||
bantime = 10m
|
||||
action = %(action_)s
|
||||
EOF
|
||||
as_root fail2ban-client -t
|
||||
as_root fail2ban-client reload
|
||||
as_root fail2ban-client status sshd
|
||||
echo "[已修复] $path"
|
||||
}
|
||||
|
||||
rollback() {
|
||||
backup_root="/var/backups/host-sec-check/$ROLLBACK_ID"
|
||||
manifest="$backup_root/MANIFEST"
|
||||
modes="$backup_root/MODES"
|
||||
as_root test -f "$manifest" || { echo "[阻断] 找不到备份: $backup_root" >&2; return 1; }
|
||||
while read -r state path; do
|
||||
[[ -n "${path:-}" ]] || continue
|
||||
if [[ ! "$path" =~ ^/root/\.ssh(/authorized_keys)?$ && ! "$path" =~ ^/home/[A-Za-z0-9._-]+/\.ssh(/authorized_keys)?$ && "$path" != /etc/fail2ban/jail.d/host-sec-check.local ]]; then
|
||||
echo "[阻断] 备份路径不在允许回滚范围: $path" >&2
|
||||
return 1
|
||||
fi
|
||||
case "$state" in
|
||||
present)
|
||||
source="$backup_root$path"
|
||||
[[ -e "$source" || -L "$source" ]] || { echo "[阻断] 备份文件缺失: $source" >&2; return 1; }
|
||||
as_root install -d -m 0755 "$(dirname "$path")"
|
||||
as_root cp -a -- "$source" "$path"
|
||||
echo "[已回滚] $path"
|
||||
;;
|
||||
absent)
|
||||
as_root rm -f -- "$path"
|
||||
echo "[已回滚] 删除本次新建文件 $path"
|
||||
;;
|
||||
*) echo "[阻断] MANIFEST 状态无效: $state" >&2; return 1 ;;
|
||||
esac
|
||||
done < <(as_root cat "$manifest")
|
||||
if as_root test -f "$modes"; then
|
||||
while read -r mode path; do
|
||||
[[ -n "${path:-}" && -e "$path" ]] || continue
|
||||
if [[ ! "$path" =~ ^/root/\.ssh(/authorized_keys)?$ && ! "$path" =~ ^/home/[A-Za-z0-9._-]+/\.ssh(/authorized_keys)?$ ]]; then
|
||||
echo "[阻断] 权限备份路径不在允许回滚范围: $path" >&2
|
||||
return 1
|
||||
fi
|
||||
as_root chmod "$mode" "$path"
|
||||
echo "[已回滚] $path mode=$mode"
|
||||
done < <(as_root cat "$modes")
|
||||
fi
|
||||
}
|
||||
|
||||
case "$MODE" in
|
||||
plan)
|
||||
print_plan
|
||||
;;
|
||||
apply)
|
||||
need_root
|
||||
start_backup
|
||||
trap 'rc=$?; echo "[部分失败] 已执行的变更可能不完整: $backup_root" >&2; echo "回滚命令: remediate.sh HOST --rollback $(basename "$backup_root") --confirm \"ROLLBACK $(basename "$backup_root")\"" >&2; exit "$rc"' ERR
|
||||
if has_fix ssh-perms; then apply_ssh_perms; fi
|
||||
if has_fix fail2ban; then apply_fail2ban; fi
|
||||
trap - ERR
|
||||
echo "应用完成。备份目录: $backup_root"
|
||||
;;
|
||||
rollback)
|
||||
need_root
|
||||
rollback
|
||||
;;
|
||||
*)
|
||||
echo "[阻断] 未知模式: $MODE" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
REMOTE
|
||||
@@ -0,0 +1,46 @@
|
||||
# ios-tester
|
||||
|
||||
检查并执行 iOS 真机或 Xcode Simulator 测试;在 Linux 上明确报告官方 Simulator 不可本地运行,并支持远程 Mac/云设备入口。
|
||||
|
||||
## 什么时候使用
|
||||
|
||||
- 「检查 iOS 测试环境」
|
||||
- 「用 iPhone 真机跑测试」
|
||||
- 「用 iOS Simulator 跑 smoke」
|
||||
- 「在远程 Mac 上跑 iOS 测试」
|
||||
- 「报告本次 iOS 测试结果」
|
||||
|
||||
## 使用前准备
|
||||
|
||||
- 本地 Simulator 或真机测试需要 macOS、Xcode 和对应平台组件。
|
||||
- 真机还需要设备配对、Developer Mode、签名和 Provisioning Profile。
|
||||
- Linux 上不能安装 Apple 官方 Simulator;需要提供远程 Mac、macOS CI 或云真机入口。
|
||||
- 项目需要提供 Xcode scheme、workspace/project、destination 和测试命令。
|
||||
|
||||
## 使用示例
|
||||
|
||||
```text
|
||||
检查当前机器是否可以跑 iOS Simulator
|
||||
```
|
||||
|
||||
```text
|
||||
用 iPhone 15 真机跑 iOS smoke,并保留 xcodebuild 日志
|
||||
```
|
||||
|
||||
```text
|
||||
在远程 Mac 上运行 iOS 测试,最后给出 pass/fail/environment-fail 结果
|
||||
```
|
||||
|
||||
## Agent 会做什么
|
||||
|
||||
1. 先判断当前是 macOS、本地 Linux、远程 Mac 还是云设备路径。
|
||||
2. 检查 Xcode、Simulator runtime、设备配对、签名和测试命令。
|
||||
3. 环境完整后执行测试;环境不完整时停止,不将阻塞误报为产品失败。
|
||||
4. 采集测试日志、失败诊断和可用的截图或测试产物。
|
||||
5. 生成包含目标、环境、用例结果和证据路径的运行报告。
|
||||
|
||||
## 如何判断完成
|
||||
|
||||
- 有明确的目标路径和环境检查结论。
|
||||
- 每条测试都有标准结果状态。
|
||||
- macOS/远程执行有日志和产物;Linux 本地不可行时有清晰的修复建议。
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
name: ios-tester
|
||||
description: >-
|
||||
检查并运行 iOS 真机或 Xcode Simulator 测试,生成可追溯结果;支持 Linux 上识别
|
||||
不可本地运行 Simulator 的边界,并通过 macOS 或远程 Mac 执行。触发词:iOS 测试、
|
||||
苹果测试、iPhone 真机、iOS Simulator、Xcode 测试、远程 Mac 测试。
|
||||
---
|
||||
|
||||
# iOS Tester
|
||||
|
||||
本 skill 负责 iOS 测试环境判定、测试执行编排和结果报告,不伪造 Linux 上不存在的
|
||||
iOS Simulator。项目根是 `git rev-parse --show-toplevel`。
|
||||
|
||||
远程 Mac 的 environment/project/path、Agent CLI、model 和 reasoning effort 使用共享
|
||||
`agent-runtime` 的 binding(例如 `builder.ios` 或 `tester.ios`);本 skill 只负责 iOS
|
||||
工具链和设备环境门禁。Linux 没有本地 iOS 工具链时,不能把远程 binding 静默改成本机。
|
||||
|
||||
## 模式路由
|
||||
|
||||
- 用户要求检查环境:先读 `references/environment.md`。
|
||||
- 用户要求真机测试:读 `references/device.md`。
|
||||
- 用户要求 Simulator 测试:读 `references/simulator.md`。
|
||||
- 用户要求远程 Mac 或云设备:先读取对应目标配置,再按同一环境/执行/报告闭环。
|
||||
- 用户要求结果或失败复盘:读 `references/reporting.md`。
|
||||
|
||||
## 全局硬规则
|
||||
|
||||
- 每次执行前必须检查环境;环境不完整记 `environment-fail`。
|
||||
- 真机、Simulator、远程 Mac 必须由用户明确选择,禁止自动 fallback。
|
||||
- Linux 本机不能安装或运行 Apple 官方 iOS Simulator;不能把 Android 模拟器或浏览器
|
||||
结果冒充 iOS 结果。
|
||||
- macOS/Xcode 是本地 iOS Simulator 和完整 iOS 真机开发测试的官方工具链。
|
||||
- 不自动申请 Apple Developer 账号、签名证书、Provisioning Profile 或设备授权。
|
||||
- 不清除真机数据、不重启真机、不修改 Apple 账号或钥匙串。
|
||||
- 结果使用 `pass/fail/environment-fail/skipped/not-run`,并区分环境阻塞与产品失败。
|
||||
|
||||
## 运行顺序
|
||||
|
||||
1. 明确目标:local-device、local-simulator、remote-mac 或 cloud-device。
|
||||
2. 检查 Xcode、Simulator runtime、设备配对/签名和项目测试配置。
|
||||
3. 只有环境通过后才构建、安装或运行测试。
|
||||
4. 采集 xcodebuild、设备/Simulator 日志和失败证据。
|
||||
5. 生成运行快照、成绩单和结果总结。
|
||||
|
||||
## 验证
|
||||
|
||||
- `pouch check ios-tester` 通过。
|
||||
- macOS Simulator 和物理设备各完成一条 readonly 测试,或在 Linux 上明确得到
|
||||
Simulator 不可用的 `environment-fail` 报告。
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user