@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
@@ -3,21 +3,24 @@ from __future__ import annotations
3
3
 
4
4
  import argparse
5
5
  import getpass
6
+ import importlib
6
7
  import json
7
8
  import os
8
9
  from pathlib import Path
9
10
  import sys
10
11
  import tempfile
11
- import time
12
12
  import urllib.parse
13
13
 
14
- from forge_registry import register_run_dir, runs_registry
14
+ from forge_registry import register_run_dir
15
15
 
16
- from . import (CAPABILITIES, CLEF_ONLY_SITES, CLOUDFLARE_DEFAULT_SITES, CLOUDFLARE_TOKEN_FILE,
17
- DEFAULT_THRESHOLDS, PROVIDERS, RETIRED_THRESHOLDS, SITE_CAPABILITY, THRESHOLD_FALLBACK, api_key,
18
- capability_ready, cloudflare, config_path, enabled, load_config, provider_for, provider_ready,
19
- redact, save_config, secrets, site_ready)
16
+ from . import (CAPABILITIES, CLOUDFLARE_DEFAULT_SITES, CLOUDFLARE_TOKEN_FILE,
17
+ DEFAULT_THRESHOLDS, PROVIDERS, RETIRED_CAPABILITIES, RETIRED_THRESHOLDS,
18
+ SITE_CAPABILITY, THRESHOLD_FALLBACK, api_key,
19
+ capability_ready, cloudflare, config_path, enabled, gate_mode, gate_reason, load_config,
20
+ plan_gate_mode, provider_for, provider_ready, redact, save_config, secrets, site_ready,
21
+ threshold, use_repo, _resolved)
20
22
  from . import client, questions
23
+ import forge_decide
21
24
 
22
25
  PRIVACY_STATEMENT = """\
23
26
  Jev (TypeSafe System One) sends task prompts, diff hunks, file excerpts, test names,
@@ -52,15 +55,6 @@ def parser() -> argparse.ArgumentParser:
52
55
  setup.add_argument('--model', choices=('clef', 'clef-flash'), default='clef')
53
56
  setup.add_argument('--sites', help='comma-separated sites to send to Cloudflare (default: the measured ones)')
54
57
 
55
- first = sub.add_parser('first-pass', help=argparse.SUPPRESS)
56
- first.add_argument('--plan', required=True)
57
- first.add_argument('--repo', required=True)
58
- retry = sub.add_parser('retry-pass', help=argparse.SUPPRESS)
59
- retry.add_argument('--plan', required=True)
60
- retry.add_argument('--repo', required=True)
61
- retry.add_argument('--task', required=True)
62
- retry.add_argument('--attempt', type=int, required=True)
63
-
64
58
  sites = sub.add_parser('sites', help='show or set which provider answers each site')
65
59
  sites.add_argument('assign', nargs='*', metavar='SITE=PROVIDER')
66
60
 
@@ -75,15 +69,6 @@ def parser() -> argparse.ArgumentParser:
75
69
  doctor.add_argument('--live', action='store_true')
76
70
  doctor.add_argument('--json', action='store_true')
77
71
 
78
- backtest = sub.add_parser('backtest')
79
- backtest.add_argument('--repo', required=True)
80
- backtest.add_argument('--limit', type=int, default=None)
81
- backtest.add_argument('--execute', action='store_true')
82
- backtest.add_argument('--max-requests', type=int, default=200)
83
- backtest.add_argument('--out', default=None)
84
- backtest.add_argument('--capability', choices=('tests', 'drift'), default='tests')
85
- backtest.add_argument('--json', action='store_true')
86
-
87
72
  verify_discover = sub.add_parser('verify-discover')
88
73
  verify_discover.add_argument('--repo', required=True)
89
74
  verify_discover.add_argument('--json', action='store_true')
@@ -99,11 +84,6 @@ def parser() -> argparse.ArgumentParser:
99
84
  coupling.add_argument('--repo', required=True)
100
85
  coupling.add_argument('--json', action='store_true')
101
86
 
102
- review_triage = sub.add_parser('review-triage')
103
- review_triage.add_argument('--review', required=True)
104
- review_triage.add_argument('--diff', required=True)
105
- review_triage.add_argument('--run-dir', default=None)
106
- review_triage.add_argument('--json', action='store_true')
107
87
 
108
88
  memory_curate = sub.add_parser('memory-curate')
109
89
  memory_curate.add_argument('--repo', required=True)
@@ -126,26 +106,32 @@ def parser() -> argparse.ArgumentParser:
126
106
  memory_stale.add_argument('--anchor', required=True)
127
107
  memory_stale.add_argument('--run-dir', default=None)
128
108
 
129
- test_subset = sub.add_parser('test-subset')
130
- test_subset.add_argument('--repo', required=True)
131
- test_subset.add_argument('--commit', required=True)
132
- test_subset.add_argument('--task', required=True)
133
- test_subset.add_argument('--command', dest='subset_command', required=True)
134
- test_subset.add_argument('--changed', default=None)
135
- test_subset.add_argument('--base', default=None)
136
- test_subset.add_argument('--run-dir', default=None)
137
- test_subset.add_argument('--max', type=int, default=8)
138
- test_subset.add_argument('--timeout', type=int, default=600)
139
-
140
- verify_triage = sub.add_parser('verify-triage')
141
- verify_triage.add_argument('--repo', required=True)
142
- # dest is deliberately not 'command': the top-level subparsers already own that dest
143
- # name for the subcommand itself ('verify-triage'), and letting --command collide
144
- # with it would overwrite the dispatch key in main().
145
- verify_triage.add_argument('--command', dest='verify_command', required=True)
146
- verify_triage.add_argument('--log', required=True)
147
- verify_triage.add_argument('--json', action='store_true')
148
- verify_triage.add_argument('--run-dir')
109
+ coverage = sub.add_parser('coverage')
110
+ coverage.add_argument('--plan', required=True)
111
+ coverage.add_argument('--repo', required=True)
112
+ coverage.add_argument('--json', action='store_true')
113
+
114
+ retry_addressed = sub.add_parser('retry-addressed')
115
+ retry_addressed.add_argument('--plan', required=True)
116
+ retry_addressed.add_argument('--task', required=True)
117
+ retry_addressed.add_argument('--attempt', type=int, required=True)
118
+ retry_addressed.add_argument('--repo', required=True)
119
+
120
+ dwarf_message = sub.add_parser('dwarf-message')
121
+ dwarf_message.add_argument('--plan', required=True)
122
+ dwarf_message.add_argument('--task', required=True)
123
+ dwarf_message.add_argument('--attempt', type=int, required=True)
124
+ dwarf_message.add_argument('--repo', required=True)
125
+
126
+ attribution = sub.add_parser('attribution')
127
+ attribution.add_argument('--plan', required=True)
128
+ attribution.add_argument('--repo', required=True)
129
+ attribution.add_argument('--log', required=True)
130
+
131
+ findings = sub.add_parser('findings')
132
+ findings.add_argument('--repo', required=True)
133
+ findings.add_argument('--input', required=True)
134
+ findings.add_argument('--run-dir', default=None)
149
135
  return p
150
136
 
151
137
 
@@ -209,7 +195,7 @@ def _setup_cloudflare(args) -> int:
209
195
  handle.write('CLOUDFLARE_API_TOKEN=%s\n' % token)
210
196
  os.chmod(token_file, 0o600)
211
197
  chosen = [s for s in (args.sites.split(',') if args.sites else CLOUDFLARE_DEFAULT_SITES) if s]
212
- unknown = [s for s in chosen if s not in SITE_CAPABILITY or s in CLEF_ONLY_SITES]
198
+ unknown = [s for s in chosen if s not in SITE_CAPABILITY]
213
199
  if unknown:
214
200
  print('forge jev: unknown site(s): ' + ', '.join(unknown), file=sys.stderr)
215
201
  return 2
@@ -226,51 +212,19 @@ def _setup_cloudflare(args) -> int:
226
212
  return 0
227
213
 
228
214
 
229
- def _watchdog(seconds: float) -> None:
230
- """Exit this process, whatever it is doing, `seconds` from now. A separate CLI process
231
- with no worker threads of its own to protect, so SIGALRM is safe here (unlike in
232
- Fractal's threads); the shell hooks that call it then never wait past the bound."""
233
- import signal
234
-
235
- signal.signal(signal.SIGALRM, lambda *_: os._exit(3))
236
- signal.setitimer(signal.ITIMER_REAL, seconds)
237
-
238
-
239
- def cmd_first_pass(args) -> int:
240
- """Silent first-attempt predictions for a freshly planned table (forge_jev/predict.py)."""
241
- from . import predict
242
- config = load_config()
243
- if not site_ready('clef-first-pass', config):
244
- return 3
245
- _watchdog(2 * config.get('deadline_s', 5.0) + 5)
246
- return predict.main_first_pass(args)
247
-
248
-
249
- def cmd_retry_pass(args) -> int:
250
- """Silent prediction for a dwarf attempt above 1 (forge_jev/predict.py)."""
251
- from . import predict
252
- config = load_config()
253
- if not site_ready('clef-retry-pass', config):
254
- return 3
255
- _watchdog(2 * config.get('deadline_s', 5.0) + 5)
256
- return predict.main_retry_pass(args)
257
-
258
-
259
215
  def cmd_sites(args) -> int:
260
216
  config = load_config()
261
217
  if args.assign:
262
218
  for item in args.assign:
263
219
  site, _, provider = item.partition('=')
264
- if site not in SITE_CAPABILITY or site in CLEF_ONLY_SITES or provider not in PROVIDERS:
220
+ if site not in SITE_CAPABILITY or provider not in PROVIDERS:
265
221
  print('forge jev sites: expected SITE=PROVIDER with SITE one of %s and PROVIDER one of %s; got %r'
266
- % (', '.join(s for s in SITE_CAPABILITY if s not in CLEF_ONLY_SITES), ', '.join(PROVIDERS), item),
222
+ % (', '.join(SITE_CAPABILITY), ', '.join(PROVIDERS), item),
267
223
  file=sys.stderr)
268
224
  return 2
269
225
  config['sites'][site] = provider
270
226
  save_config(config)
271
227
  for site in SITE_CAPABILITY:
272
- if site in CLEF_ONLY_SITES and cloudflare(config) is None:
273
- continue
274
228
  print('%-20s %-10s %s' % (site, provider_for(site, config), 'ready' if site_ready(site, config) else 'not ready'))
275
229
  return 0
276
230
 
@@ -302,7 +256,27 @@ def cmd_setup(args) -> int:
302
256
  return 0
303
257
 
304
258
 
259
+ def _migrated(args, mode: str) -> bool:
260
+ """Once a user decide.json exists, jev.json no longer controls runs: refuse to write it
261
+ and name the `forge decide gate` commands that do what was asked."""
262
+ if not forge_decide.user_path().exists():
263
+ return False
264
+ caps = set(args.capability or ())
265
+ gates = [g for g in forge_decide.GATES if not caps or forge_decide.GATE_CAPABILITY[g] in caps]
266
+ print('forge jev: %s exists, so jev.json no longer controls runs; nothing was written.'
267
+ % forge_decide.user_path(), file=sys.stderr)
268
+ if gates:
269
+ print('use instead:', file=sys.stderr)
270
+ for gate in gates:
271
+ print(' forge decide gate %s %s' % (gate, mode), file=sys.stderr)
272
+ else:
273
+ print('%s has no gates any more' % ', '.join(sorted(caps)), file=sys.stderr)
274
+ return True
275
+
276
+
305
277
  def cmd_enable(args) -> int:
278
+ if _migrated(args, 'on'):
279
+ return 1
306
280
  config = load_config()
307
281
  if args.capability:
308
282
  for name in args.capability:
@@ -310,10 +284,16 @@ def cmd_enable(args) -> int:
310
284
  else:
311
285
  config['enabled'] = True
312
286
  save_config(config)
287
+ # Accepted so old commands keep working. Nothing is left to ask.
288
+ for name in dict.fromkeys(args.capability or ()):
289
+ if name in RETIRED_CAPABILITIES:
290
+ print('forge: %s has no sites any more' % name, file=sys.stderr)
313
291
  return 0
314
292
 
315
293
 
316
294
  def cmd_disable(args) -> int:
295
+ if _migrated(args, 'off'):
296
+ return 1
317
297
  config = load_config()
318
298
  if args.capability:
319
299
  for name in args.capability:
@@ -324,18 +304,42 @@ def cmd_disable(args) -> int:
324
304
  return 0
325
305
 
326
306
 
307
+ def _capability_sites() -> dict:
308
+ sites = {cap: [] for cap in CAPABILITIES}
309
+ for site, cap in SITE_CAPABILITY.items():
310
+ if cap is not None: # a site with no capability belongs to no capability's list
311
+ sites.setdefault(cap, []).append(site)
312
+ return sites
313
+
314
+
315
+ def _gates_block(config: dict) -> dict:
316
+ """Each gate's resolved mode and source, and whether its site can be asked (reason:
317
+ None, off, privacy, kill, no-provider or no-key)."""
318
+ resolved = _resolved(config)
319
+ out = {}
320
+ for name, gate in resolved['gates'].items():
321
+ reason = gate_reason(forge_decide.GATE_SITE[name], config)
322
+ out[name] = dict(mode=gate['mode'], source=gate['source'], ready=reason is None, reason=reason)
323
+ return out
324
+
325
+
327
326
  def cmd_status(args) -> int:
328
327
  config = load_config()
329
- overrides = {var: os.environ[var] for var in ('FORGE_JEV', 'FORGE_JEV_ACT', 'FORGE_JEV_SHADOW',
328
+ # FORGE_JEV_ACT is not read: --jev-act no longer changes anything.
329
+ overrides = {var: os.environ[var] for var in ('FORGE_JEV', 'FORGE_JEV_SHADOW',
330
330
  *_CAP_ENV.values()) if var in os.environ}
331
- overrides.update({var: os.environ[var] for var in ('FORGE_CLEF', 'FORGE_JEV_PROVIDER', 'FORGE_JEV_OUTCOMES')
331
+ overrides.update({var: os.environ[var] for var in ('FORGE_CLEF', 'FORGE_JEV_PROVIDER')
332
332
  if var in os.environ})
333
333
  remote = cloudflare(config)
334
- # Offline by contract: the shell's forge_jev_active reads this before every Jev step.
334
+ sites_by_cap = _capability_sites()
335
+ # Offline by contract: the shell's forge_decide_active reads `gates` (each gate's `ready`)
336
+ # from this before every decision-model step.
335
337
  data = dict(config_path=str(config_path()), key_present=api_key(config) is not None,
336
338
  enabled=enabled(config=config),
337
339
  capabilities={c: enabled(c, config=config) for c in CAPABILITIES},
338
340
  capability_ready={c: capability_ready(c, config) for c in CAPABILITIES},
341
+ capability_sites=sites_by_cap,
342
+ retired_capabilities=sorted(RETIRED_CAPABILITIES),
339
343
  providers=dict(typesafe=dict(ready=provider_ready('typesafe', config)),
340
344
  cloudflare=dict(configured=remote is not None,
341
345
  ready=provider_ready('cloudflare', config),
@@ -343,7 +347,7 @@ def cmd_status(args) -> int:
343
347
  sites={s: dict(provider=provider_for(s, config), ready=site_ready(s, config))
344
348
  for s in SITE_CAPABILITY},
345
349
  thresholds=config['thresholds'], model_thresholds=config.get('model_thresholds') or {},
346
- env_overrides=overrides)
350
+ env_overrides=overrides, gates=_gates_block(config))
347
351
  if args.json:
348
352
  print(json.dumps(data, indent=2))
349
353
  else:
@@ -351,15 +355,22 @@ def cmd_status(args) -> int:
351
355
  print('key present: ' + str(data['key_present']))
352
356
  print('enabled: ' + str(data['enabled']))
353
357
  for name, state in data['capabilities'].items():
354
- print(f' {name}: {state}')
358
+ if name in RETIRED_CAPABILITIES:
359
+ print(f' {name}: {state} (retired, no sites)')
360
+ else:
361
+ print(f' {name}: {state}')
355
362
  cf = data['providers']['cloudflare']
356
363
  if cf['configured']:
357
364
  print('cloudflare: ready=%s model=%s' % (cf['ready'], cf['model']))
358
365
  moved = {s: v for s, v in data['sites'].items()
359
- if v['provider'] != 'typesafe' and (cf['configured'] or s not in CLEF_ONLY_SITES)}
366
+ if v['provider'] != 'typesafe'}
360
367
  for site, value in sorted(moved.items()):
361
368
  print(f" {site}: {value['provider']}{'' if value['ready'] else ' (not ready)'}")
362
369
  print('thresholds: ' + json.dumps(data['thresholds']))
370
+ print('gates:')
371
+ for name, gate in data['gates'].items():
372
+ print(' %-16s %-6s (%s) %s' % (name, gate['mode'], gate['source'],
373
+ 'ready' if gate['ready'] else 'not ready: ' + gate['reason']))
363
374
  if overrides:
364
375
  print('env overrides: ' + ', '.join(f'{k}={v}' for k, v in overrides.items()))
365
376
  return 0
@@ -380,12 +391,9 @@ def cmd_doctor(args) -> int:
380
391
  else:
381
392
  checks.append(('config readable', True, 'no config file; using defaults'))
382
393
  key = api_key(config)
383
- # The Clef-only sites count once a Cloudflare provider is configured, not before:
384
- # a TypeSafe-only setup is as ready as it ever was.
385
- used = {provider_for(s, config) for s in SITE_CAPABILITY
386
- if enabled(SITE_CAPABILITY[s], config=config) and s not in CLEF_ONLY_SITES}
387
- if cloudflare(config) is not None:
388
- used.add('cloudflare')
394
+ # enabled(None) means any gate on, so a site with no capability counts by its own gate.
395
+ used = {provider_for(s, config) for s, cap in SITE_CAPABILITY.items()
396
+ if (enabled(cap, config=config) if cap is not None else gate_mode(s) != 'off')}
389
397
  if 'typesafe' in used or not used:
390
398
  checks.append(('key present', key is not None, None))
391
399
  if 'cloudflare' in used:
@@ -445,39 +453,6 @@ def cmd_doctor(args) -> int:
445
453
  return 0 if ready else 3
446
454
 
447
455
 
448
- def cmd_backtest(args) -> int:
449
- repo = Path(args.repo)
450
- if not repo.is_dir() or not (repo / '.git').exists():
451
- print(f'forge jev backtest: --repo {args.repo!r} is not a git repository', file=sys.stderr)
452
- return 2
453
-
454
- # Imported lazily so cli.py keeps working (and status/doctor keep paying nothing)
455
- # even while backtest.py is mid-edit by another agent, and so a missing module is a
456
- # clean exit rather than a traceback.
457
- try:
458
- from . import backtest
459
- except ImportError as error:
460
- print('forge jev backtest: backtest module unavailable (' + str(error) + ')', file=sys.stderr)
461
- return 3
462
-
463
- config = load_config()
464
- if args.execute and api_key(config) is None:
465
- print('forge jev backtest: no API key configured. Run `forge jev setup` first.', file=sys.stderr)
466
- return 3
467
-
468
- if not args.execute:
469
- print('Dry estimate only -- no API call was made (pass --execute to run one).', file=sys.stderr)
470
-
471
- summary = backtest.run(repo, limit=args.limit, execute=args.execute,
472
- max_requests=args.max_requests, out_dir=args.out,
473
- capability=args.capability, config=config)
474
- if args.json:
475
- print(json.dumps(summary, indent=2))
476
- else:
477
- print(backtest.report(summary))
478
- return 0
479
-
480
-
481
456
  def cmd_verify_discover(args) -> int:
482
457
  repo = Path(args.repo)
483
458
  if not repo.is_dir():
@@ -485,16 +460,22 @@ def cmd_verify_discover(args) -> int:
485
460
  return 2
486
461
 
487
462
  # Imported lazily so cli.py keeps working, and status/doctor keep paying nothing,
488
- # even while verify.py is mid-edit -- same reasoning as cmd_backtest's import.
463
+ # even while verify.py is mid-edit, and so a missing module is a clean exit.
489
464
  try:
490
465
  from . import verify
491
466
  except ImportError as error:
492
467
  print('forge jev verify-discover: verify module unavailable (' + str(error) + ')', file=sys.stderr)
493
468
  return 3
494
469
 
470
+ use_repo(repo)
495
471
  config = load_config()
496
- result = verify.discover(repo, config=config, run_dir=args.run_dir)
497
- if result is None:
472
+ # Asked only when the gate's provider is usable. discover() does not check that, and a
473
+ # gate naming a missing provider would send the repo's commands to the hosted TypeSafe.
474
+ result = None
475
+ if site_ready('jev-verify-discover', config):
476
+ result = verify.discover(repo, config=config, run_dir=args.run_dir)
477
+ # Shadow: asked and recorded like `on`, then the path a run takes with no command.
478
+ if result is None or gate_mode('jev-verify-discover') == 'shadow':
498
479
  if not args.json:
499
480
  print('forge jev verify-discover: no verified candidate found', file=sys.stderr)
500
481
  else:
@@ -511,52 +492,130 @@ def cmd_verify_discover(args) -> int:
511
492
  return 0
512
493
 
513
494
 
514
- def cmd_verify_triage(args) -> int:
515
- repo = Path(args.repo)
516
- if not repo.is_dir():
517
- print(f'forge jev verify-triage: --repo {args.repo!r} is not a directory', file=sys.stderr)
518
- return 2
519
- try:
520
- log_tail = Path(args.log).read_text(errors='replace')
521
- except OSError as error:
522
- print(f'forge jev verify-triage: cannot read --log {args.log!r}: {error}', file=sys.stderr)
523
- return 2
495
+ # Enough of a task prompt for the gates to judge it. The longest prompt in forge's own
496
+ # test plan is about 3.5KB; this leaves room without letting one enormous task prompt
497
+ # dominate a request that also carries file excerpts and memory.
498
+ PROMPT_CHARS = 8000
524
499
 
500
+
501
+ def _column(plan: Path, task_id: str) -> list:
502
+ """The names in the task's `files` column right now (tasks.tsv column 4)."""
525
503
  try:
526
- from . import verify
527
- except ImportError as error:
528
- print('forge jev verify-triage: verify module unavailable (' + str(error) + ')', file=sys.stderr)
529
- return 3
504
+ for line in (plan / 'tasks.tsv').read_text(errors='replace').splitlines():
505
+ cells = line.split('\t')
506
+ if len(cells) >= 7 and not line.startswith('#') and cells[0] == task_id:
507
+ return [name.strip() for name in cells[3].split(',') if name.strip() not in ('', '-')]
508
+ except OSError:
509
+ pass
510
+ return []
530
511
 
531
- config = load_config()
532
- traps = verify.known_traps(repo)
533
- result = verify.triage(repo, command=args.verify_command, log_tail=log_tail, traps=traps, config=config,
534
- run_dir=args.run_dir)
535
- if result is None:
536
- if args.json:
537
- print(json.dumps(None))
538
- else:
539
- print('forge jev verify-triage: no judgment produced', file=sys.stderr)
540
- return 3
541
- if args.json:
542
- print(json.dumps(result, indent=2))
543
- else:
544
- print(f"{result['verdict']} (confidence {result['confidence']:.2f})")
545
- return 0
546
512
 
513
+ def _drift_act(plan: Path, task_id: str, predicted, mode: str) -> list:
514
+ """What the drift gate does with an answer, and records in plan-gates.json.
547
515
 
548
- # Enough of a task prompt for the rubrics to judge it. The longest prompt in forge's
549
- # own test plan is about 3.5KB; this leaves room without letting one enormous task
550
- # prompt dominate a request that also carries file excerpts and memory.
551
- PROMPT_CHARS = 8000
516
+ `on` appends the predicted files to the task's `files` column and records them under
517
+ `drift.<task>.added`; `shadow` records them under `would_add` and touches nothing else.
518
+ `added` entries from an earlier plan stay while their file is still in the column: the
519
+ labels need to know the planner did not declare it. Returns the files added now. Any
520
+ failure behaves as `off`, so a plan never fails because of this gate: when the record
521
+ cannot be saved, tasks.tsv goes back to the bytes it had, so no file is added without
522
+ its provenance.
523
+ """
524
+ if mode not in ('on', 'shadow'):
525
+ return []
526
+ original = None
527
+ try:
528
+ from . import plan_gates
529
+ if mode == 'on':
530
+ original = (plan / 'tasks.tsv').read_bytes()
531
+ files = [dict(file=name, p=probability) for name, probability in predicted]
532
+ added = []
533
+ if mode == 'on' and files:
534
+ done = set(plan_gates.add_files(plan, task_id, [item['file'] for item in files]))
535
+ added = [item for item in files if item['file'] in done]
536
+ data = plan_gates.load(plan)
537
+ drift = data.get('drift') if isinstance(data.get('drift'), dict) else {}
538
+ entry = drift.get(task_id) if isinstance(drift.get(task_id), dict) else {}
539
+ column = set(_column(plan, task_id))
540
+ kept = [item for item in entry.get('added') or []
541
+ if isinstance(item, dict) and item.get('file') in column
542
+ and item['file'] not in {a['file'] for a in added}]
543
+ fresh = {}
544
+ if kept or added:
545
+ fresh['added'] = kept + added
546
+ if mode == 'shadow' and files:
547
+ fresh['would_add'] = files
548
+ if fresh != entry:
549
+ if fresh:
550
+ drift[task_id] = fresh
551
+ else:
552
+ drift.pop(task_id, None)
553
+ data['drift'] = drift
554
+ if not drift:
555
+ data.pop('drift')
556
+ if data or (plan / plan_gates.GATES_FILE).exists():
557
+ plan_gates.save(plan, data)
558
+ return [item['file'] for item in added]
559
+ except Exception:
560
+ if original is not None:
561
+ try:
562
+ plan_gates._atomic_write(plan / 'tasks.tsv', original)
563
+ except Exception:
564
+ pass
565
+ return []
566
+
567
+
568
+ def _prompt_act(plan: Path, scores: dict, mode: str, warn_at: float) -> None:
569
+ """What the prompt gate does with the plan's adequacy scores, recorded in plan-gates.json.
570
+
571
+ `on` records `prompt.<task> = {p, shadow: false}` and queues a task below `warn_at` for
572
+ the planner (plan_gates.mark_pending). A task that was already sent back is never queued
573
+ again: its new score goes under `after`, and the table lists it when still below the
574
+ threshold. `shadow` records `{p, shadow: true}` and queues nothing. `sendback` is not
575
+ called here: `plan` runs it once after every gate. Any failure behaves as `off`, so a
576
+ plan never fails because of this gate.
577
+ """
578
+ if mode not in ('on', 'shadow') or not scores:
579
+ return
580
+ try:
581
+ from . import plan_gates
582
+ data = plan_gates.load(plan)
583
+ before = json.dumps(data, sort_keys=True)
584
+ prompt = data.get('prompt') if isinstance(data.get('prompt'), dict) else {}
585
+ sent = (data.get('sent_back') or {}).get('prompt') or []
586
+ for task_id, p in scores.items():
587
+ entry = dict(p=round(p, 3), shadow=mode == 'shadow')
588
+ if mode == 'on':
589
+ if task_id in sent:
590
+ entry['after'] = entry['p']
591
+ elif p < warn_at:
592
+ plan_gates.mark_pending(data, 'prompt', task_id)
593
+ prompt[task_id] = entry
594
+ data['prompt'] = prompt
595
+ if json.dumps(data, sort_keys=True) != before:
596
+ plan_gates.save(plan, data)
597
+ except Exception:
598
+ pass
552
599
 
553
600
 
554
601
  def cmd_score_plan(args) -> int:
555
- """Rate every task in a plan. Advisory output only: nothing ever writes it into tasks.tsv.
556
-
557
- Writing a Jev tier into the plan (`--jev-act`, gated on a per-repo calibration) was
558
- removed on 2026-10-17 without ever having acted: no repo reached the calibration bar,
559
- and model choice is now measured from `plan --explore` draws (`forge dataset routing`).
602
+ """The plan-time gates: prompt adequacy (jev-prompt) and drift (jev-drift), per task.
603
+
604
+ Prompt adequacy is advisory unless the gate is `on`: then a task below `prompt_warn` is
605
+ queued for the planner once (plan_gates.mark_pending) and its score recorded under
606
+ `prompt.<task>`; in `shadow` the score is recorded and nothing queued. Drift is advisory
607
+ too unless the gate is `on`: then each file it
608
+ predicts at or above `drift_warn` is appended to the task's `files` column in tasks.tsv
609
+ (before the shell computes waves, so the waves treat it as declared) and recorded under
610
+ `drift.<task>.added` in plan-gates.json. In `shadow` the files are recorded as
611
+ `would_add` and tasks.tsv is left alone. Each task's answers go to tasks/<id>/jev.json;
612
+ stdout carries one `id<TAB>warnings<TAB>drift` row per task that got any answer, and in
613
+ `on` the drift field lists the files that were added. (This command used to rate routing
614
+ rubrics into a suggested tier; that was removed in milestone C1.)
615
+
616
+ A gate in shadow is asked and its answer kept in jev.json, but it adds `-` to the row;
617
+ a task whose every answer is shadowed prints no row, and exit 3 means no row at all.
618
+ A gate that cannot write its change behaves as `off`: the plan goes on unchanged.
560
619
  """
561
620
  plan, repo = Path(args.plan), Path(args.repo)
562
621
  if not plan.is_dir():
@@ -569,18 +628,22 @@ def cmd_score_plan(args) -> int:
569
628
  if not tasks.is_file():
570
629
  print(f'forge jev score-plan: no tasks.tsv in {args.plan!r}', file=sys.stderr)
571
630
  return 2
631
+ use_repo(repo)
572
632
  config = load_config()
573
- if not site_ready('jev-score-plan', config):
633
+ ask_prompt, ask_drift = site_ready('jev-prompt', config), site_ready('jev-drift', config)
634
+ if not (ask_prompt or ask_drift):
574
635
  return 3
636
+ shadow_prompt = gate_mode('jev-prompt') == 'shadow'
637
+ shadow_drift = gate_mode('jev-drift') == 'shadow'
575
638
 
576
- from . import gates, routing
639
+ from . import gates
577
640
 
578
641
  goal = ''
579
642
  goal_file = plan / 'goal.txt'
580
643
  if goal_file.is_file():
581
644
  goal = goal_file.read_text(errors='replace')[:2000]
582
645
 
583
- rows, judgments = [], []
646
+ rows, judgments, shown, adequacies = [], [], [], {}
584
647
  for line in tasks.read_text(errors='replace').splitlines():
585
648
  if not line.strip() or line.startswith('#'):
586
649
  continue
@@ -589,44 +652,57 @@ def cmd_score_plan(args) -> int:
589
652
  continue
590
653
  rows.append(parts)
591
654
 
592
- # The whole plan, once, for every task's state. independently_verifiable asks
593
- # whether confirming a task needs another task in the plan to land first; it had
594
- # never been shown another task, so it was guessing whether one existed.
655
+ # The whole plan, once, for every task's state: prompt_warn was measured with it there.
595
656
  siblings = [dict(id=p[0], deps=p[1], files=p[3], title=p[6]) for p in rows]
657
+ warn_at = threshold('prompt_warn', config=config, site='jev-prompt')
596
658
 
597
659
  for parts in rows:
598
- task_id, task_deps, declared, files, _dwarf, _qa, title = parts[:7]
660
+ task_id, task_deps, _declared, files, _dwarf, _qa, title = parts[:7]
599
661
  approach = ''
600
662
  approach_file = plan / 'tasks' / task_id / 'approach.md'
601
663
  if approach_file.is_file():
602
664
  approach = approach_file.read_text(errors='replace')[:4000]
603
665
  # The requirements themselves. decompose.md makes this file mandatory and
604
- # SKILL.md says a short title is insufficient for QA -- so scoring a task
605
- # without it was scoring the one thing both documents say is not the task.
666
+ # SKILL.md says a short title is insufficient for QA.
606
667
  prompt_text = ''
607
668
  prompt_file = plan / 'tasks' / task_id / 'prompt.md'
608
669
  if prompt_file.is_file():
609
670
  prompt_text = prompt_file.read_text(errors='replace')[:PROMPT_CHARS]
610
- judgment = routing.score_task(repo, goal=goal, task_id=task_id, title=title,
611
- files=files, approach=approach, prompt=prompt_text,
612
- declared_difficulty=declared, deps=task_deps,
613
- siblings=siblings, run_dir=str(plan),
614
- config=config)
615
- if judgment is None:
616
- continue
617
671
 
618
- # A second request per task, and the only one Phase 4 adds -- the adequacy and
619
- # verifiability gates ride inside the routing request above. This one cannot,
620
- # because it asks about a different universe (every tracked file) rather than
621
- # about the task itself.
622
- if enabled('gates', config=config):
672
+ adequacy = None
673
+ if ask_prompt:
674
+ adequacy = gates.prompt_adequacy(repo, goal=goal, task_id=task_id, title=title,
675
+ files=files, deps=task_deps, approach=approach,
676
+ prompt=prompt_text, siblings=siblings,
677
+ run_dir=str(plan), config=config)
678
+ # A second request, asked whether or not the first answered: it asks about a
679
+ # different universe (every tracked file) rather than about the task itself.
680
+ predicted = None
681
+ if ask_drift:
623
682
  predicted = gates.predict_drift(repo, goal=goal, task_id=task_id, title=title,
624
683
  declared=files, approach=approach,
625
684
  prompt=prompt_text,
626
685
  run_dir=str(plan), config=config)
627
- if predicted:
628
- judgment['predicted_drift'] = [dict(file=name, probability=probability)
629
- for name, probability in predicted]
686
+ if adequacy is not None:
687
+ adequacies[task_id] = adequacy
688
+ if adequacy is None and predicted is None:
689
+ continue
690
+ added = _drift_act(plan, task_id, predicted, plan_gate_mode('jev-drift')) if predicted is not None else []
691
+
692
+ # A warning, not a gate: recorded below the threshold and silent above it.
693
+ warnings = {}
694
+ if adequacy is not None and adequacy < warn_at:
695
+ warnings['prompt_adequacy'] = round(adequacy, 3)
696
+ judgment = dict(id=task_id,
697
+ prompt_adequacy=None if adequacy is None else round(adequacy, 3),
698
+ warnings=warnings,
699
+ predicted_drift=[dict(file=name, probability=probability)
700
+ for name, probability in predicted or ()])
701
+ shadowed = [name for name, value, hidden in (('prompt', adequacy, shadow_prompt),
702
+ ('drift', predicted, shadow_drift))
703
+ if value is not None and hidden]
704
+ if shadowed:
705
+ judgment['shadow'] = shadowed
630
706
  judgments.append(judgment)
631
707
  out = plan / 'tasks' / task_id
632
708
  try:
@@ -634,37 +710,112 @@ def cmd_score_plan(args) -> int:
634
710
  (out / 'jev.json').write_text(json.dumps(judgment, indent=2, sort_keys=True) + '\n')
635
711
  except OSError:
636
712
  pass
713
+ # What the run sees: a shadowed answer counts as no answer.
714
+ if (adequacy is not None and not shadow_prompt) or (predicted is not None and not shadow_drift):
715
+ visible = {k: v for k, v in judgment.items() if k != 'shadow'}
716
+ if shadow_prompt:
717
+ visible.update(prompt_adequacy=None, warnings={})
718
+ if shadow_drift:
719
+ visible['predicted_drift'] = []
720
+ else:
721
+ # In `on` the row names what the gate added to the column.
722
+ visible['predicted_drift'] = [item for item in visible['predicted_drift']
723
+ if item['file'] in added]
724
+ shown.append(visible)
637
725
 
638
726
  if not judgments:
639
727
  return 3
728
+ _prompt_act(plan, adequacies, plan_gate_mode('jev-prompt'), warn_at)
640
729
 
641
730
  # Tell the repo where its own run data lives: forge keeps plan dirs wherever the user put
642
731
  # them, and `forge dataset import --registry` (and forge-ui) find them through this list.
643
732
  # A registry rather than moving the file: plan dirs are the user's to place, and
644
733
  # relocating them would orphan every run already on disk.
645
734
  register_run_dir(repo, plan)
735
+ if not shown:
736
+ return 3
646
737
 
647
738
  if args.json:
648
- print(json.dumps(judgments, indent=2, sort_keys=True))
739
+ print(json.dumps(shown, indent=2, sort_keys=True))
649
740
  else:
650
- for judgment in judgments:
651
- # Two extra columns for the Phase 4 gates. '-' rather than an empty field so
652
- # a `read` in bash cannot silently shift the columns after it.
653
- warnings = ','.join(sorted(judgment.get('warnings') or {})) or '-'
654
- drift = ','.join(item['file'] for item in judgment.get('predicted_drift') or ()) or '-'
655
- print('\t'.join((judgment['id'], judgment['tier'],
656
- str(judgment['confidence']), str(judgment['composite']),
657
- judgment['escalated'] or '-',
658
- judgment['declared'], warnings, drift)))
741
+ for judgment in shown:
742
+ # '-' rather than an empty field so a `read` in bash cannot silently shift the
743
+ # columns after it.
744
+ warnings = ','.join(sorted(judgment['warnings'])) or '-'
745
+ drift = ','.join(item['file'] for item in judgment['predicted_drift']) or '-'
746
+ print('\t'.join((judgment['id'], warnings, drift)))
659
747
  return 0
660
748
 
661
749
 
662
- def cmd_coupling(args) -> int:
663
- """Warn about same-wave task pairs that may conflict despite disjoint files.
750
+ def _forward_act(plan: Path, forward, mode: str) -> list:
751
+ """What the forward gate does with its warned pairs, and records in plan-gates.json.
664
752
 
665
- Advisory only -- like cmd_score_plan, this never edits tasks.tsv or waves.tsv. It
666
- reads both (waves.tsv must already exist; forge-parallel.sh runs this after
667
- compute_waves) and writes jev-coupling.json for a human or a later run to inspect.
753
+ `on` makes each pair's earlier task depend on the later one (plan_gates.add_dep, which
754
+ refuses a cycle): added pairs go under `forward.added`, refused ones under
755
+ `skipped_cycle`. `shadow` records them under `would_add` and touches nothing else.
756
+ `added` entries from an earlier plan stay while the dep is still in the column: the
757
+ labels need to know the planner did not write it. Returns `(earlier, later, p, kind)`
758
+ with kind `added` or `cycle`. Any failure behaves as `off`: when the record cannot be
759
+ saved, tasks.tsv goes back to the bytes it had, so no dependency exists without its
760
+ provenance.
761
+ """
762
+ if mode not in ('on', 'shadow'):
763
+ return []
764
+ original = None
765
+ try:
766
+ from . import plan_gates
767
+ if mode == 'on':
768
+ original = (plan / 'tasks.tsv').read_bytes()
769
+ pairs = [dict(earlier=a, later=b, p=p) for a, b, p in forward]
770
+ added, refused = [], []
771
+ if mode == 'on':
772
+ for item in pairs:
773
+ (added if plan_gates.add_dep(plan, item['earlier'], item['later']) else refused).append(item)
774
+ data = plan_gates.load(plan)
775
+ entry = data.get('forward') if isinstance(data.get('forward'), dict) else {}
776
+ _text, lines = plan_gates._read_tasks(plan)
777
+ deps = plan_gates._deps(lines)
778
+ now = {(i['earlier'], i['later']) for i in added}
779
+ kept = [item for item in entry.get('added') or []
780
+ if isinstance(item, dict) and item.get('later') in deps.get(item.get('earlier'), ())
781
+ and (item['earlier'], item['later']) not in now]
782
+ fresh = {}
783
+ if kept or added:
784
+ fresh['added'] = kept + added
785
+ if refused:
786
+ fresh['skipped_cycle'] = refused
787
+ if mode == 'shadow' and pairs:
788
+ fresh['would_add'] = pairs
789
+ if fresh != entry:
790
+ if fresh:
791
+ data['forward'] = fresh
792
+ else:
793
+ data.pop('forward', None)
794
+ if data or (plan / plan_gates.GATES_FILE).exists():
795
+ plan_gates.save(plan, data)
796
+ return [(i['earlier'], i['later'], i['p'], 'added') for i in added] \
797
+ + [(i['earlier'], i['later'], i['p'], 'cycle') for i in refused]
798
+ except Exception:
799
+ if original is not None:
800
+ try:
801
+ plan_gates._atomic_write(plan / 'tasks.tsv', original)
802
+ except Exception:
803
+ pass
804
+ return []
805
+
806
+
807
+ def cmd_coupling(args) -> int:
808
+ """Warn about earlier-wave tasks written against what a later wave builds.
809
+
810
+ Advisory unless the gate is `on`: then each warned pair becomes a dependency, the earlier
811
+ task waiting for the later one, written to the `deps` column of tasks.tsv and recorded
812
+ under `forward.added` in plan-gates.json (a pair whose dependency would form a cycle is
813
+ left out and recorded under `skipped_cycle`). In `shadow` the pairs are recorded as
814
+ `would_add`, nothing is printed and tasks.tsv is left alone. It never edits waves.tsv:
815
+ forge-parallel.sh runs this after compute_waves and recomputes the waves itself. It reads
816
+ both files (waves.tsv must already exist) and writes jev-coupling.json for a human or a
817
+ later run to inspect; there every row has kind 'forward', and the file keeps its name for
818
+ old consumers. Printed rows end in the outcome: `forward` (advisory), `added` or `cycle`.
668
819
  """
669
820
  plan, repo = Path(args.plan), Path(args.repo)
670
821
  if not plan.is_dir():
@@ -677,32 +828,39 @@ def cmd_coupling(args) -> int:
677
828
  if not waves_file.is_file():
678
829
  print(f'forge jev coupling: no waves.tsv in {args.plan!r} -- run compute_waves first', file=sys.stderr)
679
830
  return 2
831
+ use_repo(repo)
680
832
  config = load_config()
681
- if not site_ready('jev-coupling', config):
833
+ if not site_ready('jev-forward', config):
682
834
  return 3
683
835
 
684
836
  from . import coupling
685
837
 
686
838
  tasks = list(coupling.parse_tasks(plan).values())
687
839
  waves = coupling.parse_waves(plan)
688
- found = coupling.coupled_pairs(repo, tasks=tasks, waves=waves, run_dir=str(plan), config=config)
689
- # The other half of the same question. `pairs()` only looks inside a wave, so "task A
690
- # is written against an interface task B builds later" was structurally out of reach
691
- # -- and that is what shipped: jevscope's `readme` ran in wave 1 documenting the
692
- # wave-2 CLI and passed its own review, because the thing it was wrong about did not
693
- # exist yet. Asked here rather than in a separate command so a plan gets both
694
- # warnings or neither.
695
840
  forward = coupling.forward_dependencies(repo, tasks=tasks, waves=waves,
696
841
  run_dir=str(plan), config=config)
697
- if not found and not forward:
842
+ if forward is None:
843
+ return 3
844
+
845
+ mode = plan_gate_mode('jev-forward')
846
+ # An answer of "nothing to flag" is still an answer: the record of an earlier plan
847
+ # (a stale would_add, a dependency the planner has since dropped) is reconciled with it.
848
+ # `shadow` is recorded under would_add, and the run hears nothing.
849
+ acted = _forward_act(plan, forward, mode)
850
+ if not forward:
698
851
  return 3
699
852
 
700
- payload = ([dict(a=a, b=b, probability=p, kind='same-wave') for a, b, p in (found or [])]
701
- + [dict(a=a, b=b, probability=p, kind='forward') for a, b, p in (forward or [])])
853
+ payload = [dict(a=a, b=b, probability=p, kind='forward') for a, b, p in forward]
702
854
  try:
703
855
  (plan / 'jev-coupling.json').write_text(json.dumps(payload, indent=2, sort_keys=True) + '\n')
704
856
  except OSError:
705
857
  pass
858
+ if mode == 'shadow':
859
+ return 3
860
+ if mode == 'on':
861
+ if not acted:
862
+ return 3
863
+ payload = [dict(a=a, b=b, probability=p, kind=kind) for a, b, p, kind in acted]
706
864
 
707
865
  if args.json:
708
866
  print(json.dumps(payload, indent=2, sort_keys=True))
@@ -714,30 +872,6 @@ def cmd_coupling(args) -> int:
714
872
  return 0
715
873
 
716
874
 
717
- def cmd_review_triage(args) -> int:
718
- """Annotate a FAIL. Exit 0 only when the review looks SUSPECT.
719
-
720
- The exit code carries the whole signal so the caller stays a one-liner, and it is
721
- deliberately the narrow case that exits 0: anything else -- a sound review, no key,
722
- no judgment, a crash -- leaves the verdict to speak for itself.
723
- """
724
- config = load_config()
725
- if not site_ready('jev-review-triage', config):
726
- return 3
727
- from . import review
728
-
729
- result = review.annotate_failure(review_path=args.review, diff_path=args.diff,
730
- run_dir=args.run_dir, config=config)
731
- if result is None:
732
- return 3
733
- if args.json:
734
- print(json.dumps(result, indent=2, sort_keys=True))
735
- elif result['suspect']:
736
- for reason in result['reasons']:
737
- print(reason)
738
- return 0 if result['suspect'] else 1
739
-
740
-
741
875
  def cmd_memory_curate(args) -> int:
742
876
  """Curate one learning line. Prints `category<TAB>injectable<TAB>matched_key`.
743
877
 
@@ -745,6 +879,7 @@ def cmd_memory_curate(args) -> int:
745
879
  learning and parsing JSON in bash for three fields is not worth the subprocess. Exit
746
880
  3 means "no opinion", and the caller keeps exactly what the model said.
747
881
  """
882
+ use_repo(args.repo)
748
883
  config = load_config()
749
884
  if not site_ready('jev-memory-curate', config):
750
885
  return 3
@@ -761,7 +896,8 @@ def cmd_memory_curate(args) -> int:
761
896
 
762
897
  result = memory_module.curate(category=args.category, text=args.text,
763
898
  existing=existing, run_dir=args.run_dir, config=config)
764
- if result is None:
899
+ # Shadow: asked and recorded, then the path a failed request takes.
900
+ if result is None or gate_mode('jev-memory-curate') == 'shadow':
765
901
  return 3
766
902
  if args.json:
767
903
  print(json.dumps(result, indent=2, sort_keys=True))
@@ -792,7 +928,7 @@ def cmd_memory_slice(args) -> int:
792
928
  task=task, lines=lines, run_dir=args.run_dir,
793
929
  keep=args.keep if args.keep and args.keep > 0 else memory_module.SLICE_KEEP,
794
930
  config=config)
795
- if kept is None:
931
+ if kept is None or gate_mode('jev-memory-slice') == 'shadow':
796
932
  return 3
797
933
  for line in kept:
798
934
  print(line)
@@ -800,7 +936,9 @@ def cmd_memory_slice(args) -> int:
800
936
 
801
937
 
802
938
  def cmd_memory_stale(args) -> int:
803
- """Exit 0 when the fact looks stale, 1 when it still holds, 3 when unknown."""
939
+ """Exit 0 when the fact looks stale, 1 when it still holds, 3 when unknown (and in
940
+ shadow, which asks and records but keeps the fact as an unknown does)."""
941
+ use_repo(_anchor_repo(args.anchor))
804
942
  config = load_config()
805
943
  if not site_ready('jev-memory-stale', config):
806
944
  return 3
@@ -808,149 +946,86 @@ def cmd_memory_stale(args) -> int:
808
946
 
809
947
  result = memory_module.still_true(text=args.text, anchor_path=args.anchor,
810
948
  run_dir=args.run_dir, config=config)
811
- if result is None:
949
+ if result is None or gate_mode('jev-memory-stale') == 'shadow':
812
950
  return 3
813
951
  return 0 if result['stale'] else 1
814
952
 
815
953
 
816
- def cmd_test_subset(args) -> int:
817
- """Run the likely-affected tests in a throwaway export of the reviewed commit.
818
-
819
- Exit 0 only when the subset RAN AND FAILED -- that is the one outcome worth telling
820
- a reviewer about. Exit 1 covers "ran and passed", which proves nothing here because
821
- the subset is not the suite, and exit 3 covers everything else. The task worktree is
822
- never touched, so no fingerprint can change.
823
- """
954
+ def _anchor_repo(anchor: str) -> str | None:
955
+ """The repo an anchor file lives in: FORGE_DECIDE_REPO when set, else its git top level."""
956
+ if os.environ.get('FORGE_DECIDE_REPO'):
957
+ return None
824
958
  import subprocess
825
- import tempfile
959
+ try:
960
+ out = subprocess.run(['git', '-C', str(Path(anchor).parent), 'rev-parse', '--show-toplevel'],
961
+ capture_output=True, text=True, timeout=5)
962
+ except (OSError, subprocess.SubprocessError):
963
+ return None
964
+ return (out.stdout.strip() or None) if out.returncode == 0 else None
965
+
966
+
967
+ def _path_missing(verb: str, dirs: dict, files: dict) -> bool:
968
+ """True, after saying which, when a path the verb was given is not there. `dirs` values must
969
+ be directories and `files` values regular files; None means the flag was not given."""
970
+ for flag, path in dirs.items():
971
+ if path is not None and not Path(path).is_dir():
972
+ print(f'forge jev {verb}: --{flag} {path!r} is not a directory', file=sys.stderr)
973
+ return True
974
+ for flag, path in files.items():
975
+ if path is not None and not Path(path).is_file():
976
+ print(f'forge jev {verb}: --{flag} {path!r} is not a file', file=sys.stderr)
977
+ return True
978
+ return False
979
+
980
+
981
+ def _delegate(verb: str, module_name: str, args, repo: str) -> int:
982
+ """use_repo(repo), then the module's `main(args)`. A module that is missing, or has no
983
+ main, is no opinion (exit 3) and says so on stderr only. Imported here, not at the top of
984
+ this file, so a module still being written cannot break the other verbs."""
985
+ use_repo(repo)
986
+ try:
987
+ main = importlib.import_module(f'.{module_name}', __package__).main
988
+ except (ImportError, AttributeError) as error:
989
+ print(f'forge jev {verb}: {module_name} module unavailable ({error})', file=sys.stderr)
990
+ return 3
991
+ return main(args)
826
992
 
827
- receipt_values: dict = {}
828
993
 
829
- def receipt(outcome: str, **values) -> None:
830
- """Record how the subset run ended, every outcome, not just a failure. A selection
831
- is only trainable when we know whether the chosen tests passed, failed on this
832
- diff, or could not run. Fail-open."""
833
- receipt_values.update(values)
834
- try:
835
- scripts = str(Path(__file__).resolve().parent.parent)
836
- if scripts not in sys.path:
837
- sys.path.insert(0, scripts)
838
- from forge_dataset.capture import point
839
- texts = {k: receipt_values.pop(k) for k in ('candidate_output', 'base_output') if k in receipt_values}
840
- point('subset_run', args.run_dir, None, dict(receipt_values, outcome=outcome), texts=texts)
841
- except Exception:
842
- pass
994
+ def cmd_coverage(args) -> int:
995
+ """Plan covers the request (#47): which requirement no task's acceptance criteria cover."""
996
+ if _path_missing('coverage', dirs={'plan': args.plan, 'repo': args.repo}, files={}):
997
+ return 2
998
+ return _delegate('coverage', 'coverage', args, args.repo)
999
+
843
1000
 
844
- # Usage errors come first and need neither a key nor a config: a caller who gets
845
- # exit 3 ("Jev is unavailable") for a malformed command would conclude the wrong
846
- # thing and never fix the command.
847
- if '{files}' not in args.subset_command:
848
- # Without the placeholder there is nowhere to put the selection, and appending
849
- # blindly is what broke this before. Do nothing rather than run the full suite
850
- # twice under a name that says "subset".
1001
+ def cmd_retry_addressed(args) -> int:
1002
+ """A retry touched its blocking findings (#43): which findings its diff left as they were."""
1003
+ if _path_missing('retry-addressed', dirs={'plan': args.plan, 'repo': args.repo}, files={}):
851
1004
  return 2
852
- repo = Path(args.repo)
853
- if not repo.is_dir():
1005
+ return _delegate('retry-addressed', 'addressed', args, args.repo)
1006
+
1007
+
1008
+ def cmd_dwarf_message(args) -> int:
1009
+ """The dwarf's final message (#44): unfinished, blocked or a question for the user."""
1010
+ if _path_missing('dwarf-message', dirs={'plan': args.plan, 'repo': args.repo}, files={}):
854
1011
  return 2
855
- config = load_config()
856
- if not site_ready('jev-test-subset', config):
857
- return 3
858
- from . import subset
1012
+ return _delegate('dwarf-message', 'message', args, args.repo)
859
1013
 
860
- try:
861
- task = Path(args.task).read_text(errors='replace')[:6000]
862
- except OSError:
863
- return 3
864
- changed = []
865
- if args.changed:
866
- try:
867
- changed = Path(args.changed).read_text(errors='replace').split()[:200]
868
- except OSError:
869
- changed = []
870
1014
 
871
- candidates = subset.candidate_tests(repo)
872
- if not candidates:
873
- return 3
874
- scored = subset.select(repo, task=task, changed=changed, candidates=candidates,
875
- run_dir=args.run_dir, config=config)
876
- if not scored:
877
- return 3
1015
+ def cmd_attribution(args) -> int:
1016
+ """Integration attribution (#45): which merged task most likely broke the combined run."""
1017
+ if _path_missing('attribution', dirs={'plan': args.plan, 'repo': args.repo}, files={'log': args.log}):
1018
+ return 2
1019
+ return _delegate('attribution', 'attribution', args, args.repo)
878
1020
 
879
- # No measured per-repo threshold exists, so rather than invent one this takes the
880
- # highest-scoring few. Over-selecting only costs runtime in a throwaway directory;
881
- # the result is advisory either way and never decides verification.
882
- chosen = [name for _p, name in scored[:max(1, args.max)]]
883
- receipt_values.update(chosen=chosen, scored=[[p, name] for p, name in scored[:40]], changed=changed,
884
- commit=args.commit, base=args.base)
885
- export_dir = tempfile.mkdtemp(prefix='forge-subset-')
886
- try:
887
- if not subset.export(repo, args.commit, export_dir):
888
- receipt('export_failed')
889
- return 3
890
- # The template says how THIS project's runner takes a file list, because there
891
- # is no general answer. `pytest -q <files>` works; `npm test <files>` does not
892
- # (it needs `--`), `go test ./...` and `bash tests/check.sh` take no file list at
893
- # all, and `python -m unittest discover -s tests` rejects paths outright. Guessing
894
- # produced a command that failed for a reason having nothing to do with the diff.
895
- command = args.subset_command.replace('{files}', ' '.join(chosen))
896
- receipt_values['command'] = command
897
- started = time.time()
898
- try:
899
- completed = subprocess.run(command, shell=True, cwd=export_dir,
900
- capture_output=True, text=True,
901
- timeout=max(1, args.timeout))
902
- except (OSError, subprocess.SubprocessError) as error:
903
- receipt('timeout' if isinstance(error, subprocess.TimeoutExpired) else 'candidate_error',
904
- candidate_s=round(time.time() - started, 3))
905
- return 3
906
- tail = (completed.stdout or '') + (completed.stderr or '')
907
- receipt_values.update(candidate_exit=completed.returncode, candidate_s=round(time.time() - started, 3),
908
- candidate_output=tail[-65536:])
909
- if completed.returncode == 0:
910
- receipt('pass')
911
- return 1
912
- finally:
913
- subset.cleanup(export_dir)
914
-
915
- # It failed. That is not yet evidence against the diff. A throwaway export has no
916
- # installed dependencies of its own, so `No module named pytest` looks exactly like
917
- # a broken test -- and reporting an environment failure to a reviewer as "your diff
918
- # breaks tests" is worse than saying nothing at all. Pre-existing failures have the
919
- # same shape. So run the identical subset against the BASE commit and only speak up
920
- # when the base passes: that is the one case where this diff is implicated.
921
- if not args.base:
922
- receipt('fail_no_base')
923
- return 3
924
- control_dir = tempfile.mkdtemp(prefix='forge-subset-base-')
925
- try:
926
- if not subset.export(repo, args.base, control_dir):
927
- receipt('base_export_failed')
928
- return 3
929
- started = time.time()
930
- try:
931
- control = subprocess.run(command, shell=True, cwd=control_dir,
932
- capture_output=True, text=True,
933
- timeout=max(1, args.timeout))
934
- except (OSError, subprocess.SubprocessError) as error:
935
- receipt('base_timeout' if isinstance(error, subprocess.TimeoutExpired) else 'base_error',
936
- base_s=round(time.time() - started, 3))
937
- return 3
938
- receipt_values.update(base_exit=control.returncode, base_s=round(time.time() - started, 3),
939
- base_output=((control.stdout or '') + (control.stderr or ''))[-65536:])
940
- if control.returncode != 0:
941
- # Same failure without the diff: environment or pre-existing, not this change.
942
- receipt('environment')
943
- return 3
944
- finally:
945
- subset.cleanup(control_dir)
946
- receipt('regression')
947
-
948
- print('The likely-affected tests were run against this diff and FAILED.')
949
- print('The same tests PASS on the commit this task started from, so the failure')
950
- print('is attributable to this diff rather than to the environment.')
951
- print('Command: ' + command)
952
- print(redact(tail[-3000:]))
953
- return 0
1021
+
1022
+ def cmd_findings(args) -> int:
1023
+ """Findings duplicates and triage (#46): which findings duplicate an open issue or read as
1024
+ a preference. --run-dir is the plan the findings came from, for dataset capture."""
1025
+ if _path_missing('findings', dirs={'repo': args.repo, 'run-dir': args.run_dir},
1026
+ files={'input': args.input}):
1027
+ return 2
1028
+ return _delegate('findings', 'findings', args, args.repo)
954
1029
 
955
1030
 
956
1031
  def main(argv: list[str] | None = None) -> int:
@@ -958,17 +1033,18 @@ def main(argv: list[str] | None = None) -> int:
958
1033
  try:
959
1034
  args = parser().parse_args(argv)
960
1035
  return dict(setup=cmd_setup, sites=cmd_sites, enable=cmd_enable, disable=cmd_disable,
961
- **{'first-pass': cmd_first_pass, 'retry-pass': cmd_retry_pass},
962
- status=cmd_status, doctor=cmd_doctor, backtest=cmd_backtest,
1036
+ status=cmd_status, doctor=cmd_doctor,
963
1037
  **{'score-plan': cmd_score_plan,
964
1038
  'coupling': cmd_coupling,
965
- 'review-triage': cmd_review_triage,
966
- 'test-subset': cmd_test_subset,
967
1039
  'memory-curate': cmd_memory_curate,
968
1040
  'memory-slice': cmd_memory_slice,
969
1041
  'memory-stale': cmd_memory_stale,
970
1042
  'verify-discover': cmd_verify_discover,
971
- 'verify-triage': cmd_verify_triage})[args.command](args)
1043
+ 'coverage': cmd_coverage,
1044
+ 'retry-addressed': cmd_retry_addressed,
1045
+ 'dwarf-message': cmd_dwarf_message,
1046
+ 'attribution': cmd_attribution,
1047
+ 'findings': cmd_findings})[args.command](args)
972
1048
  except SystemExit as exit:
973
1049
  # argparse exits the process on a usage error; return the code instead so the
974
1050
  # shim owns exiting and main() stays callable from a test.
@@ -978,3 +1054,5 @@ def main(argv: list[str] | None = None) -> int:
978
1054
  except (OSError, ValueError, RuntimeError, KeyError) as error:
979
1055
  print('forge jev: ' + redact(str(error)), file=sys.stderr)
980
1056
  return 3
1057
+ finally:
1058
+ use_repo(None)