@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
@@ -5,14 +5,18 @@ import importlib.util
5
5
  import json
6
6
  import os
7
7
  from pathlib import Path
8
+ import sys
9
+ import time
8
10
  import uuid
9
11
 
10
12
  SCRIPTS = Path(__file__).resolve().parents[1]
13
+ if str(SCRIPTS) not in sys.path:
14
+ sys.path.insert(0, str(SCRIPTS))
11
15
 
12
16
  ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
13
17
  MODEL = 'jev-latest'
14
18
  CAPABILITIES = ('routing', 'tests', 'gates', 'memory')
15
- DEFAULT_THRESHOLDS = dict(tests_act=0.70, flake_act=0.90,
19
+ DEFAULT_THRESHOLDS = dict(tests_act=0.70,
16
20
  gate_warn=0.60,
17
21
  # Measured twice. The first 15 prompts were hand-written and
18
22
  # scored with only a task TITLE in state, because prompt.md did
@@ -28,54 +32,9 @@ DEFAULT_THRESHOLDS = dict(tests_act=0.70, flake_act=0.90,
28
32
  # both sides, against a measured repeat-noise of 0.07.
29
33
  # 0.30 also classified every case correctly, but sat 0.03 above
30
34
  # the worst true positive -- correct by luck, not by margin.
35
+ # That state is what gates.task_state builds for jev-prompt.
31
36
  prompt_warn=0.55,
32
- # The rubric asked whether verifying a task needs "work
33
- # declared in a different task" while the state contained no
34
- # other task, so the model could only guess whether one
35
- # existed. That, not the wording, is why the classes used to
36
- # overlap. The plan is now in state (routing._siblings) and the
37
- # rubric points at it by name.
38
- #
39
- # Re-measured on the 8 real jevscope tasks, ground truth taken
40
- # from the import graph and wave position rather than from the
41
- # titles: `server` (wave 1, imports discover/events/stats and
42
- # serves page's index.html, none declared) 0.26-0.34; `page`
43
- # (consumes server's API -- both defects that shipped were
44
- # page<->events shape mismatches) 0.43-0.53; `readme`
45
- # (documents the wave-2 CLI, and shipped wrong) 0.60-0.65.
46
- # Genuinely self-contained tasks scored 0.65-0.96.
47
- #
48
- # At the old 0.38 this gate caught NOTHING on a real plan, the
49
- # same way coupling never fired: every fragment scored above
50
- # it. 0.55 catches server (0.21 clear) and page (0.02 clear --
51
- # marginal, counted as recall but not relied on), misses readme
52
- # entirely, and keeps 0.10 to the nearest true negative, which
53
- # is the only margin here that beats the 0.07 noise floor.
54
- # Precision is what an advisory gate must hold: a gate that
55
- # cries wolf is one people switch off.
56
- #
57
- # `readme` is not separable from a real task by this rubric --
58
- # it sits at 0.65 alongside `cli` at 0.65 -- so silence above
59
- # 0.55 still means "no evidence", not "verifiable".
60
- #
61
- # Equal to prompt_warn by coincidence, not by kinship. They
62
- # were measured separately against different rubrics and must
63
- # stay separate keys; collapsing them into one constant is the
64
- # exact mistake this file has now recorded six times.
65
- verifiable_warn=0.55,
66
- # Coupling borrowed gate_warn (0.60) and therefore never fired
67
- # once, on any plan. Measured over 11 same-wave pairs from a
68
- # real 8-task plan, 5 runs each, with ground truth taken from
69
- # the run itself -- two of those pairs produced a defect that
70
- # actually shipped. Coupling probabilities live at 0.09-0.27.
71
- # 0.60 was not a strict threshold, it was unreachable.
72
- #
73
- # At 0.20: 4 of 5 genuinely coupled pairs warn, 0 of 6
74
- # independent ones do. Provisional -- one plan, one repo, and
75
- # margins of about 0.02 either side -- but a gate that fires on
76
- # the right pairs 4 times in 5 beats one that cannot fire.
77
- coupling_warn=0.20,
78
- # The ordering question coupling could not ask: an earlier-wave
37
+ # The ordering question: an earlier-wave
79
38
  # task written against what a LATER task builds. jevscope's
80
39
  # `readme` ran in wave 1 documenting the wave-2 CLI, passed its
81
40
  # own review because the thing it was wrong about did not exist
@@ -108,12 +67,24 @@ DEFAULT_THRESHOLDS = dict(tests_act=0.70, flake_act=0.90,
108
67
  memory_recategorize=0.80,
109
68
  # Deliberately far below gate_warn: dropping a fact is
110
69
  # irreversible, so only a confident "this went false" acts.
111
- stale_drop=0.25)
70
+ stale_drop=0.25,
71
+ # Unmeasured: a starting point until a replay sets it.
72
+ coverage_warn=0.50,
73
+ # Unmeasured: a starting point until a replay sets it.
74
+ untouched_warn=0.70,
75
+ # Unmeasured: a starting point until a replay sets it.
76
+ message_warn=0.70,
77
+ # Unmeasured: a starting point until a replay sets it.
78
+ message_ask=0.70,
79
+ # Unmeasured: a starting point until a replay sets it.
80
+ findings_dup=0.85,
81
+ # Unmeasured: a starting point until a replay sets it.
82
+ findings_concrete=0.50)
112
83
  DEFAULTS = dict(enabled=False, key='', model=MODEL, endpoint=ENDPOINT, deadline_s=5.0,
113
84
  capabilities={c: True for c in CAPABILITIES},
114
85
  thresholds=dict(DEFAULT_THRESHOLDS),
115
86
  # A second provider, per site. Empty means every site asks TypeSafe exactly
116
- # as before; see "Cloudflare Clef" in references/jev.md.
87
+ # as before; see "Cloudflare Clef" in references/decision-models.md.
117
88
  providers={}, sites={}, model_thresholds={})
118
89
 
119
90
  # Cloudflare Workers AI's hosted Clef: Jev's request shape, a different envelope and
@@ -129,17 +100,18 @@ CLOUDFLARE_MAX_QUESTIONS = 64
129
100
  CLOUDFLARE_TOKEN_FILE = 'cloudflare.env'
130
101
 
131
102
  # Which capability each site belongs to, so a site on a provider with no credentials is
132
- # not ready even when its capability is on. clef-* sites exist only on Cloudflare: they
133
- # ask rubrics TypeSafe was never measured on, and record silently.
103
+ # not ready even when its capability is on. A site with None has no legacy capability: its
104
+ # gate's own mode alone makes it ready (#43-#47).
134
105
  SITE_CAPABILITY = {
135
- 'jev-score-plan': 'routing',
136
- 'clef-first-pass': 'routing', 'clef-retry-pass': 'routing',
137
- 'jev-drift': 'gates', 'jev-coupling': 'gates', 'jev-forward': 'gates',
138
- 'jev-review-triage': 'gates',
106
+ 'jev-prompt': 'gates', 'jev-drift': 'gates', 'jev-forward': 'gates',
139
107
  'jev-memory-curate': 'memory', 'jev-memory-stale': 'memory', 'jev-memory-slice': 'memory',
140
- 'jev-test-subset': 'tests', 'jev-verify-discover': 'tests', 'jev-verify-triage': 'tests',
108
+ 'jev-verify-discover': 'tests',
109
+ 'jev-coverage': None, 'jev-retry-addressed': None, 'jev-dwarf-message': None,
110
+ 'jev-attribution': None, 'jev-findings': None,
141
111
  }
142
- CLEF_ONLY_SITES = ('clef-first-pass', 'clef-retry-pass')
112
+ # routing's rubrics are gone. The name stays in CAPABILITIES so old configs, frozen
113
+ # selections and --jev-routing keep parsing, but the capability has no sites.
114
+ RETIRED_CAPABILITIES = frozenset(('routing',))
143
115
 
144
116
  # Loaded via importlib rather than a package-relative import: forge-runtime.py lives one
145
117
  # directory up and is not itself part of a package (same trick as forge_fractal).
@@ -260,13 +232,13 @@ def secrets(config: dict | None = None) -> list:
260
232
  return [s for s in out if s]
261
233
 
262
234
 
263
- def provider_for(site: str, config: dict | None = None) -> str:
264
- """Which provider answers `site`: the site map, unless an env override says otherwise."""
265
- if site in CLEF_ONLY_SITES:
266
- return 'cloudflare'
267
- if os.environ.get('FORGE_CLEF') == 'off':
235
+ def provider_for(site: str, config: dict | None = None, env=None) -> str:
236
+ """Which provider answers `site`: the site map, unless an env override says otherwise.
237
+ `env` stands in for os.environ (an empty one gives the configured provider alone)."""
238
+ env = os.environ if env is None else env
239
+ if env.get('FORGE_CLEF') == 'off':
268
240
  return 'typesafe'
269
- forced = os.environ.get('FORGE_JEV_PROVIDER')
241
+ forced = env.get('FORGE_JEV_PROVIDER')
270
242
  if forced in PROVIDERS:
271
243
  return forced
272
244
  config = config if config is not None else load_config()
@@ -282,60 +254,184 @@ def provider_ready(name: str, config: dict | None = None) -> bool:
282
254
  return api_key(config) is not None
283
255
 
284
256
 
257
+ # Each site now answers to its own gate (forge_decide): off, shadow or on, resolved across
258
+ # six levels. Without a user decide.json the resolver's legacy level reproduces jev.json and
259
+ # the FORGE_JEV* variables, so the capability switches above still decide there.
260
+ #
261
+ # The repo whose .forge/decide.json applies: a command that knows it (--repo, --anchor)
262
+ # sets it for its own duration; otherwise FORGE_DECIDE_REPO, else none (no repo level and
263
+ # no privacy floor here; client.ask still checks the floor of the repo it finds).
264
+ _repo_override: str | None = None
265
+ # One command asks several gates; it reads the files once. The key holds everything the
266
+ # resolution reads, so a changed file or variable is never served stale.
267
+ _CACHE_S = 2.0
268
+ _cache: dict = {}
269
+
270
+
271
+ def use_repo(repo) -> None:
272
+ global _repo_override
273
+ _repo_override = str(Path(repo).resolve()) if repo else None
274
+
275
+
276
+ def current_repo() -> str | None:
277
+ return _repo_override or os.environ.get('FORGE_DECIDE_REPO') or None
278
+
279
+
280
+ def _stamp(path: Path):
281
+ try:
282
+ st = path.stat()
283
+ except OSError:
284
+ return None
285
+ return st.st_mtime_ns, st.st_size
286
+
287
+
288
+ def _resolved(config: dict | None = None) -> dict:
289
+ """forge_decide.resolve.resolve() for current_repo(), cached for _CACHE_S. With an
290
+ explicit `config` that is not jev.json's (tests, a probe), the legacy level is
291
+ re-derived from it, as enabled(config=) always did."""
292
+ import forge_decide
293
+ from forge_decide import resolve as resolve_module
294
+ repo = current_repo()
295
+ env = tuple(sorted((k, v) for k, v in os.environ.items()
296
+ if k.startswith(('FORGE_', 'XDG_')) or k == 'HOME'))
297
+ files = (_stamp(forge_decide.user_path()), _stamp(config_path()),
298
+ _stamp(forge_decide.repo_path(repo)) if repo else None)
299
+ key = (repo, env, files)
300
+ hit = _cache.get('entry')
301
+ if hit and hit[0] == key and time.monotonic() - hit[1] < _CACHE_S:
302
+ result = hit[2]
303
+ else:
304
+ result = resolve_module.resolve(repo)
305
+ _cache['entry'] = (key, time.monotonic(), result)
306
+ if config is None or forge_decide.user_path().exists() or config == load_config():
307
+ return result
308
+ result = json.loads(json.dumps(result))
309
+ for gate, value in result['gates'].items():
310
+ capability = forge_decide.GATE_CAPABILITY[gate]
311
+ if value['skip'] or capability is None or value['source'] not in ('default', 'legacy', 'repo'):
312
+ continue
313
+ if resolve_module._legacy_enabled(capability, os.environ, config):
314
+ # Before migration FORGE_JEV_SHADOW marks records only: the gate stays on.
315
+ value['mode'], value['source'] = 'on', 'legacy'
316
+ elif value['source'] != 'repo':
317
+ value['mode'], value['source'] = 'off', 'legacy'
318
+ return result
319
+
320
+
321
+ def _gate(site: str, resolved: dict) -> dict | None:
322
+ import forge_decide
323
+ return resolved['gates'].get(forge_decide.SITE_GATE.get(site))
324
+
325
+
326
+ def gate_mode(site: str) -> str:
327
+ """'off', 'shadow' or 'on': the resolved mode of the site's gate. An unknown site is off."""
328
+ gate = _gate(site, _resolved())
329
+ return gate['mode'] if gate else 'off'
330
+
331
+
332
+ def plan_gate_mode(site: str) -> str:
333
+ """The mode a plan-time gate that changes the plan (drift, forward, prompt) acts in:
334
+ gate_mode(site), except that under --jev-shadow a gate the legacy level turned on (no user
335
+ decide.json yet) is 'shadow'. Its records were always marked shadow (client._gate_fields);
336
+ now that these gates act in `on` (#38–#40), a flag that promises no change keeps them from
337
+ acting too."""
338
+ gate = _gate(site, _resolved())
339
+ mode = gate['mode'] if gate else 'off'
340
+ if mode == 'on' and gate.get('source') == 'legacy' and shadow():
341
+ return 'shadow'
342
+ return mode
343
+
344
+
345
+ def _spec(site: str, config: dict | None, resolved: dict) -> dict:
346
+ from forge_decide import providers
347
+ return providers.spec_for_site(site, config=config, repo=current_repo(), resolved=resolved)
348
+
349
+
350
+ def gate_reason(site: str, config: dict | None = None) -> str | None:
351
+ """Why the site cannot be asked: None when it can, else 'privacy', 'kill', 'off',
352
+ 'no-provider' (the gate names a provider that is not configured, or one with no
353
+ address) or 'no-key'."""
354
+ import forge_decide
355
+ resolved = _resolved(config)
356
+ gate = _gate(site, resolved)
357
+ if gate is None:
358
+ return 'off'
359
+ if gate['skip']:
360
+ return gate['skip']
361
+ if gate['mode'] == 'off':
362
+ return 'off'
363
+ if gate['provider']:
364
+ user, _ = forge_decide.load_user()
365
+ stored = user.get('providers')
366
+ if not isinstance(stored, dict) or not isinstance(stored.get(gate['provider']), dict):
367
+ return 'no-provider'
368
+ spec = _spec(site, config, resolved)
369
+ if not spec['url']:
370
+ return 'no-provider'
371
+ if not spec['key'] and not spec['local']:
372
+ return 'no-key'
373
+ return None
374
+
375
+
285
376
  def site_ready(site: str, config: dict | None = None) -> bool:
286
- """The site's capability is on and its provider has credentials. Offline: reads config only."""
287
- config = config if config is not None else load_config()
288
- capability = SITE_CAPABILITY.get(site)
289
- if not enabled(capability, config=config):
290
- return False
291
- if site in CLEF_ONLY_SITES:
292
- entry = (config.get('providers') or {}).get('cloudflare')
293
- if (os.environ.get('FORGE_CLEF') == 'off' or os.environ.get('FORGE_JEV_OUTCOMES') == 'off'
294
- or (isinstance(entry, dict) and entry.get('outcomes') is False)):
295
- return False
296
- return provider_ready(provider_for(site, config), config)
377
+ """The site's gate is shadow or on, nothing skips it, and its provider can be asked: a
378
+ key, or a local provider. Offline: reads config only."""
379
+ return gate_reason(site, config) is None
297
380
 
298
381
 
299
382
  def capability_ready(capability: str, config: dict | None = None) -> bool:
300
- """Some site of this capability can be asked: what the shell's forge_jev_active tests."""
301
- config = config if config is not None else load_config()
383
+ """Some site of this capability can be asked: `forge jev status`'s capability_ready,
384
+ kept for older readers. The shell's forge_decide_active reads the per-gate `ready`
385
+ in that status's `gates` block instead."""
386
+ if capability in RETIRED_CAPABILITIES:
387
+ return False
302
388
  return any(site_ready(site, config) for site, cap in SITE_CAPABILITY.items()
303
- if cap == capability and site not in CLEF_ONLY_SITES)
304
-
305
-
306
- def _capability_overrides() -> dict[str, str]:
307
- names = dict(routing='FORGE_JEV_ROUTING', tests='FORGE_JEV_TESTS', gates='FORGE_JEV_GATES', memory='FORGE_JEV_MEMORY')
308
- return {cap: os.environ[var] for cap, var in names.items() if os.environ.get(var) in ('on', 'off')}
389
+ if cap == capability)
309
390
 
310
391
 
311
392
  def enabled(capability: str | None = None, *, config: dict | None = None) -> bool:
312
- if os.environ.get('FORGE_JEV') == 'off':
313
- return False
314
- overrides = _capability_overrides()
315
- # An explicit --jev-<cap> is an allowlist, so naming one capability does not
316
- # silently enable the rest.
317
- if 'on' in overrides.values():
318
- return capability is None or overrides.get(capability) == 'on'
319
- if overrides.get(capability) == 'off':
393
+ """Some gate of this capability (any gate, for None) is not off. Retired capabilities
394
+ have no gates, so they are never enabled."""
395
+ if capability in RETIRED_CAPABILITIES:
320
396
  return False
321
- stored = config if config is not None else load_config()
322
- if os.environ.get('FORGE_JEV') != 'on' and not stored['enabled']:
323
- return False
324
- return capability is None or stored['capabilities'].get(capability, True)
397
+ import forge_decide
398
+ resolved = _resolved(config)
399
+ return any(value['mode'] != 'off' for gate, value in resolved['gates'].items()
400
+ if capability is None or forge_decide.GATE_CAPABILITY.get(gate) == capability)
325
401
 
326
402
 
327
403
  def acting() -> bool:
328
- return os.environ.get('FORGE_JEV_ACT') == 'on'
404
+ # Keeps jev.jsonl's acting field.
405
+ return False
329
406
 
330
407
 
331
408
  def shadow() -> bool:
409
+ """The run-wide FORGE_JEV_SHADOW. Per site, shadow is gate_mode(site) == 'shadow'."""
332
410
  return os.environ.get('FORGE_JEV_SHADOW') == 'on'
333
411
 
334
412
 
335
- def threshold(name: str, *, config: dict | None = None, model: str | None = None) -> float:
336
- """A rubric's cutoff. `model` is the model that answered: a threshold measured on one
337
- model's probabilities means nothing on another's, so a per-model value wins."""
413
+ def threshold(name: str, *, config: dict | None = None, site: str | None = None,
414
+ model: str | None = None) -> float:
415
+ """A rubric's cutoff. `model` is the model that answered (else the site's provider
416
+ model): a threshold measured on one model's probabilities means nothing on another's.
417
+
418
+ 1. A gate's `thresholds` override, only while its `thresholds_model` is that model.
419
+ 2. Without a user decide.json: jev.json's thresholds and model_thresholds, as before.
420
+ 3. With one: the measured defaults, per model where a replay justified one.
421
+ """
422
+ import forge_decide
338
423
  config = config or load_config()
424
+ if site is not None:
425
+ resolved = _resolved(config)
426
+ gate = _gate(site, resolved)
427
+ # The override may sit under the name a fallback reads: migration saves jev.json's
428
+ # gate_warn on the drift gate, which drift_warn reads.
429
+ for key in (name, THRESHOLD_FALLBACK.get(name, name)):
430
+ if gate and key in gate['thresholds'] and gate['thresholds_model']:
431
+ if gate['thresholds_model'] == (model or _spec(site, config, resolved)['model']):
432
+ return gate['thresholds'][key]
433
+ if forge_decide.user_path().exists():
434
+ config = dict(config, thresholds=dict(DEFAULT_THRESHOLDS), model_thresholds={})
339
435
  if model:
340
436
  per_model = dict(DEFAULT_MODEL_THRESHOLDS.get(model, {}),
341
437
  **((config.get('model_thresholds') or {}).get(model) or {}))
@@ -349,10 +445,12 @@ def threshold(name: str, *, config: dict | None = None, model: str | None = None
349
445
  # Rubric thresholds introduced after a shared one: until measured separately they read the
350
446
  # old shared value, so a config that never named them behaves exactly as before.
351
447
  THRESHOLD_FALLBACK = dict(drift_warn='gate_warn')
352
- # Thresholds whose only reader was removed on 2026-10-17 (routing's --jev-act tier rewrite
353
- # and `forge jev calibrate`). A config written before then still holds them: they are
354
- # ignored, and `doctor` names them as safe to delete rather than as unknown.
355
- RETIRED_THRESHOLDS = frozenset(('routing_act', 'calibrate_floor'))
448
+ # Thresholds whose only reader was removed (routing's --jev-act tier rewrite and `forge jev
449
+ # calibrate` on 2026-10-17; same-wave coupling, flake triage and the verifiability gate
450
+ # in milestone C1). A config written before then still holds them: they are ignored, and
451
+ # `doctor` names them as safe to delete rather than as unknown.
452
+ RETIRED_THRESHOLDS = frozenset(('routing_act', 'calibrate_floor', 'coupling_warn', 'flake_act',
453
+ 'verifiable_warn'))
356
454
  # Per-model cutoffs, only where a replay justified one. Clef has none yet:
357
455
  #
358
456
  # Replayed 2026-10-16 on the 38 live jev-drift requests whose task outcome could be joined
@@ -367,7 +465,7 @@ DEFAULT_MODEL_THRESHOLDS: dict = {}
367
465
 
368
466
  # The sites a replay showed Clef non-inferior on, which `forge jev setup --provider
369
467
  # cloudflare` maps by default. jev-memory-slice tied (AUC 0.951 vs 0.953) on too few held-out
370
- # runs (5) to clear the rule; jev-review-triage has no live label for its correctness half.
468
+ # runs (5) to clear the rule.
371
469
  CLOUDFLARE_DEFAULT_SITES = ('jev-drift',)
372
470
 
373
471
 
@@ -0,0 +1,171 @@
1
+ """A retry touched its blocking findings (#43).
2
+
3
+ A retry implementer is handed the blocking findings of the review that rejected its
4
+ predecessor. Before the next review is paid for, this asks per CONFIRMED P0/P1 finding whether
5
+ the retry's diff (`changes.since.diff`, everything changed since the reviewed attempt) leaves it
6
+ unaddressed. The shell sends an attempt back, without a review, when a finding clearly is.
7
+
8
+ The gate can only send work back: it never accepts anything and never changes a verdict. It
9
+ asks nothing when there is nothing to compare (no delta), when the findings did not come from
10
+ a review (a bounced or pre-review retry has none to check) or when none of them blocks.
11
+
12
+ Prints one `u<i>TAB<p>TAB<finding>` row per finding at or above `untouched_warn`. Exit 3 is no
13
+ opinion: nothing to ask, the gate is off or in shadow, or the model did not answer.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import importlib.util
18
+ import re
19
+ from pathlib import Path
20
+
21
+ from . import gate_mode, site_ready, threshold
22
+ from .client import ask, noul
23
+ from .questions import finding_untouched
24
+
25
+ SITE = 'jev-retry-addressed'
26
+ BLOCKING = ('P0', 'P1')
27
+ DIFF_CHARS = 40000
28
+
29
+ _issues = None
30
+ _INDEXED = re.compile(r'u(\d+)$')
31
+ _LOCATION = re.compile(r'(.+):\d+$')
32
+ _DIFF_FILE = re.compile(r'^\+\+\+ b/(.+)$', re.M)
33
+
34
+
35
+ def parse_findings(text: str) -> list[dict]:
36
+ """forge-issues.py's `parse_findings`, loaded by path: its file name is not importable."""
37
+ global _issues
38
+ if _issues is None:
39
+ path = Path(__file__).resolve().parent.parent / 'forge-issues.py'
40
+ spec = importlib.util.spec_from_file_location('forge_issues', path)
41
+ module = importlib.util.module_from_spec(spec)
42
+ spec.loader.exec_module(module)
43
+ _issues = module
44
+ return _issues.parse_findings(text)
45
+
46
+
47
+ def blocking_findings(text: str) -> list[dict]:
48
+ """The CONFIRMED P0/P1 findings of a findings text, in the order written."""
49
+ return [f for f in parse_findings(text)
50
+ if f.get('severity') in BLOCKING and f.get('confidence') == 'CONFIRMED']
51
+
52
+
53
+ def _location(finding: dict) -> str:
54
+ return f"{finding['file']}:{finding['line']}" if finding.get('line') is not None else str(finding['file'])
55
+
56
+
57
+ def _read(path: Path) -> str:
58
+ try:
59
+ return path.read_text(errors='replace')
60
+ except OSError:
61
+ return ''
62
+
63
+
64
+ def _run_id(plan: Path) -> str:
65
+ return _read(plan / 'run_id').strip() or plan.name
66
+
67
+
68
+ def main(args) -> int:
69
+ if not site_ready(SITE):
70
+ return 3
71
+ plan = Path(args.plan)
72
+ tdir = plan / 'tasks' / args.task
73
+ diff = _read(tdir / 'changes.since.diff')
74
+ if not diff.strip():
75
+ return 3
76
+ if _read(tdir / 'retry_findings.source').strip() != 'review':
77
+ return 3
78
+ findings = blocking_findings(_read(tdir / 'retry_findings.md'))
79
+ if not findings:
80
+ return 3
81
+
82
+ state = dict(
83
+ run=_run_id(plan), task=args.task, attempt=args.attempt,
84
+ findings=[dict(i=i, severity=f['severity'], location=_location(f), text=f['text'])
85
+ for i, f in enumerate(findings)],
86
+ diff=diff[:DIFF_CHARS] + ('\n[cut]' if len(diff) > DIFF_CHARS else ''))
87
+ questions = {f'u{i}': finding_untouched(f['raw']) for i, f in enumerate(findings)}
88
+ result = ask(state, questions, site=SITE, run_dir=str(tdir),
89
+ context=dict(task=args.task, attempt=args.attempt))
90
+ if result is None or gate_mode(SITE) != 'on':
91
+ return 3
92
+
93
+ warn_at = threshold('untouched_warn', site=SITE, model=result.get('model'))
94
+ rows = []
95
+ for i, finding in enumerate(findings):
96
+ probability = noul(result, f'u{i}')
97
+ if probability is not None and probability >= warn_at:
98
+ rows.append(f"u{i}\t{probability:.3f}\t{finding['raw']}")
99
+ if not rows:
100
+ return 3
101
+ print('\n'.join(rows))
102
+ return 0
103
+
104
+
105
+ # --- measurement: what forge_decide.sites reads for this site --------------------------------
106
+
107
+ def _index(qid) -> int:
108
+ found = _INDEXED.match(str(qid))
109
+ return int(found.group(1)) if found else -1
110
+
111
+
112
+ def _number(value) -> float | None:
113
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
114
+ return None
115
+ return float(value)
116
+
117
+
118
+ def decisions(body) -> list[str]:
119
+ """The `u<i>` ids a request asked, in finding order."""
120
+ questions = body.get('questions') if isinstance(body, dict) else None
121
+ ids = list(questions) if isinstance(questions, (dict, list)) else []
122
+ return sorted((str(qid) for qid in ids if _index(qid) >= 0), key=_index)
123
+
124
+
125
+ def score(answers, qid, request=None) -> float | None:
126
+ """The Noul of the question: the probability that the finding was left unaddressed."""
127
+ answer = (answers or {}).get(qid)
128
+ if isinstance(answer, dict) and answer.get('type', 'noul') == 'noul':
129
+ return _number(answer.get('noul'))
130
+ return None
131
+
132
+
133
+ def fired(answers, threshold_value, request=None) -> list[str]:
134
+ """The questions at or above the threshold: the findings the gate would send back."""
135
+ limit = _number(threshold_value)
136
+ if limit is None:
137
+ return []
138
+ out = []
139
+ for qid in sorted((q for q in (answers or {}) if _index(q) >= 0), key=_index):
140
+ probability = score(answers, qid)
141
+ if probability is not None and probability >= limit:
142
+ out.append(qid)
143
+ return out
144
+
145
+
146
+ def _state_finding(body, qid) -> dict:
147
+ state = body.get('state') if isinstance(body, dict) else None
148
+ findings = state.get('findings') if isinstance(state, dict) else None
149
+ for item in findings if isinstance(findings, list) else []:
150
+ if isinstance(item, dict) and item.get('i') == _index(qid):
151
+ return item
152
+ return {}
153
+
154
+
155
+ def finding_file(item: dict) -> str:
156
+ """The file a state finding names: its location without the line."""
157
+ location = str(item.get('location') or '')
158
+ found = _LOCATION.match(location)
159
+ return (found.group(1) if found else location).removeprefix('./')
160
+
161
+
162
+ def baseline(body, qid) -> float:
163
+ """1.0 when the finding's file is not among the diff's files, else 0.0: the plain rule the
164
+ model's score is measured against."""
165
+ path = finding_file(_state_finding(body, qid))
166
+ state = body.get('state') if isinstance(body, dict) else None
167
+ diff = str(state.get('diff') or '') if isinstance(state, dict) else ''
168
+ if not path:
169
+ return 0.0
170
+ touched = set(_DIFF_FILE.findall(diff))
171
+ return 0.0 if path in touched else 1.0