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
29 changes: 17 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<number>`.

**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 <owner/repo>
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 <N> --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

Expand Down Expand Up @@ -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

Expand Down
33 changes: 25 additions & 8 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <owner/repo>
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` 重建) |
Expand Down Expand Up @@ -102,7 +119,7 @@ devledger 面向正在成型的全新协作形态:**一个技术负责人 +

## 他人一句话接入

对其 AI 说:「克隆 guanlili/devledger 到 ~/.agents/skills/devledger,跑 install.sh,按 SKILL.md 给我的仓库 <owner/repo> 接入项目管理」。管理员需先:加 devledger 仓库协作者 + 确认目标仓库写权限。
对其 AI 说:「克隆 guanlili/devledger 到 ~/.agents/skills/devledger,跑 install.sh,按 SKILL.md 给我的仓库 <owner/repo> 接入项目管理」。接入者需要目标仓库和目标 Project 的写权限。

## 支持

Expand Down
4 changes: 2 additions & 2 deletions SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ GitHub Projects(数据层:issue + 6 字段;一仓库一 Project,名=仓
```bash
scripts/new-project.sh <owner/repo> [--local <项目本地路径>]
# 脚手架项目(本地已克隆)加 --local:替换占位符并本地提交;存量仓库走 API 注入
# 中断续跑:PM_RESUME=<Project编号> 前缀重跑
# 中断续跑或确认接入已有同名 Project:PM_RESUME=<Project编号> 前缀重跑
```

自动完成: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 会话收尾,硬性纪律)

Expand Down
56 changes: 44 additions & 12 deletions scripts/_common.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down
70 changes: 70 additions & 0 deletions scripts/_onboarding.py
Original file line number Diff line number Diff line change
@@ -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("本地规范无需替换。")
4 changes: 2 additions & 2 deletions scripts/demo.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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'
## 来源
Expand Down
Loading
Loading