@giamme/forge 0.12.1 → 0.13.1

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 (111) hide show
  1. package/CHANGELOG.md +66 -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 +14 -4
  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 +763 -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 +22 -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 +457 -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 +39 -9
  50. package/scripts/forge-submodules.py +389 -0
  51. package/scripts/forge-ui-options.sh +25 -0
  52. package/scripts/forge_dataset/cli.py +12 -6
  53. package/scripts/forge_dataset/export.py +140 -84
  54. package/scripts/forge_dataset/harvest.py +33 -5
  55. package/scripts/{forge_jev/outcome.py → forge_dataset/states.py} +21 -7
  56. package/scripts/forge_decide/__init__.py +141 -0
  57. package/scripts/forge_decide/budget.py +180 -0
  58. package/scripts/forge_decide/cache.py +66 -0
  59. package/scripts/forge_decide/cli.py +953 -0
  60. package/scripts/forge_decide/doctor.py +270 -0
  61. package/scripts/forge_decide/label_addressed.py +75 -0
  62. package/scripts/forge_decide/label_attribution.py +62 -0
  63. package/scripts/forge_decide/label_coverage.py +81 -0
  64. package/scripts/forge_decide/label_message.py +38 -0
  65. package/scripts/forge_decide/label_prompt.py +139 -0
  66. package/scripts/forge_decide/labels.py +328 -0
  67. package/scripts/forge_decide/metrics.py +125 -0
  68. package/scripts/forge_decide/migrate.py +226 -0
  69. package/scripts/forge_decide/providers.py +292 -0
  70. package/scripts/forge_decide/replay.py +350 -0
  71. package/scripts/forge_decide/report.py +382 -0
  72. package/scripts/forge_decide/resolve.py +397 -0
  73. package/scripts/forge_decide/sites.py +377 -0
  74. package/scripts/forge_jev/__init__.py +202 -104
  75. package/scripts/forge_jev/addressed.py +171 -0
  76. package/scripts/forge_jev/attribution.py +198 -0
  77. package/scripts/forge_jev/cli.py +460 -382
  78. package/scripts/forge_jev/client.py +155 -77
  79. package/scripts/forge_jev/coupling.py +19 -87
  80. package/scripts/forge_jev/coverage.py +303 -0
  81. package/scripts/forge_jev/findings.py +219 -0
  82. package/scripts/forge_jev/gates.py +225 -27
  83. package/scripts/forge_jev/memory.py +65 -4
  84. package/scripts/forge_jev/message.py +134 -0
  85. package/scripts/forge_jev/plan_gates.py +294 -0
  86. package/scripts/forge_jev/questions.py +173 -313
  87. package/scripts/forge_jev/verify.py +130 -104
  88. package/ui/README.md +2 -2
  89. package/ui/docs/api.md +92 -39
  90. package/ui/forge_ui/control.py +71 -14
  91. package/ui/forge_ui/export.py +2 -1
  92. package/ui/forge_ui/models.py +17 -16
  93. package/ui/forge_ui/reader.py +132 -21
  94. package/ui/forge_ui/repos.py +428 -0
  95. package/ui/forge_ui/static/app.js +24 -5
  96. package/ui/forge_ui/static/cloudmodel.js +8 -5
  97. package/ui/forge_ui/static/controls.js +20 -13
  98. package/ui/forge_ui/static/modelstats.js +12 -8
  99. package/ui/forge_ui/static/panel.js +63 -17
  100. package/ui/forge_ui/static/runmodel.js +48 -7
  101. package/ui/forge_ui/static/scene3d.js +2 -15
  102. package/ui/forge_ui/static/settings.js +481 -68
  103. package/ui/forge_ui/static/style.css +56 -9
  104. package/references/jev.md +0 -865
  105. package/scripts/forge_jev/backtest.py +0 -322
  106. package/scripts/forge_jev/corpus.py +0 -156
  107. package/scripts/forge_jev/features.py +0 -24
  108. package/scripts/forge_jev/predict.py +0 -204
  109. package/scripts/forge_jev/review.py +0 -73
  110. package/scripts/forge_jev/routing.py +0 -271
  111. package/scripts/forge_jev/subset.py +0 -123
@@ -0,0 +1,328 @@
1
+ """Free labels for the live decision-model sites, read from the run dataset (GitHub #37).
2
+
3
+ A gate earns `on` only by being measured against a label that arrives for free after the
4
+ run. `collect(site)` turns the dataset store's stored live requests of one site into rows
5
+ of labelled decisions:
6
+
7
+ {site, gate, run, run_id, repo, ts, key, model, body, labels: {qid: bool}, live: {qid: p}}
8
+
9
+ `body` is the decoded request blob ({state, model, questions}); `live` is the site's
10
+ `score` of the event's own answers. A request with no labelled decision gives no row.
11
+
12
+ The labels, per site (forge_decide.sites names each in one sentence):
13
+
14
+ drift the undeclared file was edited by the task's final passing attempt
15
+ memory-slice the fact's anchor was edited by the task (true), or lies in an area
16
+ the task never touched (false); a request needs both classes
17
+ verify-discover the candidate is the command the repo documents
18
+ forward a later plan revision added the dependency (true); both tasks merged
19
+ with no such dependency (false)
20
+
21
+ The gate modules' labellers (label_prompt, label_coverage, label_addressed, label_message,
22
+ label_attribution) are read lazily: until a module exists its site has no rows. The memory
23
+ sites and findings have none.
24
+
25
+ The joins are the export's (forge_dataset.export: Store, Runs, the final passing
26
+ attempt, the memory rule), not a copy. The store is only read: never opened by
27
+ connect(), which creates and migrates it. Imported only by `forge decide` commands: the
28
+ store is never read by anything that builds a prompt.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ from collections import defaultdict
33
+ import json
34
+ from pathlib import Path
35
+ import sqlite3
36
+
37
+ from forge_dataset import dataset_dir
38
+ from forge_dataset import export
39
+ from forge_decide import sites
40
+
41
+
42
+ def _open_store() -> export.Store | None:
43
+ """The dataset store, read-only; None when there is none yet."""
44
+ path = dataset_dir() / 'dataset.sqlite'
45
+ if not path.is_file():
46
+ return None
47
+ db = sqlite3.connect(path.resolve().as_uri() + '?mode=ro', uri=True, timeout=5)
48
+ try:
49
+ return export.Store(db)
50
+ finally:
51
+ db.close()
52
+
53
+
54
+ def _body(store: export.Store, ref) -> dict | None:
55
+ """The decoded request body, or None when it is cut, gone or not a request."""
56
+ if not isinstance(ref, dict) or not ref.get('sha') or ref.get('cut'):
57
+ return None
58
+ try:
59
+ body = json.loads(store.text(ref) or 'null')
60
+ except (OSError, ValueError):
61
+ return None
62
+ return body if isinstance(body, dict) and isinstance(body.get('state'), dict) else None
63
+
64
+
65
+ def requests(store: export.Store, site: str) -> list[tuple[dict, dict]]:
66
+ """The stored live requests of a site, (event, body), the first per `key` by `ts`."""
67
+ out, seen = [], set()
68
+ for event in sorted(store.of('jev'), key=lambda e: e['ts']):
69
+ d = event['d']
70
+ if d.get('site') != site or d.get('ok') is not True or d.get('key') in seen:
71
+ continue
72
+ body = _body(store, (d.get('blobs') or {}).get('request'))
73
+ if body is None:
74
+ continue
75
+ seen.add(d.get('key'))
76
+ out.append((event, body))
77
+ return out
78
+
79
+
80
+ def _state(body) -> dict:
81
+ state = body.get('state')
82
+ return state if isinstance(state, dict) else {}
83
+
84
+
85
+ def _started(rows) -> float:
86
+ return min((e['d'].get('wall_started') or e['ts']) for e in rows)
87
+
88
+
89
+ class _Index:
90
+ """The joins every labeller shares, built once per collect()."""
91
+
92
+ def __init__(self, store: export.Store):
93
+ self.store = store
94
+ self.runs = export.Runs(store)
95
+ self._by_task = None
96
+ self._merged = None
97
+ self._documented = {}
98
+
99
+ def attempts(self, run, repo, task, ts) -> list:
100
+ """The task's attempts in the request's run. A `legacy-` run uid never joins its
101
+ attempts directly: those join by repo and task id, the run whose attempts started
102
+ first within DRIFT_JOIN_S after the request; two runs in that window are ambiguous."""
103
+ if run and not str(run).startswith('legacy-'):
104
+ return self.runs.attempts.get((run, task), [])
105
+ if self._by_task is None:
106
+ self._by_task = defaultdict(list)
107
+ for (attempt_run, attempt_task), rows in self.runs.attempts.items():
108
+ if rows:
109
+ self._by_task[(rows[0]['repo'], attempt_task)].append((_started(rows), attempt_run))
110
+ window = [(at, attempt_run) for at, attempt_run in self._by_task.get((repo, task), [])
111
+ if ts <= at <= ts + export.DRIFT_JOIN_S]
112
+ if len({attempt_run for _at, attempt_run in window}) != 1:
113
+ return []
114
+ return self.runs.attempts.get((window[0][1], task), [])
115
+
116
+ def merged(self, run, task) -> bool:
117
+ """Whether the task's last merge event in the run says MERGED."""
118
+ if self._merged is None:
119
+ last = {}
120
+ for e in sorted(self.store.of('event'), key=lambda e: e['ts']):
121
+ if e['d'].get('name') == 'merge' and e['task']:
122
+ last[(e['run'], e['task'])] = e['d'].get('status')
123
+ self._merged = {key for key, status in last.items() if status == 'MERGED'}
124
+ return (run, task) in self._merged
125
+
126
+ def documented(self, repo, ts) -> str | None:
127
+ """The command the repo documents: the first non-comment line of its .forge/verify
128
+ while the repo dir still has one, else the command of the latest verification of the
129
+ same repo after `ts` that did not come from Jev."""
130
+ if repo not in self._documented:
131
+ path = self.store.repo_paths.get(repo)
132
+ command = None
133
+ try:
134
+ if path and (Path(path) / '.forge' / 'verify').is_file():
135
+ lines = (Path(path) / '.forge' / 'verify').read_text(errors='replace').splitlines()
136
+ command = next((line.strip() for line in lines
137
+ if line.strip() and not line.strip().startswith('#')), None)
138
+ except OSError:
139
+ command = None
140
+ self._documented[repo] = command
141
+ if self._documented[repo]:
142
+ return self._documented[repo]
143
+ later = [e for e in self.store.of('verification')
144
+ if e['repo'] == repo and e['ts'] > ts and e['d'].get('command')
145
+ and e['d'].get('command_source') not in (None, 'jev')]
146
+ return max(later, key=lambda e: e['ts'])['d']['command'] if later else None
147
+
148
+
149
+ # --- labellers: (index, site record, event, body) -> {qid: bool} -------------------------
150
+
151
+ def _drift_added(index: _Index, run, task) -> set:
152
+ """The files any plan revision of the run recorded as added by the drift gate to `task`."""
153
+ out = set()
154
+ for plan in index.runs.plans.get(run, []) if run else []:
155
+ gates = plan['d'].get('plan_gates')
156
+ entry = ((gates.get('drift') or {}).get(task) if isinstance(gates, dict)
157
+ and isinstance(gates.get('drift'), dict) else None)
158
+ for item in (entry.get('added') if isinstance(entry, dict) else None) or []:
159
+ if isinstance(item, dict) and item.get('file'):
160
+ out.add(str(item['file']))
161
+ return out
162
+
163
+
164
+ def _drift(index: _Index, record, event, body) -> dict:
165
+ state = _state(body)
166
+ task = state.get('task') if isinstance(state.get('task'), dict) else {}
167
+ task_id = task.get('id')
168
+ if not task_id:
169
+ return {}
170
+ final = export.final_pass(index.attempts(event['run'], event['repo'], task_id, event['ts']))
171
+ if final is None:
172
+ return {}
173
+ changed = set(export.words(final['d'].get('changed_files')))
174
+ # A file the gate added to the column is declared in the attempt but not by the planner:
175
+ # whether the task edited it is still the label. Adding it changes the waves, not the edit.
176
+ added = _drift_added(index, final['run'], task_id)
177
+ declared = (set(export.words(task.get('declared_files')))
178
+ | (set(export.words(final['d'].get('declared_files'))) - added))
179
+ out = {}
180
+ for qid in record.decisions(body):
181
+ path = sites._drift_file(body, qid)
182
+ if path and path not in declared:
183
+ out[qid] = path in changed
184
+ return out
185
+
186
+
187
+ def _memory_slice(index: _Index, record, event, body) -> dict:
188
+ facts = _state(body).get('facts')
189
+ if not event['task'] or not isinstance(facts, list):
190
+ return {}
191
+ final = export.final_pass(index.runs.attempts.get((event['run'], event['task']), []))
192
+ if final is None:
193
+ return {}
194
+ changed = set(export.words(final['d'].get('changed_files')))
195
+ areas = {export.area(f) for f in changed | set(export.words(final['d'].get('declared_files')))}
196
+ out = {}
197
+ for qid in record.decisions(body):
198
+ i = sites._index(qid)
199
+ found = export.ANCHOR.search(str(facts[i])) if 0 <= i < len(facts) else None
200
+ if not found:
201
+ continue
202
+ anchors = export.words(found.group(1))
203
+ if any(a in changed for a in anchors):
204
+ out[qid] = True
205
+ elif not any(export.area(a) in areas for a in anchors):
206
+ out[qid] = False
207
+ # One class alone says nothing a ranking can be judged on.
208
+ return out if set(out.values()) == {True, False} else {}
209
+
210
+
211
+ def _verify_discover(index: _Index, record, event, body) -> dict:
212
+ commands = sites._commands(body) or []
213
+ documented = index.documented(event['repo'], event['ts'])
214
+ if not documented:
215
+ return {}
216
+ out = {}
217
+ for qid in record.decisions(body):
218
+ i = sites._index(qid)
219
+ if 0 <= i < len(commands) and commands[i]:
220
+ out[qid] = commands[i] == documented
221
+ return out
222
+
223
+
224
+ def _depends(plan, earlier, later) -> bool:
225
+ """Whether the plan revision lists `later` in `earlier`'s deps: the dependency the
226
+ forward question is about. The question asks whether EARLIER depends on what LATER
227
+ builds ("LATER is not a declared dependency of EARLIER"), and coupling.forward_pairs
228
+ drops a pair that already has it. `later` naming `earlier` is the order the waves
229
+ already run in, so it confirms nothing."""
230
+ row = (plan['d'].get('tasks') or {}).get(earlier) or {}
231
+ return later in export.words(row.get('deps'))
232
+
233
+
234
+ def _forward_added(plans) -> set:
235
+ """The (earlier, later) pairs any plan revision recorded as added by the forward gate."""
236
+ out = set()
237
+ for plan in plans:
238
+ gates = plan['d'].get('plan_gates')
239
+ forward = gates.get('forward') if isinstance(gates, dict) else None
240
+ for item in (forward.get('added') if isinstance(forward, dict) else None) or []:
241
+ if isinstance(item, dict) and item.get('earlier') and item.get('later'):
242
+ out.add((str(item['earlier']), str(item['later'])))
243
+ return out
244
+
245
+
246
+ def _removed(plans, earlier, later) -> bool:
247
+ """Whether a revision lacks the dep after an earlier revision had it."""
248
+ had = False
249
+ for plan in plans:
250
+ if _depends(plan, earlier, later):
251
+ had = True
252
+ elif had:
253
+ return True
254
+ return False
255
+
256
+
257
+ def _forward(index: _Index, record, event, body) -> dict:
258
+ run = event['run']
259
+ plans = index.runs.plans.get(run, []) if run else []
260
+ if not plans:
261
+ return {}
262
+ added = _forward_added(plans)
263
+ out = {}
264
+ for qid in record.decisions(body):
265
+ text = sites._instructions(body, qid)
266
+ earlier, later = sites._EARLIER.search(text), sites._LATER.search(text)
267
+ if not earlier or not later:
268
+ continue
269
+ earlier, later = earlier.group('id'), later.group('id')
270
+ if (earlier, later) in added:
271
+ # The gate wrote this dep, so its presence says nothing: only the user taking it
272
+ # out again does, and then the gate was wrong.
273
+ if _removed(plans, earlier, later):
274
+ out[qid] = False
275
+ elif any(_depends(plan, earlier, later) for plan in plans if plan['ts'] > event['ts']):
276
+ out[qid] = True
277
+ elif index.merged(run, earlier) and index.merged(run, later) and not _depends(plans[-1], earlier, later):
278
+ out[qid] = False
279
+ return out
280
+
281
+
282
+ LABELLERS = {
283
+ 'jev-drift': _drift,
284
+ 'jev-memory-slice': _memory_slice,
285
+ 'jev-verify-discover': _verify_discover,
286
+ 'jev-forward': _forward,
287
+ # The gate modules' own labellers, read lazily: `{}` (no rows) while a module is missing.
288
+ 'jev-prompt': sites._lazy('forge_decide.label_prompt', 'label', {}),
289
+ 'jev-coverage': sites._lazy('forge_decide.label_coverage', 'label', {}),
290
+ 'jev-retry-addressed': sites._lazy('forge_decide.label_addressed', 'label', {}),
291
+ 'jev-dwarf-message': sites._lazy('forge_decide.label_message', 'label', {}),
292
+ 'jev-attribution': sites._lazy('forge_decide.label_attribution', 'label', {}),
293
+ }
294
+
295
+
296
+ def collect(site: str, *, store: export.Store | None = None, runs=None) -> list[dict]:
297
+ """One row per stored live request of `site` with at least one labelled decision.
298
+
299
+ `store` is an already-open forge_dataset.export.Store; without one the store is opened
300
+ read-only. `runs`, when given, keeps only those dataset run uids. A site with no label
301
+ (prompt, memory-curate, memory-stale) or an unknown one returns []."""
302
+ record = sites.site(site)
303
+ labeller = LABELLERS.get(site)
304
+ if record is None or record.label is None or labeller is None:
305
+ return []
306
+ if store is None:
307
+ store = _open_store()
308
+ if store is None:
309
+ return []
310
+ index = _Index(store)
311
+ out = []
312
+ for event, body in requests(store, site):
313
+ if runs is not None and event['run'] not in runs:
314
+ continue
315
+ labels = labeller(index, record, event, body)
316
+ if not labels:
317
+ continue
318
+ answers = event['d'].get('answers') or {}
319
+ live = {}
320
+ for qid in labels:
321
+ p = record.score(answers, qid, body)
322
+ if p is not None:
323
+ live[qid] = float(p)
324
+ out.append(dict(site=site, gate=record.gate, run=event['run'], run_id=event['run_id'],
325
+ repo=event['repo'], ts=event['ts'], key=event['d'].get('key'),
326
+ model=event['d'].get('model') or body.get('model'), body=body,
327
+ labels=labels, live=live))
328
+ return out
@@ -0,0 +1,125 @@
1
+ """Statistics that decide whether a decision-model gate may be promoted to `on`.
2
+
3
+ Ported from the out-of-repo replay_score.py / analyze.py, so the 2026-10-16 drift numbers
4
+ reproduce. Pure functions over rows and pairs: standard library only, no I/O.
5
+
6
+ A row is a dict. `split` needs `run` and `ts`; `promotes` needs `run`, `label`, `replay`
7
+ and `baseline` (scores, higher = more likely positive; `replay` may be None for a
8
+ decision the replay did not answer, which then drops out of the replay's AUC).
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import random
13
+
14
+ MIN_DECISIONS = 30
15
+ MIN_RUNS = 8
16
+
17
+
18
+ def auc(pairs):
19
+ """Mann-Whitney AUC of [(score, label)]; tied scores share their average rank.
20
+ None unless both classes are present."""
21
+ pairs = list(pairs)
22
+ positives = sum(1 for _score, label in pairs if label)
23
+ negatives = len(pairs) - positives
24
+ if not positives or not negatives:
25
+ return None
26
+ ordered = sorted(((score, 1 if label else 0) for score, label in pairs), key=lambda item: item[0])
27
+ rank_sum = 0.0
28
+ i = 0
29
+ while i < len(ordered):
30
+ j = i
31
+ while j < len(ordered) and ordered[j][0] == ordered[i][0]:
32
+ j += 1
33
+ rank_sum += (i + j + 1) / 2.0 * sum(ordered[k][1] for k in range(i, j))
34
+ i = j
35
+ return (rank_sum - positives * (positives + 1) / 2.0) / (positives * negatives)
36
+
37
+
38
+ def split(rows):
39
+ """(calibrate, judged): runs ordered by their earliest `ts`, the older len//2 to
40
+ calibrate and the rest judged. Each is a list of the rows of those runs."""
41
+ first = {}
42
+ for row in rows:
43
+ first[row['run']] = min(first.get(row['run'], row['ts']), row['ts'])
44
+ ordered = sorted(first, key=lambda run: (first[run], run))
45
+ older = set(ordered[:len(ordered) // 2])
46
+ return ([row for row in rows if row['run'] in older],
47
+ [row for row in rows if row['run'] not in older])
48
+
49
+
50
+ def paired_bootstrap(rows, stat, *, n=2000, seed=7):
51
+ """95% interval of stat(rows), resampling whole runs, since decisions of one run are
52
+ not independent. `stat` returns a number or None (a resample it cannot judge, such as
53
+ one with a single class). None when fewer than n/2 resamples are valid."""
54
+ rng = random.Random(seed)
55
+ by_run = {}
56
+ for row in rows:
57
+ by_run.setdefault(row['run'], []).append(row)
58
+ keys = sorted(by_run)
59
+ if not keys:
60
+ return None
61
+ values = []
62
+ for _ in range(n):
63
+ sample = [row for key in (rng.choice(keys) for _ in keys) for row in by_run[key]]
64
+ value = stat(sample)
65
+ if value is not None:
66
+ values.append(value)
67
+ if len(values) < n / 2:
68
+ return None
69
+ values.sort()
70
+ # No -1 on the upper index, as replay_score._boot has it: the 2026-10-16 interval
71
+ # reproduces only with this rule.
72
+ return values[int(len(values) * 0.025)], values[int(len(values) * 0.975)]
73
+
74
+
75
+ def precision_at(pairs, threshold):
76
+ """{precision, recall, flagged} of the decisions scoring >= threshold. precision is
77
+ None when nothing is flagged, recall None when no decision is positive."""
78
+ pairs = [(score, bool(label)) for score, label in pairs]
79
+ flagged = [label for score, label in pairs if score >= threshold]
80
+ positives = sum(label for _score, label in pairs)
81
+ hits = sum(flagged)
82
+ return dict(precision=hits / len(flagged) if flagged else None,
83
+ recall=hits / positives if positives else None,
84
+ flagged=len(flagged))
85
+
86
+
87
+ def _difference(rows):
88
+ """AUC(replay) - AUC(baseline) over the rows both answered, None when undefined."""
89
+ both = [row for row in rows if row.get('replay') is not None and row.get('baseline') is not None]
90
+ replay = auc([(row['replay'], row['label']) for row in both])
91
+ baseline = auc([(row['baseline'], row['label']) for row in both])
92
+ return None if replay is None or baseline is None else replay - baseline
93
+
94
+
95
+ def promotes(judged_rows, *, margin=0.02, floor=None, threshold=None):
96
+ """The promotion rule over the judged half: (passes, reason). Needs
97
+
98
+ 1. at least 30 labelled decisions,
99
+ 2. from at least 8 runs,
100
+ 3. the lower bound of the paired interval of AUC(replay) - AUC(baseline) > -margin,
101
+ 4. when `floor` is set, precision of the replay at `threshold` >= floor.
102
+
103
+ `reason` names the first failed condition, else "passes"."""
104
+ rows = [row for row in judged_rows if row.get('label') is not None]
105
+ runs = {row['run'] for row in rows}
106
+ if len(rows) < MIN_DECISIONS:
107
+ return False, f'only {len(rows)} labelled decisions in the judged half, need {MIN_DECISIONS}'
108
+ if len(runs) < MIN_RUNS:
109
+ return False, f'only {len(runs)} judged runs, need {MIN_RUNS}'
110
+ interval = paired_bootstrap(rows, _difference)
111
+ if interval is None:
112
+ return False, 'the replay and the baseline cannot be compared (a class is missing or too few resamples)'
113
+ if not interval[0] > -margin:
114
+ return False, (f'replay is worse than the cheap baseline: AUC difference lower bound '
115
+ f'{interval[0]:.3f} is not above -{margin}')
116
+ if floor is not None:
117
+ if threshold is None:
118
+ return False, 'the precision floor needs a threshold'
119
+ got = precision_at([(row['replay'], row['label']) for row in rows
120
+ if row.get('replay') is not None], threshold)['precision']
121
+ if got is None:
122
+ return False, f'the replay flags nothing at {threshold}, so precision cannot reach {floor}'
123
+ if got < floor:
124
+ return False, f'precision {got:.3f} at {threshold} is below the floor {floor}'
125
+ return True, 'passes'
@@ -0,0 +1,226 @@
1
+ """One-time migration of the legacy decision-model settings into the user decide.json.
2
+
3
+ derive(jev_cfg, cloudflare) -> (decide_dict, keys)
4
+ preview() -> decide_dict | None
5
+ run(*, force=False) -> {"status": "exists" | "nothing" | "migrated", ...}
6
+
7
+ The legacy settings are jev.json (the TypeSafe key, `enabled`, the capability map, thresholds,
8
+ `model_thresholds`, `providers.cloudflare` and the `sites` map), cloudflare.env and the
9
+ CLOUDFLARE_API_TOKEN variable. TypeSafe becomes the `jev` provider `typesafe`, Cloudflare the
10
+ `clef` provider `cloudflare`. A gate the legacy config turned `on` is written with
11
+ "force": true: it keeps acting as before, and shows as forced until a replay passes.
12
+
13
+ Keys are secrets. A key lives in a mode-0600 file under config_dir()/keys/, or stays where it
14
+ already is (a token in cloudflare.env, or in the environment) with the provider pointing at it.
15
+ It never appears in decide.json, in a return value, in an exception message or on stdout.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ from datetime import datetime, timezone
20
+ import os
21
+ from pathlib import Path
22
+ import uuid
23
+
24
+ from . import GATE_CAPABILITY, GATE_SITE, GATES, config_dir, save_user, user_path
25
+
26
+ # Which gates read each threshold.
27
+ THRESHOLD_GATES = {
28
+ 'gate_warn': ('drift', 'memory-curate'),
29
+ 'drift_warn': ('drift',),
30
+ 'forward_warn': ('forward',),
31
+ 'prompt_warn': ('prompt',),
32
+ 'memory_merge': ('memory-curate',),
33
+ 'memory_recategorize': ('memory-curate',),
34
+ 'stale_drop': ('memory-stale',),
35
+ 'tests_act': ('verify-discover',),
36
+ 'coverage_warn': ('coverage',),
37
+ 'untouched_warn': ('retry-addressed',),
38
+ 'message_warn': ('dwarf-message',),
39
+ 'message_ask': ('dwarf-message',),
40
+ 'findings_dup': ('findings',),
41
+ 'findings_concrete': ('findings',),
42
+ }
43
+ # Thresholds whose reader #35 removed (routing, review triage, coupling, verify triage),
44
+ # on top of forge_jev.RETIRED_THRESHOLDS: stored values are ignored, never copied.
45
+ REMOVED_THRESHOLDS = frozenset(('verifiable_warn', 'coupling_warn', 'flake_act'))
46
+ # Capability -> the mode its gates get when the legacy config is enabled.
47
+ CAPABILITY_MODE = {'memory': 'on', 'tests': 'on', 'gates': 'shadow'}
48
+ KEYS_DIR = 'keys'
49
+
50
+
51
+ def retired_thresholds() -> frozenset:
52
+ import forge_jev
53
+ return frozenset(forge_jev.RETIRED_THRESHOLDS) | REMOVED_THRESHOLDS
54
+
55
+
56
+ def _token_sources(config: dict, cf: dict) -> tuple[str | None, tuple[str, str] | None]:
57
+ """Cloudflare's token sources in forge_jev's order: the variable name for `key_env` when
58
+ CLOUDFLARE_API_TOKEN is set, then the persistent fallback forge_jev reads when it is not,
59
+ as ('key', token) for a token stored inline in jev.json (it needs a key file) or ('file',
60
+ path) for a token file, the path as the provider should name it. Both are kept when both
61
+ exist, so the migrated provider reads the environment first and the file second."""
62
+ import forge_jev
63
+ if not cf.get('token'):
64
+ return None, None
65
+ env = 'CLOUDFLARE_API_TOKEN' if os.environ.get('CLOUDFLARE_API_TOKEN') else None
66
+ entry = (config.get('providers') or {}).get('cloudflare')
67
+ entry = entry if isinstance(entry, dict) else {}
68
+ if entry.get('token'):
69
+ return env, ('key', entry['token'])
70
+ configured = entry.get('token_file') or str(forge_jev.config_path().parent / forge_jev.CLOUDFLARE_TOKEN_FILE)
71
+ if not forge_jev._env_file(configured).get('CLOUDFLARE_API_TOKEN'):
72
+ return env, None
73
+ # forge_jev reads a relative token_file against the working directory; the provider's
74
+ # key_file is read against config_dir(), so pin the path down before it is stored.
75
+ path = Path(os.path.abspath(Path(configured).expanduser()))
76
+ try:
77
+ return env, ('file', str(path.relative_to(config_dir())))
78
+ except ValueError:
79
+ return env, ('file', str(path))
80
+
81
+
82
+ def derive(jev_cfg: dict, cloudflare: dict | None) -> tuple[dict, dict]:
83
+ """(decide_dict, keys): the user decide.json for a legacy config, and {provider: secret}
84
+ for the keys that must be written to key files. `jev_cfg` is forge_jev.load_config(),
85
+ `cloudflare` is forge_jev.cloudflare(jev_cfg)."""
86
+ import forge_jev
87
+ retired = retired_thresholds()
88
+ providers: dict = {}
89
+ keys: dict = {}
90
+ # The key is looked up as forge_jev.api_key() does: TYPESAFE_API_KEY, then jev.json's key.
91
+ # The provider names each source found; providers.py reads key_env before key_file.
92
+ if os.environ.get('TYPESAFE_API_KEY') or jev_cfg.get('key'):
93
+ entry = dict(type='jev', url=jev_cfg.get('endpoint') or forge_jev.ENDPOINT,
94
+ model=jev_cfg.get('model') or forge_jev.MODEL)
95
+ if os.environ.get('TYPESAFE_API_KEY'):
96
+ entry['key_env'] = 'TYPESAFE_API_KEY'
97
+ if jev_cfg.get('key'):
98
+ entry['key_file'] = f'{KEYS_DIR}/typesafe.key'
99
+ keys['typesafe'] = jev_cfg['key']
100
+ entry['local'] = False
101
+ providers['typesafe'] = entry
102
+ if cloudflare is not None:
103
+ url = (cloudflare.get('url') or forge_jev.CLOUDFLARE_URL)
104
+ if cloudflare.get('account_id'):
105
+ url = url.replace('{account}', cloudflare['account_id'])
106
+ url = url.replace('{model}', cloudflare['model'])
107
+ entry = dict(type='clef', url=url, model=cloudflare['model'])
108
+ key_env, fallback = _token_sources(jev_cfg, cloudflare)
109
+ if key_env:
110
+ entry['key_env'] = key_env
111
+ if fallback and fallback[0] == 'file':
112
+ entry['key_file'] = fallback[1]
113
+ elif fallback:
114
+ entry['key_file'] = f'{KEYS_DIR}/cloudflare.key'
115
+ keys['cloudflare'] = fallback[1]
116
+ entry['local'] = False
117
+ providers['cloudflare'] = entry
118
+
119
+ sites = jev_cfg.get('sites') or {}
120
+ capabilities = jev_cfg.get('capabilities') or {}
121
+ thresholds = jev_cfg.get('thresholds') or {}
122
+ model_thresholds = jev_cfg.get('model_thresholds') or {}
123
+ gates: dict = {}
124
+ for gate in GATES:
125
+ name = 'cloudflare' if sites.get(GATE_SITE[gate]) == 'cloudflare' else 'typesafe'
126
+ entry = {}
127
+ if name in providers:
128
+ entry['provider'] = name
129
+ capability = GATE_CAPABILITY[gate]
130
+ if jev_cfg.get('enabled') and capability in CAPABILITY_MODE and capabilities.get(capability, True):
131
+ entry['mode'] = CAPABILITY_MODE[capability]
132
+ if entry['mode'] == 'on':
133
+ entry['force'] = True
134
+ model = providers.get(name, {}).get('model')
135
+ values = {key: value for key, value in thresholds.items()
136
+ if key not in retired and gate in THRESHOLD_GATES.get(key, ())}
137
+ per_model = model_thresholds.get(model) if model else None
138
+ if isinstance(per_model, dict):
139
+ values.update({key: value for key, value in per_model.items()
140
+ if key not in retired and gate in THRESHOLD_GATES.get(key, ())})
141
+ if values:
142
+ entry['thresholds'] = values
143
+ if model:
144
+ entry['thresholds_model'] = model
145
+ if entry:
146
+ gates[gate] = entry
147
+
148
+ decide = dict(version=1, gates=gates, providers=providers,
149
+ migrated_from={'jev.json': datetime.now(timezone.utc).isoformat(timespec='seconds')})
150
+ return decide, keys
151
+
152
+
153
+ def _write_key(name: str, secret: str) -> None:
154
+ directory = config_dir() / KEYS_DIR
155
+ directory.mkdir(parents=True, exist_ok=True)
156
+ directory.chmod(0o700) # also for a keys/ directory that was already there
157
+ path = directory / f'{name}.key'
158
+ temporary = path.with_name(path.name + '.' + uuid.uuid4().hex)
159
+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
160
+ try:
161
+ with os.fdopen(fd, 'w') as handle:
162
+ handle.write(secret)
163
+ os.chmod(temporary, 0o600)
164
+ os.replace(temporary, path)
165
+ except BaseException:
166
+ try:
167
+ os.unlink(temporary)
168
+ except OSError:
169
+ pass
170
+ raise
171
+
172
+
173
+ def _stored_thresholds(config: dict) -> dict:
174
+ """The thresholds jev.json itself holds: load_config() fills in every default, and copying
175
+ those would pin today's defaults into the user's file."""
176
+ import forge_jev
177
+ try:
178
+ stored = forge_jev.read_json(forge_jev.config_path()).get('thresholds')
179
+ except (OSError, ValueError, AttributeError):
180
+ return {}
181
+ return {key: value for key, value in stored.items() if isinstance(key, str)} \
182
+ if isinstance(stored, dict) else {}
183
+
184
+
185
+ def _derived() -> tuple[dict, dict] | None:
186
+ """derive()'s (decide_dict, keys) for the legacy settings on disk, or None when there is
187
+ no jev.json and no Cloudflare token. Writes nothing."""
188
+ import forge_jev
189
+ config = forge_jev.load_config()
190
+ cloudflare = forge_jev.cloudflare(config)
191
+ if cloudflare is None and forge_jev._env_file(
192
+ str(forge_jev.config_path().parent / forge_jev.CLOUDFLARE_TOKEN_FILE)).get('CLOUDFLARE_API_TOKEN'):
193
+ # A standalone cloudflare.env (no jev.json entry, no environment token) is still a credential.
194
+ config = dict(config, providers=dict(config.get('providers') or {}, cloudflare={}))
195
+ cloudflare = forge_jev.cloudflare(config)
196
+ if not forge_jev.config_path().exists() and not (cloudflare and cloudflare.get('token')):
197
+ return None
198
+ return derive(dict(config, thresholds=_stored_thresholds(config)), cloudflare)
199
+
200
+
201
+ def preview() -> dict | None:
202
+ """The decide.json run() would write, without writing it or any key file; None when
203
+ decide.json already exists or there is nothing to migrate."""
204
+ if user_path().exists():
205
+ return None
206
+ derived = _derived()
207
+ return derived[0] if derived else None
208
+
209
+
210
+ def run(*, force: bool = False) -> dict:
211
+ """Write decide.json (and key files) from the legacy settings, once.
212
+
213
+ {"status": "exists"} when decide.json is already there (and `force` is false), nothing
214
+ written; {"status": "nothing"} when there is no jev.json and no Cloudflare token;
215
+ otherwise {"status": "migrated", "providers": [names], "gates": {gate: settings}}. No
216
+ key is in the result."""
217
+ if user_path().exists() and not force:
218
+ return {'status': 'exists'}
219
+ derived = _derived()
220
+ if derived is None:
221
+ return {'status': 'nothing'}
222
+ decide, keys = derived
223
+ for name, secret in keys.items():
224
+ _write_key(name, secret)
225
+ save_user(decide)
226
+ return {'status': 'migrated', 'providers': sorted(decide['providers']), 'gates': decide['gates']}