@giamme/forge 0.19.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.
@@ -0,0 +1,441 @@
1
+ """Approve or reject one proposal of a triage (#161).
2
+
3
+ `apply` is the only writer of what a triage proposed. An approval names the proposal's hash: the
4
+ hash is recomputed from `proposals.json`, so a proposal that changed after the person read it is
5
+ refused. The effect goes through the finding record (`store`), with the actor `triage`; the person
6
+ who asked is kept in the proposal's `decided`. A `plan` proposal becomes a plan dir that
7
+ `forge-planner.py parse` has accepted; nothing is dispatched and GitHub is never contacted.
8
+
9
+ The whole of one apply (checks, effect, bookkeeping) runs under a lock file in the triage dir, so two
10
+ approvals of one proposal cannot both apply. Any failure leaves the proposal `pending`. The record
11
+ change and the `proposals.json` write happen under one store lock, and the record is put back when that
12
+ write fails; a failure before the record changes (a refusal, a planner error) leaves it untouched.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ import re
19
+ import shlex
20
+ import shutil
21
+ import subprocess
22
+ import sys
23
+ import tempfile
24
+ from pathlib import Path
25
+
26
+ SCRIPTS = Path(__file__).resolve().parent.parent
27
+ if str(SCRIPTS) not in sys.path:
28
+ sys.path.insert(0, str(SCRIPTS))
29
+
30
+ import forge_identity # noqa: E402
31
+ import forge_side # noqa: E402
32
+ from forge_findings import store, triage # noqa: E402
33
+
34
+ LOCK_NAME = ".apply.lock"
35
+ MAX_REASON = 500
36
+ PLANNER_TIMEOUT = 120
37
+ PID_RE = re.compile(r"p[0-9]+\Z")
38
+ COMMIT_RE = re.compile(r"[0-9a-f]{7,40}\Z")
39
+ ACTOR = "triage"
40
+ PARALLEL = "bash scripts/forge-parallel.sh"
41
+
42
+
43
+ class Refused(Exception):
44
+ """Exit 3. The proposal is not applied; nothing changed."""
45
+
46
+
47
+ class Failed(Exception):
48
+ """Exit 1. The effect could not be carried out; the proposal stays pending."""
49
+
50
+
51
+ # --- the proposal ---------------------------------------------------------------------------------
52
+
53
+ def _load(ident, n, pid):
54
+ """`(dir, data, proposal)` of one proposal. Refused for an unknown triage, file or proposal id."""
55
+ if not isinstance(pid, str) or PID_RE.fullmatch(pid) is None:
56
+ raise Refused(f"{pid!r} is not a proposal id (p1, p2, ...)")
57
+ found = triage.triage_dir(ident["key"], n)
58
+ if found is None:
59
+ raise Refused(f"no triage {n}")
60
+ dest = found[1]
61
+ data = triage.read_json(dest / "proposals.json")
62
+ if not isinstance(data, dict) or not isinstance(data.get("proposals"), list):
63
+ state = triage.read_state(dest) or {}
64
+ raise Refused(f"triage {n} has no proposals ({state.get('state', 'no state')})")
65
+ for item in data["proposals"]:
66
+ if isinstance(item, dict) and item.get("id") == pid:
67
+ return dest, data, item
68
+ raise Refused(f"triage {n} has no proposal {pid}")
69
+
70
+
71
+ def _require_pending(n, pid, proposal):
72
+ if proposal.get("state") != "pending":
73
+ raise Refused(f"{pid} of triage {n} is {proposal.get('state')}, not pending")
74
+
75
+
76
+ def _fps(proposal):
77
+ """Every fingerprint a proposal names, in order, each once."""
78
+ kind = proposal.get("kind")
79
+ if kind in ("duplicate", "fixed"):
80
+ names = [proposal.get("fp")]
81
+ if kind == "duplicate":
82
+ names.append(proposal.get("of"))
83
+ else:
84
+ names = proposal.get("fps")
85
+ if not isinstance(names, list):
86
+ raise Refused(f"{proposal.get('id')}: fps must be a list")
87
+ for name in names:
88
+ if not isinstance(name, str):
89
+ raise Refused(f"{proposal.get('id')}: {name!r} is not a fingerprint")
90
+ return list(dict.fromkeys(names))
91
+
92
+
93
+ def _text(proposal, name):
94
+ value = proposal.get(name)
95
+ if not isinstance(value, str) or not value.strip():
96
+ raise Refused(f"{proposal.get('id')}: {name} must be a non-empty string")
97
+ return value
98
+
99
+
100
+ def _check_known(proposal, rows):
101
+ known = {row.get("fp") for row in rows if isinstance(row, dict)}
102
+ for fp in _fps(proposal):
103
+ if fp not in known:
104
+ raise Refused(f"{fp}: not a finding of this repository now")
105
+ if proposal.get("kind") == "duplicate" and proposal.get("fp") == proposal.get("of"):
106
+ raise Refused(f"{proposal.get('fp')}: a finding cannot be a duplicate of itself")
107
+
108
+
109
+ # --- the effects ----------------------------------------------------------------------------------
110
+
111
+ def _call(fn):
112
+ try:
113
+ return fn()
114
+ except store.Invalid as exc:
115
+ raise Refused(str(exc)) from exc
116
+ except store.Busy as exc:
117
+ raise Refused(str(exc)) from exc
118
+ except store.Corrupt as exc:
119
+ raise Failed(str(exc)) from exc
120
+
121
+
122
+ def _cut(text):
123
+ return text[:MAX_REASON]
124
+
125
+
126
+ def _effect_duplicate(ident, proposal, locked=False):
127
+ fp, of = proposal["fp"], proposal["of"]
128
+ return _call(lambda: store.update(
129
+ ident, [fp], ACTOR, locked=locked, status="duplicate", duplicate_of=of,
130
+ reason=_cut(_text(proposal, "why"))))
131
+
132
+
133
+ def _effect_fixed(ident, proposal, locked=False):
134
+ fields = {"reason": _cut(_text(proposal, "evidence"))}
135
+ commit = proposal.get("commit")
136
+ if isinstance(commit, str) and COMMIT_RE.fullmatch(commit):
137
+ fields["commit"] = commit
138
+ return _call(lambda: store.set_status(ident, [proposal["fp"]], "fixed", ACTOR, locked=locked, **fields))
139
+
140
+
141
+ def _effect_tag(ident, proposal, locked=False):
142
+ tags = proposal.get("tags")
143
+ if not isinstance(tags, list) or not tags or not all(isinstance(tag, str) for tag in tags):
144
+ raise Refused(f"{proposal.get('id')}: tags must be a list of tags")
145
+ # add_tags cannot be told the lock is already held
146
+ return _call(lambda: store.update(ident, _fps(proposal), ACTOR, locked=locked, add_tags=list(tags)))
147
+
148
+
149
+ def _effect_issue(ident, proposal, locked=False):
150
+ draft = {"title": _text(proposal, "title"), "body": _text(proposal, "body")}
151
+ return _call(lambda: store.update(
152
+ ident, _fps(proposal), ACTOR, locked=locked, status="to-file", draft=draft))
153
+
154
+
155
+ def _place(row):
156
+ file = row.get("file") if isinstance(row.get("file"), str) else ""
157
+ line = row.get("line")
158
+ if file and isinstance(line, int) and not isinstance(line, bool):
159
+ return f"{file}:{line}"
160
+ return file or "-"
161
+
162
+
163
+ def _request_text(proposal, dest, rows):
164
+ """The proposal's request, then its findings as the triage saw them (findings.json), else as they are now."""
165
+ seen = triage.read_json(Path(dest) / "findings.json")
166
+ by_fp = {}
167
+ for source in ((seen.get("findings") if isinstance(seen, dict) else None) or [], rows):
168
+ for row in source:
169
+ if isinstance(row, dict) and isinstance(row.get("fp"), str):
170
+ by_fp.setdefault(row["fp"], row)
171
+ lines = []
172
+ for fp in _fps(proposal):
173
+ row = by_fp.get(fp, {})
174
+ summary = " ".join(str(row.get("summary") or row.get("text") or "").split())
175
+ lines.append(f"- {fp} [{row.get('severity') or '-'}] {_place(row)}" + (f" — {summary}" if summary else ""))
176
+ return _text(proposal, "request").rstrip("\n") + "\n\n## Findings\n\n" + "\n".join(lines) + "\n"
177
+
178
+
179
+ def default_plan_dir(ident, n, pid) -> Path:
180
+ try:
181
+ root = forge_side._state_root()
182
+ except ValueError as exc:
183
+ raise Failed(str(exc)) from exc
184
+ return root / "forge" / "plans" / ident["key"] / f"triage-{n}-{pid}"
185
+
186
+
187
+ def _existing_checkout(ident):
188
+ for candidate in forge_identity.checkouts(ident):
189
+ if candidate and os.path.isdir(candidate):
190
+ return candidate
191
+ checkout = ident.get("checkout")
192
+ return checkout if isinstance(checkout, str) and checkout else ident.get("root") or "."
193
+
194
+
195
+ def _make_plan(proposal, plan_dir, dest, rows):
196
+ """request.md, then the planner's parse. Raises Refused (planner refusal) or Failed."""
197
+ plan = proposal.get("plan")
198
+ if not isinstance(plan, dict):
199
+ raise Refused(f"{proposal.get('id')}: plan must be an object")
200
+ request = _request_text(proposal, dest, rows)
201
+ try:
202
+ reply = "```forge-plan\n" + json.dumps(plan, ensure_ascii=True) + "\n```\n"
203
+ except (TypeError, ValueError) as exc:
204
+ raise Refused(f"{proposal.get('id')}: the plan cannot be written: {exc}") from exc
205
+ try:
206
+ (plan_dir / "request.md").write_text(request, encoding="utf-8")
207
+ except (OSError, UnicodeError) as exc:
208
+ raise Failed(f"cannot write {plan_dir / 'request.md'}: {exc}") from exc
209
+ scratch = tempfile.mkdtemp(prefix="forge-triage-reply-")
210
+ try:
211
+ reply_path = Path(scratch) / "reply.md"
212
+ reply_path.write_text(reply, encoding="utf-8")
213
+ try:
214
+ done = subprocess.run(
215
+ [sys.executable, str(triage.PLANNER), "parse", "--plan", str(plan_dir), "--reply", str(reply_path)],
216
+ capture_output=True, text=True, timeout=PLANNER_TIMEOUT)
217
+ except (OSError, subprocess.TimeoutExpired) as exc:
218
+ raise Failed(f"the planner did not run: {exc}") from exc
219
+ finally:
220
+ shutil.rmtree(scratch, ignore_errors=True)
221
+ if done.returncode == 4:
222
+ reason = " ".join((done.stdout or "").splitlines()[:1]) or "the planner refused the plan"
223
+ raise Refused(reason)
224
+ if done.returncode != 0:
225
+ message = " ".join((done.stderr or done.stdout or "").split())[:300]
226
+ raise Failed(f"the planner failed ({done.returncode}): {message}")
227
+
228
+
229
+ def _create_dir(plan_dir):
230
+ """Make the plan dir; Refused when it exists. Its parents may be created and are kept."""
231
+ if os.path.lexists(plan_dir):
232
+ raise Refused(f"{plan_dir} exists")
233
+ try:
234
+ plan_dir.parent.mkdir(parents=True, exist_ok=True)
235
+ os.mkdir(plan_dir)
236
+ except FileExistsError as exc:
237
+ raise Refused(f"{plan_dir} exists") from exc
238
+ except OSError as exc:
239
+ raise Failed(f"cannot create {plan_dir}: {exc.strerror or exc}") from exc
240
+
241
+
242
+ def _effect_plan(ident, proposal, dest, rows, n, pid, plan_dir):
243
+ """The plan dir. Removed here when the planner fails; the caller removes it when the apply does not stick."""
244
+ target = Path(plan_dir) if plan_dir else default_plan_dir(ident, n, pid)
245
+ if not target.is_absolute():
246
+ target = Path(os.path.abspath(target))
247
+ _create_dir(target)
248
+ try:
249
+ _make_plan(proposal, target, dest, rows)
250
+ except BaseException:
251
+ shutil.rmtree(target, ignore_errors=True)
252
+ raise
253
+ return target
254
+
255
+
256
+ def _note_fresh(ident, proposal, note):
257
+ """Set `note` on findings that still have none. The caller holds `store.lock` across this read and write."""
258
+ fresh = [fp for fp in _fps(proposal) if not ((store.get(ident, fp) or {}).get("note"))]
259
+ if not fresh:
260
+ return []
261
+ return store.update(ident, fresh, ACTOR, locked=True, note=note)
262
+
263
+
264
+ # --- bookkeeping ----------------------------------------------------------------------------------
265
+
266
+ def _record_files(ident):
267
+ record = store.record_path(ident)
268
+ return record, record.with_name(record.name.removesuffix(".json") + ".log.jsonl")
269
+
270
+
271
+ def _capture(ident):
272
+ """`(record bytes or None, log size or None)`, to put back if proposals.json cannot be written."""
273
+ record, log = _record_files(ident)
274
+ try:
275
+ data = record.read_bytes()
276
+ except FileNotFoundError:
277
+ data = None
278
+ try:
279
+ size = log.stat().st_size
280
+ except FileNotFoundError:
281
+ size = None
282
+ return data, size
283
+
284
+
285
+ def _put_bytes(path, data):
286
+ path = Path(path)
287
+ fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
288
+ try:
289
+ view = memoryview(data)
290
+ while view:
291
+ view = view[os.write(fd, view):]
292
+ os.fsync(fd)
293
+ os.close(fd)
294
+ fd = -1
295
+ os.replace(tmp, path)
296
+ except BaseException:
297
+ if fd >= 0:
298
+ os.close(fd)
299
+ try:
300
+ os.unlink(tmp)
301
+ except OSError:
302
+ pass
303
+ raise
304
+
305
+
306
+ def _restore(ident, captured):
307
+ """Put the record and its log back to `_capture`. The caller holds `store.lock`."""
308
+ data, size = captured
309
+ record, log = _record_files(ident)
310
+ if data is None:
311
+ try:
312
+ record.unlink()
313
+ except FileNotFoundError:
314
+ pass
315
+ else:
316
+ _put_bytes(record, data)
317
+ if size is None:
318
+ try:
319
+ log.unlink()
320
+ except FileNotFoundError:
321
+ pass
322
+ return
323
+ fd = os.open(log, os.O_WRONLY | os.O_NOFOLLOW)
324
+ try:
325
+ os.ftruncate(fd, size)
326
+ finally:
327
+ os.close(fd)
328
+
329
+
330
+ def _effect(ident, proposal, kind, target):
331
+ """The record change. The caller holds `store.lock`."""
332
+ if kind == "duplicate":
333
+ return _effect_duplicate(ident, proposal, locked=True)
334
+ if kind == "fixed":
335
+ return _effect_fixed(ident, proposal, locked=True)
336
+ if kind == "tag":
337
+ return _effect_tag(ident, proposal, locked=True)
338
+ if kind == "issue":
339
+ return _effect_issue(ident, proposal, locked=True)
340
+ return _note_fresh(ident, proposal, f"in plan {target}")
341
+
342
+
343
+ def _commit(ident, dest, data, proposal, actor, kind, target, nxt):
344
+ """Write the effect and mark the proposal applied, or leave both as they were.
345
+
346
+ One store lock covers a plan's "no note yet" read and the note write, so a note set in
347
+ between cannot be overwritten. The record is put back when proposals.json cannot be written.
348
+ """
349
+ def run():
350
+ with store.lock(ident):
351
+ captured = _capture(ident)
352
+ changed = _effect(ident, proposal, kind, target)
353
+ out = {}
354
+ if target is not None:
355
+ out["plan_dir"] = str(target)
356
+ out["next"] = nxt
357
+ try:
358
+ _decide(dest, data, proposal, "applied", actor, plan_dir=out.get("plan_dir"))
359
+ except OSError as exc:
360
+ proposal["state"] = "pending"
361
+ proposal.pop("decided", None)
362
+ proposal.pop("plan_dir", None)
363
+ _restore(ident, captured)
364
+ path = Path(dest) / "proposals.json"
365
+ raise Failed(f"cannot write {path}: {exc.strerror or exc}") from exc
366
+ return changed, out
367
+ return _call(run)
368
+
369
+
370
+ def _decide(dest, data, proposal, state, actor, reason=None, plan_dir=None):
371
+ decided = {"at": triage.now(), "actor": actor}
372
+ if reason:
373
+ decided["reason"] = reason
374
+ proposal["state"] = state
375
+ proposal["decided"] = decided
376
+ if plan_dir is not None:
377
+ proposal["plan_dir"] = str(plan_dir)
378
+ triage.write_json(Path(dest) / "proposals.json", data)
379
+
380
+
381
+ def apply(ident, n, pid, approve, rows_fn, actor="cli", plan_dir=None):
382
+ """Apply one proposal. `rows_fn()` returns the current `forge findings show --json` rows.
383
+
384
+ Returns `{"proposal", "changed", "plan_dir"?, "next"?}`. Raises Refused or Failed.
385
+ """
386
+ found = triage.triage_dir(ident["key"], n)
387
+ if found is None:
388
+ raise Refused(f"no triage {n}")
389
+ try:
390
+ gate = triage._Lock(found[1] / LOCK_NAME)
391
+ gate.__enter__()
392
+ except OSError as exc:
393
+ raise Failed(f"cannot lock {found[1]}: {exc.strerror or exc}") from exc
394
+ try:
395
+ dest, data, proposal = _load(ident, n, pid)
396
+ _require_pending(n, pid, proposal)
397
+ if not isinstance(approve, str) or approve != triage.proposal_hash(proposal):
398
+ raise Refused(f"{pid}: the hash does not match the proposal as it is now; read it again")
399
+ rows = rows_fn()
400
+ _check_known(proposal, rows)
401
+ kind = proposal.get("kind")
402
+ if kind not in ("duplicate", "fixed", "tag", "issue", "plan"):
403
+ raise Refused(f"{pid}: unknown kind {kind!r}")
404
+ target = None
405
+ try:
406
+ nxt = None
407
+ if kind == "plan":
408
+ target = _effect_plan(ident, proposal, dest, rows, n, pid, plan_dir)
409
+ nxt = f"{PARALLEL} plan {shlex.quote(str(target))} --repo {shlex.quote(_existing_checkout(ident))}"
410
+ changed, out = _commit(ident, dest, data, proposal, actor, kind, target, nxt)
411
+ except BaseException:
412
+ if target is not None:
413
+ shutil.rmtree(target, ignore_errors=True)
414
+ raise
415
+ return {"proposal": proposal, "changed": [fp for fp, _before, _after in changed], **out}
416
+ finally:
417
+ gate.__exit__(None, None, None)
418
+
419
+
420
+ def reject(ident, n, pid, actor="cli", reason=None):
421
+ """Mark one pending proposal rejected. Returns `{"proposal", "changed": []}`."""
422
+ if reason is not None and len(reason) > MAX_REASON:
423
+ raise Refused(f"--reason must be at most {MAX_REASON} characters")
424
+ found = triage.triage_dir(ident["key"], n)
425
+ if found is None:
426
+ raise Refused(f"no triage {n}")
427
+ try:
428
+ gate = triage._Lock(found[1] / LOCK_NAME)
429
+ gate.__enter__()
430
+ except OSError as exc:
431
+ raise Failed(f"cannot lock {found[1]}: {exc.strerror or exc}") from exc
432
+ try:
433
+ dest, data, proposal = _load(ident, n, pid)
434
+ _require_pending(n, pid, proposal)
435
+ try:
436
+ _decide(dest, data, proposal, "rejected", actor, reason=reason)
437
+ except OSError as exc:
438
+ raise Failed(f"cannot write {Path(dest) / 'proposals.json'}: {exc.strerror or exc}") from exc
439
+ return {"proposal": proposal, "changed": []}
440
+ finally:
441
+ gate.__exit__(None, None, None)
@@ -0,0 +1,43 @@
1
+ """The one rule for what state a finding is in, shared by the CLI, the sweep and forge-ui."""
2
+ from __future__ import annotations
3
+
4
+ # Only these two count as open. `swept`, `shadow`, `unlabelled` and `superseded` are shown, not worked on.
5
+ OPEN = ("open", "to-file")
6
+
7
+ _RECORD_WINS = ("duplicate", "dismissed", "fixed", "filed", "to-file")
8
+
9
+
10
+ def effective(record_entry, issues_entry, review_row) -> str:
11
+ """The status of one finding, from the first of these that answers.
12
+
13
+ 1. The record: duplicate, dismissed, fixed, filed, to-file. `open` means reopened: go to 3
14
+ (a filed issue in step 2 still shows).
15
+ 2. The issues entry (a `forge issues --json` finding): filed and CLOSED is fixed, filed is filed,
16
+ swept is swept, dismissed (the old store) is dismissed.
17
+ 3. The review row (forge-ui only, may be None): a shadow review, an unlabelled one, a superseded one.
18
+ 4. open.
19
+
20
+ An entry that holds only tags, a note, an edit or a draft has no status: it says nothing about the state.
21
+ """
22
+ recorded = record_entry.get("status") if isinstance(record_entry, dict) else None
23
+ if recorded in _RECORD_WINS:
24
+ return recorded
25
+ reopened = recorded == "open"
26
+ if isinstance(issues_entry, dict):
27
+ filed = issues_entry.get("filed")
28
+ if filed:
29
+ state = filed.get("state") if isinstance(filed, dict) else None
30
+ return "fixed" if isinstance(state, str) and state.upper() == "CLOSED" else "filed"
31
+ if not reopened:
32
+ if issues_entry.get("swept"):
33
+ return "swept"
34
+ if issues_entry.get("dismissed"):
35
+ return "dismissed"
36
+ if isinstance(review_row, dict):
37
+ if review_row.get("kind") == "shadow":
38
+ return "shadow"
39
+ if review_row.get("confidence") == "UNSTATED":
40
+ return "unlabelled"
41
+ if review_row.get("superseded"):
42
+ return "superseded"
43
+ return "open"