@giamme/forge 0.18.0 → 0.19.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 (78) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +16 -2
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +25 -1
  6. package/docs/commands.md +81 -14
  7. package/docs/decomposed-runs.md +114 -1
  8. package/docs/development.md +2 -1
  9. package/docs/forge-ui.md +84 -15
  10. package/docs/memory.md +25 -4
  11. package/docs/models.md +8 -0
  12. package/docs/reviews.md +122 -0
  13. package/forge +20 -3
  14. package/package.json +2 -1
  15. package/references/dataset.md +20 -1
  16. package/references/decompose.md +621 -33
  17. package/references/harnesses.md +18 -3
  18. package/references/planning.md +43 -14
  19. package/references/ui.md +53 -6
  20. package/registry.tsv +8 -3
  21. package/scripts/forge-brief.py +88 -3
  22. package/scripts/forge-compare.py +4 -3
  23. package/scripts/forge-contract.py +202 -27
  24. package/scripts/forge-control.py +117 -5
  25. package/scripts/forge-dispatch.sh +34 -5
  26. package/scripts/forge-group.py +496 -0
  27. package/scripts/forge-groups.py +89 -0
  28. package/scripts/forge-handoff.py +1128 -0
  29. package/scripts/forge-lib-group.sh +641 -0
  30. package/scripts/forge-lib-plans.sh +339 -3
  31. package/scripts/forge-lib-task.sh +197 -4
  32. package/scripts/forge-memory.sh +245 -3
  33. package/scripts/forge-parallel.sh +715 -34
  34. package/scripts/forge-planner.py +104 -8
  35. package/scripts/forge-route.py +190 -12
  36. package/scripts/forge-runs.py +9 -5
  37. package/scripts/forge-schedule.py +354 -45
  38. package/scripts/forge-solo.sh +2 -0
  39. package/scripts/forge-worktrees.py +243 -0
  40. package/scripts/forge_brief/__init__.py +294 -50
  41. package/scripts/forge_brief/answers.py +58 -11
  42. package/scripts/forge_brief/proposals.py +1630 -0
  43. package/scripts/forge_dataset/efforts.py +4 -3
  44. package/scripts/forge_dataset/export.py +24 -12
  45. package/scripts/forge_dataset/facts.py +5 -3
  46. package/scripts/forge_dataset/forecast.py +8 -18
  47. package/scripts/forge_dataset/harvest.py +204 -9
  48. package/scripts/forge_dataset/history.py +11 -6
  49. package/scripts/forge_dataset/importer.py +65 -1
  50. package/scripts/forge_dataset/names.py +66 -0
  51. package/scripts/forge_dataset/reviewers.py +5 -2
  52. package/scripts/forge_dataset/risk.py +6 -3
  53. package/scripts/forge_dataset/routing.py +6 -1
  54. package/scripts/forge_groups/__init__.py +308 -0
  55. package/scripts/forge_groups/attribute.py +289 -0
  56. package/scripts/forge_groups/review.py +286 -0
  57. package/scripts/forge_owner.py +152 -0
  58. package/scripts/forge_side/__init__.py +12 -7
  59. package/ui/docs/api.md +173 -17
  60. package/ui/forge_ui/control.py +361 -2
  61. package/ui/forge_ui/executions.py +8 -1
  62. package/ui/forge_ui/export.py +31 -4
  63. package/ui/forge_ui/groups.py +264 -0
  64. package/ui/forge_ui/models.py +70 -8
  65. package/ui/forge_ui/reader.py +262 -19
  66. package/ui/forge_ui/server.py +4 -0
  67. package/ui/forge_ui/static/app.js +93 -13
  68. package/ui/forge_ui/static/briefview.js +350 -47
  69. package/ui/forge_ui/static/diffview.js +86 -1
  70. package/ui/forge_ui/static/groupsview.js +332 -0
  71. package/ui/forge_ui/static/index.html +1 -0
  72. package/ui/forge_ui/static/panel.js +127 -7
  73. package/ui/forge_ui/static/projectsview.js +189 -10
  74. package/ui/forge_ui/static/runmodel.js +14 -3
  75. package/ui/forge_ui/static/storageview.js +91 -10
  76. package/ui/forge_ui/static/style.css +79 -5
  77. package/ui/forge_ui/static/worktreesview.js +233 -12
  78. package/ui/forge_ui/storage.py +14 -0
@@ -9,8 +9,9 @@ gate and the one-task plan. Standard library only; no shell wiring.
9
9
  forge-planner.py parse --plan P --reply FILE
10
10
  Turns the planner's reply into P/tasks.tsv, P/tasks/<id>/prompt.md and, when it is not
11
11
  empty, P/tasks/<id>/approach.md; a task's `risk` (#122) goes to P/tasks/<id>/risk, and a
12
- missing or unknown one writes nothing. It never guesses or repairs: a reply that breaks one
13
- rule writes nothing but P/planner.refused (the first reason and the reply's path), prints
12
+ missing or unknown one writes nothing. A reply that includes `groups` also writes
13
+ P/groups.tsv (review always `task`, qa `-`). It never guesses or repairs: a reply that breaks
14
+ one rule writes nothing but P/planner.refused (the first reason and the reply's path), prints
14
15
  both and exits 4. P/request.md must hold the user's request (exit 2 when it is missing);
15
16
  it is attached to every task prompt so no requirement is lost.
16
17
 
@@ -32,8 +33,10 @@ import os
32
33
  from pathlib import Path
33
34
  import re
34
35
  import sys
36
+ import tempfile
35
37
 
36
38
  sys.path.insert(0, str(Path(__file__).resolve().parent))
39
+ import forge_groups # noqa: E402
37
40
  from forge_jev.coverage import split_requirements # noqa: E402 (read-only use)
38
41
 
39
42
  # The gate: a request at or under both limits skips the planner. On #86's 16 benchmark plans
@@ -47,6 +50,10 @@ TASK_KEYS = ('id', 'deps', 'difficulty', 'files', 'title', 'approach', 'prompt')
47
50
  # #122: a task's risk, recorded in shadow beside its difficulty. Optional, and the one key that never refuses a
48
51
  # reply: a missing or unknown value records nothing, because a label nothing routes on must not cost a plan.
49
52
  OPTIONAL_KEYS = ('risk',)
53
+ # #136: groups are optional on the reply. A missing key writes no groups.tsv. A present one is
54
+ # checked strictly; the planner never sets review=group (that is plan --group-review, or an edit).
55
+ GROUP_KEYS = ('id', 'title', 'goal', 'members')
56
+ MAX_GROUP_TEXT = 200
50
57
  DIFFICULTIES = ('low', 'medium', 'high')
51
58
  RISKS = ('low', 'medium', 'high')
52
59
  LEVELS = DIFFICULTIES
@@ -85,6 +92,11 @@ EXAMPLE = """\
85
92
  "title": "Parse the new config section",
86
93
  "approach": "Add parse_section() beside load(); keep load()'s signature.",
87
94
  "prompt": "Add the `limits` section to the config parser in src/config.py ...\\n\\n## Acceptance criteria\\n\\n- `limits` is read into Config.limits, with the defaults the request names.\\n- python3 -m unittest tests.test_config passes."}
95
+ ],
96
+ "groups": [
97
+ {"id": "config-limits", "title": "Config limits",
98
+ "goal": "The limits section is read into Config with the defaults the request names.",
99
+ "members": ["parse-config"]}
88
100
  ]}
89
101
  ```"""
90
102
 
@@ -174,6 +186,10 @@ def build_prompt(request: str, level: str | None) -> str:
174
186
  '**Keep each task** under about 7000 characters of prompt and 9 files. A smaller task with '
175
187
  'stated acceptance criteria passes its first review far more often.',
176
188
  f'At most {MAX_TASKS} tasks.',
189
+ '**Groups.** Tasks that together deliver one goal, and that the user will think of as one '
190
+ 'step, form one group (usually one per wave of the plan\'s dependency order). Each group '
191
+ 'has a short title and a goal sentence that says what is true once its tasks are done. A '
192
+ 'group may have one task. A task may be left out of every group.',
177
193
  ]
178
194
  numbered = '\n'.join(f'{n}. {rule}' for n, rule in enumerate(rules, 1))
179
195
  return f"""\
@@ -195,8 +211,8 @@ The request follows verbatim between the markers. It is the whole requirement.
195
211
  # Reply format
196
212
 
197
213
  Reply with exactly one fenced block whose opening line is ```forge-plan and whose body is one
198
- JSON object with exactly the key `tasks`: a list of 1 to {MAX_TASKS} objects, each with exactly
199
- these keys and no others:
214
+ JSON object with the key `tasks` and, optionally, `groups`. `tasks` is a list of 1 to {MAX_TASKS}
215
+ objects, each with exactly these keys and no others:
200
216
 
201
217
  - `id`: lowercase slug matching `^[a-z0-9][a-z0-9-]{{0,39}}$`, unique in the plan;
202
218
  - `deps`: list of ids of tasks that must land first (`[]` for none), no cycles;
@@ -208,6 +224,15 @@ these keys and no others:
208
224
  - `approach`: a few lines on the intended shape (a string; `""` for none);
209
225
  - `prompt`: the task's full instruction, ending with a `## Acceptance criteria` section.
210
226
 
227
+ `groups`, when present, is a list of objects with exactly these keys and no others. Omit the key
228
+ to return no groups:
229
+
230
+ - `id`: the same slug as a task id, unique in the plan, and not a task id;
231
+ - `title`: one short line, at most 200 characters;
232
+ - `goal`: one line, at most 200 characters, what is true once the group's tasks are done;
233
+ - `members`: ids of tasks from this reply, in order. A group may have one task. A task is in at
234
+ most one group, and a task may be left out of every group.
235
+
211
236
  Put no other `forge-plan` block in the reply. Text outside the block is ignored. Anything that
212
237
  breaks these rules makes the whole reply refused; nothing is repaired. A valid reply:
213
238
 
@@ -339,6 +364,73 @@ def check_task(task, index: int, seen: set) -> dict:
339
364
  return dict(task, risk=risk if isinstance(risk, str) and risk in RISKS else None)
340
365
 
341
366
 
367
+ def check_group_line(value, where: str):
368
+ """A group's title or goal: one non-empty line, at most MAX_GROUP_TEXT characters."""
369
+ if not isinstance(value, str):
370
+ raise Refusal(f'{where} is not a string')
371
+ # Line separators first, so a tab or other control is not reported as a second line.
372
+ # Not a raw string: \n, \x85 and \u2028 have to be the characters, not the escape text.
373
+ if re.search('[\n\r\x85\u2028\u2029]', value):
374
+ raise Refusal(f'{where} is not one line')
375
+ if LINE_BREAKS_RE.search(value):
376
+ raise Refusal(f'{where} holds a tab or a control character')
377
+ if not value.strip():
378
+ raise Refusal(f'{where} is empty')
379
+ if len(value) > MAX_GROUP_TEXT:
380
+ raise Refusal(f'{where} is longer than {MAX_GROUP_TEXT} characters')
381
+ check_text(value, where)
382
+
383
+
384
+ def check_groups(raw, task_ids: set) -> list:
385
+ """The reply's groups, each forced to review=task and qa=-. Order is the reply's."""
386
+ if not isinstance(raw, list):
387
+ raise Refusal('groups is not a list')
388
+ seen: set = set()
389
+ owner: dict = {}
390
+ groups = []
391
+ for index, group in enumerate(raw):
392
+ where = f'group {index + 1}'
393
+ check_keys(group, GROUP_KEYS, where)
394
+ gid = group['id']
395
+ if not isinstance(gid, str) or not ID_RE.fullmatch(gid):
396
+ raise Refusal(f'{where}: id {gid!r} does not match ^[a-z0-9][a-z0-9-]{{0,39}}$')
397
+ where = f'group {gid}'
398
+ if gid in seen:
399
+ raise Refusal(f'{where}: duplicate id')
400
+ seen.add(gid)
401
+ if gid in task_ids:
402
+ raise Refusal(f'{where}: the id is also a task id')
403
+ check_group_line(group['title'], f'{where}: title')
404
+ check_group_line(group['goal'], f'{where}: goal')
405
+ members = group['members']
406
+ if not isinstance(members, list) or not all(isinstance(m, str) for m in members):
407
+ raise Refusal(f'{where}: members is not a list of task ids')
408
+ if not members:
409
+ raise Refusal(f'{where}: members is empty')
410
+ for member in members:
411
+ if member not in task_ids:
412
+ raise Refusal(f'{where}: member {member!r} is not a task of the reply')
413
+ if member in owner:
414
+ prior = owner[member]
415
+ if prior == gid:
416
+ raise Refusal(f'{where}: task {member} is listed twice')
417
+ raise Refusal(f'{where}: task {member} is in two groups ({prior} and {gid})')
418
+ owner[member] = gid
419
+ groups.append(forge_groups.Group(gid, 'task', '-', tuple(members), group['title'], group['goal']))
420
+ return groups
421
+
422
+
423
+ def groups_tsv_bytes(groups) -> bytes:
424
+ """Bytes `forge_groups.write` emits, held until the other outputs are written too.
425
+
426
+ A refusal must write none of the plan. write() would touch the disk now, so the bytes are
427
+ captured and joined to the outputs list cmd_parse already flushes in one pass.
428
+ """
429
+ with tempfile.TemporaryDirectory() as tmp:
430
+ forge_groups.write(tmp, groups)
431
+ return (Path(tmp) / 'groups.tsv').read_bytes()
432
+
433
+
342
434
  def check_graph(tasks: list):
343
435
  ids = {t['id'] for t in tasks}
344
436
  for t in tasks:
@@ -363,7 +455,8 @@ def check_graph(tasks: list):
363
455
  visit(t['id'], [t['id']])
364
456
 
365
457
 
366
- def parse_reply(reply: str) -> list:
458
+ def parse_reply(reply: str):
459
+ """(tasks, groups). groups is None when the reply has no groups key, else a list (maybe empty)."""
367
460
  body = extract_block(reply)
368
461
  try:
369
462
  data = json.loads(body, object_pairs_hook=no_duplicate_keys)
@@ -371,7 +464,7 @@ def parse_reply(reply: str) -> list:
371
464
  # JSONDecodeError is a ValueError; so is Python's limit on integer digits. Nesting deeper
372
465
  # than the interpreter allows raises RecursionError.
373
466
  raise Refusal(f'the forge-plan body is not valid JSON: {type(err).__name__}: {str(err)[:200]}')
374
- check_keys(data, ('tasks',), 'the forge-plan body')
467
+ check_keys(data, ('tasks',), 'the forge-plan body', ('groups',))
375
468
  tasks = data['tasks']
376
469
  if not isinstance(tasks, list) or not 1 <= len(tasks) <= MAX_TASKS:
377
470
  count = f' ({len(tasks)})' if isinstance(tasks, list) else ''
@@ -379,7 +472,8 @@ def parse_reply(reply: str) -> list:
379
472
  seen: set = set()
380
473
  checked = [check_task(t, i, seen) for i, t in enumerate(tasks)]
381
474
  check_graph(checked)
382
- return checked
475
+ groups = check_groups(data['groups'], seen) if 'groups' in data else None
476
+ return checked, groups
383
477
 
384
478
 
385
479
  def cmd_parse(args) -> int:
@@ -390,7 +484,7 @@ def cmd_parse(args) -> int:
390
484
  request = read_text(request_path, 'request')
391
485
  reply = read_text(args.reply, 'reply')
392
486
  try:
393
- tasks = parse_reply(reply)
487
+ tasks, groups = parse_reply(reply)
394
488
  except Refusal as err:
395
489
  # A key or path may hold a lone surrogate; escape it so the reason can be written and printed.
396
490
  reason = str(err).encode('utf-8', 'backslashreplace').decode('utf-8')
@@ -412,6 +506,8 @@ def cmd_parse(args) -> int:
412
506
  outputs.append((folder / 'approach.md', t['approach'].encode('utf-8') if t['approach'].strip() else None))
413
507
  outputs.append((folder / 'risk', (t['risk'] + '\n').encode('utf-8') if t['risk'] else None))
414
508
  outputs.append((plan / 'tasks.tsv', ('\n'.join(rows) + '\n').encode('utf-8')))
509
+ if groups is not None:
510
+ outputs.append((plan / 'groups.tsv', groups_tsv_bytes(groups)))
415
511
  for path, data in outputs:
416
512
  if data is None:
417
513
  path.unlink(missing_ok=True) # an empty approach must not keep an older one alive
@@ -46,6 +46,16 @@ bias (inverse-propensity weighting needs the probability each choice had).
46
46
  re-read escalate_after inside it: a policy decision made before a human switched the
47
47
  policy off writes nothing.
48
48
 
49
+ forge-route.py per-model --plan P --task ID
50
+ forge-route.py worst-case --plan P
51
+ `plan --retry-per-model N` (<plan>/retry_per_model, 1-99): a task may fail N times on each
52
+ rung the retry policy gives it (the stronger tiers of the pools, then the efforts when
53
+ escalate_effort is on), and the count starts again after each escalation. It replaces
54
+ escalate_after as the trigger. `per-model` prints {retry, rung, failed_on_rung, rungs_left,
55
+ per_model} as JSON (exit 2 when the plan has no valid file); `worst-case` prints the dispatches
56
+ the unmerged tasks can spend, per task and in total, and the tasks N*rungs takes past
57
+ max_attempts. Without the file nothing else here changes.
58
+
49
59
  forge-route.py fallback --plan P --task ID [--exclude harness/model,...]
50
60
  The lateral move of an infrastructure stop: prints the next free model of the pool of the
51
61
  tier the task runs in (the newest record of it: see running_tier), or exits 1 when there is none.
@@ -92,6 +102,7 @@ import errno
92
102
  import fcntl
93
103
  import hashlib
94
104
  import json
105
+ import math
95
106
  import os
96
107
  import random
97
108
  import re
@@ -107,7 +118,7 @@ TIERS = ('low', 'medium', 'high')
107
118
  SCRIPTS = Path(__file__).resolve().parent
108
119
  REGISTRY = SCRIPTS.parent / 'registry.tsv'
109
120
  FAILED = ('FAIL', 'TIMEOUT', 'BOUNCED', 'INCOMPLETE') # a judgment against the spec that ran
110
- NEUTRAL = ('INFRA', 'UNKNOWN', 'ERROR', 'RUNNING', 'INTERRUPTED', 'NEEDS_INPUT', 'NEEDS_DECISION') # say nothing about it
121
+ NEUTRAL = ('INFRA', 'UNKNOWN', 'ERROR', 'RUNNING', 'INTERRUPTED', 'NEEDS_INPUT', 'NEEDS_DECISION', 'STALE') # say nothing about it
111
122
  DEFAULT_ESCALATE_AFTER = 3
112
123
  DEFAULT_MAX_ATTEMPTS = 8 # `plan --max-attempts`; a plan without the file
113
124
  DEFAULT_EFFORT = 'medium' # forge-dispatch.sh dwarf default
@@ -343,7 +354,9 @@ def qa_fallback_pick(current: str, implementer: str, pools: dict, registry: dict
343
354
  own = canonical(current, registry)
344
355
  if not any(canonical(s, registry) == own for pool in order for s in pool):
345
356
  return None
346
- wrote = implementer if implementer not in ('', '-', 'UNASSIGNED') else None
357
+ # `script` names the command that implements the task, not a model, so it cannot
358
+ # exclude a reviewer that shares a registry alias of that name.
359
+ wrote = implementer if implementer not in ('', '-', 'UNASSIGNED', 'script') else None
347
360
  for pool in order:
348
361
  keys = [canonical(s, registry) for s in pool]
349
362
  start = keys.index(own) if own in keys else -1
@@ -382,7 +395,9 @@ def running_tier(plan: Path, task: str, current: str = '') -> str:
382
395
  the task still runs its spec: an older record never beats a newer pick of the same model (#106).
383
396
  With neither, or when the newest is for another spec (the table was edited by hand), the
384
397
  difficulty. `current` is the spec the task runs, read from tasks.tsv when not given. '' when the
385
- difficulty is no tier."""
398
+ difficulty is no tier, and when the task is scripted: `script` is not a model, so nothing is recorded."""
399
+ if current == 'script' or _is_script(plan, task):
400
+ return ''
386
401
  tier = _row_cell(plan, task, 2)
387
402
  if tier not in TIERS:
388
403
  return ''
@@ -414,9 +429,14 @@ def write_running_tier(plan: str, task: str, tier: str, spec: str, control) -> N
414
429
 
415
430
  def record_running_tier(plan: str, task: str, row: str, control) -> None:
416
431
  """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."""
432
+ here with the pools of this moment. A fallback stays in its tier. A scripted task has no model
433
+ tier to record, and an existing file is left as it is."""
434
+ if _is_script(Path(plan), task):
435
+ return
418
436
  cells = row.rstrip('\n').split('\t')
419
437
  frm, to, source = cells[2], cells[3], cells[4] if len(cells) > 4 else 'policy'
438
+ if to == 'script':
439
+ return
420
440
  tier = running_tier(Path(plan), task, frm)
421
441
  if tier and source != 'fallback':
422
442
  tier = escalation_target(source, frm, to, tier, load_pools(Path(plan) / 'fractal-routing.json'),
@@ -427,6 +447,8 @@ def record_running_tier(plan: str, task: str, row: str, control) -> None:
427
447
 
428
448
  def fallback(args) -> int:
429
449
  plan = Path(os.path.realpath(args.plan))
450
+ if _is_script(plan, args.task):
451
+ return 1
430
452
  current = _dwarf_of(plan, args.task)
431
453
  if not current or current in ('-', 'UNASSIGNED'):
432
454
  return 1
@@ -488,7 +510,11 @@ def explore(args) -> tuple:
488
510
  def assign(args) -> str:
489
511
  """`plan`'s resolution of a row: the exploration draw, then the record of the tier its pick runs in,
490
512
  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."""
513
+ speak for the new pick. Prints the pick; any failure prints SPEC, as explore does.
514
+
515
+ A scripted row is not a model to explore or to record a tier for: the cell comes back unchanged."""
516
+ if args.default == 'script' or _is_script(Path(args.plan), args.task):
517
+ return 'script'
492
518
  chosen, tier = args.default, args.tier
493
519
  with contextlib.suppress(Exception):
494
520
  chosen, tier = explore(args)
@@ -523,6 +549,14 @@ def _dwarf_of(plan: Path, task: str) -> str:
523
549
  return ''
524
550
 
525
551
 
552
+ def _is_script(plan: Path, task: str) -> bool:
553
+ """True when the task's dwarf cell is the literal `script`: it runs tasks/<id>/run, not a model."""
554
+ try:
555
+ return _dwarf_of(plan, task) == 'script'
556
+ except OSError:
557
+ return False
558
+
559
+
526
560
  def _spec_parts(spec: str):
527
561
  """(alias, effort, harness) of alias[:effort[:harness]]. Effort and harness are '' when unnamed."""
528
562
  alias, sep, rest = str(spec).partition(':')
@@ -693,6 +727,122 @@ def _setting(plan: Path) -> int:
693
727
  return DEFAULT_ESCALATE_AFTER
694
728
 
695
729
 
730
+ # --- per-model retries (#141) ------------------------------------------------------
731
+ # `plan --retry-per-model N`: a task may fail N times on each rung the retry policy gives it, and the
732
+ # count starts again after each escalation. The trigger lives in escalation(); the questions the
733
+ # scheduler and the plan table ask (may it retry, what is the worst case) are answered here.
734
+
735
+ MAX_RUNGS = 12
736
+ NON_MODEL_DWARFS = ('', '-', 'UNASSIGNED', 'script')
737
+
738
+
739
+ def per_model_setting(plan: Path):
740
+ """<plan>/retry_per_model as an integer from 1 to 99, else None (missing, empty or malformed)."""
741
+ try:
742
+ value = (plan / 'retry_per_model').read_text().strip()
743
+ except OSError:
744
+ return None
745
+ if not re.fullmatch(r'[0-9]{1,9}', value):
746
+ return None
747
+ return int(value) if 1 <= int(value) <= 99 else None
748
+
749
+
750
+ def rungs_above(spec: str, plan: Path) -> list:
751
+ """The specs the policy would move through from `spec`, in order: repeated stronger() until it
752
+ returns None, then, with the effort step on, repeated _next_effort_spec on the last one. A spec
753
+ in none of the pools has none. Stops on a repeat, and at MAX_RUNGS."""
754
+ if spec in NON_MODEL_DWARFS:
755
+ return []
756
+ registry = registry_models()
757
+ pools = load_pools(plan / 'fractal-routing.json')
758
+ if rank_of(spec, pools, registry) is None:
759
+ return []
760
+ out, seen = [], {spec}
761
+ current = spec
762
+ while len(out) < MAX_RUNGS:
763
+ target, _why = stronger(current, pools, registry)
764
+ if not target or target in seen:
765
+ break
766
+ out.append(target)
767
+ seen.add(target)
768
+ current = target
769
+ if _effort_step(plan):
770
+ while len(out) < MAX_RUNGS:
771
+ target = _next_effort_spec(current)
772
+ if not target or target in seen:
773
+ break
774
+ out.append(target)
775
+ seen.add(target)
776
+ current = target
777
+ return out
778
+
779
+
780
+ def _task_listed(plan: Path, task: str) -> bool:
781
+ try:
782
+ lines = (plan / 'tasks.tsv').read_text().splitlines()
783
+ except OSError:
784
+ return False
785
+ return any(not line.startswith('#') and line.split('\t')[0] == task for line in lines)
786
+
787
+
788
+ def per_model(plan: Path, task: str) -> dict:
789
+ """{"retry", "rung", "failed_on_rung", "rungs_left", "per_model"}: whether the task may be attempted
790
+ again under the per-model budget. Pins and held decisions are the scheduler's other checks."""
791
+ limit = per_model_setting(plan)
792
+ out = {'retry': False, 'rung': '', 'failed_on_rung': 0, 'rungs_left': 0, 'per_model': limit}
793
+ if limit is None or not task or not _task_listed(plan, task):
794
+ return out
795
+ current = _dwarf_of(plan, task)
796
+ tdir = plan / 'tasks' / task
797
+ decided = decided_attempt(tdir)
798
+ rows = [row for row in attempt_rows(tdir) if row[0] > decided]
799
+ failed = failed_streak(rows, current, registry_models(), by_effort=_effort_step(plan),
800
+ laterals=lateral_rows(tdir))
801
+ left = len(rungs_above(current, plan))
802
+ out.update(rung=current, failed_on_rung=failed, rungs_left=left, retry=failed < limit or left > 0)
803
+ return out
804
+
805
+
806
+ def _shadow_rate(plan: Path) -> float:
807
+ try:
808
+ rate = float((plan / 'shadow_rate').read_text().strip())
809
+ except (OSError, ValueError):
810
+ return 0.1
811
+ # As forge-shadow.py's rate_of reads it: a share past 1 samples every review, never more.
812
+ return min(max(rate, 0.0), 1.0) if rate == rate else 0.1
813
+
814
+
815
+ def worst_case(plan: Path) -> dict:
816
+ """The most dispatches the unmerged tasks can spend if every rung fails N times: the implementer's
817
+ (`dwarf`), the reviewer's (`qa`) and the shadow reviews (`shadow`). N is 1 without retry_per_model."""
818
+ limit = per_model_setting(plan)
819
+ n = limit or 1
820
+ cap = max_attempts_setting(plan)
821
+ shadow_on = (plan / 'shadow_qa').exists()
822
+ rate = _shadow_rate(plan)
823
+ tasks, capped = [], []
824
+ try:
825
+ lines = (plan / 'tasks.tsv').read_text().splitlines()
826
+ except OSError:
827
+ lines = []
828
+ for line in lines:
829
+ cells = line.split('\t')
830
+ if line.startswith('#') or not cells or not cells[0]:
831
+ continue
832
+ task = cells[0]
833
+ if (plan / 'tasks' / task / 'merged').exists():
834
+ continue
835
+ dwarf = cells[4] if len(cells) > 4 else ''
836
+ rungs = 1 if dwarf in NON_MODEL_DWARFS else 1 + len(rungs_above(dwarf, plan))
837
+ qa = n * rungs
838
+ tasks.append({'id': task, 'rungs': rungs, 'dwarf': 0 if dwarf == 'script' else n * rungs,
839
+ 'qa': qa, 'shadow': math.ceil(qa * rate) if shadow_on else 0})
840
+ if cap > 0 and n * rungs > cap:
841
+ capped.append(task)
842
+ total = sum(t['dwarf'] + t['qa'] + t['shadow'] for t in tasks)
843
+ return {'per_model': limit, 'tasks': tasks, 'total': total, 'capped': capped}
844
+
845
+
696
846
  def _fractal(plan: Path) -> bool:
697
847
  try:
698
848
  return bool(json.loads((plan / 'fractal-selection.json').read_text()).get('enabled'))
@@ -716,10 +866,11 @@ def max_attempts_setting(plan: Path) -> int:
716
866
 
717
867
 
718
868
  def attempts_spent(tdir: Path) -> int:
719
- """Attempts the task has used: the attempts.tsv rows whose status is not INFRA. An infrastructure stop
720
- spends none. A QA-only resume re-reviews the same attempt number and writes a row of its own, and that
869
+ """Attempts the task has used: the attempts.tsv rows whose status is not INFRA or STALE. An infrastructure
870
+ stop spends none, and neither does an attempt whose prompt was edited while it ran (STALE). A QA-only
871
+ resume re-reviews the same attempt number and writes a row of its own, and that
721
872
  row spends one too: a task whose reviews return no verdict reaches its cap like any other."""
722
- return sum(1 for _number, status, _spec in attempt_rows(tdir) if status != 'INFRA')
873
+ return sum(1 for _number, status, _spec in attempt_rows(tdir) if status not in ('INFRA', 'STALE'))
723
874
 
724
875
 
725
876
  def granted_attempts(tdir: Path) -> int:
@@ -876,16 +1027,22 @@ def _qa_next(tdir: Path) -> bool:
876
1027
  return False
877
1028
 
878
1029
 
1030
+ def _patience(plan: Path) -> int:
1031
+ """Failures on one model before the next tier: retry_per_model when set (#141, it replaces
1032
+ escalate_after for its plan), else escalate_after. 0 is off."""
1033
+ return per_model_setting(plan) or _setting(plan)
1034
+
1035
+
879
1036
  def _apply(plan: Path, tdir: Path, clear=(), writes=(), policy=True, pin=None):
880
1037
  """Clear and write markers under the control lock. Returns (policy stood, pin reported).
881
1038
 
882
- The policy re-reads escalate_after inside the lock (a human may have switched it off since
1039
+ The policy re-reads its patience inside the lock (a human may have switched it off since
883
1040
  the decision was made): it then writes nothing and its markers go, as `--escalate-after 0`
884
- clears them. A pin is reported as escalation.next only while it is still pending; the stop
1041
+ clears them. retry_per_model, when set, is that patience, as in escalation(). A pin is reported as escalation.next only while it is still pending; the stop
885
1042
  and split markers beneath it stay the policy's, because the pin has not been applied.
886
1043
  """
887
1044
  with _control_lock(plan):
888
- stood = policy and _setting(plan) > 0
1045
+ stood = policy and _patience(plan) > 0
889
1046
  if policy and not stood:
890
1047
  clear, writes = MARKERS, ()
891
1048
  reported = pin is not None and _pin(tdir) == pin
@@ -900,6 +1057,9 @@ def _apply(plan: Path, tdir: Path, clear=(), writes=(), policy=True, pin=None):
900
1057
  def _decide(plan: Path, tdir: Path, args, after: int):
901
1058
  """What the policy wants done to the markers: (clear, writes, spec to print, exit code)."""
902
1059
  current = _dwarf_of(plan, args.task)
1060
+ if current == 'script':
1061
+ # No implementer to escalate, and no pin to report: drop any markers a model once left.
1062
+ return MARKERS, (), '', 0
903
1063
  if not current or current in ('-', 'UNASSIGNED'):
904
1064
  return (), (), '', 0
905
1065
  registry = registry_models()
@@ -931,7 +1091,13 @@ def escalation(args) -> int:
931
1091
  tdir = _task_dir(plan, args.task)
932
1092
  if tdir is None:
933
1093
  return 0
934
- after = _setting(plan)
1094
+ # A scripted task has no model to change. Idle, even with a pending pin or a failed streak:
1095
+ # print nothing, leave no escalation marker, and remove ones already there. The pin file
1096
+ # itself stays; nothing here applies it.
1097
+ if _is_script(plan, args.task):
1098
+ _clear(tdir, *MARKERS)
1099
+ return 0
1100
+ after = _patience(plan)
935
1101
  fractal = _fractal(plan)
936
1102
  # Fractal plans freeze their eligible set at selection; a QA-only resume spends no dwarf
937
1103
  # attempt, so neither is a moment to change the implementer.
@@ -1054,6 +1220,11 @@ def main(argv=None) -> int:
1054
1220
  p.add_argument('--plan', required=True)
1055
1221
  p.add_argument('--task', required=True)
1056
1222
  p.add_argument('--exclude', default='', help='harness/model pairs to skip, comma-separated (harness/* for all)')
1223
+ p = sub.add_parser('per-model', help='whether a task may retry under plan --retry-per-model (exit 2 without it)')
1224
+ p.add_argument('--plan', required=True)
1225
+ p.add_argument('--task', required=True)
1226
+ p = sub.add_parser('worst-case', help='the most dispatches the unmerged tasks can spend under --retry-per-model')
1227
+ p.add_argument('--plan', required=True)
1057
1228
  for name in ('record', 'lateral'):
1058
1229
  p = sub.add_parser(name, help=argparse.SUPPRESS)
1059
1230
  p.add_argument('--plan', required=True)
@@ -1077,6 +1248,13 @@ def main(argv=None) -> int:
1077
1248
  return record_lateral(args)
1078
1249
  if args.command == 'attempt-cap':
1079
1250
  return attempt_cap_cmd(args)
1251
+ if args.command == 'per-model':
1252
+ result = per_model(Path(os.path.realpath(args.plan)), args.task)
1253
+ print(json.dumps(result))
1254
+ return 0 if result['per_model'] is not None else 2
1255
+ if args.command == 'worst-case':
1256
+ print(json.dumps(worst_case(Path(os.path.realpath(args.plan)))))
1257
+ return 0
1080
1258
  if args.command in ('fallback', 'qa-fallback'):
1081
1259
  try:
1082
1260
  return (fallback if args.command == 'fallback' else qa_fallback)(args)
@@ -2,9 +2,10 @@
2
2
  """forge runs [--repo DIR | --all] [--limit N] [--json]: this repo's recent runs, in the terminal.
3
3
 
4
4
  Every solo run, `plan` and `run` registers its run dir (forge_registry.py); this lists them newest
5
- first, one line each (run id, kind, age, task states, verification and final review, goal) with the
6
- run dir under it, so you can see what happened without a browser and get the dir to resume, retry
7
- or open with `forge ui open`. The repo is the Git top level of the current directory unless
5
+ first, one line each (run id, kind, age, task states, verification, final review, goal, and
6
+ `after <run>` when the plan was chained) with the run dir under it, so you can see what happened
7
+ without a browser and get the dir to resume, retry or open with `forge ui open`. The repo is the
8
+ Git top level of the current directory unless
8
9
  `--repo` names one; `--all` lists the runs of every repo. It reads the same run summaries as
9
10
  forge-ui and never writes anything.
10
11
 
@@ -36,7 +37,7 @@ import forge_registry # noqa: E402
36
37
  from forge_ui import reader # noqa: E402
37
38
 
38
39
  FIELDS = ('key', 'run_id', 'kind', 'goal', 'repo', 'path', 'created', 'updated', 'task_count', 'counts',
39
- 'verification_status', 'final_review')
40
+ 'verification_status', 'final_review', 'after')
40
41
 
41
42
 
42
43
  def repo_of(start: Path) -> Path:
@@ -89,11 +90,14 @@ def line(run: dict, now: float, with_repo: bool = False) -> str:
89
90
  counts = ' · '.join(f'{status.lower()} {n}' for status, n in (run['counts'] or {}).items()) or 'no tasks'
90
91
  checks = ''.join(f' {label} {run[key]}' for label, key in (('verify', 'verification_status'), ('review', 'final_review'))
91
92
  if run.get(key))
93
+ previous = run.get('after') or {}
94
+ predecessor = previous.get('run_id') or previous.get('key')
95
+ chain = f' after {predecessor}' if predecessor else ''
92
96
  goal = str(run['goal'] or 'Untitled run').splitlines()[0]
93
97
  if len(goal) > 72:
94
98
  goal = goal[:71] + '…'
95
99
  repo = f" {Path(run['repo']).name or run['repo']}" if with_repo and run.get('repo') else ''
96
- return f"{run['run_id'] or run['key']} {run['kind']}{repo} {age(run['updated'], now)} {counts}{checks} {goal}\n {run['path']}"
100
+ return f"{run['run_id'] or run['key']} {run['kind']}{repo} {age(run['updated'], now)} {counts}{checks}{chain} {goal}\n {run['path']}"
97
101
 
98
102
 
99
103
  def remove(argv) -> int: