@giamme/forge 0.12.1 → 0.13.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 +55 -0
- package/README.md +1 -1
- package/SKILL.md +29 -12
- package/VERSION +1 -1
- package/docs/add-ons.md +11 -6
- package/docs/artifacts.md +12 -6
- package/docs/commands.md +179 -17
- package/docs/decomposed-runs.md +13 -5
- package/docs/forge-ui.md +7 -3
- package/docs/memory.md +2 -1
- package/docs/models.md +4 -2
- package/docs/reviews.md +49 -20
- package/docs/troubleshooting.md +3 -1
- package/forge +17 -1
- package/package.json +1 -1
- package/references/dataset.md +39 -13
- package/references/decision-models.md +759 -0
- package/references/decompose.md +166 -29
- package/references/harnesses.md +10 -3
- package/references/planning.md +8 -0
- package/references/solo.md +13 -3
- package/scripts/forge-artifact.sh +30 -4
- package/scripts/forge-config.py +238 -29
- package/scripts/forge-contract.py +95 -56
- package/scripts/forge-control.py +40 -9
- package/scripts/forge-decide.py +6 -0
- package/scripts/forge-dispatch.sh +38 -16
- package/scripts/forge-fail-first.py +2 -2
- package/scripts/forge-gate-addressed.sh +40 -0
- package/scripts/forge-gate-message.sh +64 -0
- package/scripts/forge-issues.py +321 -33
- package/scripts/forge-jev-options.sh +269 -42
- package/scripts/forge-lib-attribute.sh +447 -0
- package/scripts/forge-lib-gates.sh +32 -0
- package/scripts/forge-lib-plans.sh +17 -6
- package/scripts/forge-lib-review.sh +22 -17
- package/scripts/forge-lib-task.sh +217 -38
- package/scripts/forge-lib-verify.sh +45 -8
- package/scripts/forge-memory.sh +3 -3
- package/scripts/forge-parallel-options.sh +18 -5
- package/scripts/forge-parallel.sh +455 -303
- package/scripts/forge-plan-check.py +35 -1
- package/scripts/forge-pre-review.py +437 -0
- package/scripts/forge-prompt.py +25 -5
- package/scripts/forge-route.py +2 -2
- package/scripts/forge-runtime.py +10 -4
- package/scripts/forge-schedule.py +21 -5
- package/scripts/forge-shadow.py +2 -2
- package/scripts/forge-solo.sh +38 -9
- package/scripts/forge-submodules.py +389 -0
- package/scripts/forge_dataset/cli.py +12 -6
- package/scripts/forge_dataset/export.py +55 -45
- package/scripts/forge_dataset/harvest.py +33 -5
- package/scripts/{forge_jev/outcome.py → forge_dataset/states.py} +21 -7
- package/scripts/forge_decide/__init__.py +141 -0
- package/scripts/forge_decide/budget.py +149 -0
- package/scripts/forge_decide/cache.py +66 -0
- package/scripts/forge_decide/cli.py +953 -0
- package/scripts/forge_decide/doctor.py +221 -0
- package/scripts/forge_decide/label_addressed.py +75 -0
- package/scripts/forge_decide/label_attribution.py +62 -0
- package/scripts/forge_decide/label_coverage.py +81 -0
- package/scripts/forge_decide/label_message.py +38 -0
- package/scripts/forge_decide/label_prompt.py +139 -0
- package/scripts/forge_decide/labels.py +328 -0
- package/scripts/forge_decide/metrics.py +125 -0
- package/scripts/forge_decide/migrate.py +226 -0
- package/scripts/forge_decide/providers.py +292 -0
- package/scripts/forge_decide/replay.py +350 -0
- package/scripts/forge_decide/report.py +382 -0
- package/scripts/forge_decide/resolve.py +397 -0
- package/scripts/forge_decide/sites.py +377 -0
- package/scripts/forge_jev/__init__.py +202 -104
- package/scripts/forge_jev/addressed.py +171 -0
- package/scripts/forge_jev/attribution.py +198 -0
- package/scripts/forge_jev/cli.py +460 -382
- package/scripts/forge_jev/client.py +155 -77
- package/scripts/forge_jev/coupling.py +19 -87
- package/scripts/forge_jev/coverage.py +303 -0
- package/scripts/forge_jev/findings.py +219 -0
- package/scripts/forge_jev/gates.py +225 -27
- package/scripts/forge_jev/memory.py +65 -4
- package/scripts/forge_jev/message.py +134 -0
- package/scripts/forge_jev/plan_gates.py +294 -0
- package/scripts/forge_jev/questions.py +173 -313
- package/scripts/forge_jev/verify.py +130 -104
- package/ui/README.md +2 -2
- package/ui/docs/api.md +60 -32
- package/ui/forge_ui/control.py +60 -11
- package/ui/forge_ui/export.py +2 -1
- package/ui/forge_ui/models.py +1 -0
- package/ui/forge_ui/reader.py +87 -14
- package/ui/forge_ui/static/app.js +2 -2
- package/ui/forge_ui/static/controls.js +20 -13
- package/ui/forge_ui/static/panel.js +63 -17
- package/ui/forge_ui/static/runmodel.js +23 -1
- package/ui/forge_ui/static/scene3d.js +2 -15
- package/ui/forge_ui/static/settings.js +336 -41
- package/ui/forge_ui/static/style.css +19 -7
- package/references/jev.md +0 -865
- package/scripts/forge_jev/backtest.py +0 -322
- package/scripts/forge_jev/corpus.py +0 -156
- package/scripts/forge_jev/features.py +0 -24
- package/scripts/forge_jev/predict.py +0 -204
- package/scripts/forge_jev/review.py +0 -73
- package/scripts/forge_jev/routing.py +0 -271
- package/scripts/forge_jev/subset.py +0 -123
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""Plan covers the request (#47): which requirement of the request no task's criteria cover.
|
|
2
|
+
|
|
3
|
+
A decomposed run can pass every task and still miss part of what the user asked for. A
|
|
4
|
+
requirement dropped while decomposing belongs to no task, so nobody builds it and no reviewer
|
|
5
|
+
checks for it. Forge keeps what is needed to ask before dispatch: the request verbatim in
|
|
6
|
+
`request.md`, and each task's `## Acceptance criteria` in its `prompt.md`.
|
|
7
|
+
|
|
8
|
+
`split_requirements` cuts the request into requirements, deterministically. `main` asks, for
|
|
9
|
+
each, which task's criteria deliver it (site `jev-coverage`, rubric `requirement_coverage`);
|
|
10
|
+
`none` at or above `coverage_warn` means uncovered. The result goes into `plan-gates.json`
|
|
11
|
+
(`coverage`, replaced on every call). In `on` each uncovered requirement is also marked pending
|
|
12
|
+
for `plan_gates.sendback`, which `plan` runs once after every gate; in `shadow` nothing is.
|
|
13
|
+
|
|
14
|
+
`decisions`, `score`, `fired` and `baseline` are what forge_decide.sites reads for this site.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import hashlib
|
|
19
|
+
import json
|
|
20
|
+
import math
|
|
21
|
+
import re
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from . import gate_mode, load_config, site_ready, threshold
|
|
25
|
+
from .client import ask, choice, probabilities
|
|
26
|
+
from .questions import requirement_coverage
|
|
27
|
+
|
|
28
|
+
SITE = 'jev-coverage'
|
|
29
|
+
MAX_REQUIREMENTS = 30
|
|
30
|
+
MAX_TASKS = 40
|
|
31
|
+
MIN_WORDS = 4
|
|
32
|
+
REQUEST_CHARS = 6000
|
|
33
|
+
CRITERIA_CHARS = 1200
|
|
34
|
+
|
|
35
|
+
_FENCE = re.compile(r'^\s*(`{3,}|~{3,})(.*)$')
|
|
36
|
+
_HEADING = re.compile(r'^\s{0,3}#{1,6}(\s|$)')
|
|
37
|
+
_ITEM = re.compile(r'^\s*(?:[-*+]|\d+[.)])\s+(.*)$')
|
|
38
|
+
_SENTENCE_END = re.compile(r'(?<=[.?!])\s+(?=[A-Z])')
|
|
39
|
+
# The same patterns forge-plan-check.py `has_acceptance_criteria` reads sections with.
|
|
40
|
+
_CRITERIA_HEADING = re.compile(r'^(#{1,6})\s+acceptance criteria\s*:?\s*$', re.IGNORECASE)
|
|
41
|
+
_ANY_HEADING = re.compile(r'^(#{1,6})\s')
|
|
42
|
+
_WORD = re.compile(r'[a-z]{4,}')
|
|
43
|
+
_QID = re.compile(r'r(\d+)')
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _fence(line, open_fence):
|
|
47
|
+
"""The fence state after `line`: None outside a fence, else (marker char, length). A fence
|
|
48
|
+
closes only on a marker of the same character, at least as long, with nothing after it, so a
|
|
49
|
+
shorter or different marker inside a block is content."""
|
|
50
|
+
found = _FENCE.match(line)
|
|
51
|
+
if not found:
|
|
52
|
+
return open_fence
|
|
53
|
+
marker, rest = found.group(1), found.group(2)
|
|
54
|
+
if open_fence is None:
|
|
55
|
+
return None if marker[0] == '`' and '`' in rest else (marker[0], len(marker))
|
|
56
|
+
if marker[0] == open_fence[0] and len(marker) >= open_fence[1] and not rest.strip():
|
|
57
|
+
return None
|
|
58
|
+
return open_fence
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _collapse(text) -> str:
|
|
62
|
+
return ' '.join(str(text).split())
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def sha(text) -> str:
|
|
66
|
+
"""The key a requirement goes by in plan-gates.json: sha1 of its whitespace-collapsed text."""
|
|
67
|
+
return hashlib.sha1(_collapse(text).encode('utf-8', 'replace')).hexdigest()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def content_words(text) -> set[str]:
|
|
71
|
+
"""The lower-case words of four or more letters."""
|
|
72
|
+
return set(_WORD.findall(str(text).lower()))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# --- the request -------------------------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
def split_requirements(text) -> list[str]:
|
|
78
|
+
"""The requirements of a request, in order, at most MAX_REQUIREMENTS.
|
|
79
|
+
|
|
80
|
+
A bullet or numbered item is one requirement, continuation lines joined. The other
|
|
81
|
+
paragraphs split into sentences at `. `, `? ` and `! ` before an uppercase letter. Fenced
|
|
82
|
+
code, headings and anything under four words are dropped; a duplicate (after whitespace
|
|
83
|
+
collapse) is dropped, keeping the first.
|
|
84
|
+
"""
|
|
85
|
+
found: list[str] = []
|
|
86
|
+
items: list[str] = [] # lines of the bullet being read
|
|
87
|
+
prose: list[str] = [] # lines of the paragraph being read
|
|
88
|
+
|
|
89
|
+
def flush():
|
|
90
|
+
if items:
|
|
91
|
+
found.append(' '.join(items))
|
|
92
|
+
if prose:
|
|
93
|
+
found.extend(_SENTENCE_END.split(' '.join(prose)))
|
|
94
|
+
items.clear()
|
|
95
|
+
prose.clear()
|
|
96
|
+
|
|
97
|
+
fence = None
|
|
98
|
+
for line in str(text or '').splitlines():
|
|
99
|
+
after = _fence(line, fence)
|
|
100
|
+
if fence is not None or after is not None:
|
|
101
|
+
flush()
|
|
102
|
+
fence = after
|
|
103
|
+
continue
|
|
104
|
+
if not line.strip() or _HEADING.match(line):
|
|
105
|
+
flush()
|
|
106
|
+
continue
|
|
107
|
+
item = _ITEM.match(line)
|
|
108
|
+
if item:
|
|
109
|
+
flush()
|
|
110
|
+
items.append(item.group(1).strip())
|
|
111
|
+
elif items:
|
|
112
|
+
items.append(line.strip())
|
|
113
|
+
else:
|
|
114
|
+
prose.append(line.strip())
|
|
115
|
+
flush()
|
|
116
|
+
out, seen = [], set()
|
|
117
|
+
for candidate in found:
|
|
118
|
+
candidate = _collapse(candidate)
|
|
119
|
+
if len(candidate.split()) < MIN_WORDS or candidate in seen:
|
|
120
|
+
continue
|
|
121
|
+
seen.add(candidate)
|
|
122
|
+
out.append(candidate)
|
|
123
|
+
if len(out) == MAX_REQUIREMENTS:
|
|
124
|
+
break
|
|
125
|
+
return out
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def acceptance_criteria(prompt_text) -> str:
|
|
129
|
+
"""The body of the first non-empty `## Acceptance criteria` section, up to the next heading
|
|
130
|
+
of the same or a higher level, at most CRITERIA_CHARS. Headings inside fences do not count
|
|
131
|
+
(the rule of forge-plan-check.py), but fenced lines under the heading are part of the body."""
|
|
132
|
+
fence = None
|
|
133
|
+
level = None
|
|
134
|
+
body: list[str] = []
|
|
135
|
+
for line in str(prompt_text or '').splitlines():
|
|
136
|
+
after = _fence(line, fence)
|
|
137
|
+
if fence is not None or after is not None:
|
|
138
|
+
fence = after
|
|
139
|
+
if level is not None:
|
|
140
|
+
body.append(line)
|
|
141
|
+
continue
|
|
142
|
+
heading = _ANY_HEADING.match(line)
|
|
143
|
+
if level is not None and heading and len(heading.group(1)) <= level:
|
|
144
|
+
text = '\n'.join(body).strip()
|
|
145
|
+
if text:
|
|
146
|
+
return text[:CRITERIA_CHARS]
|
|
147
|
+
level, body = None, []
|
|
148
|
+
elif level is not None:
|
|
149
|
+
body.append(line)
|
|
150
|
+
continue
|
|
151
|
+
match = _CRITERIA_HEADING.match(line)
|
|
152
|
+
if match:
|
|
153
|
+
level, body = len(match.group(1)), []
|
|
154
|
+
return '\n'.join(body).strip()[:CRITERIA_CHARS] if level is not None else ''
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _tasks(plan: Path) -> list[dict]:
|
|
158
|
+
"""[{id, title, acceptance_criteria}] from tasks.tsv and each task's prompt.md."""
|
|
159
|
+
try:
|
|
160
|
+
lines = (plan / 'tasks.tsv').read_text(errors='replace').splitlines()
|
|
161
|
+
except OSError:
|
|
162
|
+
return []
|
|
163
|
+
out = []
|
|
164
|
+
for line in lines:
|
|
165
|
+
if not line.strip() or line.startswith('#'):
|
|
166
|
+
continue
|
|
167
|
+
cells = line.split('\t')
|
|
168
|
+
if len(cells) < 7 or not cells[0]:
|
|
169
|
+
continue
|
|
170
|
+
try:
|
|
171
|
+
prompt = (plan / 'tasks' / cells[0] / 'prompt.md').read_text(errors='replace')
|
|
172
|
+
except OSError:
|
|
173
|
+
prompt = ''
|
|
174
|
+
out.append(dict(id=cells[0], title=cells[6], acceptance_criteria=acceptance_criteria(prompt)))
|
|
175
|
+
return out
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# --- the measurement functions forge_decide.sites reads ----------------------------------
|
|
179
|
+
|
|
180
|
+
def _index(qid) -> int:
|
|
181
|
+
found = _QID.fullmatch(str(qid))
|
|
182
|
+
return int(found.group(1)) if found else -1
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def decisions(body) -> list[str]:
|
|
186
|
+
"""The `r<i>` question ids of a stored request body, in index order."""
|
|
187
|
+
questions = body.get('questions') if isinstance(body, dict) else None
|
|
188
|
+
return sorted((q for q in questions or () if _index(q) >= 0), key=_index)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _probability(value) -> float | None:
|
|
192
|
+
"""`value` as a probability: a finite number in [0, 1], else None. A malformed score is
|
|
193
|
+
no opinion, so the gate fails open instead of sending a requirement back."""
|
|
194
|
+
if isinstance(value, bool):
|
|
195
|
+
return None
|
|
196
|
+
try:
|
|
197
|
+
value = float(value)
|
|
198
|
+
except (TypeError, ValueError):
|
|
199
|
+
return None
|
|
200
|
+
return value if math.isfinite(value) and 0.0 <= value <= 1.0 else None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _p_none(answers, qid) -> float | None:
|
|
204
|
+
"""P(`none`) of a question: the Choice's distribution, else its confidence when it chose
|
|
205
|
+
`none`, else 0.0 for a choice of a task. None when the question has no choice answer or
|
|
206
|
+
its score is not a probability."""
|
|
207
|
+
if not isinstance(answers, dict) or not isinstance(answers.get(qid), dict):
|
|
208
|
+
return None
|
|
209
|
+
result = dict(answers=answers)
|
|
210
|
+
found = probabilities(result, qid)
|
|
211
|
+
if 'none' in found:
|
|
212
|
+
return _probability(found['none'])
|
|
213
|
+
picked, confidence = choice(result, qid)
|
|
214
|
+
if picked is None:
|
|
215
|
+
return None
|
|
216
|
+
if picked != 'none':
|
|
217
|
+
return 0.0
|
|
218
|
+
return _probability(confidence)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def score(answers, qid, request=None) -> float | None:
|
|
222
|
+
return _p_none(answers, qid)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def fired(answers, threshold_value, request=None) -> list[str]:
|
|
226
|
+
"""The questions whose requirement is uncovered: P(`none`) at or above the threshold."""
|
|
227
|
+
out = []
|
|
228
|
+
for qid in sorted((q for q in answers or () if _index(q) >= 0), key=_index):
|
|
229
|
+
p = _p_none(answers, qid)
|
|
230
|
+
if p is not None and p >= threshold_value:
|
|
231
|
+
out.append(qid)
|
|
232
|
+
return out
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def baseline(body, qid) -> float:
|
|
236
|
+
"""The share of the requirement's content words that no task's criteria use: the cheap
|
|
237
|
+
guess the gate must beat. Higher = more likely uncovered."""
|
|
238
|
+
state = body.get('state') if isinstance(body, dict) else None
|
|
239
|
+
state = state if isinstance(state, dict) else {}
|
|
240
|
+
requirements = state.get('requirements')
|
|
241
|
+
i = _index(qid)
|
|
242
|
+
if not isinstance(requirements, list) or not 0 <= i < len(requirements):
|
|
243
|
+
return 0.0
|
|
244
|
+
words = content_words(requirements[i])
|
|
245
|
+
if not words:
|
|
246
|
+
return 0.0
|
|
247
|
+
used = set()
|
|
248
|
+
for task in state.get('tasks') or ():
|
|
249
|
+
if isinstance(task, dict):
|
|
250
|
+
used |= content_words(task.get('acceptance_criteria') or '')
|
|
251
|
+
return len(words - used) / len(words)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
# --- the gate ----------------------------------------------------------------------------
|
|
255
|
+
|
|
256
|
+
def main(args) -> int:
|
|
257
|
+
"""`forge-jev.py coverage --plan P --repo R`. Exit 3 is no opinion: skipped, shadow, or
|
|
258
|
+
nothing uncovered; otherwise one `r<i><TAB>p<TAB>text` row per uncovered requirement."""
|
|
259
|
+
plan = Path(args.plan)
|
|
260
|
+
config = load_config()
|
|
261
|
+
if not site_ready(SITE, config):
|
|
262
|
+
return 3
|
|
263
|
+
try:
|
|
264
|
+
request = (plan / 'request.md').read_text(errors='replace')
|
|
265
|
+
except OSError:
|
|
266
|
+
return 3
|
|
267
|
+
requirements = split_requirements(request)
|
|
268
|
+
tasks = _tasks(plan)
|
|
269
|
+
if len(requirements) < 2 or not tasks or len(tasks) > MAX_TASKS:
|
|
270
|
+
return 3
|
|
271
|
+
|
|
272
|
+
ids = [t['id'] for t in tasks]
|
|
273
|
+
state = dict(request=request[:REQUEST_CHARS], requirements=requirements, tasks=tasks)
|
|
274
|
+
questions = {f'r{i}': requirement_coverage(text, ids) for i, text in enumerate(requirements)}
|
|
275
|
+
result = ask(state, questions, site=SITE, run_dir=str(plan), config=config)
|
|
276
|
+
if result is None:
|
|
277
|
+
return 3
|
|
278
|
+
|
|
279
|
+
warn_at = threshold('coverage_warn', config=config, site=SITE, model=result.get('model'))
|
|
280
|
+
shadow = gate_mode(SITE) == 'shadow'
|
|
281
|
+
uncovered = []
|
|
282
|
+
for i, text in enumerate(requirements):
|
|
283
|
+
p = _p_none(result['answers'], f'r{i}')
|
|
284
|
+
if p is not None and p >= warn_at:
|
|
285
|
+
uncovered.append(dict(index=i, text=text, sha=sha(text), p=round(p, 3), shadow=shadow))
|
|
286
|
+
|
|
287
|
+
from . import plan_gates
|
|
288
|
+
data = plan_gates.load(plan)
|
|
289
|
+
data['coverage'] = dict(requirements=requirements,
|
|
290
|
+
uncovered=[{k: u[k] for k in ('text', 'sha', 'p', 'shadow')} for u in uncovered])
|
|
291
|
+
if not shadow:
|
|
292
|
+
for item in uncovered:
|
|
293
|
+
plan_gates.mark_pending(data, 'coverage', item['sha'])
|
|
294
|
+
plan_gates.save(plan, data)
|
|
295
|
+
|
|
296
|
+
if shadow or not uncovered:
|
|
297
|
+
return 3
|
|
298
|
+
if getattr(args, 'json', False):
|
|
299
|
+
print(json.dumps([dict(id=f"r{u['index']}", p=u['p'], text=u['text']) for u in uncovered], indent=2))
|
|
300
|
+
else:
|
|
301
|
+
for item in uncovered:
|
|
302
|
+
print('\t'.join((f"r{item['index']}", str(item['p']), item['text'])))
|
|
303
|
+
return 0
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""Findings duplicates and triage (#46): which review findings restate an open issue, and which
|
|
2
|
+
PLAUSIBLE ones read as a preference.
|
|
3
|
+
|
|
4
|
+
A finished run can leave findings nobody will act on. `forge-issues.py` turns them into GitHub
|
|
5
|
+
issues, guarded by an exact fingerprint and an open issue with the same title; a finding
|
|
6
|
+
reworded from an open issue slips through both. This verb asks two reading questions about a
|
|
7
|
+
batch of findings, and prints the answers. It decides nothing: the caller applies the
|
|
8
|
+
`findings_dup` and `findings_concrete` thresholds and the gate's mode (`forge-issues.py` does,
|
|
9
|
+
and gh-proman can). It never changes a finding, a severity or a verdict.
|
|
10
|
+
|
|
11
|
+
forge-jev.py findings --repo R --input F [--run-dir D]
|
|
12
|
+
|
|
13
|
+
`--run-dir` is the plan or run dir the findings came from, used for the dataset record and the
|
|
14
|
+
request cache; call the verb once per plan.
|
|
15
|
+
|
|
16
|
+
Input, a JSON object in file F:
|
|
17
|
+
|
|
18
|
+
{"findings": [{"fp", "plan", "severity", "status", "location", "text",
|
|
19
|
+
"candidates": [id, ...]}],
|
|
20
|
+
"candidates": [{"id", "title", "body"}]}
|
|
21
|
+
|
|
22
|
+
`status` is CONFIRMED or PLAUSIBLE. The optional `candidates` of a finding narrows the issues it
|
|
23
|
+
is compared with (ids from the top-level list); without it, every candidate is an option.
|
|
24
|
+
|
|
25
|
+
Questions, one request, site `jev-findings`:
|
|
26
|
+
- `d<i>` per finding that has at least one candidate: rubric `finding_duplicate`, a Choice over
|
|
27
|
+
the candidate ids plus `none`.
|
|
28
|
+
- `c<i>` per PLAUSIBLE finding: rubric `finding_concrete`.
|
|
29
|
+
Both quote the finding. The state is `{findings: [{i, fp, severity, status, location, text}],
|
|
30
|
+
candidates: {id: {title, body[:600]}}}`.
|
|
31
|
+
|
|
32
|
+
Output, a JSON list on stdout, one object per input finding, in input order:
|
|
33
|
+
|
|
34
|
+
[{"fp", "duplicate_of": id|null, "dup_p": p|null, "concrete": p|null}]
|
|
35
|
+
|
|
36
|
+
- `duplicate_of` is the candidate id the model chose, null when it chose `none` or was not
|
|
37
|
+
asked. `dup_p` is that choice's probability; when it chose `none`, the highest probability of
|
|
38
|
+
any candidate (the closest duplicate); null when it was not asked.
|
|
39
|
+
- `concrete` is the probability that the finding names a concrete defect: one minus the Noul of
|
|
40
|
+
`c<i>`, because the rubric asks the opposite way (does it read as a preference?) so that a
|
|
41
|
+
high Noul keeps the direction every other gate has, "the gate acts". Null for a CONFIRMED
|
|
42
|
+
finding or an unanswered question.
|
|
43
|
+
|
|
44
|
+
Exit 3 is no opinion and prints nothing: the gate is off, the model did not answer, or the input
|
|
45
|
+
is unusable. Shadow prints the same JSON as on: the caller records it, and the mode decides
|
|
46
|
+
whether it acts.
|
|
47
|
+
|
|
48
|
+
`decisions`, `score`, `fired` and `baseline` are what forge_decide.sites reads for this site.
|
|
49
|
+
Like every site's, `score` and `baseline` point at acting, here deselecting: `score` is the Noul
|
|
50
|
+
itself (the preference), one minus the output's `concrete`, and `baseline` is 1.0 for a finding
|
|
51
|
+
that looks like a preference. The threshold `findings_concrete` is on the `concrete` scale, so the
|
|
52
|
+
site is inverted (forge_decide.sites `invert`): replay flags a score at or above 1 - threshold.
|
|
53
|
+
"""
|
|
54
|
+
from __future__ import annotations
|
|
55
|
+
|
|
56
|
+
import json
|
|
57
|
+
import math
|
|
58
|
+
import re
|
|
59
|
+
from pathlib import Path
|
|
60
|
+
|
|
61
|
+
from . import site_ready
|
|
62
|
+
from .client import ask, choice, noul, probabilities
|
|
63
|
+
from .questions import finding_concrete, finding_duplicate
|
|
64
|
+
|
|
65
|
+
SITE = 'jev-findings'
|
|
66
|
+
BODY_CHARS = 600
|
|
67
|
+
|
|
68
|
+
_CONCRETE = re.compile(r'c(\d+)')
|
|
69
|
+
_BASELINE_WORDS = re.compile(r'\b(?:when|if|returns|raises|crash|wrong)\b', re.I)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _probability(value) -> float | None:
|
|
73
|
+
"""`value` as a probability: a finite number in [0, 1], else None (no opinion)."""
|
|
74
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
75
|
+
return None
|
|
76
|
+
value = float(value)
|
|
77
|
+
return value if math.isfinite(value) and 0.0 <= value <= 1.0 else None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _concreteness(preference) -> float | None:
|
|
81
|
+
"""P(concrete defect) from the Noul of `finding_concrete`, which asks whether the finding is
|
|
82
|
+
a preference; None when it is not a probability."""
|
|
83
|
+
p = _probability(preference)
|
|
84
|
+
return None if p is None else 1.0 - p
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _text(value) -> str:
|
|
88
|
+
return value if isinstance(value, str) else ''
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _line(item: dict) -> str:
|
|
92
|
+
"""The finding as one review line: `[P1][CONFIRMED] a.py:12 — text`."""
|
|
93
|
+
return f"[{item['severity']}][{item['status']}] {item['location']} — {item['text']}"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def read_input(path) -> tuple[list[dict], dict, list[list[str]]] | None:
|
|
97
|
+
"""(findings, candidates {id: {title, body}}, candidate ids per finding), or None when the
|
|
98
|
+
file is not the input of the module docstring. A finding without text or a fingerprint is
|
|
99
|
+
not usable, so it makes the whole input unusable rather than shifting the indexes."""
|
|
100
|
+
try:
|
|
101
|
+
data = json.loads(Path(path).read_text(errors='replace'))
|
|
102
|
+
except (OSError, ValueError):
|
|
103
|
+
return None
|
|
104
|
+
if not isinstance(data, dict) or not isinstance(data.get('findings'), list):
|
|
105
|
+
return None
|
|
106
|
+
candidates: dict[str, dict] = {}
|
|
107
|
+
raw = data.get('candidates')
|
|
108
|
+
for item in raw if isinstance(raw, list) else ():
|
|
109
|
+
if isinstance(item, dict) and item.get('id') not in (None, '') and not isinstance(item['id'], bool):
|
|
110
|
+
candidates.setdefault(str(item['id']), dict(title=_text(item.get('title')),
|
|
111
|
+
body=_text(item.get('body'))[:BODY_CHARS]))
|
|
112
|
+
findings, options = [], []
|
|
113
|
+
for item in data['findings']:
|
|
114
|
+
if not isinstance(item, dict) or not _text(item.get('fp')) or not _text(item.get('text')):
|
|
115
|
+
return None
|
|
116
|
+
findings.append(dict(i=len(findings), fp=item['fp'], severity=_text(item.get('severity')),
|
|
117
|
+
status=_text(item.get('status')), location=_text(item.get('location')),
|
|
118
|
+
text=item['text']))
|
|
119
|
+
narrowed = item.get('candidates')
|
|
120
|
+
ids = [str(c) for c in narrowed] if isinstance(narrowed, list) else list(candidates)
|
|
121
|
+
options.append([c for c in dict.fromkeys(ids) if c in candidates])
|
|
122
|
+
return findings, candidates, options
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _duplicate(result, qid: str, options: list[str]) -> tuple[str | None, float | None]:
|
|
126
|
+
"""(candidate id or None, probability) of a `d<i>` answer."""
|
|
127
|
+
picked, confidence = choice(result, qid)
|
|
128
|
+
if picked is None:
|
|
129
|
+
return None, None
|
|
130
|
+
spread = probabilities(result, qid)
|
|
131
|
+
if picked != 'none':
|
|
132
|
+
if picked not in options:
|
|
133
|
+
return None, None
|
|
134
|
+
return picked, _probability(spread.get(picked, confidence))
|
|
135
|
+
rivals = [p for c, p in ((c, _probability(spread.get(c))) for c in options) if p is not None]
|
|
136
|
+
return None, max(rivals) if rivals else 0.0
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def main(args) -> int:
|
|
140
|
+
if not site_ready(SITE):
|
|
141
|
+
return 3
|
|
142
|
+
parsed = read_input(args.input)
|
|
143
|
+
if parsed is None:
|
|
144
|
+
return 3
|
|
145
|
+
findings, candidates, options = parsed
|
|
146
|
+
if not findings:
|
|
147
|
+
return 3
|
|
148
|
+
|
|
149
|
+
state = dict(findings=findings,
|
|
150
|
+
candidates={cid: dict(title=c['title'], body=c['body']) for cid, c in candidates.items()})
|
|
151
|
+
questions = {}
|
|
152
|
+
for item, ids in zip(findings, options):
|
|
153
|
+
if ids:
|
|
154
|
+
questions[f"d{item['i']}"] = finding_duplicate(_line(item), {cid: candidates[cid]['title'] for cid in ids})
|
|
155
|
+
if item['status'] == 'PLAUSIBLE':
|
|
156
|
+
questions[f"c{item['i']}"] = finding_concrete(_line(item))
|
|
157
|
+
if not questions:
|
|
158
|
+
return 3
|
|
159
|
+
result = ask(state, questions, site=SITE, run_dir=args.run_dir)
|
|
160
|
+
if result is None:
|
|
161
|
+
return 3
|
|
162
|
+
|
|
163
|
+
out = []
|
|
164
|
+
for item, ids in zip(findings, options):
|
|
165
|
+
duplicate_of, dup_p = _duplicate(result, f"d{item['i']}", ids) if ids else (None, None)
|
|
166
|
+
concrete = _concreteness(noul(result, f"c{item['i']}")) if item['status'] == 'PLAUSIBLE' else None
|
|
167
|
+
out.append(dict(fp=item['fp'], duplicate_of=duplicate_of,
|
|
168
|
+
dup_p=dup_p, concrete=concrete))
|
|
169
|
+
print(json.dumps(out, indent=2))
|
|
170
|
+
return 0
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
# --- measurement: what forge_decide.sites reads for this site ---------------------------------
|
|
174
|
+
|
|
175
|
+
def _index(qid) -> int:
|
|
176
|
+
found = _CONCRETE.fullmatch(str(qid))
|
|
177
|
+
return int(found.group(1)) if found else -1
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def decisions(body) -> list[str]:
|
|
181
|
+
"""The `c<i>` ids a request asked, in finding order."""
|
|
182
|
+
questions = body.get('questions') if isinstance(body, dict) else None
|
|
183
|
+
ids = list(questions) if isinstance(questions, (dict, list)) else []
|
|
184
|
+
return sorted((str(qid) for qid in ids if _index(qid) >= 0), key=_index)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def score(answers, qid, request=None) -> float | None:
|
|
188
|
+
"""P(preference), the probability of deselecting: the Noul of a `c<i>` question (see the module
|
|
189
|
+
docstring); None for any other id or an answer that is not a probability."""
|
|
190
|
+
answer = (answers or {}).get(qid)
|
|
191
|
+
if _index(qid) >= 0 and isinstance(answer, dict) and answer.get('type', 'noul') == 'noul':
|
|
192
|
+
return _probability(answer.get('noul'))
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def fired(answers, threshold_value, request=None) -> list[str]:
|
|
197
|
+
"""The `c<i>` whose concreteness is below the threshold: the findings the gate would deselect."""
|
|
198
|
+
limit = _probability(threshold_value)
|
|
199
|
+
if limit is None:
|
|
200
|
+
return []
|
|
201
|
+
out = []
|
|
202
|
+
for qid in sorted((q for q in (answers or {}) if _index(q) >= 0), key=_index):
|
|
203
|
+
p = score(answers, qid)
|
|
204
|
+
if p is not None and 1.0 - p < limit:
|
|
205
|
+
out.append(qid)
|
|
206
|
+
return out
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def baseline(body, qid) -> float:
|
|
210
|
+
"""0.0 when the finding's text has a digit, a backtick or one of when, if, returns, raises,
|
|
211
|
+
crash, wrong (it looks concrete); else 1.0 (it looks like a preference): the plain rule the
|
|
212
|
+
model's Noul is measured against. 0.0 for a question with no finding."""
|
|
213
|
+
state = body.get('state') if isinstance(body, dict) else None
|
|
214
|
+
findings = state.get('findings') if isinstance(state, dict) else None
|
|
215
|
+
for item in findings if isinstance(findings, list) else ():
|
|
216
|
+
if isinstance(item, dict) and item.get('i') == _index(qid):
|
|
217
|
+
text = _text(item.get('text'))
|
|
218
|
+
return 0.0 if re.search(r'\d|`', text) or _BASELINE_WORDS.search(text) else 1.0
|
|
219
|
+
return 0.0
|