@bbcsoftwarefactory/skills 0.0.0-stage → 0.1.0
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/index.json +42 -0
- package/dist/skills/code-quality-gate/SKILL.md +59 -0
- package/dist/skills/code-quality-gate/references/gate-bigo.md +31 -0
- package/dist/skills/code-quality-gate/references/gate-earlyreturn.md +73 -0
- package/dist/skills/code-quality-gate/references/gate-typesafe.md +32 -0
- package/dist/skills/code-quality-gate/references/output-schema.yml +40 -0
- package/dist/skills/code-quality-gate/scripts/extract-diff-scope.py +225 -0
- package/dist/skills/code-quality-gate/tests/extract-diff-scope.test.sh +200 -0
- package/dist/skills/delivery-coordinator/SKILL.md +81 -0
- package/dist/skills/delivery-coordinator/references/hud-output.md +55 -0
- package/dist/skills/delivery-coordinator/references/intake.md +86 -0
- package/dist/skills/delivery-coordinator/references/issue-claim.md +143 -0
- package/dist/skills/delivery-coordinator/references/issue-dedup.md +38 -0
- package/dist/skills/delivery-coordinator/references/sleuth-regression-exercise.md +60 -0
- package/dist/skills/delivery-coordinator/references/visual-reference.md +45 -0
- package/dist/skills/delivery-coordinator/references/worktree-isolation.md +19 -0
- package/dist/skills/delivery-coordinator/scripts/check-issue-claim.py +363 -0
- package/dist/skills/delivery-coordinator/scripts/check-worktree-guard.py +220 -0
- package/dist/skills/delivery-coordinator/scripts/classify-change-lane.py +263 -0
- package/dist/skills/delivery-coordinator/tests/check-issue-claim.test.sh +221 -0
- package/dist/skills/delivery-coordinator/tests/check-worktree-guard.test.sh +123 -0
- package/dist/skills/delivery-coordinator/tests/classify-change-lane.test.sh +124 -0
- package/dist/skills/documentation-steward/SKILL.md +43 -0
- package/dist/skills/documentation-steward/references/discovery.md +17 -0
- package/dist/skills/documentation-steward/references/handoff.md +15 -0
- package/dist/skills/greptile-review-loop/SKILL.md +57 -0
- package/dist/skills/greptile-review-loop/references/review-protocol.md +37 -0
- package/dist/skills/greptile-review-loop/scripts/review-loop.py +435 -0
- package/dist/skills/greptile-review-loop/tests/review-loop.test.sh +331 -0
- package/dist/skills/issue-reviewer/SKILL.md +87 -0
- package/dist/skills/issue-reviewer/references/review-format.md +100 -0
- package/dist/skills/issue-reviewer/references/triage.md +105 -0
- package/dist/skills/issue-reviewer/scripts/fetch-issue-attachments.py +239 -0
- package/dist/skills/issue-reviewer/scripts/plan-issue-triage.py +311 -0
- package/dist/skills/issue-reviewer/tests/fetch-issue-attachments.test.sh +90 -0
- package/dist/skills/issue-reviewer/tests/plan-issue-triage.test.sh +168 -0
- package/dist/skills/question-gate/SKILL.md +66 -0
- package/dist/skills/question-gate/references/client-hooks.md +111 -0
- package/dist/skills/question-gate/references/diagram-routing.md +58 -0
- package/dist/skills/question-gate/scripts/triage-question.py +713 -0
- package/dist/skills/question-gate/tests/fixtures/question-corpus.json +481 -0
- package/dist/skills/question-gate/tests/question-corpus.test.sh +32 -0
- package/dist/skills/question-gate/tests/triage-question.test.sh +441 -0
- package/dist/skills/regression-testing/SKILL.md +49 -0
- package/dist/skills/regression-testing/references/evidence-record.md +35 -0
- package/dist/skills/requirements-spec/SKILL.md +59 -0
- package/dist/skills/risk-scout/SKILL.md +53 -0
- package/dist/skills/risk-scout/references/risk-matrix.md +49 -0
- package/dist/skills/skill-clean-architecture/SKILL.md +54 -0
- package/dist/skills/skill-clean-architecture/references/layer-rules.md +22 -0
- package/dist/skills/skill-clean-architecture/references/source-headers.md +31 -0
- package/dist/skills/skill-clean-architecture/scripts/measure-bigo.py +427 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/bad-utf8.js +1 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/edge-crlf.ts +6 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/edge-mixed.ts +15 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/empty.js +0 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/no-newline.js +1 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo.expected.yml +95 -0
- package/dist/skills/skill-clean-architecture/tests/measure-bigo.test.sh +222 -0
- package/dist/skills/tool-depot/SKILL.md +47 -0
- package/dist/skills/tool-depot/references/checkout.md +29 -0
- package/dist/skills/tool-depot/references/loki-read.md +41 -0
- package/dist/skills/tool-depot/references/readonly-access.md +84 -0
- package/dist/skills/tool-depot/references/tool-catalog.json +47 -0
- package/dist/skills/tool-depot/scripts/loki-runtime-logs.py +305 -0
- package/dist/skills/tool-depot/tests/loki-runtime-logs.test.sh +101 -0
- package/dist/skills/watcher-observability/SKILL.md +73 -0
- package/dist/skills/watcher-observability/references/batch-protocol.md +44 -0
- package/dist/skills/watcher-observability/references/configuration.md +31 -0
- package/dist/skills/watcher-observability/references/error-scan.md +102 -0
- package/dist/skills/watcher-observability/references/live-protocol.md +49 -0
- package/dist/skills/watcher-observability/references/server-account.md +72 -0
- package/dist/skills/watcher-observability/scripts/error-scan.py +318 -0
- package/dist/skills/watcher-observability/scripts/resolve-containers.py +155 -0
- package/dist/skills/watcher-observability/scripts/save-counts.py +381 -0
- package/dist/skills/watcher-observability/scripts/summarize-logs.py +113 -0
- package/dist/skills/watcher-observability/scripts/watch-live.py +606 -0
- package/dist/skills/watcher-observability/server/watcher-gate.sh +51 -0
- package/dist/skills/watcher-observability/tests/error-scan.test.sh +257 -0
- package/dist/skills/watcher-observability/tests/live-windows.test.sh +177 -0
- package/dist/skills/watcher-observability/tests/resolve-containers.test.sh +87 -0
- package/dist/skills/watcher-observability/tests/save-counts.test.sh +338 -0
- package/dist/skills/watcher-observability/tests/sleuth.test.sh +176 -0
- package/dist/skills/watcher-observability/tests/summarize-logs.test.sh +105 -0
- package/dist/skills/watcher-observability/tests/watcher-config.test.sh +70 -0
- package/dist/skills/watcher-observability/tests/watcher-gate.test.sh +110 -0
- package/dist/skills/watcher-observability/watcher.json +1 -0
- package/dist/skills/workflow-auditor/SKILL.md +55 -0
- package/dist/skills/workflow-auditor/references/audit-protocol.md +49 -0
- package/dist/skills/workflow-auditor/references/ledger.md +122 -0
- package/dist/skills/workflow-auditor/scripts/audit-ledger.py +624 -0
- package/dist/skills/workflow-auditor/scripts/list-zed-commands.py +183 -0
- package/dist/skills/workflow-auditor/scripts/render-workflow.py +201 -0
- package/dist/skills/workflow-auditor/scripts/validate-skills.py +444 -0
- package/dist/skills/workflow-auditor/tests/audit-ledger.test.sh +660 -0
- package/dist/skills/workflow-auditor/tests/list-zed-commands.test.sh +93 -0
- package/dist/skills/workflow-auditor/tests/render-workflow.test.sh +135 -0
- package/dist/skills/workflow-auditor/tests/validate-skills.test.sh +190 -0
- package/package.json +27 -6
- package/README.md +0 -3
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# Exercise: from Sleuth evidence to a regression test
|
|
2
|
+
|
|
3
|
+
This is a fictional incident. Use the anonymized evidence below to draft an issue and run an offline reproduction. Do not open a GitHub issue, capture logs, or change production code for the exercise.
|
|
4
|
+
|
|
5
|
+
## 1. Read the evidence
|
|
6
|
+
|
|
7
|
+
Selected fields from a synthetic Sleuth report (not a complete Watcher artifact):
|
|
8
|
+
|
|
9
|
+
| Window | Sequence | Capture-local label | Evidence |
|
|
10
|
+
|---|---|---|---|
|
|
11
|
+
| 1 | 8 | `id1` | `TimeoutError`, code `ETIMEDOUT` |
|
|
12
|
+
| 1 | 9 | `id1` | Code `ECONNRESET` |
|
|
13
|
+
|
|
14
|
+
Coverage is incomplete. The events share a label, but neither proves that the application stored a job twice. A separate synthetic product report says one job appeared twice after a timeout. Treat that symptom and the log observations as different evidence.
|
|
15
|
+
|
|
16
|
+
## 2. Draft the issue
|
|
17
|
+
|
|
18
|
+
**Title:** Retrying a job after a timeout can create a duplicate
|
|
19
|
+
|
|
20
|
+
- **Observed:** A synthetic product report describes two entries for one job. Sleuth observed two network errors linked within one capture; it did not observe the writes.
|
|
21
|
+
- **Expected:** If the first attempt stored the job but its acknowledgement was lost, retrying the same command with the same key leaves exactly one stored job.
|
|
22
|
+
- **Reproduction:** In an isolated fixture, persist the first attempt, simulate a lost acknowledgement, retry with the same key, and query the stored jobs via the public read interface.
|
|
23
|
+
- **Acceptance scenario:** Given a stored job whose acknowledgement was lost, when a caller retries the same key, then the read interface returns exactly one job for that key.
|
|
24
|
+
- **Unknown:** Whether the first attempt committed in the reported incident. The fixture tests that scenario; it does not prove the production cause.
|
|
25
|
+
|
|
26
|
+
## 3. Exercise the acceptance test offline
|
|
27
|
+
|
|
28
|
+
Run this self-contained Python example. Its intentionally faulty fake service should fail the regression assertion with `expected 1 stored job; got 2`. A process or fixture setup error is not an acceptable RED result.
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
class FakeJobService:
|
|
32
|
+
def __init__(self):
|
|
33
|
+
self.jobs = []
|
|
34
|
+
|
|
35
|
+
def submit(self, key, *, lose_ack=False):
|
|
36
|
+
self.jobs.append(key)
|
|
37
|
+
if lose_ack:
|
|
38
|
+
raise TimeoutError("fixture: acknowledgement lost")
|
|
39
|
+
|
|
40
|
+
def find_jobs(self, key):
|
|
41
|
+
return [job for job in self.jobs if job == key]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_retry_after_lost_ack():
|
|
45
|
+
service = FakeJobService()
|
|
46
|
+
try:
|
|
47
|
+
service.submit("synthetic-key", lose_ack=True)
|
|
48
|
+
except TimeoutError:
|
|
49
|
+
pass
|
|
50
|
+
else:
|
|
51
|
+
raise AssertionError("fixture did not simulate a lost acknowledgement")
|
|
52
|
+
service.submit("synthetic-key")
|
|
53
|
+
count = len(service.find_jobs("synthetic-key"))
|
|
54
|
+
assert count == 1, f"expected 1 stored job; got {count}"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
test_retry_after_lost_ack()
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
In a real repository, use its public API and test runner instead of the fake. Stop after the issue draft if that is the requested deliverable. If implementation is authorized, follow the Clean Architecture companion and record GREEN only when the same regression test passes against the changed application.
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Visual reference on every issue write
|
|
2
|
+
|
|
3
|
+
Every issue the workflow publishes, every issue body it updates, and every comment it posts on an issue (including the PR back-link) embeds at least one visual reference. A reader must see the problem or the change without reproducing it. Text alone is not enough.
|
|
4
|
+
|
|
5
|
+
## Pick the visual
|
|
6
|
+
|
|
7
|
+
Use the first source that applies:
|
|
8
|
+
|
|
9
|
+
| Situation | Visual |
|
|
10
|
+
|---|---|
|
|
11
|
+
| The person supplied a screenshot, image, or recording | Attach that file. Describing it is not a substitute. On an existing issue, keep the original embeds intact and add new ones next to them. |
|
|
12
|
+
| UI bug | Screenshot of the observed failure on the real screen, cropped to the relevant area. |
|
|
13
|
+
| UI change (PR back-link or progress comment) | Screenshot of the new state. If the real screen cannot reach that state, render the real component with synthetic data in a temporary harness that is never committed. Add a before/after pair when it explains the change. |
|
|
14
|
+
| No UI surface (API, backend, worker, infra) | A rendered image of sanitized evidence: the failing and passing test output, a sequence or flow diagram, or a sanitized error panel. |
|
|
15
|
+
| None of the above can be produced safely | Write a `🟡 GAP visual: <reason>` line in the issue body or comment, and show the same gap in the HUD. Never skip silently. |
|
|
16
|
+
|
|
17
|
+
## Keep it safe
|
|
18
|
+
|
|
19
|
+
Images on GitHub are readable by anyone with the URL. Before uploading, open the image and check it:
|
|
20
|
+
|
|
21
|
+
- Use synthetic data: fictional names, `555-01xx` phone numbers, `example.com` addresses, fake IDs.
|
|
22
|
+
- Crop or redact tokens, API keys, emails, phone numbers, customer names, internal hostnames, container IDs, and raw log lines.
|
|
23
|
+
- Never upload a full Sleuth report, a raw log, or a terminal that shows secrets or environment values.
|
|
24
|
+
- If redaction would leave nothing useful, record the `🟡 GAP visual` instead.
|
|
25
|
+
|
|
26
|
+
## Host and embed
|
|
27
|
+
|
|
28
|
+
The GitHub REST API cannot upload `user-attachments`. When the host has no native image upload, use a secret gist:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
gh gist create README.md -d "<repo>#<n> visual reference" # returns https://gist.github.com/<id>
|
|
32
|
+
git clone https://gist.github.com/<id>.git <tmp>/gist
|
|
33
|
+
cp <tmp>/<name>.png <tmp>/gist/ && git -C <tmp>/gist add . && git -C <tmp>/gist commit -m "add visual" && git -C <tmp>/gist push
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
1. Embed the raw URL pinned to the gist commit SHA, so the image does not change later: `https://gist.githubusercontent.com/<user>/<id>/raw/<sha>/<name>.png`.
|
|
37
|
+
2. Check that it returns `200` with an `image/*` content type before posting.
|
|
38
|
+
3. Use descriptive alt text in the issue's language, for example ``.
|
|
39
|
+
4. Keep screenshots, harness files, and gist clones in a temporary directory outside the repository. Delete any harness file from the worktree before committing.
|
|
40
|
+
|
|
41
|
+
Request `github-write` / `host-approved-visual-reference` through `tool-depot` for the gist. The authorization for the issue write it illustrates also covers hosting its images.
|
|
42
|
+
|
|
43
|
+
## Record it
|
|
44
|
+
|
|
45
|
+
In the delivery ledger, every `tool_uses` entry for `publish-approved-issue`, `update-approved-issue`, or `comment-approved-issue` carries `visual`: the embedded image URL, or `{"gap": "<reason>"}`. `workflow-auditor` flags a missing visual as `V1` and a stated gap as `G2`.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Prepare an isolated worktree
|
|
2
|
+
|
|
3
|
+
Delivery Coordinator owns this preflight. Complete it before writing repository files or launching a writer, including tests and documentation. Read-only work and issue-only work that changes no repository files do not need a worktree. Publishing an issue still needs its own authorization.
|
|
4
|
+
|
|
5
|
+
1. Confirm the target repository and authoritative remote. Do not assume `main`, `master`, or even `origin` if the repository uses another upstream. Through the host's authorized Git workflow, inspect `git ls-remote --symref <remote> HEAD`, fetch the reported default branch, verify the matching remote-tracking ref, and record its commit SHA. If the default branch or its fetched commit cannot be established, stop before writing.
|
|
6
|
+
2. When the task implements a canonical issue, [claim the issue](issue-claim.md) before this step and name the branch `feat/<issue-number>-<slug>`, so another person's work on the same issue is visible on the remote. Give each independent task a dedicated linked Git worktree and a unique `feat/<task>` branch from that SHA, using `git worktree add -b <branch> <approved-path> <base-sha>`. Reuse an existing worktree only if it is assigned to the same task, uses its dedicated feature branch, and its recorded base and ownership can be verified. Never reset, overwrite, or switch another task's checkout. Before editing, verify the target worktree and branch from that directory; register the worktree if the host supports registration.
|
|
7
|
+
3. For parallel writers, assign each writer a separate worktree and feature branch, with explicit ownership and non-overlapping edit scope. Sequence changes that need the same contract or module. Share the task reference, worktree path, branch, base SHA, and verification commands; do not share credentials.
|
|
8
|
+
4. Isolate execution as well as files. Use separate test databases or schemas, ports, and output directories where applicable. A worktree shares Git metadata and does not isolate filesystem access, credentials, or network. Use host-enforced isolation (such as a sandbox, container, or VM) with least privilege and no production access. If required isolation cannot be verified, stop the affected write or test; do not fall back to the primary checkout or shared production resources.
|
|
9
|
+
5. Report the resulting branch, worktree, and verification. Rerun affected checks after authorized integration. Push, PR creation, merge, deployment, and worktree cleanup remain separate actions under host policy. Remove a worktree only with authorization, after checking for pending changes and active processes.
|
|
10
|
+
|
|
11
|
+
## Automated pre-edit guard
|
|
12
|
+
|
|
13
|
+
Verify linked `feat/<task>` isolation deterministically with `scripts/check-worktree-guard.py` before writing files, or wire it into a client pre-tool hook (`--stdin --format claude-hook|cursor-hook|codex-hook`) so edits targeting the primary checkout or non-`feat/` branches are blocked automatically:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
python3 -I -B skills/delivery-coordinator/scripts/check-worktree-guard.py --path .
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Reference: [Git worktree](https://git-scm.com/docs/git-worktree) and [Git ls-remote](https://git-scm.com/docs/git-ls-remote).
|
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""check-issue-claim.py: decide whether one person may work on a canonical GitHub issue.
|
|
3
|
+
|
|
4
|
+
Read-only and offline: it evaluates GitHub REST (or `gh --json`) output and `git ls-remote`
|
|
5
|
+
output that the caller fetched through Tool Depot, and never calls GitHub itself.
|
|
6
|
+
Rules CL1-CL12 are defined in references/issue-claim.md.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from datetime import datetime, timedelta, timezone
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
import sys
|
|
13
|
+
|
|
14
|
+
PHASES = ('check', 'verify', 'release', 'status')
|
|
15
|
+
DEFAULT_LABEL = 'status:in-progress'
|
|
16
|
+
DEFAULT_STALE_DAYS = 7
|
|
17
|
+
BRANCH = re.compile(r'feat/(\d+)-[a-z0-9][a-z0-9._-]*')
|
|
18
|
+
REFERENCE = re.compile(r'(?:\b([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+))?#(\d+)\b')
|
|
19
|
+
ISSUE_URL = re.compile(r'github\.com/([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)/issues/(\d+)\b')
|
|
20
|
+
HEAD_REF = re.compile(r'refs/heads/(\S+)')
|
|
21
|
+
|
|
22
|
+
# Most severe first: the first verdict found here is the reported one.
|
|
23
|
+
STOP_VERDICTS = ('closed', 'claimed-by-other', 'contended-lost', 'orphan-claim', 'invalid-branch',
|
|
24
|
+
'unrecorded-claim', 'still-held', 'duplicate-work', 'stale-claim')
|
|
25
|
+
|
|
26
|
+
HELP = (
|
|
27
|
+
'Usage: python3 -I -B scripts/check-issue-claim.py --phase check|verify|release|status\n'
|
|
28
|
+
' --issue-json <file> gh api repos/<o>/<r>/issues/<n> (or gh issue view <n> --json ...)\n'
|
|
29
|
+
' --pulls-json <file> gh api --paginate --slurp "repos/<o>/<r>/pulls?state=open&per_page=100"\n'
|
|
30
|
+
' --branches <file> git ls-remote --heads <remote> "feat/<n>-*"\n'
|
|
31
|
+
' --events-json <file> gh api --paginate --slurp repos/<o>/<r>/issues/<n>/events (verify)\n'
|
|
32
|
+
' --claimant <login> GitHub login of the person (check, verify, release)\n'
|
|
33
|
+
' --branch <feat/<n>-<slug>> the branch this delivery will use (check, verify)\n'
|
|
34
|
+
' [--repo <owner/repo>] [--label status:in-progress] [--stale-days 7] [--now <ISO-8601>]\n'
|
|
35
|
+
'Exit 0: proceed (free, claimed-by-you, released, claimed, unclaimed); 1: stop; 2: unusable.'
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Unusable(Exception):
|
|
40
|
+
"""The inputs cannot be evaluated (rule CL1)."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _write_out(text):
|
|
44
|
+
sys.stdout.buffer.write((text + '\n').encode('utf-8', 'surrogateescape'))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _fold(value):
|
|
48
|
+
return value.casefold() if isinstance(value, str) else ''
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _login(value):
|
|
52
|
+
if isinstance(value, dict):
|
|
53
|
+
value = value.get('login')
|
|
54
|
+
return value if isinstance(value, str) and value.strip() else None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _flatten(value):
|
|
58
|
+
if isinstance(value, list) and all(isinstance(item, list) for item in value):
|
|
59
|
+
return [item for page in value for item in page]
|
|
60
|
+
return value
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _time(value):
|
|
64
|
+
if not isinstance(value, str):
|
|
65
|
+
return None
|
|
66
|
+
try:
|
|
67
|
+
parsed = datetime.fromisoformat(value.strip().replace('Z', '+00:00'))
|
|
68
|
+
except ValueError:
|
|
69
|
+
return None
|
|
70
|
+
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _read(path, label):
|
|
74
|
+
try:
|
|
75
|
+
with open(path, encoding='utf-8') as handle:
|
|
76
|
+
return handle.read()
|
|
77
|
+
except OSError:
|
|
78
|
+
raise Unusable(label + ' cannot be read.')
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _load_json(path, label):
|
|
82
|
+
try:
|
|
83
|
+
return json.loads(_read(path, label))
|
|
84
|
+
except ValueError:
|
|
85
|
+
raise Unusable(label + ' is not valid JSON.')
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def load_issue(path):
|
|
89
|
+
raw = _load_json(path, 'Issue JSON')
|
|
90
|
+
if not isinstance(raw, dict) or not isinstance(raw.get('state'), str):
|
|
91
|
+
raise Unusable('Issue JSON needs a state.')
|
|
92
|
+
number = raw.get('number')
|
|
93
|
+
if not isinstance(number, int):
|
|
94
|
+
raise Unusable('Issue JSON needs a numeric number.')
|
|
95
|
+
labels = []
|
|
96
|
+
for label in raw.get('labels') or []:
|
|
97
|
+
name = label.get('name') if isinstance(label, dict) else label
|
|
98
|
+
if isinstance(name, str):
|
|
99
|
+
labels.append(name)
|
|
100
|
+
return {
|
|
101
|
+
'number': number,
|
|
102
|
+
'author': _login(raw.get('user')) or _login(raw.get('author')),
|
|
103
|
+
'open': raw['state'].lower() == 'open',
|
|
104
|
+
'assignees': [login for login in map(_login, raw.get('assignees') or []) if login],
|
|
105
|
+
'labels': labels,
|
|
106
|
+
'updated': _time(raw.get('updated_at') or raw.get('updatedAt')),
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def load_pulls(path):
|
|
111
|
+
raw = _flatten(_load_json(path, 'Pull request JSON'))
|
|
112
|
+
if not isinstance(raw, list):
|
|
113
|
+
raise Unusable('Pull request JSON must be an array.')
|
|
114
|
+
pulls = []
|
|
115
|
+
for item in raw:
|
|
116
|
+
if not isinstance(item, dict):
|
|
117
|
+
continue
|
|
118
|
+
head = item.get('head')
|
|
119
|
+
pulls.append({
|
|
120
|
+
'number': item.get('number'),
|
|
121
|
+
'author': _login(item.get('user')) or _login(item.get('author')),
|
|
122
|
+
'head': (head.get('ref') if isinstance(head, dict) else None) or item.get('headRefName') or '',
|
|
123
|
+
'text': (item.get('title') or '') + '\n' + (item.get('body') or ''),
|
|
124
|
+
})
|
|
125
|
+
return pulls
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def load_branches(path):
|
|
129
|
+
names = []
|
|
130
|
+
for line in _read(path, 'Branch list').splitlines():
|
|
131
|
+
match = HEAD_REF.search(line)
|
|
132
|
+
name = match.group(1) if match else line.strip()
|
|
133
|
+
if name:
|
|
134
|
+
names.append(name)
|
|
135
|
+
return names
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def load_events(path):
|
|
139
|
+
raw = _flatten(_load_json(path, 'Issue events JSON'))
|
|
140
|
+
if not isinstance(raw, list):
|
|
141
|
+
raise Unusable('Issue events JSON must be an array.')
|
|
142
|
+
return [item for item in raw if isinstance(item, dict)]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def mentions(text, number, repo):
|
|
146
|
+
for match in list(REFERENCE.finditer(text)) + list(ISSUE_URL.finditer(text)):
|
|
147
|
+
if int(match.group(2)) != number:
|
|
148
|
+
continue
|
|
149
|
+
if match.group(1) is None or repo is None or _fold(match.group(1)) == _fold(repo):
|
|
150
|
+
return True
|
|
151
|
+
return False
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def issue_branch(name, number):
|
|
155
|
+
match = BRANCH.fullmatch(name or '')
|
|
156
|
+
return match is not None and int(match.group(1)) == number
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def current_assignments(events):
|
|
160
|
+
"""Login (folded) -> time of the assignment that is still in effect."""
|
|
161
|
+
timed = [(_time(e.get('created_at') or e.get('createdAt')), e) for e in events
|
|
162
|
+
if e.get('event') in ('assigned', 'unassigned')]
|
|
163
|
+
timed = sorted((pair for pair in timed if pair[0] is not None), key=lambda pair: pair[0])
|
|
164
|
+
since = {}
|
|
165
|
+
for at, event in timed:
|
|
166
|
+
who = _fold(_login(event.get('assignee')))
|
|
167
|
+
if event['event'] == 'assigned':
|
|
168
|
+
since[who] = at
|
|
169
|
+
else:
|
|
170
|
+
since.pop(who, None)
|
|
171
|
+
return since
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def label_setter(events, label):
|
|
175
|
+
"""(login folded, time) of whoever set the claim label still in effect, or None."""
|
|
176
|
+
timed = [(_time(e.get('created_at') or e.get('createdAt')), e) for e in events
|
|
177
|
+
if e.get('event') in ('labeled', 'unlabeled') and isinstance(e.get('label'), dict)
|
|
178
|
+
and e['label'].get('name') == label]
|
|
179
|
+
setter = None
|
|
180
|
+
for at, event in sorted((pair for pair in timed if pair[0] is not None), key=lambda pair: pair[0]):
|
|
181
|
+
setter = (_fold(_login(event.get('actor'))), at) if event['event'] == 'labeled' else None
|
|
182
|
+
return setter
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def claim_times(issue, events, label):
|
|
186
|
+
"""Login (folded) -> when each assignee's claim took effect; None for a reporter who is not claiming.
|
|
187
|
+
|
|
188
|
+
The issue author's assignment (issue-reviewer triage) becomes a claim only once the author
|
|
189
|
+
set the claim label, and dates from that moment.
|
|
190
|
+
"""
|
|
191
|
+
since = current_assignments(events)
|
|
192
|
+
missing = [login for login in issue['assignees'] if _fold(login) not in since]
|
|
193
|
+
if missing:
|
|
194
|
+
raise Unusable('No assignment event for: ' + ', '.join(missing) + '.')
|
|
195
|
+
setter = label_setter(events, label)
|
|
196
|
+
times = {}
|
|
197
|
+
for login in issue['assignees']:
|
|
198
|
+
who = _fold(login)
|
|
199
|
+
if who != _fold(issue['author']):
|
|
200
|
+
times[who] = since[who]
|
|
201
|
+
elif setter is not None and setter[0] == who:
|
|
202
|
+
times[who] = max(since[who], setter[1])
|
|
203
|
+
else:
|
|
204
|
+
times[who] = None
|
|
205
|
+
return times
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class Report:
|
|
209
|
+
def __init__(self):
|
|
210
|
+
self.findings = []
|
|
211
|
+
|
|
212
|
+
def add(self, rule, verdict, detail, who=None):
|
|
213
|
+
finding = {'rule': rule, 'verdict': verdict, 'detail': detail}
|
|
214
|
+
if who:
|
|
215
|
+
finding['who'] = who
|
|
216
|
+
self.findings.append(finding)
|
|
217
|
+
|
|
218
|
+
def verdict(self, default):
|
|
219
|
+
found = {finding['verdict'] for finding in self.findings}
|
|
220
|
+
return next((verdict for verdict in STOP_VERDICTS if verdict in found), default)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def evaluate(phase, issue, pulls, branches, events, options):
|
|
224
|
+
report = Report()
|
|
225
|
+
number, label = issue['number'], options['label']
|
|
226
|
+
me = _fold(options['claimant'])
|
|
227
|
+
has_label = label in issue['labels']
|
|
228
|
+
others = [login for login in issue['assignees'] if _fold(login) != me]
|
|
229
|
+
mine = len(others) < len(issue['assignees'])
|
|
230
|
+
reporter = _fold(issue['author'])
|
|
231
|
+
# Without the claim label, the author's own assignment comes from triage and holds nothing.
|
|
232
|
+
claimers = [login for login in others if _fold(login) != reporter] or (others if has_label else [])
|
|
233
|
+
holding = [login for login in issue['assignees'] if _fold(login) != reporter] or (
|
|
234
|
+
issue['assignees'] if has_label else [])
|
|
235
|
+
linked = [pull for pull in pulls if mentions(pull['text'], number, options['repo']) or issue_branch(pull['head'], number)]
|
|
236
|
+
other_pulls = [pull for pull in linked if _fold(pull['author']) != me]
|
|
237
|
+
claim_branches = [name for name in branches if issue_branch(name, number)]
|
|
238
|
+
holders = {'assignees': issue['assignees'], 'reporter': issue['author'], 'label': has_label,
|
|
239
|
+
'pulls': [{'number': p['number'], 'author': p['author']} for p in linked], 'branches': claim_branches}
|
|
240
|
+
|
|
241
|
+
if phase == 'release':
|
|
242
|
+
if mine:
|
|
243
|
+
report.add('CL10', 'still-held', 'The claimant is still assigned.')
|
|
244
|
+
kept = [login for login in others if _fold(login) != reporter]
|
|
245
|
+
if has_label and not kept and others:
|
|
246
|
+
if events is None:
|
|
247
|
+
raise Unusable('The issue author is still assigned: --events-json is needed to tell '
|
|
248
|
+
'whether the claim label is theirs.')
|
|
249
|
+
times = claim_times(issue, events, label)
|
|
250
|
+
kept = [login for login in others if times[_fold(login)] is not None]
|
|
251
|
+
if has_label and not kept:
|
|
252
|
+
report.add('CL10', 'still-held', 'The claim label is still set and no one else holds the issue.')
|
|
253
|
+
return report.verdict('released'), report, holders
|
|
254
|
+
|
|
255
|
+
if phase == 'status':
|
|
256
|
+
if len(linked) > 1:
|
|
257
|
+
report.add('CL11', 'duplicate-work', 'More than one open pull request works on this issue.',
|
|
258
|
+
['#' + str(p['number']) for p in linked])
|
|
259
|
+
if has_label and not issue['assignees']:
|
|
260
|
+
report.add('CL6', 'orphan-claim', 'The claim label is set but nobody is assigned.')
|
|
261
|
+
held = bool(holding) or has_label
|
|
262
|
+
if held and not linked and not claim_branches:
|
|
263
|
+
if issue['updated'] is None:
|
|
264
|
+
raise Unusable('Issue JSON needs updated_at to judge a stale claim.')
|
|
265
|
+
if options['now'] - issue['updated'] > timedelta(days=options['stale_days']):
|
|
266
|
+
report.add('CL12', 'stale-claim', 'Claimed with no open pull request, no feat/<n>- branch and no '
|
|
267
|
+
'activity for more than ' + str(options['stale_days']) + ' days.', holding)
|
|
268
|
+
claimed = held or bool(linked) or bool(claim_branches)
|
|
269
|
+
return report.verdict('claimed' if claimed else 'unclaimed'), report, holders
|
|
270
|
+
|
|
271
|
+
branch = options['branch']
|
|
272
|
+
if not issue_branch(branch, number):
|
|
273
|
+
report.add('CL7', 'invalid-branch', 'The delivery branch must be feat/' + str(number) + '-<slug>.')
|
|
274
|
+
if not issue['open']:
|
|
275
|
+
report.add('CL2', 'closed', 'The issue is closed; reopen it through issue-dedup before claiming.')
|
|
276
|
+
if other_pulls:
|
|
277
|
+
report.add('CL4', 'claimed-by-other', 'An open pull request by someone else works on this issue.',
|
|
278
|
+
['#' + str(p['number']) + ' @' + str(p['author']) for p in other_pulls])
|
|
279
|
+
foreign = [name for name in claim_branches if name != branch]
|
|
280
|
+
if foreign:
|
|
281
|
+
report.add('CL5', 'claimed-by-other', 'Another feat/' + str(number) + '- branch exists on the remote.', foreign)
|
|
282
|
+
|
|
283
|
+
if phase == 'check':
|
|
284
|
+
if claimers:
|
|
285
|
+
report.add('CL3', 'claimed-by-other', 'The issue is assigned to someone else.', claimers)
|
|
286
|
+
if has_label and not issue['assignees']:
|
|
287
|
+
report.add('CL6', 'orphan-claim', 'The claim label is set but nobody is assigned.')
|
|
288
|
+
yours = mine or any(_fold(p['author']) == me for p in linked)
|
|
289
|
+
return report.verdict('claimed-by-you' if yours else 'free'), report, holders
|
|
290
|
+
|
|
291
|
+
if not mine or not has_label:
|
|
292
|
+
report.add('CL8', 'unrecorded-claim', 'After claiming, the claimant must be assigned and the label set.')
|
|
293
|
+
if mine and others:
|
|
294
|
+
if events is None:
|
|
295
|
+
raise Unusable('Several assignees: --events-json is needed to order the assignments.')
|
|
296
|
+
times = claim_times(issue, events, label)
|
|
297
|
+
claiming = [login for login in issue['assignees'] if times[_fold(login)] is not None]
|
|
298
|
+
winner = min(claiming, key=lambda login: (times[_fold(login)], _fold(login))) if claiming else None
|
|
299
|
+
if _fold(winner) != me:
|
|
300
|
+
report.add('CL9', 'contended-lost', 'Someone else was assigned first; unassign yourself and remove nothing else.',
|
|
301
|
+
[winner])
|
|
302
|
+
return report.verdict('claimed-by-you'), report, holders
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def parse_args(argv):
|
|
306
|
+
options = {'phase': None, 'issue': None, 'pulls': None, 'branches': None, 'events': None, 'claimant': None,
|
|
307
|
+
'branch': None, 'repo': None, 'label': DEFAULT_LABEL, 'stale_days': DEFAULT_STALE_DAYS, 'now': None}
|
|
308
|
+
keys = {'--phase': 'phase', '--issue-json': 'issue', '--pulls-json': 'pulls', '--branches': 'branches',
|
|
309
|
+
'--events-json': 'events', '--claimant': 'claimant', '--branch': 'branch', '--repo': 'repo',
|
|
310
|
+
'--label': 'label', '--stale-days': 'stale_days', '--now': 'now'}
|
|
311
|
+
args = list(argv)
|
|
312
|
+
while args:
|
|
313
|
+
arg = args.pop(0)
|
|
314
|
+
if arg in ('-h', '--help'):
|
|
315
|
+
return None
|
|
316
|
+
if arg not in keys or not args:
|
|
317
|
+
raise Unusable('Unexpected argument ' + arg + '; see --help.')
|
|
318
|
+
options[keys[arg]] = args.pop(0)
|
|
319
|
+
if options['phase'] not in PHASES:
|
|
320
|
+
raise Unusable('--phase must be one of: ' + ', '.join(PHASES) + '.')
|
|
321
|
+
if options['issue'] is None:
|
|
322
|
+
raise Unusable('--issue-json is required.')
|
|
323
|
+
if options['phase'] != 'release' and (options['pulls'] is None or options['branches'] is None):
|
|
324
|
+
raise Unusable('--pulls-json and --branches are required for ' + options['phase'] + '.')
|
|
325
|
+
if options['phase'] != 'status' and not options['claimant']:
|
|
326
|
+
raise Unusable('--claimant is required for ' + options['phase'] + '.')
|
|
327
|
+
if options['phase'] in ('check', 'verify') and not options['branch']:
|
|
328
|
+
raise Unusable('--branch is required for ' + options['phase'] + '.')
|
|
329
|
+
try:
|
|
330
|
+
options['stale_days'] = int(options['stale_days'])
|
|
331
|
+
except ValueError:
|
|
332
|
+
raise Unusable('--stale-days must be an integer.')
|
|
333
|
+
now = _time(options['now']) if options['now'] else datetime.now(timezone.utc)
|
|
334
|
+
if now is None:
|
|
335
|
+
raise Unusable('--now must be an ISO-8601 time.')
|
|
336
|
+
options['now'] = now
|
|
337
|
+
return options
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def main(argv):
|
|
341
|
+
try:
|
|
342
|
+
options = parse_args(argv)
|
|
343
|
+
if options is None:
|
|
344
|
+
_write_out(HELP)
|
|
345
|
+
return 0
|
|
346
|
+
phase = options['phase']
|
|
347
|
+
issue = load_issue(options['issue'])
|
|
348
|
+
pulls = load_pulls(options['pulls']) if options['pulls'] else []
|
|
349
|
+
branches = load_branches(options['branches']) if options['branches'] else []
|
|
350
|
+
events = load_events(options['events']) if options['events'] else None
|
|
351
|
+
verdict, report, holders = evaluate(phase, issue, pulls, branches, events, options)
|
|
352
|
+
except Unusable as error:
|
|
353
|
+
_write_out(json.dumps({'verdict': 'unusable', 'proceed': False,
|
|
354
|
+
'findings': [{'rule': 'CL1', 'verdict': 'unusable', 'detail': str(error)}]}, indent=2))
|
|
355
|
+
return 2
|
|
356
|
+
proceed = verdict not in STOP_VERDICTS
|
|
357
|
+
_write_out(json.dumps({'verdict': verdict, 'proceed': proceed, 'phase': phase, 'issue': issue['number'],
|
|
358
|
+
'claimant': options['claimant'], 'holders': holders, 'findings': report.findings}, indent=2))
|
|
359
|
+
return 0 if proceed else 1
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
if __name__ == '__main__':
|
|
363
|
+
sys.exit(main(sys.argv[1:]))
|