@bbcsoftwarefactory/commands 0.1.0 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/daily/SKILL.md +5 -5
- package/dist/commands/issue-clean-and-close/SKILL.md +7 -8
- package/dist/commands/issue-clean-and-close/references/policy.md +9 -9
- package/dist/commands/recap/SKILL.md +7 -13
- package/dist/index.json +5 -10
- package/package.json +3 -4
- package/dist/commands/issue-clean-and-close/scripts/sweep-github.py +0 -347
- package/dist/commands/issue-clean-and-close/scripts/sweep-issues.py +0 -487
- package/dist/commands/issue-clean-and-close/scripts/sweep.py +0 -231
- package/dist/commands/issue-clean-and-close/tests/sweep-github.test.sh +0 -156
- package/dist/commands/issue-clean-and-close/tests/sweep-issues.test.sh +0 -269
- package/dist/commands/issue-clean-and-close/tests/sweep.test.sh +0 -181
- package/dist/commands/recap/scripts/recap.py +0 -1610
- package/dist/commands/recap/tests/recap.test.sh +0 -275
|
@@ -7,7 +7,7 @@ metadata:
|
|
|
7
7
|
author: bbc-skill-internals
|
|
8
8
|
version: "1.4"
|
|
9
9
|
pre_hook: "gh auth status && git fetch origin --prune; tool-depot (github-read / github-write)"
|
|
10
|
-
post_hook: "question-gate (triage-question
|
|
10
|
+
post_hook: "question-gate (bbc triage-question) + Quest-Tree HUD"
|
|
11
11
|
post_install: "npx --full-depth; copy adapters/gemini.toml + /commands reload (Gemini); server restart (Zed ACP)"
|
|
12
12
|
adapters: "adapters/command.md, adapters/gemini.toml"
|
|
13
13
|
---
|
|
@@ -37,7 +37,7 @@ Granted authority upon explicit `/daily` invocation:
|
|
|
37
37
|
| Situation | Action |
|
|
38
38
|
|---|---|
|
|
39
39
|
| `--dry-run` passed | Run all read-only checks and render HUD; draft and post no comments |
|
|
40
|
-
| Issue has image/file attachments and `
|
|
40
|
+
| Issue has image/file attachments and `@bbcsoftwarefactory/cli` (`fetch-issue-attachments`) is available | Download and visually inspect attachments before classifying the issue |
|
|
41
41
|
| Issue is already fixed (merged PR + commit on `origin/<default-branch>` + verified in code) | Draft a comment with PR link, merge commit, and verified code location (unless `--dry-run`); queue it and the close candidate in `🟡 BOSS GATE` |
|
|
42
42
|
| Issue is open and latest comment is already an unchanged `daily` (or legacy `allio`) follow-up | Skip commenting (`⚪ Sin cambios` / `unchanged`) to avoid duplicate noise |
|
|
43
43
|
| Issue is open and unresolved (pending / in-progress PR / blocked) | Draft 1 concrete follow-up comment (unless `--dry-run`) stating observed state, what was checked, and next recommended step; queue it in `🟡 BOSS GATE` |
|
|
@@ -56,10 +56,10 @@ Granted authority upon explicit `/daily` invocation:
|
|
|
56
56
|
- Run `gh api "repos/<owner>/<repo>/issues?state=open&per_page=50" --jq '[.[] | select(.pull_request == null)]'` (the endpoint also returns PRs; the filter drops them). Filter by `#<n>` if provided. If empty, record `🟢 0 open issues` and continue to step 3.
|
|
57
57
|
- For each open issue:
|
|
58
58
|
- Read body and comments via `gh api -H "Accept: application/vnd.github.full+json" repos/<owner>/<repo>/issues/<n>` and `gh api repos/<owner>/<repo>/issues/<n>/comments`.
|
|
59
|
-
- If attachments exist and `issue-reviewer` is available, run `
|
|
59
|
+
- If attachments exist and `issue-reviewer` is available, run `npx -y @bbcsoftwarefactory/cli fetch-issue-attachments --repo <owner/repo> --issue <n>` and inspect them before judging status.
|
|
60
60
|
- Cross-check related PRs (`gh api -X GET search/issues -f q='repo:<owner>/<repo> is:pr <terms>'`), commits on `origin/<default-branch>` (`git log origin/<default-branch> --oneline -n 50 --grep="..."`), and current code (`rg` / file read).
|
|
61
61
|
- Classify as resolved (Case A) or pending/in-progress/blocked (Case B) and apply the Decision Gates above.
|
|
62
|
-
- Check who holds it with the [claim rules](../../skills/delivery-coordinator/references/issue-claim.md), when `delivery-coordinator` is installed: save the issue (`gh api repos/<owner>/<repo>/issues/<n>`), and once per run the open PRs (`gh api --paginate --slurp "repos/<owner>/<repo>/pulls?state=open&per_page=100"`) and claim branches (`git ls-remote --heads origin "feat/*"`), then run `
|
|
62
|
+
- Check who holds it with the [claim rules](../../skills/delivery-coordinator/references/issue-claim.md), when `delivery-coordinator` is installed: save the issue (`gh api repos/<owner>/<repo>/issues/<n>`), and once per run the open PRs (`gh api --paginate --slurp "repos/<owner>/<repo>/pulls?state=open&per_page=100"`) and claim branches (`git ls-remote --heads origin "feat/*"`), then run `npx -y @bbcsoftwarefactory/cli check-issue-claim --phase status --issue-json <issue> --pulls-json <pulls> --branches <branches> --repo <owner>/<repo>`. Report `claimed` with the holder, and apply the claim rows above for `duplicate-work`, `stale-claim`, or `orphan-claim`.
|
|
63
63
|
|
|
64
64
|
3. **Audit open PRs (CI checks & conflicts)**
|
|
65
65
|
- Run `gh api "repos/<owner>/<repo>/pulls?state=open&per_page=50"`.
|
|
@@ -71,7 +71,7 @@ Granted authority upon explicit `/daily` invocation:
|
|
|
71
71
|
- `🔴 Conflicts` (`mergeable: false` / `mergeable_state: dirty`): fetch `pull/<pr>/head:refs/remotes/origin/pr/<pr>` and run `git merge-tree --write-tree origin/<base.ref> refs/remotes/origin/pr/<pr>` (or use a temporary detached worktree to run `git merge --no-commit --no-ff`, list `git diff --name-only --diff-filter=U`, abort, and remove the temporary worktree).
|
|
72
72
|
|
|
73
73
|
4. **Gate & report**
|
|
74
|
-
- If `question-gate` (`triage-question
|
|
74
|
+
- If `question-gate` (`bbc triage-question`) is installed and any human decision remains (comment drafts to post, conflicted PRs, resolved issues ready to close, or green PRs ready to merge), validate the closing prompt before replying.
|
|
75
75
|
- List each comment draft in the `🟡 BOSS GATE` as `#<n>: <first line of the draft>`, so the person approves exact targets (all, some by number, or none).
|
|
76
76
|
|
|
77
77
|
5. **Post approved comments** (only after the person answers the gate)
|
|
@@ -3,14 +3,13 @@ name: issue-clean-and-close
|
|
|
3
3
|
description: "Trigger: /issue-clean-and-close, limpiar issues, cerrar issues resueltas, issues abiertas con PR fusionado, backlog sin trazabilidad. Review every open issue of the current repository, propose closing only what a merged PR or an unanswered needs-info settles, label and ping the rest, and apply only the plan the person approves."
|
|
4
4
|
disable-model-invocation: true
|
|
5
5
|
license: Apache-2.0
|
|
6
|
-
compatibility: Requires
|
|
6
|
+
compatibility: Requires Node.js 22.18+ (`@bbcsoftwarefactory/cli`), git, and an authenticated gh CLI with GraphQL access for `sweep` and `sweep-github`; `sweep-issues` runs offline.
|
|
7
7
|
metadata:
|
|
8
8
|
author: bbc-skill-internals
|
|
9
9
|
version: "1.0"
|
|
10
10
|
pre_hook: "gh auth status; tool-depot (github-read / github-write)"
|
|
11
|
-
post_hook: "question-gate (triage-question
|
|
11
|
+
post_hook: "question-gate (bbc triage-question) + Quest-Tree HUD"
|
|
12
12
|
post_install: "npx --full-depth; copy adapters/gemini.toml + /commands reload (Gemini); server restart (Zed ACP)"
|
|
13
|
-
scripts: "scripts/sweep-github.py, scripts/sweep-issues.py, scripts/sweep.py"
|
|
14
13
|
adapters: "adapters/command.md, adapters/gemini.toml"
|
|
15
14
|
---
|
|
16
15
|
|
|
@@ -23,8 +22,8 @@ Optional arguments:
|
|
|
23
22
|
- `--repo <owner/repo>`: review another repository instead of the current checkout's `origin`.
|
|
24
23
|
|
|
25
24
|
Granted authority upon explicit invocation:
|
|
26
|
-
- `A1` (read): `sweep
|
|
27
|
-
- `A2` (write, only after the gate): `sweep
|
|
25
|
+
- `A1` (read): `sweep plan` under Tool Depot `github-read` / `read-issues-for-cleanup`: the authenticated login, the optional `.github/issue-sweeper.json` on the default branch, and the open issues with one paginated GraphQL query.
|
|
26
|
+
- `A2` (write, only after the gate): `sweep apply` of the exact plan file under `github-write` / `clean-approved-issues`. Invoking the command is **not** approval to write.
|
|
28
27
|
|
|
29
28
|
## Hard Rules
|
|
30
29
|
|
|
@@ -38,20 +37,20 @@ Granted authority upon explicit invocation:
|
|
|
38
37
|
## Execution Steps
|
|
39
38
|
|
|
40
39
|
1. **Plan** (read-only)
|
|
41
|
-
- Run `
|
|
40
|
+
- Run `npx -y @bbcsoftwarefactory/cli sweep plan` from the repository root (add `--repo <owner/repo>` if given).
|
|
42
41
|
- On `unusable`, report its `reason` and stop. A missing `.github/issue-sweeper.json` is not an error: the defaults apply (`config: defaults`).
|
|
43
42
|
|
|
44
43
|
2. **Render the plan** as the HUD below, from the `plan` output: every action with its issue link, rule, and steps; the issues deferred by the per-run cap; report-only issues (`SW4` duplicate work, `SW8` exempt); gaps (missing labels, incomplete timelines); and the metrics.
|
|
45
44
|
- If `actions` is empty, close with `🏁 STAGE CLEAR` (nothing to apply).
|
|
46
45
|
- With `--dry-run`, stop after the HUD.
|
|
47
46
|
|
|
48
|
-
3. **Gate**: validate the closing prompt with `question-gate` (`triage-question
|
|
47
|
+
3. **Gate**: validate the closing prompt with `question-gate` (`bbc triage-question`) when installed, then ask one `🟡 BOSS GATE ─ Code Owner / Issue cleanup`:
|
|
49
48
|
- `[A]` apply the whole plan (each issue's comment, close, or label, plus the report issue);
|
|
50
49
|
- `[B]` apply only the issue numbers the person lists;
|
|
51
50
|
- `[C]` apply nothing.
|
|
52
51
|
|
|
53
52
|
4. **Apply** (only after `[A]` or `[B]`)
|
|
54
|
-
- Run `
|
|
53
|
+
- Run `npx -y @bbcsoftwarefactory/cli sweep apply --plan <plan> [--only <n,m>]` with the `plan` path from step 1. Record the request and the use in the delivery ledger when one exists.
|
|
55
54
|
- If it reports a stale plan, go back to step 1 and show the new plan at a new gate; never widen an approval to a plan the person has not seen.
|
|
56
55
|
- Report what was applied and any `errors` (a failed comment means that issue was not closed).
|
|
57
56
|
|
|
@@ -5,14 +5,14 @@
|
|
|
5
5
|
## Pipeline
|
|
6
6
|
|
|
7
7
|
```text
|
|
8
|
-
sweep
|
|
9
|
-
sweep-github
|
|
10
|
-
sweep-issues
|
|
8
|
+
bbc sweep plan -> login, optional .github/issue-sweeper.json from the default branch
|
|
9
|
+
bbc sweep-github fetch -> snapshot.json (one GraphQL query per 30 open issues)
|
|
10
|
+
bbc sweep-issues -> plans/<UTC>.json (offline: rules SW1-SW8, metrics, report)
|
|
11
11
|
🟡 Boss Gate -> the person approves all, some issue numbers, or nothing
|
|
12
|
-
sweep
|
|
12
|
+
bbc sweep apply --plan -> bbc sweep-github apply: only what the approved plan lists, plus the report issue
|
|
13
13
|
```
|
|
14
14
|
|
|
15
|
-
`sweep-issues
|
|
15
|
+
`sweep-issues` decides everything and never calls GitHub; `sweep-github` only reads and writes what the plan says; `sweep` chains them, finds the repository from the checkout's `origin`, and keeps the evidence. An LLM reading this file applies the same rules and must reach the same plan; when they differ, the CLI stands and the difference is reported.
|
|
16
16
|
|
|
17
17
|
## Configuration (optional `.github/issue-sweeper.json`)
|
|
18
18
|
|
|
@@ -32,7 +32,7 @@ Without the file, the defaults apply. With it, its keys override them; it is rea
|
|
|
32
32
|
|
|
33
33
|
The account that applies the plan is the `gh` login of whoever runs the command (`run_by` in the plan). Its sweep comments (by marker) and the `stale` and `needs-close-review` labels it sets are the command's own writes; anything else that person does is activity.
|
|
34
34
|
|
|
35
|
-
## Rules decided by `sweep-issues
|
|
35
|
+
## Rules decided by `sweep-issues`
|
|
36
36
|
|
|
37
37
|
Rules are checked in this order; an issue gets at most one action per plan.
|
|
38
38
|
|
|
@@ -74,13 +74,13 @@ The plan carries a report, shown at the gate and kept as `report.md`. When a pla
|
|
|
74
74
|
## Operation
|
|
75
75
|
|
|
76
76
|
```bash
|
|
77
|
-
|
|
78
|
-
|
|
77
|
+
npx -y @bbcsoftwarefactory/cli sweep plan [--repo <owner>/<repo>]
|
|
78
|
+
npx -y @bbcsoftwarefactory/cli sweep apply --plan <plan> [--only 12,15] [--dry-run]
|
|
79
79
|
```
|
|
80
80
|
|
|
81
81
|
Every step keeps its evidence in `~/.issue-clean-and-close/<owner>__<repo>/` (`SWEEP_HOME` overrides it): the policy file used (`config.json`), `snapshot.json`, the last 30 plans in `plans/` (`--keep`), `report.md`, and one JSON line per step in `runs.log` (plan: actions, deferred, gaps; apply: the plan, `only`, writes, errors).
|
|
82
82
|
|
|
83
|
-
| Exit | `sweep
|
|
83
|
+
| Exit | `sweep` | `sweep-issues` | `sweep-github` |
|
|
84
84
|
|---|---|---|---|
|
|
85
85
|
| 0 | Done | Plan ready | Done |
|
|
86
86
|
| 1 | Some writes failed (listed) | — | Some writes failed (listed) |
|
|
@@ -3,14 +3,13 @@ name: recap
|
|
|
3
3
|
description: "Trigger: /recap, recap, resumen del dia, progreso del dia, cuanto avance, que efectivo fui, daily progress summary. Daily progress summary across Git, GitHub REST, and Project v2 boards: issues created/closed, PRs opened/merged, contribution, work in progress, effectiveness ratios, and optional board sync."
|
|
4
4
|
disable-model-invocation: true
|
|
5
5
|
license: Apache-2.0
|
|
6
|
-
compatibility: Requires
|
|
6
|
+
compatibility: Requires Node.js 22.18+ (`@bbcsoftwarefactory/cli`), Git, and an authenticated gh CLI for GitHub metrics in `bbc recap`.
|
|
7
7
|
metadata:
|
|
8
8
|
author: bbc-skill-internals
|
|
9
9
|
version: "1.1"
|
|
10
10
|
pre_hook: "tool-depot (github-read: read-approved-issue-or-pr, read-pr-review-and-checks)"
|
|
11
11
|
post_hook: "Quest-Tree HUD"
|
|
12
12
|
post_install: "npx --full-depth; copy adapters/gemini.toml + /commands reload (Gemini); server restart (Zed ACP)"
|
|
13
|
-
scripts: "scripts/recap.py"
|
|
14
13
|
adapters: "adapters/command.md, adapters/gemini.toml"
|
|
15
14
|
---
|
|
16
15
|
|
|
@@ -34,14 +33,14 @@ Optional arguments:
|
|
|
34
33
|
- `--json`: Return structured JSON instead of the Quest-Tree HUD.
|
|
35
34
|
|
|
36
35
|
Granted authority upon explicit `/recap` invocation:
|
|
37
|
-
- `A1` (Read-only repo, GitHub & Project v2): local read-only `git log` / `git status` / `git rev-list`, GitHub REST reads (`gh api`) under [Tool Depot](../../skills/tool-depot/SKILL.md) `github-read` (`read-approved-issue-or-pr`, `read-pr-review-and-checks`), and read-only Project v2 GraphQL queries when `--project` is passed. Keep issue/PR/CI reads on REST (`
|
|
36
|
+
- `A1` (Read-only repo, GitHub & Project v2): local read-only `git log` / `git status` / `git rev-list`, GitHub REST reads (`gh api`) under [Tool Depot](../../skills/tool-depot/SKILL.md) `github-read` (`read-approved-issue-or-pr`, `read-pr-review-and-checks`), and read-only Project v2 GraphQL queries when `--project` is passed. Keep issue/PR/CI reads on REST (`bbc recap`).
|
|
38
37
|
- `A2` (Board sync, only when explicitly requested): `--sync-board` mutates only the named `--project` board (and existing repo labels when `--apply-labels` is passed), never closing issues, merging PRs, or modifying local Git files. Preview with `--dry-run` first when the user has not explicitly approved the write target.
|
|
39
38
|
|
|
40
39
|
## Hard Rules
|
|
41
40
|
|
|
42
41
|
- **Read-only by default.** Never write files, switch branches, push commits, or mutate issues, PRs, or boards unless `--sync-board` is explicitly authorized for that target project.
|
|
43
42
|
- **Preserve option IDs on color updates.** When `--fix-colors` updates a single-select field, always keep every option `id` so existing card assignments are never cleared.
|
|
44
|
-
- **No invented numbers.** Every count and ratio comes from `
|
|
43
|
+
- **No invented numbers.** Every count and ratio comes from `bbc recap` against real Git/GitHub output. When GitHub or local Git is unavailable, report `🟡 GAP` and `N/A` rather than guessing `0` or `100%`.
|
|
45
44
|
- **Objective effectiveness.** Report ratios (`merged/opened`, `CI passing`, `closed/created`) with traffic lights (`🟢` / `🟡` / `🔴` / `⚪ N/A`), never a fabricated score.
|
|
46
45
|
- Match the final HUD language to the user (`--lang es` or `--lang en`).
|
|
47
46
|
|
|
@@ -49,7 +48,7 @@ Granted authority upon explicit `/recap` invocation:
|
|
|
49
48
|
|
|
50
49
|
| Situation | Action |
|
|
51
50
|
|---|---|
|
|
52
|
-
| Default invocation (`/recap`) | Run `
|
|
51
|
+
| Default invocation (`/recap`) | Run `npx -y @bbcsoftwarefactory/cli recap` for the current repo (`origin`) from local midnight today |
|
|
53
52
|
| `--all-repos` passed | Include all GitHub repositories for the user while keeping local Git metrics from the current working tree if present |
|
|
54
53
|
| `--project <url\|owner/n>` passed | Query Project v2 board columns, assignee breakdown, and sync diff (`missing_from_board`, `status_mismatches`) read-only |
|
|
55
54
|
| `--team` or `--users` passed | Collect per-member metrics across org members (or listed logins) and include them in the board cross-check |
|
|
@@ -59,16 +58,11 @@ Granted authority upon explicit `/recap` invocation:
|
|
|
59
58
|
|
|
60
59
|
## Execution Steps
|
|
61
60
|
|
|
62
|
-
1.
|
|
63
|
-
2. Run the script with `--lang` matching the user's language (`es` or `en`) and any user-supplied flags (`--since`, `--all-repos`, `--repo`, `--user`, `--team`, `--users`, `--project`, `--sync-board`, `--fix-colors`, `--apply-labels`, `--dry-run`, `--no-github`, `--json`):
|
|
61
|
+
1. Run `bbc recap` (via `npx -y @bbcsoftwarefactory/cli recap` or the linked `bbc` binary) with `--lang` matching the user's language (`es` or `en`) and any user-supplied flags (`--since`, `--all-repos`, `--repo`, `--user`, `--team`, `--users`, `--project`, `--sync-board`, `--fix-colors`, `--apply-labels`, `--dry-run`, `--no-github`, `--json`):
|
|
64
62
|
```bash
|
|
65
|
-
|
|
63
|
+
npx -y @bbcsoftwarefactory/cli recap --lang es
|
|
66
64
|
```
|
|
67
|
-
|
|
68
|
-
```powershell
|
|
69
|
-
python -I -X utf8 -B <recap-root>\scripts\recap.py --lang es
|
|
70
|
-
```
|
|
71
|
-
3. Render the script's Quest-Tree HUD directly in chat. If the user asks for item links (`"detalle"`), rerun with `--json` (or include the `items` list from the JSON output) without inventing details.
|
|
65
|
+
2. Render the command's Quest-Tree HUD directly in chat. If the user asks for item links (`"detalle"`), rerun with `--json` (or include the `items` list from the JSON output) without inventing details.
|
|
72
66
|
|
|
73
67
|
## Output Contract
|
|
74
68
|
|
package/dist/index.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bbcsoftwarefactory/commands",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.1.2",
|
|
4
4
|
"description": "Public BuilderBot slash commands (daily, recap, issue-clean-and-close), packaged for installation by the CLI.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"test": "node --test \"*.test.ts\""
|
|
17
17
|
},
|
|
18
18
|
"dependencies": {
|
|
19
|
-
"@bbcsoftwarefactory/cli-core": "^
|
|
19
|
+
"@bbcsoftwarefactory/cli-core": "^1.1.2"
|
|
20
20
|
},
|
|
21
21
|
"repository": {
|
|
22
22
|
"type": "git",
|
|
@@ -24,8 +24,7 @@
|
|
|
24
24
|
"directory": "packages/commands"
|
|
25
25
|
},
|
|
26
26
|
"publishConfig": {
|
|
27
|
-
"access": "public"
|
|
28
|
-
"provenance": true
|
|
27
|
+
"access": "public"
|
|
29
28
|
},
|
|
30
29
|
"commands": [
|
|
31
30
|
"daily",
|
|
@@ -40,15 +39,11 @@
|
|
|
40
39
|
"commands/issue-clean-and-close": [
|
|
41
40
|
"SKILL.md",
|
|
42
41
|
"adapters",
|
|
43
|
-
"references"
|
|
44
|
-
"scripts",
|
|
45
|
-
"tests"
|
|
42
|
+
"references"
|
|
46
43
|
],
|
|
47
44
|
"commands/recap": [
|
|
48
45
|
"SKILL.md",
|
|
49
|
-
"adapters"
|
|
50
|
-
"scripts",
|
|
51
|
-
"tests"
|
|
46
|
+
"adapters"
|
|
52
47
|
]
|
|
53
48
|
}
|
|
54
49
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bbcsoftwarefactory/commands",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.1.2",
|
|
4
4
|
"description": "Public BuilderBot slash commands (daily, recap, issue-clean-and-close), packaged for installation by the CLI.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"test": "node --test \"*.test.ts\""
|
|
17
17
|
},
|
|
18
18
|
"dependencies": {
|
|
19
|
-
"@bbcsoftwarefactory/cli-core": "^
|
|
19
|
+
"@bbcsoftwarefactory/cli-core": "^1.1.2"
|
|
20
20
|
},
|
|
21
21
|
"repository": {
|
|
22
22
|
"type": "git",
|
|
@@ -24,7 +24,6 @@
|
|
|
24
24
|
"directory": "packages/commands"
|
|
25
25
|
},
|
|
26
26
|
"publishConfig": {
|
|
27
|
-
"access": "public"
|
|
28
|
-
"provenance": true
|
|
27
|
+
"access": "public"
|
|
29
28
|
}
|
|
30
29
|
}
|
|
@@ -1,347 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
"""sweep-github.py: the only part of /issue-clean-and-close that talks to GitHub.
|
|
3
|
-
|
|
4
|
-
`fetch` reads every open issue with one paginated GraphQL query and writes the snapshot
|
|
5
|
-
that sweep-issues.py evaluates. `apply` performs exactly the writes a plan lists, in order,
|
|
6
|
-
and nothing else. Both use the `gh` CLI. Policy: references/policy.md.
|
|
7
|
-
"""
|
|
8
|
-
|
|
9
|
-
from datetime import datetime, timezone
|
|
10
|
-
import json
|
|
11
|
-
import os
|
|
12
|
-
import re
|
|
13
|
-
import subprocess
|
|
14
|
-
import sys
|
|
15
|
-
from urllib.parse import quote
|
|
16
|
-
|
|
17
|
-
DEFAULT_SWEEPER = 'github-actions[bot]'
|
|
18
|
-
PAGE_SIZE = 30
|
|
19
|
-
MAX_PAGES = 100
|
|
20
|
-
PR_TEXT_LIMIT = 4000
|
|
21
|
-
ISSUE_REFERENCE = re.compile(r'#\d|/issues/\d')
|
|
22
|
-
MARKER = re.compile(r'<!-- issue-sweeper:([A-Za-z0-9]+) -->')
|
|
23
|
-
REPORT_MARKER = '<!-- issue-sweeper:report -->'
|
|
24
|
-
PR_FIELDS = 'number url state mergedAt title body repository { nameWithOwner } mergeCommit { oid }'
|
|
25
|
-
QUERY = '''
|
|
26
|
-
query($owner: String!, $name: String!, $cursor: String) {
|
|
27
|
-
repository(owner: $owner, name: $name) {
|
|
28
|
-
nameWithOwner
|
|
29
|
-
labels(first: 100) { nodes { name } }
|
|
30
|
-
issues(states: OPEN, first: %d, after: $cursor, orderBy: {field: CREATED_AT, direction: ASC}) {
|
|
31
|
-
pageInfo { hasNextPage endCursor }
|
|
32
|
-
nodes {
|
|
33
|
-
number title url createdAt body
|
|
34
|
-
author { login }
|
|
35
|
-
labels(first: 50) { nodes { name } }
|
|
36
|
-
assignees(first: 10) { nodes { login } }
|
|
37
|
-
refs: timelineItems(first: 25, itemTypes: [CONNECTED_EVENT, DISCONNECTED_EVENT, CROSS_REFERENCED_EVENT]) {
|
|
38
|
-
pageInfo { hasNextPage }
|
|
39
|
-
nodes {
|
|
40
|
-
__typename
|
|
41
|
-
... on ConnectedEvent { createdAt subject { ... on PullRequest { %s } } }
|
|
42
|
-
... on DisconnectedEvent { createdAt subject { ... on PullRequest { %s } } }
|
|
43
|
-
... on CrossReferencedEvent { createdAt willCloseTarget source { ... on PullRequest { %s } } }
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
recent: timelineItems(last: 25, itemTypes: [ISSUE_COMMENT, LABELED_EVENT, UNLABELED_EVENT, REOPENED_EVENT]) {
|
|
47
|
-
nodes {
|
|
48
|
-
__typename
|
|
49
|
-
... on IssueComment { createdAt author { login } body }
|
|
50
|
-
... on LabeledEvent { createdAt actor { login } label { name } }
|
|
51
|
-
... on UnlabeledEvent { createdAt actor { login } label { name } }
|
|
52
|
-
... on ReopenedEvent { createdAt actor { login } }
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
''' % (PAGE_SIZE, PR_FIELDS, PR_FIELDS, PR_FIELDS)
|
|
60
|
-
LABEL_EVENTS = {'LabeledEvent': 'labeled', 'UnlabeledEvent': 'unlabeled'}
|
|
61
|
-
|
|
62
|
-
HELP = (
|
|
63
|
-
'Usage: python3 -I -B scripts/sweep-github.py fetch --repo <owner/repo> --out <snapshot.json>'
|
|
64
|
-
' [--sweeper-login github-actions[bot]]\n'
|
|
65
|
-
' python3 -I -B scripts/sweep-github.py apply --repo <owner/repo> --plan <plan.json> [--only 12,15] [--dry-run]\n'
|
|
66
|
-
'Needs an authenticated gh CLI (SWEEP_GH overrides the command); sweep.py runs both steps.\n'
|
|
67
|
-
'Exit 0: done; 1: some writes failed (listed); 2: unusable input.'
|
|
68
|
-
)
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
class Unusable(Exception):
|
|
72
|
-
"""The arguments, plan, or GitHub response cannot be used."""
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
def _write_out(text):
|
|
76
|
-
sys.stdout.buffer.write((text + '\n').encode('utf-8', 'surrogateescape'))
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
def _fold(value):
|
|
80
|
-
return value.strip().casefold() if isinstance(value, str) else ''
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
def _login(value):
|
|
84
|
-
login = value.get('login') if isinstance(value, dict) else None
|
|
85
|
-
return login if isinstance(login, str) and login else 'ghost'
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
def _nodes(value):
|
|
89
|
-
nodes = value.get('nodes') if isinstance(value, dict) else None
|
|
90
|
-
return [node for node in nodes or [] if isinstance(node, dict)]
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
def _pull(node):
|
|
94
|
-
"""The pull request in a timeline node, or None for issues and inaccessible sources."""
|
|
95
|
-
return node if isinstance(node, dict) and 'state' in node and isinstance(node.get('number'), int) else None
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
def _pr_entry(pr, at):
|
|
99
|
-
body = pr.get('body') if isinstance(pr.get('body'), str) else ''
|
|
100
|
-
references = [line.strip() for line in body.splitlines() if ISSUE_REFERENCE.search(line)]
|
|
101
|
-
text = '\n'.join([pr.get('title') or ''] + references)[:PR_TEXT_LIMIT]
|
|
102
|
-
merge = pr.get('mergeCommit') if isinstance(pr.get('mergeCommit'), dict) else {}
|
|
103
|
-
repo = pr.get('repository') if isinstance(pr.get('repository'), dict) else {}
|
|
104
|
-
return {'number': pr['number'], 'repo': repo.get('nameWithOwner'), 'state': pr.get('state'),
|
|
105
|
-
'merged_at': pr.get('mergedAt'), 'merge_commit': merge.get('oid'), 'url': pr.get('url'),
|
|
106
|
-
'will_close': False, 'manual_link': False, 'text': text, 'referenced_at': at}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
def _prs(refs):
|
|
110
|
-
found = {}
|
|
111
|
-
for node in sorted(_nodes(refs), key=lambda item: item.get('createdAt') or ''):
|
|
112
|
-
kind = node.get('__typename')
|
|
113
|
-
pr = _pull(node.get('source') if kind == 'CrossReferencedEvent' else node.get('subject'))
|
|
114
|
-
if pr is None:
|
|
115
|
-
continue
|
|
116
|
-
key = (_fold((pr.get('repository') or {}).get('nameWithOwner')), pr['number'])
|
|
117
|
-
entry = found.setdefault(key, _pr_entry(pr, node.get('createdAt')))
|
|
118
|
-
if kind == 'CrossReferencedEvent':
|
|
119
|
-
entry['will_close'] = entry['will_close'] or node.get('willCloseTarget') is True
|
|
120
|
-
else:
|
|
121
|
-
entry['manual_link'] = kind == 'ConnectedEvent'
|
|
122
|
-
return list(found.values())
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
def _events(recent):
|
|
126
|
-
events = []
|
|
127
|
-
for node in _nodes(recent):
|
|
128
|
-
kind = node.get('__typename')
|
|
129
|
-
at = node.get('createdAt')
|
|
130
|
-
if kind == 'IssueComment':
|
|
131
|
-
body = node.get('body') if isinstance(node.get('body'), str) else ''
|
|
132
|
-
match = MARKER.search(body)
|
|
133
|
-
events.append({'type': 'comment', 'at': at, 'actor': _login(node.get('author')),
|
|
134
|
-
'marker': match.group(1) if match else None})
|
|
135
|
-
elif kind in LABEL_EVENTS:
|
|
136
|
-
label = node.get('label') if isinstance(node.get('label'), dict) else {}
|
|
137
|
-
events.append({'type': LABEL_EVENTS[kind], 'label': label.get('name'), 'at': at,
|
|
138
|
-
'actor': _login(node.get('actor'))})
|
|
139
|
-
elif kind == 'ReopenedEvent':
|
|
140
|
-
events.append({'type': 'reopened', 'at': at, 'actor': _login(node.get('actor'))})
|
|
141
|
-
return events
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
def _bare(login):
|
|
145
|
-
folded = _fold(login)
|
|
146
|
-
return folded[:-5] if folded.endswith('[bot]') else folded
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
def to_snapshot(pages, fetched_at, sweeper_login=DEFAULT_SWEEPER):
|
|
150
|
-
"""GraphQL pages -> the snapshot sweep-issues.py reads. Bodies never leave this function.
|
|
151
|
-
|
|
152
|
-
Only an issue the sweeper itself opened can be the report issue, so nobody can get
|
|
153
|
-
another issue's body overwritten by copying the marker into it.
|
|
154
|
-
"""
|
|
155
|
-
sweeper = _bare(sweeper_login)
|
|
156
|
-
if not pages:
|
|
157
|
-
raise Unusable('No GraphQL pages.')
|
|
158
|
-
repos = [((page or {}).get('data') or {}).get('repository') for page in pages]
|
|
159
|
-
if not all(isinstance(repo, dict) for repo in repos):
|
|
160
|
-
raise Unusable('GraphQL response has no repository; check the name and the token.')
|
|
161
|
-
snapshot = {'repo': repos[0].get('nameWithOwner'), 'fetched_at': fetched_at,
|
|
162
|
-
'labels': [node.get('name') for node in _nodes(repos[0].get('labels'))],
|
|
163
|
-
'report_issue': None, 'issues': []}
|
|
164
|
-
for repo in repos:
|
|
165
|
-
for node in _nodes(repo.get('issues')):
|
|
166
|
-
body = node.get('body') if isinstance(node.get('body'), str) else ''
|
|
167
|
-
if REPORT_MARKER in body and _bare(_login(node.get('author'))) == sweeper:
|
|
168
|
-
snapshot['report_issue'] = snapshot['report_issue'] or node.get('number')
|
|
169
|
-
continue
|
|
170
|
-
refs = node.get('refs') if isinstance(node.get('refs'), dict) else {}
|
|
171
|
-
snapshot['issues'].append({
|
|
172
|
-
'number': node.get('number'), 'title': node.get('title'), 'url': node.get('url'),
|
|
173
|
-
'author': _login(node.get('author')), 'created_at': node.get('createdAt'),
|
|
174
|
-
'labels': [label.get('name') for label in _nodes(node.get('labels'))],
|
|
175
|
-
'assignees': [_login(user) for user in _nodes(node.get('assignees'))],
|
|
176
|
-
'prs': _prs(refs), 'events': _events(node.get('recent')),
|
|
177
|
-
'incomplete': (refs.get('pageInfo') or {}).get('hasNextPage') is True,
|
|
178
|
-
})
|
|
179
|
-
return snapshot
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
def issue_commands(plan, repo):
|
|
183
|
-
"""[(issue, gh argv)] for every step of every action, in plan order."""
|
|
184
|
-
commands = []
|
|
185
|
-
for entry in plan.get('actions') or []:
|
|
186
|
-
base = 'repos/' + repo + '/issues/' + str(entry['issue'])
|
|
187
|
-
for step in entry.get('steps') or []:
|
|
188
|
-
action = step.get('action')
|
|
189
|
-
if action == 'comment':
|
|
190
|
-
argv = ['api', '-X', 'POST', base + '/comments', '-f', 'body=' + step['body']]
|
|
191
|
-
elif action == 'close':
|
|
192
|
-
argv = ['api', '-X', 'PATCH', base, '-f', 'state=closed', '-f', 'state_reason=' + step['state_reason']]
|
|
193
|
-
elif action == 'add-label':
|
|
194
|
-
argv = ['api', '-X', 'POST', base + '/labels', '-f', 'labels[]=' + step['label']]
|
|
195
|
-
elif action == 'remove-label':
|
|
196
|
-
argv = ['api', '-X', 'DELETE', base + '/labels/' + quote(step['label'], safe='')]
|
|
197
|
-
else:
|
|
198
|
-
raise Unusable('Unknown plan step: ' + str(action))
|
|
199
|
-
commands.append((entry['issue'], argv))
|
|
200
|
-
return commands
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
def report_command(plan, repo):
|
|
204
|
-
body = 'body=' + plan['report_markdown']
|
|
205
|
-
if isinstance(plan.get('report_issue'), int):
|
|
206
|
-
return ['api', '-X', 'PATCH', 'repos/' + repo + '/issues/' + str(plan['report_issue']), '-f', body]
|
|
207
|
-
return ['api', '-X', 'POST', 'repos/' + repo + '/issues', '-f', 'title=' + plan['report_title'], '-f', body]
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
def _gh_command():
|
|
211
|
-
"""`gh`, or SWEEP_GH: a path, or a JSON array such as ["python3", "fake_gh.py"] for tests."""
|
|
212
|
-
value = os.environ.get('SWEEP_GH', '').strip()
|
|
213
|
-
return json.loads(value) if value.startswith('[') else [value or 'gh']
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
def _gh(argv):
|
|
217
|
-
try:
|
|
218
|
-
result = subprocess.run(_gh_command() + argv, capture_output=True, text=True, encoding='utf-8')
|
|
219
|
-
except OSError as error:
|
|
220
|
-
raise Unusable('gh CLI is not available: ' + str(error))
|
|
221
|
-
return result.returncode, result.stdout, result.stderr.strip()[:500]
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
def fetch(repo, out, sweeper_login):
|
|
225
|
-
owner, name = repo.split('/', 1)
|
|
226
|
-
pages, cursor = [], None
|
|
227
|
-
for _ in range(MAX_PAGES):
|
|
228
|
-
argv = ['api', 'graphql', '-f', 'query=' + QUERY, '-f', 'owner=' + owner, '-f', 'name=' + name]
|
|
229
|
-
if cursor:
|
|
230
|
-
argv += ['-f', 'cursor=' + cursor]
|
|
231
|
-
code, stdout, stderr = _gh(argv)
|
|
232
|
-
if code != 0:
|
|
233
|
-
raise Unusable('GraphQL query failed: ' + stderr)
|
|
234
|
-
try:
|
|
235
|
-
page = json.loads(stdout)
|
|
236
|
-
except ValueError:
|
|
237
|
-
raise Unusable('GraphQL response is not JSON.')
|
|
238
|
-
pages.append(page)
|
|
239
|
-
info = (((page.get('data') or {}).get('repository') or {}).get('issues') or {}).get('pageInfo') or {}
|
|
240
|
-
if not info.get('hasNextPage'):
|
|
241
|
-
break
|
|
242
|
-
cursor = info.get('endCursor')
|
|
243
|
-
else:
|
|
244
|
-
raise Unusable('More than ' + str(MAX_PAGES * PAGE_SIZE) + ' open issues; raise MAX_PAGES deliberately.')
|
|
245
|
-
snapshot = to_snapshot(pages, datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'), sweeper_login)
|
|
246
|
-
with open(out, 'w', encoding='utf-8') as handle:
|
|
247
|
-
json.dump(snapshot, handle, ensure_ascii=False, indent=2)
|
|
248
|
-
return {'snapshot': out, 'issues': len(snapshot['issues']), 'pages': len(pages),
|
|
249
|
-
'report_issue': snapshot['report_issue']}
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
def load_plan(path, repo):
|
|
253
|
-
try:
|
|
254
|
-
with open(path, encoding='utf-8') as handle:
|
|
255
|
-
plan = json.load(handle)
|
|
256
|
-
except (OSError, ValueError):
|
|
257
|
-
raise Unusable('Plan cannot be read as JSON.')
|
|
258
|
-
if not isinstance(plan, dict) or plan.get('verdict') != 'ok':
|
|
259
|
-
raise Unusable('Plan verdict is not ok; nothing is written.')
|
|
260
|
-
if _fold(plan.get('repo')) != _fold(repo):
|
|
261
|
-
raise Unusable('Plan is for ' + str(plan.get('repo')) + ', not ' + repo + '.')
|
|
262
|
-
if not isinstance(plan.get('actions'), list) or not isinstance(plan.get('report_markdown'), str):
|
|
263
|
-
raise Unusable('Plan needs actions and report_markdown.')
|
|
264
|
-
return plan
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
def select(plan, only):
|
|
268
|
-
"""The plan restricted to the approved issue numbers; an unknown number is refused, not ignored."""
|
|
269
|
-
if only is None:
|
|
270
|
-
return plan
|
|
271
|
-
planned = {entry['issue'] for entry in plan['actions']}
|
|
272
|
-
unknown = sorted(only - planned)
|
|
273
|
-
if unknown:
|
|
274
|
-
raise Unusable('--only lists issues the plan does not act on: ' + ', '.join(map(str, unknown)))
|
|
275
|
-
return dict(plan, actions=[entry for entry in plan['actions'] if entry['issue'] in only])
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
def apply(repo, plan_path, dry_run, only=None):
|
|
279
|
-
plan = select(load_plan(plan_path, repo), only)
|
|
280
|
-
commands = issue_commands(plan, repo)
|
|
281
|
-
commands.append(('report', report_command(plan, repo)))
|
|
282
|
-
if dry_run:
|
|
283
|
-
return {'dry_run': True, 'writes': [{'issue': issue, 'argv': argv} for issue, argv in commands]}, 0
|
|
284
|
-
applied, errors, failed = [], [], set()
|
|
285
|
-
for issue, argv in commands:
|
|
286
|
-
if issue in failed:
|
|
287
|
-
errors.append({'issue': issue, 'argv': argv[:4], 'error': 'skipped after an earlier failure'})
|
|
288
|
-
continue
|
|
289
|
-
code, _, stderr = _gh(argv)
|
|
290
|
-
if code == 0:
|
|
291
|
-
applied.append({'issue': issue, 'argv': argv[:4]})
|
|
292
|
-
else:
|
|
293
|
-
failed.add(issue)
|
|
294
|
-
errors.append({'issue': issue, 'argv': argv[:4], 'error': stderr})
|
|
295
|
-
return {'dry_run': False, 'applied': applied, 'errors': errors}, 1 if errors else 0
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
def parse_args(argv):
|
|
299
|
-
if not argv or argv[0] in ('--help', '-h') or '--help' in argv:
|
|
300
|
-
return None
|
|
301
|
-
command, rest = argv[0], argv[1:]
|
|
302
|
-
if command not in ('fetch', 'apply'):
|
|
303
|
-
raise Unusable('Unknown command: ' + command)
|
|
304
|
-
args = {'command': command, 'dry_run': '--dry-run' in rest}
|
|
305
|
-
rest = [item for item in rest if item != '--dry-run']
|
|
306
|
-
required = ('--repo', '--out') if command == 'fetch' else ('--repo', '--plan')
|
|
307
|
-
allowed = required + (('--sweeper-login',) if command == 'fetch' else ('--only',))
|
|
308
|
-
args['sweeper-login'] = DEFAULT_SWEEPER
|
|
309
|
-
for index in range(0, len(rest), 2):
|
|
310
|
-
if rest[index] not in allowed or index + 1 >= len(rest):
|
|
311
|
-
raise Unusable('Unknown or incomplete argument: ' + rest[index])
|
|
312
|
-
args[rest[index][2:]] = rest[index + 1]
|
|
313
|
-
for key in required:
|
|
314
|
-
if key[2:] not in args:
|
|
315
|
-
raise Unusable('Missing ' + key + '.')
|
|
316
|
-
if not re.fullmatch(r'[\w.-]+/[\w.-]+', args['repo']):
|
|
317
|
-
raise Unusable('--repo must be owner/name.')
|
|
318
|
-
args['only'] = parse_only(args['only']) if 'only' in args else None
|
|
319
|
-
return args
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
def parse_only(value):
|
|
323
|
-
numbers = [item.strip().lstrip('#') for item in value.split(',') if item.strip()]
|
|
324
|
-
if not numbers or not all(item.isdigit() for item in numbers):
|
|
325
|
-
raise Unusable('--only must be issue numbers separated by commas, e.g. 12,15.')
|
|
326
|
-
return {int(item) for item in numbers}
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
def main(argv):
|
|
330
|
-
try:
|
|
331
|
-
args = parse_args(argv)
|
|
332
|
-
if args is None:
|
|
333
|
-
_write_out(HELP)
|
|
334
|
-
return 0
|
|
335
|
-
if args['command'] == 'fetch':
|
|
336
|
-
result, code = fetch(args['repo'], args['out'], args['sweeper-login']), 0
|
|
337
|
-
else:
|
|
338
|
-
result, code = apply(args['repo'], args['plan'], args['dry_run'], args['only'])
|
|
339
|
-
except Unusable as error:
|
|
340
|
-
_write_out(json.dumps({'verdict': 'unusable', 'reason': str(error)}, ensure_ascii=False))
|
|
341
|
-
return 2
|
|
342
|
-
_write_out(json.dumps(result, ensure_ascii=False, indent=2))
|
|
343
|
-
return code
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
if __name__ == '__main__':
|
|
347
|
-
sys.exit(main(sys.argv[1:]))
|