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