@giamme/forge 0.17.0 → 0.18.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 (76) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/SKILL.md +16 -3
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +8 -0
  5. package/docs/commands.md +70 -6
  6. package/docs/dataset.md +5 -0
  7. package/docs/decomposed-runs.md +8 -0
  8. package/docs/forge-ui.md +23 -2
  9. package/docs/memory.md +2 -0
  10. package/docs/safety.md +8 -0
  11. package/forge +24 -1
  12. package/package.json +1 -1
  13. package/references/dataset.md +19 -0
  14. package/references/decompose.md +134 -1
  15. package/references/solo.md +2 -1
  16. package/references/ui.md +5 -2
  17. package/scripts/forge-artifact.sh +14 -0
  18. package/scripts/forge-brief.py +132 -0
  19. package/scripts/forge-compare.py +11 -1
  20. package/scripts/forge-config.py +176 -9
  21. package/scripts/forge-contract.py +46 -3
  22. package/scripts/forge-control.py +86 -13
  23. package/scripts/forge-dispatch.sh +14 -10
  24. package/scripts/forge-du.py +167 -0
  25. package/scripts/forge-lib-adopt.sh +1 -0
  26. package/scripts/forge-lib-plans.sh +5 -2
  27. package/scripts/forge-lib-review.sh +29 -1
  28. package/scripts/forge-metrics.sh +7 -3
  29. package/scripts/forge-parallel-options.sh +4 -0
  30. package/scripts/forge-parallel.sh +503 -9
  31. package/scripts/forge-prompt.py +120 -0
  32. package/scripts/forge-retro.py +115 -0
  33. package/scripts/forge-runs-compact.py +443 -0
  34. package/scripts/forge-runs-rm.py +2 -0
  35. package/scripts/forge-runs.py +18 -3
  36. package/scripts/forge-schedule.py +279 -4
  37. package/scripts/forge-shadow.py +7 -1
  38. package/scripts/forge-solo.sh +2 -0
  39. package/scripts/forge-summarize.py +698 -0
  40. package/scripts/forge-ui-options.sh +10 -0
  41. package/scripts/forge_brief/__init__.py +587 -0
  42. package/scripts/forge_brief/answers.py +459 -0
  43. package/scripts/forge_dataset/__init__.py +10 -0
  44. package/scripts/forge_dataset/export.py +18 -4
  45. package/scripts/forge_dataset/facts.py +6 -4
  46. package/scripts/forge_dataset/harvest.py +40 -6
  47. package/scripts/forge_dataset/history.py +5 -3
  48. package/scripts/forge_decide/__init__.py +11 -1
  49. package/scripts/forge_locations.py +366 -0
  50. package/scripts/forge_registry.py +19 -0
  51. package/scripts/forge_retro/__init__.py +417 -0
  52. package/scripts/forge_retro/issues.py +1193 -0
  53. package/scripts/forge_retro/report.py +671 -0
  54. package/scripts/forge_side/__init__.py +477 -0
  55. package/scripts/forge_storage.py +515 -0
  56. package/ui/README.md +68 -8
  57. package/ui/docs/api.md +205 -17
  58. package/ui/forge_ui/control.py +92 -11
  59. package/ui/forge_ui/export.py +24 -5
  60. package/ui/forge_ui/links.py +337 -0
  61. package/ui/forge_ui/models.py +57 -4
  62. package/ui/forge_ui/projects.py +4 -1
  63. package/ui/forge_ui/reader.py +661 -30
  64. package/ui/forge_ui/static/app.js +86 -4
  65. package/ui/forge_ui/static/briefview.js +302 -0
  66. package/ui/forge_ui/static/checksview.js +6 -2
  67. package/ui/forge_ui/static/controls.js +5 -0
  68. package/ui/forge_ui/static/index.html +3 -0
  69. package/ui/forge_ui/static/panel.js +268 -2
  70. package/ui/forge_ui/static/runmodel.js +13 -1
  71. package/ui/forge_ui/static/storageview.js +271 -0
  72. package/ui/forge_ui/static/style.css +99 -3
  73. package/ui/forge_ui/static/worktreesview.js +3 -3
  74. package/ui/forge_ui/storage.py +136 -0
  75. package/ui/forge_ui/transcripts.py +35 -10
  76. package/ui/forge_ui/worktrees.py +154 -13
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env python3
2
2
  """The QA contract: one shared review prompt, a severity vocabulary and a deterministic gate.
3
3
 
4
- Three subcommands, stdlib only, no network:
4
+ Subcommands, stdlib only, no network:
5
5
 
6
6
  qa --part head|tail [--kind task|final|solo|sweep] [--threshold P0|P1|P2|P3|none]
7
7
  Prints one piece of the QA prompt. The caller prints everything between and
@@ -10,6 +10,9 @@ Three subcommands, stdlib only, no network:
10
10
  dwarf [--pre-review]
11
11
  Prints the implementer rules block that callers append to the dwarf prompt;
12
12
  --pre-review adds that forge runs the affected tests before the review (#85).
13
+ retro --role dwarf|qa|planner|review
14
+ Prints the retro-note instruction. Most tasks have nothing to say. Only the
15
+ dwarf's text mentions writing .forge/retro-inbox.jsonl when a hard blocker hits.
13
16
  gate --verdict PASS|FAIL|UNKNOWN --qa-last FILE [--threshold Pn|none] [--known-issues OUT]
14
17
  Prints ONE tab-separated line
15
18
  decision <TAB> worst_confirmed <TAB> n_confirmed <TAB> n_unlabelled <TAB> n_below
@@ -60,7 +63,7 @@ recorded in shadow and decide nothing: the gate never reads them, and `split_fac
60
63
  suffix for readers that show the line. A missing or malformed suffix changes nothing.
61
64
 
62
65
  Phantom findings. A reviewer may echo the contract it was given. Three layers keep that
63
- from creating findings or blocking: (1) FORGE_VERDICT, FORGE_LEARNING and FORGE_TESTS text is removed
66
+ from creating findings or blocking: (1) FORGE_VERDICT, FORGE_LEARNING, FORGE_TESTS and FORGE_RETRO text is removed
64
67
  before parsing (the verdict line itself says "CONFIRMED"); (2) any line that is a
65
68
  contiguous fragment of this module's own contract text (all parts, kinds and thresholds,
66
69
  whitespace-collapsed, at least 25 characters, list marker ignored) is removed, which
@@ -306,6 +309,38 @@ _DWARF_PRE_REVIEW = [
306
309
  ]
307
310
 
308
311
 
312
+ # Retro notes (#132). Silence is the default: the task being hard is not a note. Only the
313
+ # dwarf can be blocked before it has a final message, so only that text mentions the inbox.
314
+ RETRO_ROLES = ('dwarf', 'qa', 'planner', 'review')
315
+ _RETRO = [
316
+ 'Most tasks have nothing to report. Write a retro note only for an obstacle that came',
317
+ 'from forge, this machine, or the instructions. The task\'s own difficulty does not',
318
+ 'belong here: a hard task is not a note.',
319
+ 'When you do have one, put it on a line of its own in your final message, as JSON:',
320
+ ' FORGE_RETRO: {"type":"sandbox","fixable_by":"user","summary":"the sandbox blocked git push","evidence":{"command":"git push","exit":128,"error":"fatal: unable to access"},"blocking":true,"tried":"retried the push once"}',
321
+ 'type is one of environment, sandbox, tooling, prompt, forge-bug, other.',
322
+ 'fixable_by is one of user, forge, unsure.',
323
+ 'summary is one line. evidence is the command, its exit code and the error text',
324
+ '(keep the error under 2 KB). blocking is true when you could not finish without it.',
325
+ 'tried is what you did before giving up. Omit the line when there is nothing to say.',
326
+ ]
327
+ _RETRO_INBOX = [
328
+ 'If a hard blocker hits before you can finish, append that same JSON object as one',
329
+ 'line to .forge/retro-inbox.jsonl in this worktree, at that moment. .forge is already',
330
+ 'excluded from diffs and commits.',
331
+ ]
332
+
333
+
334
+ def retro_text(role: str) -> str:
335
+ """The retro-note instruction for one role, newline-terminated."""
336
+ if role not in RETRO_ROLES:
337
+ raise ValueError('role must be one of ' + ', '.join(RETRO_ROLES))
338
+ lines = list(_RETRO)
339
+ if role == 'dwarf':
340
+ lines += [''] + _RETRO_INBOX
341
+ return '\n'.join(lines) + '\n'
342
+
343
+
309
344
  def dwarf_text(pre_review: bool = False, verify_after_merge: bool = False) -> str:
310
345
  """The implementer rules block, newline-terminated."""
311
346
  lines = []
@@ -319,7 +354,7 @@ def dwarf_text(pre_review: bool = False, verify_after_merge: bool = False) -> st
319
354
 
320
355
  # --- parsing ---------------------------------------------------------------------
321
356
 
322
- _PROTOCOL = re.compile(r'FORGE_(?:VERDICT|LEARNING|TESTS):.*$')
357
+ _PROTOCOL = re.compile(r'FORGE_(?:VERDICT|LEARNING|TESTS|RETRO):.*$')
323
358
  _QUOTE = re.compile(r'^\s*(?:>[ \t]?)+')
324
359
  _MARKER = re.compile(r'^(?:[-*+•–]|\d{1,3}[.)]|#{1,6})\s+')
325
360
  _HEADING = re.compile(r'^ {0,3}#{1,6}[ \t]+\S')
@@ -347,6 +382,8 @@ def _contract_flat() -> str:
347
382
  for part in ('head', 'tail'):
348
383
  for threshold in SEVERITIES: # None and `none` render one of these
349
384
  parts.append(qa_text(part, kind, threshold))
385
+ for role in RETRO_ROLES: # an echoed retro instruction is not a finding either
386
+ parts.append(retro_text(role))
350
387
  return _collapse(' '.join(parts))
351
388
 
352
389
 
@@ -567,6 +604,9 @@ def _parser() -> argparse.ArgumentParser:
567
604
  dwarf.add_argument('--pre-review', action='store_true', help='forge runs the affected tests before the review')
568
605
  dwarf.add_argument('--verify-after-merge', action='store_true',
569
606
  help='the run verifies the repository after each merge, so the whole suite is left to it')
607
+ retro = sub.add_parser('retro', help='print the retro-note instruction for one role')
608
+ retro.add_argument('--role', required=True, choices=RETRO_ROLES,
609
+ help='dwarf also hears about .forge/retro-inbox.jsonl')
570
610
  gate_parser = sub.add_parser(
571
611
  'gate', help='print: decision (accept|fail|keep), worst_confirmed, n_confirmed, n_unlabelled, n_below')
572
612
  gate_parser.add_argument('--verdict', required=True, choices=('PASS', 'FAIL', 'UNKNOWN'))
@@ -589,6 +629,9 @@ def main(argv=None) -> int:
589
629
  if args.command == 'dwarf':
590
630
  _emit(dwarf_text(args.pre_review, args.verify_after_merge))
591
631
  return 0
632
+ if args.command == 'retro':
633
+ _emit(retro_text(args.role))
634
+ return 0
592
635
  try:
593
636
  with open(args.qa_last, 'rb') as handle:
594
637
  text = handle.read().decode('utf-8', 'replace')
@@ -8,13 +8,17 @@
8
8
  pre-review-tests
9
9
  (on/off), pre-review-parallel (1-64), max-attempts (0 = no cap;
10
10
  needs --confirm: raising the cap is a person's decision),
11
- converge-window (reviews the non-converging signal looks at)
11
+ converge-window (reviews the non-converging signal looks at),
12
+ summaries (on/off; with --task also inherit; on for a finished run
13
+ also starts `forge summarize` detached, output in summaries.out)
12
14
  pin <plan> <task> <spec> the model the task's next FULL implementer retry uses
13
15
  unpin <plan> <task>
14
16
  retry <plan> <task> [--dwarf SPEC] queue a retry of a stopped or failed task into the live run
15
17
  a NEEDS_DECISION task (reviews that do not converge, or a stop with no
16
18
  stronger model) is resumed only by a decision: --decide retry=N or
17
19
  threshold=P0..P3, or --dwarf SPEC, each with --reason TEXT --approved
20
+ accept <plan> <task> --reason TEXT --approved queue an accept of a FAIL, UNKNOWN or NEEDS_DECISION task into the
21
+ live run: its findings become known issues, it merges, its dependents start
18
22
  add <plan> <task> queue a row added to tasks.tsv (with its prompt.md) into the live run
19
23
  drain <plan> start nothing new; running tasks finish and the scheduler waits
20
24
  while tasks remain (with none left to start, the run ends as usual)
@@ -91,6 +95,7 @@ NEXT_VERIFY = 'at the next verification'
91
95
  NEXT_INFRA_WAIT = 'at the next infrastructure wait'
92
96
  NEXT_INFRA_STOP = 'at the next infrastructure stop'
93
97
  NEXT_DISPATCH = "at the scheduler's next dispatch decision"
98
+ NEXT_CHANGE = "at the task's next change"
94
99
 
95
100
 
96
101
  class Invalid(Exception):
@@ -374,8 +379,9 @@ def task_status(plan, task, strict=False):
374
379
  return words[0] if words else 'PENDING'
375
380
 
376
381
 
377
- def refuse_task(plan, task, pin=False):
378
- if task_status(plan, task, strict=True) == 'MERGED':
382
+ def refuse_task(plan, task, pin=False, merged_ok=False):
383
+ # merged_ok: a switch that changes no run behaviour (summaries) may still be set on a finished task.
384
+ if task_status(plan, task, strict=True) == 'MERGED' and not merged_ok:
379
385
  raise Refused(f'task {task} is MERGED: nothing left to change')
380
386
  if pin and is_fractal(plan):
381
387
  raise Refused('this plan runs under Fractal, which never applies pins')
@@ -564,6 +570,12 @@ def _onoff(value, _task):
564
570
  raise Invalid('needs on or off')
565
571
 
566
572
 
573
+ def _summaries(value, task):
574
+ if value in ('on', 'off') or (task and value == 'inherit'):
575
+ return value
576
+ raise Invalid('needs on or off' + (' (or inherit to drop the override)' if task else ''))
577
+
578
+
567
579
  # key -> (plan only or both, validator, file, live only, when it applies)
568
580
  KEYS = {
569
581
  'qa-threshold': ('both', _qa, 'qa_threshold', False, NEXT_ATTEMPT),
@@ -580,6 +592,7 @@ KEYS = {
580
592
  'pre-review-parallel': ('plan', _parallel, 'pre_review_parallel', False, NEXT_ATTEMPT),
581
593
  'max-attempts': ('plan', _int, 'max_attempts', False, NEXT_DECISION),
582
594
  'converge-window': ('plan', _int, 'converge_window', False, NEXT_DECISION),
595
+ 'summaries': ('both', _summaries, 'summaries', False, NEXT_CHANGE),
583
596
  }
584
597
 
585
598
 
@@ -607,14 +620,15 @@ def audit(plan, actor, action, task, key, value, previous, **extra):
607
620
  return entry
608
621
 
609
622
 
610
- def change(args, plan, rows, action, task, key, work, applies, summary, live_only=False, pin_guard=False):
623
+ def change(args, plan, rows, action, task, key, work, applies, summary, live_only=False, pin_guard=False,
624
+ merged_ok=False):
611
625
  """Run work() -> (value, previous, changed) under the control lock, audit a change, report the result."""
612
626
  with control_lock(plan):
613
627
  probe(plan, 'control.log') # an unsafe log refuses the change instead of leaving it unaudited
614
628
  if live_only and not is_live(plan):
615
629
  raise Refused(f'{key or action} can only change while a run is live (no live scheduler for this plan)')
616
630
  if task:
617
- refuse_task(plan, task, pin_guard)
631
+ refuse_task(plan, task, pin_guard, merged_ok)
618
632
  value, previous, changed = work()
619
633
  if changed: # setting a value it already has, or unpinning nothing, is not a change
620
634
  audit(plan, args.actor, action, task, key, value, previous)
@@ -668,8 +682,28 @@ def cmd_set(args):
668
682
  return value, previous, changed or any(swept)
669
683
 
670
684
  where = f'task {task}' if task else 'the plan'
671
- return change(args, plan, rows, 'set', task, args.key, work, applies,
672
- lambda v: f'set {args.key} {v} on {where}', live_only=live_only)
685
+ done = change(args, plan, rows, 'set', task, args.key, work, applies,
686
+ lambda v: f'set {args.key} {v} on {where}', live_only=live_only,
687
+ merged_ok=args.key == 'summaries')
688
+ if args.key == 'summaries' and value == 'on':
689
+ start_summaries(plan, task)
690
+ return done
691
+
692
+
693
+ def start_summaries(plan, task):
694
+ """A finished run has no scheduler to notice a change: `summaries on` starts `forge summarize` itself,
695
+ detached, its output in summaries.out. A live run's scheduler does it at the next change instead.
696
+ Best effort: the switch is already set."""
697
+ if is_live(plan):
698
+ return
699
+ command = [sys.executable, os.path.join(SKILL, 'scripts', 'forge-summarize.py'), plan]
700
+ if task:
701
+ command += ['--task', task]
702
+ try:
703
+ with open(os.path.join(plan, 'summaries.out'), 'ab') as out:
704
+ subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=out, stderr=out, start_new_session=True)
705
+ except OSError:
706
+ pass
673
707
 
674
708
 
675
709
  def doctor(spec, role='dwarf'):
@@ -804,12 +838,16 @@ def check_row(plan, rows, task):
804
838
  return dwarf, qa
805
839
 
806
840
 
807
- def queue(args, plan, verb, task, dwarf, decision=None):
841
+ def queue(args, plan, verb, task, dwarf, decision=None, accept_reason=None):
808
842
  """Write the request under the control lock, live only; log it with its id.
809
- decision: a retry's (--decide choice or None, reason, approved) for a NEEDS_DECISION task."""
843
+ decision: a retry's (--decide choice or None, reason, approved) for a NEEDS_DECISION task.
844
+ accept_reason: an accept's reason; it is given with --approved (#138)."""
810
845
  with control_lock(plan):
811
846
  probe(plan, 'control.log')
812
847
  if not is_live(plan):
848
+ if verb == 'accept':
849
+ raise Refused(f'accept needs a live run (no live scheduler for this plan); with no run going, accept it '
850
+ f'directly: forge-parallel.sh accept {plan} {task} --reason TEXT --approved')
813
851
  raise Refused(f'{verb} needs a live run (no live scheduler for this plan)')
814
852
  if verb == 'retry':
815
853
  refuse_task(plan, task, pin=True)
@@ -817,8 +855,12 @@ def queue(args, plan, verb, task, dwarf, decision=None):
817
855
  request = dict(verb=verb, task=task, dwarf=dwarf, at=time.time(), actor=args.actor)
818
856
  if decision:
819
857
  request.update(decide=decision[0], reason=decision[1], approved=True)
858
+ extra = {}
859
+ if accept_reason is not None:
860
+ request.update(reason=accept_reason, approved=True)
861
+ extra['reason'] = accept_reason
820
862
  write_atomic(plan, f'{REQUESTS}/{name}', json.dumps(request) + '\n')
821
- audit(plan, args.actor, verb, task, None, dwarf or (decision[0] if decision else None), None, request=name)
863
+ audit(plan, args.actor, verb, task, None, dwarf or (decision[0] if decision else None), None, request=name, **extra)
822
864
  if args.json:
823
865
  json.dump(dict(queued=True, request=name), sys.stdout)
824
866
  sys.stdout.write('\n')
@@ -868,6 +910,29 @@ def cmd_retry(args):
868
910
  return queue(args, plan, 'retry', args.task, dwarf, decision)
869
911
 
870
912
 
913
+ ACCEPTABLE = ('FAIL', 'UNKNOWN', 'NEEDS_DECISION') # what plain `accept` takes: a verdict to override
914
+
915
+
916
+ def cmd_accept(args):
917
+ """Queue an accept into the live run (#138): the scheduler holds the plan lock that plain
918
+ `forge-parallel.sh accept` needs, so it applies the request itself at its next pass."""
919
+ plan, rows = load(args.plan)
920
+ require_task(rows, args.task)
921
+ refuse_task(plan, args.task)
922
+ reason = re.sub(r'\s+', ' ', args.reason or '').strip()
923
+ if not reason:
924
+ raise Invalid('accept needs --reason TEXT: why this work is acceptable despite the reviewer, recorded with the work')
925
+ if len(reason) > 2000:
926
+ raise Invalid('--reason is limited to 2000 characters')
927
+ if not args.approved:
928
+ raise Invalid('accept needs --approved: it overrides the reviewer\'s verdict, and is only given on the user\'s instruction')
929
+ status = task_status(plan, args.task, strict=True)
930
+ if status not in ACCEPTABLE:
931
+ raise Refused(f'task {args.task} is {status}: accept overrides a reviewer\'s verdict, so it takes a FAIL, '
932
+ 'UNKNOWN or NEEDS_DECISION task')
933
+ return queue(args, plan, 'accept', args.task, None, accept_reason=reason)
934
+
935
+
871
936
  def cmd_add(args):
872
937
  plan, rows = load(args.plan)
873
938
  dwarf, qa = check_row(plan, rows, args.task)
@@ -940,7 +1005,7 @@ def cmd_show(args):
940
1005
  def parser():
941
1006
  top = argparse.ArgumentParser(prog='forge control', description="Show and change a plan's live controls.")
942
1007
  sub = top.add_subparsers(dest='command', required=True,
943
- metavar='{show,set,pin,unpin,retry,add,drain,resume,stop}')
1008
+ metavar='{show,set,pin,unpin,retry,accept,add,drain,resume,stop}')
944
1009
 
945
1010
  def common(p, mutator=True):
946
1011
  p.add_argument('plan', metavar='PLAN_DIR', help="the plan dir (the one with tasks.tsv)")
@@ -953,11 +1018,12 @@ def parser():
953
1018
  p.set_defaults(func=cmd_show)
954
1019
  p = sub.add_parser('set', help='change a control', description='Keys: ' + ', '.join(KEYS) + '. '
955
1020
  'retry-budget, infra-retries and max-parallel change only while a run is live. '
956
- 'qa-threshold and retry-budget also take --task (value inherit drops the override; at run level, default drops the file and none means P3).')
1021
+ 'qa-threshold, retry-budget and summaries also take --task (value inherit drops the override; at run level, default drops the file and none means P3). '
1022
+ 'summaries on|off turns generated task summaries on or off; on for a finished run also starts them.')
957
1023
  common(p)
958
1024
  p.add_argument('key', choices=list(KEYS))
959
1025
  p.add_argument('value')
960
- p.add_argument('--task', metavar='ID', help='change this task only (qa-threshold, retry-budget)')
1026
+ p.add_argument('--task', metavar='ID', help='change this task only (qa-threshold, retry-budget, summaries)')
961
1027
  p.add_argument('--confirm', action='store_true', help="max-attempts only: the change is a person's decision")
962
1028
  p.set_defaults(func=cmd_set)
963
1029
  p = sub.add_parser('pin', help="set the model a task's next full retry uses")
@@ -977,6 +1043,13 @@ def parser():
977
1043
  p.add_argument('--reason', metavar='TEXT', help='why (a decision needs it)')
978
1044
  p.add_argument('--approved', action='store_true', help='the decision is the user\'s (a decision needs it)')
979
1045
  p.set_defaults(func=cmd_retry)
1046
+ p = sub.add_parser('accept', help="queue an accept of a FAIL or NEEDS_DECISION task into the live run: "
1047
+ "its findings become known issues and it merges (the user's decision only)")
1048
+ common(p)
1049
+ p.add_argument('task')
1050
+ p.add_argument('--reason', metavar='TEXT', required=False, help='why the work is acceptable despite the reviewer (required)')
1051
+ p.add_argument('--approved', action='store_true', help="the decision is the user's (required)")
1052
+ p.set_defaults(func=cmd_accept)
980
1053
  p = sub.add_parser('add', help='queue a row added to tasks.tsv into the live run')
981
1054
  common(p)
982
1055
  p.add_argument('task')
@@ -13,11 +13,13 @@
13
13
  # (claude, openclaude, codex; custom prompt only)
14
14
  # forge-dispatch.sh dwarf <spec> ... --continue-session <id> continue that implementer session
15
15
  # (claude, openclaude)
16
+ # forge-dispatch.sh side <spec> --prompt-file <f> [--repo <dir>] [--run-dir <d>] [--yolo] [--dry-run]
17
+ # read-only; a brief or summary dispatch (default effort low)
16
18
  # any role: [--no-ripwire] [--ripwire-query-file <requirements>]
17
19
  # any role: [--timeout <seconds>] 0 disables the watchdog
18
20
  # any role: [--service-tier fast] codex and claude only; any other harness exits 3
19
21
  # before it runs. doctor --spec takes the same option.
20
- # forge-dispatch.sh doctor --spec <spec> [--role dwarf|qa|planner] [--service-tier fast]
22
+ # forge-dispatch.sh doctor --spec <spec> [--role dwarf|qa|planner|side] [--service-tier fast]
21
23
  # A measured slowdown is `forge: note: …` on stderr, never in
22
24
  # the resolved block. A plain dispatch does not print it.
23
25
  # forge-dispatch.sh efforts --spec <spec>
@@ -206,14 +208,14 @@ EOT
206
208
  return $rc
207
209
  }
208
210
 
209
- [ $# -ge 1 ] || die "usage: forge-dispatch.sh <doctor|dwarf|qa|planner|efforts> [spec] [options]"
211
+ [ $# -ge 1 ] || die "usage: forge-dispatch.sh <doctor|dwarf|qa|planner|side|efforts> [spec] [options]"
210
212
  if [ "$1" = efforts ]; then shift; efforts_cmd "$@"; exit $?; fi
211
213
  ROLE="$1"; shift
212
214
  if [ "$ROLE" = report ]; then python3 "$RUNTIME" report "${1:?report needs a run directory}"; exit $?; fi
213
215
  PREFLIGHT=0
214
216
  if [ "$ROLE" = doctor ]; then
215
217
  if [ $# = 0 ]; then doctor; exit $?; fi
216
- [ "${1:-}" = --spec ] || die "doctor accepts --spec <spec> [--role dwarf|qa|planner] [--service-tier fast]"
218
+ [ "${1:-}" = --spec ] || die "doctor accepts --spec <spec> [--role dwarf|qa|planner|side] [--service-tier fast]"
217
219
  SPEC_CHECK="${2:?--spec needs a spec}"; shift 2
218
220
  ROLE=dwarf
219
221
  if [ "${1:-}" = --role ]; then ROLE="${2:?}"; shift 2; fi
@@ -223,12 +225,13 @@ if [ "$ROLE" = doctor ]; then
223
225
  echo 'Offline capability check' > "$CHECK_DIR/input"
224
226
  set -- "$SPEC_CHECK" --run-dir "$CHECK_DIR" --prompt-file "$CHECK_DIR/input" "$@"
225
227
  fi
226
- case "$ROLE" in dwarf|qa|planner) ;; *) die "unknown role '$ROLE' (expected dwarf, qa, planner or doctor)" ;; esac
228
+ case "$ROLE" in dwarf|qa|planner|side) ;; *) die "unknown role '$ROLE' (expected dwarf, qa, planner, side or doctor)" ;; esac
227
229
 
228
- # qa and planner both read the repo and write nothing to it: a reviewer that can
229
- # edit the diff is no longer an independent check of it, and a planner that edits
230
- # has quietly become the dwarf. They share one permission profile.
231
- read_only_role() { case "$ROLE" in qa|planner) return 0 ;; *) return 1 ;; esac; }
230
+ # qa, planner and side all read the repo and write nothing to it: a reviewer that
231
+ # can edit the diff is no longer an independent check of it, a planner that edits
232
+ # has quietly become the dwarf, and a side dispatch (a brief or a summary) must
233
+ # not touch the work it is reading. They share one permission profile.
234
+ read_only_role() { case "$ROLE" in qa|planner|side) return 0 ;; *) return 1 ;; esac; }
232
235
  [ $# -ge 1 ] || die "role '$ROLE' needs a spec, e.g. sol:xhigh:openclaude"
233
236
  SPEC="$1"; shift
234
237
 
@@ -330,9 +333,10 @@ else
330
333
  # implementer tends to rubber-stamp, which defeats the point of a second model;
331
334
  # xhigh reviews cost about twice as much for the same verdicts (#89). Planning is
332
335
  # the stage where thinking pays for itself most cheaply — a bad plan is executed
333
- # at full cost by every dwarf downstream of it. forge-parallel.sh's approval
336
+ # at full cost by every dwarf downstream of it. A side dispatch (brief, summary)
337
+ # is a cheap read, so it defaults to low. forge-parallel.sh's approval
334
338
  # table names the QA default (render_table).
335
- case "$ROLE" in dwarf) EFFORT="medium" ;; qa) EFFORT="high" ;; planner) EFFORT="xhigh" ;; esac
339
+ case "$ROLE" in dwarf) EFFORT="medium" ;; qa) EFFORT="high" ;; planner) EFFORT="xhigh" ;; side) EFFORT="low" ;; esac
336
340
  DEFAULTED=1
337
341
  [ -n "$LADDER" ] || EFFORT="" # opencode: no ladder, let the provider choose
338
342
  else
@@ -0,0 +1,167 @@
1
+ #!/usr/bin/env python3
2
+ """forge du [--repo DIR | --all] [--top N] [--json]: what forge takes on disk, and the command that takes each part back (#139).
3
+
4
+ Reports, for the repository at the current directory (its Git top level) unless `--repo` names one, or for
5
+ every repository with `--all`:
6
+
7
+ run dirs each registered run dir: its total, review snapshots, logs (plain and gzipped), other files,
8
+ and what `forge runs compact --logs` would take back
9
+ strays what forge does not create but found inside a run dir (a dependency install, a .git):
10
+ reported, never removed by forge
11
+ worktrees each run's worktree folder (<repo>/../.forge-worktrees/<run id>); forge-ui's Worktrees
12
+ screen has the state of each one and the command that removes it safely
13
+ data home the dataset (kept: it is what forge learns from), its blobs, archives, exports, legacy
14
+
15
+ Sizes are disk usage, as `du` counts it (forge_storage.py has the rules). It reads only, and measuring a
16
+ large tree takes a while: every file is visited. The repository's total is kept for the storage.warn-gb
17
+ check at run start.
18
+
19
+ --json prints {repo, computed, complete, runs, strays, worktrees, data_home, totals, commands}.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import json
25
+ import os
26
+ from pathlib import Path
27
+ import shlex
28
+ import subprocess
29
+ import sys
30
+ import time
31
+
32
+ SKILL = Path(__file__).resolve().parent.parent
33
+ sys.path.insert(0, str(SKILL / 'scripts'))
34
+
35
+ import forge_storage # noqa: E402
36
+ from forge_storage import size_text # noqa: E402
37
+
38
+
39
+ def repo_of(start: Path) -> Path:
40
+ try:
41
+ out = subprocess.run(['git', '-C', str(start), 'rev-parse', '--show-toplevel'], capture_output=True, text=True,
42
+ stdin=subprocess.DEVNULL, timeout=10)
43
+ if out.returncode == 0 and out.stdout.strip():
44
+ return Path(out.stdout.strip()).resolve()
45
+ except (OSError, subprocess.SubprocessError):
46
+ pass
47
+ return start.resolve()
48
+
49
+
50
+ def data_home() -> Path:
51
+ from forge_dataset import data_home
52
+ return data_home()
53
+
54
+
55
+ def commands(result: dict) -> list[dict]:
56
+ """What takes each part back, as text to run: never run here."""
57
+ out = []
58
+ scope = ('--repo ' + shlex.quote(result['repo'])) if result['repo'] else '--all'
59
+ if result['totals']['reclaimable']:
60
+ out.append(dict(label='remove the leftover review snapshots and gzip the log copies (every run stays, and the dataset keeps it)',
61
+ command='forge runs compact %s --logs' % scope, bytes=result['totals']['reclaimable']))
62
+ if result['worktrees']:
63
+ out.append(dict(label='see each worktree\'s state and the command that removes it safely', command='forge ui open',
64
+ bytes=result['totals']['worktrees'], note='then open Worktrees'))
65
+ return out
66
+
67
+
68
+ def age(epoch, now) -> str:
69
+ if epoch is None:
70
+ return '?'
71
+ s = max(0, now - epoch)
72
+ for unit, size in (('d', 86400), ('h', 3600), ('m', 60)):
73
+ if s >= size:
74
+ return '%d%s ago' % (s // size, unit)
75
+ return 'just now'
76
+
77
+
78
+ def print_text(result: dict, top: int) -> None:
79
+ now = time.time()
80
+ t = result['totals']
81
+ where = result['repo'] or 'every repository'
82
+ print('forge du for %s: %s in %d run dir(s), %s in %d worktree folder(s)%s' % (
83
+ where, size_text(t['runs']), len(result['runs']), size_text(t['worktrees']), len(result['worktrees']),
84
+ ', data home %s' % size_text(t['data_home']) if result['data_home'] else ''))
85
+ if t['reclaimable']:
86
+ print(' about %s can be taken back without losing a run: %s in review snapshots, the rest by gzipping logs'
87
+ % (size_text(t['reclaimable']), size_text(t['snapshots'])))
88
+ if not result['complete']:
89
+ print(' (measuring stopped at its time limit: some sizes are lower bounds)')
90
+ if result['runs']:
91
+ shown = result['runs'][:top] if top else result['runs']
92
+ print('\nrun dirs, largest first (%d of %d):' % (len(shown), len(result['runs'])))
93
+ print(' %-28s %9s %10s %9s %9s %12s %12s' % ('run', 'total', 'snapshots', 'logs', 'other', 'not forge\'s', 'reclaimable'))
94
+ for run in shown:
95
+ name = run['run_id'] if len(run['run_id']) <= 28 else run['run_id'][:27] + '…'
96
+ print(' %-28s %9s %10s %9s %9s %12s %12s %s' % (
97
+ name, size_text(run['total']), size_text(run['snapshots']), size_text(run['logs'] + run['gz']),
98
+ size_text(run['other'] + run['fractal']), size_text(run['strays']) if run['strays'] else '-',
99
+ size_text(run['reclaimable']), age(run['updated'], now)))
100
+ print(' %s' % run['path'])
101
+ if result['strays']:
102
+ print('\nnot forge\'s, found inside run dirs (forge never removes these; delete them by hand if you do not need them):')
103
+ for stray in result['strays']:
104
+ print(' %9s %s' % (size_text(stray['bytes']), stray['path']))
105
+ if result['worktrees']:
106
+ shown = result['worktrees'][:top] if top else result['worktrees']
107
+ print('\nworktree folders, largest first (%d of %d):' % (len(shown), len(result['worktrees'])))
108
+ for wt in shown:
109
+ print(' %9s %s' % (size_text(wt['bytes']), wt['path']))
110
+ home = result['data_home']
111
+ if home:
112
+ p = home['parts']
113
+ print('\ndata home %s: %s' % (home['path'], size_text(home['bytes'])))
114
+ print(' dataset %s and blobs %s (kept: what forge learns from); archives %s (forge runs rm); exports %s '
115
+ '(forge dataset export writes them again); legacy %s; other %s'
116
+ % (size_text(p['dataset']), size_text(p['blobs']), size_text(p['archive']), size_text(p['exports']),
117
+ size_text(p['legacy']), size_text(p['storage'] + p['other'])))
118
+ if result['commands']:
119
+ print('\nto take space back:')
120
+ for c in result['commands']:
121
+ print(' %s%s\n %s' % (c['command'], (' (' + c['note'] + ')') if c.get('note') else '', c['label']))
122
+
123
+
124
+ def main(argv=None) -> int:
125
+ parser = argparse.ArgumentParser(prog='forge du', description='What forge takes on disk: run dirs, worktrees and its data '
126
+ 'home, and the command that takes each part back. Reads only.')
127
+ which = parser.add_mutually_exclusive_group()
128
+ which.add_argument('--repo', type=Path, metavar='DIR', help='the repository (default: the Git top level of the current directory)')
129
+ which.add_argument('--all', action='store_true', help='every repository forge has runs for')
130
+ parser.add_argument('--top', type=int, default=10, metavar='N', help='list the N largest run dirs and worktree folders (default 10; 0: all)')
131
+ parser.add_argument('--json', action='store_true', help='print one JSON object, for scripts and agents')
132
+ args = parser.parse_args(sys.argv[1:] if argv is None else argv)
133
+ if args.top < 0:
134
+ parser.error('--top must be 0 or more')
135
+ if args.repo is not None and not args.repo.is_dir():
136
+ parser.error('--repo: no such directory: %s' % args.repo)
137
+ repo = None if args.all else repo_of(args.repo if args.repo is not None else Path.cwd())
138
+ import forge_locations
139
+ forge_locations.ensure_imported() # once: what the run registry and the disk already hold
140
+ home = data_home()
141
+ tty = not args.json and sys.stderr.isatty()
142
+
143
+ def progress(index, count, _path):
144
+ if tty:
145
+ sys.stderr.write('\rmeasuring run dir %d of %d…' % (index + 1, count))
146
+ sys.stderr.flush()
147
+
148
+ result = forge_storage.report(repo, home=home, progress=progress)
149
+ if tty:
150
+ sys.stderr.write('\r\033[K')
151
+ result['commands'] = commands(result)
152
+ forge_storage.save_footprints(home, forge_storage.footprints_of(result))
153
+ if args.json:
154
+ json.dump(result, sys.stdout, indent=2)
155
+ sys.stdout.write('\n')
156
+ return 0
157
+ if not result['runs'] and not result['worktrees']:
158
+ print('forge du: no registered runs for %s' % (repo or 'any repository'))
159
+ if result['data_home']:
160
+ print('data home %s: %s' % (result['data_home']['path'], size_text(result['data_home']['bytes'])))
161
+ return 0
162
+ print_text(result, args.top)
163
+ return 0
164
+
165
+
166
+ if __name__ == '__main__':
167
+ sys.exit(main())
@@ -129,6 +129,7 @@ do_adopt() {
129
129
  tip="$(git -C "$int_wt" rev-parse HEAD)"
130
130
 
131
131
  local review="$out/review" thr verdict gate_line decision kept inline=1 vcmd
132
+ FORGE_REVIEW_SNAPSHOT="$review" # the EXIT trap of forge-parallel.sh removes it on every exit (#139)
132
133
  forge_review_snapshot "$int_wt" "$base" "$tip" "$review" > "$out/snapshot.log" 2>&1 \
133
134
  || { adopt_rollback; die "adopt: cannot build the review snapshot (see $out/snapshot.log)" 3; }
134
135
  forge_review_deps "$int_wt" "$review" "$out/review.deps"
@@ -130,7 +130,7 @@ plans_make_integration() { # plans_make_integration <repo> <branch> <commit> <wt
130
130
 
131
131
  # Per-plan option files carried to a derived plan. The cost-bearing choices a user made
132
132
  # for this plan apply to the plan made from it; `planner` does not (nothing plans again).
133
- PLANS_OPTION_FILES="no_ripwire no_memory yolo_dwarf yolo_qa reviewer_session implementer_session fast pre_review_tests pre_review_parallel qa_threshold timeout verify_retries verify_cmd verify_parallel setup_cmd final_qa shadow_qa shadow_rate explore escalate_after fractal-routing.json fractal-selection.json jev-selection.json profile.json routed.json"
133
+ PLANS_OPTION_FILES="no_ripwire no_memory yolo_dwarf yolo_qa reviewer_session implementer_session fast pre_review_tests pre_review_parallel qa_threshold timeout verify_retries verify_cmd verify_parallel setup_cmd final_qa shadow_qa shadow_rate explore escalate_after fractal-routing.json fractal-selection.json jev-selection.json profile.json routed.json retro_mode brief brief_scope brief_model summaries summaries_model"
134
134
 
135
135
  # --- accept ---------------------------------------------------------------------
136
136
  # A reviewer's FAIL is the QA gate; overriding it is the user's call and never forge's or
@@ -267,6 +267,8 @@ do_accept() {
267
267
  echo "attempt=$attempt"
268
268
  echo "reviewed_commit=$sha"
269
269
  [ "${gdec:-}" != fail ] || echo "gate=fail"
270
+ # Through forge control on a live run: who asked (ui or cli), as control.log has it (#138).
271
+ [ -z "${FORGE_ACCEPT_ACTOR:-}" ] || echo "actor=$FORGE_ACCEPT_ACTOR"
270
272
  } > "$tdir/accepted.by"
271
273
  echo PASS > "$tdir/status"
272
274
 
@@ -283,7 +285,8 @@ do_accept() {
283
285
  write_results "$PLAN"
284
286
  echo "$id accepted by a human and merged"
285
287
  echo "known issues recorded in $ki"
286
- if [ "$(awk -F'\t' '$2!="MERGED" {n++} END {print n+0}' "$PLAN/results.tsv")" -gt 0 ]; then
288
+ # A live run starts the tasks that waited on it by itself.
289
+ if [ -z "${FORGE_ACCEPT_LIVE:-}" ] && [ "$(awk -F'\t' '$2!="MERGED" {n++} END {print n+0}' "$PLAN/results.tsv")" -gt 0 ]; then
287
290
  echo "tasks that were waiting on it are unchanged; continue with: forge-parallel.sh run $PLAN"
288
291
  fi
289
292
  return 0