@giamme/forge 0.16.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 (95) hide show
  1. package/CHANGELOG.md +43 -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 +13 -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/reviews.md +15 -1
  11. package/docs/safety.md +8 -0
  12. package/forge +24 -1
  13. package/package.json +1 -1
  14. package/references/dataset.md +143 -5
  15. package/references/decision-models.md +15 -2
  16. package/references/decompose.md +180 -11
  17. package/references/planning.md +3 -2
  18. package/references/solo.md +2 -1
  19. package/references/ui.md +5 -2
  20. package/scripts/forge-artifact.sh +14 -0
  21. package/scripts/forge-brief.py +132 -0
  22. package/scripts/forge-compare.py +11 -1
  23. package/scripts/forge-config.py +176 -9
  24. package/scripts/forge-contract.py +98 -4
  25. package/scripts/forge-control.py +86 -13
  26. package/scripts/forge-dispatch.sh +14 -10
  27. package/scripts/forge-du.py +167 -0
  28. package/scripts/forge-issues.py +4 -3
  29. package/scripts/forge-ledger.py +3 -1
  30. package/scripts/forge-lib-adopt.sh +8 -1
  31. package/scripts/forge-lib-plans.sh +5 -2
  32. package/scripts/forge-lib-review.sh +29 -1
  33. package/scripts/forge-metrics.sh +29 -3
  34. package/scripts/forge-parallel-options.sh +4 -0
  35. package/scripts/forge-parallel.sh +506 -10
  36. package/scripts/forge-plan-check.py +25 -2
  37. package/scripts/forge-planner.py +20 -6
  38. package/scripts/forge-prompt.py +120 -0
  39. package/scripts/forge-retro.py +115 -0
  40. package/scripts/forge-runs-compact.py +443 -0
  41. package/scripts/forge-runs-rm.py +2 -0
  42. package/scripts/forge-runs.py +18 -3
  43. package/scripts/forge-schedule.py +279 -4
  44. package/scripts/forge-shadow.py +35 -10
  45. package/scripts/forge-solo.sh +2 -0
  46. package/scripts/forge-summarize.py +698 -0
  47. package/scripts/forge-sweep.py +25 -10
  48. package/scripts/forge-ui-options.sh +10 -0
  49. package/scripts/forge_brief/__init__.py +587 -0
  50. package/scripts/forge_brief/answers.py +459 -0
  51. package/scripts/forge_dataset/__init__.py +10 -0
  52. package/scripts/forge_dataset/cli.py +83 -0
  53. package/scripts/forge_dataset/export.py +18 -4
  54. package/scripts/forge_dataset/facts.py +280 -0
  55. package/scripts/forge_dataset/harvest.py +56 -9
  56. package/scripts/forge_dataset/history.py +5 -3
  57. package/scripts/forge_dataset/outcomes.py +206 -58
  58. package/scripts/forge_dataset/pairs.py +174 -0
  59. package/scripts/forge_dataset/risk.py +108 -0
  60. package/scripts/forge_dataset/tiers.py +427 -0
  61. package/scripts/forge_decide/__init__.py +11 -1
  62. package/scripts/forge_decide/cli.py +23 -2
  63. package/scripts/forge_decide/labels.py +30 -6
  64. package/scripts/forge_decide/replay.py +10 -4
  65. package/scripts/forge_locations.py +366 -0
  66. package/scripts/forge_registry.py +19 -0
  67. package/scripts/forge_retro/__init__.py +417 -0
  68. package/scripts/forge_retro/issues.py +1193 -0
  69. package/scripts/forge_retro/report.py +671 -0
  70. package/scripts/forge_side/__init__.py +477 -0
  71. package/scripts/forge_storage.py +515 -0
  72. package/ui/README.md +68 -8
  73. package/ui/docs/api.md +217 -20
  74. package/ui/forge_ui/control.py +92 -11
  75. package/ui/forge_ui/export.py +31 -5
  76. package/ui/forge_ui/findings.py +4 -2
  77. package/ui/forge_ui/links.py +337 -0
  78. package/ui/forge_ui/models.py +57 -4
  79. package/ui/forge_ui/projects.py +4 -1
  80. package/ui/forge_ui/reader.py +732 -34
  81. package/ui/forge_ui/server.py +8 -0
  82. package/ui/forge_ui/static/app.js +92 -5
  83. package/ui/forge_ui/static/briefview.js +302 -0
  84. package/ui/forge_ui/static/checksview.js +6 -2
  85. package/ui/forge_ui/static/controls.js +5 -0
  86. package/ui/forge_ui/static/diffview.js +7 -3
  87. package/ui/forge_ui/static/index.html +3 -0
  88. package/ui/forge_ui/static/panel.js +311 -4
  89. package/ui/forge_ui/static/runmodel.js +13 -1
  90. package/ui/forge_ui/static/storageview.js +271 -0
  91. package/ui/forge_ui/static/style.css +100 -3
  92. package/ui/forge_ui/static/worktreesview.js +3 -3
  93. package/ui/forge_ui/storage.py +136 -0
  94. package/ui/forge_ui/transcripts.py +35 -10
  95. package/ui/forge_ui/worktrees.py +154 -13
@@ -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())
@@ -189,6 +189,7 @@ def clean_markdown(text):
189
189
  def parse_findings(text):
190
190
  out = []
191
191
  for m in FINDING_RE.finditer(text or ""):
192
+ said = contract().split_facts(m.group(4))[0].rstrip() # #119: the facts suffix is no part of the title
192
193
  loc = m.group(3).strip()
193
194
  link = re.fullmatch(r"\[([^\]]+)\]\([^)]*\)", loc)
194
195
  loc = (link.group(1) if link else loc).strip("` ")
@@ -196,8 +197,8 @@ def parse_findings(text):
196
197
  # `:442,674`, a range then a note): the path runs to its first `:<digit>`, the line is that number.
197
198
  lm = re.match(r"(.+?):(\d+)(?:[-:]\d+)?$", loc) or re.match(r"([^\s,;()]+?):(\d+)(?=[-:,;\s(]|$)", loc)
198
199
  out.append({"severity": m.group(1), "confidence": m.group(2), "file": lm.group(1) if lm else loc,
199
- "line": int(lm.group(2)) if lm else None, "text": clean_markdown(m.group(4)),
200
- "raw": f"[{m.group(1)}][{m.group(2)}] {loc} — {m.group(4).strip()}"})
200
+ "line": int(lm.group(2)) if lm else None, "text": clean_markdown(said),
201
+ "raw": f"[{m.group(1)}][{m.group(2)}] {loc} — {said.strip()}"})
201
202
  return out
202
203
 
203
204
 
@@ -230,7 +231,7 @@ def parse_known(text):
230
231
  if canonical:
231
232
  out.append(canonical[0])
232
233
  continue
233
- body = _BULLET_RE.sub("", first, count=1)
234
+ body = _BULLET_RE.sub("", contract().split_facts(first)[0], count=1)
234
235
  lm = _LOCATION_RE.search(body)
235
236
  if lm:
236
237
  file, line = lm.group(1).strip("`*"), int(lm.group(2))
@@ -80,7 +80,9 @@ def _is_file(path: str) -> bool:
80
80
 
81
81
 
82
82
  def _words(finding) -> set:
83
- return set(_WORD.findall(finding.text.lower()))
83
+ # #119: the facts suffix's words (reach, origin, evidence, ...) would make any two findings look alike
84
+ text = '\n'.join(contract.split_facts(line)[0] for line in finding.text.split('\n'))
85
+ return set(_WORD.findall(text.lower()))
84
86
 
85
87
 
86
88
  def same_finding(a, b) -> bool:
@@ -128,7 +128,8 @@ do_adopt() {
128
128
  fi
129
129
  tip="$(git -C "$int_wt" rev-parse HEAD)"
130
130
 
131
- local review="$out/review" thr verdict gate_line decision kept inline=1
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"
@@ -146,6 +147,12 @@ do_adopt() {
146
147
  echo
147
148
  cat "$out/review.deps"
148
149
  echo "Forge ran no tests of its own on this range, so nothing here stands in for yours."
150
+ # The run's verification, named and not run: it runs after this review, on the whole branch (#131).
151
+ vcmd="$(verify_command_for "$PLAN" "$(cat "$PLAN/repo")" | head -c 4000)"
152
+ if [ -n "$vcmd" ]; then
153
+ echo "The run verifies its integration branch with the command below, after this review. Run the parts of it that touch this range:"
154
+ echo '```sh'; printf '%s\n' "$vcmd"; echo '```'
155
+ fi
149
156
  echo
150
157
  python3 "$SKILL_DIR/scripts/forge-contract.py" qa --part tail --kind adopt --threshold "$thr"
151
158
  echo
@@ -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
@@ -26,7 +26,8 @@
26
26
  # qa.out, verdict (PASS | FAIL | UNKNOWN | INVALIDATED | ACCEPTED; absent when nothing was
27
27
  # judged), qa.gate and known_issues.md (with a threshold), qa.infra (infrastructure stop),
28
28
  # review.meta, context.md, notes.md, tasks.summary, combined.diff (when inlined),
29
- # source/review.fingerprint and review-<pid>/ (the disposable checkout the reviewer ran in).
29
+ # source/review.fingerprint and review-<pid>/ (the disposable checkout the reviewer ran in, removed
30
+ # when the review ends; FORGE_KEEP_SNAPSHOTS=1 keeps it).
30
31
  # `review` also keeps $PLAN/final-review (a link to the newest directory) and
31
32
  # $PLAN/final-review.verdict (a copy of its verdict).
32
33
  #
@@ -357,7 +358,19 @@ PY
357
358
  # src is a repository or worktree that contains both revisions; it is also the checkout
358
359
  # whose fingerprint must not change while the reviewer runs. Never uses `die`/`exit`:
359
360
  # it is called from inside do_integrate.
361
+ # The review snapshot goes once the review is over, on every return (#139). A signal that ends the
362
+ # process first leaves it, and the next final review of the plan removes it: they hold the plan's
363
+ # lock, so one runs at a time and any snapshot already there is an interrupted one's.
360
364
  final_review() {
365
+ local final_rc
366
+ FINAL_REVIEW_SNAPSHOT=""
367
+ final_review_body "$@"; final_rc=$?
368
+ forge_drop_snapshot "$FINAL_REVIEW_SNAPSHOT"
369
+ FINAL_REVIEW_SNAPSHOT=""
370
+ return "$final_rc"
371
+ }
372
+
373
+ final_review_body() {
361
374
  local plan="$1" base="$2" tip="$3" src="$4" out="$5" spec="$6" yolo="${7:-}"
362
375
  local review n rc verdict thr gate_line gate_forced source_fp review_fp vdir tflag="" inline=1 diff_n ft
363
376
  local plan_real prev="" prev_rel=none prev_tip="" since=none integration="" prev_note=""
@@ -391,8 +404,13 @@ final_review() {
391
404
 
392
405
  # `forge_review_snapshot` writes review.base beside the snapshot, so it gets a directory
393
406
  # of its own under the artifact dir.
407
+ local stale
408
+ for stale in "$out"/review-* "$plan"/final-review*/review-* "$plan"/integrate-*/final-review/review-*; do
409
+ [ -d "$stale/.git" ] && forge_drop_snapshot "$stale"
410
+ done
394
411
  review="$out/review-$$"; n=0
395
412
  while [ -e "$review" ]; do n=$((n+1)); review="$out/review-$$-$n"; done
413
+ FINAL_REVIEW_SNAPSHOT="$review"
396
414
  forge_review_snapshot "$src" "$base" "$tip" "$review" > "$out/snapshot.log" 2>&1 ||
397
415
  { note "final review: cannot build the review snapshot (see $out/snapshot.log)"; return 3; }
398
416
  forge_review_deps "$src" "$review" "$out/review.deps"
@@ -482,6 +500,9 @@ final_review() {
482
500
  echo " git diff HEAD~1 HEAD -- . ':(exclude).forge'"
483
501
  echo "(and 'git diff --stat HEAD~1 HEAD' for the overview)."
484
502
  fi
503
+ # Last. A shadow of a task review copies qa.input itself; this prompt is the final
504
+ # review's, and nothing copies it onward. Off prints nothing.
505
+ forge_retro_prompt "$plan" review
485
506
  } > "$out/qa.input"
486
507
 
487
508
  [ -s "$plan/timeout" ] && tflag="--timeout $(cat "$plan/timeout")"
@@ -516,12 +537,19 @@ final_review() {
516
537
  fi
517
538
  rs_mode=fresh
518
539
  mv "$out/qa.out" "$out/qa.continue.out" 2>/dev/null || true
540
+ # The fresh dispatch deletes qa.last and qa.log as it starts. Record the continuation
541
+ # first; a failure to record does not change rc, which the fresh dispatch sets next.
542
+ forge_retro_record "$plan" qa "$out"
519
543
  FORGE_CAPABILITY_CACHE="${FORGE_CAPABILITY_CACHE:-$plan/capabilities}" \
520
544
  "${qa_cmd[@]}" > "$out/qa.out" 2>&1
521
545
  rc=$?
522
546
  fi
523
547
  [ ! -f "$plan/reviewer_session" ] || { echo "session=$rs_mode"; echo "session_reason=$rs_reason"; } >> "$out/review.meta"
524
548
  if [ "${FORGE_OUTPUT:-summary}" = full ]; then cat "$out/qa.out"; fi
549
+ # The dispatch role is qa, so the notes are in qa.last. No task: this is the whole run.
550
+ # Record and the regenerated report never change rc; the case below still decides it.
551
+ forge_retro_record "$plan" qa "$out"
552
+ forge_retro_report "$plan"
525
553
  case "$rc" in
526
554
  0) ;;
527
555
  8) note "final review: the reviewer hit an infrastructure failure; nothing was judged"