Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
记账三步:

1. 当轮 commits 聚类成可交付单元(甲方可感知的主题,一次 commit 不等于一条);commit 末尾尽量带 issue 号 `(#N)` 自动关联
2. 按模板建 issue(`.github/ISSUE_TEMPLATE/需求.md`:来源[含原话]/描述[为什么·否决方案·做了什么]/交付物/验证/工时,label=类型;决策上下文记录时写全,事后不可补),关闭之,`gh project item-add 13 --owner "@me" --url <issue url>`
3. 设 6 字段:类型(需求/缺陷/优化/交付线/文档,与 label 同名)、来源(甲方/内部)、需求人(甲方联系人;内部可空)、工时(h)(AI 评估:人类等价工作量,从宽、宁多勿漏,依据写进 issue)、开始、结束;Status=已完成
2. 按模板建 issue(`.github/ISSUE_TEMPLATE/需求.md`:来源[含原话]/描述[为什么·否决方案·做了什么]/交付物/验证/工时,label=类型;决策上下文记录时写全,事后不可补)。保存 issue URL,已有 issue 直接复用。
3. 用 `python3 ~/.agents/skills/devledger/scripts/bookkeep.py --project 13 --issue <issue URL> --type <类型> --source <来源> --hours <人类等价工时> --start <YYYY-MM-DD> --end <YYYY-MM-DD>` 入板、补字段并读回,确认后关闭 issue。甲方需求加 `--requester <需求人>`。中断后使用相同 URL 和参数续跑。

**issue 是唯一工作真相源**:字段与任何汇总均为派生视图。已知坑与扩展工具见 ~/devledger/SKILL.md。

6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,13 @@ graph TB
```mermaid
flowchart LR
s["AI dev session<br/>ships a deliverable"] -->|"① create issue"| i["4-section body: source (client quote) / why<br/>deliverables / verification · hours, label = type"]
i -->|"② close + add to board"| b["Project board"]
b -->|"③ set 6 fields"| f["type · source · requester<br/>hours · start · end"]
i -->|"② add to board"| b["Project board"]
b -->|"③ verify fields and close issue"| f["type · source · requester<br/>hours · start · end"]
f --> v["board / summaries = derived views"]
v -. "one command at acceptance" .-> x["client-ready xlsx"]
```

Requires `gh` CLI (project scopes), bash 3.2+, python3+openpyxl for exports. Works with ZCode, Claude Code, Cursor — any agent that reads SKILL.md/AGENTS.md.
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.

## Documentation

Expand Down
4 changes: 2 additions & 2 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ graph TB
```mermaid
flowchart LR
s["AI 开发会话<br/>交付可交付单元"] -->|"① 建 issue"| i["四段正文:来源(含甲方原话)/描述<br/>交付物/验证·工时,label=类型"]
i -->|"② 关闭 + 入板"| b["Project 看板"]
b -->|"③ 设 6 字段"| f["类型 · 来源 · 需求人<br/>工时(h) · 开始 · 结束"]
i -->|"② 入板"| b["Project 看板"]
b -->|"③ 读回字段后关闭 issue"| f["类型 · 来源 · 需求人<br/>工时(h) · 开始 · 结束"]
f --> v["看板 / 汇总 = 派生视图"]
v -. "验收时一条命令" .-> x["交付级 xlsx"]
```
Expand Down
13 changes: 6 additions & 7 deletions SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,14 @@ scripts/new-project.sh <owner/repo> [--local <项目本地路径>]
> **没记账的工作等于没做。完成可交付单元的会话,结束前必须完成三步。**

```bash
N=<Project编号>; URL=<issue url>
# ① 建 issue:正文按模板 assets/issue-template.md(来源[含甲方原话]/描述[为什么现在做·否决方案·做了什么]/交付物/验证/工时——决策上下文记录时写全,事后不可补),label=类型 → 关闭 → 入板
gh issue create -R <owner/repo> --title "<可交付单元>" --body-file <四段正文.md> --label <类型> --assignee @me
gh issue close <issue号> -R <owner/repo> && gh project item-add ${N} --owner "@me" --url "${URL}"
# ② 设 6 字段
for fv in "类型:需求" "来源:甲方" "需求人:张三" "工时(h):8" "开始:YYYY-MM-DD" "结束:YYYY-MM-DD" "Status:已完成"; do
gh project item-edit ${N} --owner "@me" --url "${URL}" --field "${fv%%:*}" --value "${fv#*:}"; done
# ① 按模板写正文,复用已有 issue 或创建一次,保存 URL。
URL=$(gh issue create -R <owner/repo> --title "<可交付单元>" --body-file <正文.md> --label 需求 --assignee @me)
# ② 入板并补齐字段。③ 读回确认后关闭 issue。
python3 scripts/bookkeep.py --project <Project编号> --issue "${URL}" \
--type 需求 --source 甲方 --requester 张三 --hours 8 --start YYYY-MM-DD --end YYYY-MM-DD
```

- 用同一个 issue URL 和相同参数续跑。命令只补差异,已关闭的 issue 也可补齐字段。内部需求可省略 `--requester`。
- 工时口径:**人类等价工作量、从宽宁多勿漏**,依据写进 issue;commit 末尾带 `(#N)` 自动关联
- **issue 是唯一真相源**:字段与任何汇总均为派生视图

Expand Down
4 changes: 2 additions & 2 deletions assets/agents-section.template.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
记账三步:

1. 当轮 commits 聚类成可交付单元(甲方可感知的主题,一次 commit ≠ 一条);commit message 末尾带 issue 号 `(#N)` 自动关联
2. 按模板建 issue(`.github/ISSUE_TEMPLATE/需求.md`:来源[含甲方原话]/描述[为什么现在做·否决方案·做了什么]/交付物/验证/工时,label=类型;决策上下文记录时写全,事后不可补),关闭之,`gh project item-add __PM_PROJECT__ --owner "@me" --url <issue url>`
3. 设 6 字段:类型(需求/缺陷/优化/交付线/文档,与 label 同名)、来源(甲方/内部)、需求人(提需求的人;内部可空)、工时(h)(AI 评估:人类等价工作量,从宽、宁多勿漏,依据写进 issue)、开始、结束;Status=已完成
2. 按模板建 issue(`.github/ISSUE_TEMPLATE/需求.md`:来源[含甲方原话]/描述[为什么现在做·否决方案·做了什么]/交付物/验证/工时,label=类型;决策上下文记录时写全,事后不可补)。保存 issue URL,已有 issue 直接复用。
3. 用 `python3 ~/.agents/skills/devledger/scripts/bookkeep.py --project __PM_PROJECT__ --issue <issue URL> --type <类型> --source <来源> --hours <人类等价工时> --start <YYYY-MM-DD> --end <YYYY-MM-DD>` 入板、补字段并读回,确认后关闭 issue。甲方需求加 `--requester <需求人>`。中断后使用相同 URL 和参数续跑。

**issue 是唯一工作真相源**:字段与任何汇总均为派生视图。已知坑与扩展工具见 `~/.agents/skills/devledger/SKILL.md`。
4 changes: 2 additions & 2 deletions assets/claude-section.template.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
记账三步:

1. 当轮 commits 聚类成可交付单元(甲方可感知的主题,一次 commit 不等于一条);commit 末尾尽量带 issue 号 `(#N)` 自动关联
2. 按模板建 issue(`.github/ISSUE_TEMPLATE/需求.md`:来源[含原话]/描述[为什么·否决方案·做了什么]/交付物/验证/工时,label=类型;决策上下文记录时写全,事后不可补),关闭之,`gh project item-add __PM_PROJECT__ --owner "@me" --url <issue url>`
3. 设 6 字段:类型(需求/缺陷/优化/交付线/文档,与 label 同名)、来源(甲方/内部)、需求人(甲方联系人;内部可空)、工时(h)(AI 评估:人类等价工作量,从宽、宁多勿漏,依据写进 issue)、开始、结束;Status=已完成
2. 按模板建 issue(`.github/ISSUE_TEMPLATE/需求.md`:来源[含原话]/描述[为什么·否决方案·做了什么]/交付物/验证/工时,label=类型;决策上下文记录时写全,事后不可补)。保存 issue URL,已有 issue 直接复用。
3. 用 `python3 ~/.agents/skills/devledger/scripts/bookkeep.py --project __PM_PROJECT__ --issue <issue URL> --type <类型> --source <来源> --hours <人类等价工时> --start <YYYY-MM-DD> --end <YYYY-MM-DD>` 入板、补字段并读回,确认后关闭 issue。甲方需求加 `--requester <需求人>`。中断后使用相同 URL 和参数续跑。

**issue 是唯一工作真相源**:字段与任何汇总均为派生视图。已知坑与扩展工具见 ~/.agents/skills/devledger/SKILL.md。
3 changes: 2 additions & 1 deletion scripts/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ def run(args, retries=5, timeout=180, pace=0):
time.sleep(pace)
return r.returncode, r.stdout.strip(), r.stderr.strip()
last = r.stderr.strip()
time.sleep(300 if "rate limit" in last.lower() else 15 * (a + 1))
if a + 1 < retries:
time.sleep(300 if "rate limit" in last.lower() else 15 * (a + 1))
return 1, "", last


Expand Down
154 changes: 154 additions & 0 deletions scripts/bookkeep.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
#!/usr/bin/env python3
"""按已有 issue URL 补齐 Project 字段,读回确认后关闭 issue。"""

import argparse
import json
import re
import sys
from datetime import date
from decimal import Decimal, InvalidOperation

from _common import norm, run

FIELDS = {
"kind": ("类型", "SingleSelect", "name"),
"source": ("来源", "SingleSelect", "name"),
"requester": ("需求人", "Text", "text"),
"hours": ("工时(h)", "Number", "number"),
"start": ("开始", "Date", "date"),
"end": ("结束", "Date", "date"),
"status": ("Status", "SingleSelect", "name"),
}

FIELD_SELECTION = "\n".join(
f'{key}: fieldValueByName(name: {json.dumps(name, ensure_ascii=False)}) '
f'{{ ... on ProjectV2ItemField{kind}Value {{ {value} }} }}'
for key, (name, kind, value) in FIELDS.items()
)

QUERY = """
query($project: Int!, $owner: String!, $repo: String!, $number: Int!, $cursor: String) {
viewer { projectV2(number: $project) { id } }
repository(owner: $owner, name: $repo) {
issue(number: $number) {
state
projectItems(first: 30, after: $cursor, includeArchived: true) {
pageInfo { hasNextPage endCursor }
nodes {
project { id }
isArchived
FIELD_SELECTION
}
}
}
}
}
""".replace("FIELD_SELECTION", FIELD_SELECTION)


def gh(args, *, pace=0):
rc, out, err = run(["gh", *args], retries=1, pace=pace)
if rc:
raise RuntimeError(err or out or f"gh 退出码 {rc}")
return out


def read_state(project, issue):
owner, repo, number = issue
args = ["api", "graphql", "-f", f"query={QUERY}", "-F", f"project={project}",
"-f", f"owner={owner}", "-f", f"repo={repo}", "-F", f"number={number}"]
cursor_args = []
while True:
response = json.loads(gh(args + cursor_args))
if response.get("errors"):
raise RuntimeError(str(response["errors"]))
data = response["data"]
board = data["viewer"]["projectV2"]
record = (data.get("repository") or {}).get("issue")
if not board or not record:
raise RuntimeError("无法读取目标 Project 或 issue,请检查编号和权限")
page = record["projectItems"]
for item in page["nodes"]:
if item["project"]["id"] != board["id"]:
continue
if item["isArchived"]:
raise RuntimeError("目标 Project 中的条目已归档,请先恢复条目")
values = {
key: (item.get(key) or {}).get(value)
for key, (_, _, value) in FIELDS.items()
}
return record["state"], values
if not page["pageInfo"]["hasNextPage"]:
return record["state"], None
cursor_args = ["-f", f'cursor={page["pageInfo"]["endCursor"]}']


def pending_fields(current, expected):
current = current or {}
return {
key: value for key, value in expected.items()
if (norm(current.get(key)) != norm(value) if key == "hours" else current.get(key) != value)
}


def complete(project, issue, url, expected):
board_args = [str(project), "--owner", "@me", "--url", url]
state, current = read_state(project, issue)
if current is None:
gh(["project", "item-add", *board_args], pace=1)
state, current = read_state(project, issue)
if current is None:
raise RuntimeError("暂未读到入板条目,请稍后续跑")

changes = pending_fields(current, expected)
for key, value in changes.items():
name = FIELDS[key][0]
gh(["project", "item-edit", *board_args, "--field", name, "--value", value], pace=1)

if changes:
state, current = read_state(project, issue)
remaining = pending_fields(current, expected)
if remaining:
raise RuntimeError("读回仍有差异:" + "、".join(FIELDS[key][0] for key in remaining))

if state != "CLOSED":
gh(["issue", "close", url])
state, current = read_state(project, issue)
if state != "CLOSED" or pending_fields(current, expected):
raise RuntimeError("关闭后的读回结果尚未一致,请稍后续跑")


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--project", type=int, required=True)
parser.add_argument("--issue", required=True, help="已有 GitHub issue 的完整 URL")
parser.add_argument("--type", dest="kind", required=True, choices=["需求", "缺陷", "优化", "交付线", "文档"])
parser.add_argument("--source", required=True, choices=["甲方", "内部"])
parser.add_argument("--requester", help="需求人,省略时保留现有值")
parser.add_argument("--hours", required=True, help="非负的人类等价工时")
parser.add_argument("--start", required=True, help="YYYY-MM-DD")
parser.add_argument("--end", required=True, help="YYYY-MM-DD")
args = parser.parse_args()
match = re.fullmatch(r"https://github\.com/([\w.-]+)/([\w.-]+)/issues/([1-9]\d*)/?", args.issue)
if not match or args.project < 1:
parser.error("请提供有效的 GitHub issue URL 和正整数 Project 编号")
try:
hours = Decimal(args.hours)
if not hours.is_finite() or hours < 0:
raise ValueError
start, end = date.fromisoformat(args.start), date.fromisoformat(args.end)
if start.isoformat() != args.start or end.isoformat() != args.end or start > end:
raise ValueError
except (InvalidOperation, ValueError):
parser.error("工时必须为非负有限数字,日期须为 YYYY-MM-DD,且开始不晚于结束")
expected = {key: getattr(args, key) for key in FIELDS if key != "status" and getattr(args, key) is not None}
expected["status"] = "已完成"
try:
complete(args.project, match.groups(), args.issue.rstrip("/"), expected)
except (RuntimeError, ValueError) as exc:
sys.exit(f"记账未确认完成:{exc}\n请用同一 issue URL 和参数续跑:{args.issue}")
print(f"记账完成,已读回确认:{args.issue}")


if __name__ == "__main__":
main()
13 changes: 8 additions & 5 deletions scripts/demo.sh
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,14 @@ MD
for pair in "首页性能优化:优化:甲方:8:${DEMO1}" "预测超时修复:缺陷:内部:5:${DEMO2}"; do
IFS=':' read -r T TY SRC H BODY <<<"${pair}"
U=$(gh issue create -R "${REPO}" --title "${T}" --body-file "${BODY}" --label "${TY}" --assignee @me)
NUM=${U##*/}; gh issue close "${NUM}" -R "${REPO}" >/dev/null
gh project item-add "${N}" --owner "@me" --url "${U}" >/dev/null
for fv in "类型:${TY}" "来源:${SRC}" "工时(h):${H}" "开始:2026-01-10" "结束:2026-01-10" "Status:已完成"; do
gh project item-edit "${N}" --owner "@me" --url "${U}" --field "${fv%%:*}" --value "${fv#*:}" >/dev/null
done
NUM=${U##*/}
REQUESTER=()
if [ "${SRC}" = "甲方" ]; then
REQUESTER=(--requester "示例联系人")
fi
python3 "${DL}/scripts/bookkeep.py" --project "${N}" --issue "${U}" \
--type "${TY}" --source "${SRC}" --hours "${H}" --start 2026-01-10 --end 2026-01-10 \
${REQUESTER[@]+"${REQUESTER[@]}"} >/dev/null
say " #${NUM} ${T}(${TY}/${SRC}/${H}h)已入账"
done
rm -f "${DEMO1}" "${DEMO2}"
Expand Down
53 changes: 53 additions & 0 deletions tests/test_bookkeep.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""用模拟 Project 验证中断续跑、关闭顺序和重复执行。"""
import pathlib
import runpy
import sys
import unittest
from unittest.mock import Mock, patch

ROOT = pathlib.Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
complete = runpy.run_path(str(ROOT / "scripts" / "bookkeep.py"))["complete"]
ISSUE = ("a", "r", "1")
URL = "https://github.com/a/r/issues/1"
EXPECTED = {"hours": "0", "status": "已完成"}


class TestComplete(unittest.TestCase):
def setUp(self):
self.write = Mock()
self.read = Mock()
mocks = patch.dict(complete.__globals__, {"gh": self.write, "read_state": self.read})
mocks.start()
self.addCleanup(mocks.stop)

def test_resume_writes_only_missing_field_then_closes(self):
fields = {"hours": 0.0, "status": "已完成"}
self.read.side_effect = [
("OPEN", {"hours": 0.0}),
("OPEN", fields),
("CLOSED", fields),
]
complete(13, ISSUE, URL, EXPECTED)
commands = [call.args[0] for call in self.write.call_args_list]
self.assertEqual(commands[0][-4:], ["--field", "Status", "--value", "已完成"])
self.assertEqual(commands[1], ["issue", "close", URL])

def test_missing_item_is_added_and_read_before_writing(self):
self.read.side_effect = [("OPEN", None), ("OPEN", None)]
with self.assertRaisesRegex(RuntimeError, "暂未读到"):
complete(13, ISSUE, URL, EXPECTED)
self.write.assert_called_once()
self.assertEqual(self.write.call_args.args[0][:2], ["project", "item-add"])

def test_unconfirmed_field_leaves_issue_open(self):
self.read.side_effect = [("OPEN", {"status": "已完成"}), ("OPEN", {"status": "已完成"})]
with self.assertRaisesRegex(RuntimeError, "工时"):
complete(13, ISSUE, URL, EXPECTED)
self.write.assert_called_once()
self.assertEqual(self.write.call_args.args[0][:2], ["project", "item-edit"])

def test_completed_issue_has_no_writes(self):
self.read.return_value = ("CLOSED", {"hours": 0, "status": "已完成"})
complete(13, ISSUE, URL, EXPECTED)
self.write.assert_not_called()
Loading