@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.
Files changed (107) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +1 -1
  3. package/SKILL.md +29 -12
  4. package/VERSION +1 -1
  5. package/docs/add-ons.md +11 -6
  6. package/docs/artifacts.md +12 -6
  7. package/docs/commands.md +179 -17
  8. package/docs/decomposed-runs.md +13 -5
  9. package/docs/forge-ui.md +7 -3
  10. package/docs/memory.md +2 -1
  11. package/docs/models.md +4 -2
  12. package/docs/reviews.md +49 -20
  13. package/docs/troubleshooting.md +3 -1
  14. package/forge +17 -1
  15. package/package.json +1 -1
  16. package/references/dataset.md +39 -13
  17. package/references/decision-models.md +759 -0
  18. package/references/decompose.md +166 -29
  19. package/references/harnesses.md +10 -3
  20. package/references/planning.md +8 -0
  21. package/references/solo.md +13 -3
  22. package/scripts/forge-artifact.sh +30 -4
  23. package/scripts/forge-config.py +238 -29
  24. package/scripts/forge-contract.py +95 -56
  25. package/scripts/forge-control.py +40 -9
  26. package/scripts/forge-decide.py +6 -0
  27. package/scripts/forge-dispatch.sh +38 -16
  28. package/scripts/forge-fail-first.py +2 -2
  29. package/scripts/forge-gate-addressed.sh +40 -0
  30. package/scripts/forge-gate-message.sh +64 -0
  31. package/scripts/forge-issues.py +321 -33
  32. package/scripts/forge-jev-options.sh +269 -42
  33. package/scripts/forge-lib-attribute.sh +447 -0
  34. package/scripts/forge-lib-gates.sh +32 -0
  35. package/scripts/forge-lib-plans.sh +17 -6
  36. package/scripts/forge-lib-review.sh +22 -17
  37. package/scripts/forge-lib-task.sh +217 -38
  38. package/scripts/forge-lib-verify.sh +45 -8
  39. package/scripts/forge-memory.sh +3 -3
  40. package/scripts/forge-parallel-options.sh +18 -5
  41. package/scripts/forge-parallel.sh +455 -303
  42. package/scripts/forge-plan-check.py +35 -1
  43. package/scripts/forge-pre-review.py +437 -0
  44. package/scripts/forge-prompt.py +25 -5
  45. package/scripts/forge-route.py +2 -2
  46. package/scripts/forge-runtime.py +10 -4
  47. package/scripts/forge-schedule.py +21 -5
  48. package/scripts/forge-shadow.py +2 -2
  49. package/scripts/forge-solo.sh +38 -9
  50. package/scripts/forge-submodules.py +389 -0
  51. package/scripts/forge_dataset/cli.py +12 -6
  52. package/scripts/forge_dataset/export.py +55 -45
  53. package/scripts/forge_dataset/harvest.py +33 -5
  54. package/scripts/{forge_jev/outcome.py → forge_dataset/states.py} +21 -7
  55. package/scripts/forge_decide/__init__.py +141 -0
  56. package/scripts/forge_decide/budget.py +149 -0
  57. package/scripts/forge_decide/cache.py +66 -0
  58. package/scripts/forge_decide/cli.py +953 -0
  59. package/scripts/forge_decide/doctor.py +221 -0
  60. package/scripts/forge_decide/label_addressed.py +75 -0
  61. package/scripts/forge_decide/label_attribution.py +62 -0
  62. package/scripts/forge_decide/label_coverage.py +81 -0
  63. package/scripts/forge_decide/label_message.py +38 -0
  64. package/scripts/forge_decide/label_prompt.py +139 -0
  65. package/scripts/forge_decide/labels.py +328 -0
  66. package/scripts/forge_decide/metrics.py +125 -0
  67. package/scripts/forge_decide/migrate.py +226 -0
  68. package/scripts/forge_decide/providers.py +292 -0
  69. package/scripts/forge_decide/replay.py +350 -0
  70. package/scripts/forge_decide/report.py +382 -0
  71. package/scripts/forge_decide/resolve.py +397 -0
  72. package/scripts/forge_decide/sites.py +377 -0
  73. package/scripts/forge_jev/__init__.py +202 -104
  74. package/scripts/forge_jev/addressed.py +171 -0
  75. package/scripts/forge_jev/attribution.py +198 -0
  76. package/scripts/forge_jev/cli.py +460 -382
  77. package/scripts/forge_jev/client.py +155 -77
  78. package/scripts/forge_jev/coupling.py +19 -87
  79. package/scripts/forge_jev/coverage.py +303 -0
  80. package/scripts/forge_jev/findings.py +219 -0
  81. package/scripts/forge_jev/gates.py +225 -27
  82. package/scripts/forge_jev/memory.py +65 -4
  83. package/scripts/forge_jev/message.py +134 -0
  84. package/scripts/forge_jev/plan_gates.py +294 -0
  85. package/scripts/forge_jev/questions.py +173 -313
  86. package/scripts/forge_jev/verify.py +130 -104
  87. package/ui/README.md +2 -2
  88. package/ui/docs/api.md +60 -32
  89. package/ui/forge_ui/control.py +60 -11
  90. package/ui/forge_ui/export.py +2 -1
  91. package/ui/forge_ui/models.py +1 -0
  92. package/ui/forge_ui/reader.py +87 -14
  93. package/ui/forge_ui/static/app.js +2 -2
  94. package/ui/forge_ui/static/controls.js +20 -13
  95. package/ui/forge_ui/static/panel.js +63 -17
  96. package/ui/forge_ui/static/runmodel.js +23 -1
  97. package/ui/forge_ui/static/scene3d.js +2 -15
  98. package/ui/forge_ui/static/settings.js +336 -41
  99. package/ui/forge_ui/static/style.css +19 -7
  100. package/references/jev.md +0 -865
  101. package/scripts/forge_jev/backtest.py +0 -322
  102. package/scripts/forge_jev/corpus.py +0 -156
  103. package/scripts/forge_jev/features.py +0 -24
  104. package/scripts/forge_jev/predict.py +0 -204
  105. package/scripts/forge_jev/review.py +0 -73
  106. package/scripts/forge_jev/routing.py +0 -271
  107. package/scripts/forge_jev/subset.py +0 -123
@@ -0,0 +1,221 @@
1
+ """Doctor's checks for decision-model settings that went stale.
2
+
3
+ checks(repo=None, *, env=None) -> [{"kind", "message", ...fields}]
4
+
5
+ Offline, read-only and never raises. No item holds a key: they name files, gates, providers
6
+ and thresholds only. Kinds:
7
+
8
+ threshold-override a stored threshold differs from the measured default
9
+ ({gate | source: 'jev.json', name, value, default}, plus `model`
10
+ for a per-model value, `profile` for a value inside a profile)
11
+ retired-threshold a threshold nothing reads any more, in jev.json or in a gate
12
+ unknown-provider a gate names a provider that is not configured
13
+ unused-provider a configured provider no gate uses
14
+ shadowed a repo value the user file overrides
15
+ misplaced a user-only key in a repo file, or `privacy` in a user file
16
+ key-file a provider's key file is missing or not mode 0600
17
+ privacy-floor the repo has `privacy: never-send`
18
+ not-migrated jev.json exists but decide.json does not
19
+ config-error anything else wrong with reading the files
20
+
21
+ A stored value equal to the default is not an override. A value is compared against
22
+ DEFAULT_THRESHOLDS after THRESHOLD_FALLBACK, so a stored drift_warn is compared with gate_warn.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ from pathlib import Path
27
+
28
+ from . import GATES, config_dir, load_repo, load_user, repo_path, user_path
29
+ from .migrate import retired_thresholds
30
+ from .resolve import resolve
31
+
32
+ MISPLACED_MARKERS = ('user file only', 'only in a repo file')
33
+
34
+
35
+ def _default(name: str):
36
+ import forge_jev
37
+ name = forge_jev.THRESHOLD_FALLBACK.get(name, name)
38
+ return forge_jev.DEFAULT_THRESHOLDS.get(name)
39
+
40
+
41
+ def _number(value) -> bool:
42
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
43
+
44
+
45
+ def _thresholds(values, retired: frozenset, where: dict, items: list, label: str) -> None:
46
+ if not isinstance(values, dict):
47
+ return
48
+ for name, value in sorted(values.items()):
49
+ if name in retired:
50
+ items.append(dict(kind='retired-threshold', name=name, value=value, **where,
51
+ message=f'{label}: threshold {name} is retired; safe to delete'))
52
+ continue
53
+ default = _default(name)
54
+ if default is not None and _number(value) and value != default:
55
+ items.append(dict(kind='threshold-override', name=name, value=value, default=default, **where,
56
+ message=f'{label}: {name} is {value}, the measured default is {default}'))
57
+
58
+
59
+ def _jev_json(retired: frozenset, items: list) -> bool:
60
+ """Check jev.json; True when the file exists."""
61
+ import forge_jev
62
+ path = forge_jev.config_path()
63
+ if not path.exists():
64
+ return False
65
+ try:
66
+ stored = forge_jev.read_json(path)
67
+ except (OSError, ValueError, RecursionError) as exc:
68
+ items.append(dict(kind='config-error', message=f'{path}: unreadable ({type(exc).__name__})'))
69
+ return True
70
+ if not isinstance(stored, dict):
71
+ return True
72
+ where = dict(source='jev.json')
73
+ _thresholds(stored.get('thresholds'), retired, where, items, str(path))
74
+ per_model = stored.get('model_thresholds')
75
+ if isinstance(per_model, dict):
76
+ for model, values in sorted(per_model.items()):
77
+ _thresholds(values, retired, dict(where, model=model), items, f'{path} [{model}]')
78
+ return True
79
+
80
+
81
+ def _provider_names(data: dict) -> set:
82
+ gates = data.get('gates')
83
+ if not isinstance(gates, dict):
84
+ return set()
85
+ providers = (g.get('provider') for g in gates.values() if isinstance(g, dict))
86
+ return {name for name in providers if isinstance(name, str)}
87
+
88
+
89
+ def _used_providers(user: dict, repo: dict, resolved: dict) -> set:
90
+ used = {gate['provider'] for gate in resolved['gates'].values() if gate.get('provider')}
91
+ for data in (user, repo):
92
+ used |= _provider_names(data)
93
+ profiles = data.get('profiles')
94
+ if isinstance(profiles, dict):
95
+ for profile in profiles.values():
96
+ if isinstance(profile, dict):
97
+ used |= _provider_names(profile)
98
+ return used
99
+
100
+
101
+ def _unknown_providers(user: dict, repo: dict, resolved: dict, providers: dict, items: list) -> None:
102
+ """A gate naming a provider that is not configured: in the resolved gates, and in every stored
103
+ gate of the user file, the repo file and their profiles, active or not."""
104
+ seen: set = set()
105
+
106
+ def report(gate: str, name, where: dict) -> None:
107
+ if not isinstance(name, str) or not name or name in providers or (gate, name) in seen:
108
+ return
109
+ seen.add((gate, name))
110
+ suffix = f' (profile {where["profile"]})' if 'profile' in where else ''
111
+ items.append(dict(kind='unknown-provider', gate=gate, provider=name, **where,
112
+ message=f'gate {gate}{suffix} names provider {name!r}, which is not configured'))
113
+
114
+ for gate in GATES:
115
+ report(gate, resolved['gates'][gate].get('provider'), {})
116
+ for data in (user, repo):
117
+ bodies = [({}, data)]
118
+ profiles = data.get('profiles')
119
+ if isinstance(profiles, dict):
120
+ bodies += [(dict(profile=name), body) for name, body in sorted(profiles.items())]
121
+ for where, body in bodies:
122
+ gates = body.get('gates') if isinstance(body, dict) else None
123
+ if not isinstance(gates, dict):
124
+ continue
125
+ for gate in GATES:
126
+ entry = gates.get(gate)
127
+ if isinstance(entry, dict):
128
+ report(gate, entry.get('provider'), where)
129
+
130
+
131
+ def _key_path(value: str) -> Path:
132
+ path = Path(value).expanduser()
133
+ return path if path.is_absolute() else config_dir() / path
134
+
135
+
136
+ def _key_files(providers: dict, items: list) -> None:
137
+ for name, provider in sorted(providers.items()):
138
+ key_file = provider.get('key_file') if isinstance(provider, dict) else None
139
+ if not isinstance(key_file, str) or not key_file:
140
+ continue
141
+ path = _key_path(key_file)
142
+ try:
143
+ mode = path.stat().st_mode & 0o777
144
+ except OSError:
145
+ items.append(dict(kind='key-file', provider=name, path=str(path),
146
+ message=f'provider {name}: key file {path} is missing'))
147
+ continue
148
+ if mode != 0o600:
149
+ items.append(dict(kind='key-file', provider=name, path=str(path), mode=format(mode, '04o'),
150
+ message=f'provider {name}: key file {path} is mode {mode:04o}, expected 0600'))
151
+
152
+
153
+ def _gate_thresholds(data: dict, label: str, prefix: str, where: dict, retired: frozenset, items: list) -> None:
154
+ gates = data.get('gates')
155
+ if not isinstance(gates, dict):
156
+ return
157
+ for gate in GATES:
158
+ entry = gates.get(gate)
159
+ if isinstance(entry, dict):
160
+ _thresholds(entry.get('thresholds'), retired, dict(where, gate=gate), items,
161
+ f'{label} {prefix}gates.{gate}')
162
+
163
+
164
+ def _checks(repo, env, items: list) -> None:
165
+ retired = retired_thresholds()
166
+ has_jev = _jev_json(retired, items)
167
+ migrated = user_path().exists()
168
+ if has_jev and not migrated:
169
+ items.append(dict(kind='not-migrated',
170
+ message='jev.json exists but decide.json does not; run `forge decide migrate`'))
171
+
172
+ user, error = load_user()
173
+ if error:
174
+ items.append(dict(kind='config-error', message=error))
175
+ repo_data = {}
176
+ if repo is not None:
177
+ repo_data, error = load_repo(repo)
178
+ if error:
179
+ items.append(dict(kind='config-error', message=error))
180
+ resolved = resolve(repo, env=env)
181
+
182
+ for label, data in ((str(user_path()), user), (str(repo_path(repo)) if repo is not None else '', repo_data)):
183
+ _gate_thresholds(data, label, '', {}, retired, items)
184
+ profiles = data.get('profiles')
185
+ if isinstance(profiles, dict):
186
+ for profile, body in sorted(profiles.items()):
187
+ if isinstance(body, dict):
188
+ _gate_thresholds(body, label, f'profiles.{profile}.', dict(profile=profile), retired, items)
189
+
190
+ providers = user.get('providers')
191
+ providers = providers if isinstance(providers, dict) else {}
192
+ _unknown_providers(user, repo_data, resolved, providers, items)
193
+ used = _used_providers(user, repo_data, resolved)
194
+ for name in sorted(providers):
195
+ if name not in used:
196
+ items.append(dict(kind='unused-provider', provider=name,
197
+ message=f'provider {name!r} is configured but no gate uses it'))
198
+
199
+ for entry in resolved['shadowed']:
200
+ items.append(dict(kind='shadowed', **entry,
201
+ message=f"{entry['key']}: the repo sets {entry['repo']!r}, the user file's "
202
+ f"{entry['user']!r} wins"))
203
+ for error in resolved['errors']:
204
+ if any(marker in error for marker in MISPLACED_MARKERS):
205
+ items.append(dict(kind='misplaced', message=error))
206
+ _key_files(providers, items)
207
+
208
+ privacy = resolved['privacy']
209
+ if privacy.get('floor'):
210
+ items.append(dict(kind='privacy-floor', path=privacy.get('path'),
211
+ message=f"{privacy.get('path')}: privacy is {privacy['floor']}; every gate is off"))
212
+
213
+
214
+ def checks(repo=None, *, env=None) -> list:
215
+ """Every stale or inconsistent setting found. Never raises."""
216
+ items: list = []
217
+ try:
218
+ _checks(repo, env, items)
219
+ except Exception as exc: # doctor must keep going; the type alone cannot leak a key
220
+ items.append(dict(kind='config-error', message=f'decision-model checks failed ({type(exc).__name__})'))
221
+ return items
@@ -0,0 +1,75 @@
1
+ """Labels for `jev-retry-addressed` (#43): was the finding left unaddressed?
2
+
3
+ `u<i>` is true when the review of the same run, task and attempt raises the same finding again
4
+ -- the retry did not fix it, so the gate should have sent the attempt back. It is false when that
5
+ review parsed completely and does not raise it.
6
+
7
+ There is no label when the attempt has no review (the gate, or another send-back, bounced it:
8
+ a label must never come from the gate's own action), and none when the review's findings cannot
9
+ be read in full (`unparseable`, `ungraded`, or a message the dataset cut): such a review may hold
10
+ findings the strict parser misses, so "not raised again" cannot be read from it.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import re
15
+
16
+ from forge_jev.addressed import finding_file, parse_findings
17
+
18
+ JACCARD = 0.5
19
+ _WORDS = re.compile(r'[a-z]{4,}')
20
+
21
+
22
+ def _words(text) -> set[str]:
23
+ return set(_WORDS.findall(str(text or '').lower()))
24
+
25
+
26
+ def _same(item: dict, found: dict) -> bool:
27
+ """The same finding: the same file, and content words that overlap by at least JACCARD."""
28
+ if finding_file(item) != str(found.get('file') or '').removeprefix('./'):
29
+ return False
30
+ ours, theirs = _words(item.get('text')), _words(found.get('text'))
31
+ union = ours | theirs
32
+ return bool(union) and len(ours & theirs) / len(union) >= JACCARD
33
+
34
+
35
+ def _reviews(index) -> dict:
36
+ """(run, task, attempt) -> the last `qa` dispatch event, built once per collect()."""
37
+ if getattr(index, '_qa_reviews', None) is None:
38
+ found = {}
39
+ for event in sorted(index.store.of('dispatch'), key=lambda e: e['ts']):
40
+ if event['d'].get('role') == 'qa':
41
+ found[(event['run'], event['task'], event['attempt'])] = event
42
+ index._qa_reviews = found
43
+ return index._qa_reviews
44
+
45
+
46
+ def _attempt(value):
47
+ return value if isinstance(value, int) and not isinstance(value, bool) else None
48
+
49
+
50
+ def label(index, record, event, body) -> dict:
51
+ state = body.get('state') if isinstance(body, dict) else None
52
+ state = state if isinstance(state, dict) else {}
53
+ task, attempt = state.get('task'), _attempt(state.get('attempt'))
54
+ if not task or attempt is None:
55
+ return {}
56
+ review = _reviews(index).get((event['run'], task, attempt))
57
+ if review is None:
58
+ return {}
59
+ d = review['d']
60
+ if d.get('findings_parse') not in ('clean', 'graded'):
61
+ return {}
62
+ ref = (d.get('blobs') or {}).get('message')
63
+ raised = parse_findings(index.store.text(ref))
64
+ complete = not (isinstance(ref, dict) and ref.get('cut'))
65
+ items = {item.get('i'): item for item in state.get('findings') or [] if isinstance(item, dict)}
66
+ out = {}
67
+ for qid in record.decisions(body):
68
+ item = items.get(int(qid[1:]))
69
+ if item is None:
70
+ continue
71
+ if any(_same(item, found) for found in raised):
72
+ out[qid] = True
73
+ elif complete:
74
+ out[qid] = False
75
+ return out
@@ -0,0 +1,62 @@
1
+ """Labels for `jev-attribution` (#45): is the suspect a breaking merge?
2
+
3
+ `culprit:<id>` is true when the run's attribution search verified prefix k-1 (PASS) and prefix k
4
+ (FAIL) for the merge k of that task: the gate was right to put it first. It is false when both
5
+ prefixes were verified and they are not a pass then a fail. There is no label when either prefix
6
+ was never verified, and none at all when the search found the base failing, ended inconclusive,
7
+ or left no event.
8
+
9
+ These are facts about verified prefixes, whichever order the search took: a confirmed guess is
10
+ labelled by the same evidence as any other boundary, so a label never comes from the gate's own
11
+ choice.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+
17
+ PREFIX = 'culprit:'
18
+
19
+
20
+ def _events(index) -> dict:
21
+ """run -> the last `attribution` event's parsed blob, built once per collect()."""
22
+ if getattr(index, '_attributions', None) is None:
23
+ found = {}
24
+ for event in sorted(index.store.of('event'), key=lambda e: e['ts']):
25
+ d = event['d']
26
+ if d.get('name') != 'attribution':
27
+ continue
28
+ try:
29
+ doc = json.loads(index.store.text((d.get('blobs') or {}).get('attribution')) or 'null')
30
+ except ValueError:
31
+ continue
32
+ if isinstance(doc, dict):
33
+ found[event['run']] = doc
34
+ index._attributions = found
35
+ return index._attributions
36
+
37
+
38
+ def _statuses(doc) -> dict:
39
+ """prefix -> 'PASS' or 'FAIL', for the verified steps only."""
40
+ out = {}
41
+ for step in doc.get('steps') or []:
42
+ if isinstance(step, dict) and step.get('status') in ('PASS', 'FAIL') and isinstance(step.get('prefix'), int):
43
+ out.setdefault(step['prefix'], step['status'])
44
+ return out
45
+
46
+
47
+ def label(index, record, event, body) -> dict:
48
+ doc = _events(index).get(event['run']) if event.get('run') else None
49
+ if doc is None or doc.get('base_fails') or doc.get('inconclusive'):
50
+ return {}
51
+ numbers = {}
52
+ for k, merge in enumerate(doc.get('merges') or [], 1):
53
+ if isinstance(merge, dict) and merge.get('id') is not None:
54
+ numbers.setdefault(str(merge['id']), k)
55
+ steps = _statuses(doc)
56
+ out = {}
57
+ for qid in record.decisions(body):
58
+ k = numbers.get(qid[len(PREFIX):])
59
+ if k is None or k - 1 not in steps or k not in steps:
60
+ continue
61
+ out[qid] = steps[k - 1] == 'PASS' and steps[k] == 'FAIL'
62
+ return out
@@ -0,0 +1,81 @@
1
+ """The label of the `jev-coverage` site (#47): was the requirement really left uncovered?
2
+
3
+ True means uncovered: the gate should have sent the requirement back. For `r<i>` the requirement
4
+ is `state.requirements[i]` of the stored request.
5
+
6
+ true a later plan revision of the run has a task whose acceptance criteria hold at least
7
+ COVERED_SHARE of the requirement's content words, and the tasks the request asked
8
+ about had none
9
+ false every task of the run merged, and no later revision changed any task's criteria
10
+ no label a requirement the gate itself sent back (its sha is in `plan_gates.sent_back.coverage`
11
+ of any revision of the run): the rewrite that followed is the gate's own doing
12
+
13
+ Imported lazily by forge_decide.labels (`LABELLERS['jev-coverage']`); signature as the labellers
14
+ there: `label(index, record, event, body) -> {qid: bool}`.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ COVERED_SHARE = 0.6
19
+
20
+
21
+ def _criteria(index, plan) -> dict[str, str]:
22
+ """task -> its acceptance criteria (whitespace collapsed), from a plan event's stored prompts."""
23
+ from forge_jev import coverage
24
+ out = {}
25
+ tasks = plan['d'].get('tasks')
26
+ for task, row in (tasks if isinstance(tasks, dict) else {}).items():
27
+ ref = row.get('prompt') if isinstance(row, dict) else None
28
+ out[task] = ' '.join(coverage.acceptance_criteria(index.store.text(ref)).split())
29
+ return out
30
+
31
+
32
+ def _holds(words: set, criteria: dict[str, str]) -> bool:
33
+ from forge_jev import coverage
34
+ return any(len(words & coverage.content_words(text)) >= COVERED_SHARE * len(words)
35
+ for text in criteria.values())
36
+
37
+
38
+ def label(index, record, event, body) -> dict:
39
+ from forge_decide import labels
40
+ from forge_jev import coverage
41
+
42
+ state = labels._state(body)
43
+ requirements = state.get('requirements')
44
+ run = event['run']
45
+ plans = index.runs.plans.get(run, []) if run else []
46
+ if not plans or not isinstance(requirements, list):
47
+ return {}
48
+ asked_tasks = state.get('tasks') if isinstance(state.get('tasks'), list) else []
49
+ asked = {str(t.get('id')): ' '.join(str(t.get('acceptance_criteria') or '').split())
50
+ for t in asked_tasks if isinstance(t, dict)}
51
+ sent_back = set()
52
+ for plan in plans:
53
+ gates = plan['d'].get('plan_gates')
54
+ sent_back.update(((gates or {}).get('sent_back') or {}).get('coverage') or [])
55
+
56
+ later = [_criteria(index, plan) for plan in plans if plan['ts'] > event['ts']]
57
+ # A task the request never saw counts as changed when its criteria say anything.
58
+ # A task the request saw and a later revision dropped counts as changed too.
59
+ changed = any(text != asked.get(task, '') for criteria in later for task, text in criteria.items())
60
+ changed = changed or any(task not in criteria for criteria in later for task in asked)
61
+ # Every task of the run, in any revision, must have merged: a dropped task did not.
62
+ every = set(asked)
63
+ for plan in plans:
64
+ tasks = plan['d'].get('tasks')
65
+ every.update(tasks if isinstance(tasks, dict) else ())
66
+ merged = bool(every) and all(index.merged(run, task) for task in every)
67
+
68
+ out = {}
69
+ for qid in record.decisions(body):
70
+ i = coverage._index(qid)
71
+ if not 0 <= i < len(requirements):
72
+ continue
73
+ text = str(requirements[i])
74
+ words = coverage.content_words(text)
75
+ if not words or coverage.sha(text) in sent_back:
76
+ continue
77
+ if not _holds(words, asked) and any(_holds(words, criteria) for criteria in later):
78
+ out[qid] = True
79
+ elif merged and not changed:
80
+ out[qid] = False
81
+ return out
@@ -0,0 +1,38 @@
1
+ """Labels for `jev-dwarf-message` (#44): should the attempt have been sent back?
2
+
3
+ `unfinished` and `blocked` are true when the QA verdict of the request's task and attempt, in the
4
+ same run, was FAIL: the review rejected work the implementer had already said was not finished.
5
+ They are false when it was PASS. There is no label when that attempt has no review (the gate
6
+ sent it back, so a label must never come from the gate's own action), and `question` has none:
7
+ nothing downstream says whether the user needed to be asked.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ LABELLED = ('unfinished', 'blocked')
12
+
13
+
14
+ def _attempt(value):
15
+ return value if isinstance(value, int) and not isinstance(value, bool) else None
16
+
17
+
18
+ def _verdicts(index) -> dict:
19
+ """(run, task, attempt) -> the verdict of the last `qa` dispatch event, built once per collect()."""
20
+ if getattr(index, '_message_verdicts', None) is None:
21
+ found = {}
22
+ for event in sorted(index.store.of('dispatch'), key=lambda e: e['ts']):
23
+ if event['d'].get('role') == 'qa':
24
+ found[(event['run'], event['task'], event['attempt'])] = event['d'].get('verdict')
25
+ index._message_verdicts = found
26
+ return index._message_verdicts
27
+
28
+
29
+ def label(index, record, event, body) -> dict:
30
+ state = body.get('state') if isinstance(body, dict) else None
31
+ state = state if isinstance(state, dict) else {}
32
+ task, attempt = state.get('task'), _attempt(state.get('attempt'))
33
+ if not task or attempt is None:
34
+ return {}
35
+ verdict = _verdicts(index).get((event['run'], task, attempt))
36
+ if verdict not in ('PASS', 'FAIL'):
37
+ return {}
38
+ return {qid: verdict == 'FAIL' for qid in record.decisions(body) if qid in LABELLED}
@@ -0,0 +1,139 @@
1
+ """The free label of the prompt adequacy gate (GitHub #40): was the task's prompt inadequate?
2
+
3
+ `label(index, record, event, body) -> {qid: bool}` for qid `prompt_adequacy`, the signature of
4
+ the labellers in forge_decide.labels. **True means inadequate**: the gate should have sent the
5
+ task back. The site is inverted (forge_decide.sites: `invert`), so a fired task labelled true
6
+ is fired-right.
7
+
8
+ true the first attempt was reviewed, and either its review has a finding saying the task is
9
+ ambiguous, or the prompt it was dispatched with (the last plan revision at or before
10
+ its start) is a later revision's, with other text than the request scored
11
+ false the first attempt was reviewed, and neither
12
+ none the task is in `plan_gates.sent_back.prompt` of any revision (the gate acted, so what
13
+ followed is its own doing), the task never ran, its first review is missing or cannot
14
+ be read (a rewrite alone is then no label), the rewrite cannot be told (the request
15
+ has no prompt text, or the attempt's start is unknown), or the task was rewritten in a
16
+ plan with anything in `plan_gates.sent_back.coverage` (the planner may have rewritten
17
+ it to cover a requirement that gate sent back, which says nothing about this prompt)
18
+
19
+ The prompt of a revision is the plan event's per-task `prompt` blob; the scored one is the
20
+ request's `state.prompt`. The attempt starts at its dwarf dispatch's `wall_started`. The review
21
+ is the `qa` dispatch of attempt 1, its `blobs.message` parsed by forge-issues.py's
22
+ `parse_findings`.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import importlib.util
27
+ from pathlib import Path
28
+ import re
29
+
30
+ QID = 'prompt_adequacy'
31
+ AMBIGUOUS = re.compile(r'\b(ambiguous|unclear|underspecified|under-specified|not specified|'
32
+ r'unspecified|does not (say|specify))\b', re.I)
33
+ _issues = None
34
+
35
+
36
+ def _parse_findings(text):
37
+ """forge-issues.py's parse_findings: its file name is not importable, so loaded by path."""
38
+ global _issues
39
+ if _issues is None:
40
+ path = Path(__file__).resolve().parents[1] / 'forge-issues.py'
41
+ spec = importlib.util.spec_from_file_location('forge_issues', path)
42
+ _issues = importlib.util.module_from_spec(spec)
43
+ spec.loader.exec_module(_issues)
44
+ return _issues.parse_findings(text)
45
+
46
+
47
+ def _sent_back(plans, kind, task=None) -> bool:
48
+ """Whether any revision lists `task` (or, without one, anything) in `sent_back.<kind>`."""
49
+ for plan in plans:
50
+ gates = plan['d'].get('plan_gates')
51
+ sent = (gates.get('sent_back') if isinstance(gates, dict) else None)
52
+ listed = sent.get(kind) if isinstance(sent, dict) else None
53
+ if isinstance(listed, list) and (task in listed if task is not None else listed):
54
+ return True
55
+ return False
56
+
57
+
58
+ def _text(index, plan, task) -> str:
59
+ """The whole prompt of `task` in a revision, its plan-event blob; '' without one."""
60
+ row = (plan['d'].get('tasks') or {}).get(task)
61
+ return index.store.text(row.get('prompt') if isinstance(row, dict) else None)
62
+
63
+
64
+ def _seen(text: str) -> str:
65
+ """What the gate saw of a prompt: the first PROMPT_CHARS (`cmd_score_plan` sends no
66
+ more), stripped."""
67
+ from forge_jev.cli import PROMPT_CHARS
68
+ return text[:PROMPT_CHARS].strip()
69
+
70
+
71
+ def _started(index, first, run, task):
72
+ """When attempt 1 started: its dwarf dispatch's `wall_started`, else the attempt event's.
73
+ Never the event's `ts`, which records completion; None when neither says."""
74
+ for e in index.runs.dispatches.get((run, task, 'dwarf'), []):
75
+ if e['attempt'] == 1 and e['d'].get('wall_started'):
76
+ return float(e['d']['wall_started'])
77
+ return float(first['d']['wall_started']) if first['d'].get('wall_started') else None
78
+
79
+
80
+ def _rewritten(index, plans, task, scored, asked, started):
81
+ """Whether the prompt the first attempt was dispatched with is not the one the request
82
+ scored. The dispatched prompt is the last revision holding the task at or before
83
+ `started`; no revision after the request means no rewrite.
84
+
85
+ The request holds only what the gate saw (`_seen`), so a different seen part is a
86
+ rewrite. A rewrite past the cut is read from the whole prompts: the scored plan's own
87
+ snapshot is the first revision at or after the request (snapshots are taken after the
88
+ gate scores), and a dispatched prompt that differs from it was rewritten.
89
+
90
+ None when that cannot be told: the request has no prompt text (`scored` None; an empty
91
+ string is a prompt the gate scored empty), the start is unknown, or the snapshot after
92
+ the request is not the text the gate saw."""
93
+ if scored is None or started is None:
94
+ return None
95
+ held = [plan for plan in plans if task in (plan['d'].get('tasks') or {}) and plan['ts'] <= started]
96
+ if not held or held[-1]['ts'] <= asked:
97
+ return False
98
+ dispatched = _text(index, held[-1], task)
99
+ if _seen(dispatched) != scored:
100
+ return True
101
+ snapshot = _text(index, next(plan for plan in held if plan['ts'] >= asked), task)
102
+ if _seen(snapshot) != scored:
103
+ return None
104
+ return snapshot.strip() != dispatched.strip()
105
+
106
+
107
+ def _review(index, run, task):
108
+ """The first attempt's reviewer dispatch, or None."""
109
+ rows = [e for e in index.runs.dispatches.get((run, task, 'qa'), []) if e['attempt'] == 1]
110
+ return min(rows, key=lambda e: e['ts']) if rows else None
111
+
112
+
113
+ def label(index, record, event, body) -> dict:
114
+ from forge_decide import labels
115
+ state = labels._state(body)
116
+ task_state = state.get('task') if isinstance(state.get('task'), dict) else {}
117
+ task = task_state.get('id') or event.get('task')
118
+ if not task or QID not in record.decisions(body):
119
+ return {}
120
+ attempts = index.attempts(event['run'], event['repo'], task, event['ts'])
121
+ first = next((a for a in attempts if a['attempt'] == 1), None)
122
+ if first is None:
123
+ return {}
124
+ run = first['run']
125
+ plans = index.runs.plans.get(run, []) if run else []
126
+ if _sent_back(plans, 'prompt', task):
127
+ return {}
128
+ review = _review(index, run, task)
129
+ if review is None or review['d'].get('findings_parse') == 'unparseable':
130
+ return {}
131
+ found = _parse_findings(index.store.text((review['d'].get('blobs') or {}).get('message')))
132
+ if any(AMBIGUOUS.search(item.get('text') or '') for item in found):
133
+ return {QID: True}
134
+ scored = state.get('prompt')
135
+ rewritten = _rewritten(index, plans, task, scored.strip() if isinstance(scored, str) else None,
136
+ event['ts'], _started(index, first, run, task))
137
+ if rewritten and _sent_back(plans, 'coverage'):
138
+ return {}
139
+ return {} if rewritten is None else {QID: rewritten}