@giamme/forge 0.18.0 → 0.20.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.
Files changed (93) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +19 -2
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +25 -1
  6. package/docs/commands.md +217 -18
  7. package/docs/decomposed-runs.md +114 -1
  8. package/docs/development.md +2 -1
  9. package/docs/forge-ui.md +138 -18
  10. package/docs/memory.md +25 -4
  11. package/docs/models.md +8 -0
  12. package/docs/reviews.md +122 -0
  13. package/forge +26 -3
  14. package/package.json +2 -1
  15. package/references/dataset.md +20 -1
  16. package/references/decompose.md +641 -41
  17. package/references/harnesses.md +18 -3
  18. package/references/memory.md +30 -5
  19. package/references/planning.md +43 -14
  20. package/references/ui.md +53 -6
  21. package/registry.tsv +8 -3
  22. package/scripts/forge-brief.py +88 -3
  23. package/scripts/forge-compare.py +4 -3
  24. package/scripts/forge-contract.py +202 -27
  25. package/scripts/forge-control.py +117 -5
  26. package/scripts/forge-dispatch.sh +34 -5
  27. package/scripts/forge-findings.py +675 -0
  28. package/scripts/forge-group.py +496 -0
  29. package/scripts/forge-groups.py +89 -0
  30. package/scripts/forge-handoff.py +1128 -0
  31. package/scripts/forge-issues.py +228 -97
  32. package/scripts/forge-lib-group.sh +641 -0
  33. package/scripts/forge-lib-plans.sh +339 -3
  34. package/scripts/forge-lib-task.sh +197 -4
  35. package/scripts/forge-memory.sh +711 -17
  36. package/scripts/forge-parallel.sh +721 -38
  37. package/scripts/forge-planner.py +104 -8
  38. package/scripts/forge-route.py +190 -12
  39. package/scripts/forge-runs.py +9 -5
  40. package/scripts/forge-schedule.py +417 -52
  41. package/scripts/forge-solo.sh +2 -0
  42. package/scripts/forge-sweep.py +199 -44
  43. package/scripts/forge-worktrees.py +243 -0
  44. package/scripts/forge_brief/__init__.py +294 -50
  45. package/scripts/forge_brief/answers.py +58 -11
  46. package/scripts/forge_brief/proposals.py +1630 -0
  47. package/scripts/forge_dataset/efforts.py +4 -3
  48. package/scripts/forge_dataset/export.py +24 -12
  49. package/scripts/forge_dataset/facts.py +5 -3
  50. package/scripts/forge_dataset/forecast.py +8 -18
  51. package/scripts/forge_dataset/harvest.py +204 -9
  52. package/scripts/forge_dataset/history.py +11 -6
  53. package/scripts/forge_dataset/importer.py +65 -1
  54. package/scripts/forge_dataset/names.py +66 -0
  55. package/scripts/forge_dataset/reviewers.py +5 -2
  56. package/scripts/forge_dataset/risk.py +6 -3
  57. package/scripts/forge_dataset/routing.py +6 -1
  58. package/scripts/forge_findings/__init__.py +17 -0
  59. package/scripts/forge_findings/apply.py +441 -0
  60. package/scripts/forge_findings/status.py +43 -0
  61. package/scripts/forge_findings/store.py +583 -0
  62. package/scripts/forge_findings/tags.py +53 -0
  63. package/scripts/forge_findings/triage.py +603 -0
  64. package/scripts/forge_groups/__init__.py +308 -0
  65. package/scripts/forge_groups/attribute.py +289 -0
  66. package/scripts/forge_groups/review.py +286 -0
  67. package/scripts/forge_identity.py +327 -0
  68. package/scripts/forge_memory_list.py +7 -3
  69. package/scripts/forge_owner.py +152 -0
  70. package/scripts/forge_side/__init__.py +228 -38
  71. package/ui/docs/api.md +303 -29
  72. package/ui/forge_ui/control.py +1018 -6
  73. package/ui/forge_ui/executions.py +8 -1
  74. package/ui/forge_ui/export.py +31 -4
  75. package/ui/forge_ui/groups.py +264 -0
  76. package/ui/forge_ui/models.py +70 -8
  77. package/ui/forge_ui/projects.py +209 -22
  78. package/ui/forge_ui/reader.py +262 -19
  79. package/ui/forge_ui/server.py +4 -0
  80. package/ui/forge_ui/static/app.js +93 -13
  81. package/ui/forge_ui/static/briefview.js +350 -47
  82. package/ui/forge_ui/static/diffview.js +86 -1
  83. package/ui/forge_ui/static/findingsactions.js +201 -0
  84. package/ui/forge_ui/static/groupsview.js +332 -0
  85. package/ui/forge_ui/static/index.html +3 -0
  86. package/ui/forge_ui/static/panel.js +127 -7
  87. package/ui/forge_ui/static/projectsview.js +764 -30
  88. package/ui/forge_ui/static/runmodel.js +14 -3
  89. package/ui/forge_ui/static/storageview.js +91 -10
  90. package/ui/forge_ui/static/style.css +138 -5
  91. package/ui/forge_ui/static/triageview.js +423 -0
  92. package/ui/forge_ui/static/worktreesview.js +233 -12
  93. package/ui/forge_ui/storage.py +14 -0
@@ -0,0 +1,308 @@
1
+ """groups.tsv: a frozen set of tasks with a title and goal.
2
+
3
+ Two opt-in features share it: group review (one QA review covers several tasks) and
4
+ brief mode part 2 (a wave-scoped answer acts on a group). This module is only the data
5
+ layer: parse, validate, derive from waves.tsv, resolve the QA spec, freeze.
6
+
7
+ <plan>/groups.tsv has six tab-separated columns, `#` lines and empty lines ignored:
8
+
9
+ id review qa members title goal
10
+
11
+ `review` is task or group, `qa` a spec or `-`, `members` a comma list of task ids in
12
+ order, `title` and `goal` one line each (`-` when absent). Stdlib only.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import os
18
+ import posixpath
19
+ import re
20
+ import tempfile
21
+ from collections import namedtuple
22
+ from pathlib import Path
23
+
24
+ Group = namedtuple('Group', 'id review qa members title goal')
25
+
26
+ HEADER = '# id\treview\tqa\tmembers\ttitle\tgoal'
27
+ FROZEN_REASON = "groups.tsv or a member's deps/files changed since plan; run plan again"
28
+ ID_RE = re.compile(r'[a-z0-9][a-z0-9-]{0,39}')
29
+ SWEEP_ID_RE = re.compile(r'sweep-[0-9]+')
30
+ REVIEWS = ('task', 'group')
31
+ RANK = {'high': 3, 'medium': 2, 'low': 1}
32
+
33
+
34
+ class GroupError(Exception):
35
+ """A malformed groups.tsv or a broken group rule; the message is one line."""
36
+
37
+
38
+ # --- tasks.tsv ----------------------------------------------------------------
39
+
40
+ def _tasks(plan) -> dict:
41
+ """tasks.tsv rows by id, in file order: id deps difficulty files dwarf qa title."""
42
+ path = Path(plan) / 'tasks.tsv'
43
+ try:
44
+ text = path.read_text()
45
+ except OSError as error:
46
+ raise GroupError('tasks.tsv could not be read: %s' % error.strerror)
47
+ rows = {}
48
+ for number, line in enumerate(text.splitlines(), 1):
49
+ if not line or line.startswith('#'):
50
+ continue
51
+ row = line.split('\t')
52
+ if len(row) != 7:
53
+ raise GroupError('tasks.tsv line %d: needs seven columns, has %d' % (number, len(row)))
54
+ rows[row[0]] = row
55
+ return rows
56
+
57
+
58
+ def _list(value: str) -> list:
59
+ return [item for item in value.split(',') if item and item != '-']
60
+
61
+
62
+ def overlap(a: str, b: str) -> bool:
63
+ """forge-schedule.py's overlap, ported exactly: a declared directory covers the
64
+ paths beneath it, and `.` covers everything. `-` declares nothing."""
65
+ def paths(value: str) -> list:
66
+ return [posixpath.normpath(p) for p in value.split(',') if p and p != '-']
67
+
68
+ return any(
69
+ x == '.' or y == '.' or x == y or x.startswith(y + '/') or y.startswith(x + '/')
70
+ for x in paths(a) for y in paths(b)
71
+ )
72
+
73
+
74
+ # --- groups.tsv ---------------------------------------------------------------
75
+
76
+ def load(plan) -> list:
77
+ path = Path(plan) / 'groups.tsv'
78
+ if not path.is_file():
79
+ return []
80
+ groups = []
81
+ seen = set()
82
+ for number, line in enumerate(path.read_text().splitlines(), 1):
83
+ if not line.strip() or line.startswith('#'):
84
+ continue
85
+ row = line.split('\t')
86
+ where = 'groups.tsv line %d' % number
87
+ if len(row) != 6:
88
+ raise GroupError('%s: needs six columns, has %d' % (where, len(row)))
89
+ gid, review, qa, members, title, goal = row
90
+ if not ID_RE.fullmatch(gid):
91
+ raise GroupError('%s: bad group id %r (use [a-z0-9][a-z0-9-]{0,39})' % (where, gid))
92
+ if gid in seen:
93
+ raise GroupError('%s: duplicate group id %s' % (where, gid))
94
+ seen.add(gid)
95
+ if review not in REVIEWS:
96
+ raise GroupError('%s: review must be task or group, not %r' % (where, review))
97
+ if not qa.strip():
98
+ raise GroupError('%s: qa is empty (use - for none)' % where)
99
+ names = [m.strip() for m in members.split(',')]
100
+ if members.strip() in ('', '-') or any(not m for m in names):
101
+ raise GroupError('%s: members is empty or has an empty entry' % where)
102
+ groups.append(Group(gid, review, qa, tuple(names), title or '-', goal or '-'))
103
+ return groups
104
+
105
+
106
+ def _is_sweep(plan, task: str) -> bool:
107
+ return bool(SWEEP_ID_RE.fullmatch(task)) or (Path(plan) / 'tasks' / task / 'sweep.json').is_file()
108
+
109
+
110
+ def _reaches(tasks: dict, start: str, targets: set):
111
+ """A target task reachable from start through deps (any task, transitively), or None.
112
+ Returns (target, path) where path lists the tasks passed through."""
113
+ stack = [(dep, []) for dep in reversed(_list(tasks[start][1]))]
114
+ seen = {start}
115
+ while stack:
116
+ task, via = stack.pop()
117
+ if task in seen:
118
+ continue
119
+ seen.add(task)
120
+ if task in targets:
121
+ return task, via
122
+ if task in tasks:
123
+ stack.extend((dep, via + [task]) for dep in reversed(_list(tasks[task][1])))
124
+ return None
125
+
126
+
127
+ def validate(plan, groups, max_tasks=6) -> None:
128
+ tasks = _tasks(plan)
129
+ owner = {}
130
+ ids = set()
131
+ for g in groups:
132
+ if g.id in ids:
133
+ raise GroupError('group %s: duplicate group id' % g.id)
134
+ ids.add(g.id)
135
+ for member in g.members:
136
+ if member not in tasks:
137
+ raise GroupError('group %s: member %s is not in tasks.tsv' % (g.id, member))
138
+ if member in owner:
139
+ raise GroupError('group %s: task %s is in two groups (%s and %s)'
140
+ % (g.id, member, owner[member], g.id))
141
+ owner[member] = g.id
142
+ if g.id in tasks:
143
+ raise GroupError('group %s: the id is also a task id' % g.id)
144
+ if g.review != 'group':
145
+ continue
146
+ if len(g.members) < 2:
147
+ raise GroupError('group %s: a review group needs at least 2 members' % g.id)
148
+ if len(g.members) > max_tasks:
149
+ raise GroupError('group %s: %d members, at most %d allowed' % (g.id, len(g.members), max_tasks))
150
+ for member in g.members:
151
+ others = set(g.members) - {member}
152
+ hit = _reaches(tasks, member, others)
153
+ if hit:
154
+ other, via = hit
155
+ how = 'through ' + ', '.join(via) if via else 'directly'
156
+ raise GroupError('group %s: member %s depends on member %s (%s)' % (g.id, member, other, how))
157
+ for i, a in enumerate(g.members):
158
+ for b in g.members[i + 1:]:
159
+ if overlap(tasks[a][3], tasks[b][3]):
160
+ raise GroupError('group %s: members %s and %s declare overlapping files' % (g.id, a, b))
161
+ for member in g.members:
162
+ if _is_sweep(plan, member):
163
+ raise GroupError('group %s: member %s is a sweep task' % (g.id, member))
164
+
165
+
166
+ def derive(plan, review='task', max_tasks=6) -> list:
167
+ """One group per computed wave with at least two tasks (w1, w2, ...). A wave larger
168
+ than max_tasks splits into w3a, w3b, ... in tasks.tsv order. With review='group',
169
+ high-difficulty tasks stay out and keep their own review."""
170
+ if review not in REVIEWS:
171
+ raise GroupError('review must be task or group, not %r' % review)
172
+ if max_tasks < 2:
173
+ raise GroupError('max tasks must be at least 2')
174
+ tasks = _tasks(plan)
175
+ path = Path(plan) / 'waves.tsv'
176
+ try:
177
+ text = path.read_text()
178
+ except OSError as error:
179
+ raise GroupError('waves.tsv could not be read: %s' % error.strerror)
180
+ waves = {}
181
+ for number, line in enumerate(text.splitlines(), 1):
182
+ if not line or line.startswith('#'):
183
+ continue
184
+ row = line.split('\t')
185
+ if len(row) != 2 or not row[0].isdigit() or row[1] not in tasks:
186
+ raise GroupError('waves.tsv line %d: needs wave<TAB>task with a task from tasks.tsv' % number)
187
+ waves.setdefault(int(row[0]), set()).add(row[1])
188
+ groups = []
189
+ for wave in sorted(waves):
190
+ members = [t for t in tasks if t in waves[wave]]
191
+ if review == 'group':
192
+ members = [t for t in members if tasks[t][2] != 'high']
193
+ chunks = [members[i:i + max_tasks] for i in range(0, len(members), max_tasks)]
194
+ for index, chunk in enumerate(chunks):
195
+ if len(chunk) < 2:
196
+ continue
197
+ suffix = chr(ord('a') + index) if len(chunks) > 1 else ''
198
+ # A derived group has a title and no goal: nothing here knows what the wave is for.
199
+ # plan asks for one, and `forge group set` writes it.
200
+ groups.append(Group('w%d%s' % (wave, suffix), review, '-', tuple(chunk), 'Wave %d%s' % (wave, suffix), '-'))
201
+ return groups
202
+
203
+
204
+ def _cell(value: str) -> str:
205
+ value = ' '.join(str(value).split())
206
+ return value or '-'
207
+
208
+
209
+ def write(plan, groups) -> None:
210
+ lines = [HEADER] + ['\t'.join([g.id, g.review, _cell(g.qa), ','.join(g.members),
211
+ _cell(g.title), _cell(g.goal)]) for g in groups]
212
+ _atomic(Path(plan) / 'groups.tsv', '\n'.join(lines) + '\n')
213
+
214
+
215
+ def _atomic(path: Path, text: str) -> None:
216
+ fd, temp = tempfile.mkstemp(dir=str(path.parent), prefix='.' + path.name + '.')
217
+ try:
218
+ # mkstemp makes the file 0600, and os.replace keeps that: give it the mode a plain open would.
219
+ mask = os.umask(0)
220
+ os.umask(mask)
221
+ os.fchmod(fd, 0o666 & ~mask)
222
+ with os.fdopen(fd, 'w') as handle:
223
+ handle.write(text)
224
+ os.replace(temp, path)
225
+ except BaseException:
226
+ try:
227
+ os.unlink(temp)
228
+ except OSError:
229
+ pass
230
+ raise
231
+
232
+
233
+ def resolve_qa(plan, groups) -> list:
234
+ """For review=group with qa `-`: the qa of the member with the highest difficulty
235
+ (high > medium > low, ties to the first listed), as tasks.tsv has it after plan."""
236
+ tasks = _tasks(plan)
237
+ out = []
238
+ for g in groups:
239
+ if g.review == 'group' and g.qa == '-':
240
+ best = None
241
+ for member in g.members:
242
+ if member in tasks and (best is None or RANK.get(tasks[member][2], 0) > RANK.get(tasks[best][2], 0)):
243
+ best = member
244
+ if best is not None:
245
+ g = g._replace(qa=tasks[best][5] or '-')
246
+ out.append(g)
247
+ return out
248
+
249
+
250
+ # --- freeze -------------------------------------------------------------------
251
+
252
+ def freeze_text(plan, groups) -> str:
253
+ """One line per group with all six columns, each followed by one line per member:
254
+ member<TAB>deps<TAB>files. A member's dwarf column is not part of it."""
255
+ tasks = _tasks(plan)
256
+ lines = []
257
+ for g in groups:
258
+ lines.append('\t'.join([g.id, g.review, g.qa, ','.join(g.members), g.title, g.goal]))
259
+ for member in g.members:
260
+ row = tasks.get(member)
261
+ lines.append('\t'.join([member, row[1], row[3]]) if row else '%s\t<missing>\t<missing>' % member)
262
+ return '\n'.join(lines) + '\n' if lines else ''
263
+
264
+
265
+ def fingerprint(plan, groups) -> str:
266
+ return hashlib.sha256(freeze_text(plan, groups).encode()).hexdigest()
267
+
268
+
269
+ def freeze(plan) -> None:
270
+ plan = Path(plan)
271
+ groups = load(plan)
272
+ frozen = plan / 'groups.frozen'
273
+ if not groups:
274
+ try:
275
+ frozen.unlink()
276
+ except FileNotFoundError:
277
+ pass
278
+ return
279
+ _atomic(frozen, fingerprint(plan, groups) + '\n')
280
+
281
+
282
+ def check_frozen(plan):
283
+ """None when groups.tsv and its members still match groups.frozen (or neither
284
+ exists); otherwise the reason."""
285
+ plan = Path(plan)
286
+ frozen = plan / 'groups.frozen'
287
+ try:
288
+ groups = load(plan)
289
+ if not groups:
290
+ return FROZEN_REASON if frozen.exists() else None
291
+ if not frozen.is_file():
292
+ return FROZEN_REASON
293
+ return None if frozen.read_text().strip() == fingerprint(plan, groups) else FROZEN_REASON
294
+ except (GroupError, OSError):
295
+ return FROZEN_REASON
296
+
297
+
298
+ # --- lookups ------------------------------------------------------------------
299
+
300
+ def group_of(plan, task):
301
+ for g in load(plan):
302
+ if task in g.members:
303
+ return g
304
+ return None
305
+
306
+
307
+ def members_in_review_groups(plan) -> set:
308
+ return {m for g in load(plan) if g.review == 'group' for m in g.members}
@@ -0,0 +1,289 @@
1
+ #!/usr/bin/env python3
2
+ """Attribute a group QA reply to the member whose diff each finding belongs to.
3
+
4
+ One group review covers several tasks. Each member has its own file-disjoint diff, and the
5
+ reviewer saw the combined diff. `attribute` sends each finding back to the members that must
6
+ change, so only those members are retried. It parses with forge-contract.py: the same finding
7
+ blocks and the same severity and status the gate would decide. The facts brace
8
+ `{reach=… origin=… evidence=…}` is not a tasks tag; both may be on one bullet.
9
+
10
+ attribute(qa_last_text, members, threshold) -> dict
11
+
12
+ `members` is an ordered list of `(task_id, changed_paths)`. `changed_paths` are the
13
+ repo-relative files that member's own diff changed. A path matches after a leading `./` is
14
+ removed, and no other normalisation: `src/./a.py` does not match `src/a.py`.
15
+
16
+ The dict is `{"findings", "implicated", "ambiguous", "blocking"}`. Each finding is
17
+ `{n, severity, status, file, line, tasks, blocking, ambiguous}`:
18
+
19
+ - `n` is 1-based in the parser's order. `severity` is `P0`–`P3` or null. `status` is the
20
+ parser's CONFIRMED, PLAUSIBLE or UNSTATED.
21
+ - `file` and `line` are, first, the first path a member changed that the block names (its
22
+ `path:line` before a bare mention), matched literally, so an extensionless `Makefile:12`
23
+ counts and `example.com:443` does not beat the file the bullet names. When the block names
24
+ no member's path: the block's first `path:line`, or, when it has none, the first path. `line` is null then. A `path:line` is a path: a slash or an extension, so
25
+ `localhost:8080`, `12:30` and `a:1` are not one. A dotted word earlier in the prose
26
+ (`os.path.join`, `json.loads`, `node.js`) is not that path when a `path:line` follows it.
27
+ - `tasks` is `{tasks=…}` when the bullet has one: comma or space separated, trimmed,
28
+ duplicates dropped, member ids in member order and any other id after them in the order
29
+ written. Otherwise it is every member whose changed paths contain `file`, in member order.
30
+ A present tag with no id (`{tasks=}`, `{tasks= , }`) names nobody and does not fall back
31
+ to the file.
32
+ - `ambiguous` is true when there is no `{tasks=…}` and either there is no file or no member
33
+ changed that file, when `{tasks=…}` names an id that is not a member, and when `{tasks=…}`
34
+ names no id.
35
+ - `blocking` is the gate's per-finding decision at `threshold` (`none` is P3; unset is P2).
36
+ PLAUSIBLE never blocks.
37
+
38
+ `implicated` is the union, in member order, of `tasks` over blocking findings that are not
39
+ ambiguous. `ambiguous` at the top is the `n` of findings that are both blocking and ambiguous.
40
+ `blocking` is true when any finding blocks. Non-blocking findings stay in the list, attributed
41
+ the same way, so a tolerated one can still be written to that member's known issues.
42
+
43
+ python3 scripts/forge_groups/attribute.py --qa-last F --members members.tsv --threshold P2
44
+
45
+ `members.tsv` has one `task<TAB>path` row per changed path. Blank lines and `#` comments are
46
+ ignored. The command prints the JSON and exits 0, or 2 on bad input.
47
+ """
48
+ from __future__ import annotations
49
+
50
+ import argparse
51
+ import importlib.util
52
+ import json
53
+ import re
54
+ import sys
55
+ from pathlib import Path
56
+
57
+ # The contract's facts brace is `{reach=… origin=… evidence=…}`. A tasks tag is its own brace,
58
+ # so a facts group is not read as one even when the two sit on the same line.
59
+ _TASKS_TAG = re.compile(r'\{[ \t]*tasks[ \t]*=[ \t]*([^{}]*)\}', re.IGNORECASE)
60
+ _ID_SPLIT = re.compile(r'[\s,]+')
61
+ # A segment ends on a word character, so a sentence's final dot stays outside the path.
62
+ _SEG = r'[\w+-]+(?:\.[\w+-]+)*'
63
+ # Same shapes as a bare path: a slash, or an extension. Looser than that, and
64
+ # `localhost:8080`, `12:30` and `a:1` beat the file the bullet names.
65
+ _PATH_BODY = (
66
+ r'(?:\./)?' + _SEG + r'(?:/' + _SEG + r')+'
67
+ r'|(?:\./)?' + _SEG + r'\.[A-Za-z][A-Za-z0-9]{0,7}')
68
+ _PATH_LINE = re.compile(r'(?<![\w./])(' + _PATH_BODY + r'):(\d+)')
69
+ _PATH = re.compile(r'(?<![\w./])(' + _PATH_BODY + r')(?![\w:/])')
70
+ _NOT_PATH = {'e.g', 'i.e'}
71
+
72
+ _contract_mod = None
73
+
74
+
75
+ def _contract():
76
+ """forge-contract.py, loaded by path: its file name is not importable."""
77
+ global _contract_mod
78
+ if _contract_mod is None:
79
+ path = Path(__file__).resolve().parents[1] / 'forge-contract.py'
80
+ spec = importlib.util.spec_from_file_location('forge_contract', path)
81
+ module = importlib.util.module_from_spec(spec)
82
+ spec.loader.exec_module(module)
83
+ _contract_mod = module
84
+ return _contract_mod
85
+
86
+
87
+ def norm_path(path: str) -> str:
88
+ """Repo-relative path with a leading `./` removed. `..` and an inner `./` stay."""
89
+ path = str(path).strip().strip('`"\'')
90
+ while path.startswith('./'):
91
+ path = path[2:]
92
+ return path
93
+
94
+
95
+ def _clean_file(path: str) -> str:
96
+ return norm_path(path).rstrip('.')
97
+
98
+
99
+ def _usable(path: str) -> bool:
100
+ return bool(path) and path.lower() not in _NOT_PATH
101
+
102
+
103
+ def _known(text: str, known):
104
+ """(file, line) of the first member-changed path the block names, or None.
105
+
106
+ A path:line of one wins over a bare mention of one, as in `_locate`. Matching the members'
107
+ own paths literally is what lets an extensionless file (`Makefile:12`) count, and keeps a
108
+ host with a port (`example.com:443`) from beating the file the bullet names."""
109
+ with_line = bare = None
110
+ for path in known:
111
+ pattern = re.compile(r'(?<![\w./])(?:\./)?' + re.escape(path) + r'(?::(\d+))?(?!\.?[\w/-])')
112
+ for match in pattern.finditer(text):
113
+ if match.group(1) is not None:
114
+ if with_line is None or match.start() < with_line[0]:
115
+ with_line = (match.start(), path, int(match.group(1)))
116
+ break
117
+ if bare is None or match.start() < bare[0]:
118
+ bare = (match.start(), path, None)
119
+ hit = with_line or bare
120
+ return None if hit is None else hit[1:]
121
+
122
+
123
+ def _locate(text: str, known=()):
124
+ """(file, line) of the first path:line, else the first path, else (None, None).
125
+
126
+ When the block names a path a member changed (`known`), that path is the location
127
+ (see `_known`); the rules below apply only when it names none.
128
+
129
+ A path:line anywhere in the block wins over a bare path, including one that starts
130
+ earlier. `Calls os.path.join badly in src/a.py:3` is `src/a.py` line 3, and `src/a.py:10`
131
+ keeps its line rather than the bare `src/a.py` at the same character. The path:line has
132
+ to be a path, with a slash or an extension: `localhost:8080`, `12:30` and `a:1` are not
133
+ one, so the file named beside them stays the location."""
134
+ hit = _known(text, known)
135
+ if hit is not None:
136
+ return hit
137
+ for match in _PATH_LINE.finditer(text):
138
+ path = _clean_file(match.group(1))
139
+ if _usable(path):
140
+ return path, int(match.group(2))
141
+ for match in _PATH.finditer(text):
142
+ path = _clean_file(match.group(1))
143
+ if _usable(path):
144
+ return path, None
145
+ return None, None
146
+
147
+
148
+ def _split_ids(raw: str) -> list:
149
+ return [part for part in _ID_SPLIT.split(raw.strip()) if part]
150
+
151
+
152
+ def _in_member_order(ids: list, member_ids: list) -> tuple:
153
+ """(ids, ambiguous). Member ids lead, in member order; other ids keep written order."""
154
+ seen = []
155
+ for task_id in ids:
156
+ if task_id not in seen:
157
+ seen.append(task_id)
158
+ known = set(member_ids)
159
+ ordered = [task_id for task_id in member_ids if task_id in seen]
160
+ ordered.extend(task_id for task_id in seen if task_id not in known)
161
+ return ordered, any(task_id not in known for task_id in seen)
162
+
163
+
164
+ def _index(members):
165
+ """(member ids in order, {normalised path: [task ids]})."""
166
+ if isinstance(members, (str, bytes)):
167
+ raise ValueError('members must be a list of (task, paths) pairs')
168
+ order = []
169
+ by_path = {}
170
+ seen = set()
171
+ for item in members:
172
+ if not isinstance(item, (tuple, list)) or len(item) != 2:
173
+ raise ValueError('members must be a list of (task, paths) pairs')
174
+ task, changed = item
175
+ task = str(task).strip()
176
+ if not task:
177
+ raise ValueError('member task id is empty')
178
+ if task not in seen:
179
+ seen.add(task)
180
+ order.append(task)
181
+ if isinstance(changed, (str, bytes)):
182
+ changed = [changed]
183
+ try:
184
+ paths = list(changed)
185
+ except TypeError as error:
186
+ raise ValueError('changed paths for %s must be a list of paths' % task) from error
187
+ for path in paths:
188
+ key = norm_path(path)
189
+ if not key:
190
+ raise ValueError('member %s has an empty path' % task)
191
+ owners = by_path.setdefault(key, [])
192
+ if task not in owners:
193
+ owners.append(task)
194
+ return order, by_path
195
+
196
+
197
+ def attribute(qa_last_text, members, threshold=None) -> dict:
198
+ """Findings of one group QA reply, each attributed to the members that must change."""
199
+ contract = _contract()
200
+ # The gate's threshold rule, checked even when the reply has no findings.
201
+ contract.finding_blocks(contract.Finding('CONFIRMED', None, False, 1, ''), threshold)
202
+ order, by_path = _index(members)
203
+ rows = []
204
+ blocked = False
205
+ wanted = set()
206
+ ambiguous_ns = []
207
+ for number, finding in enumerate(contract.parse_findings(qa_last_text or ''), 1):
208
+ tags = list(_TASKS_TAG.finditer(finding.text))
209
+ file, line = _locate(_TASKS_TAG.sub(' ', finding.text), by_path)
210
+ if not tags:
211
+ if file is None:
212
+ tasks, ambiguous = [], True
213
+ else:
214
+ tasks = list(by_path.get(file, ()))
215
+ ambiguous = not tasks
216
+ else:
217
+ # The last {tasks=…} wins. A tag with no id names nobody: do not fall back to the
218
+ # file, or a blocking finding would skip the member it must escalate as unattributable.
219
+ tasks, ambiguous = _in_member_order(_split_ids(tags[-1].group(1)), order)
220
+ if not tasks:
221
+ ambiguous = True
222
+ blocking = contract.finding_blocks(finding, threshold)
223
+ rows.append({
224
+ 'n': number,
225
+ 'severity': None if finding.severity is None else 'P%d' % finding.severity,
226
+ 'status': finding.status,
227
+ 'file': file,
228
+ 'line': line,
229
+ 'tasks': tasks,
230
+ 'blocking': blocking,
231
+ 'ambiguous': ambiguous,
232
+ })
233
+ if not blocking:
234
+ continue
235
+ blocked = True
236
+ if ambiguous:
237
+ ambiguous_ns.append(number)
238
+ else:
239
+ wanted.update(tasks)
240
+ return {
241
+ 'findings': rows,
242
+ 'implicated': [task for task in order if task in wanted],
243
+ 'ambiguous': ambiguous_ns,
244
+ 'blocking': blocked,
245
+ }
246
+
247
+
248
+ def load_members(text: str) -> list:
249
+ """`(task, [paths])` in first-seen order, from `task<TAB>path` rows."""
250
+ order = []
251
+ paths = {}
252
+ for number, line in enumerate((text or '').splitlines(), 1):
253
+ if not line.strip() or line.lstrip().startswith('#'):
254
+ continue
255
+ if line.count('\t') != 1:
256
+ raise ValueError('members line %d: needs task<TAB>path' % number)
257
+ task, path = (part.strip() for part in line.split('\t'))
258
+ if not task or not path:
259
+ raise ValueError('members line %d: needs task<TAB>path' % number)
260
+ if task not in paths:
261
+ order.append(task)
262
+ paths[task] = []
263
+ paths[task].append(path)
264
+ return [(task, paths[task]) for task in order]
265
+
266
+
267
+ def main(argv=None) -> int:
268
+ parser = argparse.ArgumentParser(
269
+ prog='attribute.py',
270
+ description='Attribute a group QA reply to the member tasks its findings name.')
271
+ parser.add_argument('--qa-last', required=True, metavar='FILE', help='the QA reply')
272
+ parser.add_argument('--members', required=True, metavar='FILE',
273
+ help='rows of task<TAB>path, one changed path per row')
274
+ parser.add_argument('--threshold', default=None,
275
+ help='least severe level that still blocks (default P2; none means P3)')
276
+ args = parser.parse_args(argv)
277
+ try:
278
+ qa = Path(args.qa_last).read_text(encoding='utf-8', errors='replace')
279
+ members = load_members(Path(args.members).read_text(encoding='utf-8', errors='replace'))
280
+ result = attribute(qa, members, args.threshold)
281
+ except (OSError, ValueError) as error:
282
+ sys.stderr.write('attribute: %s\n' % error)
283
+ return 2
284
+ sys.stdout.write(json.dumps(result, indent=2, ensure_ascii=False) + '\n')
285
+ return 0
286
+
287
+
288
+ if __name__ == '__main__':
289
+ sys.exit(main())