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
86 changes: 86 additions & 0 deletions bin/guild-ledger
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ usage: guild-ledger append < one event as JSON on stdin
guild-ledger backfill [--council-dir DIR]
guild-ledger backfill-prs --repo OWNER/NAME [--repo ...] [--days N]
guild-ledger refresh [--council-dir DIR]
guild-ledger touches [--days N] [--repo OWNER/NAME ...]

Ledger: $GUILD_LEDGER (default ~/.local/state/guild/ledger.jsonl), append-only
JSONL. The schema and the backfill's proxy are in docs/outcome-ledger.md.
Expand All @@ -22,6 +23,10 @@ refresh runs backfill, then backfill-prs over Guild, each roster tool and the
org's guild-ledger.pr_repos (guild-config --org). A failed step sends
one job-notify ping per kind until that step passes again; the other
step still runs. guild-ledger-refresh.timer runs it daily.
touches joins human_stop decisions to pr-lifecycle outcomes by (repo, pr) in
the last N days (default 7) from the ledger file alone and prints
merged PRs, human stops on them, touches per merged PR, and counts by
stop name per repo.

Council dir: --council-dir, else $GUILD_LEDGER_COUNCIL_DIR, else
~/code/conclave/tmp/council.
Expand Down Expand Up @@ -54,6 +59,9 @@ REPO_RE = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
SHA_RE = re.compile(r"^[0-9a-f]{40}$")
PROXY = "cited-code-at-head"
PR_PROXY = "pr-lifecycle"
HUMAN_STOP_ACTION = "human_stop"
HUMAN_STOPS = {"split_decision", "posting_go", "manual_merge", "ack_loop", "one_way_ack", "brief_approval"}
TOUCHES_DAYS = 7
PAGE = 100
REVERTS_RE = re.compile(r"\bReverts\s+\[?(?:[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)?#(\d+)")
EXIT_OK, EXIT_BAD_EVENT, EXIT_UNREADABLE = 0, 2, 3
Expand Down Expand Up @@ -122,6 +130,11 @@ def validate(event) -> dict:
need = KINDS[kind]
if not isinstance(data, dict) or not isinstance(data.get(need), str) or not data[need]:
raise BadEvent(f"data must be an object with a {need} string for a {kind}")
if kind == "decision" and data["action"] == HUMAN_STOP_ACTION:
if data.get("stop") not in HUMAN_STOPS:
raise BadEvent(f"data.stop must be one of {sorted(HUMAN_STOPS)} for action {HUMAN_STOP_ACTION}")
if data.get("answered_at") is not None and not is_time(data["answered_at"]):
raise BadEvent("data.answered_at must be an ISO 8601 time or null")
if "recorded_at" in event and not is_time(event["recorded_at"]):
raise BadEvent("recorded_at must be an ISO 8601 time")
clean = {k: v for k, v in event.items() if k not in ("id", "recorded_at")}
Expand Down Expand Up @@ -503,6 +516,74 @@ def refresh(council: Path) -> int:
return EXIT_UNREADABLE if failed else EXIT_OK


# --- touches ---------------------------------------------------------------

def read_events() -> list[dict]:
path = ledger_path()
try:
lines = path.read_text(encoding="utf-8").splitlines()
except OSError as exc:
raise Unreadable(f"{path}: {exc.strerror or exc}")
events = []
for n, line in enumerate(lines, 1):
if not line.strip():
continue
try:
event = json.loads(line)
except ValueError:
raise Unreadable(f"{path}:{n}: malformed ledger line")
if not isinstance(event, dict):
raise Unreadable(f"{path}:{n}: malformed ledger line")
if event.get("v") != VERSION:
continue
events.append(event)
return events


def touches(repos: list[str] | None, days: int) -> int:
since = datetime.now(timezone.utc) - timedelta(days=days)
events = read_events()
wanted = set(repos) if repos else None
lifecycle_by_pr: dict[tuple[str, int], dict] = {}
stops_by_pr: dict[tuple[str, int], list[str]] = {}
seen_repos: set[str] = set()
for e in events:
subject = e["subject"]
repo, pr = subject["repo"], subject["pr"]
if wanted is not None and repo not in wanted:
continue
data = e["data"]
if e["kind"] == "outcome" and data.get("proxy") == PR_PROXY:
seen_repos.add(repo)
lifecycle_by_pr[(repo, pr)] = e
elif e["kind"] == "decision" and data.get("action") == HUMAN_STOP_ACTION:
seen_repos.add(repo)
stop = data.get("stop")
if not isinstance(stop, str):
raise Unreadable(f"human_stop decision {e.get('id')!r} missing stop name")
stops_by_pr.setdefault((repo, pr), []).append(stop)

merged_by_repo: dict[str, list[int]] = {}
for (repo, pr), e in lifecycle_by_pr.items():
data = e["data"]
ended = data.get("merged_at") or e.get("at")
if data.get("state") == "merged" and ended and parse_time(ended) >= since:
merged_by_repo.setdefault(repo, []).append(pr)

order = list(dict.fromkeys(repos)) if repos else sorted(seen_repos)
print(f"window {since.isoformat(timespec='seconds')} to now ({days} days)")
for repo in order:
merged_prs = merged_by_repo.get(repo, [])
counts: Counter[str] = Counter()
for pr in merged_prs:
counts.update(stops_by_pr.get((repo, pr), ()))
total_stops = sum(counts.values())
ratio = f"{total_stops / len(merged_prs):.2f}" if merged_prs else "-"
print(f"{repo}: merged {len(merged_prs)} human stops {total_stops}"
f" touches/merged PR {ratio} by stop {dict(sorted(counts.items()))}")
return EXIT_OK


# --- entry ---------------------------------------------------------------

def repo_arg(value: str) -> str:
Expand All @@ -528,6 +609,9 @@ def main(argv: list[str]) -> int:
bp.add_argument("--days", type=days_arg, default=30)
rf = sub.add_parser("refresh", help="run both backfills and ping on a failure (the daily timer)")
rf.add_argument("--council-dir", default=council_default())
tc = sub.add_parser("touches", help="human touches per merged PR from the ledger alone")
tc.add_argument("--repo", action="append", type=repo_arg, metavar="OWNER/NAME")
tc.add_argument("--days", type=days_arg, default=TOUCHES_DAYS)
try:
args = parser.parse_args(argv)
except SystemExit as exc:
Expand All @@ -544,6 +628,8 @@ def main(argv: list[str]) -> int:
if args.cmd == "refresh":
return refresh(Path(args.council_dir))
try:
if args.cmd == "touches":
return touches(args.repo, args.days)
if args.cmd == "backfill-prs":
return backfill_prs(list(dict.fromkeys(args.repo)), args.days)
return backfill(Path(args.council_dir))
Expand Down
13 changes: 12 additions & 1 deletion docs/outcome-ledger.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,20 @@ The cited block's longest line, with whitespace collapsed, is the needle. A thre
**The proxy's limits.**

- An escape is an explicit revert only. A fix-forward PR that repairs a bad merge is not counted, so reverts undercount escapes.
- Human touches are not counted. Agents act under the owner's GitHub login, so GitHub cannot tell the owner's click from an agent's. The tools must record a touch when they stop for a person. That is a later unit.
- Human touches are not counted on the lifecycle event. Agents act under the owner's GitHub login, so GitHub cannot tell the owner's click from an agent's. The tools record a touch as a `human_stop` decision event when they stop for a person, and `guild-ledger touches` joins those stops to `pr-lifecycle` outcomes.
- `reviewers` counts only GitHub review submissions. On a repo with one author it is near zero: a council review posted under the owner's login on the owner's own PR counts as the author's.
- `hours_open` starts at PR creation, not at the first commit or the first request for review.

## Human stops and touches

When a tool stops for a person on a PR, it writes a `decision` event with `data.action: human_stop`.

- `data.stop` is one of a closed list: `split_decision`, `posting_go`, `manual_merge`, `ack_loop`, `one_way_ack`, or `brief_approval`. `validate()` rejects any other stop name (exit 2).
- `data.answered_at` is an optional ISO 8601 time (or null) for when the person answered.
- `subject` keeps the full schema (`repo`, `pr`, 40-hex `sha`, and `finding` or null). Stops without a PR, such as route asks in `asks.jsonl`, are out of this unit until a stop can name its PR.

`guild-ledger touches [--days N] [--repo OWNER/NAME ...]` reads only the ledger file and makes no GitHub calls. It takes each PR whose latest `pr-lifecycle` outcome is `state: merged` in the last N days (default 7), joins all `human_stop` decisions to it by `(repo, pr)`, and prints per repo: merged PRs in the window, human stops on them, touches per merged PR, and a count per stop name. With `--repo`, it reports those repos in the order given; without `--repo`, it reports every repo present in the ledger's `pr-lifecycle` or `human_stop` events in alphabetical order.

## Scheduled refresh (BLD only)

`guild-ledger refresh` runs `backfill`, then `backfill-prs` with the default 30-day window. `guild-ledger-refresh.timer` starts it once a day, and at the next boot when BLD was off at midnight. It runs on BLD only: Conclave's run folders and the ledger are local state there. Nothing enables it on the Surface.
Expand All @@ -96,6 +106,7 @@ echo '<event json>' | guild-ledger append # prints "appended <id>" or "exists
guild-ledger backfill [--council-dir DIR] # prints counts; default DIR ~/code/conclave/tmp/council
guild-ledger backfill-prs --repo OWNER/NAME [--repo ...] [--days N] # prints per-repo cycle time and reverts
guild-ledger refresh [--council-dir DIR] # both backfills, one ping per failed kind (the daily timer)
guild-ledger touches [--days N] [--repo OWNER/NAME ...] # prints per-repo human touches per merged PR from the ledger
```

The council dir is `--council-dir`, else `$GUILD_LEDGER_COUNCIL_DIR`, else `~/code/conclave/tmp/council`.
Expand Down
116 changes: 116 additions & 0 deletions tests/test_guild_ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,11 @@ def test_malformed_event_fails_closed_and_writes_nothing(self) -> None:
json.dumps(event(data={})),
json.dumps(event(kind="outcome", data={"action": "x"})),
json.dumps(event(id="0" * 64)),
json.dumps(event(data={"action": "human_stop"})),
json.dumps(event(data={"action": "human_stop", "stop": "unknown_stop"})),
json.dumps(event(data={"action": "human_stop", "stop": 123})),
json.dumps(event(data={"action": "human_stop", "stop": "posting_go", "answered_at": "yesterday"})),
json.dumps(event(data={"action": "human_stop", "stop": "posting_go", "answered_at": 123})),
]
for text in bad:
with self.subTest(event=text):
Expand All @@ -137,6 +142,19 @@ def test_malformed_event_fails_closed_and_writes_nothing(self) -> None:
self.assertIn("malformed event", p.stderr)
self.assertFalse(self.ledger.exists())

def test_human_stop_accepts_known_stops_and_optional_answered_at(self) -> None:
stops = ("split_decision", "posting_go", "manual_merge", "ack_loop", "one_way_ack", "brief_approval")
for i, stop in enumerate(stops, 1):
data = {"action": "human_stop", "stop": stop}
if i == 1:
data["answered_at"] = "2026-01-02T03:05:00+00:00"
elif i == 2:
data["answered_at"] = None
p = self.run_tool("append", stdin=json.dumps(
event(subject={"repo": REPO, "pr": i, "sha": REVIEWED, "finding": None}, data=data)))
self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
self.assertEqual(len(self.lines()), len(stops))

def test_malformed_ledger_line_fails_closed(self) -> None:
self.ledger.parent.mkdir(parents=True)
self.ledger.write_text("{half a line\n", encoding="utf-8")
Expand Down Expand Up @@ -531,6 +549,104 @@ def test_council_dir_comes_from_the_environment(self) -> None:
self.assertEqual(p.returncode, 3, p.stdout + p.stderr)
self.assertIn(str(self.tmp / "nope"), p.stderr)

# --- touches ---------------------------------------------------------

def touches_fixture(self) -> None:
now = datetime.now(timezone.utc)
iso = lambda days_ago: (now - timedelta(days=days_ago)).strftime("%Y-%m-%dT%H:%M:%SZ")

def pr_outcome(repo, pr, days_ago, state="merged", sha=HEAD):
ended = iso(days_ago)
data = {"proxy": "pr-lifecycle", "state": state, "author": "alex-acme",
"created_at": iso(days_ago + 1),
("merged_at" if state == "merged" else "closed_at"): ended,
"hours_open": 24.0, "reviewers": 0, "reviews": 0,
"is_revert": False, "reverts_pr": None}
return {"v": 1, "kind": "outcome", "source": "github",
"subject": {"repo": repo, "pr": pr, "sha": sha, "finding": None},
"at": ended, "data": data}

def stop(repo, pr, name, days_ago=1, sha=REVIEWED, finding=None):
return {"v": 1, "kind": "decision", "source": "conclave",
"subject": {"repo": repo, "pr": pr, "sha": sha, "finding": finding},
"at": iso(days_ago),
"data": {"action": "human_stop", "stop": name, "answered_at": iso(days_ago)}}

events = [
# REPO: PR 1 merged in window with 2 stops (different commits/findings), PR 2 merged with 0 stops.
pr_outcome(REPO, 1, 2, sha=REVIEWED),
pr_outcome(REPO, 1, 2, sha=HEAD), # later outcome on same PR
stop(REPO, 1, "split_decision", sha=REVIEWED, finding="f1"),
stop(REPO, 1, "posting_go", sha=HEAD),
pr_outcome(REPO, 2, 3),
# PR 3 closed unmerged in window with a stop: excluded from merged PRs and stops on them.
pr_outcome(REPO, 3, 1, state="closed"),
stop(REPO, 3, "manual_merge"),
# PR 4 merged outside the 7-day window with a stop: excluded.
pr_outcome(REPO, 4, 10),
stop(REPO, 4, "ack_loop", days_ago=10),
# Stop on an open PR with no lifecycle outcome: excluded.
stop(REPO, 5, "brief_approval"),
# Non-stop decision on PR 1: ignored.
event(subject={"repo": REPO, "pr": 1, "sha": REVIEWED, "finding": "f1"}),
# Second repo: 1 merged PR with 3 stops (two of the same stop name).
pr_outcome(self.ORG_REPO, 10, 1),
stop(self.ORG_REPO, 10, "posting_go"),
stop(self.ORG_REPO, 10, "posting_go", days_ago=2),
stop(self.ORG_REPO, 10, "manual_merge"),
]
for e in events:
p = self.run_tool("append", stdin=json.dumps(e))
self.assertEqual(p.returncode, 0, p.stderr)

def test_touches_joins_human_stops_to_merged_prs_per_repo(self) -> None:
self.touches_fixture()
p = self.run_tool("touches")
self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
self.assertIn("(7 days)", p.stdout)
self.assertIn(
f"{REPO}: merged 2 human stops 2 touches/merged PR 1.00"
" by stop {'posting_go': 1, 'split_decision': 1}",
p.stdout,
)
self.assertIn(
f"{self.ORG_REPO}: merged 1 human stops 3 touches/merged PR 3.00"
" by stop {'manual_merge': 1, 'posting_go': 2}",
p.stdout,
)
self.assertFalse(self.log.exists())

def test_touches_filters_by_repo_and_handles_zero_stops_and_zero_merged(self) -> None:
self.touches_fixture()
# Only PR 2 has 0 stops; test a repo filter and an explicit empty repo.
empty_repo = "AcmeCorp/empty"
p = self.run_tool("touches", "--days", "7", "--repo", empty_repo, "--repo", REPO)
self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
self.assertNotIn(self.ORG_REPO, p.stdout)
self.assertIn(f"{empty_repo}: merged 0 human stops 0 touches/merged PR - by stop {{}}", p.stdout)
self.assertIn(f"{REPO}: merged 2 human stops 2 touches/merged PR 1.00", p.stdout)

def test_touches_pr_with_zero_stops(self) -> None:
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
pr = {"v": 1, "kind": "outcome", "source": "github",
"subject": {"repo": REPO, "pr": 1, "sha": HEAD, "finding": None},
"at": now,
"data": {"proxy": "pr-lifecycle", "state": "merged", "author": "alex-acme",
"created_at": now, "merged_at": now, "hours_open": 0.1,
"reviewers": 0, "reviews": 0, "is_revert": False, "reverts_pr": None}}
self.assertEqual(self.run_tool("append", stdin=json.dumps(pr)).returncode, 0)
p = self.run_tool("touches", "--repo", REPO)
self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
self.assertIn(f"{REPO}: merged 1 human stops 0 touches/merged PR 0.00 by stop {{}}", p.stdout)

def test_touches_bad_arguments_and_unreadable_ledger(self) -> None:
for args in (["--repo", "nope"], ["--days", "0"], ["--days", "x"]):
with self.subTest(args=args):
p = self.run_tool("touches", *args)
self.assertEqual(p.returncode, 2, p.stdout + p.stderr)
p = self.run_tool("touches")
self.assertEqual(p.returncode, 3, p.stdout + p.stderr)


if __name__ == "__main__":
unittest.main()
Loading