@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
@@ -1,19 +1,29 @@
1
1
  #!/usr/bin/env python3
2
2
  """forge config <command>: one view of every config source, and safe edits for the per-repo ones.
3
3
 
4
- show [--repo DIR] [--json] registry, Jev, the repo's .forge files, dataset and FORGE_* env
5
- set <key> <value> --repo DIR [--json] repo.verify | repo.setup | repo.verify-subset | jev.enabled
6
- unset <key> --repo DIR [--json] repo.verify | repo.setup | repo.verify-subset
7
-
8
- A value of `-` reads stdin. repo.verify-subset must contain `{files}`. jev.enabled true|false is
9
- delegated to `forge jev enable|disable`. The registry is read-only here: the skill dir is often a
10
- live symlink to a checkout, so an edit would change runs already in progress; edit the checkout.
4
+ show [--repo DIR] [--json] registry, Jev, decide, the repo's .forge files, dataset and FORGE_* env
5
+ set <key> <value> [--repo DIR] [--json] repo.verify | repo.setup | repo.verify-subset | decide.gate.<gate>[.provider|.model]
6
+ unset <key> [--repo DIR] [--json] repo.verify | repo.setup | repo.verify-subset
7
+
8
+ A value of `-` reads stdin for the per-repo files. repo.verify-subset must contain `{files}` (the
9
+ selected test files) or `{changed}` (the changed paths, for a runner with a related-tests mode).
10
+ decide.gate.<gate> (off, shadow or on) is delegated to `forge decide gate` and writes the user
11
+ level. decide.gate.<gate>.provider and decide.gate.<gate>.model write the user level with no mode,
12
+ so the gate keeps the mode the other levels give it. Unset of those keys is refused: set the mode
13
+ to off. jev.enabled is gone; set a gate with decide.gate.<gate>. The registry is
14
+ read-only here: the skill dir is often a live symlink to a checkout, so an edit would change
15
+ runs already in progress; edit the checkout.
11
16
 
12
17
  Only the three per-repo files are ever read for content; cloudflare.env never is. Values of FORGE_*
13
- variables whose name contains TOKEN, KEY, SECRET or PASSWORD show as "<set>".
18
+ variables whose name contains TOKEN, KEY, SECRET or PASSWORD show as "<set>". A provider key never
19
+ appears in show.
20
+
21
+ A provider or model written to a gate that is `on` and not forced needs a passing replay of the
22
+ new provider and model, as `forge decide gate G on` does; without one nothing is written and the
23
+ exit code is 3 (with --json, an error object on stdout too).
14
24
 
15
- Exit codes: 0 ok, 2 usage or invalid input (including an unsafe path); any other code is the jev
16
- CLI's own, passed through.
25
+ Exit codes: 0 ok, 2 usage or invalid input (including an unsafe path), 3 refused by the promotion
26
+ rule; any other code is the decide CLI's own, passed through.
17
27
  """
18
28
  from __future__ import annotations
19
29
 
@@ -21,6 +31,7 @@ import argparse
21
31
  import json
22
32
  import os
23
33
  from pathlib import Path
34
+ import re
24
35
  import stat
25
36
  import subprocess
26
37
  import sys
@@ -28,14 +39,26 @@ import sys
28
39
  SKILL = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
29
40
  sys.path.insert(0, os.path.join(SKILL, 'scripts'))
30
41
 
42
+ from forge_decide import GATES, MODES, load_user, save_user, user_path
43
+ from forge_decide.migrate import run as migrate_run
44
+ from forge_decide.providers import spec_for_site
45
+
31
46
  REPO_FILES = ('verify', 'setup', 'verify-subset')
32
- KEYS = tuple('repo.' + n for n in REPO_FILES) + ('jev.enabled',)
47
+ KEYS = tuple('repo.' + n for n in REPO_FILES)
48
+ # decide.gate.<gate>, and the same with .provider or .model. The gate is checked against GATES.
49
+ _DECIDE_KEY = re.compile(r'^decide\.gate\.([A-Za-z0-9_-]+?)(?:\.(provider|model))?$')
50
+ MAX_DECIDE_VALUE = 256
51
+ _SECRET_PROVIDER_FIELDS = ('key', 'key_source', 'key_file', 'key_env')
33
52
  CONTENT_MAX = 64 * 1024
34
53
  SECRET_WORDS = ('TOKEN', 'KEY', 'SECRET', 'PASSWORD')
35
54
  REGISTRY_NOTE = ('read-only here: the skill dir is often a live symlink to a checkout, so an edit '
36
55
  'changes runs already in progress; edit registry.tsv in the checkout instead')
37
56
 
38
57
 
58
+ class Refused(Exception):
59
+ """A change the promotion rule refuses (#37): exit 3."""
60
+
61
+
39
62
  class Invalid(Exception):
40
63
  """Usage or invalid input, an unsafe path included: exit 2."""
41
64
 
@@ -170,6 +193,47 @@ def jev_block():
170
193
  return dict(path=str(path), exists=path.is_file(), enabled=bool(load_config().get('enabled')))
171
194
 
172
195
 
196
+ def _gate_ready(gate, providers):
197
+ """A gate can run when it is shadow or on, nothing skips it, and its provider is local or has a key.
198
+
199
+ With no provider the run uses the legacy client, so the gate is ready when that client has a key.
200
+ """
201
+ if gate.get('mode') not in ('shadow', 'on') or gate.get('skip'):
202
+ return False
203
+ if not gate.get('provider'):
204
+ # resolved={} names no provider, so spec_for_site gives the legacy spec the run would use
205
+ try:
206
+ return bool(spec_for_site(gate['site'], resolved={}).get('key'))
207
+ except Exception: # a legacy config the run cannot describe; show must still print (resolve.py too)
208
+ return False
209
+ row = providers.get(gate['provider'])
210
+ if not isinstance(row, dict):
211
+ return False
212
+ if row.get('local') is True:
213
+ return True
214
+ return row.get('key') == 'present'
215
+
216
+
217
+ def decide_block(root):
218
+ """The full `forge decide status --json` object for `root`, plus `ready` on each gate.
219
+
220
+ Provider rows drop every key field. `ready` is computed before that, so a hosted provider
221
+ with a key on file still counts. The key itself is never copied.
222
+ """
223
+ from forge_decide.cli import status_data
224
+ data = status_data(root)
225
+ full = data.get('providers') if isinstance(data.get('providers'), dict) else {}
226
+ gates = data.get('gates') if isinstance(data.get('gates'), dict) else {}
227
+ for gate in gates.values():
228
+ if isinstance(gate, dict):
229
+ gate['ready'] = _gate_ready(gate, full)
230
+ data['providers'] = {
231
+ name: {k: v for k, v in row.items() if k not in _SECRET_PROVIDER_FIELDS}
232
+ for name, row in full.items() if isinstance(row, dict)
233
+ }
234
+ return data
235
+
236
+
173
237
  def repo_block(root):
174
238
  files = {}
175
239
  for name in REPO_FILES:
@@ -218,9 +282,54 @@ def env_block():
218
282
  return out
219
283
 
220
284
 
285
+ def _print_decide(decide):
286
+ """The human view of a status object. A provider key is not among these fields."""
287
+ privacy = decide.get('privacy') if isinstance(decide.get('privacy'), dict) else {}
288
+ print('decide: %s (%s, migrated %s, privacy floor %s)' % (
289
+ decide.get('user_path'), 'present' if decide.get('migrated') else 'absent',
290
+ 'yes' if decide.get('migrated') else 'no',
291
+ 'yes' if privacy.get('floor') else 'no'))
292
+ gates = decide.get('gates') if isinstance(decide.get('gates'), dict) else {}
293
+ for name, gate in gates.items():
294
+ if not isinstance(gate, dict):
295
+ print(' gate %s: %s' % (name, gate))
296
+ continue
297
+ bits = [str(gate.get('mode')), 'source %s' % gate.get('source')]
298
+ if gate.get('provider'):
299
+ bits.append('provider %s' % gate['provider'])
300
+ if gate.get('model'):
301
+ bits.append('model %s' % gate['model'])
302
+ if gate.get('skip'):
303
+ bits.append('skip %s' % gate['skip'])
304
+ bits.append('ready %s' % ('yes' if gate.get('ready') else 'no'))
305
+ print(' gate %s: %s' % (name, ', '.join(bits)))
306
+ providers = decide.get('providers') if isinstance(decide.get('providers'), dict) else {}
307
+ if providers:
308
+ parts = []
309
+ for name, row in providers.items():
310
+ row = row if isinstance(row, dict) else {}
311
+ kind = row.get('type') or ''
312
+ local = ' local' if row.get('local') else ''
313
+ parts.append('%s (%s%s)' % (name, kind, local) if kind or row.get('local') else name)
314
+ print(' providers: %s' % ', '.join(parts))
315
+ else:
316
+ print(' providers: none')
317
+ budget = decide.get('budget') if isinstance(decide.get('budget'), dict) else {}
318
+ caps = budget.get('caps') if isinstance(budget.get('caps'), dict) else {}
319
+ shown = ', '.join('%s=%s' % (key, value) for key, value in caps.items() if value is not None)
320
+ print(' budget: %s' % (shown or 'none'))
321
+ spend = budget.get('spend') if isinstance(budget.get('spend'), dict) else None
322
+ if spend and isinstance(spend.get('today'), dict):
323
+ today = spend['today']
324
+ print(' today (%s): %s tokens, $%s' % (spend.get('date'), today.get('tokens'), today.get('usd')))
325
+ for entry in decide.get('shadowed') or []:
326
+ if isinstance(entry, dict):
327
+ print(' shadowed: %s: repo %r, user %r' % (entry.get('key'), entry.get('repo'), entry.get('user')))
328
+
329
+
221
330
  def cmd_show(args):
222
331
  root = repo_root(args.repo, required=False)
223
- data = dict(registry=registry_block(), jev=jev_block())
332
+ data = dict(registry=registry_block(), jev=jev_block(), decide=decide_block(root))
224
333
  if root:
225
334
  data['repo'] = repo_block(root)
226
335
  data['dataset'] = dataset_block()
@@ -236,6 +345,7 @@ def cmd_show(args):
236
345
  jev = data['jev']
237
346
  print('jev: %s (%s, %s)' % ('enabled' if jev['enabled'] else 'disabled', jev['path'],
238
347
  'present' if jev['exists'] else 'absent'))
348
+ _print_decide(data['decide'])
239
349
  if root:
240
350
  print('repo: %s' % root)
241
351
  for name, entry in data['repo']['files'].items():
@@ -252,7 +362,85 @@ def cmd_show(args):
252
362
 
253
363
  def check_key(key):
254
364
  if key not in KEYS:
255
- raise Invalid('unknown key %r; valid keys: %s' % (key, ', '.join(KEYS)))
365
+ raise Invalid('unknown key %r; valid keys: %s, decide.gate.<gate>, '
366
+ 'decide.gate.<gate>.provider, decide.gate.<gate>.model' % (key, ', '.join(KEYS)))
367
+
368
+
369
+ def decide_target(key):
370
+ """(gate, field) for a decide key. field is None, 'provider' or 'model'.
371
+
372
+ None when `key` is not that shape. Invalid when the shape names a gate that does not exist.
373
+ """
374
+ match = _DECIDE_KEY.fullmatch(key or '')
375
+ if not match:
376
+ return None
377
+ gate, field = match.group(1), match.group(2)
378
+ if gate not in GATES:
379
+ raise Invalid('unknown gate %r; gates: %s' % (gate, ', '.join(GATES)))
380
+ return gate, field
381
+
382
+
383
+ def _no_control(value):
384
+ return not any(ord(ch) < 32 or ord(ch) == 127 or 0xD800 <= ord(ch) <= 0xDFFF for ch in value)
385
+
386
+
387
+ def _decide_value(field, value):
388
+ """The mode, or a provider or model name. A decide value is never read from stdin."""
389
+ if field is None:
390
+ if value not in MODES:
391
+ raise Invalid('mode must be off, shadow or on')
392
+ return value
393
+ if (not isinstance(value, str) or not value or value != value.strip()
394
+ or len(value) > MAX_DECIDE_VALUE or value.startswith('-') or not _no_control(value)):
395
+ raise Invalid('short single-line text, not starting with "-"')
396
+ return value
397
+
398
+
399
+ def _check_replayed(gate, entry, providers):
400
+ """Refuse (before anything is written) an `on` entry, not forced, whose provider and model, as
401
+ `entry` will have them, have no passing replay: the rule `forge decide gate G on` applies."""
402
+ if entry.get('mode') != 'on' or entry.get('force'):
403
+ return
404
+ from forge_decide import GATE_SITE
405
+ from forge_decide.providers import identity
406
+ from forge_decide.replay import recorded
407
+ site = GATE_SITE[gate]
408
+ provider, model = identity(site, entry, providers=providers, env={})
409
+ stored = recorded(gate, provider, model)
410
+ if stored is not None and stored.get('passes') is True:
411
+ return
412
+ raise Refused('%s is on and has no passing replay on provider %s, model %s.\n'
413
+ 'Run `forge decide replay --site %s --provider %s --model %s --send`, '
414
+ 'or turn it on without one with `forge decide gate %s on --force` (shown as forced).' % (gate, provider, model, site, provider, model, gate))
415
+
416
+
417
+ def _write_user_field(gate, field, value):
418
+ """Set a gate's provider or model in the user file, storing no mode.
419
+
420
+ `forge decide gate` always writes a mode, and a mode written here would outlive the repo, profile
421
+ or environment variable that set it. So the field is written here, after the jev.json migration
422
+ and the provider check that `forge decide gate` makes. A mode the user file holds is kept as it is.
423
+ """
424
+ result = migrate_run()
425
+ if result['status'] == 'migrated':
426
+ print('forge config: migrated jev.json into %s first' % user_path(), file=sys.stderr)
427
+ data, error = load_user()
428
+ if error:
429
+ raise Invalid(error)
430
+ providers = data.get('providers')
431
+ providers = providers if isinstance(providers, dict) else {}
432
+ if field == 'provider' and value not in providers:
433
+ raise Invalid('unknown provider %r; configured: %s (add one with `forge decide provider add`)'
434
+ % (value, ', '.join(sorted(providers)) or 'none'))
435
+ gates = data.get('gates') if isinstance(data.get('gates'), dict) else {}
436
+ entry = gates.get(gate)
437
+ entry = dict(mode=entry) if isinstance(entry, str) else dict(entry) if isinstance(entry, dict) else {}
438
+ entry[field] = value
439
+ _check_replayed(gate, entry, providers)
440
+ gates[gate] = entry
441
+ data['gates'] = gates
442
+ data.setdefault('version', 1)
443
+ save_user(data)
256
444
 
257
445
 
258
446
  def emit(args, key, previous, value):
@@ -263,9 +451,10 @@ def emit(args, key, previous, value):
263
451
 
264
452
 
265
453
  def cmd_set(args):
266
- check_key(args.key)
267
454
  if args.key == 'jev.enabled':
268
- return set_jev(args)
455
+ raise Invalid('jev.enabled is gone; set a gate with decide.gate.<gate>')
456
+ if args.key not in KEYS:
457
+ return set_decide(args)
269
458
  root = repo_root(args.repo, required=True)
270
459
  if root is None:
271
460
  raise Invalid('--repo DIR is required for %s' % args.key)
@@ -273,8 +462,8 @@ def cmd_set(args):
273
462
  name = args.key[len('repo.'):]
274
463
  if not value.strip():
275
464
  raise Invalid('empty value; use `forge config unset %s` to remove it' % args.key)
276
- if name == 'verify-subset' and '{files}' not in value:
277
- raise Invalid('repo.verify-subset must contain {files}')
465
+ if name == 'verify-subset' and '{files}' not in value and '{changed}' not in value:
466
+ raise Invalid('repo.verify-subset must contain {files} or {changed}')
278
467
  d, target = safe_target(root, name)
279
468
  previous = read_small(target)[0] if d else None
280
469
  if not value.endswith('\n'):
@@ -285,9 +474,11 @@ def cmd_set(args):
285
474
 
286
475
 
287
476
  def cmd_unset(args):
288
- check_key(args.key)
289
477
  if args.key == 'jev.enabled':
290
- raise Invalid('jev.enabled cannot be unset; use `set jev.enabled true|false`')
478
+ raise Invalid('jev.enabled is gone; set a gate with decide.gate.<gate>')
479
+ if decide_target(args.key):
480
+ raise Invalid('set the mode to off')
481
+ check_key(args.key)
291
482
  root = repo_root(args.repo, required=True)
292
483
  if root is None:
293
484
  raise Invalid('--repo DIR is required for %s' % args.key)
@@ -303,16 +494,29 @@ def cmd_unset(args):
303
494
  return 0
304
495
 
305
496
 
306
- def set_jev(args):
307
- if args.value not in ('true', 'false'):
308
- raise Invalid('jev.enabled takes true or false')
309
- previous = jev_block()['enabled']
310
- verb = 'enable' if args.value == 'true' else 'disable'
311
- run = subprocess.run([sys.executable, os.path.join(SKILL, 'scripts', 'forge-jev.py'), verb],
312
- stdout=subprocess.DEVNULL, stderr=None)
313
- if run.returncode != 0:
314
- return run.returncode
315
- emit(args, args.key, previous, args.value == 'true')
497
+ def set_decide(args):
498
+ """Write one decide key at the user level: a mode through `forge decide gate`, a provider or model
499
+ through _write_user_field. --repo is only the repo whose effective settings are read for `previous`."""
500
+ found = decide_target(args.key)
501
+ if found is None:
502
+ check_key(args.key)
503
+ gate, field = found
504
+ value = _decide_value(field, args.value)
505
+ root = repo_root(args.repo, required=True) if args.repo is not None else None
506
+ from forge_decide.cli import status_data
507
+ before = status_data(root)
508
+ row = (before.get('gates') or {}).get(gate) or {}
509
+ if field is None:
510
+ previous = row.get('mode')
511
+ script = os.path.join(SKILL, 'scripts', 'forge-decide.py')
512
+ run = subprocess.run([sys.executable, script, 'gate', gate, value],
513
+ stdout=subprocess.DEVNULL, stderr=None)
514
+ if run.returncode != 0:
515
+ return run.returncode
516
+ else:
517
+ previous = row.get(field)
518
+ _write_user_field(gate, field, value)
519
+ emit(args, args.key, previous, value)
316
520
  return 0
317
521
 
318
522
 
@@ -344,6 +548,11 @@ def main(argv=None):
344
548
  except Invalid as err:
345
549
  print('forge config: %s' % err, file=sys.stderr)
346
550
  return 2
551
+ except Refused as err:
552
+ print('forge config: %s' % err, file=sys.stderr)
553
+ if getattr(args, 'json', False):
554
+ print(json.dumps(dict(ok=False, key=args.key, error=str(err))))
555
+ return 3
347
556
 
348
557
 
349
558
  if __name__ == '__main__':
@@ -3,13 +3,14 @@
3
3
 
4
4
  Three subcommands, stdlib only, no network:
5
5
 
6
- qa --part head|tail [--kind task|final|solo|sweep] [--threshold P0|P1|P2|P3]
6
+ qa --part head|tail [--kind task|final|solo|sweep] [--threshold P0|P1|P2|P3|none]
7
7
  Prints one piece of the QA prompt. The caller prints everything between and
8
8
  after the pieces itself (scope notes, the diff fence, the memory note and the
9
9
  "Place any learning notes before the final FORGE_VERDICT ..." sentence).
10
- dwarf
11
- Prints the implementer rules block that callers append to the dwarf prompt.
12
- gate --verdict PASS|FAIL|UNKNOWN --qa-last FILE [--threshold Pn] [--known-issues OUT]
10
+ dwarf [--pre-review]
11
+ Prints the implementer rules block that callers append to the dwarf prompt;
12
+ --pre-review adds that forge runs the affected tests before the review (#85).
13
+ gate --verdict PASS|FAIL|UNKNOWN --qa-last FILE [--threshold Pn|none] [--known-issues OUT]
13
14
  Prints ONE tab-separated line
14
15
  decision <TAB> worst_confirmed <TAB> n_confirmed <TAB> n_unlabelled <TAB> n_below
15
16
  and, when findings were tolerated, writes them to OUT.
@@ -19,25 +20,29 @@ result on the main path), P1 (wrong behaviour on realistic input, breaks an exis
19
20
  contract), P2 (edge-case bug, unusual-timing race, missing hardening) or P3 (minor).
20
21
  Severity is impact; confidence stays CONFIRMED vs PLAUSIBLE.
21
22
 
22
- Threshold. Without one nothing changes: any CONFIRMED finding means FAIL and the gate
23
- never overrides a verdict. The threshold is the LEAST severe level that still blocks:
24
- `P2` means P0, P1 and P2 block and only P3 is tolerated; `P0` means only P0 blocks;
25
- `P3` means everything blocks (nothing is ever tolerated). A threshold of "" is "unset".
26
-
27
- The gate. decision is `accept` only when ALL of these hold, otherwise `keep`:
28
- - a threshold is set and the verdict is FAIL (PASS and UNKNOWN are always `keep`);
29
- - at least one CONFIRMED finding exists (a FAIL with none stays a FAIL);
30
- - n_unlabelled == 0, and every CONFIRMED finding carries a P0-P3 label strictly less
31
- severe than the threshold.
32
- `accept` is a statement about the findings only; wiring it into a verdict is the
23
+ Threshold. The threshold is the LEAST severe level that still blocks: `P2` means P0, P1
24
+ and P2 block and only P3 is tolerated; `P0` means only P0 blocks; `P3` means everything
25
+ blocks (nothing is ever tolerated). There is always one: unset (None or "") means
26
+ DEFAULT_THRESHOLD, P2, and `none` (any case) means P3, nothing tolerated.
27
+
28
+ The gate. A finding is BLOCKING when it is CONFIRMED with a severity at the threshold or
29
+ worse, CONFIRMED with no severity, or UNSTATED with a severity at the threshold or worse.
30
+ PLAUSIBLE findings never block. decision is one of:
31
+ - `fail` when the verdict is PASS and at least one finding is blocking;
32
+ - `accept` when ALL of these hold: the verdict is FAIL; at least one CONFIRMED finding
33
+ exists (a FAIL with none stays a FAIL); n_unlabelled == 0, and every CONFIRMED
34
+ finding carries a P0-P3 label strictly less severe than the threshold;
35
+ - `keep` otherwise, and always for UNKNOWN.
36
+ The decision is a statement about the findings only; wiring it into a verdict is the
33
37
  caller's job. Fail-safe means blocking: anything the parser cannot read confidently
34
- pushes toward `keep`, never toward `accept`.
38
+ pushes toward `keep` for a FAIL and toward `fail` for a PASS, never toward `accept`.
35
39
 
36
40
  Fields: worst_confirmed is the most severe label among CONFIRMED labelled findings
37
41
  (`-` if none); n_confirmed counts CONFIRMED findings; n_unlabelled counts CONFIRMED
38
42
  findings with no recognisable severity, plus located findings carrying a severity but
39
43
  no CONFIRMED/PLAUSIBLE tag at all (neither can ever be tolerated); n_below counts
40
- CONFIRMED labelled findings below the threshold (0 with no threshold).
44
+ CONFIRMED labelled findings strictly below the threshold. They are the tolerated ones,
45
+ listed in OUT whenever n_below >= 1, whatever the decision.
41
46
 
42
47
  Parsing. The reply is cut into finding blocks. A block starts at a bullet (`-`, `*`,
43
48
  `+`, `1.`, `1)`), a markdown heading, a table row, or a flush line that leads with a
@@ -74,6 +79,8 @@ import sys
74
79
  SEVERITIES = ('P0', 'P1', 'P2', 'P3')
75
80
  PLACEHOLDER = 'path/file.py:123'
76
81
  KINDS = ('task', 'final', 'solo', 'sweep')
82
+ DEFAULT_THRESHOLD = 'P2'
83
+ QA_TEST_MINUTES = 5 # the reviewer's own test time, beyond which it says the check is too broad (#89)
77
84
 
78
85
  Finding = collections.namedtuple('Finding', 'status severity located line text')
79
86
  Finding.__doc__ = (
@@ -83,18 +90,19 @@ Finding.__doc__ = (
83
90
  GateResult = collections.namedtuple(
84
91
  'GateResult', 'decision worst n_confirmed n_unlabelled n_below tolerated')
85
92
  GateResult.__doc__ = (
86
- 'decision accept|keep, worst most severe confirmed label or "-", counters, and the '
93
+ 'decision accept|fail|keep, worst most severe confirmed label or "-", counters, and the '
87
94
  'tuple of tolerated Findings (CONFIRMED, labelled, below the threshold).')
88
95
 
89
96
 
90
97
  # --- prompt text -----------------------------------------------------------------
91
98
 
92
- def _rank(threshold) -> 'int | None':
93
- if threshold is None or str(threshold).strip() == '':
94
- return None
95
- value = str(threshold).strip().upper()
99
+ def _rank(threshold) -> int:
100
+ """The threshold's index (P0 = 0): None or "" is the default, `none` is P3."""
101
+ value = str(threshold if threshold is not None else '').strip().upper() or DEFAULT_THRESHOLD
102
+ if value == 'NONE':
103
+ value = SEVERITIES[-1]
96
104
  if value not in SEVERITIES:
97
- raise ValueError('threshold must be one of ' + ', '.join(SEVERITIES))
105
+ raise ValueError('threshold must be one of ' + ', '.join(SEVERITIES) + ' or none')
98
106
  return int(value[1])
99
107
 
100
108
 
@@ -143,6 +151,18 @@ _FINDINGS = [
143
151
  ]
144
152
  _SOLO_EXTRA = ['If the diff is correct, say so plainly rather than inventing something to report.']
145
153
 
154
+ # The reviewer's own verification, bounded to the change (#89): one reviewer re-ran a whole
155
+ # repository suite to review a one-file patch. The evidence is what the caller prints between
156
+ # the head and the tail (fail-first, pre-review tests).
157
+ _VERIFY = [
158
+ 'Verify within the change: run only the tests that touch the changed code (the tests the',
159
+ 'diff adds or edits, and the tests of the modules it changes), never the whole suite, and',
160
+ 'spend at most about %d minutes running tests. Use any test evidence forge gives you above' % QA_TEST_MINUTES,
161
+ 'before running a test yourself. When the targeted tests would take longer, or the change',
162
+ 'touches shared infrastructure (a test helper, a build file, a lockfile), say so instead of',
163
+ 'running everything.',
164
+ ]
165
+
146
166
  _SEVERITY = [
147
167
  'Label every finding with its severity at the start of its own bullet, in exactly this form:',
148
168
  ' - [P1][CONFIRMED] path/file.py:123 — what breaks (trigger input)',
@@ -154,8 +174,6 @@ _SEVERITY = [
154
174
  ' P3 minor: cosmetic, naming, nit-level correctness',
155
175
  ]
156
176
 
157
- _NO_THRESHOLD = ['The severity tag does not change the verdict rule below.']
158
-
159
177
  _SWEEP_FINDINGS = [
160
178
  'Report findings only — do not edit any file. A finding here is a regression the change',
161
179
  'introduced: give its file and line, what breaks, and a concrete input that triggers it. Mark it',
@@ -170,8 +188,11 @@ _SWEEP_STATUS = [
170
188
  'repeat a NOT FIXED finding as a finding bullet; its line is enough.',
171
189
  ]
172
190
 
173
- _PASS = ' FORGE_VERDICT: PASS — no confirmed correctness bug (style nits are not failures)'
174
- _FAIL = ' FORGE_VERDICT: FAIL — at least one CONFIRMED correctness bug'
191
+ _CHECKED = [
192
+ 'forge checks the verdict against your findings: a PASS that lists a blocking CONFIRMED',
193
+ 'finding is turned into FAIL. List only problems still present in the code under review;',
194
+ 'never list a fixed problem as a finding.',
195
+ ]
175
196
 
176
197
 
177
198
  def _threshold_clause(rank: int, kind: str = 'task') -> list:
@@ -201,15 +222,14 @@ def qa_text(part: str, kind: str = 'task', threshold=None) -> str:
201
222
  if part != 'tail':
202
223
  raise ValueError('part must be head or tail')
203
224
  lines = list(_SWEEP_FINDINGS if kind == 'sweep' else _FINDINGS) + (_SOLO_EXTRA if kind == 'solo' else [])
225
+ lines += [''] + _VERIFY
204
226
  lines += [''] + _SEVERITY
205
- lines += [''] + (_NO_THRESHOLD if rank is None else _threshold_clause(rank, kind))
227
+ lines += [''] + _threshold_clause(rank, kind) + _CHECKED
206
228
  if kind == 'sweep':
207
229
  lines += [''] + _SWEEP_STATUS
208
- where = '' if rank is None else ' at the blocking threshold (%s or worse)' % SEVERITIES[rank]
230
+ where = ' at the blocking threshold (%s or worse)' % SEVERITIES[rank]
209
231
  verdicts = [' FORGE_VERDICT: PASS — at least one listed finding is FIXED, and no CONFIRMED regression%s' % where,
210
232
  ' FORGE_VERDICT: FAIL — no listed finding is FIXED, or a CONFIRMED regression%s' % where]
211
- elif rank is None:
212
- verdicts = [_PASS, _FAIL]
213
233
  else:
214
234
  where = '%s or worse' % SEVERITIES[rank]
215
235
  verdicts = [' FORGE_VERDICT: PASS — no CONFIRMED finding at the blocking threshold (%s)' % where,
@@ -223,15 +243,24 @@ _DWARF = [
223
243
  '- Do not run git commit, checkout, switch, reset, stash or rebase. The harness captures',
224
244
  ' the working tree itself; a self-commit makes the change set ambiguous.',
225
245
  '- Do not start background processes, and leave nothing running when you finish.',
246
+ '- Verify within your change: run the tests the change affects (the task\'s own tests and the',
247
+ ' tests of the modules you changed). Do not run the whole suite or repo-wide lint, format or',
248
+ ' type checks unless the task asks for them.',
226
249
  '- Finish every measurement and test run BEFORE your last message and report its actual',
227
250
  ' result. If you could not run something, say so explicitly instead of claiming it passed.',
228
251
  '- State precisely which verification commands you ran and what each one returned.',
229
252
  ]
230
253
 
231
254
 
232
- def dwarf_text() -> str:
255
+ _DWARF_PRE_REVIEW = [
256
+ '- forge runs the tests this change affects before the review, and a failure comes back to',
257
+ ' you instead of a review: you need not repeat them exhaustively, but report what you ran.',
258
+ ]
259
+
260
+
261
+ def dwarf_text(pre_review: bool = False) -> str:
233
262
  """The implementer rules block, newline-terminated."""
234
- return '\n'.join(_DWARF) + '\n'
263
+ return '\n'.join(_DWARF + (_DWARF_PRE_REVIEW if pre_review else [])) + '\n'
235
264
 
236
265
 
237
266
  # --- parsing ---------------------------------------------------------------------
@@ -262,7 +291,7 @@ def _contract_flat() -> str:
262
291
  parts = [dwarf_text()]
263
292
  for kind in KINDS:
264
293
  for part in ('head', 'tail'):
265
- for threshold in (None,) + SEVERITIES:
294
+ for threshold in SEVERITIES: # None and `none` render one of these
266
295
  parts.append(qa_text(part, kind, threshold))
267
296
  return _collapse(' '.join(parts))
268
297
 
@@ -352,7 +381,8 @@ def parse_findings(text: str) -> list:
352
381
  # --- the gate --------------------------------------------------------------------
353
382
 
354
383
  def gate(verdict: str, text: str, threshold=None) -> GateResult:
355
- """Decide whether a QA FAIL may be accepted as PASS-with-known-issues."""
384
+ """Check a QA verdict against its findings: a FAIL may be accepted as
385
+ PASS-with-known-issues, a PASS that lists a blocking finding fails."""
356
386
  rank = _rank(threshold)
357
387
  findings = parse_findings(text)
358
388
  confirmed = [f for f in findings if f.status == 'CONFIRMED']
@@ -360,11 +390,17 @@ def gate(verdict: str, text: str, threshold=None) -> GateResult:
360
390
  unlabelled = (len(confirmed) - len(labelled)
361
391
  + sum(1 for f in findings if f.status == 'UNSTATED'))
362
392
  worst = 'P%d' % min(f.severity for f in labelled) if labelled else '-'
363
- below = tuple(f for f in labelled if rank is not None and f.severity > rank)
364
- accept = (rank is not None and verdict == 'FAIL' and bool(confirmed)
365
- and unlabelled == 0 and len(below) == len(confirmed))
366
- return GateResult('accept' if accept else 'keep', worst, len(confirmed),
367
- unlabelled, len(below), below)
393
+ below = tuple(f for f in labelled if f.severity > rank)
394
+ blocking = any(f.status in ('CONFIRMED', 'UNSTATED')
395
+ and (f.severity is None or f.severity <= rank) for f in findings)
396
+ if verdict == 'PASS' and blocking:
397
+ decision = 'fail'
398
+ elif (verdict == 'FAIL' and confirmed and unlabelled == 0
399
+ and len(below) == len(confirmed)):
400
+ decision = 'accept'
401
+ else:
402
+ decision = 'keep'
403
+ return GateResult(decision, worst, len(confirmed), unlabelled, len(below), below)
368
404
 
369
405
 
370
406
  def known_issues_text(threshold, tolerated) -> str:
@@ -380,13 +416,12 @@ def known_issues_text(threshold, tolerated) -> str:
380
416
 
381
417
  # --- command line ----------------------------------------------------------------
382
418
 
383
- def _threshold_arg(value: str):
384
- value = value.strip().upper()
385
- if value == '':
386
- return None
387
- if value not in SEVERITIES:
388
- raise argparse.ArgumentTypeError('invalid threshold %r (choose P0, P1, P2 or P3)' % value)
389
- return value
419
+ def _threshold_arg(value: str) -> str:
420
+ try:
421
+ return SEVERITIES[_rank(value)]
422
+ except ValueError:
423
+ raise argparse.ArgumentTypeError(
424
+ 'invalid threshold %r (choose P0, P1, P2, P3 or none)' % value.strip()) from None
390
425
 
391
426
 
392
427
  def _emit(text: str) -> None:
@@ -400,8 +435,10 @@ def _parser() -> argparse.ArgumentParser:
400
435
  prog='forge-contract.py', formatter_class=argparse.RawDescriptionHelpFormatter,
401
436
  description='Shared QA contract, implementer rules and severity gate for forge.',
402
437
  epilog='threshold: the LEAST severe level that still blocks. P2 = P0, P1 and P2 '
403
- 'block, only P3 is tolerated; P0 = only P0 blocks; P3 = everything blocks. '
404
- 'Unset (or empty) = no gate, today\'s semantics.')
438
+ 'block, only P3 is tolerated; P0 = only P0 blocks; P3 = everything blocks; '
439
+ 'none = P3. Unset (or empty) = the default, %s. The gate turns a FAIL whose '
440
+ 'findings are all tolerated into accept, and a PASS that lists a blocking '
441
+ 'finding into fail.' % DEFAULT_THRESHOLD)
405
442
  sub = parser.add_subparsers(dest='command', required=True)
406
443
  qa = sub.add_parser('qa', help='print one piece of the QA prompt')
407
444
  qa.add_argument('--part', required=True, choices=('head', 'tail'),
@@ -409,15 +446,17 @@ def _parser() -> argparse.ArgumentParser:
409
446
  qa.add_argument('--kind', choices=KINDS, default='task',
410
447
  help='task (default), final (whole-run review), solo (solo wording) or sweep (a finding '
411
448
  'sweep task: per-finding FIXED lines, regressions only)')
412
- qa.add_argument('--threshold', type=_threshold_arg, default=None, metavar='P0..P3',
413
- help='least severe level that still blocks (default: none)')
414
- sub.add_parser('dwarf', help='print the implementer rules block')
449
+ qa.add_argument('--threshold', type=_threshold_arg, default=None, metavar='P0..P3|none',
450
+ help='least severe level that still blocks; none = P3 (default: %s)' % DEFAULT_THRESHOLD)
451
+ dwarf = sub.add_parser('dwarf', help='print the implementer rules block')
452
+ dwarf.add_argument('--pre-review', action='store_true', help='forge runs the affected tests before the review')
415
453
  gate_parser = sub.add_parser(
416
- 'gate', help='print: decision, worst_confirmed, n_confirmed, n_unlabelled, n_below')
454
+ 'gate', help='print: decision (accept|fail|keep), worst_confirmed, n_confirmed, n_unlabelled, n_below')
417
455
  gate_parser.add_argument('--verdict', required=True, choices=('PASS', 'FAIL', 'UNKNOWN'))
418
456
  gate_parser.add_argument('--qa-last', required=True, metavar='FILE', help="the QA reply")
419
- gate_parser.add_argument('--threshold', type=_threshold_arg, default=None, metavar='P0..P3',
420
- help='least severe level that still blocks (default: none)')
457
+ gate_parser.add_argument('--threshold', type=_threshold_arg, default=None, metavar='P0..P3|none',
458
+ help='least severe level that still blocks; none = P3 (default: %s)'
459
+ % DEFAULT_THRESHOLD)
421
460
  gate_parser.add_argument('--known-issues', metavar='OUT', default=None,
422
461
  help='write tolerated findings here when there are any')
423
462
  return parser
@@ -429,7 +468,7 @@ def main(argv=None) -> int:
429
468
  _emit(qa_text(args.part, args.kind, args.threshold))
430
469
  return 0
431
470
  if args.command == 'dwarf':
432
- _emit(dwarf_text())
471
+ _emit(dwarf_text(args.pre_review))
433
472
  return 0
434
473
  try:
435
474
  with open(args.qa_last, 'rb') as handle: