@bbcsoftwarefactory/skills 0.1.1 → 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.
Files changed (71) hide show
  1. package/dist/index.json +2 -3
  2. package/dist/skills/code-quality-gate/SKILL.md +4 -5
  3. package/dist/skills/code-quality-gate/references/gate-bigo.md +1 -1
  4. package/dist/skills/delivery-coordinator/SKILL.md +7 -8
  5. package/dist/skills/delivery-coordinator/references/hud-output.md +1 -1
  6. package/dist/skills/delivery-coordinator/references/issue-claim.md +5 -5
  7. package/dist/skills/delivery-coordinator/references/issue-dedup.md +1 -1
  8. package/dist/skills/delivery-coordinator/references/worktree-isolation.md +2 -2
  9. package/dist/skills/greptile-review-loop/SKILL.md +3 -4
  10. package/dist/skills/greptile-review-loop/references/review-protocol.md +1 -1
  11. package/dist/skills/issue-reviewer/SKILL.md +10 -13
  12. package/dist/skills/issue-reviewer/references/review-format.md +1 -1
  13. package/dist/skills/issue-reviewer/references/triage.md +6 -6
  14. package/dist/skills/question-gate/SKILL.md +6 -8
  15. package/dist/skills/question-gate/references/client-hooks.md +10 -10
  16. package/dist/skills/question-gate/references/diagram-routing.md +3 -3
  17. package/dist/skills/skill-clean-architecture/SKILL.md +2 -3
  18. package/dist/skills/skill-clean-architecture/references/source-headers.md +2 -3
  19. package/dist/skills/tool-depot/references/readonly-access.md +1 -1
  20. package/dist/skills/tool-depot/references/tool-catalog.json +2 -2
  21. package/dist/skills/watcher-observability/SKILL.md +3 -4
  22. package/dist/skills/watcher-observability/references/batch-protocol.md +6 -6
  23. package/dist/skills/watcher-observability/references/configuration.md +1 -1
  24. package/dist/skills/watcher-observability/references/error-scan.md +1 -1
  25. package/dist/skills/watcher-observability/references/live-protocol.md +8 -8
  26. package/dist/skills/watcher-observability/references/server-account.md +8 -8
  27. package/dist/skills/watcher-observability/server/watcher-gate.sh +1 -1
  28. package/dist/skills/watcher-observability/tests/watcher-gate.test.sh +10 -7
  29. package/dist/skills/workflow-auditor/SKILL.md +3 -5
  30. package/dist/skills/workflow-auditor/references/audit-protocol.md +3 -3
  31. package/dist/skills/workflow-auditor/references/ledger.md +1 -1
  32. package/package.json +26 -27
  33. package/dist/skills/code-quality-gate/scripts/extract-diff-scope.py +0 -225
  34. package/dist/skills/code-quality-gate/tests/extract-diff-scope.test.sh +0 -200
  35. package/dist/skills/delivery-coordinator/scripts/check-issue-claim.py +0 -363
  36. package/dist/skills/delivery-coordinator/scripts/check-worktree-guard.py +0 -220
  37. package/dist/skills/delivery-coordinator/scripts/classify-change-lane.py +0 -263
  38. package/dist/skills/delivery-coordinator/tests/check-issue-claim.test.sh +0 -221
  39. package/dist/skills/delivery-coordinator/tests/check-worktree-guard.test.sh +0 -123
  40. package/dist/skills/delivery-coordinator/tests/classify-change-lane.test.sh +0 -124
  41. package/dist/skills/greptile-review-loop/scripts/review-loop.py +0 -435
  42. package/dist/skills/greptile-review-loop/tests/review-loop.test.sh +0 -331
  43. package/dist/skills/issue-reviewer/scripts/fetch-issue-attachments.py +0 -239
  44. package/dist/skills/issue-reviewer/scripts/plan-issue-triage.py +0 -311
  45. package/dist/skills/issue-reviewer/tests/fetch-issue-attachments.test.sh +0 -90
  46. package/dist/skills/issue-reviewer/tests/plan-issue-triage.test.sh +0 -168
  47. package/dist/skills/question-gate/scripts/triage-question.py +0 -713
  48. package/dist/skills/question-gate/tests/question-corpus.test.sh +0 -32
  49. package/dist/skills/question-gate/tests/triage-question.test.sh +0 -441
  50. package/dist/skills/skill-clean-architecture/scripts/measure-bigo.py +0 -427
  51. package/dist/skills/skill-clean-architecture/tests/measure-bigo.test.sh +0 -222
  52. package/dist/skills/watcher-observability/scripts/error-scan.py +0 -318
  53. package/dist/skills/watcher-observability/scripts/resolve-containers.py +0 -155
  54. package/dist/skills/watcher-observability/scripts/save-counts.py +0 -381
  55. package/dist/skills/watcher-observability/scripts/summarize-logs.py +0 -113
  56. package/dist/skills/watcher-observability/scripts/watch-live.py +0 -606
  57. package/dist/skills/watcher-observability/tests/error-scan.test.sh +0 -257
  58. package/dist/skills/watcher-observability/tests/live-windows.test.sh +0 -177
  59. package/dist/skills/watcher-observability/tests/resolve-containers.test.sh +0 -87
  60. package/dist/skills/watcher-observability/tests/save-counts.test.sh +0 -338
  61. package/dist/skills/watcher-observability/tests/sleuth.test.sh +0 -176
  62. package/dist/skills/watcher-observability/tests/summarize-logs.test.sh +0 -105
  63. package/dist/skills/watcher-observability/tests/watcher-config.test.sh +0 -70
  64. package/dist/skills/workflow-auditor/scripts/audit-ledger.py +0 -624
  65. package/dist/skills/workflow-auditor/scripts/list-zed-commands.py +0 -183
  66. package/dist/skills/workflow-auditor/scripts/render-workflow.py +0 -201
  67. package/dist/skills/workflow-auditor/scripts/validate-skills.py +0 -444
  68. package/dist/skills/workflow-auditor/tests/audit-ledger.test.sh +0 -660
  69. package/dist/skills/workflow-auditor/tests/list-zed-commands.test.sh +0 -93
  70. package/dist/skills/workflow-auditor/tests/render-workflow.test.sh +0 -135
  71. package/dist/skills/workflow-auditor/tests/validate-skills.test.sh +0 -190
@@ -1,311 +0,0 @@
1
- #!/usr/bin/env python3
2
- """plan-issue-triage.py: turn an LLM triage proposal into the exact, safe GitHub writes for one issue.
3
-
4
- Read-only and offline: it evaluates GitHub REST (or `gh --json`) output fetched through Tool Depot
5
- and the reviewer's proposal, and never calls GitHub itself. Rules TR1-TR8 are defined in
6
- references/triage.md.
7
- """
8
-
9
- import json
10
- import re
11
- import sys
12
- from urllib.parse import quote
13
-
14
- DEFAULT_CLAIM_LABEL = 'status:in-progress'
15
- ASSIGNABLE = ('yes', 'no', 'unknown')
16
- PRIORITIES = ('P0', 'P1', 'P2', 'P3')
17
- PRIORITY_NAME = re.compile(r'(?:priority|prioridad|prio)\s*[:/_ -]\s*(.+)|(p[0-3])\b.*')
18
- LEVEL_WORDS = {
19
- 'p0': 0, 'critical': 0, 'critica': 0, 'crítica': 0, 'urgent': 0, 'urgente': 0, 'blocker': 0,
20
- 'p1': 1, 'high': 1, 'alta': 1,
21
- 'p2': 2, 'medium': 2, 'media': 2, 'normal': 2,
22
- 'p3': 3, 'low': 3, 'baja': 3, 'minor': 3,
23
- }
24
- INVALID_RULES = ('TR5', 'TR6', 'TR7')
25
- SHELL_SPECIAL = re.compile(r'(["$`\\])')
26
-
27
- HELP = (
28
- 'Usage: python3 -I -B scripts/plan-issue-triage.py --repo <owner/repo>\n'
29
- ' --issue-json <file> gh api repos/<o>/<r>/issues/<n> (or gh issue view <n> --json ...)\n'
30
- ' --labels-json <file> gh api --paginate --slurp "repos/<o>/<r>/labels?per_page=100"\n'
31
- ' --proposal-json <file> {"priority": "P0-P3", "add": [...], "remove": [...], "rationale": "..."}\n'
32
- ' --author-assignable yes|no|unknown gh api repos/<o>/<r>/assignees/<author> (204 yes, 404 no)\n'
33
- ' [--claim-label status:in-progress]\n'
34
- 'Exit 0: ready or ready-with-gaps; 1: invalid-proposal; 2: unusable.'
35
- )
36
-
37
-
38
- class Unusable(Exception):
39
- """The inputs cannot be evaluated (rule TR1)."""
40
-
41
-
42
- def _write_out(text):
43
- sys.stdout.buffer.write((text + '\n').encode('utf-8', 'surrogateescape'))
44
-
45
-
46
- def _fold(value):
47
- return value.strip().casefold() if isinstance(value, str) else ''
48
-
49
-
50
- def _login(value):
51
- if isinstance(value, dict):
52
- value = value.get('login')
53
- return value if isinstance(value, str) and value.strip() else None
54
-
55
-
56
- def _flatten(value):
57
- if isinstance(value, list) and all(isinstance(item, list) for item in value):
58
- return [item for page in value for item in page]
59
- return value
60
-
61
-
62
- def _names(items):
63
- names = []
64
- for item in items or []:
65
- name = item.get('name') if isinstance(item, dict) else item
66
- if isinstance(name, str) and name.strip():
67
- names.append(name)
68
- return names
69
-
70
-
71
- def _load_json(path, label):
72
- try:
73
- with open(path, encoding='utf-8') as handle:
74
- return json.load(handle)
75
- except OSError:
76
- raise Unusable(label + ' cannot be read.')
77
- except ValueError:
78
- raise Unusable(label + ' is not valid JSON.')
79
-
80
-
81
- def load_issue(path):
82
- raw = _load_json(path, 'Issue JSON')
83
- if not isinstance(raw, dict) or not isinstance(raw.get('number'), int):
84
- raise Unusable('Issue JSON needs a numeric number.')
85
- if not isinstance(raw.get('state'), str) or raw['state'].lower() != 'open':
86
- raise Unusable('Only an open issue is triaged; reopen it first.')
87
- user = raw.get('user') if isinstance(raw.get('user'), dict) else raw.get('author')
88
- author = _login(user)
89
- if author is None:
90
- raise Unusable('Issue JSON needs the author login (user.login).')
91
- kind = user.get('type') if isinstance(user, dict) else None
92
- return {
93
- 'number': raw['number'],
94
- 'author': author,
95
- 'bot': kind == 'Bot' or author.endswith('[bot]') or bool(isinstance(user, dict) and user.get('is_bot')),
96
- 'assignees': [login for login in map(_login, raw.get('assignees') or []) if login],
97
- 'labels': _names(raw.get('labels')),
98
- }
99
-
100
-
101
- def load_labels(path):
102
- raw = _flatten(_load_json(path, 'Repository labels JSON'))
103
- if not isinstance(raw, list):
104
- raise Unusable('Repository labels JSON must be an array.')
105
- return _names(raw)
106
-
107
-
108
- def load_proposal(path):
109
- raw = _load_json(path, 'Proposal JSON')
110
- if not isinstance(raw, dict):
111
- raise Unusable('Proposal JSON must be an object.')
112
- priority = raw.get('priority')
113
- if not isinstance(priority, str) or priority.strip().upper() not in PRIORITIES:
114
- raise Unusable('Proposal priority must be one of: ' + ', '.join(PRIORITIES) + '.')
115
- if not isinstance(raw.get('rationale'), str) or not raw['rationale'].strip():
116
- raise Unusable('Proposal needs a rationale grounded in the evidence.')
117
- lists = {}
118
- for key in ('add', 'remove'):
119
- value = raw.get(key) or []
120
- if not isinstance(value, list) or not all(isinstance(name, str) and name.strip() for name in value):
121
- raise Unusable('Proposal "' + key + '" must be an array of label names.')
122
- lists[key] = value
123
- both = {_fold(name) for name in lists['add']} & {_fold(name) for name in lists['remove']}
124
- if both:
125
- raise Unusable('A label cannot be added and removed at once: ' + ', '.join(sorted(both)) + '.')
126
- return {'priority': priority.strip().upper(), 'add': lists['add'], 'remove': lists['remove'],
127
- 'rationale': raw['rationale'].strip()}
128
-
129
-
130
- def priority_level(name):
131
- """(is a priority label, level 0-3 or None when the level word is unknown)."""
132
- match = PRIORITY_NAME.fullmatch(_fold(name))
133
- if match is None:
134
- return False, None
135
- word = match.group(2) or re.split(r'[\s:/_-]+', match.group(1).strip())[0]
136
- return True, LEVEL_WORDS.get(word)
137
-
138
-
139
- def _is_priority(name):
140
- return priority_level(name)[0]
141
-
142
-
143
- class Report:
144
- def __init__(self):
145
- self.findings = []
146
-
147
- def add(self, rule, detail, labels=None):
148
- finding = {'rule': rule, 'detail': detail}
149
- if labels:
150
- finding['labels'] = labels
151
- self.findings.append(finding)
152
-
153
- def verdict(self):
154
- rules = {finding['rule'] for finding in self.findings}
155
- if rules & set(INVALID_RULES):
156
- return 'invalid-proposal'
157
- return 'ready-with-gaps' if rules else 'ready'
158
-
159
-
160
- def plan_assignment(issue, assignable, report):
161
- if issue['bot']:
162
- report.add('TR2', 'The author is a bot; nobody is assigned. Say so in the triage comment.')
163
- return None, False
164
- if _fold(issue['author']) in {_fold(login) for login in issue['assignees']}:
165
- return None, True
166
- if assignable != 'yes':
167
- reason = 'cannot be assigned in this repository' if assignable == 'no' else 'was not verified as assignable'
168
- report.add('TR3', 'The author ' + reason + '; nobody is assigned. Say so in the triage comment.')
169
- return None, False
170
- return issue['author'], False
171
-
172
-
173
- def plan_priority(proposal, resolved_add, repo_labels, current, report):
174
- level = int(proposal['priority'][1])
175
- chosen = [name for name in resolved_add if _is_priority(name)]
176
- if len(chosen) > 1:
177
- report.add('TR6', 'Only one priority label may be set.', chosen)
178
- return None
179
- if chosen:
180
- if priority_level(chosen[0])[1] != level:
181
- report.add('TR7', 'The priority label does not match ' + proposal['priority'] + '.', chosen)
182
- return chosen[0]
183
- candidates = [name for name in repo_labels if priority_level(name) == (True, level)]
184
- on_issue = [name for name in candidates if _fold(name) in current]
185
- if len(candidates) == 1 or len(on_issue) == 1:
186
- return (on_issue or candidates)[0]
187
- if candidates:
188
- report.add('TR7', 'Several repository labels mean ' + proposal['priority'] + '; name one in "add".', candidates)
189
- return None
190
- detail = ('The repository has no priority labels' if not any(map(_is_priority, repo_labels))
191
- else 'The repository has no label for ' + proposal['priority'])
192
- report.add('TR8', detail + '; state the priority in the triage comment only. A maintainer may create the label.')
193
- return None
194
-
195
-
196
- def evaluate(issue, repo_labels, proposal, assignable, claim_label):
197
- report = Report()
198
- real = {}
199
- for name in repo_labels:
200
- real.setdefault(_fold(name), name)
201
- current = {_fold(name): name for name in issue['labels']}
202
-
203
- protected = [name for name in proposal['add'] + proposal['remove']
204
- if _fold(name) == _fold(claim_label) or _fold(name).startswith('status:')]
205
- if protected:
206
- report.add('TR5', 'Status and claim labels belong to the delivery workflow; triage never changes them.',
207
- protected)
208
-
209
- resolved_add, missing, seen = [], [], set()
210
- for name in proposal['add']:
211
- if _fold(name) not in real:
212
- missing.append(name)
213
- elif _fold(name) not in seen:
214
- seen.add(_fold(name))
215
- resolved_add.append(real[_fold(name)])
216
- if missing:
217
- report.add('TR4', 'Labels missing in the repository were dropped; the workflow never creates labels.', missing)
218
-
219
- priority_label = plan_priority(proposal, resolved_add, repo_labels, current, report)
220
- if priority_label is not None and _fold(priority_label) not in seen:
221
- resolved_add.append(priority_label)
222
- labels_add = [name for name in resolved_add if _fold(name) not in current]
223
- labels_remove = [current[_fold(name)] for name in proposal['remove'] if _fold(name) in current]
224
- removed = {_fold(name) for name in labels_remove}
225
- for name in issue['labels']:
226
- if _is_priority(name) and _fold(name) != _fold(priority_label) and _fold(name) not in removed:
227
- removed.add(_fold(name))
228
- labels_remove.append(name)
229
-
230
- assign, already = plan_assignment(issue, assignable, report)
231
- final = [name for name in issue['labels'] if _fold(name) not in removed] + labels_add
232
- return {
233
- 'verdict': report.verdict(),
234
- 'issue': issue['number'],
235
- 'author': issue['author'],
236
- 'assign': assign,
237
- 'already_assigned': already,
238
- 'labels_add': labels_add,
239
- 'labels_remove': labels_remove,
240
- 'labels_final': final,
241
- 'priority': proposal['priority'],
242
- 'priority_label': priority_label,
243
- 'missing_labels': missing,
244
- 'rationale': proposal['rationale'],
245
- 'findings': report.findings,
246
- }
247
-
248
-
249
- def _arg(value):
250
- return '"' + SHELL_SPECIAL.sub(r'\\\1', value) + '"'
251
-
252
-
253
- def commands(plan, repo):
254
- base = 'repos/' + repo + '/issues/' + str(plan['issue'])
255
- lines = []
256
- if plan['assign']:
257
- lines.append('gh api -X POST ' + base + '/assignees -f ' + _arg('assignees[]=' + plan['assign']))
258
- if plan['labels_add']:
259
- lines.append('gh api -X POST ' + base + '/labels ' + ' '.join('-f ' + _arg('labels[]=' + name)
260
- for name in plan['labels_add']))
261
- for name in plan['labels_remove']:
262
- lines.append('gh api -X DELETE ' + base + '/labels/' + quote(name, safe=''))
263
- return lines
264
-
265
-
266
- def parse_args(argv):
267
- options = {'repo': None, 'issue': None, 'labels': None, 'proposal': None, 'assignable': None,
268
- 'claim_label': DEFAULT_CLAIM_LABEL}
269
- keys = {'--repo': 'repo', '--issue-json': 'issue', '--labels-json': 'labels', '--proposal-json': 'proposal',
270
- '--author-assignable': 'assignable', '--claim-label': 'claim_label'}
271
- args = list(argv)
272
- while args:
273
- arg = args.pop(0)
274
- if arg in ('-h', '--help'):
275
- return None
276
- if arg not in keys or not args:
277
- raise Unusable('Unexpected argument ' + arg + '; see --help.')
278
- options[keys[arg]] = args.pop(0)
279
- missing = [flag for flag, key in keys.items() if key != 'claim_label' and not options[key]]
280
- if missing:
281
- raise Unusable('Required: ' + ', '.join(missing) + '.')
282
- if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', options['repo']):
283
- raise Unusable('--repo must be <owner>/<repo>.')
284
- if options['assignable'] not in ASSIGNABLE:
285
- raise Unusable('--author-assignable must be one of: ' + ', '.join(ASSIGNABLE) + '.')
286
- return options
287
-
288
-
289
- def main(argv):
290
- try:
291
- options = parse_args(argv)
292
- if options is None:
293
- _write_out(HELP)
294
- return 0
295
- issue = load_issue(options['issue'])
296
- repo_labels = load_labels(options['labels'])
297
- proposal = load_proposal(options['proposal'])
298
- plan = evaluate(issue, repo_labels, proposal, options['assignable'], options['claim_label'])
299
- except Unusable as error:
300
- _write_out(json.dumps({'verdict': 'unusable', 'proceed': False,
301
- 'findings': [{'rule': 'TR1', 'detail': str(error)}]}, indent=2, ensure_ascii=False))
302
- return 2
303
- proceed = plan['verdict'] != 'invalid-proposal'
304
- plan['proceed'] = proceed
305
- plan['commands'] = commands(plan, options['repo']) if proceed else []
306
- _write_out(json.dumps(plan, indent=2, ensure_ascii=False))
307
- return 0 if proceed else 1
308
-
309
-
310
- if __name__ == '__main__':
311
- sys.exit(main(sys.argv[1:]))
@@ -1,90 +0,0 @@
1
- #!/usr/bin/env bash
2
- set -eu
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
- from pathlib import Path
8
- import tempfile
9
-
10
- spec = importlib.util.spec_from_file_location(
11
- 'fetch_issue_attachments', Path('scripts/fetch-issue-attachments.py')
12
- )
13
- mod = importlib.util.module_from_spec(spec)
14
- spec.loader.exec_module(mod)
15
-
16
- checks = 0
17
-
18
- # 1. HTML unescaping and deduplication between <a> and <img>
19
- html_sample = (
20
- '<a href="https://private-user-images.githubusercontent.com/1/2.png?a=1&amp;b=2">'
21
- '<img src="https://private-user-images.githubusercontent.com/1/2.png?a=1&amp;b=2" /></a>'
22
- '<a href="https://github.com/user-attachments/files/99/trace.txt">trace.txt</a>'
23
- )
24
- urls = mod.extract_urls_from_html(html_sample, '')
25
- assert len(urls) == 2, urls
26
- assert urls[0]['url'] == 'https://private-user-images.githubusercontent.com/1/2.png?a=1&b=2'
27
- assert urls[1]['url'] == 'https://github.com/user-attachments/files/99/trace.txt'
28
- checks += 1
29
-
30
- # 2. Ignores plain non-attachment web links while keeping user-attachments
31
- html_links = (
32
- '<a href="https://example.com/docs">docs</a>'
33
- '<img src="https://private-user-images.githubusercontent.com/1/shot.jpeg?jwt=abc" />'
34
- )
35
- urls2 = mod.extract_urls_from_html(html_links, '')
36
- assert len(urls2) == 1 and urls2[0]['url'].endswith('jwt=abc'), urls2
37
- checks += 1
38
-
39
- # 3. process_issue_payload handles body + comments without duplicating URLs
40
- with tempfile.TemporaryDirectory() as tmp:
41
- def fake_downloader(url, dest_dir, index):
42
- p = Path(dest_dir) / f'attachment-{index}.jpg'
43
- p.write_bytes(b'fake-jpg')
44
- return {
45
- 'url': url,
46
- 'local_path': str(p),
47
- 'content_type': 'image/jpeg',
48
- 'bytes': 8,
49
- 'status': 'downloaded',
50
- }
51
-
52
- report = mod.process_issue_payload(
53
- {
54
- 'number': 743,
55
- 'title': 'ui ux problema edit',
56
- 'html_url': 'https://github.com/example-org/example-app/issues/743',
57
- 'body_html': '<img src="https://private-user-images.githubusercontent.com/1/a.jpg?jwt=1" />',
58
- 'body': '![image](https://github.com/user-attachments/assets/uuid-1)',
59
- },
60
- [
61
- {
62
- 'id': 10,
63
- 'body_html': (
64
- '<img src="https://private-user-images.githubusercontent.com/1/a.jpg?jwt=1" />'
65
- '<img src="https://private-user-images.githubusercontent.com/1/b.png?jwt=2" />'
66
- ),
67
- }
68
- ],
69
- tmp,
70
- downloader=fake_downloader,
71
- )
72
- assert report['issue'] == 743
73
- assert len(report['attachments']) == 2
74
- assert report['attachments'][0]['source'] == 'body'
75
- assert report['attachments'][1]['source'] == 'comment:10'
76
- checks += 1
77
-
78
- # 4. SSRF / untrusted host rejection and invalid --repo validation
79
- with tempfile.TemporaryDirectory() as tmp:
80
- ssrf_res = mod.download_attachment('http://127.0.0.1:8080/secret.png', tmp, 1)
81
- assert ssrf_res['status'] == 'error', ssrf_res
82
- meta_res = mod.download_attachment('https://169.254.169.254/latest/meta-data/', tmp, 2)
83
- assert meta_res['status'] == 'error', meta_res
84
- evil_res = mod.download_attachment('https://evil.example.com/shot.png', tmp, 3)
85
- assert evil_res['status'] == 'error', evil_res
86
- assert mod.main(['--repo', 'owner/repo/extra', '--issue', '1']) == 2
87
- checks += 1
88
-
89
- print(f'PASS {checks} checks')
90
- PY
@@ -1,168 +0,0 @@
1
- #!/usr/bin/env bash
2
- set -euo pipefail
3
- cd -- "${BASH_SOURCE[0]%/*}/.."
4
-
5
- SCRIPT="$PWD/scripts/plan-issue-triage.py"
6
- PYTHON_BIN=$(command -v python3 || command -v python)
7
- "$PYTHON_BIN" -I -B - "$SCRIPT" <<'PY'
8
- import json
9
- from pathlib import Path
10
- import subprocess
11
- import sys
12
- import tempfile
13
-
14
- script = Path(sys.argv[1]).resolve()
15
- if not script.is_file():
16
- sys.exit('FAIL: missing script ' + str(script))
17
-
18
- scratch = Path(tempfile.mkdtemp())
19
- checks = 0
20
- failures = []
21
- REPO_LABELS = ['bug', 'enhancement', 'documentation', 'needs-info', 'area:flows', 'Area: Inbox',
22
- 'priority:critical', 'priority:high', 'priority:medium', 'priority:low', 'status:in-progress']
23
-
24
-
25
- def issue(author='carla', kind='User', assignees=(), labels=(), number=12):
26
- return {'number': number, 'state': 'open', 'user': {'login': author, 'type': kind},
27
- 'assignees': [{'login': a} for a in assignees], 'labels': [{'name': n} for n in labels]}
28
-
29
-
30
- def proposal(priority='P1', add=('bug', 'priority:high'), remove=(), rationale='Flows editor fails for every bot.'):
31
- return {'priority': priority, 'add': list(add), 'remove': list(remove), 'rationale': rationale}
32
-
33
-
34
- def write(name, value):
35
- path = scratch / name
36
- path.write_text(value if isinstance(value, str) else json.dumps(value), encoding='utf-8')
37
- return str(path)
38
-
39
-
40
- def run(issue_data=None, plan=None, labels=REPO_LABELS, assignable='yes', extra=()):
41
- issue_data = issue() if issue_data is None else issue_data
42
- plan = proposal() if plan is None else plan
43
- pages = labels if isinstance(labels, str) else [[{'name': n} for n in labels]]
44
- args = ['--repo', 'example/repo', '--issue-json', write('issue.json', issue_data),
45
- '--labels-json', write('labels.json', pages), '--proposal-json', write('proposal.json', plan),
46
- '--author-assignable', assignable]
47
- result = subprocess.run([sys.executable, '-I', '-B', str(script), *args, *extra],
48
- capture_output=True, text=True, encoding='utf-8')
49
- try:
50
- report = json.loads(result.stdout)
51
- except ValueError:
52
- report = {'verdict': None, 'raw': result.stdout + result.stderr}
53
- return result.returncode, report
54
-
55
-
56
- def expect(label, observed, status, verdict, rules=(), **fields):
57
- global checks
58
- checks += 1
59
- code, report = observed
60
- got = (code, report.get('verdict'), sorted({f['rule'] for f in report.get('findings', [])}))
61
- want = (status, verdict, sorted(rules))
62
- wrong = {key: report.get(key) for key, value in fields.items() if report.get(key) != value}
63
- if got != want or wrong:
64
- failures.append(label + ': expected ' + repr((want, fields)) + ', observed ' + repr(got) + ' '
65
- + json.dumps(report))
66
-
67
-
68
- # assignment: the issue author, never anyone else
69
- expect('author assigned and labels added', run(), 0, 'ready', assign='carla',
70
- labels_add=['bug', 'priority:high'], labels_remove=[], priority='P1', priority_label='priority:high')
71
- expect('author already assigned is a no-op', run(issue(assignees=['carla'])), 0, 'ready', assign=None,
72
- already_assigned=True)
73
- expect('other assignees are kept, the author is added', run(issue(assignees=['bob'])), 0, 'ready', assign='carla')
74
- expect('a bot author is not assigned (TR2)', run(issue(author='dependabot[bot]', kind='Bot')),
75
- 0, 'ready-with-gaps', ['TR2'], assign=None)
76
- expect('a [bot] login without type is a bot (TR2)', run(issue(author='renovate[bot]', kind='User')),
77
- 0, 'ready-with-gaps', ['TR2'], assign=None)
78
- expect('an author without access is not assigned (TR3)', run(assignable='no'),
79
- 0, 'ready-with-gaps', ['TR3'], assign=None)
80
- expect('unverified assignability is not assigned (TR3)', run(assignable='unknown'),
81
- 0, 'ready-with-gaps', ['TR3'], assign=None)
82
-
83
- # labels: only labels that already exist, matched case-insensitively to their real name
84
- expect('a label missing in the repository is dropped (TR4)', run(plan=proposal(add=('bug', 'area:billing', 'priority:high'))),
85
- 0, 'ready-with-gaps', ['TR4'], labels_add=['bug', 'priority:high'], missing_labels=['area:billing'])
86
- expect('case-insensitive match uses the repository name', run(plan=proposal(add=('BUG', 'area: inbox', 'priority:high'))),
87
- 0, 'ready', labels_add=['bug', 'Area: Inbox', 'priority:high'])
88
- expect('a label already on the issue is not re-added', run(issue(labels=['bug'])), 0, 'ready',
89
- labels_add=['priority:high'])
90
- expect('a wrong type label is removed', run(issue(labels=['enhancement']), proposal(remove=('enhancement',))),
91
- 0, 'ready', labels_remove=['enhancement'])
92
- expect('removing a label the issue does not have is ignored', run(plan=proposal(remove=('enhancement',))),
93
- 0, 'ready', labels_remove=[])
94
- expect('the claim label is protected (TR5)', run(plan=proposal(add=('bug', 'priority:high', 'status:in-progress'))),
95
- 1, 'invalid-proposal', ['TR5'])
96
- expect('removing a status label is protected (TR5)',
97
- run(issue(labels=['status:in-progress']), proposal(remove=('status:in-progress',))),
98
- 1, 'invalid-proposal', ['TR5'])
99
- expect('a custom claim label is protected (TR5)',
100
- run(plan=proposal(add=('bug', 'priority:high', 'wip')), labels=REPO_LABELS + ['wip'], extra=['--claim-label', 'wip']),
101
- 1, 'invalid-proposal', ['TR5'])
102
- expect('add and remove the same label (TR1)', run(plan=proposal(remove=('bug',))), 2, 'unusable', ['TR1'])
103
-
104
- # priority: one level, one label, matching each other
105
- expect('re-prioritizing replaces the old priority label', run(issue(labels=['priority:low'])),
106
- 0, 'ready', labels_add=['bug', 'priority:high'], labels_remove=['priority:low'])
107
- expect('two priority labels (TR6)', run(plan=proposal(add=('bug', 'priority:high', 'priority:low'))),
108
- 1, 'invalid-proposal', ['TR6'])
109
- expect('a label of another level (TR7)', run(plan=proposal(priority='P0', add=('bug', 'priority:low'))),
110
- 1, 'invalid-proposal', ['TR7'])
111
- expect('P0 maps to critical', run(plan=proposal(priority='P0', add=('bug', 'priority:critical'))),
112
- 0, 'ready', priority_label='priority:critical')
113
- expect('P-number labels are understood', run(plan=proposal(priority='P2', add=('bug', 'P2'))
114
- , labels=['bug', 'P0', 'P1', 'P2', 'P3']), 0, 'ready', priority_label='P2')
115
- expect('the priority label is derived from the level', run(plan=proposal(add=('bug',))),
116
- 0, 'ready', labels_add=['bug', 'priority:high'], priority_label='priority:high')
117
- expect('Spanish priority labels are understood', run(plan=proposal(priority='P3', add=('bug',)),
118
- labels=['bug', 'prioridad: alta', 'prioridad: baja']), 0, 'ready', priority_label='prioridad: baja')
119
- expect('two repository labels for one level must be chosen explicitly (TR7)',
120
- run(plan=proposal(add=('bug',)), labels=REPO_LABELS + ['P1']), 1, 'invalid-proposal', ['TR7'])
121
- expect('no repository label for the level (TR8)', run(plan=proposal(priority='P0', add=('bug',)),
122
- labels=['bug', 'priority:high', 'priority:low']), 0, 'ready-with-gaps', ['TR8'], priority_label=None)
123
- expect('area labels are not priority labels', run(plan=proposal(add=('bug', 'area:flows'))),
124
- 0, 'ready', labels_add=['bug', 'area:flows', 'priority:high'])
125
- expect('without priority labels the priority goes in the comment (TR8)',
126
- run(plan=proposal(add=('bug',)), labels=['bug', 'enhancement']), 0, 'ready-with-gaps', ['TR8'],
127
- priority='P1', priority_label=None)
128
- expect('the priority label already on the issue is kept', run(issue(labels=['priority:high'])),
129
- 0, 'ready', labels_add=['bug'], labels_remove=[], priority_label='priority:high')
130
-
131
- # commands: exactly what the plan writes, nothing else
132
- code, report = run(issue(labels=['priority:low']))
133
- checks += 1
134
- commands = report.get('commands', [])
135
- want = ['gh api -X POST repos/example/repo/issues/12/assignees -f "assignees[]=carla"',
136
- 'gh api -X POST repos/example/repo/issues/12/labels -f "labels[]=bug" -f "labels[]=priority:high"',
137
- 'gh api -X DELETE repos/example/repo/issues/12/labels/priority%3Alow']
138
- if commands != want:
139
- failures.append('commands: expected ' + repr(want) + ', observed ' + repr(commands))
140
- checks += 1
141
- _, spaced = run(plan=proposal(add=('Area: Inbox', 'priority:high')), extra=[])
142
- if 'gh api -X POST repos/example/repo/issues/12/labels -f "labels[]=Area: Inbox" -f "labels[]=priority:high"' \
143
- not in spaced.get('commands', []):
144
- failures.append('label names with spaces must stay quoted: ' + json.dumps(spaced))
145
- checks += 1
146
- _, noop = run(issue(assignees=['carla'], labels=['bug', 'priority:high']))
147
- if noop.get('commands') != []:
148
- failures.append('nothing to change must yield no commands: ' + json.dumps(noop))
149
-
150
- # unusable input
151
- expect('priority must be P0-P3 (TR1)', run(plan=proposal(priority='urgent')), 2, 'unusable', ['TR1'])
152
- expect('a rationale is required (TR1)', run(plan=proposal(rationale=' ')), 2, 'unusable', ['TR1'])
153
- expect('issue JSON must be valid (TR1)', run('{'), 2, 'unusable', ['TR1'])
154
- expect('labels JSON must be an array (TR1)', run(labels='{"name": "bug"}'), 2, 'unusable', ['TR1'])
155
- expect('assignability must be yes, no or unknown (TR1)', run(assignable='maybe'), 2, 'unusable', ['TR1'])
156
- expect('closed issues are not triaged (TR1)', run({**issue(), 'state': 'closed'}), 2, 'unusable', ['TR1'])
157
-
158
- checks += 1
159
- result = subprocess.run([sys.executable, '-I', '-B', str(script), '--help'], capture_output=True, text=True)
160
- if result.returncode != 0 or 'Usage' not in result.stdout:
161
- failures.append('--help must print usage and exit 0')
162
-
163
- if failures:
164
- for item in failures:
165
- print('FAIL:', item, file=sys.stderr)
166
- sys.exit(1)
167
- print(f'PASS {checks} checks')
168
- PY