@giamme/forge 0.13.1 → 0.14.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 (48) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/SKILL.md +17 -11
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +2 -0
  5. package/docs/commands.md +134 -8
  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 +201 -61
  13. package/references/harnesses.md +4 -1
  14. package/references/runtime.md +29 -0
  15. package/references/ui.md +10 -0
  16. package/scripts/forge-compare.py +491 -0
  17. package/scripts/forge-config.py +3 -3
  18. package/scripts/forge-contract.py +34 -8
  19. package/scripts/forge-control.py +105 -13
  20. package/scripts/forge-dispatch.sh +85 -25
  21. package/scripts/forge-jev-options.sh +17 -4
  22. package/scripts/forge-ledger.py +387 -0
  23. package/scripts/forge-lib-plans.sh +11 -2
  24. package/scripts/forge-lib-task.sh +390 -28
  25. package/scripts/forge-parallel-options.sh +20 -4
  26. package/scripts/forge-parallel.sh +123 -17
  27. package/scripts/forge-plan-check.py +68 -3
  28. package/scripts/forge-pr.py +276 -0
  29. package/scripts/forge-route.py +403 -38
  30. package/scripts/forge-runs.py +18 -1
  31. package/scripts/forge-runtime.py +94 -8
  32. package/scripts/forge-schedule.py +303 -46
  33. package/scripts/forge-verify-failed.py +111 -0
  34. package/scripts/forge-watch.py +372 -0
  35. package/scripts/forge_dataset/harvest.py +3 -1
  36. package/scripts/forge_fractal/cli.py +23 -6
  37. package/scripts/forge_infra.py +274 -0
  38. package/scripts/forge_jev/client.py +13 -9
  39. package/ui/docs/api.md +51 -8
  40. package/ui/forge_ui/export.py +6 -2
  41. package/ui/forge_ui/reader.py +172 -6
  42. package/ui/forge_ui/static/app.js +2 -2
  43. package/ui/forge_ui/static/checksview.js +20 -7
  44. package/ui/forge_ui/static/controls.js +6 -3
  45. package/ui/forge_ui/static/panel.js +69 -4
  46. package/ui/forge_ui/static/runmodel.js +30 -4
  47. package/ui/forge_ui/static/scene3d.js +3 -2
  48. package/ui/forge_ui/static/style.css +11 -4
@@ -12,10 +12,16 @@ 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
+ forge-route.py assign --plan P --task ID --tier T --default SPEC --pools FILE [--epsilon E]
20
+ Called by `plan` for each row it resolves (one the user left to forge): `explore` above when E is
21
+ above 0, then tasks/<id>/running.tier for the spec it prints, with the tier of that pick (T, or the
22
+ neighbour's tier an exploration chose). A re-plan that re-resolves a row thus replaces whatever an
23
+ older escalation or pin recorded (#106); a row whose dwarf the plan keeps is never assigned.
24
+
19
25
  forge-route.py escalation --plan P --task ID [--check] [--qa-only-next yes|no]
20
26
  The retry policy: after <plan>/escalate_after (default 3; 0 = off) failed attempts on
21
27
  one spec, the next attempt goes to the next tier up of the user's pools instead of
@@ -26,6 +32,7 @@ bias (inverse-propensity weighting needs the probability each choice had).
26
32
  that names no effort counts as medium, a dwarf dispatch's default) before that stop.
27
33
  The streak then counts per effort, so the new effort starts again. At the pairing's
28
34
  highest effort the task still stops, and split.suggested says that effort was tried too.
35
+ A lateral move recorded in tasks/<id>/lateral.tsv does not end the count (see failed_streak).
29
36
  With the file absent the streak and the stop are exactly as before. `--check` (run after
30
37
  every attempt) also records a due escalation in escalation.next, and clears the markers
31
38
  once the streak no longer holds. A pending tasks/<id>/escalation.pin (a human's one-shot
@@ -39,14 +46,37 @@ bias (inverse-propensity weighting needs the probability each choice had).
39
46
  re-read escalate_after inside it: a policy decision made before a human switched the
40
47
  policy off writes nothing.
41
48
 
49
+ forge-route.py fallback --plan P --task ID [--exclude harness/model,...]
50
+ The lateral move of an infrastructure stop: prints the next free model of the pool of the
51
+ tier the task runs in (the newest record of it: see running_tier), or exits 1 when there is none.
52
+ Never a model of another tier.
53
+ The move is recorded by `lateral` below, not as an escalation.
54
+
55
+ forge-route.py qa-fallback --plan P --task ID [--exclude harness/model,...]
56
+ The lateral move of a review stopped on infrastructure: prints the peer reviewer from
57
+ plan/qa-routing.json (the --qa, --qa-low, --qa-medium and --qa-high pools `plan` was given): the
58
+ next member of the task's difficulty pool and then of `any`, never the stopped reviewer's model nor
59
+ the implementer's (a task is not reviewed by the model that wrote it), or exits 1 when there is none.
60
+ A plan with no qa-routing.json, or a reviewer no pool lists, has no peer.
61
+
42
62
  forge-route.py record --plan P --task ID (--probe | --line TEXT)
43
63
  Internal. Probe or append tasks/<id>/escalations.tsv through forge-control.py, which
44
64
  walks from the plan one directory at a time and refuses a symlink at any component.
65
+ An appended row also writes tasks/<id>/running.tier: its target tier, spec and time.
45
66
  `--probe` exits 0 when every component below the plan is a real directory and the file
46
67
  is absent or a regular file. `--line` appends one record under those same conditions.
47
68
  A missing parent exits 1 and writes nothing: the walk has no directory descriptor then,
48
69
  and opening the leaf would create it in the process's current directory.
49
70
 
71
+ forge-route.py lateral --plan P --task ID (--probe | --line TEXT)
72
+ Internal. The same probe and append, for tasks/<id>/lateral.tsv: the record of a dwarf
73
+ lateral move (epoch, attempt, role, from, to, cause). Its appended row writes running.tier
74
+ too: a move keeps the tier, and the spec it moved to is the one that tier is recorded for.
75
+
76
+ forge-route.py attempt-cap --plan P --task ID
77
+ Prints "<used> <cap>": the attempts a task has spent and its attempt cap (#69), or "-" for
78
+ no cap. Used by the shell and the scheduler, and by `forge control show`. See attempt_cap.
79
+
50
80
  The propensity of the chosen spec is (1-E)*[chosen == SPEC] + E/2. Forge never picks a
51
81
  model the user did not name: both helpers read only the pools `plan` stored in
52
82
  fractal-routing.json, and "stronger" means only "in a higher tier of those pools" --
@@ -64,6 +94,7 @@ import hashlib
64
94
  import json
65
95
  import os
66
96
  import random
97
+ import re
67
98
  import secrets
68
99
  import stat
69
100
  import subprocess
@@ -76,8 +107,9 @@ TIERS = ('low', 'medium', 'high')
76
107
  SCRIPTS = Path(__file__).resolve().parent
77
108
  REGISTRY = SCRIPTS.parent / 'registry.tsv'
78
109
  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
110
+ NEUTRAL = ('INFRA', 'UNKNOWN', 'ERROR', 'RUNNING', 'INTERRUPTED', 'NEEDS_INPUT', 'NEEDS_DECISION') # say nothing about it
80
111
  DEFAULT_ESCALATE_AFTER = 3
112
+ DEFAULT_MAX_ATTEMPTS = 8 # `plan --max-attempts`; a plan without the file
81
113
  DEFAULT_EFFORT = 'medium' # forge-dispatch.sh dwarf default
82
114
  LOCK_WAIT = 5.0 # seconds to wait for P/control.lock
83
115
  # forge-dispatch.sh rank_of. Only for "which accepted effort is above this one"; the set of
@@ -111,8 +143,10 @@ def row_inputs(plan: Path, task: str) -> str:
111
143
 
112
144
  # --- the user's ladder -------------------------------------------------------------
113
145
 
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."""
146
+ def registry_models(path=None) -> dict:
147
+ """{alias: {harness: model id}} from registry.tsv (or FORGE_REGISTRY, as dispatch and the scheduler read
148
+ it); the first row of an alias is its default."""
149
+ path = Path(path or os.environ.get('FORGE_REGISTRY') or REGISTRY)
116
150
  out = {}
117
151
  try:
118
152
  lines = path.read_text().splitlines()
@@ -140,6 +174,19 @@ def canonical(spec: str, registry: dict) -> str:
140
174
  return next(iter(rows.values()))
141
175
 
142
176
 
177
+ def model_key(spec: str, registry: dict) -> str:
178
+ """The model a spec runs, named so that one model reached through two harnesses compares equal
179
+ (`gpt-6.1-sol` on codex and `github-copilot/gpt-6.1-sol` on opencode): the id it resolves to, without
180
+ its provider prefix and with dots and dashes alike. Two ids are compared, never two aliases, since
181
+ one alias may list different models on different harnesses (`gemini` is Flash on antigravity and
182
+ Pro on opencode)."""
183
+ return canonical(spec, registry).rsplit('/', 1)[-1].lower().replace('.', '-')
184
+
185
+
186
+ def same_model(a: str, b: str, registry: dict) -> bool:
187
+ return model_key(a, registry) == model_key(b, registry)
188
+
189
+
143
190
  def arm(spec: str, registry: dict) -> tuple:
144
191
  """What exploration compares on: the model and the effort as written.
145
192
 
@@ -195,17 +242,18 @@ def _aligned(spec: str, pool_of_spec: list, other: list, key):
195
242
 
196
243
 
197
244
  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."""
245
+ """The exploration alternative and its tier: the nearest cheaper tier for medium/high, the nearest
246
+ stronger for low. (None, None) when there is none."""
199
247
  if tier not in TIERS:
200
- return None
248
+ return None, None
201
249
  i = TIERS.index(tier)
202
250
  order = TIERS[i + 1:] if i == 0 else tuple(reversed(TIERS[:i]))
203
251
  for other in order:
204
252
  if pools.get(other):
205
253
  pick = _aligned(spec, pools.get(tier) or [spec], pools[other], lambda s: arm(s, registry))
206
254
  if pick:
207
- return pick
208
- return None
255
+ return pick, other
256
+ return None, None
209
257
 
210
258
 
211
259
  def stronger(spec: str, pools: dict, registry: dict):
@@ -245,20 +293,23 @@ def parse_excluded(text: str) -> set:
245
293
  return out
246
294
 
247
295
 
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]]
296
+ def fallback_pick(current: str, pools: dict, registry: dict, excluded: set, tier: str, reviewer: str = None):
297
+ """The next member of the pool of `tier`, the tier the task runs in (running_tier), in pool
298
+ order and wrapping around, that runs another model on a pair nobody paused, and not the task's
299
+ reviewer's model: a task is never reviewed by the model that wrote it. None when there is none,
300
+ or when that pool does not run the current model (a model the user named by hand)."""
301
+ pool = pools.get(tier) or []
255
302
  own = canonical(current, registry)
256
303
  keys = [canonical(s, registry) for s in pool]
257
- start = keys.index(own) if own in keys else -1
304
+ if own not in keys:
305
+ return None
306
+ judge = reviewer if reviewer and reviewer not in ('-', 'UNASSIGNED') else None
307
+ start = keys.index(own)
258
308
  for step in range(1, len(pool) + 1):
259
309
  candidate = pool[(start + step) % len(pool)]
260
310
  pair = pair_of(candidate, registry)
261
- if canonical(candidate, registry) == own or pair is None:
311
+ # The reviewer's model on any harness (sol on opencode is codex's sol), as qa_fallback_pick compares.
312
+ if canonical(candidate, registry) == own or (judge and same_model(candidate, judge, registry)) or pair is None:
262
313
  continue
263
314
  if pair in excluded or (pair[0], '*') in excluded:
264
315
  continue
@@ -266,13 +317,135 @@ def fallback_pick(current: str, pools: dict, registry: dict, excluded: set):
266
317
  return None
267
318
 
268
319
 
320
+ def load_qa_pools(path) -> dict:
321
+ """{'any'|'low'|'medium'|'high': [spec, ...]} from plan/qa-routing.json, the reviewer pools `plan` was
322
+ given. Empty for a plan made before the file existed."""
323
+ try:
324
+ data = json.loads(Path(path).read_text())
325
+ except (OSError, ValueError):
326
+ return {}
327
+ out = {}
328
+ for key in ('any',) + TIERS:
329
+ specs = data.get(key) if isinstance(data, dict) else None
330
+ if isinstance(specs, list):
331
+ specs = [str(s).strip() for s in specs if str(s).strip()]
332
+ if specs:
333
+ out[key] = specs
334
+ return out
335
+
336
+
337
+ def qa_fallback_pick(current: str, implementer: str, pools: dict, registry: dict, excluded: set, difficulty: str):
338
+ """The peer reviewer of a review stopped on infrastructure: the next member, in pool order and
339
+ wrapping around, of the task's difficulty pool and then of `any`, that runs another model than the
340
+ stopped reviewer and than the implementer, on a pair nobody paused. A reviewer that no such pool
341
+ lists (named by hand) has no peer, since its strength is unknown. None when there is none."""
342
+ order = [pools.get(key) or [] for key in (difficulty, 'any') if key in TIERS or key == 'any']
343
+ own = canonical(current, registry)
344
+ if not any(canonical(s, registry) == own for pool in order for s in pool):
345
+ return None
346
+ wrote = implementer if implementer not in ('', '-', 'UNASSIGNED') else None
347
+ for pool in order:
348
+ keys = [canonical(s, registry) for s in pool]
349
+ start = keys.index(own) if own in keys else -1
350
+ for step in range(1, len(pool) + 1):
351
+ candidate = pool[(start + step) % len(pool)]
352
+ model, pair = canonical(candidate, registry), pair_of(candidate, registry)
353
+ if model == own or (wrote and same_model(candidate, wrote, registry)) or pair is None:
354
+ continue
355
+ if pair in excluded or (pair[0], '*') in excluded:
356
+ continue
357
+ return candidate
358
+ return None
359
+
360
+
361
+ def escalation_target(source: str, frm: str, to: str, running: str, pools: dict, registry: dict) -> str:
362
+ """The tier an escalations.tsv row moved the task to. The same model at another effort stays.
363
+ The policy (stronger) went to the first pool with its target above the highest pool of `frm`;
364
+ a person named a model, which is in the nearest pool to the tier the task was running in."""
365
+ model = canonical(to, registry)
366
+ if model == canonical(frm, registry):
367
+ return running
368
+ rank = rank_of(frm, pools, registry) if source == 'policy' else None
369
+ first = rank + 1 if rank is not None else TIERS.index(running)
370
+ for tier in TIERS[first:] + tuple(reversed(TIERS[:first])):
371
+ if any(canonical(s, registry) == model for s in pools.get(tier, ())):
372
+ return tier
373
+ return running
374
+
375
+
376
+ def running_tier(plan: Path, task: str, current: str = '') -> str:
377
+ """The tier a task runs in, from what forge recorded when it assigned the model, never from which
378
+ pools list the model: one model can sit in several, and a re-plan can change them. Two records
379
+ say it, each with its time: tasks/<id>/running.tier, written at every assignment (the plan's
380
+ resolution of the row, an escalation, a pin, `retry --dwarf`, a lateral move), and the last
381
+ exploration decision in route.jsonl, all an older plan has. The newer one counts, and only while
382
+ the task still runs its spec: an older record never beats a newer pick of the same model (#106).
383
+ With neither, or when the newest is for another spec (the table was edited by hand), the
384
+ difficulty. `current` is the spec the task runs, read from tasks.tsv when not given. '' when the
385
+ difficulty is no tier."""
386
+ tier = _row_cell(plan, task, 2)
387
+ if tier not in TIERS:
388
+ return ''
389
+ tdir = plan / 'tasks' / task
390
+ current = current or _dwarf_of(plan, task)
391
+ records = []
392
+ with contextlib.suppress(OSError, ValueError):
393
+ path = tdir / 'running.tier'
394
+ cells = path.read_text().strip().split('\t')
395
+ if len(cells) > 1 and cells[0] in TIERS:
396
+ # Written before records carried their time (forge 0.14): as old as the file.
397
+ records.append((float(cells[2]) if len(cells) > 2 else path.stat().st_mtime, cells[1], cells[0]))
398
+ with contextlib.suppress(OSError, ValueError, AttributeError, TypeError):
399
+ lines = (tdir / 'route.jsonl').read_text().splitlines()
400
+ decision = json.loads(lines[-1]) if lines else {}
401
+ if decision.get('chosen_tier') in TIERS:
402
+ records.append((float(decision.get('at') or 0), decision.get('chosen'), decision['chosen_tier']))
403
+ if records:
404
+ _, spec, recorded = max(records, key=lambda record: record[0])
405
+ if spec == current:
406
+ return recorded
407
+ return tier
408
+
409
+
410
+ def write_running_tier(plan: str, task: str, tier: str, spec: str, control) -> None:
411
+ """tasks/<id>/running.tier: `tier<TAB>spec<TAB>time`, the tier the task runs in while it runs `spec`."""
412
+ control.write_atomic(plan, 'tasks/%s/running.tier' % task, '%s\t%s\t%.6f\n' % (tier, spec, time.time()))
413
+
414
+
415
+ def record_running_tier(plan: str, task: str, row: str, control) -> None:
416
+ """tasks/<id>/running.tier for an escalations.tsv row: the tier the row moved the task to, decided
417
+ here with the pools of this moment. A fallback stays in its tier."""
418
+ cells = row.rstrip('\n').split('\t')
419
+ frm, to, source = cells[2], cells[3], cells[4] if len(cells) > 4 else 'policy'
420
+ tier = running_tier(Path(plan), task, frm)
421
+ if tier and source != 'fallback':
422
+ tier = escalation_target(source, frm, to, tier, load_pools(Path(plan) / 'fractal-routing.json'),
423
+ registry_models())
424
+ if tier:
425
+ write_running_tier(plan, task, tier, to, control)
426
+
427
+
269
428
  def fallback(args) -> int:
270
429
  plan = Path(os.path.realpath(args.plan))
271
430
  current = _dwarf_of(plan, args.task)
272
431
  if not current or current in ('-', 'UNASSIGNED'):
273
432
  return 1
274
433
  pick = fallback_pick(current, load_pools(plan / 'fractal-routing.json'), registry_models(),
275
- parse_excluded(args.exclude))
434
+ parse_excluded(args.exclude), running_tier(plan, args.task, current),
435
+ _row_cell(plan, args.task, 5))
436
+ if not pick:
437
+ return 1
438
+ print(pick)
439
+ return 0
440
+
441
+
442
+ def qa_fallback(args) -> int:
443
+ plan = Path(os.path.realpath(args.plan))
444
+ current, implementer = _row_cell(plan, args.task, 5), _dwarf_of(plan, args.task)
445
+ if not current or current in ('-', 'UNASSIGNED'):
446
+ return 1
447
+ pick = qa_fallback_pick(current, implementer, load_qa_pools(plan / 'qa-routing.json'), registry_models(),
448
+ parse_excluded(args.exclude), _row_cell(plan, args.task, 2))
276
449
  if not pick:
277
450
  return 1
278
451
  print(pick)
@@ -281,13 +454,14 @@ def fallback(args) -> int:
281
454
 
282
455
  # --- exploration -------------------------------------------------------------------
283
456
 
284
- def explore(args) -> str:
457
+ def explore(args) -> tuple:
458
+ """(spec, tier): the pick and the tier it was picked from."""
285
459
  epsilon = float(args.epsilon)
286
460
  if not 0 < epsilon <= 1:
287
- return args.default
288
- alternative = neighbour(args.default, args.tier, load_pools(args.pools), registry_models())
461
+ return args.default, args.tier
462
+ alternative, alternative_tier = neighbour(args.default, args.tier, load_pools(args.pools), registry_models())
289
463
  if not alternative:
290
- return args.default
464
+ return args.default, args.tier
291
465
  candidates = [args.default, alternative]
292
466
  rng = rng_for(args.task)
293
467
  draw = rng.random()
@@ -298,6 +472,7 @@ def explore(args) -> str:
298
472
  tdir.mkdir(parents=True, exist_ok=True)
299
473
  decision = dict(at=time.time(), task=args.task, tier=args.tier, epsilon=epsilon, candidates=candidates,
300
474
  default=args.default, chosen=chosen, explored=chosen != args.default,
475
+ chosen_tier=alternative_tier if chosen != args.default else args.tier,
301
476
  propensity=round(propensity, 6), inputs=row_inputs(plan, args.task))
302
477
  decision['decision'] = hashlib.sha256(json.dumps(decision, sort_keys=True).encode()).hexdigest()[:16]
303
478
  with open(tdir / 'route.jsonl', 'a') as log: # one line per resolution, never rewritten
@@ -307,11 +482,39 @@ def explore(args) -> str:
307
482
  marker.write_text(chosen + '\n')
308
483
  elif marker.exists():
309
484
  marker.unlink()
485
+ return chosen, decision['chosen_tier']
486
+
487
+
488
+ def assign(args) -> str:
489
+ """`plan`'s resolution of a row: the exploration draw, then the record of the tier its pick runs in,
490
+ newer than any record it replaces. A record that cannot be written is removed rather than left to
491
+ speak for the new pick. Prints the pick; any failure prints SPEC, as explore does."""
492
+ chosen, tier = args.default, args.tier
493
+ with contextlib.suppress(Exception):
494
+ chosen, tier = explore(args)
495
+ try:
496
+ control = _load_control()
497
+ plan = os.path.realpath(args.plan)
498
+ try:
499
+ write_running_tier(plan, args.task, tier, chosen, control)
500
+ except Exception as error:
501
+ print('%s: could not record the tier it runs in: %s' % (args.task, error), file=sys.stderr)
502
+ control.remove_safe(plan, 'tasks/%s/running.tier' % args.task)
503
+ except Exception:
504
+ pass
310
505
  return chosen
311
506
 
312
507
 
313
508
  # --- escalation --------------------------------------------------------------------
314
509
 
510
+ def _row_cell(plan: Path, task: str, index: int) -> str:
511
+ for line in (plan / 'tasks.tsv').read_text().splitlines():
512
+ cells = line.split('\t')
513
+ if not line.startswith('#') and cells and cells[0] == task and len(cells) > index:
514
+ return cells[index]
515
+ return ''
516
+
517
+
315
518
  def _dwarf_of(plan: Path, task: str) -> str:
316
519
  for line in (plan / 'tasks.tsv').read_text().splitlines():
317
520
  cells = line.split('\t')
@@ -381,32 +584,56 @@ def _next_effort_spec(spec: str):
381
584
  return None
382
585
 
383
586
 
384
- def failed_streak(rows: list, current: str, registry: dict, by_effort: bool = False) -> int:
587
+ def failed_streak(rows: list, current: str, registry: dict, by_effort: bool = False, laterals=()) -> int:
385
588
  """Distinct trailing attempt numbers that failed on `current`'s model.
386
589
 
387
590
  rows: (attempt, status, spec-or-None) oldest first. A row without a spec predates the
388
591
  column and is taken as the current spec. Infra stops, missing verdicts and forge errors
389
592
  judge nothing and are skipped; a pass, a merge or another model ends the streak.
593
+ laterals: (attempt, from, to) of each dwarf move in lateral.tsv. A model change between
594
+ two counted attempts does not end the streak when dwarf moves recorded between them take
595
+ the earlier attempt's spec to the later one's, through any chain of moves made in order
596
+ (see _moved_between): a lateral move is an infrastructure stop, not a judgment that the
597
+ model was too weak.
390
598
  With by_effort, another effort of the same model ends it too (a bump starts a new
391
599
  streak). A spec that names no effort counts as medium. With by_effort off the count
392
600
  is by model only, as before.
393
601
  """
394
- model = canonical(current, registry)
395
602
  effort = _effort_of(current) if by_effort else None
396
603
  seen = set()
604
+ expect, later = current, None # the spec the last counted attempt ran (current to start), and its number
397
605
  for attempt, status, spec in reversed(rows):
398
606
  if status in NEUTRAL:
399
607
  continue
400
- if spec and canonical(spec, registry) != model:
401
- break
608
+ if spec and canonical(spec, registry) != canonical(expect, registry):
609
+ if later is None or not _moved_between(laterals, spec, expect, attempt, later):
610
+ break
402
611
  if effort is not None and _effort_of(spec or current) != effort:
403
612
  break
404
613
  if status not in FAILED:
405
614
  break
406
615
  seen.add(attempt)
616
+ expect, later = spec or expect, attempt
407
617
  return len(seen)
408
618
 
409
619
 
620
+ def _moved_between(laterals, frm: str, to: str, earlier: int, later: int) -> bool:
621
+ """Whether dwarf moves took `frm` to `to` between two attempts: after attempt `earlier` was spent and
622
+ before attempt `later` began. A move records the attempts spent at that moment (an infrastructure stop
623
+ refunds its own), so a move straight after `earlier` is recorded as `earlier`. One stop can make several
624
+ moves (sol -> astra -> sonnet) with no attempt on the middle model, so the moves in the window must chain
625
+ in the order they were made: each one starts where the last ended. A move that starts elsewhere means
626
+ the model changed in between by something no lateral row records (an explicit retry), and the window
627
+ does not carry across it."""
628
+ model = frm
629
+ for n, f, t in laterals:
630
+ if earlier <= n < later:
631
+ if f != model:
632
+ return False
633
+ model = t
634
+ return model == to
635
+
636
+
410
637
  def attempt_rows(tdir: Path) -> list:
411
638
  rows = []
412
639
  try:
@@ -420,6 +647,31 @@ def attempt_rows(tdir: Path) -> list:
420
647
  return rows
421
648
 
422
649
 
650
+ def decided_attempt(tdir: Path) -> int:
651
+ """The attempt number of the latest row of tasks/<id>/decisions.tsv (epoch, attempt, choice, reason);
652
+ 0 when the task has no decision. The attempts counted against a model start after it."""
653
+ try:
654
+ lines = (tdir / 'decisions.tsv').read_text().splitlines()
655
+ except OSError:
656
+ return 0
657
+ return max([int(cells[1]) for cells in (line.split('\t') for line in lines)
658
+ if len(cells) > 1 and cells[1].isdigit()] or [0])
659
+
660
+
661
+ def lateral_rows(tdir: Path) -> list:
662
+ """(attempt, from, to) of each dwarf move in tasks/<id>/lateral.tsv, oldest first."""
663
+ rows = []
664
+ try:
665
+ lines = (tdir / 'lateral.tsv').read_text().splitlines()
666
+ except OSError:
667
+ return rows
668
+ for line in lines:
669
+ cells = line.split('\t')
670
+ if len(cells) >= 5 and cells[1].isdigit() and cells[2] == 'dwarf':
671
+ rows.append((int(cells[1]), cells[3], cells[4]))
672
+ return rows
673
+
674
+
423
675
  def _setting(plan: Path) -> int:
424
676
  try:
425
677
  value = (plan / 'escalate_after').read_text().strip()
@@ -435,6 +687,68 @@ def _fractal(plan: Path) -> bool:
435
687
  return False
436
688
 
437
689
 
690
+ # --- attempt cap (#69) -------------------------------------------------------------
691
+ # A task that keeps failing across runs stops for a person. The count and the cap live here, so
692
+ # the shell (do_task, the retry gate, the run summary), the scheduler and `forge control show`
693
+ # all read the same numbers.
694
+
695
+ def max_attempts_setting(plan: Path) -> int:
696
+ """The plan's attempt cap (`plan --max-attempts N`, `forge control set max-attempts`): the file's
697
+ number, DEFAULT_MAX_ATTEMPTS without the file, and 0 for no cap. An unreadable value is the default."""
698
+ try:
699
+ value = (plan / 'max_attempts').read_text().strip()
700
+ except OSError:
701
+ return DEFAULT_MAX_ATTEMPTS
702
+ return int(value) if re.fullmatch(r'[0-9]{1,9}', value) else DEFAULT_MAX_ATTEMPTS
703
+
704
+
705
+ def attempts_spent(tdir: Path) -> int:
706
+ """Attempts the task has used: the attempts.tsv rows whose status is not INFRA. An infrastructure stop
707
+ spends none. A QA-only resume re-reviews the same attempt number and writes a row of its own, and that
708
+ row spends one too: a task whose reviews return no verdict reaches its cap like any other."""
709
+ return sum(1 for _number, status, _spec in attempt_rows(tdir) if status != 'INFRA')
710
+
711
+
712
+ def granted_attempts(tdir: Path) -> int:
713
+ """The attempts a person granted: N of every retry=N row in tasks/<id>/decisions.tsv. The retry CLI takes
714
+ up to three digits, zero-padded ones too (retry=002), so the grant is read the same way."""
715
+ total = 0
716
+ try:
717
+ lines = (tdir / 'decisions.tsv').read_text().splitlines()
718
+ except OSError:
719
+ return total
720
+ for line in lines:
721
+ cells = line.split('\t')
722
+ if len(cells) > 2:
723
+ match = re.fullmatch(r'retry=([0-9]{1,3})', cells[2])
724
+ if match:
725
+ total += int(match.group(1))
726
+ return total
727
+
728
+
729
+ def attempt_cap(plan: Path, task: str) -> tuple:
730
+ """(attempts used, cap). The cap is max_attempts plus granted_attempts, and None when the plan has no
731
+ cap (max_attempts 0): a decision adds attempts to a cap, it does not make one."""
732
+ tdir = plan / 'tasks' / task
733
+ used = attempts_spent(tdir)
734
+ limit = max_attempts_setting(plan)
735
+ if limit == 0:
736
+ return used, None
737
+ return used, limit + granted_attempts(tdir)
738
+
739
+
740
+ def attempt_cap_cmd(args) -> int:
741
+ """`attempt-cap`: "<used> <cap>" on one line, cap "-" for no cap. Read only; a bad task id counts as
742
+ no attempts, which the callers never pass."""
743
+ plan = Path(os.path.realpath(args.plan))
744
+ if not args.task or args.task in ('.', '..') or '/' in args.task or '\0' in args.task:
745
+ print('0 -')
746
+ return 0
747
+ used, cap = attempt_cap(plan, args.task)
748
+ print('%d %s' % (used, '-' if cap is None else cap))
749
+ return 0
750
+
751
+
438
752
  # --- live-control files ------------------------------------------------------------
439
753
  # Markers are shared with `forge control` and the scheduler, so they are written the way
440
754
  # every writer of the plan's control files writes: a task id the scheduler would accept, a
@@ -577,7 +891,10 @@ def _decide(plan: Path, tdir: Path, args, after: int):
577
891
  return (), (), '', 0
578
892
  registry = registry_models()
579
893
  step = _effort_step(plan)
580
- streak = failed_streak(attempt_rows(tdir), current, registry, by_effort=step)
894
+ # A person's decision (decisions.tsv) restarts the count: only attempts after it can fail the model.
895
+ decided = decided_attempt(tdir)
896
+ rows = [row for row in attempt_rows(tdir) if row[0] > decided]
897
+ streak = failed_streak(rows, current, registry, by_effort=step, laterals=lateral_rows(tdir))
581
898
  if streak < after:
582
899
  return MARKERS, (), '', 0
583
900
  target, why = stronger(current, load_pools(plan / 'fractal-routing.json'), registry)
@@ -639,20 +956,22 @@ def _load_control():
639
956
  return module
640
957
 
641
958
 
642
- def record_escalation(args) -> int:
643
- """Probe or append tasks/<id>/escalations.tsv. 0 when that is safe; 1 when it is not.
959
+ def _record(args, name: str, after=None) -> int:
960
+ """Probe or append tasks/<id>/<name>. 0 when that is safe; 1 when it is not.
644
961
 
645
962
  A missing parent is a refusal on both paths. probe() reports that as the file being
646
963
  absent, so the check has to look at the walk itself. append_line refuses the same case
647
964
  before it opens the leaf: with no directory descriptor that open would use the process
648
965
  cwd, including when the task directory disappears between this check and the append.
966
+ `after(plan, task, line, control)` runs once the line is appended; its failure is printed,
967
+ not returned, because the row stands.
649
968
  """
650
969
  if not args.task or args.task in ('.', '..') or '/' in args.task or '\0' in args.task:
651
970
  return 1
652
971
  try:
653
972
  control = _load_control()
654
973
  plan = os.path.realpath(args.plan)
655
- rel = 'tasks/%s/escalations.tsv' % args.task
974
+ rel = 'tasks/%s/%s' % (args.task, name)
656
975
  parent, _leaf = control._open_parent(plan, rel)
657
976
  if parent is None:
658
977
  return 1
@@ -662,45 +981,91 @@ def record_escalation(args) -> int:
662
981
  else:
663
982
  line = args.line if args.line.endswith('\n') else args.line + '\n'
664
983
  control.append_line(plan, rel, line)
984
+ if after:
985
+ try:
986
+ after(plan, args.task, line, control)
987
+ except Exception as error: # the row stands; without this record the task reads as its difficulty
988
+ print('%s: could not record the tier it runs in: %s' % (args.task, error), file=sys.stderr)
665
989
  except Exception:
666
990
  return 1
667
991
  return 0
668
992
 
669
993
 
994
+ def record_escalation(args) -> int:
995
+ """Probe or append tasks/<id>/escalations.tsv, and the tier the row moved the task to."""
996
+ return _record(args, 'escalations.tsv', record_running_tier)
997
+
998
+
999
+ def record_lateral(args) -> int:
1000
+ """Probe or append tasks/<id>/lateral.tsv, and the tier the move keeps (record_lateral_tier)."""
1001
+ return _record(args, 'lateral.tsv', record_lateral_tier)
1002
+
1003
+
1004
+ def record_lateral_tier(plan: str, task: str, row: str, control) -> None:
1005
+ """tasks/<id>/running.tier after a lateral move: the tier the task ran in, now recorded for the spec
1006
+ it moved to. Without this a task moved sideways from a recorded spec would read as its difficulty again."""
1007
+ cells = row.rstrip('\n').split('\t')
1008
+ if cells[2] != 'dwarf': # a reviewer's move says nothing about the implementer's tier
1009
+ return
1010
+ frm, to = cells[3], cells[4]
1011
+ tier = running_tier(Path(plan), task, frm)
1012
+ if tier:
1013
+ write_running_tier(plan, task, tier, to, control)
1014
+
1015
+
670
1016
  def main(argv=None) -> int:
671
1017
  ap = argparse.ArgumentParser(prog='forge-route.py')
672
1018
  sub = ap.add_subparsers(dest='command', required=True)
673
1019
  p = sub.add_parser('explore')
674
1020
  for name in ('plan', 'task', 'tier', 'epsilon', 'default', 'pools'):
675
1021
  p.add_argument('--' + name, required=True)
1022
+ p = sub.add_parser('assign', help="plan's resolution of a row: exploration, then the record of its tier")
1023
+ for name in ('plan', 'task', 'tier', 'default', 'pools'):
1024
+ p.add_argument('--' + name, required=True)
1025
+ p.add_argument('--epsilon', default='0')
676
1026
  p = sub.add_parser('escalation')
677
1027
  p.add_argument('--plan', required=True)
678
1028
  p.add_argument('--task', required=True)
679
1029
  p.add_argument('--check', action='store_true')
680
1030
  p.add_argument('--qa-only-next', choices=('yes', 'no'), default=None,
681
1031
  help='whether the next entry only re-runs QA, as the caller measured it')
1032
+ p = sub.add_parser('attempt-cap', help='the attempts a task has used and its cap, "<used> <cap>" (- for none)')
1033
+ p.add_argument('--plan', required=True)
1034
+ p.add_argument('--task', required=True)
682
1035
  p = sub.add_parser('fallback', help='the same-tier model a capacity stop moves to')
683
1036
  p.add_argument('--plan', required=True)
684
1037
  p.add_argument('--task', required=True)
685
1038
  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)
1039
+ p = sub.add_parser('qa-fallback', help='the peer reviewer a review stopped on infrastructure moves to')
687
1040
  p.add_argument('--plan', required=True)
688
1041
  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')
1042
+ p.add_argument('--exclude', default='', help='harness/model pairs to skip, comma-separated (harness/* for all)')
1043
+ for name in ('record', 'lateral'):
1044
+ p = sub.add_parser(name, help=argparse.SUPPRESS)
1045
+ p.add_argument('--plan', required=True)
1046
+ p.add_argument('--task', required=True)
1047
+ mode = p.add_mutually_exclusive_group(required=True)
1048
+ mode.add_argument('--probe', action='store_true')
1049
+ mode.add_argument('--line')
692
1050
  args = ap.parse_args(argv)
693
1051
  if args.command == 'explore':
694
1052
  try:
695
- print(explore(args))
1053
+ print(explore(args)[0])
696
1054
  except Exception:
697
1055
  print(args.default)
698
1056
  return 0
1057
+ if args.command == 'assign':
1058
+ print(assign(args))
1059
+ return 0
699
1060
  if args.command == 'record':
700
1061
  return record_escalation(args)
701
- if args.command == 'fallback':
1062
+ if args.command == 'lateral':
1063
+ return record_lateral(args)
1064
+ if args.command == 'attempt-cap':
1065
+ return attempt_cap_cmd(args)
1066
+ if args.command in ('fallback', 'qa-fallback'):
702
1067
  try:
703
- return fallback(args)
1068
+ return (fallback if args.command == 'fallback' else qa_fallback)(args)
704
1069
  except Exception:
705
1070
  return 1
706
1071
  try: