@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.
@@ -1,231 +0,0 @@
1
- #!/usr/bin/env python3
2
- """sweep.py: the two steps of /issue-clean-and-close for the repository it runs in.
3
-
4
- `plan` reads the repository (sweep-github.py fetch), decides with sweep-issues.py, and
5
- prints the plan for the person's Boss Gate; it writes nothing to GitHub. `apply` performs
6
- exactly that plan file (or only the issues the person approved, `--only`), and refuses a
7
- plan older than 60 minutes or for another repository. Every step keeps its evidence and
8
- one log line under ~/.issue-clean-and-close/<owner>__<repo>/. Policy: references/policy.md.
9
- """
10
-
11
- from datetime import datetime, timedelta, timezone
12
- import json
13
- import os
14
- from pathlib import Path
15
- import re
16
- import shutil
17
- import subprocess
18
- import sys
19
-
20
- HERE = Path(__file__).resolve().parent
21
- CONFIG_PATH = '.github/issue-sweeper.json'
22
- DEFAULT_KEEP = 30
23
- PLAN_TTL = timedelta(minutes=60)
24
- REPO = re.compile(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+')
25
- REMOTE = re.compile(r'github\.com[:/]([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+?)(?:\.git)?/?$')
26
-
27
- HELP = (
28
- 'Usage: python3 -I -B scripts/sweep.py plan [--repo <owner/repo>] [--keep 30]\n'
29
- ' python3 -I -B scripts/sweep.py apply [--repo <owner/repo>] --plan <file> [--only 12,15] [--dry-run]\n'
30
- 'Without --repo, the repository is the current checkout\'s origin on github.com.\n'
31
- f'Needs an authenticated gh CLI. {CONFIG_PATH} on the default branch is optional (thresholds).\n'
32
- 'State: ~/.issue-clean-and-close/<owner>__<repo>/ (SWEEP_HOME overrides it).\n'
33
- 'Exit 0: done; 1: some writes failed (listed); 2: unusable input, plan, or policy file.'
34
- )
35
-
36
-
37
- class Unusable(Exception):
38
- """The arguments, the plan, or the policy file cannot be used."""
39
-
40
-
41
- def _write_out(text):
42
- sys.stdout.buffer.write((text + '\n').encode('utf-8', 'surrogateescape'))
43
-
44
-
45
- def _now():
46
- return datetime.now(timezone.utc)
47
-
48
-
49
- def _run(argv):
50
- try:
51
- result = subprocess.run(argv, capture_output=True, text=True, encoding='utf-8')
52
- except OSError as error:
53
- raise Unusable(argv[0] + ' is not available: ' + str(error))
54
- return result.returncode, result.stdout, result.stderr.strip()[:500]
55
-
56
-
57
- def _gh(args):
58
- value = os.environ.get('SWEEP_GH', '').strip()
59
- command = json.loads(value) if value.startswith('[') else [value or 'gh']
60
- return _run(command + args)
61
-
62
-
63
- def detect_repo():
64
- code, out, _ = _run(['git', 'remote', 'get-url', 'origin'])
65
- match = REMOTE.search(out.strip()) if code == 0 else None
66
- if match is None:
67
- raise Unusable('This is not a checkout with a github.com origin; pass --repo <owner/repo>.')
68
- return match.group(1)
69
-
70
-
71
- def state_dir(repo):
72
- home = os.environ.get('SWEEP_HOME') or str(Path.home() / '.issue-clean-and-close')
73
- path = Path(home) / repo.replace('/', '__')
74
- path.mkdir(parents=True, exist_ok=True)
75
- return path
76
-
77
-
78
- def _log(state, entry):
79
- with open(state / 'runs.log', 'a', encoding='utf-8') as handle:
80
- handle.write(json.dumps(dict(entry, at=_now().strftime('%Y-%m-%dT%H:%M:%SZ')), ensure_ascii=False) + '\n')
81
-
82
-
83
- def current_login():
84
- code, out, err = _gh(['api', 'user', '--jq', '.login'])
85
- if code != 0 or not out.strip():
86
- raise Unusable('gh is not authenticated: ' + err)
87
- return out.strip()
88
-
89
-
90
- def fetch_policy(repo, state):
91
- """The repository's optional policy file from the default branch; None means defaults."""
92
- code, out, err = _gh(['api', '-H', 'Accept: application/vnd.github.raw+json',
93
- 'repos/' + repo + '/contents/' + CONFIG_PATH])
94
- if code != 0:
95
- if '404' in err or 'not found' in err.casefold():
96
- return None
97
- raise Unusable('Cannot read ' + CONFIG_PATH + ': ' + err)
98
- try:
99
- policy = json.loads(out)
100
- except ValueError:
101
- raise Unusable(CONFIG_PATH + ' on the default branch is not valid JSON.')
102
- path = state / 'config.json'
103
- path.write_text(json.dumps(policy, ensure_ascii=False, indent=2), encoding='utf-8')
104
- return path
105
-
106
-
107
- def _script(name, argv):
108
- return _run([sys.executable, '-I', '-B', str(HERE / name), *argv])
109
-
110
-
111
- def _summary(entry):
112
- steps = [step['action'] + (':' + step['label'] if step.get('label') else '')
113
- + (':' + step['state_reason'] if step.get('state_reason') else '') for step in entry.get('steps') or []]
114
- return {'issue': entry['issue'], 'rule': entry['rule'], 'url': entry.get('url'), 'steps': steps}
115
-
116
-
117
- def plan(repo, keep):
118
- state = state_dir(repo)
119
- login = current_login()
120
- config = fetch_policy(repo, state)
121
- snapshot = state / 'snapshot.json'
122
- code, out, err = _script('sweep-github.py', ['fetch', '--repo', repo, '--out', str(snapshot),
123
- '--sweeper-login', login])
124
- if code == 0:
125
- args = ['--snapshot', str(snapshot), '--sweeper-login', login] + (['--config', str(config)] if config else [])
126
- code, out, err = _script('sweep-issues.py', args)
127
- if code != 0:
128
- reason = (out.strip() or err)[:500]
129
- _log(state, {'step': 'plan', 'repo': repo, 'verdict': 'unusable', 'reason': reason})
130
- raise Unusable('No plan: ' + reason)
131
- plans = state / 'plans'
132
- plans.mkdir(exist_ok=True)
133
- path = plans / (_now().strftime('%Y%m%dT%H%M%S%fZ') + '.json')
134
- path.write_text(out, encoding='utf-8')
135
- for old in sorted(plans.glob('*.json'))[:-keep]:
136
- old.unlink()
137
- result = json.loads(out)
138
- (state / 'report.md').write_text(result['report_markdown'] + '\n', encoding='utf-8')
139
- _log(state, {'step': 'plan', 'repo': repo, 'run_by': login, 'plan': path.name, 'actions': len(result['actions']),
140
- 'deferred': len(result['deferred']), 'gaps': len(result['gaps'])})
141
- return {'verdict': 'planned', 'repo': repo, 'run_by': login, 'plan': str(path),
142
- 'config': CONFIG_PATH if config else 'defaults', 'report_issue': result.get('report_issue'),
143
- 'actions': [_summary(entry) for entry in result['actions']],
144
- 'deferred': [entry['issue'] for entry in result['deferred']],
145
- 'report_only': [{'issue': entry['issue'], 'rule': entry['rule']} for entry in result['report_only']],
146
- 'gaps': result['gaps'], 'metrics': result['metrics'], 'report_markdown': result['report_markdown']}, 0
147
-
148
-
149
- def _check_plan(path, repo):
150
- try:
151
- data = json.loads(Path(path).read_text(encoding='utf-8'))
152
- except (OSError, ValueError):
153
- raise Unusable('The plan file cannot be read as JSON.')
154
- generated = data.get('generated_at') if isinstance(data, dict) else None
155
- try:
156
- age = _now() - datetime.fromisoformat(str(generated).replace('Z', '+00:00'))
157
- except ValueError:
158
- raise Unusable('The plan has no generated_at; run plan again.')
159
- if age > PLAN_TTL:
160
- raise Unusable('The plan is older than 60 minutes; run plan again and approve the new one.')
161
- if str(data.get('repo')).casefold() != repo.casefold():
162
- raise Unusable('The plan is for ' + str(data.get('repo')) + ', not ' + repo + '.')
163
-
164
-
165
- def apply(repo, plan_path, only, dry_run):
166
- state = state_dir(repo)
167
- _check_plan(plan_path, repo)
168
- argv = ['apply', '--repo', repo, '--plan', str(plan_path)] + (['--only', only] if only else []) + (
169
- ['--dry-run'] if dry_run else [])
170
- code, out, err = _script('sweep-github.py', argv)
171
- try:
172
- result = json.loads(out)
173
- except ValueError:
174
- raise Unusable('apply printed no JSON: ' + err)
175
- if code == 2:
176
- raise Unusable(result.get('reason', err))
177
- numbers = sorted(int(item.strip().lstrip('#')) for item in only.split(',') if item.strip()) if only else None
178
- _log(state, {'step': 'apply', 'repo': repo, 'plan': Path(plan_path).name, 'only': numbers, 'dry_run': dry_run,
179
- 'applied': len(result.get('applied') or result.get('writes') or []),
180
- 'errors': result.get('errors') or []})
181
- return result, code
182
-
183
-
184
- def parse_args(argv):
185
- if not argv or argv[0] in ('--help', '-h') or '--help' in argv:
186
- return None
187
- command, rest = argv[0], argv[1:]
188
- if command not in ('plan', 'apply'):
189
- raise Unusable('Unknown command: ' + command + ' (plan or apply).')
190
- values = {'plan': ('--repo', '--keep'), 'apply': ('--repo', '--plan', '--only')}[command]
191
- args = {'command': command, 'keep': str(DEFAULT_KEEP), 'dry-run': False}
192
- index = 0
193
- while index < len(rest):
194
- key = rest[index]
195
- if key == '--dry-run' and command == 'apply':
196
- args['dry-run'] = True
197
- index += 1
198
- elif key in values and index + 1 < len(rest):
199
- args[key[2:]] = rest[index + 1]
200
- index += 2
201
- else:
202
- raise Unusable('Unknown or incomplete argument for ' + command + ': ' + key)
203
- if 'repo' in args and not REPO.fullmatch(args['repo']):
204
- raise Unusable('--repo must be owner/name.')
205
- if not args['keep'].isdigit() or int(args['keep']) < 1:
206
- raise Unusable('--keep must be a positive integer.')
207
- if command == 'apply' and 'plan' not in args:
208
- raise Unusable('apply needs --plan: the exact plan file the person approved.')
209
- return args
210
-
211
-
212
- def main(argv):
213
- try:
214
- args = parse_args(argv)
215
- if args is None:
216
- _write_out(HELP)
217
- return 0
218
- repo = args.get('repo') or detect_repo()
219
- if args['command'] == 'plan':
220
- result, code = plan(repo, int(args['keep']))
221
- else:
222
- result, code = apply(repo, args['plan'], args.get('only'), args['dry-run'])
223
- except Unusable as error:
224
- _write_out(json.dumps({'verdict': 'unusable', 'reason': str(error)}, ensure_ascii=False))
225
- return 2
226
- _write_out(json.dumps(result, ensure_ascii=False, indent=2))
227
- return code
228
-
229
-
230
- if __name__ == '__main__':
231
- sys.exit(main(sys.argv[1:]))
@@ -1,156 +0,0 @@
1
- #!/usr/bin/env bash
2
- set -euo pipefail
3
- cd -- "${BASH_SOURCE[0]%/*}/.."
4
- PYTHON_BIN=$(command -v python3 || command -v python)
5
- "$PYTHON_BIN" -I -B - <<'PY'
6
- import importlib.util
7
- import json
8
- from pathlib import Path
9
- import subprocess
10
- import sys
11
- import tempfile
12
-
13
- path = Path('scripts/sweep-github.py')
14
- if not path.is_file():
15
- sys.exit('FAIL: missing script ' + str(path))
16
- spec = importlib.util.spec_from_file_location('sweep_github', path)
17
- mod = importlib.util.module_from_spec(spec)
18
- spec.loader.exec_module(mod)
19
- checks = 0
20
- failures = []
21
-
22
-
23
- def check(label, condition, detail=''):
24
- global checks
25
- checks += 1
26
- if not condition:
27
- failures.append(label + ' ' + str(detail)[:500])
28
-
29
-
30
- def pr_node(number, state='MERGED', body='', title='Change', repo='example/repo', merged='2026-11-20T10:00:00Z'):
31
- return {'number': number, 'url': 'https://github.com/' + repo + '/pull/' + str(number), 'state': state,
32
- 'mergedAt': merged if state == 'MERGED' else None, 'title': title, 'body': body,
33
- 'repository': {'nameWithOwner': repo}, 'mergeCommit': {'oid': 'abcdef1234567890'} if state == 'MERGED' else None}
34
-
35
-
36
- def issue_node(number, refs=(), recent=(), labels=(), assignees=(), body='', refs_more=False, author='carla'):
37
- return {'number': number, 'title': 'T' + str(number), 'url': 'https://github.com/example/repo/issues/' + str(number),
38
- 'createdAt': '2026-10-01T10:00:00Z', 'body': body, 'author': {'login': author},
39
- 'labels': {'nodes': [{'name': n} for n in labels]}, 'assignees': {'nodes': [{'login': a} for a in assignees]},
40
- 'refs': {'pageInfo': {'hasNextPage': refs_more}, 'nodes': list(refs)},
41
- 'recent': {'pageInfo': {'hasPreviousPage': False}, 'nodes': list(recent)}}
42
-
43
-
44
- page = {'data': {'repository': {
45
- 'nameWithOwner': 'example/repo',
46
- 'labels': {'nodes': [{'name': 'stale'}, {'name': 'bug'}]},
47
- 'issues': {'pageInfo': {'hasNextPage': False, 'endCursor': None}, 'nodes': [
48
- issue_node(12, labels=['bug'], assignees=['ana'], refs=[
49
- {'__typename': 'CrossReferencedEvent', 'createdAt': '2026-11-19T10:00:00Z', 'willCloseTarget': True,
50
- 'source': pr_node(20, body='Closes #12\n' + ('x' * 90 + '\n') * 100 + 'Also fixes #14')},
51
- {'__typename': 'ConnectedEvent', 'createdAt': '2026-11-19T11:00:00Z', 'subject': pr_node(20)},
52
- {'__typename': 'CrossReferencedEvent', 'createdAt': '2026-11-02T10:00:00Z', 'willCloseTarget': False,
53
- 'source': {'number': 7, 'url': 'https://github.com/example/repo/issues/7'}},
54
- ], recent=[
55
- {'__typename': 'IssueComment', 'createdAt': '2026-11-21T10:00:00Z', 'author': {'login': 'github-actions'},
56
- 'body': 'Hola\n<!-- issue-sweeper:SW2 -->'},
57
- {'__typename': 'IssueComment', 'createdAt': '2026-11-22T10:00:00Z', 'author': None, 'body': 'ghost'},
58
- {'__typename': 'LabeledEvent', 'createdAt': '2026-11-10T10:00:00Z', 'actor': {'login': 'dev'},
59
- 'label': {'name': 'needs-info'}},
60
- {'__typename': 'ReopenedEvent', 'createdAt': '2026-11-23T10:00:00Z', 'actor': {'login': 'dev'}},
61
- ]),
62
- issue_node(13, refs=[
63
- {'__typename': 'ConnectedEvent', 'createdAt': '2026-11-01T10:00:00Z', 'subject': pr_node(30, state='OPEN')},
64
- {'__typename': 'DisconnectedEvent', 'createdAt': '2026-11-02T10:00:00Z', 'subject': pr_node(30, state='OPEN')},
65
- ], refs_more=True),
66
- issue_node(98, body='copied marker <!-- issue-sweeper:report -->'),
67
- issue_node(99, body='report\n<!-- issue-sweeper:report -->', author='github-actions'),
68
- ]}}}}
69
-
70
- snapshot = mod.to_snapshot([page], '2026-11-30T12:00:00Z')
71
- issues = {i['number']: i for i in snapshot['issues']}
72
- check('report issue is excluded and remembered', 99 not in issues and snapshot.get('report_issue') == 99, snapshot)
73
- check('a marker copied by someone else does not make a report issue', 98 in issues, sorted(issues))
74
- check('repository labels', snapshot.get('labels') == ['stale', 'bug'], snapshot.get('labels'))
75
- one = issues.get(12, {})
76
- prs = one.get('prs', [])
77
- check('one entry per PR, issues are not PRs', [p['number'] for p in prs] == [20], prs)
78
- first = prs[0] if prs else {}
79
- check('willCloseTarget and manual link merged', first.get('will_close') is True and first.get('manual_link') is True, first)
80
- check('PR text keeps only lines that reference issues, wherever they are',
81
- first.get('text') == 'Change\nCloses #12\nAlso fixes #14', first.get('text'))
82
- check('merged fields', first.get('state') == 'MERGED' and first.get('merge_commit') == 'abcdef1234567890'
83
- and first.get('referenced_at') == '2026-11-19T10:00:00Z' and first.get('repo') == 'example/repo', first)
84
- events = one.get('events', [])
85
- check('comment markers, never bodies', events[0] == {'type': 'comment', 'at': '2026-11-21T10:00:00Z',
86
- 'actor': 'github-actions', 'marker': 'SW2'}, events)
87
- check('deleted author is ghost', events[1]['actor'] == 'ghost' and events[1]['marker'] is None, events)
88
- check('label and reopen events', events[2] == {'type': 'labeled', 'label': 'needs-info', 'at': '2026-11-10T10:00:00Z',
89
- 'actor': 'dev'} and events[3]['type'] == 'reopened', events)
90
- check('no comment or issue body in the snapshot', 'Hola' not in json.dumps(snapshot)
91
- and 'report\\n' not in json.dumps(snapshot), '')
92
- check('labels, assignees, author', one.get('labels') == ['bug'] and one.get('assignees') == ['ana']
93
- and one.get('author') == 'carla', one)
94
- two = issues.get(13, {})
95
- check('a disconnected manual link no longer links', [p['manual_link'] for p in two.get('prs', [])] == [False], two.get('prs'))
96
- check('truncated references mark the issue incomplete', two.get('incomplete') is True and one.get('incomplete') is False, two)
97
-
98
- # apply: commands from the plan
99
- step_comment = {'action': 'comment', 'marker': 'SW1', 'body': 'Cierro <!-- issue-sweeper:SW1 -->'}
100
- plan = {'verdict': 'ok', 'repo': 'example/repo', 'report_issue': 99, 'report_title': 'Estado de issues',
101
- 'report_markdown': 'r <!-- issue-sweeper:report -->',
102
- 'actions': [{'issue': 12, 'rule': 'SW1', 'steps': [step_comment, {'action': 'close', 'state_reason': 'completed'}]},
103
- {'issue': 13, 'rule': 'SW2', 'steps': [{'action': 'add-label', 'label': 'needs close/review'}]},
104
- {'issue': 14, 'rule': 'SW7', 'steps': [{'action': 'remove-label', 'label': 'stale'}]}]}
105
- cmds = mod.issue_commands(plan, 'example/repo')
106
- check('comment then close', cmds[0] == (12, ['api', '-X', 'POST', 'repos/example/repo/issues/12/comments', '-f',
107
- 'body=Cierro <!-- issue-sweeper:SW1 -->'])
108
- and cmds[1] == (12, ['api', '-X', 'PATCH', 'repos/example/repo/issues/12', '-f', 'state=closed',
109
- '-f', 'state_reason=completed']), cmds[:2])
110
- check('labels', cmds[2] == (13, ['api', '-X', 'POST', 'repos/example/repo/issues/13/labels', '-f',
111
- 'labels[]=needs close/review'])
112
- and cmds[3] == (14, ['api', '-X', 'DELETE', 'repos/example/repo/issues/14/labels/stale']), cmds[2:])
113
- check('report update', mod.report_command(plan, 'example/repo') == ['api', '-X', 'PATCH', 'repos/example/repo/issues/99',
114
- '-f', 'body=r <!-- issue-sweeper:report -->'],
115
- mod.report_command(plan, 'example/repo'))
116
- created = dict(plan, report_issue=None)
117
- check('report creation', mod.report_command(created, 'example/repo') == [
118
- 'api', '-X', 'POST', 'repos/example/repo/issues', '-f', 'title=Estado de issues',
119
- '-f', 'body=r <!-- issue-sweeper:report -->'], mod.report_command(created, 'example/repo'))
120
-
121
- scratch = Path(tempfile.mkdtemp())
122
-
123
-
124
- def apply(plan_data, *extra):
125
- plan_path = scratch / 'plan.json'
126
- plan_path.write_text(json.dumps(plan_data), encoding='utf-8')
127
- result = subprocess.run([sys.executable, '-I', '-B', str(path), 'apply', '--repo', 'example/repo', '--plan',
128
- str(plan_path), *extra], capture_output=True, text=True, encoding='utf-8')
129
- try:
130
- return result.returncode, json.loads(result.stdout)
131
- except ValueError:
132
- return result.returncode, {'raw': result.stdout + result.stderr}
133
-
134
-
135
- code, out = apply(plan, '--dry-run')
136
- check('dry-run lists writes without making them', code == 0 and len(out.get('writes', [])) == 5 and out.get('dry_run'), out)
137
- code, out = apply(plan, '--dry-run', '--only', '#12')
138
- check('--only keeps the approved issues and the report', code == 0 and [w['issue'] for w in out.get('writes', [])]
139
- == [12, 12, 'report'], out)
140
- code, out = apply(plan, '--dry-run', '--only', '12,77')
141
- check('--only with an issue outside the plan is refused', code == 2, out)
142
- code, out = apply(plan, '--dry-run', '--only', 'twelve')
143
- check('--only needs numbers', code == 2, out)
144
- code, out = apply(dict(plan, verdict='unusable'), '--dry-run')
145
- check('an unusable plan is refused', code == 2, out)
146
- code, out = apply(dict(plan, repo='other/repo'), '--dry-run')
147
- check('a plan for another repository is refused', code == 2, out)
148
- result = subprocess.run([sys.executable, '-I', '-B', str(path), '--help'], capture_output=True, text=True)
149
- check('--help', result.returncode == 0 and 'Usage' in result.stdout, result.stdout)
150
-
151
- if failures:
152
- for item in failures:
153
- print('FAIL:', item, file=sys.stderr)
154
- sys.exit(1)
155
- print(f'PASS {checks} checks')
156
- PY
@@ -1,269 +0,0 @@
1
- #!/usr/bin/env bash
2
- set -euo pipefail
3
- cd -- "${BASH_SOURCE[0]%/*}/.."
4
-
5
- SCRIPT="$PWD/scripts/sweep-issues.py"
6
- PYTHON_BIN=$(command -v python3 || command -v python)
7
- "$PYTHON_BIN" -I -B - "$SCRIPT" <<'PY'
8
- import copy
9
- import json
10
- from pathlib import Path
11
- import subprocess
12
- import sys
13
- import tempfile
14
-
15
- script = Path(sys.argv[1]).resolve()
16
- if not script.is_file():
17
- sys.exit('FAIL: missing script ' + str(script))
18
-
19
- scratch = Path(tempfile.mkdtemp())
20
- checks = 0
21
- failures = []
22
- NOW = '2026-11-30T12:00:00Z'
23
- BOT = 'github-actions[bot]'
24
- CONFIG = {}
25
- REPO_LABELS = ['stale', 'needs-info', 'needs-close-review', 'status:in-progress', 'bug', 'priority:high', 'security']
26
-
27
-
28
- def pr(number=20, state='MERGED', merged_at='2026-11-20T10:00:00Z', text='Closes #12', will_close=False,
29
- manual=False, referenced_at='2026-11-19T10:00:00Z', repo='example/repo'):
30
- return {'number': number, 'repo': repo, 'state': state, 'merged_at': merged_at if state == 'MERGED' else None,
31
- 'merge_commit': 'abcdef1234567' if state == 'MERGED' else None,
32
- 'url': 'https://github.com/' + repo + '/pull/' + str(number), 'will_close': will_close,
33
- 'manual_link': manual, 'text': text, 'referenced_at': referenced_at}
34
-
35
-
36
- def comment(at, actor='dev', marker=None):
37
- return {'type': 'comment', 'at': at, 'actor': actor, 'marker': marker}
38
-
39
-
40
- def label_event(name, at, actor='dev', kind='labeled'):
41
- return {'type': kind, 'label': name, 'at': at, 'actor': actor}
42
-
43
-
44
- def issue(number=12, labels=(), assignees=(), prs=(), events=(), created='2026-10-01T10:00:00Z', author='carla',
45
- incomplete=False):
46
- return {'number': number, 'title': 'Issue ' + str(number), 'url': 'https://github.com/example/repo/issues/' + str(number),
47
- 'author': author, 'created_at': created, 'labels': list(labels), 'assignees': list(assignees),
48
- 'prs': list(prs), 'events': list(events), 'incomplete': incomplete}
49
-
50
-
51
- def write(name, value):
52
- path = scratch / name
53
- path.write_text(value if isinstance(value, str) else json.dumps(value), encoding='utf-8')
54
- return str(path)
55
-
56
-
57
- def run(issues, config=None, labels=REPO_LABELS, extra=()):
58
- snapshot = {'repo': 'example/repo', 'fetched_at': NOW, 'labels': list(labels), 'issues': list(issues)}
59
- cfg = CONFIG if config is None else config
60
- login = BOT
61
- if isinstance(cfg, dict):
62
- cfg = dict(cfg)
63
- login = cfg.pop('sweeper_login', BOT)
64
- args = ['--snapshot', write('snapshot.json', snapshot), '--sweeper-login', login, '--now', NOW]
65
- if cfg:
66
- args += ['--config', write('config.json', cfg)]
67
- result = subprocess.run([sys.executable, '-I', '-B', str(script), *args, *extra],
68
- capture_output=True, text=True, encoding='utf-8')
69
- try:
70
- return result.returncode, json.loads(result.stdout)
71
- except ValueError:
72
- return result.returncode, {'verdict': None, 'raw': result.stdout + result.stderr}
73
-
74
-
75
- def act(plan, number):
76
- return [a for a in plan.get('actions', []) if a['issue'] == number]
77
-
78
-
79
- def expect(label, issues, rule, steps, config=None, labels=REPO_LABELS, bucket='actions', number=12):
80
- """steps: list of (action, detail) for the issue, e.g. [('comment', 'SW1'), ('close', 'completed')]."""
81
- global checks
82
- checks += 1
83
- code, plan = run(issues, config, labels)
84
- entries = [a for a in plan.get(bucket, []) if a['issue'] == number]
85
- got_rule = entries[0]['rule'] if entries else None
86
- got_steps = [(s['action'], s.get('state_reason') or s.get('label') or s.get('marker')) for e in entries
87
- for s in e.get('steps', [])]
88
- if code != 0 or got_rule != rule or got_steps != steps:
89
- failures.append(label + ': expected ' + repr((rule, steps)) + ', observed ' + repr((code, got_rule, got_steps))
90
- + ' ' + json.dumps(plan)[:600])
91
- return plan
92
-
93
-
94
- # SW1: merged PR that declares closing
95
- expect('closing keyword in a merged PR closes the issue (SW1)', [issue(prs=[pr()])], 'SW1',
96
- [('comment', 'SW1'), ('close', 'completed')])
97
- expect('willCloseTarget closes (SW1)', [issue(prs=[pr(text='See #12', will_close=True)])], 'SW1',
98
- [('comment', 'SW1'), ('close', 'completed')])
99
- expect('a manual link closes (SW1)', [issue(prs=[pr(text='', manual=True)])], 'SW1',
100
- [('comment', 'SW1'), ('close', 'completed')])
101
- expect('keyword variants: "Fixes: #12"', [issue(prs=[pr(text='Fixes: #12 and more')])], 'SW1',
102
- [('comment', 'SW1'), ('close', 'completed')])
103
- expect('full reference to this repository', [issue(prs=[pr(text='resolves Example/Repo#12')])], 'SW1',
104
- [('comment', 'SW1'), ('close', 'completed')])
105
- expect('"Closes #123" is not #12 (SW2 by reference only)', [issue(prs=[pr(text='Closes #123, refs #12')])], 'SW2',
106
- [('add-label', 'needs-close-review'), ('comment', 'SW2')])
107
- expect('a closing keyword for another repository is a mention', [issue(prs=[pr(text='Closes other/repo#12')])],
108
- 'SW2', [('add-label', 'needs-close-review'), ('comment', 'SW2')])
109
- expect('reopened after the merge goes to review (SW2)',
110
- [issue(prs=[pr()], events=[{'type': 'reopened', 'at': '2026-11-21T10:00:00Z', 'actor': 'dev'}])], 'SW2',
111
- [('add-label', 'needs-close-review'), ('comment', 'SW2')])
112
- expect('another open PR still declares closing it (SW2)',
113
- [issue(prs=[pr(), pr(number=21, state='OPEN', text='Fixes #12')])], 'SW2',
114
- [('add-label', 'needs-close-review'), ('comment', 'SW2')])
115
- expect('a closed unmerged PR does not count', [issue(prs=[pr(state='CLOSED')], created='2026-11-25T10:00:00Z')],
116
- None, [])
117
- expect('an incomplete timeline is never closed', [issue(prs=[pr()], incomplete=True)], None, [])
118
-
119
- # SW2: merged PR that only mentions the issue
120
- expect('a merged mention asks for review (SW2)', [issue(prs=[pr(text='Refs #12')])], 'SW2',
121
- [('add-label', 'needs-close-review'), ('comment', 'SW2')])
122
- expect('SW2 does not repeat while its marker is newest',
123
- [issue(labels=['needs-close-review'], prs=[pr(text='Refs #12')],
124
- events=[comment('2026-11-21T10:00:00Z', BOT, 'SW2')])], None, [])
125
- expect('SW2 without the label in the repository still comments',
126
- [issue(prs=[pr(text='Refs #12')])], 'SW2', [('comment', 'SW2')],
127
- labels=[name for name in REPO_LABELS if name != 'needs-close-review'])
128
-
129
- # SW3: needs-info without an answer
130
- asked = [label_event('needs-info', '2026-11-10T10:00:00Z')]
131
- expect('needs-info unanswered for 14 days closes as not planned (SW3)',
132
- [issue(labels=['needs-info'], events=asked)], 'SW3', [('comment', 'SW3'), ('close', 'not_planned')])
133
- expect('the author answered: no close',
134
- [issue(labels=['needs-info'], events=asked + [comment('2026-11-12T10:00:00Z', 'carla')],
135
- created='2026-11-09T10:00:00Z')], None, [])
136
- expect('only 10 days: wait',
137
- [issue(labels=['needs-info'], events=[label_event('needs-info', '2026-11-20T10:00:00Z')],
138
- created='2026-11-19T10:00:00Z')], None, [])
139
- expect('someone else commenting does not answer for the author',
140
- [issue(labels=['needs-info'], events=asked + [comment('2026-11-12T10:00:00Z', 'dev')])], 'SW3',
141
- [('comment', 'SW3'), ('close', 'not_planned')])
142
-
143
- # SW4: duplicate work is reported only
144
- plan = expect('two open PRs: report only (SW4)',
145
- [issue(prs=[pr(number=20, state='OPEN', text='Refs #12'), pr(number=21, state='OPEN', text='Refs #12')],
146
- created='2026-11-25T10:00:00Z')], 'SW4', [], bucket='report_only')
147
- checks += 1
148
- if act(plan, 12):
149
- failures.append('SW4 must not write: ' + json.dumps(plan))
150
-
151
- # SW5: stale claim
152
- expect('claimed, no PR, 9 days idle: ping the holder (SW5)',
153
- [issue(labels=['status:in-progress'], assignees=['ana'], events=[comment('2026-11-21T10:00:00Z', 'ana')],
154
- created='2026-11-20T10:00:00Z')], 'SW5', [('comment', 'SW5')])
155
- expect('an open PR keeps a claim alive',
156
- [issue(labels=['status:in-progress'], assignees=['ana'], prs=[pr(state='OPEN', text='Fixes #12')],
157
- created='2026-11-01T10:00:00Z')], None, [])
158
- expect('the author assigned without the claim label is not a claim (SW6 instead)',
159
- [issue(assignees=['carla'], created='2026-10-01T10:00:00Z')], 'SW6', [('add-label', 'stale'), ('comment', 'SW6')])
160
-
161
- # SW6 / SW7: inactivity is labeled, never closed
162
- expect('no PR, unclaimed, 60 days idle: stale (SW6)', [issue()], 'SW6', [('add-label', 'stale'), ('comment', 'SW6')])
163
- expect('the sweep own comment is not activity',
164
- [issue(events=[comment('2026-11-29T10:00:00Z', BOT, 'SW5')])], 'SW6', [('add-label', 'stale'), ('comment', 'SW6')])
165
- expect('a person as sweeper: their other labels are still activity',
166
- [issue(events=[label_event('bug', '2026-11-25T10:00:00Z', 'pm-login')])], None, [],
167
- config=dict(CONFIG, sweeper_login='pm-login'))
168
- expect('a person as sweeper: the stale label they set is not activity',
169
- [issue(labels=['stale'], events=[label_event('stale', '2026-11-25T10:00:00Z', 'pm-login')])], None, [],
170
- config=dict(CONFIG, sweeper_login='pm-login'))
171
- expect('already stale and quiet: nothing',
172
- [issue(labels=['stale'], events=[label_event('stale', '2026-11-01T10:00:00Z', BOT),
173
- comment('2026-11-01T10:00:01Z', BOT, 'SW6')])], None, [])
174
- expect('activity after stale removes the label (SW7)',
175
- [issue(labels=['stale'], events=[label_event('stale', '2026-11-01T10:00:00Z', BOT),
176
- comment('2026-11-25T10:00:00Z', 'carla')])], 'SW7',
177
- [('remove-label', 'stale')])
178
- expect('recent activity: nothing', [issue(events=[comment('2026-11-25T10:00:00Z', 'carla')])], None, [])
179
-
180
- # SW8: exempt issues are never touched
181
- expect('security is exempt (SW8)', [issue(labels=['security'], prs=[pr()])], 'SW8', [], bucket='report_only')
182
- expect('P1 is exempt (SW8)', [issue(labels=['priority:high'])], 'SW8', [], bucket='report_only')
183
- expect('P1 written as "P1 - alta" is exempt', [issue(labels=['P1 - alta'])], 'SW8', [], bucket='report_only')
184
-
185
- # guards: cap, config
186
- many = [issue(number=n, prs=[pr(number=100 + n, text='Closes #' + str(n))]) for n in range(1, 23)]
187
- code, plan = run(many)
188
- checks += 1
189
- if len(plan.get('actions', [])) != 20 or [a['issue'] for a in plan.get('deferred', [])] != [21, 22]:
190
- failures.append('cap of 20 issues per run: ' + json.dumps(plan)[:400])
191
- code, plan = run(many, dict(CONFIG, max_writes_per_run=3))
192
- checks += 1
193
- if len(plan.get('actions', [])) != 3:
194
- failures.append('max_writes_per_run is configurable: ' + json.dumps(plan)[:300])
195
- code, plan = run([issue(prs=[pr()]), issue(number=13)], labels=['bug'])
196
- checks += 1
197
- missing = sorted(gap.get('label') for gap in plan.get('gaps', []) if gap.get('kind') == 'missing-label')
198
- if missing != ['needs-close-review', 'needs-info', 'stale', 'status:in-progress']:
199
- failures.append('missing labels are gaps: ' + json.dumps(plan.get('gaps')))
200
- code, plan = run([issue(prs=[pr()], incomplete=True)])
201
- checks += 1
202
- if not any(gap.get('kind') == 'incomplete' and gap.get('issue') == 12 for gap in plan.get('gaps', [])):
203
- failures.append('incomplete issues are gaps: ' + json.dumps(plan.get('gaps')))
204
-
205
- # comments: fixed text, numbers and links only, marker and visual gap line
206
- code, plan = run([issue(prs=[pr(text='Closes #12 <script>alert(1)</script>')])])
207
- body = next(s['body'] for s in act(plan, 12)[0]['steps'] if s['action'] == 'comment')
208
- checks += 1
209
- if ('<script>' in body or '<!-- issue-sweeper:SW1 -->' not in body or '#20' not in body or 'abcdef1' not in body
210
- or '🟡 GAP visual' not in body):
211
- failures.append('SW1 comment content: ' + body)
212
- code, plan = run([issue(prs=[pr()])], dict(CONFIG, language='en'))
213
- body = next(s['body'] for s in act(plan, 12)[0]['steps'] if s['action'] == 'comment')
214
- checks += 1
215
- if 'Closing' not in body:
216
- failures.append('English comments: ' + body)
217
- code, plan = run([issue(prs=[pr(text='Refs #12')], assignees=['ana', 'bob'])])
218
- body = next(s['body'] for s in act(plan, 12)[0]['steps'] if s['action'] == 'comment')
219
- checks += 1
220
- if '@ana' not in body or '@bob' not in body:
221
- failures.append('SW2 pings the assignees: ' + body)
222
-
223
- # metrics and report
224
- issues = [issue(number=1, prs=[pr(number=30, text='Closes #1')], assignees=['ana'], created='2026-11-28T10:00:00Z'),
225
- issue(number=2, created='2026-11-20T10:00:00Z', events=[comment('2026-11-29T10:00:00Z')]),
226
- issue(number=3, labels=['security'], created='2026-08-01T10:00:00Z')]
227
- code, plan = run(issues)
228
- metrics = plan.get('metrics', {})
229
- checks += 1
230
- want = {'open': 3, 'with_pr': 1, 'assigned': 1, 'merged_but_open': 1, 'exempt': 1}
231
- if {key: metrics.get(key) for key in want} != want or metrics.get('age_days_p50') != 10:
232
- failures.append('metrics: ' + json.dumps(metrics))
233
- report = plan.get('report_markdown', '')
234
- checks += 1
235
- if '<!-- issue-sweeper:report -->' not in report or '#1' not in report or 'SW1' not in report:
236
- failures.append('report markdown: ' + report[:400])
237
-
238
- # unusable input
239
- for label, cfg in (('unknown language', dict(CONFIG, language='fr')),
240
- ('cap must be positive', dict(CONFIG, max_writes_per_run=0)),
241
- ('config must be an object', ['not', 'an', 'object'])):
242
- checks += 1
243
- code, plan = run([issue()], cfg)
244
- if code != 2 or plan.get('verdict') != 'unusable':
245
- failures.append(label + ' must be unusable: ' + json.dumps(plan)[:300])
246
- checks += 1
247
- code, plan = run('not-a-list')
248
- if code != 2:
249
- failures.append('issues must be a list')
250
- checks += 1
251
- code, plan = run([issue()])
252
- if plan.get('verdict') != 'ok' or plan.get('run_by') != BOT or 'mode' in plan:
253
- failures.append('plan names who runs it: ' + json.dumps(plan)[:300])
254
- checks += 1
255
- code, plan = run([issue()], {'needs_info_days': 7})
256
- if code != 0 or plan.get('verdict') != 'ok':
257
- failures.append('a partial config only overrides its keys: ' + json.dumps(plan)[:300])
258
-
259
- checks += 1
260
- result = subprocess.run([sys.executable, '-I', '-B', str(script), '--help'], capture_output=True, text=True)
261
- if result.returncode != 0 or 'Usage' not in result.stdout:
262
- failures.append('--help must print usage and exit 0')
263
-
264
- if failures:
265
- for item in failures:
266
- print('FAIL:', item, file=sys.stderr)
267
- sys.exit(1)
268
- print(f'PASS {checks} checks')
269
- PY