@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.
- package/CHANGELOG.md +49 -0
- package/README.md +1 -0
- package/SKILL.md +19 -2
- package/VERSION +1 -1
- package/docs/artifacts.md +25 -1
- package/docs/commands.md +217 -18
- package/docs/decomposed-runs.md +114 -1
- package/docs/development.md +2 -1
- package/docs/forge-ui.md +138 -18
- package/docs/memory.md +25 -4
- package/docs/models.md +8 -0
- package/docs/reviews.md +122 -0
- package/forge +26 -3
- package/package.json +2 -1
- package/references/dataset.md +20 -1
- package/references/decompose.md +641 -41
- package/references/harnesses.md +18 -3
- package/references/memory.md +30 -5
- package/references/planning.md +43 -14
- package/references/ui.md +53 -6
- package/registry.tsv +8 -3
- package/scripts/forge-brief.py +88 -3
- package/scripts/forge-compare.py +4 -3
- package/scripts/forge-contract.py +202 -27
- package/scripts/forge-control.py +117 -5
- package/scripts/forge-dispatch.sh +34 -5
- package/scripts/forge-findings.py +675 -0
- package/scripts/forge-group.py +496 -0
- package/scripts/forge-groups.py +89 -0
- package/scripts/forge-handoff.py +1128 -0
- package/scripts/forge-issues.py +228 -97
- package/scripts/forge-lib-group.sh +641 -0
- package/scripts/forge-lib-plans.sh +339 -3
- package/scripts/forge-lib-task.sh +197 -4
- package/scripts/forge-memory.sh +711 -17
- package/scripts/forge-parallel.sh +721 -38
- package/scripts/forge-planner.py +104 -8
- package/scripts/forge-route.py +190 -12
- package/scripts/forge-runs.py +9 -5
- package/scripts/forge-schedule.py +417 -52
- package/scripts/forge-solo.sh +2 -0
- package/scripts/forge-sweep.py +199 -44
- package/scripts/forge-worktrees.py +243 -0
- package/scripts/forge_brief/__init__.py +294 -50
- package/scripts/forge_brief/answers.py +58 -11
- package/scripts/forge_brief/proposals.py +1630 -0
- package/scripts/forge_dataset/efforts.py +4 -3
- package/scripts/forge_dataset/export.py +24 -12
- package/scripts/forge_dataset/facts.py +5 -3
- package/scripts/forge_dataset/forecast.py +8 -18
- package/scripts/forge_dataset/harvest.py +204 -9
- package/scripts/forge_dataset/history.py +11 -6
- package/scripts/forge_dataset/importer.py +65 -1
- package/scripts/forge_dataset/names.py +66 -0
- package/scripts/forge_dataset/reviewers.py +5 -2
- package/scripts/forge_dataset/risk.py +6 -3
- package/scripts/forge_dataset/routing.py +6 -1
- package/scripts/forge_findings/__init__.py +17 -0
- package/scripts/forge_findings/apply.py +441 -0
- package/scripts/forge_findings/status.py +43 -0
- package/scripts/forge_findings/store.py +583 -0
- package/scripts/forge_findings/tags.py +53 -0
- package/scripts/forge_findings/triage.py +603 -0
- package/scripts/forge_groups/__init__.py +308 -0
- package/scripts/forge_groups/attribute.py +289 -0
- package/scripts/forge_groups/review.py +286 -0
- package/scripts/forge_identity.py +327 -0
- package/scripts/forge_memory_list.py +7 -3
- package/scripts/forge_owner.py +152 -0
- package/scripts/forge_side/__init__.py +228 -38
- package/ui/docs/api.md +303 -29
- package/ui/forge_ui/control.py +1018 -6
- package/ui/forge_ui/executions.py +8 -1
- package/ui/forge_ui/export.py +31 -4
- package/ui/forge_ui/groups.py +264 -0
- package/ui/forge_ui/models.py +70 -8
- package/ui/forge_ui/projects.py +209 -22
- package/ui/forge_ui/reader.py +262 -19
- package/ui/forge_ui/server.py +4 -0
- package/ui/forge_ui/static/app.js +93 -13
- package/ui/forge_ui/static/briefview.js +350 -47
- package/ui/forge_ui/static/diffview.js +86 -1
- package/ui/forge_ui/static/findingsactions.js +201 -0
- package/ui/forge_ui/static/groupsview.js +332 -0
- package/ui/forge_ui/static/index.html +3 -0
- package/ui/forge_ui/static/panel.js +127 -7
- package/ui/forge_ui/static/projectsview.js +764 -30
- package/ui/forge_ui/static/runmodel.js +14 -3
- package/ui/forge_ui/static/storageview.js +91 -10
- package/ui/forge_ui/static/style.css +138 -5
- package/ui/forge_ui/static/triageview.js +423 -0
- package/ui/forge_ui/static/worktreesview.js +233 -12
- package/ui/forge_ui/storage.py +14 -0
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""The name a recorded dispatch is counted under in statistics keyed by alias.
|
|
2
|
+
|
|
3
|
+
A dispatch records the alias it was asked for and the model id that alias resolved to then.
|
|
4
|
+
When an alias later moves to a newer model (`terra` from gpt-5.6-terra to gpt-6.1-terra), its
|
|
5
|
+
old dispatches must not be counted as the new model's. `dispatch_name` names such a dispatch
|
|
6
|
+
by the alias that resolves to its recorded model today on the same harness (`terra-5.6`).
|
|
7
|
+
When no alias does, it keeps the alias it recorded: moving an alias without a versioned alias for
|
|
8
|
+
the old model is a choice to count both together. Statistics keyed by model id (routing,
|
|
9
|
+
forecast, efforts, pairs) need none of this.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
# No package import: forge-ui loads this file on its own to name its model rows the same way.
|
|
17
|
+
SKILL = Path(__file__).resolve().parents[2]
|
|
18
|
+
|
|
19
|
+
_CACHE = {}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def registry_models() -> dict:
|
|
23
|
+
"""{alias: {harness: model id}}; the first row of an alias is its default."""
|
|
24
|
+
out = {}
|
|
25
|
+
path = Path(os.environ.get('FORGE_REGISTRY') or str(SKILL / 'registry.tsv'))
|
|
26
|
+
try:
|
|
27
|
+
lines = path.read_text().splitlines()
|
|
28
|
+
except OSError:
|
|
29
|
+
return out
|
|
30
|
+
for line in lines:
|
|
31
|
+
if not line.strip() or line.startswith('#'):
|
|
32
|
+
continue
|
|
33
|
+
cells = line.split('\t')
|
|
34
|
+
if len(cells) >= 3:
|
|
35
|
+
out.setdefault(cells[0], {}).setdefault(cells[1], cells[2])
|
|
36
|
+
return out
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _registry() -> dict:
|
|
40
|
+
key = os.environ.get('FORGE_REGISTRY') or ''
|
|
41
|
+
if key not in _CACHE:
|
|
42
|
+
_CACHE[key] = registry_models()
|
|
43
|
+
return _CACHE[key]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def dispatch_name(d: dict, registry: dict | None = None):
|
|
47
|
+
"""The alias (or model id) a dispatch's event data `d` is counted under, or None."""
|
|
48
|
+
alias, model, harness = d.get('alias'), d.get('model'), d.get('harness')
|
|
49
|
+
if not alias:
|
|
50
|
+
return model or None
|
|
51
|
+
rows = (_registry() if registry is None else registry).get(alias)
|
|
52
|
+
if not rows or not model:
|
|
53
|
+
return alias
|
|
54
|
+
current = rows.get(harness) if harness else None
|
|
55
|
+
if current is None:
|
|
56
|
+
current = next(iter(rows.values()))
|
|
57
|
+
if current == model:
|
|
58
|
+
return alias
|
|
59
|
+
table = _registry() if registry is None else registry
|
|
60
|
+
for other, other_rows in table.items():
|
|
61
|
+
if other == alias:
|
|
62
|
+
continue
|
|
63
|
+
found = other_rows.get(harness) if harness else next(iter(other_rows.values()), None)
|
|
64
|
+
if found == model:
|
|
65
|
+
return other
|
|
66
|
+
return alias
|
|
@@ -22,6 +22,7 @@ from collections import defaultdict
|
|
|
22
22
|
|
|
23
23
|
from . import connect, dataset_dir
|
|
24
24
|
from .export import SURVIVES_AT, Runs, Store
|
|
25
|
+
from .names import dispatch_name
|
|
25
26
|
from .routing import wilson
|
|
26
27
|
|
|
27
28
|
MIN_LANDED = 10
|
|
@@ -63,10 +64,12 @@ def report(runs: Runs, *, horizon_days: int = HORIZON_DAYS, repo: str = None) ->
|
|
|
63
64
|
continue
|
|
64
65
|
reviews = []
|
|
65
66
|
for run, task, attempt in attempts_of.get(commit, ()):
|
|
66
|
-
|
|
67
|
+
# scope group is one review of several tasks, not this task's reviewer.
|
|
68
|
+
reviews += [r for r in runs.dispatches.get((run, task, 'qa'), ())
|
|
69
|
+
if r['attempt'] == attempt and (r.get('d') or {}).get('scope') != 'group']
|
|
67
70
|
passed = {}
|
|
68
71
|
for r in sorted(reviews, key=lambda r: r['ts']):
|
|
69
|
-
name =
|
|
72
|
+
name = dispatch_name(r['d'])
|
|
70
73
|
if r['d'].get('verdict') == 'PASS' and name:
|
|
71
74
|
passed[name] = r['d']
|
|
72
75
|
if not passed:
|
|
@@ -22,7 +22,7 @@ import json
|
|
|
22
22
|
import os
|
|
23
23
|
|
|
24
24
|
from . import connect, dataset_dir
|
|
25
|
-
from .export import SURVIVES_AT, Runs, Store
|
|
25
|
+
from .export import SURVIVES_AT, Runs, Store, _attempts
|
|
26
26
|
from .facts import _kappa
|
|
27
27
|
|
|
28
28
|
LEVELS = ('low', 'medium', 'high')
|
|
@@ -54,9 +54,12 @@ def report(runs: Runs, repo: str = None) -> dict:
|
|
|
54
54
|
first_pass=0, serious=0, landed=0, did_not_hold=0))
|
|
55
55
|
cell['tasks'] += 1
|
|
56
56
|
attempts = runs.attempts.get((run, task)) or []
|
|
57
|
-
|
|
57
|
+
# Only attempts that spent one, as the export counts them: an execution whose prompt changed
|
|
58
|
+
# while it ran (STALE), an infrastructure stop or a refund is not a first attempt.
|
|
59
|
+
spent = _attempts(runs, run, task, attempts)
|
|
60
|
+
if spent:
|
|
58
61
|
cell['attempted'] += 1
|
|
59
|
-
cell['first_pass'] +=
|
|
62
|
+
cell['first_pass'] += spent[0]['events'][-1]['d'].get('status') == 'PASS'
|
|
60
63
|
reviews = runs.dispatches.get((run, task, 'qa')) or []
|
|
61
64
|
cell['serious'] += any(f.get('status') == 'CONFIRMED' and f.get('severity') in (0, 1)
|
|
62
65
|
for e in reviews for f in e['d'].get('findings') or [] if isinstance(f, dict))
|
|
@@ -100,13 +100,18 @@ def tasks(runs: Runs, *, repo=None, since=None) -> list:
|
|
|
100
100
|
continue
|
|
101
101
|
if since and not (events and events[0]['ts'] >= since):
|
|
102
102
|
continue
|
|
103
|
+
# The first counted attempt's dwarf cell. `script` ran tasks/<id>/run, not a model,
|
|
104
|
+
# so the task is not a model's result (history and the tier tables read this list).
|
|
105
|
+
ran = first['events'][0]['d'].get('dwarf') if first else None
|
|
106
|
+
if ran == 'script':
|
|
107
|
+
continue
|
|
103
108
|
started = _started(runs, run, tid, first) if first else None
|
|
104
109
|
decision = decision_before(decisions.get(tid), started)
|
|
105
110
|
resolved = runs.resolved(run, tid, 'dwarf', first['n']) if first else {}
|
|
106
111
|
model = ':'.join(x for x in (resolved.get('model'), resolved.get('effort')) if x) or None
|
|
107
112
|
out.append(dict(
|
|
108
113
|
run=run, task=tid, tier=row.get('declared_difficulty') or row.get('difficulty'),
|
|
109
|
-
ran=
|
|
114
|
+
ran=ran, model=model,
|
|
110
115
|
model_id=resolved.get('model'), effort=resolved.get('effort'),
|
|
111
116
|
first_pass=first['outcome'] if first else None,
|
|
112
117
|
censored=(first['reason'] if first and first['outcome'] is None else (None if first else 'not_run')),
|
|
@@ -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,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"
|