@giamme/forge 0.18.0 → 0.19.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 (78) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +16 -2
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +25 -1
  6. package/docs/commands.md +81 -14
  7. package/docs/decomposed-runs.md +114 -1
  8. package/docs/development.md +2 -1
  9. package/docs/forge-ui.md +84 -15
  10. package/docs/memory.md +25 -4
  11. package/docs/models.md +8 -0
  12. package/docs/reviews.md +122 -0
  13. package/forge +20 -3
  14. package/package.json +2 -1
  15. package/references/dataset.md +20 -1
  16. package/references/decompose.md +621 -33
  17. package/references/harnesses.md +18 -3
  18. package/references/planning.md +43 -14
  19. package/references/ui.md +53 -6
  20. package/registry.tsv +8 -3
  21. package/scripts/forge-brief.py +88 -3
  22. package/scripts/forge-compare.py +4 -3
  23. package/scripts/forge-contract.py +202 -27
  24. package/scripts/forge-control.py +117 -5
  25. package/scripts/forge-dispatch.sh +34 -5
  26. package/scripts/forge-group.py +496 -0
  27. package/scripts/forge-groups.py +89 -0
  28. package/scripts/forge-handoff.py +1128 -0
  29. package/scripts/forge-lib-group.sh +641 -0
  30. package/scripts/forge-lib-plans.sh +339 -3
  31. package/scripts/forge-lib-task.sh +197 -4
  32. package/scripts/forge-memory.sh +245 -3
  33. package/scripts/forge-parallel.sh +715 -34
  34. package/scripts/forge-planner.py +104 -8
  35. package/scripts/forge-route.py +190 -12
  36. package/scripts/forge-runs.py +9 -5
  37. package/scripts/forge-schedule.py +354 -45
  38. package/scripts/forge-solo.sh +2 -0
  39. package/scripts/forge-worktrees.py +243 -0
  40. package/scripts/forge_brief/__init__.py +294 -50
  41. package/scripts/forge_brief/answers.py +58 -11
  42. package/scripts/forge_brief/proposals.py +1630 -0
  43. package/scripts/forge_dataset/efforts.py +4 -3
  44. package/scripts/forge_dataset/export.py +24 -12
  45. package/scripts/forge_dataset/facts.py +5 -3
  46. package/scripts/forge_dataset/forecast.py +8 -18
  47. package/scripts/forge_dataset/harvest.py +204 -9
  48. package/scripts/forge_dataset/history.py +11 -6
  49. package/scripts/forge_dataset/importer.py +65 -1
  50. package/scripts/forge_dataset/names.py +66 -0
  51. package/scripts/forge_dataset/reviewers.py +5 -2
  52. package/scripts/forge_dataset/risk.py +6 -3
  53. package/scripts/forge_dataset/routing.py +6 -1
  54. package/scripts/forge_groups/__init__.py +308 -0
  55. package/scripts/forge_groups/attribute.py +289 -0
  56. package/scripts/forge_groups/review.py +286 -0
  57. package/scripts/forge_owner.py +152 -0
  58. package/scripts/forge_side/__init__.py +12 -7
  59. package/ui/docs/api.md +173 -17
  60. package/ui/forge_ui/control.py +361 -2
  61. package/ui/forge_ui/executions.py +8 -1
  62. package/ui/forge_ui/export.py +31 -4
  63. package/ui/forge_ui/groups.py +264 -0
  64. package/ui/forge_ui/models.py +70 -8
  65. package/ui/forge_ui/reader.py +262 -19
  66. package/ui/forge_ui/server.py +4 -0
  67. package/ui/forge_ui/static/app.js +93 -13
  68. package/ui/forge_ui/static/briefview.js +350 -47
  69. package/ui/forge_ui/static/diffview.js +86 -1
  70. package/ui/forge_ui/static/groupsview.js +332 -0
  71. package/ui/forge_ui/static/index.html +1 -0
  72. package/ui/forge_ui/static/panel.js +127 -7
  73. package/ui/forge_ui/static/projectsview.js +189 -10
  74. package/ui/forge_ui/static/runmodel.js +14 -3
  75. package/ui/forge_ui/static/storageview.js +91 -10
  76. package/ui/forge_ui/static/style.css +79 -5
  77. package/ui/forge_ui/static/worktreesview.js +233 -12
  78. package/ui/forge_ui/storage.py +14 -0
@@ -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())
@@ -0,0 +1,286 @@
1
+ #!/usr/bin/env python3
2
+ """The text side of one group review (#140): the prompt, the decision files, the round's facts.
3
+
4
+ forge-lib-group.sh builds the candidate and dispatches the reviewer; this prints what the reviewer
5
+ reads and what a person reads when the round stops for a decision. Stdlib only.
6
+
7
+ python3 -I scripts/forge_groups/review.py prompt PLAN GID [--threshold P2]
8
+ python3 -I scripts/forge_groups/review.py decision PLAN GID oversized --size BYTES --limit KB
9
+ python3 -I scripts/forge_groups/review.py decision PLAN GID ambiguous --attribution FILE
10
+ python3 -I scripts/forge_groups/review.py facts ATTRIBUTION_JSON
11
+
12
+ `prompt` reads, under the plan and `groups/GID/`: groups.tsv, tasks.tsv, each member's task dir, the
13
+ group's `candidate.base`, `candidate.commit`, `members.tsv` and `round`, and the combined diff in
14
+ `combined.diff` (computed from the repository when absent). `facts` prints one line:
15
+ implicated<TAB>ambiguous<TAB>findings<TAB>blocking, the two lists comma separated or `-`.
16
+ Exit 0, or 2 on bad input with the reason on stderr.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import json
22
+ import subprocess
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
27
+ import forge_groups # noqa: E402
28
+ from forge_groups import attribute # noqa: E402
29
+
30
+
31
+ class ReviewError(Exception):
32
+ """Bad input; the message is one line."""
33
+
34
+
35
+ def _read(path: Path) -> str:
36
+ try:
37
+ return path.read_text(encoding='utf-8', errors='replace')
38
+ except OSError:
39
+ return ''
40
+
41
+
42
+ def _git(repo: str, *args) -> str:
43
+ done = subprocess.run(['git', '-C', repo, '-c', 'core.quotepath=off', *args],
44
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False)
45
+ if done.returncode != 0:
46
+ raise ReviewError('git %s failed' % ' '.join(args[:2]))
47
+ return done.stdout.decode('utf-8', 'replace')
48
+
49
+
50
+ def _group(plan: Path, gid: str):
51
+ for group in forge_groups.load(plan):
52
+ if group.id == gid:
53
+ return group
54
+ raise ReviewError('%s is not a group of %s' % (gid, plan))
55
+
56
+
57
+ def _tasks(plan: Path) -> dict:
58
+ return forge_groups._tasks(plan)
59
+
60
+
61
+ def _rows(path: Path) -> list:
62
+ """members.tsv rows as (round, task, commit, attempt)."""
63
+ rows = []
64
+ for line in _read(path).splitlines():
65
+ parts = line.split('\t')
66
+ if len(parts) == 4 and parts[0].isdigit():
67
+ rows.append((int(parts[0]), parts[1], parts[2], parts[3]))
68
+ return rows
69
+
70
+
71
+ def _round(gdir: Path) -> int:
72
+ text = _read(gdir / 'round').strip()
73
+ return int(text) if text.isdigit() else 1
74
+
75
+
76
+ def _attribution(gdir: Path):
77
+ try:
78
+ data = json.loads(_read(gdir / 'attribution.json'))
79
+ except ValueError:
80
+ return None
81
+ return data if isinstance(data, dict) and isinstance(data.get('findings'), list) else None
82
+
83
+
84
+ def _finding_text(finding: dict, blocks: dict) -> str:
85
+ text = blocks.get(finding.get('n'))
86
+ if text:
87
+ return text.strip('\n')
88
+ where = finding.get('file') or 'no file'
89
+ if finding.get('line'):
90
+ where += ':%s' % finding['line']
91
+ return '- [%s][%s] %s' % (finding.get('severity') or '?', finding.get('status') or '?', where)
92
+
93
+
94
+ def _earlier(gdir: Path):
95
+ """The findings of the last reviewed round: (round, rows, {n: text}), or None."""
96
+ data = _attribution(gdir)
97
+ if not data or not isinstance(data.get('round'), int) or data['round'] >= _round(gdir):
98
+ return None
99
+ reply = _read(gdir / ('qa.round-%d.last' % data['round']))
100
+ blocks = {number: finding.text for number, finding in
101
+ enumerate(attribute._contract().parse_findings(reply), 1)}
102
+ return data['round'], [f for f in data['findings'] if isinstance(f, dict)], blocks
103
+
104
+
105
+ def _stat(repo: str, base: str, commit: str) -> str:
106
+ try:
107
+ return _git(repo, 'diff', '--stat', base, commit, '--', '.', ':(exclude).forge').rstrip('\n')
108
+ except ReviewError:
109
+ return '(the diff stat could not be read)'
110
+
111
+
112
+ def _member(plan: Path, repo: str, task: str, row: list, gdir: Path, current: int, earlier, history: dict) -> list:
113
+ tdir = plan / 'tasks' / task
114
+ commit = _read(tdir / 'reviewed.commit').strip()
115
+ base = _read(tdir / 'base_ref').strip()
116
+ out = ['## Task %s: %s' % (task, row[6] if len(row) > 6 else task), '', _read(tdir / 'prompt.md').rstrip('\n')]
117
+ approach = _read(tdir / 'approach.md').strip('\n')
118
+ if approach:
119
+ out += ['', 'Intended approach:', approach]
120
+ out += ['', 'Files this task declared it would touch: %s' % (row[3] if len(row) > 3 else '-'),
121
+ 'Reviewed commit: %s' % commit]
122
+ if base and commit:
123
+ out += ['Its own diff against its base (%s):' % base[:7], _stat(repo, base, commit)]
124
+ # The same wording the task review uses, so a reviewer reads one vocabulary.
125
+ prereview = _read(tdir / 'prereview.txt').rstrip('\n')
126
+ if prereview.strip():
127
+ out += ['', prereview]
128
+ guard = [line for line in _read(tdir / 'guard.txt').splitlines() if line.strip()]
129
+ if guard:
130
+ out += ['', 'Implementer guard notes (observed by forge, not claimed by the implementer):']
131
+ out += [' - ' + line for line in guard]
132
+ out += ["A promise of later work means a check may never have run; judge the diff on its own merits."]
133
+ drift = [line for line in _read(tdir / 'drift.txt').splitlines() if line.strip()]
134
+ if drift:
135
+ out += ['', 'Scope note: this task declared it would touch %s, and the' % (row[3] if len(row) > 3 else '-'),
136
+ 'diff also changes files it did not declare:']
137
+ out += [' - ' + line for line in drift]
138
+ out += ['That is not automatically wrong — judge whether each was actually necessary. It',
139
+ 'matters because another task may own those files.']
140
+ if earlier:
141
+ number, findings, blocks = earlier
142
+ mine = [f for f in findings if task in (f.get('tasks') or [])]
143
+ if mine:
144
+ out += ['', "Round %d findings attributed to this task (check each one against the code now):" % number]
145
+ for finding in mine:
146
+ out += [_finding_text(finding, blocks)]
147
+ previous = history.get(task)
148
+ now = history.get((task, current))
149
+ if previous is not None and now is not None and previous != now:
150
+ reply = _read(tdir / 'dwarf.last').strip('\n')
151
+ out += ['', 'This task was reworked since round %d (attempt %s, then attempt %s).' % (number, previous, now)]
152
+ if reply:
153
+ out += ["The implementer's reply for the new attempt, to check against the code:", reply]
154
+ return out
155
+
156
+
157
+ def _combined(repo: str, gdir: Path, base: str, commit: str) -> str:
158
+ text = _read(gdir / 'combined.diff')
159
+ if text:
160
+ return text
161
+ return _git(repo, 'diff', '--binary', '--irreversible-delete', base, commit, '--', '.', ':(exclude).forge')
162
+
163
+
164
+ def prompt(plan: Path, gid: str, threshold) -> str:
165
+ group = _group(plan, gid)
166
+ tasks = _tasks(plan)
167
+ repo = _read(plan / 'repo').strip()
168
+ gdir = plan / 'groups' / gid
169
+ base = _read(gdir / 'candidate.base').strip()
170
+ commit = _read(gdir / 'candidate.commit').strip()
171
+ if not base or not commit:
172
+ raise ReviewError('group %s has no candidate yet' % gid)
173
+ current = _round(gdir)
174
+ rows = _rows(gdir / 'members.tsv')
175
+ history = {}
176
+ for number, task, _, attempt in rows:
177
+ if number < current:
178
+ history[task] = attempt # the last round before this one that held the task
179
+ elif number == current:
180
+ history[(task, current)] = attempt
181
+ earlier = _earlier(gdir)
182
+ contract = attribute._contract()
183
+ out = [contract.qa_text('head', 'group').rstrip('\n'), '']
184
+ out += ['# Group %s: %s' % (gid, group.title if group.title != '-' else gid)]
185
+ if group.goal != '-':
186
+ out += ['', 'Goal of the group: %s' % group.goal]
187
+ out += ['', 'Members, in merge order: %s.' % ', '.join(group.members), '']
188
+ if earlier:
189
+ number, findings, blocks = earlier
190
+ loose = [f for f in findings if not f.get('tasks')]
191
+ if loose:
192
+ out += ['## Round %d findings that named no task' % number]
193
+ out += [_finding_text(f, blocks) for f in loose] + ['']
194
+ for task in group.members:
195
+ out += _member(plan, repo, task, tasks.get(task, []), gdir, current, earlier, history) + ['']
196
+ out += [contract.qa_text('tail', 'group', threshold).rstrip('\n'), '']
197
+ out += ['```diff', _combined(repo, gdir, base, commit).rstrip('\n'), '```']
198
+ return '\n'.join(out) + '\n'
199
+
200
+
201
+ def decision(plan: Path, gid: str, reason: str, size: int, limit: int, attribution: str) -> str:
202
+ gdir = plan / 'groups' / gid
203
+ lines = ['reasons: %s' % reason, '']
204
+ if reason == 'oversized':
205
+ lines += [
206
+ 'Group %s was not reviewed: its combined diff is %d bytes (%.1f KB), over the limit of %d KB'
207
+ % (gid, size, size / 1024.0, limit),
208
+ '(group_max_diff_kb in the plan). Nothing was dispatched, truncated or re-routed.',
209
+ '',
210
+ 'Choices:',
211
+ ' split the group: edit %s/groups.tsv so its members form smaller groups, then run plan again' % plan,
212
+ ' review each task alone: set the review of %s to `task` in %s/groups.tsv, then run plan again' % (gid, plan),
213
+ ]
214
+ else:
215
+ try:
216
+ data = json.loads(_read(Path(attribution)))
217
+ except ValueError:
218
+ data = None
219
+ wanted = set((data or {}).get('ambiguous') or [])
220
+ reply = _read(gdir / 'qa.last')
221
+ blocks = {number: finding.text for number, finding in
222
+ enumerate(attribute._contract().parse_findings(reply), 1)}
223
+ lines += ['Group %s stopped for your decision: the reviewer reported a blocking finding that names no' % gid,
224
+ 'member task (no file of any member, or a task id outside the group), so forge cannot tell',
225
+ 'which task has to change. Nothing retried.', '', 'Ambiguous blocking findings:']
226
+ for finding in (data or {}).get('findings') or []:
227
+ if finding.get('n') in wanted:
228
+ lines += ['', _finding_text(finding, blocks)]
229
+ lines += ['', 'The full review is in %s/qa.last.' % gdir, '',
230
+ 'Choices:',
231
+ ' name the task: answer with the member task id(s) each finding belongs to, then review again',
232
+ ' review each task alone: set the review of %s to `task` in %s/groups.tsv, then run plan again' % (gid, plan)]
233
+ return '\n'.join(lines) + '\n'
234
+
235
+
236
+ def facts(path: str) -> str:
237
+ try:
238
+ data = json.loads(_read(Path(path)))
239
+ except ValueError:
240
+ data = None
241
+ if not isinstance(data, dict):
242
+ raise ReviewError('%s is not an attribution' % path)
243
+
244
+ def listed(values):
245
+ return ','.join(str(v) for v in values) if values else '-'
246
+
247
+ return '%s\t%s\t%d\t%d' % (listed(data.get('implicated')), listed(data.get('ambiguous')),
248
+ len(data.get('findings') or []), 1 if data.get('blocking') else 0)
249
+
250
+
251
+ def main(argv=None) -> int:
252
+ parser = argparse.ArgumentParser(prog='review.py', description=__doc__.split('\n')[0])
253
+ sub = parser.add_subparsers(dest='command', required=True)
254
+ p = sub.add_parser('prompt')
255
+ p.add_argument('plan')
256
+ p.add_argument('gid')
257
+ p.add_argument('--threshold', default=None)
258
+ d = sub.add_parser('decision')
259
+ d.add_argument('plan')
260
+ d.add_argument('gid')
261
+ d.add_argument('reason', choices=('oversized', 'ambiguous'))
262
+ d.add_argument('--size', type=int, default=0)
263
+ d.add_argument('--limit', type=int, default=0)
264
+ d.add_argument('--attribution', default='')
265
+ f = sub.add_parser('facts')
266
+ f.add_argument('attribution')
267
+ args = parser.parse_args(argv)
268
+ try:
269
+ if args.command == 'facts':
270
+ text = facts(args.attribution) + '\n'
271
+ else:
272
+ plan = Path(args.plan)
273
+ if args.command == 'prompt':
274
+ text = prompt(plan, args.gid, args.threshold)
275
+ else:
276
+ _group(plan, args.gid)
277
+ text = decision(plan, args.gid, args.reason, args.size, args.limit, args.attribution)
278
+ except (ReviewError, forge_groups.GroupError, ValueError) as error:
279
+ sys.stderr.write('review: %s\n' % ' '.join(str(error).split()))
280
+ return 2
281
+ sys.stdout.write(text)
282
+ return 0
283
+
284
+
285
+ if __name__ == '__main__':
286
+ sys.exit(main())