@giamme/forge 0.13.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/SKILL.md +17 -11
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +1 -0
  5. package/docs/commands.md +121 -7
  6. package/docs/development.md +3 -0
  7. package/docs/reviews.md +2 -0
  8. package/docs/troubleshooting.md +5 -1
  9. package/forge +28 -1
  10. package/package.json +1 -1
  11. package/references/dataset.md +3 -1
  12. package/references/decompose.md +199 -61
  13. package/references/runtime.md +29 -0
  14. package/references/ui.md +10 -0
  15. package/scripts/forge-compare.py +491 -0
  16. package/scripts/forge-config.py +3 -3
  17. package/scripts/forge-contract.py +34 -8
  18. package/scripts/forge-control.py +105 -13
  19. package/scripts/forge-dispatch.sh +9 -5
  20. package/scripts/forge-jev-options.sh +17 -4
  21. package/scripts/forge-ledger.py +387 -0
  22. package/scripts/forge-lib-plans.sh +11 -2
  23. package/scripts/forge-lib-task.sh +390 -28
  24. package/scripts/forge-parallel-options.sh +20 -4
  25. package/scripts/forge-parallel.sh +116 -12
  26. package/scripts/forge-plan-check.py +68 -3
  27. package/scripts/forge-pr.py +276 -0
  28. package/scripts/forge-route.py +350 -34
  29. package/scripts/forge-runs.py +18 -1
  30. package/scripts/forge-runtime.py +23 -7
  31. package/scripts/forge-schedule.py +303 -46
  32. package/scripts/forge-verify-failed.py +111 -0
  33. package/scripts/forge-watch.py +372 -0
  34. package/scripts/forge_dataset/harvest.py +3 -1
  35. package/scripts/forge_fractal/cli.py +23 -6
  36. package/scripts/forge_infra.py +274 -0
  37. package/scripts/forge_jev/client.py +13 -9
  38. package/ui/docs/api.md +51 -8
  39. package/ui/forge_ui/export.py +6 -2
  40. package/ui/forge_ui/reader.py +172 -6
  41. package/ui/forge_ui/static/app.js +2 -2
  42. package/ui/forge_ui/static/checksview.js +20 -7
  43. package/ui/forge_ui/static/controls.js +6 -3
  44. package/ui/forge_ui/static/panel.js +69 -4
  45. package/ui/forge_ui/static/runmodel.js +30 -4
  46. package/ui/forge_ui/static/scene3d.js +3 -2
  47. package/ui/forge_ui/static/style.css +11 -4
@@ -12,8 +12,8 @@ bias (inverse-propensity weighting needs the probability each choice had).
12
12
  exactly two: SPEC and its neighbour, the model one tier away in the user's own pools
13
13
  (the next cheaper tier for medium and high, the next stronger for low). With
14
14
  probability 1-E it keeps SPEC; with probability E it picks uniformly between the two.
15
- Prints the spec to use. Appends the decision to <plan>/tasks/<id>/route.jsonl (never
16
- rewritten) and marks a changed pick in tasks/<id>/route.explored for the table. A row
15
+ Prints the spec to use. Appends the decision, with the tier of its choice, to
16
+ <plan>/tasks/<id>/route.jsonl (never rewritten) and marks a changed pick in tasks/<id>/route.explored for the table. A row
17
17
  with no neighbour is not explored and records nothing.
18
18
 
19
19
  forge-route.py escalation --plan P --task ID [--check] [--qa-only-next yes|no]
@@ -26,6 +26,7 @@ bias (inverse-propensity weighting needs the probability each choice had).
26
26
  that names no effort counts as medium, a dwarf dispatch's default) before that stop.
27
27
  The streak then counts per effort, so the new effort starts again. At the pairing's
28
28
  highest effort the task still stops, and split.suggested says that effort was tried too.
29
+ A lateral move recorded in tasks/<id>/lateral.tsv does not end the count (see failed_streak).
29
30
  With the file absent the streak and the stop are exactly as before. `--check` (run after
30
31
  every attempt) also records a due escalation in escalation.next, and clears the markers
31
32
  once the streak no longer holds. A pending tasks/<id>/escalation.pin (a human's one-shot
@@ -39,14 +40,37 @@ bias (inverse-propensity weighting needs the probability each choice had).
39
40
  re-read escalate_after inside it: a policy decision made before a human switched the
40
41
  policy off writes nothing.
41
42
 
43
+ forge-route.py fallback --plan P --task ID [--exclude harness/model,...]
44
+ The lateral move of an infrastructure stop: prints the next free model of the pool of the
45
+ tier the task runs in (its difficulty, the tier its exploration picked, or the target its last
46
+ escalation recorded in running.tier), or exits 1 when there is none. Never a model of another tier.
47
+ The move is recorded by `lateral` below, not as an escalation.
48
+
49
+ forge-route.py qa-fallback --plan P --task ID [--exclude harness/model,...]
50
+ The lateral move of a review stopped on infrastructure: prints the peer reviewer from
51
+ plan/qa-routing.json (the --qa, --qa-low, --qa-medium and --qa-high pools `plan` was given): the
52
+ next member of the task's difficulty pool and then of `any`, never the stopped reviewer's model nor
53
+ the implementer's (a task is not reviewed by the model that wrote it), or exits 1 when there is none.
54
+ A plan with no qa-routing.json, or a reviewer no pool lists, has no peer.
55
+
42
56
  forge-route.py record --plan P --task ID (--probe | --line TEXT)
43
57
  Internal. Probe or append tasks/<id>/escalations.tsv through forge-control.py, which
44
58
  walks from the plan one directory at a time and refuses a symlink at any component.
59
+ An appended row also writes tasks/<id>/running.tier: its target tier and spec.
45
60
  `--probe` exits 0 when every component below the plan is a real directory and the file
46
61
  is absent or a regular file. `--line` appends one record under those same conditions.
47
62
  A missing parent exits 1 and writes nothing: the walk has no directory descriptor then,
48
63
  and opening the leaf would create it in the process's current directory.
49
64
 
65
+ forge-route.py lateral --plan P --task ID (--probe | --line TEXT)
66
+ Internal. The same probe and append, for tasks/<id>/lateral.tsv: the record of a dwarf
67
+ lateral move (epoch, attempt, role, from, to, cause). Its appended row writes running.tier
68
+ too: a move keeps the tier, and the spec it moved to is the one that tier is recorded for.
69
+
70
+ forge-route.py attempt-cap --plan P --task ID
71
+ Prints "<used> <cap>": the attempts a task has spent and its attempt cap (#69), or "-" for
72
+ no cap. Used by the shell and the scheduler, and by `forge control show`. See attempt_cap.
73
+
50
74
  The propensity of the chosen spec is (1-E)*[chosen == SPEC] + E/2. Forge never picks a
51
75
  model the user did not name: both helpers read only the pools `plan` stored in
52
76
  fractal-routing.json, and "stronger" means only "in a higher tier of those pools" --
@@ -64,6 +88,7 @@ import hashlib
64
88
  import json
65
89
  import os
66
90
  import random
91
+ import re
67
92
  import secrets
68
93
  import stat
69
94
  import subprocess
@@ -76,8 +101,9 @@ TIERS = ('low', 'medium', 'high')
76
101
  SCRIPTS = Path(__file__).resolve().parent
77
102
  REGISTRY = SCRIPTS.parent / 'registry.tsv'
78
103
  FAILED = ('FAIL', 'TIMEOUT', 'BOUNCED', 'INCOMPLETE') # a judgment against the spec that ran
79
- NEUTRAL = ('INFRA', 'UNKNOWN', 'ERROR', 'RUNNING', 'INTERRUPTED', 'NEEDS_INPUT') # say nothing about it
104
+ NEUTRAL = ('INFRA', 'UNKNOWN', 'ERROR', 'RUNNING', 'INTERRUPTED', 'NEEDS_INPUT', 'NEEDS_DECISION') # say nothing about it
80
105
  DEFAULT_ESCALATE_AFTER = 3
106
+ DEFAULT_MAX_ATTEMPTS = 8 # `plan --max-attempts`; a plan without the file
81
107
  DEFAULT_EFFORT = 'medium' # forge-dispatch.sh dwarf default
82
108
  LOCK_WAIT = 5.0 # seconds to wait for P/control.lock
83
109
  # forge-dispatch.sh rank_of. Only for "which accepted effort is above this one"; the set of
@@ -111,8 +137,10 @@ def row_inputs(plan: Path, task: str) -> str:
111
137
 
112
138
  # --- the user's ladder -------------------------------------------------------------
113
139
 
114
- def registry_models(path: Path = REGISTRY) -> dict:
115
- """{alias: {harness: model id}} from registry.tsv; the first row of an alias is its default."""
140
+ def registry_models(path=None) -> dict:
141
+ """{alias: {harness: model id}} from registry.tsv (or FORGE_REGISTRY, as dispatch and the scheduler read
142
+ it); the first row of an alias is its default."""
143
+ path = Path(path or os.environ.get('FORGE_REGISTRY') or REGISTRY)
116
144
  out = {}
117
145
  try:
118
146
  lines = path.read_text().splitlines()
@@ -140,6 +168,19 @@ def canonical(spec: str, registry: dict) -> str:
140
168
  return next(iter(rows.values()))
141
169
 
142
170
 
171
+ def model_key(spec: str, registry: dict) -> str:
172
+ """The model a spec runs, named so that one model reached through two harnesses compares equal
173
+ (`gpt-6.1-sol` on codex and `github-copilot/gpt-6.1-sol` on opencode): the id it resolves to, without
174
+ its provider prefix and with dots and dashes alike. Two ids are compared, never two aliases, since
175
+ one alias may list different models on different harnesses (`gemini` is Flash on antigravity and
176
+ Pro on opencode)."""
177
+ return canonical(spec, registry).rsplit('/', 1)[-1].lower().replace('.', '-')
178
+
179
+
180
+ def same_model(a: str, b: str, registry: dict) -> bool:
181
+ return model_key(a, registry) == model_key(b, registry)
182
+
183
+
143
184
  def arm(spec: str, registry: dict) -> tuple:
144
185
  """What exploration compares on: the model and the effort as written.
145
186
 
@@ -195,17 +236,18 @@ def _aligned(spec: str, pool_of_spec: list, other: list, key):
195
236
 
196
237
 
197
238
  def neighbour(spec: str, tier: str, pools: dict, registry: dict):
198
- """The exploration alternative: the nearest cheaper tier for medium/high, the nearest stronger for low."""
239
+ """The exploration alternative and its tier: the nearest cheaper tier for medium/high, the nearest
240
+ stronger for low. (None, None) when there is none."""
199
241
  if tier not in TIERS:
200
- return None
242
+ return None, None
201
243
  i = TIERS.index(tier)
202
244
  order = TIERS[i + 1:] if i == 0 else tuple(reversed(TIERS[:i]))
203
245
  for other in order:
204
246
  if pools.get(other):
205
247
  pick = _aligned(spec, pools.get(tier) or [spec], pools[other], lambda s: arm(s, registry))
206
248
  if pick:
207
- return pick
208
- return None
249
+ return pick, other
250
+ return None, None
209
251
 
210
252
 
211
253
  def stronger(spec: str, pools: dict, registry: dict):
@@ -245,20 +287,23 @@ def parse_excluded(text: str) -> set:
245
287
  return out
246
288
 
247
289
 
248
- def fallback_pick(current: str, pools: dict, registry: dict, excluded: set):
249
- """The next member of the current dwarf's own tier pool, in pool order and wrapping around,
250
- that runs another model on a pair nobody paused; None when there is none."""
251
- rank = rank_of(current, pools, registry)
252
- if rank is None:
253
- return None
254
- pool = pools[TIERS[rank]]
290
+ def fallback_pick(current: str, pools: dict, registry: dict, excluded: set, tier: str, reviewer: str = None):
291
+ """The next member of the pool of `tier`, the tier the task runs in (running_tier), in pool
292
+ order and wrapping around, that runs another model on a pair nobody paused, and not the task's
293
+ reviewer's model: a task is never reviewed by the model that wrote it. None when there is none,
294
+ or when that pool does not run the current model (a model the user named by hand)."""
295
+ pool = pools.get(tier) or []
255
296
  own = canonical(current, registry)
256
297
  keys = [canonical(s, registry) for s in pool]
257
- start = keys.index(own) if own in keys else -1
298
+ if own not in keys:
299
+ return None
300
+ judge = reviewer if reviewer and reviewer not in ('-', 'UNASSIGNED') else None
301
+ start = keys.index(own)
258
302
  for step in range(1, len(pool) + 1):
259
303
  candidate = pool[(start + step) % len(pool)]
260
304
  pair = pair_of(candidate, registry)
261
- if canonical(candidate, registry) == own or pair is None:
305
+ # The reviewer's model on any harness (sol on opencode is codex's sol), as qa_fallback_pick compares.
306
+ if canonical(candidate, registry) == own or (judge and same_model(candidate, judge, registry)) or pair is None:
262
307
  continue
263
308
  if pair in excluded or (pair[0], '*') in excluded:
264
309
  continue
@@ -266,13 +311,120 @@ def fallback_pick(current: str, pools: dict, registry: dict, excluded: set):
266
311
  return None
267
312
 
268
313
 
314
+ def load_qa_pools(path) -> dict:
315
+ """{'any'|'low'|'medium'|'high': [spec, ...]} from plan/qa-routing.json, the reviewer pools `plan` was
316
+ given. Empty for a plan made before the file existed."""
317
+ try:
318
+ data = json.loads(Path(path).read_text())
319
+ except (OSError, ValueError):
320
+ return {}
321
+ out = {}
322
+ for key in ('any',) + TIERS:
323
+ specs = data.get(key) if isinstance(data, dict) else None
324
+ if isinstance(specs, list):
325
+ specs = [str(s).strip() for s in specs if str(s).strip()]
326
+ if specs:
327
+ out[key] = specs
328
+ return out
329
+
330
+
331
+ def qa_fallback_pick(current: str, implementer: str, pools: dict, registry: dict, excluded: set, difficulty: str):
332
+ """The peer reviewer of a review stopped on infrastructure: the next member, in pool order and
333
+ wrapping around, of the task's difficulty pool and then of `any`, that runs another model than the
334
+ stopped reviewer and than the implementer, on a pair nobody paused. A reviewer that no such pool
335
+ lists (named by hand) has no peer, since its strength is unknown. None when there is none."""
336
+ order = [pools.get(key) or [] for key in (difficulty, 'any') if key in TIERS or key == 'any']
337
+ own = canonical(current, registry)
338
+ if not any(canonical(s, registry) == own for pool in order for s in pool):
339
+ return None
340
+ wrote = implementer if implementer not in ('', '-', 'UNASSIGNED') else None
341
+ for pool in order:
342
+ keys = [canonical(s, registry) for s in pool]
343
+ start = keys.index(own) if own in keys else -1
344
+ for step in range(1, len(pool) + 1):
345
+ candidate = pool[(start + step) % len(pool)]
346
+ model, pair = canonical(candidate, registry), pair_of(candidate, registry)
347
+ if model == own or (wrote and same_model(candidate, wrote, registry)) or pair is None:
348
+ continue
349
+ if pair in excluded or (pair[0], '*') in excluded:
350
+ continue
351
+ return candidate
352
+ return None
353
+
354
+
355
+ def escalation_target(source: str, frm: str, to: str, running: str, pools: dict, registry: dict) -> str:
356
+ """The tier an escalations.tsv row moved the task to. The same model at another effort stays.
357
+ The policy (stronger) went to the first pool with its target above the highest pool of `frm`;
358
+ a person named a model, which is in the nearest pool to the tier the task was running in."""
359
+ model = canonical(to, registry)
360
+ if model == canonical(frm, registry):
361
+ return running
362
+ rank = rank_of(frm, pools, registry) if source == 'policy' else None
363
+ first = rank + 1 if rank is not None else TIERS.index(running)
364
+ for tier in TIERS[first:] + tuple(reversed(TIERS[:first])):
365
+ if any(canonical(s, registry) == model for s in pools.get(tier, ())):
366
+ return tier
367
+ return running
368
+
369
+
370
+ def running_tier(plan: Path, task: str, current: str = '') -> str:
371
+ """The tier a task runs in, from what forge recorded when it assigned the model, never from which
372
+ pools list the model: one model can sit in several, and a re-plan can change them. While the task
373
+ runs the spec of a record, the tier in tasks/<id>/running.tier (written with each escalations.tsv
374
+ row), else the tier its exploration picked; with neither, as in an older plan, the difficulty.
375
+ `current` is the spec the task runs, read from tasks.tsv when not given. '' when the difficulty
376
+ is no tier."""
377
+ tier = _row_cell(plan, task, 2)
378
+ if tier not in TIERS:
379
+ return ''
380
+ tdir = plan / 'tasks' / task
381
+ current = current or _dwarf_of(plan, task)
382
+ with contextlib.suppress(OSError):
383
+ recorded, _, spec = (tdir / 'running.tier').read_text().strip().partition('\t')
384
+ if spec == current and recorded in TIERS:
385
+ return recorded
386
+ with contextlib.suppress(OSError, ValueError, AttributeError): # no usable record: the difficulty
387
+ lines = (tdir / 'route.jsonl').read_text().splitlines()
388
+ decision = json.loads(lines[-1]) if lines else {}
389
+ if decision.get('chosen') == current and decision.get('chosen_tier') in TIERS:
390
+ return decision['chosen_tier']
391
+ return tier
392
+
393
+
394
+ def record_running_tier(plan: str, task: str, row: str, control) -> None:
395
+ """tasks/<id>/running.tier for an escalations.tsv row: `tier<TAB>spec`, the tier the row moved the
396
+ task to, decided here with the pools of this moment. A fallback stays in its tier."""
397
+ cells = row.rstrip('\n').split('\t')
398
+ frm, to, source = cells[2], cells[3], cells[4] if len(cells) > 4 else 'policy'
399
+ tier = running_tier(Path(plan), task, frm)
400
+ if tier and source != 'fallback':
401
+ tier = escalation_target(source, frm, to, tier, load_pools(Path(plan) / 'fractal-routing.json'),
402
+ registry_models())
403
+ if tier:
404
+ control.write_atomic(plan, 'tasks/%s/running.tier' % task, '%s\t%s\n' % (tier, to))
405
+
406
+
269
407
  def fallback(args) -> int:
270
408
  plan = Path(os.path.realpath(args.plan))
271
409
  current = _dwarf_of(plan, args.task)
272
410
  if not current or current in ('-', 'UNASSIGNED'):
273
411
  return 1
274
412
  pick = fallback_pick(current, load_pools(plan / 'fractal-routing.json'), registry_models(),
275
- parse_excluded(args.exclude))
413
+ parse_excluded(args.exclude), running_tier(plan, args.task, current),
414
+ _row_cell(plan, args.task, 5))
415
+ if not pick:
416
+ return 1
417
+ print(pick)
418
+ return 0
419
+
420
+
421
+ def qa_fallback(args) -> int:
422
+ plan = Path(os.path.realpath(args.plan))
423
+ current, implementer = _row_cell(plan, args.task, 5), _dwarf_of(plan, args.task)
424
+ if not current or current in ('-', 'UNASSIGNED'):
425
+ return 1
426
+ pick = qa_fallback_pick(current, implementer, load_qa_pools(plan / 'qa-routing.json'), registry_models(),
427
+ parse_excluded(args.exclude), _row_cell(plan, args.task, 2))
276
428
  if not pick:
277
429
  return 1
278
430
  print(pick)
@@ -285,7 +437,7 @@ def explore(args) -> str:
285
437
  epsilon = float(args.epsilon)
286
438
  if not 0 < epsilon <= 1:
287
439
  return args.default
288
- alternative = neighbour(args.default, args.tier, load_pools(args.pools), registry_models())
440
+ alternative, alternative_tier = neighbour(args.default, args.tier, load_pools(args.pools), registry_models())
289
441
  if not alternative:
290
442
  return args.default
291
443
  candidates = [args.default, alternative]
@@ -298,6 +450,7 @@ def explore(args) -> str:
298
450
  tdir.mkdir(parents=True, exist_ok=True)
299
451
  decision = dict(at=time.time(), task=args.task, tier=args.tier, epsilon=epsilon, candidates=candidates,
300
452
  default=args.default, chosen=chosen, explored=chosen != args.default,
453
+ chosen_tier=alternative_tier if chosen != args.default else args.tier,
301
454
  propensity=round(propensity, 6), inputs=row_inputs(plan, args.task))
302
455
  decision['decision'] = hashlib.sha256(json.dumps(decision, sort_keys=True).encode()).hexdigest()[:16]
303
456
  with open(tdir / 'route.jsonl', 'a') as log: # one line per resolution, never rewritten
@@ -312,6 +465,14 @@ def explore(args) -> str:
312
465
 
313
466
  # --- escalation --------------------------------------------------------------------
314
467
 
468
+ def _row_cell(plan: Path, task: str, index: int) -> str:
469
+ for line in (plan / 'tasks.tsv').read_text().splitlines():
470
+ cells = line.split('\t')
471
+ if not line.startswith('#') and cells and cells[0] == task and len(cells) > index:
472
+ return cells[index]
473
+ return ''
474
+
475
+
315
476
  def _dwarf_of(plan: Path, task: str) -> str:
316
477
  for line in (plan / 'tasks.tsv').read_text().splitlines():
317
478
  cells = line.split('\t')
@@ -381,32 +542,56 @@ def _next_effort_spec(spec: str):
381
542
  return None
382
543
 
383
544
 
384
- def failed_streak(rows: list, current: str, registry: dict, by_effort: bool = False) -> int:
545
+ def failed_streak(rows: list, current: str, registry: dict, by_effort: bool = False, laterals=()) -> int:
385
546
  """Distinct trailing attempt numbers that failed on `current`'s model.
386
547
 
387
548
  rows: (attempt, status, spec-or-None) oldest first. A row without a spec predates the
388
549
  column and is taken as the current spec. Infra stops, missing verdicts and forge errors
389
550
  judge nothing and are skipped; a pass, a merge or another model ends the streak.
551
+ laterals: (attempt, from, to) of each dwarf move in lateral.tsv. A model change between
552
+ two counted attempts does not end the streak when dwarf moves recorded between them take
553
+ the earlier attempt's spec to the later one's, through any chain of moves made in order
554
+ (see _moved_between): a lateral move is an infrastructure stop, not a judgment that the
555
+ model was too weak.
390
556
  With by_effort, another effort of the same model ends it too (a bump starts a new
391
557
  streak). A spec that names no effort counts as medium. With by_effort off the count
392
558
  is by model only, as before.
393
559
  """
394
- model = canonical(current, registry)
395
560
  effort = _effort_of(current) if by_effort else None
396
561
  seen = set()
562
+ expect, later = current, None # the spec the last counted attempt ran (current to start), and its number
397
563
  for attempt, status, spec in reversed(rows):
398
564
  if status in NEUTRAL:
399
565
  continue
400
- if spec and canonical(spec, registry) != model:
401
- break
566
+ if spec and canonical(spec, registry) != canonical(expect, registry):
567
+ if later is None or not _moved_between(laterals, spec, expect, attempt, later):
568
+ break
402
569
  if effort is not None and _effort_of(spec or current) != effort:
403
570
  break
404
571
  if status not in FAILED:
405
572
  break
406
573
  seen.add(attempt)
574
+ expect, later = spec or expect, attempt
407
575
  return len(seen)
408
576
 
409
577
 
578
+ def _moved_between(laterals, frm: str, to: str, earlier: int, later: int) -> bool:
579
+ """Whether dwarf moves took `frm` to `to` between two attempts: after attempt `earlier` was spent and
580
+ before attempt `later` began. A move records the attempts spent at that moment (an infrastructure stop
581
+ refunds its own), so a move straight after `earlier` is recorded as `earlier`. One stop can make several
582
+ moves (sol -> astra -> sonnet) with no attempt on the middle model, so the moves in the window must chain
583
+ in the order they were made: each one starts where the last ended. A move that starts elsewhere means
584
+ the model changed in between by something no lateral row records (an explicit retry), and the window
585
+ does not carry across it."""
586
+ model = frm
587
+ for n, f, t in laterals:
588
+ if earlier <= n < later:
589
+ if f != model:
590
+ return False
591
+ model = t
592
+ return model == to
593
+
594
+
410
595
  def attempt_rows(tdir: Path) -> list:
411
596
  rows = []
412
597
  try:
@@ -420,6 +605,31 @@ def attempt_rows(tdir: Path) -> list:
420
605
  return rows
421
606
 
422
607
 
608
+ def decided_attempt(tdir: Path) -> int:
609
+ """The attempt number of the latest row of tasks/<id>/decisions.tsv (epoch, attempt, choice, reason);
610
+ 0 when the task has no decision. The attempts counted against a model start after it."""
611
+ try:
612
+ lines = (tdir / 'decisions.tsv').read_text().splitlines()
613
+ except OSError:
614
+ return 0
615
+ return max([int(cells[1]) for cells in (line.split('\t') for line in lines)
616
+ if len(cells) > 1 and cells[1].isdigit()] or [0])
617
+
618
+
619
+ def lateral_rows(tdir: Path) -> list:
620
+ """(attempt, from, to) of each dwarf move in tasks/<id>/lateral.tsv, oldest first."""
621
+ rows = []
622
+ try:
623
+ lines = (tdir / 'lateral.tsv').read_text().splitlines()
624
+ except OSError:
625
+ return rows
626
+ for line in lines:
627
+ cells = line.split('\t')
628
+ if len(cells) >= 5 and cells[1].isdigit() and cells[2] == 'dwarf':
629
+ rows.append((int(cells[1]), cells[3], cells[4]))
630
+ return rows
631
+
632
+
423
633
  def _setting(plan: Path) -> int:
424
634
  try:
425
635
  value = (plan / 'escalate_after').read_text().strip()
@@ -435,6 +645,68 @@ def _fractal(plan: Path) -> bool:
435
645
  return False
436
646
 
437
647
 
648
+ # --- attempt cap (#69) -------------------------------------------------------------
649
+ # A task that keeps failing across runs stops for a person. The count and the cap live here, so
650
+ # the shell (do_task, the retry gate, the run summary), the scheduler and `forge control show`
651
+ # all read the same numbers.
652
+
653
+ def max_attempts_setting(plan: Path) -> int:
654
+ """The plan's attempt cap (`plan --max-attempts N`, `forge control set max-attempts`): the file's
655
+ number, DEFAULT_MAX_ATTEMPTS without the file, and 0 for no cap. An unreadable value is the default."""
656
+ try:
657
+ value = (plan / 'max_attempts').read_text().strip()
658
+ except OSError:
659
+ return DEFAULT_MAX_ATTEMPTS
660
+ return int(value) if re.fullmatch(r'[0-9]{1,9}', value) else DEFAULT_MAX_ATTEMPTS
661
+
662
+
663
+ def attempts_spent(tdir: Path) -> int:
664
+ """Attempts the task has used: the attempts.tsv rows whose status is not INFRA. An infrastructure stop
665
+ spends none. A QA-only resume re-reviews the same attempt number and writes a row of its own, and that
666
+ row spends one too: a task whose reviews return no verdict reaches its cap like any other."""
667
+ return sum(1 for _number, status, _spec in attempt_rows(tdir) if status != 'INFRA')
668
+
669
+
670
+ def granted_attempts(tdir: Path) -> int:
671
+ """The attempts a person granted: N of every retry=N row in tasks/<id>/decisions.tsv. The retry CLI takes
672
+ up to three digits, zero-padded ones too (retry=002), so the grant is read the same way."""
673
+ total = 0
674
+ try:
675
+ lines = (tdir / 'decisions.tsv').read_text().splitlines()
676
+ except OSError:
677
+ return total
678
+ for line in lines:
679
+ cells = line.split('\t')
680
+ if len(cells) > 2:
681
+ match = re.fullmatch(r'retry=([0-9]{1,3})', cells[2])
682
+ if match:
683
+ total += int(match.group(1))
684
+ return total
685
+
686
+
687
+ def attempt_cap(plan: Path, task: str) -> tuple:
688
+ """(attempts used, cap). The cap is max_attempts plus granted_attempts, and None when the plan has no
689
+ cap (max_attempts 0): a decision adds attempts to a cap, it does not make one."""
690
+ tdir = plan / 'tasks' / task
691
+ used = attempts_spent(tdir)
692
+ limit = max_attempts_setting(plan)
693
+ if limit == 0:
694
+ return used, None
695
+ return used, limit + granted_attempts(tdir)
696
+
697
+
698
+ def attempt_cap_cmd(args) -> int:
699
+ """`attempt-cap`: "<used> <cap>" on one line, cap "-" for no cap. Read only; a bad task id counts as
700
+ no attempts, which the callers never pass."""
701
+ plan = Path(os.path.realpath(args.plan))
702
+ if not args.task or args.task in ('.', '..') or '/' in args.task or '\0' in args.task:
703
+ print('0 -')
704
+ return 0
705
+ used, cap = attempt_cap(plan, args.task)
706
+ print('%d %s' % (used, '-' if cap is None else cap))
707
+ return 0
708
+
709
+
438
710
  # --- live-control files ------------------------------------------------------------
439
711
  # Markers are shared with `forge control` and the scheduler, so they are written the way
440
712
  # every writer of the plan's control files writes: a task id the scheduler would accept, a
@@ -577,7 +849,10 @@ def _decide(plan: Path, tdir: Path, args, after: int):
577
849
  return (), (), '', 0
578
850
  registry = registry_models()
579
851
  step = _effort_step(plan)
580
- streak = failed_streak(attempt_rows(tdir), current, registry, by_effort=step)
852
+ # A person's decision (decisions.tsv) restarts the count: only attempts after it can fail the model.
853
+ decided = decided_attempt(tdir)
854
+ rows = [row for row in attempt_rows(tdir) if row[0] > decided]
855
+ streak = failed_streak(rows, current, registry, by_effort=step, laterals=lateral_rows(tdir))
581
856
  if streak < after:
582
857
  return MARKERS, (), '', 0
583
858
  target, why = stronger(current, load_pools(plan / 'fractal-routing.json'), registry)
@@ -639,20 +914,22 @@ def _load_control():
639
914
  return module
640
915
 
641
916
 
642
- def record_escalation(args) -> int:
643
- """Probe or append tasks/<id>/escalations.tsv. 0 when that is safe; 1 when it is not.
917
+ def _record(args, name: str, after=None) -> int:
918
+ """Probe or append tasks/<id>/<name>. 0 when that is safe; 1 when it is not.
644
919
 
645
920
  A missing parent is a refusal on both paths. probe() reports that as the file being
646
921
  absent, so the check has to look at the walk itself. append_line refuses the same case
647
922
  before it opens the leaf: with no directory descriptor that open would use the process
648
923
  cwd, including when the task directory disappears between this check and the append.
924
+ `after(plan, task, line, control)` runs once the line is appended; its failure is printed,
925
+ not returned, because the row stands.
649
926
  """
650
927
  if not args.task or args.task in ('.', '..') or '/' in args.task or '\0' in args.task:
651
928
  return 1
652
929
  try:
653
930
  control = _load_control()
654
931
  plan = os.path.realpath(args.plan)
655
- rel = 'tasks/%s/escalations.tsv' % args.task
932
+ rel = 'tasks/%s/%s' % (args.task, name)
656
933
  parent, _leaf = control._open_parent(plan, rel)
657
934
  if parent is None:
658
935
  return 1
@@ -662,11 +939,38 @@ def record_escalation(args) -> int:
662
939
  else:
663
940
  line = args.line if args.line.endswith('\n') else args.line + '\n'
664
941
  control.append_line(plan, rel, line)
942
+ if after:
943
+ try:
944
+ after(plan, args.task, line, control)
945
+ except Exception as error: # the row stands; without this record the task reads as its difficulty
946
+ print('%s: could not record the tier it runs in: %s' % (args.task, error), file=sys.stderr)
665
947
  except Exception:
666
948
  return 1
667
949
  return 0
668
950
 
669
951
 
952
+ def record_escalation(args) -> int:
953
+ """Probe or append tasks/<id>/escalations.tsv, and the tier the row moved the task to."""
954
+ return _record(args, 'escalations.tsv', record_running_tier)
955
+
956
+
957
+ def record_lateral(args) -> int:
958
+ """Probe or append tasks/<id>/lateral.tsv, and the tier the move keeps (record_lateral_tier)."""
959
+ return _record(args, 'lateral.tsv', record_lateral_tier)
960
+
961
+
962
+ def record_lateral_tier(plan: str, task: str, row: str, control) -> None:
963
+ """tasks/<id>/running.tier after a lateral move: the tier the task ran in, now recorded for the spec
964
+ it moved to. Without this a task moved sideways from a recorded spec would read as its difficulty again."""
965
+ cells = row.rstrip('\n').split('\t')
966
+ if cells[2] != 'dwarf': # a reviewer's move says nothing about the implementer's tier
967
+ return
968
+ frm, to = cells[3], cells[4]
969
+ tier = running_tier(Path(plan), task, frm)
970
+ if tier:
971
+ control.write_atomic(plan, 'tasks/%s/running.tier' % task, '%s\t%s\n' % (tier, to))
972
+
973
+
670
974
  def main(argv=None) -> int:
671
975
  ap = argparse.ArgumentParser(prog='forge-route.py')
672
976
  sub = ap.add_subparsers(dest='command', required=True)
@@ -679,16 +983,24 @@ def main(argv=None) -> int:
679
983
  p.add_argument('--check', action='store_true')
680
984
  p.add_argument('--qa-only-next', choices=('yes', 'no'), default=None,
681
985
  help='whether the next entry only re-runs QA, as the caller measured it')
986
+ p = sub.add_parser('attempt-cap', help='the attempts a task has used and its cap, "<used> <cap>" (- for none)')
987
+ p.add_argument('--plan', required=True)
988
+ p.add_argument('--task', required=True)
682
989
  p = sub.add_parser('fallback', help='the same-tier model a capacity stop moves to')
683
990
  p.add_argument('--plan', required=True)
684
991
  p.add_argument('--task', required=True)
685
992
  p.add_argument('--exclude', default='', help='harness/model pairs to skip, comma-separated (harness/* for all)')
686
- p = sub.add_parser('record', help=argparse.SUPPRESS)
993
+ p = sub.add_parser('qa-fallback', help='the peer reviewer a review stopped on infrastructure moves to')
687
994
  p.add_argument('--plan', required=True)
688
995
  p.add_argument('--task', required=True)
689
- mode = p.add_mutually_exclusive_group(required=True)
690
- mode.add_argument('--probe', action='store_true')
691
- mode.add_argument('--line')
996
+ p.add_argument('--exclude', default='', help='harness/model pairs to skip, comma-separated (harness/* for all)')
997
+ for name in ('record', 'lateral'):
998
+ p = sub.add_parser(name, help=argparse.SUPPRESS)
999
+ p.add_argument('--plan', required=True)
1000
+ p.add_argument('--task', required=True)
1001
+ mode = p.add_mutually_exclusive_group(required=True)
1002
+ mode.add_argument('--probe', action='store_true')
1003
+ mode.add_argument('--line')
692
1004
  args = ap.parse_args(argv)
693
1005
  if args.command == 'explore':
694
1006
  try:
@@ -698,9 +1010,13 @@ def main(argv=None) -> int:
698
1010
  return 0
699
1011
  if args.command == 'record':
700
1012
  return record_escalation(args)
701
- if args.command == 'fallback':
1013
+ if args.command == 'lateral':
1014
+ return record_lateral(args)
1015
+ if args.command == 'attempt-cap':
1016
+ return attempt_cap_cmd(args)
1017
+ if args.command in ('fallback', 'qa-fallback'):
702
1018
  try:
703
- return fallback(args)
1019
+ return (fallback if args.command == 'fallback' else qa_fallback)(args)
704
1020
  except Exception:
705
1021
  return 1
706
1022
  try:
@@ -11,6 +11,10 @@ forge-ui and never writes anything.
11
11
  `forge runs rm <run-dir> [--dry-run] [--yes] [--no-archive] [--worktrees] [--branches] [--json]`
12
12
  is the one thing here that changes anything: it deletes a run, after its traces are in the dataset
13
13
  and an archive exists (scripts/forge-runs-rm.py).
14
+
15
+ `forge runs rerun <run-dir> --dwarf SPEC` and `forge runs compare <run-dir-A> <run-dir-B>` (scripts/forge-compare.py)
16
+ run a plan again under another implementer, from the same starting commit and never merging, and set two runs
17
+ side by side per task. Starting the rerun spends tokens, so it takes `--run --yes` after it has shown the forecast.
14
18
  """
15
19
  from __future__ import annotations
16
20
 
@@ -100,12 +104,25 @@ def remove(argv) -> int:
100
104
  return module.main(argv)
101
105
 
102
106
 
107
+ def compare_runs(argv) -> int:
108
+ """`forge runs rerun` and `forge runs compare`: loaded on demand, like rm."""
109
+ import importlib.util
110
+ spec = importlib.util.spec_from_file_location('forge_compare', Path(__file__).resolve().with_name('forge-compare.py'))
111
+ module = importlib.util.module_from_spec(spec)
112
+ sys.modules['forge_compare'] = module
113
+ spec.loader.exec_module(module)
114
+ return module.main(argv)
115
+
116
+
103
117
  def main(argv=None) -> int:
104
118
  argv = sys.argv[1:] if argv is None else list(argv)
105
119
  if argv[:1] == ['rm']:
106
120
  return remove(argv[1:])
121
+ if argv[:1] in (['rerun'], ['compare']):
122
+ return compare_runs(argv)
107
123
  parser = argparse.ArgumentParser(prog='forge runs', description="This repo's recent forge runs, newest first. Listing is read-only.",
108
- epilog='Delete a run, keeping its traces: forge runs rm <run-dir> (forge runs rm --help)')
124
+ epilog='Delete a run, keeping its traces: forge runs rm <run-dir> (forge runs rm --help). Rerun a plan with another '
125
+ 'implementer and compare: forge runs rerun --help, forge runs compare --help')
109
126
  which = parser.add_mutually_exclusive_group()
110
127
  which.add_argument('--repo', type=Path, metavar='DIR', help='the repo whose runs to list (default: the Git top level of the current directory)')
111
128
  which.add_argument('--all', action='store_true', help='list the runs of every repo')