diff --git a/README.md b/README.md index 431682e..d4c1170 100644 --- a/README.md +++ b/README.md @@ -37,32 +37,37 @@ We think accounting for AI-assisted delivery is an open industry question. devle - **Zero-input accounting**: no timesheets to fill, no boards to update. The AI records deliverables at session end — a hard rule, not a habit. - **Evidence-first**: every ledger entry links real commits (`(#N)` convention) and verification results, with decision context captured while it's still fresh (why now, what alternatives were rejected). -- **Single source of truth**: issues are the ledger; Project fields and README summaries are derived views, rebuildable anytime via the reconcile tool. -- **One repo, one project**: Project name = repo name. Nothing to configure. +- **Single source of truth**: issues are the ledger; Project fields and timesheets are derived views. Reconcile checks Project fields against a ledger file or delivery-round labels. +- **One repo, one project**: New Projects use the repository name. Repeat onboarding uses the Project number recorded in the repository. ## Quick start -**See it in 2 minutes** (no AI, no real repo needed — auto sandbox, auto ledger, auto timesheet): +**Install and check dependencies** ```bash -bash ~/.agents/skills/devledger/scripts/demo.sh +git clone https://github.com/guanlili/devledger.git ~/.agents/skills/devledger +bash ~/.agents/skills/devledger/scripts/install.sh ``` -**Install / Update** — the same idempotent command does both (and self-checks gh auth & scopes): +Run `install.sh` again to update. To try the workflow, run `bash ~/.agents/skills/devledger/scripts/demo.sh`. The demo creates a private sandbox repository, a Project, and a sample timesheet. + +**Onboard a repository** ```bash -git clone https://github.com/guanlili/devledger.git ~/.agents/skills/devledger -bash ~/.agents/skills/devledger/scripts/install.sh # install; re-run anytime to update/repair +bash ~/.agents/skills/devledger/scripts/new-project.sh YOUR_OWNER/YOUR_REPO ``` -**Onboard your repo** (one command; Project name = repo name): +Rerunning onboarding uses the recorded Project number and preserves its Status options and views. If an unconfigured repository has a matching Project name, verify the Project and rerun with `PM_RESUME=`. + +**Record work and export** + +At session end, the agent creates or reuses an issue and runs [`bookkeep.py`](scripts/bookkeep.py). It reads back the Project fields before closing the issue. After an interruption, rerun with the same issue URL and arguments. See [scenario B in SKILL.md](SKILL.md). ```bash -bash ~/.agents/skills/devledger/scripts/new-project.sh +python3 ~/.agents/skills/devledger/scripts/export-timesheet.py --project 123 --customer ``` -Daily loop: work with your AI as usual → session end auto-records the ledger. -Acceptance: `python3 scripts/export-timesheet.py --project --customer`. +Replace `123` with your Project number. `--customer` filters to client-requested items. If hours are missing, the workbook lists the affected issues and labels the total as recorded hours only. ## How it works @@ -100,7 +105,7 @@ flowchart LR v -. "one command at acceptance" .-> x["client-ready xlsx"] ``` -Requires `gh` CLI (project scopes), bash 3.2+, and Python 3. Exports also require openpyxl. Works with ZCode, Claude Code, Cursor — any agent that reads SKILL.md/AGENTS.md. +Requires `gh` with Project access, Git, Bash 3.2+, and Python 3. Onboarding requires `jq`, and exports require `openpyxl`. Works with ZCode, Claude Code, Cursor — any agent that reads SKILL.md/AGENTS.md. ## Documentation diff --git a/README.zh-CN.md b/README.zh-CN.md index c6fd920..00cbbea 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -50,22 +50,39 @@ flowchart LR ## 快速上手 +**安装与自检** + ```bash -# ① 2 分钟看效果(自动建沙盒→接入→记 2 条账→导出验收表,无需 AI 和真实仓库) -bash ~/.agents/skills/devledger/scripts/demo.sh -# ② 安装(HTTPS 免 SSH key) git clone https://github.com/guanlili/devledger.git ~/.agents/skills/devledger -# ③ 接入你的仓库(一条命令) -bash ~/.agents/skills/devledger/scripts/new-project.sh +bash ~/.agents/skills/devledger/scripts/install.sh +``` + +更新时重跑 `install.sh`。想先体验,可以运行 `bash ~/.agents/skills/devledger/scripts/demo.sh`,创建私有沙盒仓库、Project 和示例验收表。接入需要有 Project 权限的 `gh`、Git、Bash 3.2+、Python 3 和 `jq`,导出另需 `openpyxl`。 + +**接入仓库** + +```bash +bash ~/.agents/skills/devledger/scripts/new-project.sh YOUR_OWNER/YOUR_REPO +``` + +重复接入会复用仓库登记的 Project 编号,并保留已有 Status 选项和视图。如果仓库尚未登记编号,但已有同名 Project,核对后用 `PM_RESUME=<编号>` 重跑。 + +**记账与验收** + +Agent 在会话收尾时创建或复用 issue,再运行 [`bookkeep.py`](scripts/bookkeep.py)。命令读回看板字段,确认后关闭 issue。中断时用同一 issue URL 和相同参数续跑,命令示例见 [SKILL.md 的场景 B](SKILL.md)。 + +```bash +python3 ~/.agents/skills/devledger/scripts/export-timesheet.py --project 123 --customer ``` -**更新 = 重跑安装命令**:`bash ~/.agents/skills/devledger/scripts/install.sh`(同一条命令完成 安装/更新/自检,坏了随时重跑) +把 `123` 换成实际 Project 编号。`--customer` 仅导出甲方来源条目。有未填工时的条目时,验收表会列出对应 issue,并注明合计只包含已填工时。 | 路径 | 用途 | |---|---| | `SKILL.md` | **Agent 执行入口**:决策树 + 场景命令 | | `AGENTS.md` | 跨 Agent(Claude Code/Cursor 等)接口与红线 | -| `scripts/new-project.sh` | 一键建项:Project(Status 中文化+6字段+View 9列)+ labels + 规范注入 | +| `scripts/new-project.sh` | 建项或接入已有 Project,补齐字段、标签和仓库规范 | +| `scripts/bookkeep.py` | 按 issue URL 入板、补字段并读回确认,支持续跑 | | `scripts/export-timesheet.py` | 验收 xlsx(动态列,甲方版 `--customer`) | | `scripts/fill-field.py` | 批量字段填充(读回验证内置,幂等重跑) | | `scripts/reconcile.py` | 字段对账(读回→diff→补写循环;`--from-labels` 重建) | @@ -102,7 +119,7 @@ devledger 面向正在成型的全新协作形态:**一个技术负责人 + ## 他人一句话接入 -对其 AI 说:「克隆 guanlili/devledger 到 ~/.agents/skills/devledger,跑 install.sh,按 SKILL.md 给我的仓库 接入项目管理」。管理员需先:加 devledger 仓库协作者 + 确认目标仓库写权限。 +对其 AI 说:「克隆 guanlili/devledger 到 ~/.agents/skills/devledger,跑 install.sh,按 SKILL.md 给我的仓库 接入项目管理」。接入者需要目标仓库和目标 Project 的写权限。 ## 支持 diff --git a/SKILL.md b/SKILL.md index 2fef2d1..b6ef1d3 100644 --- a/SKILL.md +++ b/SKILL.md @@ -40,10 +40,10 @@ GitHub Projects(数据层:issue + 6 字段;一仓库一 Project,名=仓 ```bash scripts/new-project.sh [--local <项目本地路径>] # 脚手架项目(本地已克隆)加 --local:替换占位符并本地提交;存量仓库走 API 注入 -# 中断续跑:PM_RESUME= 前缀重跑 +# 中断续跑或确认接入已有同名 Project:PM_RESUME= 前缀重跑 ``` -自动完成:Project(名=仓库名,Status 中文化+6字段+View 9列)+ 5 类型 label + 规范注入(CLAUDE.md 小节、AGENTS.md 小节、issue 模板)。验证:`gh project view <编号>` 有 6 个自定义字段。 +新建空 Project 时设置默认 Status 和视图。重复接入优先用仓库规范登记的编号,并保留已有 Status 和视图。没有登记时,同名 Project 需用 `PM_RESUME` 明确选择。脚本补齐 6 个自定义字段和类型标签,并注入仓库规范。 ## 场景 B:日常记账(AI 会话收尾,硬性纪律) diff --git a/scripts/_common.py b/scripts/_common.py index d766a98..5e26614 100644 --- a/scripts/_common.py +++ b/scripts/_common.py @@ -1,28 +1,60 @@ """共享工具:限流感知的 gh 调用、GraphQL 封装与值归一(scripts/ 内各脚本公用)。 -设计:单点维护限流策略(主限流按退避、次级限流长睡);`--value` 通吃字段类型(实测)。 +读操作根据限流响应退避,写操作失败后由调用方读回。 """ import json import subprocess import time +def retry_delay(status, headers, error, attempt): + """返回下一次读取前等待的秒数,None 表示立即返回错误。""" + error = error.lower() + rate_limited = (status == 429 or "rate limit" in error + or (status == 403 and (headers.get("x-ratelimit-remaining") == "0" + or "retry-after" in headers))) + if rate_limited: + retry_after = headers.get("retry-after", "") + reset = headers.get("x-ratelimit-reset", "") + if retry_after.isdecimal(): + return int(retry_after) + if headers.get("x-ratelimit-remaining") == "0" and reset.isdecimal(): + return max(0, int(reset) - time.time() + 1) + return 60 * 2 ** attempt + if status in (408, 500, 502, 503, 504) or error == "timeout": + return 15 * (attempt + 1) + if any(message in error for message in ("connection reset", "connection refused", "i/o timeout", "tls handshake timeout")): + return 15 * (attempt + 1) + return None + + def run(args, retries=5, timeout=180, pace=0): - """执行命令,失败重试;rate limit 类错误退避 300s,其余线性退避。pace=成功后间歇秒数。""" - last = "" - for a in range(retries): + """读取可按响应退避。写入调用应传 retries=1,失败后读回再决定是否补写。""" + include = args[:2] == ["gh", "api"] and "--paginate" not in args and "--jq" not in args + command = [*args[:2], "--include", *args[2:]] if include else args + for attempt in range(retries): + status, headers = None, {} try: - r = subprocess.run(args, capture_output=True, text=True, timeout=timeout) + result = subprocess.run(command, capture_output=True, text=True, timeout=timeout) + rc, out, err = result.returncode, result.stdout, result.stderr.strip() except subprocess.TimeoutExpired: - r = type("R", (), {"returncode": 1, "stdout": "", "stderr": "timeout"})() - if r.returncode == 0: + rc, out, err = 1, "", "timeout" + if include and out.startswith("HTTP/"): + header, _, out = out.partition("\n\n") + status_line, *lines = header.splitlines() + status = int(status_line.split()[1]) + for line in lines: + key, _, value = line.partition(":") + headers[key.lower()] = value.strip() + if rc == 0: if pace: time.sleep(pace) - return r.returncode, r.stdout.strip(), r.stderr.strip() - last = r.stderr.strip() - if a + 1 < retries: - time.sleep(300 if "rate limit" in last.lower() else 15 * (a + 1)) - return 1, "", last + return rc, out.strip(), err + delay = retry_delay(status, headers, err, attempt) + if delay is None or attempt + 1 == retries: + return rc, out.strip(), err + time.sleep(delay) + return 1, "", "重试次数必须大于 0" def gql(query, retries=5, *, cursor=None): diff --git a/scripts/_onboarding.py b/scripts/_onboarding.py new file mode 100644 index 0000000..a8083ea --- /dev/null +++ b/scripts/_onboarding.py @@ -0,0 +1,70 @@ +"""读取仓库已登记的 Project 编号,或激活本地模板。""" + +import base64 +import re +import subprocess +import sys +from pathlib import Path + +DOCS = ("CLAUDE.md", "AGENTS.md") +TEMPLATE = ".github/ISSUE_TEMPLATE/需求.md" +SECTION = re.compile(r"^## 项目管理(?:记账)?(devledger[^\n]*\n(.*?)(?=^## |\Z)", re.M | re.S) +PROJECT = re.compile(r"GitHub Project\s*`?#(\d+)") + + +def remote_doc(repo, path): + result = subprocess.run( + ["gh", "api", f"repos/{repo}/contents/{path}", "--jq", ".content"], + capture_output=True, text=True, + ) + if result.returncode == 0: + return base64.b64decode(result.stdout).decode("utf-8") + if "HTTP 404" in result.stderr: + return "" + raise SystemExit(f"无法读取 {path}:{result.stderr.strip()}") + + +def recorded_project(repo, directory): + numbers = set() + for name in DOCS: + if directory: + path = Path(directory, name) + content = path.read_text(encoding="utf-8") if path.is_file() else "" + else: + content = remote_doc(repo, name) + for section in SECTION.findall(content): + numbers.update(PROJECT.findall(section)) + if len(numbers) > 1: + raise SystemExit("仓库规范登记了多个 Project 编号,请先核对") + return next(iter(numbers), "") + + +def activate(directory, project): + changed = [] + for name in (*DOCS, TEMPLATE): + path = Path(directory, name) + if not path.is_file(): + continue + original = path.read_bytes() + updated = original.replace(b"__PM_PROJECT__", project.encode("ascii")) + if updated != original: + path.write_bytes(updated) + changed.append(name) + if changed: + git = ["git", "-C", directory] + subprocess.run([*git, "add", "--", *changed], check=True) + subprocess.run( + [*git, "commit", "--only", "-m", f"chore: devledger 项目管理激活(Project #{project})", + "--", *changed], check=True, + ) + return len(changed) + + +if __name__ == "__main__": + action, first, second = sys.argv[1:] + if action == "lookup": + print(recorded_project(first, second)) + else: + changed = activate(first, second) + if not changed: + print("本地规范无需替换。") diff --git a/scripts/demo.sh b/scripts/demo.sh index 20c0493..e109d0c 100755 --- a/scripts/demo.sh +++ b/scripts/demo.sh @@ -19,8 +19,8 @@ grep -E 'Project #|建项完成' "${ONLOG}" | head -2 || true rm -f "${ONLOG}" say "[3/5] 记 2 条账(模拟 AI 会话收尾的产出)" -N=$(gh api graphql -f query='{viewer{projectsV2(first:10){nodes{number title}}}}' \ - --jq ".data.viewer.projectsV2.nodes[] | select(.title == \"${NAME}\") | .number" | head -1) +N=$(python3 "${DL}/scripts/_onboarding.py" lookup "${REPO}" "") +[ -n "${N}" ] || { say "未找到接入登记的 Project 编号"; exit 1; } DEMO1=$(mktemp /tmp/dl-demo1.XXXXXX.md); DEMO2=$(mktemp /tmp/dl-demo2.XXXXXX.md) cat > "${DEMO1}" <<'MD' ## 来源 diff --git a/scripts/export-timesheet.py b/scripts/export-timesheet.py index cc3e5fa..4e4c02a 100644 --- a/scripts/export-timesheet.py +++ b/scripts/export-timesheet.py @@ -12,9 +12,8 @@ """ import argparse import json -import subprocess +import math import sys -import time from datetime import date QUERY = """ @@ -49,7 +48,7 @@ import os as _os import sys as _sys _sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) -from _common import gql, run # noqa: E402 +from _common import run # noqa: E402 def gh_graphql(query, cursor=None, retries=3): """GraphQL 分页读 Project(限流退避见 _common)。""" @@ -71,12 +70,14 @@ def fetch_items(project_number): page = project["items"] for node in page["nodes"]: content = node.get("content") or {} + if not content.get("url"): + continue row = {name: "" for name in COLUMNS} row["需求名称"] = content.get("title", "") row["链接"] = content.get("url", "") row["状态"] = "已完成" if content.get("state") == "CLOSED" else "进行中" for value in (node.get("fieldValues") or {}).get("nodes", []): - field = value.get("field", {}).get("name") + field = (value.get("field") or {}).get("name") if field == "Status": row["状态"] = value.get("name", row["状态"]) elif field in row: @@ -87,10 +88,21 @@ def fetch_items(project_number): cursor = page["pageInfo"]["endCursor"] +def has_hours(row): + value = row.get("工时(h)") + return type(value) in (int, float) and math.isfinite(value) + + +def append_values(sheet, values): + sheet.append(values) + for cell in sheet[sheet.max_row]: + if isinstance(cell.value, str): + cell.data_type = "s" + + def build_sheet(rows, project_title, subtitle): - global COLUMNS - if rows and all(not r.get("交付轮次") for r in rows): - COLUMNS = [c for c in COLUMNS if c != "交付轮次"] + columns = [c for c in COLUMNS if c != "交付轮次" or not rows or any(r.get(c) for r in rows)] + missing = [row for row in rows if not has_hours(row)] from openpyxl import Workbook from openpyxl.styles import Alignment, Font, PatternFill from openpyxl.utils import get_column_letter @@ -102,31 +114,39 @@ def build_sheet(rows, project_title, subtitle): header_font = Font(bold=True, color="FFFFFF") # 交付级表头块:项目名 / 筛选说明 / 导出日期 ws["A1"] = project_title + ws["A1"].data_type = "s" ws["A1"].font = Font(bold=True, size=14) ws["A2"] = subtitle + ws["A2"].data_type = "s" ws["A3"] = f"导出日期:{date.today():%Y-%m-%d} 制表:GitHub Project 自动生成" ws["A3"].font = Font(color="808080") - ws.append([]) - ws.append(COLUMNS) + if missing: + ws["A4"] = f"{len(missing)} 条未填工时,详见「缺失工时」。合计仅包含已填工时。" + ws.cell(row=5, column=1) + for index, column in enumerate(columns, 1): + ws.cell(row=5, column=index, value=column) header_row = ws.max_row for cell in ws[header_row]: cell.fill, cell.font = header_fill, header_font cell.alignment = Alignment(horizontal="center") rows.sort(key=lambda r: (str(r["开始"]), str(r["需求名称"]))) for row in rows: - ws.append([row[c] for c in COLUMNS]) - total = sum(r["工时(h)"] or 0 for r in rows if isinstance(r["工时(h)"], (int, float))) - hours_col = COLUMNS.index("工时(h)") + 1 - link_col = COLUMNS.index("链接") + 1 - ws.append(["合计" if i == 1 else (total if i == hours_col else "") for i in range(1, len(COLUMNS) + 1)]) + append_values(ws, [row[c] for c in columns]) + total = sum(r["工时(h)"] or 0 for r in rows if has_hours(r)) + hours_col = columns.index("工时(h)") + 1 + link_col = columns.index("链接") + 1 + total_label = "已填工时合计" if missing else "合计" + ws.append([total_label if i == 1 else (total if i == hours_col else "") for i in range(1, len(columns) + 1)]) ws.cell(row=ws.max_row, column=1).font = Font(bold=True) ws.cell(row=ws.max_row, column=hours_col).font = Font(bold=True) widths = {"需求名称": 38, "类型": 8, "来源": 7, "需求人": 10, "状态": 9, "工时(h)": 9, "开始": 12, "结束": 12, "交付轮次": 18, "链接": 44} - for i, name in enumerate(COLUMNS, 1): + for i, name in enumerate(columns, 1): ws.column_dimensions[get_column_letter(i)].width = widths.get(name, 12) - for r in range(header_row + 1, ws.max_row + 1): - ws.cell(row=r, column=link_col).hyperlink = ws.cell(row=r, column=link_col).value + for r in range(header_row + 1, ws.max_row): + cell = ws.cell(row=r, column=link_col) + if cell.value: + cell.hyperlink = cell.value ws.freeze_panes = f"A{header_row + 1}" overview = wb.create_sheet("工时概览") @@ -138,11 +158,20 @@ def build_sheet(rows, project_title, subtitle): for r in rows: key = str(r[dim] or "未填") hours, count = agg.get(key, (0, 0)) - agg[key] = (hours + (r["工时(h)"] if isinstance(r["工时(h)"], (int, float)) else 0), count + 1) + agg[key] = (hours + (r["工时(h)"] if has_hours(r) else 0), count + 1) for key, (hours, count) in sorted(agg.items()): - overview.append([dim, key, hours, count]) + append_values(overview, [dim, key, hours, count]) for i, w in enumerate([10, 24, 10, 8], 1): overview.column_dimensions[get_column_letter(i)].width = w + if missing: + details = wb.create_sheet("缺失工时") + details.append(["需求名称", "链接"]) + for row in missing: + append_values(details, [row["需求名称"], row["链接"]]) + if row["链接"]: + details.cell(row=details.max_row, column=2).hyperlink = row["链接"] + details.column_dimensions["A"].width = 38 + details.column_dimensions["B"].width = 52 return wb @@ -166,7 +195,10 @@ def main(): subtitle_parts.append("来源:甲方" if args.customer else "来源:全部") wb = build_sheet(items, project_title, " | ".join(subtitle_parts)) wb.save(args.output) - hours = sum(i["工时(h)"] for i in items if isinstance(i["工时(h)"], (int, float))) + hours = sum(i["工时(h)"] for i in items if has_hours(i)) + missing = [i for i in items if not has_hours(i)] + if missing: + print(f"工时未填:{len(missing)} 条,合计仅包含已填工时。详见工作簿「缺失工时」。", file=sys.stderr) customer_count = sum(1 for i in items if i["来源"] == "甲方") print(f"已导出 {args.output}:{len(items)} 条,合计 {hours}h,其中甲方来源 {customer_count} 条") diff --git a/scripts/fill-field.py b/scripts/fill-field.py index dd3fba8..a29ac76 100755 --- a/scripts/fill-field.py +++ b/scripts/fill-field.py @@ -94,9 +94,9 @@ def main(): sys.exit(f"FILL INCOMPLETE:读回仍有 {len(todo)} 条差异") for it in todo: rc, _, err = run(["gh", "project", "item-edit", str(args.project), "--owner", "@me", - "--url", it["url"], "--field", args.field, "--value", args.value], pace=1.5) + "--url", it["url"], "--field", args.field, "--value", args.value], retries=1, pace=1.5) if rc != 0: - print(f" FAIL {it['title'][:30]}: {err[:60]}", flush=True) + sys.exit(f"写入未确认 {it['title']}: {err}。请稍后重跑,脚本将读回再补差异。") time.sleep(10) diff --git a/scripts/install.sh b/scripts/install.sh index 99da73e..3998b99 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -31,6 +31,9 @@ say "devledger ${VER:-unknown}" # 4) 前置自检 command -v gh >/dev/null 2>&1 || { say "缺 gh CLI:brew install gh(https://cli.github.com),装好后重跑本命令"; exit 1; } say "gh CLI:$(gh --version | head -1)" +for dep in jq python3; do + command -v "${dep}" >/dev/null 2>&1 || { say "缺少接入依赖:${dep},安装后重跑"; exit 1; } +done gh auth status >/dev/null 2>&1 || { say "未登录 GitHub:gh auth login(浏览器确认一次),再重跑"; exit 1; } SCOPES=$(gh auth status 2>&1 | grep -o "scopes:.*" || true) case "${SCOPES}" in diff --git a/scripts/new-project.sh b/scripts/new-project.sh index 34172f1..5e21d6c 100755 --- a/scripts/new-project.sh +++ b/scripts/new-project.sh @@ -14,6 +14,10 @@ if [ -z "${REPO}" ]; then echo "用法: new-project.sh [--local <项目路径>] Project 名=仓库名(客户名请含在仓库名里)" >&2 exit 1 fi +for dep in gh jq python3; do + command -v "${dep}" >/dev/null 2>&1 || { echo "缺少接入依赖:${dep}" >&2; exit 1; } +done +PM_DIR="$(cd "$(dirname "$0")/.." && pwd)" REPO_NAME="${REPO##*/}" TITLE="${REPO_NAME}" PACE=2 # 写操作间隔秒数,防次级限流 @@ -27,6 +31,12 @@ gql() { # gql '' [额外gh参数...] → stdout 透传 gh 输出;失败 if out=$(gh api graphql -f query="${q}" "$@" 2>"${errf}"); then printf '%s' "${out}"; rm -f "${errf}"; return 0 fi + case "${q}" in + mutation*) break ;; + esac + if [ "${attempt}" -eq 4 ] || grep -Eqi 'HTTP (400|401|403|404|422)|rate limit|forbidden|permission' "${errf}"; then + break + fi say " graphql 失败(第${attempt}次),重试..." sleep $((attempt * 15)) done @@ -60,36 +70,39 @@ mkfield() { # $1=字段名 $2=类型 $3=选项(可空) → stdout 输出 field i say "字段 ${1} 创建失败"; exit 1 } -# ---------- 1. 建 Project(PM_RESUME=<编号> 可续跑半成品) ---------- -if [ -n "${PM_RESUME:-}" ]; then - PJ_NUM="${PM_RESUME}" - PJ_JSON=$(gql "query { viewer { projectV2(number: ${PJ_NUM}) { id url title } } }" --jq '.data.viewer.projectV2') - PJ_ID=$(jq -r .id <<<"${PJ_JSON}") - PJ_URL=$(jq -r .url <<<"${PJ_JSON}") - say "续跑 Project #${PJ_NUM} ${PJ_URL}" +# ---------- 1. 优先复用仓库登记的 Project ---------- +RECORDED=$(python3 "${PM_DIR}/scripts/_onboarding.py" lookup "${REPO}" "${LOCAL_DIR}") +PJ_NUM="${PM_RESUME:-${RECORDED}}" +NEW_PROJECT=0 +if [ -n "${PJ_NUM}" ]; then + case "${PJ_NUM}" in + 0*|*[!0-9]*) say "无效 Project 编号:${PJ_NUM}"; exit 1 ;; + esac + if [ -n "${RECORDED}" ] && [ "${RECORDED}" != "${PJ_NUM}" ]; then + say "PM_RESUME 与仓库已登记的 Project #${RECORDED} 不一致" + exit 1 + fi + PJ_JSON=$(gql "query { viewer { projectV2(number: ${PJ_NUM}) { id url } } }" --jq '.data.viewer.projectV2') else - say "创建 Project: ${TITLE}" - PJ_EXIST=$(gql "query { viewer { projectsV2(first: 30) { nodes { number title url id } } } }" --jq '.data.viewer.projectsV2.nodes' || true) - PJ_JSON=$(jq -c --arg t "${TITLE}" '.[] | select(.title == $t)' <<<"${PJ_EXIST}" 2>/dev/null | head -1) - if [ -n "${PJ_JSON:-}" ] && [ "${PJ_JSON}" != "null" ]; then - PJ_NUM=$(jq -r .number <<<"${PJ_JSON}"); PJ_ID=$(jq -r .id <<<"${PJ_JSON}"); PJ_URL=$(jq -r .url <<<"${PJ_JSON}") - say " 复用已存在的 Project #${PJ_NUM}(同名去重,重跑安全)" - else - PJ_JSON="" - for attempt in 1 2 3 4; do - if PJ_JSON=$(gh project create --owner "@me" --title "${TITLE}" --format json 2>/dev/null); then break; fi - say " 创建失败(第${attempt}次),重试..." - sleep $((attempt * 15)) - PJ_JSON="" - done - [ -n "${PJ_JSON}" ] || { say "Project 创建失败"; exit 1; } - PJ_NUM=$(jq -r .number <<<"${PJ_JSON}") - PJ_ID=$(jq -r .id <<<"${PJ_JSON}") - PJ_URL=$(jq -r .url <<<"${PJ_JSON}") - say " Project #${PJ_NUM} ${PJ_URL}(中断后可 PM_RESUME=${PJ_NUM} 续跑)" - sleep "${PACE}" + PROJECTS=$(gql 'query($endCursor: String) { + viewer { projectsV2(first: 100, after: $endCursor) { + pageInfo { hasNextPage endCursor } + nodes { number title } + } } + }' --paginate --jq '.data.viewer.projectsV2.nodes[]') + MATCHES=$(jq -rs --arg t "${TITLE}" 'map(select(.title == $t)) | map(.number | tostring) | join(", ")' <<<"${PROJECTS}") + if [ -n "${MATCHES}" ]; then + say "存在同名 Project(${MATCHES}),请核对后用 PM_RESUME=<编号> 明确选择" + exit 1 fi + say "创建 Project: ${TITLE}" + PJ_JSON=$(gh project create --owner "@me" --title "${TITLE}" --format json) + PJ_NUM=$(jq -er '.number | select(type == "number" and . > 0)' <<<"${PJ_JSON}") + NEW_PROJECT=1 fi +PJ_ID=$(jq -er '.id | select(type == "string" and length > 0)' <<<"${PJ_JSON}") +PJ_URL=$(jq -er '.url | select(type == "string" and length > 0)' <<<"${PJ_JSON}") +say "Project #${PJ_NUM} ${PJ_URL}(中断后可 PM_RESUME=${PJ_NUM} 续跑)" # ---------- 2. 建 6 个自定义字段 ---------- FID_FTYPE=$(mkfield "类型" SINGLE_SELECT "需求,缺陷,优化,交付线,文档") @@ -105,37 +118,47 @@ say " 字段ok 来源=${FID_FSOURCE}" FID_FREQ=$(mkfield "需求人" TEXT "") say " 字段ok 需求人=${FID_FREQ}" -# ---------- 3. Status 选项中文化 ---------- -say "Status 选项中文化" -ALL_FIELDS=$(gql "query { node(id: \"${PJ_ID}\") { ... on ProjectV2 { fields(first: 30) { nodes { ... on ProjectV2FieldCommon { id name } } } } } }" \ - --jq '.data.node.fields.nodes') -STATUS_ID=$(jq -r '.[] | select(.name == "Status") | .id' <<<"${ALL_FIELDS}") -TITLE_ID=$(jq -r '.[] | select(.name == "Title") | .id' <<<"${ALL_FIELDS}") -ASSIGNEE_ID=$(jq -r '.[] | select(.name == "Assignees") | .id' <<<"${ALL_FIELDS}") -# 坑6:singleSelectOptions 重交会清空全部条目已选值——选项已一致时必须跳过 mutation(读回比对) -CURRENT_OPTS=$(gql "query { node(id: \"${STATUS_ID}\") { ... on ProjectV2SingleSelectField { options { name } } } }" \ - --jq '[.data.node.options[].name] | join(",")') -if [ "${CURRENT_OPTS}" = "待办,开发中,已完成" ]; then - say " Status 选项已是中文,跳过(坑6:重交会清空条目已选值)" -else - gql "mutation { updateProjectV2Field(input: {fieldId: \"${STATUS_ID}\", singleSelectOptions: [ - {name: \"待办\", color: GRAY, description: \"\"}, - {name: \"开发中\", color: YELLOW, description: \"\"}, - {name: \"已完成\", color: GREEN, description: \"\"} - ]}) { projectV2Field { ... on ProjectV2SingleSelectField { options { name } } } } }" >/dev/null - say " Status=${STATUS_ID} 选项: 待办/开发中/已完成" +# 现有看板保留 Status 选项和视图列。检查新建看板仍为空再应用默认配置。 +if [ "${NEW_PROJECT}" -eq 1 ] && [ "$(gql "query { viewer { projectV2(number: ${PJ_NUM}) { items(first: 1) { totalCount } } } }" --jq '.data.viewer.projectV2.items.totalCount')" = 0 ]; then + # ---------- 3. Status 选项中文化 ---------- + say "Status 选项中文化" + ALL_FIELDS=$(gql "query { node(id: \"${PJ_ID}\") { ... on ProjectV2 { fields(first: 30) { nodes { ... on ProjectV2FieldCommon { id name } } } } } }" \ + --jq '.data.node.fields.nodes') + STATUS_ID=$(jq -r '.[] | select(.name == "Status") | .id' <<<"${ALL_FIELDS}") + TITLE_ID=$(jq -r '.[] | select(.name == "Title") | .id' <<<"${ALL_FIELDS}") + ASSIGNEE_ID=$(jq -r '.[] | select(.name == "Assignees") | .id' <<<"${ALL_FIELDS}") + # 坑6:singleSelectOptions 重交会清空全部条目已选值——选项已一致时必须跳过 mutation(读回比对) + CURRENT_OPTS=$(gql "query { node(id: \"${STATUS_ID}\") { ... on ProjectV2SingleSelectField { options { name } } } }" \ + --jq '[.data.node.options[].name] | join(",")') + if [ "${CURRENT_OPTS}" = "待办,开发中,已完成" ]; then + say " Status 选项已是中文,跳过(坑6:重交会清空条目已选值)" + else + gql "mutation { updateProjectV2Field(input: {fieldId: \"${STATUS_ID}\", singleSelectOptions: [ + {name: \"待办\", color: GRAY, description: \"\"}, + {name: \"开发中\", color: YELLOW, description: \"\"}, + {name: \"已完成\", color: GREEN, description: \"\"} + ]}) { projectV2Field { ... on ProjectV2SingleSelectField { options { name } } } } }" >/dev/null + say " Status=${STATUS_ID} 选项: 待办/开发中/已完成" + sleep "${PACE}" + fi + + # ---------- 4. View 1 配可见列(API 建的字段不会自动进视图) ---------- + say "配置 View 1 可见列" + VIEW_ID=$(gql "query { node(id: \"${PJ_ID}\") { ... on ProjectV2 { views(first: 5) { nodes { id name } } } } }" \ + --jq '.data.node.views.nodes[0].id') + VFIDS="\"${TITLE_ID}\", \"${STATUS_ID}\", \"${FID_FTYPE}\", \"${FID_FHOURS}\", \"${FID_FSTART}\", \"${FID_FEND}\", \"${FID_FSOURCE}\", \"${FID_FREQ}\", \"${ASSIGNEE_ID}\"" + gql "mutation { updateProjectV2View(input: {viewId: \"${VIEW_ID}\", configuration: {visibleFieldIds: [${VFIDS}]}}) { projectV2View { name } } }" >/dev/null + say " View 1 已配 9 列" sleep "${PACE}" +else + say "保留已有 Project 的 Status 和视图" + HAS_DONE=$(gql "query { viewer { projectV2(number: ${PJ_NUM}) { field(name: \"Status\") { ... on ProjectV2SingleSelectField { options { name } } } } } }" \ + --jq 'any(.data.viewer.projectV2.field.options[]?; .name == "已完成")') + if [ "${HAS_DONE}" != true ]; then + say "WARN 看板缺少「已完成」状态,请在记账前添加" + fi fi -# ---------- 4. View 1 配可见列(API 建的字段不会自动进视图) ---------- -say "配置 View 1 可见列" -VIEW_ID=$(gql "query { node(id: \"${PJ_ID}\") { ... on ProjectV2 { views(first: 5) { nodes { id name } } } } }" \ - --jq '.data.node.views.nodes[0].id') -VFIDS="\"${TITLE_ID}\", \"${STATUS_ID}\", \"${FID_FTYPE}\", \"${FID_FHOURS}\", \"${FID_FSTART}\", \"${FID_FEND}\", \"${FID_FSOURCE}\", \"${FID_FREQ}\", \"${ASSIGNEE_ID}\"" -gql "mutation { updateProjectV2View(input: {viewId: \"${VIEW_ID}\", configuration: {visibleFieldIds: [${VFIDS}]}}) { projectV2View { name } } }" >/dev/null -say " View 1 已配 9 列" -sleep "${PACE}" - # ---------- 5. 仓库类型 labels ---------- say "仓库 ${REPO} 建 5 个类型 label" for l in "需求:0E8A16" "缺陷:D93F0B" "优化:1D76DB" "交付线:5319E7" "文档:705721"; do @@ -146,24 +169,9 @@ done # ---------- 6. 注入规范(--local=本地占位符替换;否则 API 注入) ---------- if [ -n "${LOCAL_DIR}" ]; then say "本地模式:替换 ${LOCAL_DIR} 中的 __PM_PROJECT__ 占位符" - CHANGED=0 - for f in "${LOCAL_DIR}/CLAUDE.md" "${LOCAL_DIR}/AGENTS.md" "${LOCAL_DIR}/.github/ISSUE_TEMPLATE/需求.md"; do - if [ -f "${f}" ] && grep -q "__PM_PROJECT__" "${f}"; then - sed -i '' "s/__PM_PROJECT__/${PJ_NUM}/g" "${f}" - CHANGED=$((CHANGED+1)) - say " 已替换 ${f}" - fi - done - if [ "${CHANGED}" -gt 0 ]; then - git -C "${LOCAL_DIR}" add CLAUDE.md AGENTS.md .github/ISSUE_TEMPLATE/需求.md 2>/dev/null - git -C "${LOCAL_DIR}" commit -q -m "chore: devledger 项目管理激活(Project #${PJ_NUM})" 2>/dev/null - say " 已本地提交(请自行 push)" - else - say " WARN 未找到占位符(非脚手架项目?改用 API 注入模式重跑不带 --local)" - fi + python3 "${PM_DIR}/scripts/_onboarding.py" activate "${LOCAL_DIR}" "${PJ_NUM}" else say "注入记账规范到仓库(CLAUDE.md + AGENTS.md + issue 模板)" -PM_DIR="$(cd "$(dirname "$0")/.." && pwd)" REPO="${REPO}" PJ_NUM="${PJ_NUM}" PJ_URL="${PJ_URL}" PJ_TITLE="${TITLE}" PM_DIR="${PM_DIR}" python3 - <<'PYEOF' import base64, json, os, subprocess, sys, urllib.parse @@ -254,5 +262,5 @@ cat <> "$TEST_GH_LOG" +case "$*" in + *'projectV2(number: 13) { id url }'*) echo '{"id":"PVT_existing","url":"https://github.com/users/a/projects/13"}' ;; + *'fields(first: 50)'*) echo PVT_field ;; + *'field(name: "Status")'*) echo true ;; + 'label create '*) ;; + *) exit 1 ;; +esac +""") + fake.chmod(0o755) + sleep = base / "sleep" + sleep.write_text("#!/bin/sh\nexit 0\n") + sleep.chmod(0o755) + git = ["git", "-C", str(repo)] + subprocess.run([*git, "init", "-q"], check=True) + subprocess.run([*git, "config", "user.name", "Test"], check=True) + subprocess.run([*git, "config", "user.email", "test@example.test"], check=True) + (repo / "CLAUDE.md").write_text("## 项目管理(devledger)\nGitHub Project `#13`\n") + (repo / "AGENTS.md").write_text("Project #__PM_PROJECT__\n") + (repo / "staged.txt").write_text("unrelated\n") + subprocess.run([*git, "add", "staged.txt"], check=True) + result = subprocess.run( + ["bash", str(SCRIPT), "a/r", "--local", str(repo)], capture_output=True, text=True, + env={**os.environ, "PATH": f"{base}:{os.environ['PATH']}", "TEST_GH_LOG": str(base / "calls"), "PM_RESUME": ""}, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((repo / "AGENTS.md").read_text(), "Project #13\n") + calls = (base / "calls").read_text() + self.assertNotIn("updateProjectV2", calls) + self.assertNotIn("project create", calls) + self.assertNotIn("projectsV2(first", calls) + self.assertEqual(subprocess.check_output([*git, "diff", "--cached", "--name-only"], text=True), "staged.txt\n")