@giamme/forge 0.17.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 (110) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +32 -5
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +33 -1
  6. package/docs/commands.md +147 -16
  7. package/docs/dataset.md +5 -0
  8. package/docs/decomposed-runs.md +122 -1
  9. package/docs/development.md +2 -1
  10. package/docs/forge-ui.md +98 -8
  11. package/docs/memory.md +27 -4
  12. package/docs/models.md +8 -0
  13. package/docs/reviews.md +122 -0
  14. package/docs/safety.md +8 -0
  15. package/forge +44 -4
  16. package/package.json +2 -1
  17. package/references/dataset.md +39 -1
  18. package/references/decompose.md +737 -16
  19. package/references/harnesses.md +18 -3
  20. package/references/planning.md +43 -14
  21. package/references/solo.md +2 -1
  22. package/references/ui.md +56 -6
  23. package/registry.tsv +8 -3
  24. package/scripts/forge-artifact.sh +14 -0
  25. package/scripts/forge-brief.py +217 -0
  26. package/scripts/forge-compare.py +13 -2
  27. package/scripts/forge-config.py +176 -9
  28. package/scripts/forge-contract.py +246 -28
  29. package/scripts/forge-control.py +200 -15
  30. package/scripts/forge-dispatch.sh +48 -15
  31. package/scripts/forge-du.py +167 -0
  32. package/scripts/forge-group.py +496 -0
  33. package/scripts/forge-groups.py +89 -0
  34. package/scripts/forge-handoff.py +1128 -0
  35. package/scripts/forge-lib-adopt.sh +1 -0
  36. package/scripts/forge-lib-group.sh +641 -0
  37. package/scripts/forge-lib-plans.sh +343 -4
  38. package/scripts/forge-lib-review.sh +29 -1
  39. package/scripts/forge-lib-task.sh +197 -4
  40. package/scripts/forge-memory.sh +245 -3
  41. package/scripts/forge-metrics.sh +7 -3
  42. package/scripts/forge-parallel-options.sh +4 -0
  43. package/scripts/forge-parallel.sh +1216 -41
  44. package/scripts/forge-planner.py +104 -8
  45. package/scripts/forge-prompt.py +120 -0
  46. package/scripts/forge-retro.py +115 -0
  47. package/scripts/forge-route.py +190 -12
  48. package/scripts/forge-runs-compact.py +443 -0
  49. package/scripts/forge-runs-rm.py +2 -0
  50. package/scripts/forge-runs.py +27 -8
  51. package/scripts/forge-schedule.py +633 -49
  52. package/scripts/forge-shadow.py +7 -1
  53. package/scripts/forge-solo.sh +4 -0
  54. package/scripts/forge-summarize.py +698 -0
  55. package/scripts/forge-ui-options.sh +10 -0
  56. package/scripts/forge-worktrees.py +243 -0
  57. package/scripts/forge_brief/__init__.py +831 -0
  58. package/scripts/forge_brief/answers.py +506 -0
  59. package/scripts/forge_brief/proposals.py +1630 -0
  60. package/scripts/forge_dataset/__init__.py +10 -0
  61. package/scripts/forge_dataset/efforts.py +4 -3
  62. package/scripts/forge_dataset/export.py +36 -10
  63. package/scripts/forge_dataset/facts.py +8 -4
  64. package/scripts/forge_dataset/forecast.py +8 -18
  65. package/scripts/forge_dataset/harvest.py +241 -12
  66. package/scripts/forge_dataset/history.py +13 -6
  67. package/scripts/forge_dataset/importer.py +65 -1
  68. package/scripts/forge_dataset/names.py +66 -0
  69. package/scripts/forge_dataset/reviewers.py +5 -2
  70. package/scripts/forge_dataset/risk.py +6 -3
  71. package/scripts/forge_dataset/routing.py +6 -1
  72. package/scripts/forge_decide/__init__.py +11 -1
  73. package/scripts/forge_groups/__init__.py +308 -0
  74. package/scripts/forge_groups/attribute.py +289 -0
  75. package/scripts/forge_groups/review.py +286 -0
  76. package/scripts/forge_locations.py +366 -0
  77. package/scripts/forge_owner.py +152 -0
  78. package/scripts/forge_registry.py +19 -0
  79. package/scripts/forge_retro/__init__.py +417 -0
  80. package/scripts/forge_retro/issues.py +1193 -0
  81. package/scripts/forge_retro/report.py +671 -0
  82. package/scripts/forge_side/__init__.py +482 -0
  83. package/scripts/forge_storage.py +515 -0
  84. package/ui/README.md +68 -8
  85. package/ui/docs/api.md +375 -31
  86. package/ui/forge_ui/control.py +451 -11
  87. package/ui/forge_ui/executions.py +8 -1
  88. package/ui/forge_ui/export.py +53 -7
  89. package/ui/forge_ui/groups.py +264 -0
  90. package/ui/forge_ui/links.py +337 -0
  91. package/ui/forge_ui/models.py +125 -10
  92. package/ui/forge_ui/projects.py +4 -1
  93. package/ui/forge_ui/reader.py +919 -45
  94. package/ui/forge_ui/server.py +4 -0
  95. package/ui/forge_ui/static/app.js +173 -11
  96. package/ui/forge_ui/static/briefview.js +605 -0
  97. package/ui/forge_ui/static/checksview.js +6 -2
  98. package/ui/forge_ui/static/controls.js +5 -0
  99. package/ui/forge_ui/static/diffview.js +86 -1
  100. package/ui/forge_ui/static/groupsview.js +332 -0
  101. package/ui/forge_ui/static/index.html +4 -0
  102. package/ui/forge_ui/static/panel.js +394 -8
  103. package/ui/forge_ui/static/projectsview.js +189 -10
  104. package/ui/forge_ui/static/runmodel.js +27 -4
  105. package/ui/forge_ui/static/storageview.js +352 -0
  106. package/ui/forge_ui/static/style.css +176 -6
  107. package/ui/forge_ui/static/worktreesview.js +235 -14
  108. package/ui/forge_ui/storage.py +150 -0
  109. package/ui/forge_ui/transcripts.py +35 -10
  110. package/ui/forge_ui/worktrees.py +154 -13
@@ -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())
@@ -0,0 +1,496 @@
1
+ #!/usr/bin/env python3
2
+ """Show a plan's task groups, retry a review=group group, and set a group's title or goal.
3
+
4
+ show PLAN [--group GID] [--json]
5
+ Every group in groups.tsv order: id, review scope, reviewer (qa), title, goal,
6
+ and each member with its status. A review=group group also reports its round,
7
+ status, the implicated tasks of the last round, the first line of decision.md
8
+ when the status is NEEDS_DECISION, and whether the group has merged.
9
+ Reads only. Works on a live run and on a finished one.
10
+ retry PLAN GID [--tasks a,b] [--reason TEXT]
11
+ Only a review=group group.
12
+ NEEDS_DECISION / ambiguous: --tasks is required. Runs _group_settle --tasks,
13
+ which makes those members FAIL, then says how the next run retries them.
14
+ A live scheduler picks the FAIL tasks up on its sweep when they have budget left.
15
+ NEEDS_DECISION / oversized: refused. Split the group in groups.tsv and run plan again.
16
+ UNKNOWN, INFRA, TIMEOUT, INTERRUPTED, ERROR: the group status becomes INTERRUPTED,
17
+ so the next run reviews it again. No member attempt is spent.
18
+ Anything else (PASS, merged, FAIL, WAITING, CONFLICT, ...) is refused.
19
+
20
+ set PLAN GID [--title TEXT] [--goal TEXT] [--reason TEXT]
21
+ Rewrite a group's title or goal in groups.tsv and freeze the groups again, under the
22
+ control lock, logged in control.log (actor cli). One line each; an empty value means none
23
+ (`-`). Refused (exit 3) when groups.tsv or a member's deps or files already differ from
24
+ what plan froze: freezing again would accept those edits too, so run plan again. Works
25
+ on a live run: title and goal change no membership, and the next prompt that names the
26
+ group (a group review, a brief) uses the new text.
27
+
28
+ Exit codes: 0 ok, 2 usage or an unknown group or task, 3 refused (no groups.tsv on show,
29
+ a state this command does not retry, groups changed since plan, the control lock busy).
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import argparse
34
+ import importlib.util
35
+ import json
36
+ import os
37
+ import re
38
+ import shlex
39
+ import subprocess
40
+ import sys
41
+ from pathlib import Path
42
+
43
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
44
+ import forge_groups # noqa: E402
45
+
46
+ SCRIPTS = Path(__file__).resolve().parent
47
+ PARALLEL = SCRIPTS / 'forge-parallel.sh'
48
+ REARM = ('UNKNOWN', 'INFRA', 'TIMEOUT', 'INTERRUPTED', 'ERROR')
49
+ REASON_LIMIT = 2000
50
+ TEXT_LIMIT = 500
51
+
52
+ _CONTROL = None
53
+ _SWEEP_EVERY = None
54
+
55
+
56
+ class Usage(Exception):
57
+ """Bad invocation or an unknown group or task. Exit 2."""
58
+
59
+
60
+ class Refused(Exception):
61
+ """A well-formed request the group's state does not allow. Exit 3."""
62
+
63
+
64
+ class SettleFailed(Exception):
65
+ """_group_settle refused or failed. Its exit code is the command's."""
66
+
67
+ def __init__(self, code: int):
68
+ super().__init__(code)
69
+ self.code = code
70
+
71
+
72
+ class Parser(argparse.ArgumentParser):
73
+ def error(self, message):
74
+ sys.stderr.write(f'forge group: {message}\n')
75
+ raise SystemExit(2)
76
+
77
+
78
+ def control():
79
+ """forge-control.py, loaded once. `audit` and `control_lock` are the writers to reuse."""
80
+ global _CONTROL
81
+ if _CONTROL is None:
82
+ spec = importlib.util.spec_from_file_location('forge_control_cli', SCRIPTS / 'forge-control.py')
83
+ module = importlib.util.module_from_spec(spec)
84
+ spec.loader.exec_module(module)
85
+ _CONTROL = module
86
+ return _CONTROL
87
+
88
+
89
+ def sweep_every() -> float:
90
+ """forge-schedule.py's SWEEP_EVERY: seconds between looks at tasks that already ended FAIL."""
91
+ global _SWEEP_EVERY
92
+ if _SWEEP_EVERY is None:
93
+ spec = importlib.util.spec_from_file_location('forge_schedule_cli', SCRIPTS / 'forge-schedule.py')
94
+ module = importlib.util.module_from_spec(spec)
95
+ spec.loader.exec_module(module)
96
+ _SWEEP_EVERY = float(module.SWEEP_EVERY)
97
+ return _SWEEP_EVERY
98
+
99
+
100
+ def parser() -> argparse.ArgumentParser:
101
+ top = Parser(prog='forge group', description="Show a plan's task groups, and retry a review=group group.")
102
+ sub = top.add_subparsers(dest='command', required=True, parser_class=Parser)
103
+ show = sub.add_parser('show', help='every group, its members and, for a review group, its round')
104
+ show.add_argument('plan', help='the plan directory')
105
+ show.add_argument('--group', metavar='GID', help='only this group')
106
+ show.add_argument('--json', action='store_true', help='print a JSON list')
107
+ retry = sub.add_parser('retry', help='answer an ambiguous group decision, or re-arm a review that did not finish')
108
+ retry.add_argument('plan', help='the plan directory')
109
+ retry.add_argument('gid', help='the group id')
110
+ retry.add_argument('--tasks', help='comma list of member tasks; required when the decision is ambiguous')
111
+ retry.add_argument('--reason', help="why, recorded in the plan's control.log (actor cli)")
112
+ setter = sub.add_parser('set', help="a group's title or goal, then the groups frozen again")
113
+ setter.add_argument('plan', help='the plan directory')
114
+ setter.add_argument('gid', help='the group id')
115
+ setter.add_argument('--title', help='one line; empty for none')
116
+ setter.add_argument('--goal', help='one line: what the group is for; empty for none')
117
+ setter.add_argument('--reason', help="why, recorded in the plan's control.log (actor cli)")
118
+ return top
119
+
120
+
121
+ def plan_dir(path: str) -> str:
122
+ return os.path.realpath(path)
123
+
124
+
125
+ def read_text(path: Path) -> str | None:
126
+ try:
127
+ return path.read_text(encoding='utf-8', errors='replace')
128
+ except OSError:
129
+ return None
130
+
131
+
132
+ def member_status(plan, task: str) -> str:
133
+ """The task's status. `merged` wins over the status file, as task_status does."""
134
+ tdir = Path(plan) / 'tasks' / task
135
+ if (tdir / 'merged').is_file():
136
+ return 'MERGED'
137
+ words = (read_text(tdir / 'status') or '').split()
138
+ return words[0] if words else 'PENDING'
139
+
140
+
141
+ def group_status(plan, gid: str) -> str | None:
142
+ words = (read_text(Path(plan) / 'groups' / gid / 'status') or '').split()
143
+ return words[0] if words else None
144
+
145
+
146
+ def group_merged(plan, gid: str) -> bool:
147
+ return (Path(plan) / 'groups' / gid / 'merged').is_file()
148
+
149
+
150
+ def last_round_row(plan, gid: str) -> list | None:
151
+ text = read_text(Path(plan) / 'groups' / gid / 'rounds.tsv')
152
+ if text is None:
153
+ return None
154
+ last = None
155
+ for line in text.splitlines():
156
+ if line.strip() and not line.startswith('#'):
157
+ last = line.split('\t')
158
+ return last
159
+
160
+
161
+ def group_round(plan, gid: str, row: list | None) -> int | None:
162
+ digits = ''.join(ch for ch in (read_text(Path(plan) / 'groups' / gid / 'round') or '') if ch.isdigit())
163
+ if digits:
164
+ return int(digits)
165
+ if row and row[0].isdigit():
166
+ return int(row[0])
167
+ return None
168
+
169
+
170
+ def implicated_of(row: list | None) -> list:
171
+ if not row or len(row) < 4 or row[3].strip() in ('', '-'):
172
+ return []
173
+ return [task for task in (part.strip() for part in row[3].split(',')) if task and task != '-']
174
+
175
+
176
+ def decision_line(plan, gid: str) -> str | None:
177
+ text = read_text(Path(plan) / 'groups' / gid / 'decision.md')
178
+ if text is None:
179
+ return None
180
+ for line in text.splitlines():
181
+ if line.strip():
182
+ return line.strip()
183
+ return None
184
+
185
+
186
+ def decision_kind(line: str | None) -> str | None:
187
+ """The reason word of a decision.md first line (`reasons: ambiguous`)."""
188
+ if not line or not line.lower().startswith('reasons:'):
189
+ return None
190
+ rest = line.split(':', 1)[1].strip()
191
+ token = rest.split()[0].strip(',') if rest else ''
192
+ return token or None
193
+
194
+
195
+ def record(plan: Path, group) -> dict:
196
+ members = [{'id': task, 'status': member_status(plan, task)} for task in group.members]
197
+ out = {
198
+ 'id': group.id,
199
+ 'review': group.review,
200
+ 'qa': group.qa,
201
+ 'title': group.title,
202
+ 'goal': group.goal,
203
+ 'members': members,
204
+ }
205
+ if group.review != 'group':
206
+ return out
207
+ row = last_round_row(plan, group.id)
208
+ status = group_status(plan, group.id)
209
+ out['round'] = group_round(plan, group.id, row)
210
+ out['status'] = status
211
+ out['implicated'] = implicated_of(row)
212
+ out['decision'] = decision_line(plan, group.id) if status == 'NEEDS_DECISION' else None
213
+ out['merged'] = group_merged(plan, group.id)
214
+ return out
215
+
216
+
217
+ def format_block(rec: dict) -> str:
218
+ lines = [f"{rec['id']} review={rec['review']} qa={rec['qa']}"]
219
+ lines.append(f" title: {rec['title']}")
220
+ lines.append(f" goal: {rec['goal']}")
221
+ lines.append(' members:')
222
+ for member in rec['members']:
223
+ lines.append(f" {member['id']} {member['status']}")
224
+ if rec['review'] != 'group':
225
+ return '\n'.join(lines)
226
+ lines.append(f" round: {'-' if rec['round'] is None else rec['round']}")
227
+ lines.append(f" status: {rec['status'] or '-'}")
228
+ lines.append(f" implicated: {', '.join(rec['implicated']) if rec['implicated'] else '-'}")
229
+ if rec['status'] == 'NEEDS_DECISION':
230
+ lines.append(f" decision: {rec['decision'] or '-'}")
231
+ if rec['merged']:
232
+ lines.append(' merged: yes')
233
+ return '\n'.join(lines)
234
+
235
+
236
+ def load_groups(plan: str) -> list:
237
+ try:
238
+ return forge_groups.load(plan)
239
+ except forge_groups.GroupError as error:
240
+ raise Usage(str(error)) from error
241
+ except OSError as error:
242
+ raise Usage(f'groups.tsv could not be read: {error.strerror or error}') from error
243
+
244
+
245
+ def require_groups_file(plan: str) -> None:
246
+ if not os.path.isfile(os.path.join(plan, 'groups.tsv')):
247
+ raise Refused(f'{plan} has no groups.tsv')
248
+
249
+
250
+ def find_group(groups, gid: str, plan: str):
251
+ found = [group for group in groups if group.id == gid]
252
+ if not found:
253
+ known = ', '.join(group.id for group in groups) or '(none)'
254
+ raise Usage(f'{gid} is not a group of {plan} (groups: {known})')
255
+ return found[0]
256
+
257
+
258
+ def clean_reason(text: str | None) -> str | None:
259
+ if text is None:
260
+ return None
261
+ reason = re.sub(r'\s+', ' ', text).strip()
262
+ if not reason:
263
+ return None
264
+ if len(reason) > REASON_LIMIT:
265
+ raise Usage(f'--reason is limited to {REASON_LIMIT} characters')
266
+ return reason
267
+
268
+
269
+ def parse_tasks(text: str, members) -> list:
270
+ names = [part.strip() for part in text.split(',')]
271
+ if not names or any(not name for name in names):
272
+ raise Usage('--tasks needs a comma list of member tasks')
273
+ unknown = [name for name in names if name not in members]
274
+ if unknown:
275
+ raise Usage(f"--tasks: {', '.join(unknown)} is not a member of this group ({', '.join(members)})")
276
+ return [member for member in members if member in names]
277
+
278
+
279
+ def state_message(plan: str, gid: str, status: str | None, members) -> str:
280
+ script = PARALLEL.name
281
+ if status == 'PASS':
282
+ return f'group {gid} is PASS: nothing to retry; the next run merges it'
283
+ if status == 'FAIL':
284
+ return (f'group {gid} is FAIL: its members were already sent back; '
285
+ f'the next {script} run {shlex.quote(plan)} --retry-failed N retries the ones that failed')
286
+ if status == 'WAITING':
287
+ return f'group {gid} is WAITING: a member is not IMPLEMENTED yet; nothing to retry'
288
+ if status == 'CONFLICT':
289
+ who = ', '.join(members) or '<id>'
290
+ return (f"group {gid} is CONFLICT: the members' branches conflict; "
291
+ f'fix one member with {script} retry {shlex.quote(plan)} <id> ({who}) and the group is re-reviewed')
292
+ if status == 'REVIEWING':
293
+ return f'group {gid} is REVIEWING: a review is running; nothing to retry'
294
+ if status == 'INVALIDATED':
295
+ return (f'group {gid} is INVALIDATED: the next run reviews it again, '
296
+ f'unless the integration branch moved or is dirty')
297
+ if status == 'NEEDS_DECISION':
298
+ return (f'group {gid} is NEEDS_DECISION but the reason is not ambiguous or oversized; '
299
+ f'see {plan}/groups/{gid}/decision.md')
300
+ if not status:
301
+ return f'group {gid} has not been reviewed; nothing to retry'
302
+ return f'group {gid} is {status}: forge group retry does not retry this state'
303
+
304
+
305
+ def retry_budget(plan: str) -> str | None:
306
+ text = control().text_of(plan, 'retry_budget')
307
+ return text if text and text.isdigit() else None
308
+
309
+
310
+ def next_run_lines(plan: str) -> list:
311
+ """How the FAIL members get another attempt: the next run, and a live scheduler's sweep."""
312
+ budget = retry_budget(plan)
313
+ number = budget if budget is not None else 'N'
314
+ lines = [f'next run retries them: {PARALLEL} run {shlex.quote(plan)} --retry-failed {number}']
315
+ if not control().is_live(plan):
316
+ return lines
317
+ every = '%g' % sweep_every()
318
+ if budget == '0':
319
+ lines.append(f"a live scheduler is running, but its retry budget is 0, so its sweep (every {every}s) "
320
+ f'leaves these FAIL tasks until the budget is raised')
321
+ else:
322
+ lines.append(f'a live scheduler picks up FAIL tasks with budget left on its sweep (every {every}s)')
323
+ return lines
324
+
325
+
326
+ def audit(plan: str, gid: str, value: str, previous: str | None, reason: str) -> None:
327
+ """One control.log line, actor cli, in the shape forge control writes. Called under the lock."""
328
+ control().probe(plan, 'control.log')
329
+ control().audit(plan, 'cli', 'retry', None, gid, value, previous, reason=reason)
330
+
331
+
332
+ def rearm(plan: str, gid: str, seen: str, reason: str) -> None:
333
+ """Reset the group to INTERRUPTED under the control lock. No member file is touched."""
334
+ ctrl = control()
335
+ with ctrl.control_lock(plan):
336
+ ctrl.probe(plan, 'control.log')
337
+ if group_merged(plan, gid):
338
+ raise Refused(f'group {gid} is merged: nothing to retry')
339
+ current = group_status(plan, gid)
340
+ if current != seen:
341
+ raise Refused(f'group {gid} changed while waiting for the control lock (now {current or "unset"})')
342
+ ctrl.write_atomic(plan, f'groups/{gid}/status', 'INTERRUPTED\n')
343
+ ctrl.audit(plan, 'cli', 'retry', None, gid, 'INTERRUPTED', seen, reason=reason)
344
+
345
+
346
+ def run_settle(plan: str, gid: str, tasks: list) -> int:
347
+ """_group_settle --tasks. Outside the control lock: post_attempt takes that same lock
348
+ when the retry policy writes a marker, and holding it here would time that write out."""
349
+ command = ['/bin/bash', str(PARALLEL), '_group_settle', plan, gid, '--tasks', ','.join(tasks)]
350
+ try:
351
+ result = subprocess.run(command, capture_output=True, text=True, timeout=120)
352
+ except OSError as error:
353
+ raise Refused(f'could not run _group_settle: {error}') from error
354
+ except subprocess.TimeoutExpired as error:
355
+ raise Refused(f'_group_settle did not finish: {error}') from error
356
+ if result.stdout:
357
+ sys.stdout.write(result.stdout)
358
+ if result.stderr:
359
+ sys.stderr.write(result.stderr)
360
+ return result.returncode
361
+
362
+
363
+ def settle(plan: str, gid: str, tasks: list, reason: str) -> None:
364
+ """Confirm the decision is still ambiguous, settle it, then record the retry."""
365
+ ctrl = control()
366
+ with ctrl.control_lock(plan):
367
+ ctrl.probe(plan, 'control.log')
368
+ if group_merged(plan, gid):
369
+ raise Refused(f'group {gid} is merged: nothing to retry')
370
+ if group_status(plan, gid) != 'NEEDS_DECISION' or decision_kind(decision_line(plan, gid)) != 'ambiguous':
371
+ raise Refused(f'group {gid} changed while waiting for the control lock; it is no longer an ambiguous decision')
372
+ code = run_settle(plan, gid, tasks)
373
+ if code != 0:
374
+ raise SettleFailed(code)
375
+ named = ','.join(tasks)
376
+ with ctrl.control_lock(plan):
377
+ audit(plan, gid, named, 'NEEDS_DECISION', reason)
378
+ sys.stdout.write(f'group {gid}: assigned the ambiguous findings to {named}\n')
379
+ sys.stdout.write('\n'.join(next_run_lines(plan)) + '\n')
380
+
381
+
382
+ def cmd_show(args) -> int:
383
+ plan = plan_dir(args.plan)
384
+ require_groups_file(plan)
385
+ groups = load_groups(plan)
386
+ if args.group:
387
+ groups = [find_group(groups, args.group, plan)]
388
+ records = [record(Path(plan), group) for group in groups]
389
+ if args.json:
390
+ json.dump(records, sys.stdout, indent=2)
391
+ sys.stdout.write('\n')
392
+ elif records:
393
+ sys.stdout.write('\n\n'.join(format_block(rec) for rec in records) + '\n')
394
+ return 0
395
+
396
+
397
+ def cmd_retry(args) -> int:
398
+ plan = plan_dir(args.plan)
399
+ if not os.path.isdir(plan):
400
+ raise Usage(f'{args.plan} is not a plan directory')
401
+ if not os.path.isfile(os.path.join(plan, 'groups.tsv')):
402
+ raise Usage(f'{plan} has no groups.tsv')
403
+ group = find_group(load_groups(plan), args.gid, plan)
404
+ if group.review != 'group':
405
+ raise Refused(f'group {group.id} has review={group.review}: forge group retry only retries a review=group group')
406
+ root = Path(plan)
407
+ if group_merged(root, group.id):
408
+ raise Refused(f'group {group.id} is merged: nothing to retry')
409
+ status = group_status(root, group.id)
410
+ kind = decision_kind(decision_line(root, group.id)) if status == 'NEEDS_DECISION' else None
411
+ if status == 'NEEDS_DECISION' and kind == 'oversized':
412
+ raise Refused(f'group {group.id} is NEEDS_DECISION (oversized): '
413
+ f'split the group in {plan}/groups.tsv and run plan again')
414
+ reason = clean_reason(args.reason)
415
+ if status == 'NEEDS_DECISION' and kind == 'ambiguous':
416
+ if not args.tasks:
417
+ raise Refused(f'group {group.id} is NEEDS_DECISION (ambiguous): --tasks is required; '
418
+ f"name the member tasks the findings belong to ({', '.join(group.members)})")
419
+ tasks = parse_tasks(args.tasks, group.members)
420
+ settle(plan, group.id, tasks, reason or f"assigned ambiguous findings to {','.join(tasks)}")
421
+ return 0
422
+ message = state_message(plan, group.id, status, group.members)
423
+ if args.tasks:
424
+ raise Refused(f'--tasks answers an ambiguous NEEDS_DECISION. {message}')
425
+ if status in REARM:
426
+ rearm(plan, group.id, status, reason or f'review the group again after {status}; no member attempt spent')
427
+ sys.stdout.write(f'group {group.id}: reset to INTERRUPTED (was {status}); '
428
+ f'the next run reviews it again, and no member attempt was spent\n')
429
+ return 0
430
+ raise Refused(message)
431
+
432
+
433
+ def one_line(text: str, flag: str) -> str:
434
+ value = ' '.join(text.split())
435
+ if len(value) > TEXT_LIMIT:
436
+ raise Usage(f'{flag} is limited to {TEXT_LIMIT} characters')
437
+ return value or '-'
438
+
439
+
440
+ def cmd_set(args) -> int:
441
+ plan = plan_dir(args.plan)
442
+ if not os.path.isdir(plan):
443
+ raise Usage(f'{args.plan} is not a plan directory')
444
+ if not os.path.isfile(os.path.join(plan, 'groups.tsv')):
445
+ raise Usage(f'{plan} has no groups.tsv')
446
+ if args.title is None and args.goal is None:
447
+ raise Usage('set needs --title or --goal')
448
+ title = None if args.title is None else one_line(args.title, '--title')
449
+ goal = None if args.goal is None else one_line(args.goal, '--goal')
450
+ reason = clean_reason(args.reason)
451
+ find_group(load_groups(plan), args.gid, plan)
452
+ ctrl = control()
453
+ with ctrl.control_lock(plan):
454
+ ctrl.probe(plan, 'control.log')
455
+ groups = load_groups(plan)
456
+ group = find_group(groups, args.gid, plan)
457
+ stale = forge_groups.check_frozen(plan)
458
+ if stale:
459
+ raise Refused(f'{stale}: forge group set would freeze those changes too')
460
+ new = group._replace(title=group.title if title is None else title, goal=group.goal if goal is None else goal)
461
+ if new == group:
462
+ sys.stdout.write(f'group {group.id}: unchanged\n')
463
+ return 0
464
+ forge_groups.write(plan, [new if g.id == group.id else g for g in groups])
465
+ forge_groups.freeze(plan)
466
+ for key, before, after in (('title', group.title, new.title), ('goal', group.goal, new.goal)):
467
+ if before != after:
468
+ ctrl.audit(plan, 'cli', 'group-set', None, f'{group.id}.{key}', after, before,
469
+ **({'reason': reason} if reason else {}))
470
+ sys.stdout.write(f'group {group.id}: title {new.title!r}, goal {new.goal!r}; groups frozen again\n')
471
+ return 0
472
+
473
+
474
+ def main(argv=None) -> int:
475
+ args = parser().parse_args(argv)
476
+ try:
477
+ if args.command == 'show':
478
+ return cmd_show(args)
479
+ if args.command == 'set':
480
+ return cmd_set(args)
481
+ return cmd_retry(args)
482
+ except Usage as error:
483
+ sys.stderr.write(f'forge group: {error}\n')
484
+ return 2
485
+ except control().Invalid as error:
486
+ sys.stderr.write(f'forge group: {error}\n')
487
+ return 2
488
+ except SettleFailed as error:
489
+ return error.code
490
+ except (Refused, control().Refused) as error:
491
+ sys.stderr.write(f'forge group: {error}\n')
492
+ return 3
493
+
494
+
495
+ if __name__ == '__main__':
496
+ sys.exit(main())