@giamme/forge 0.13.1 → 0.14.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 (47) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/SKILL.md +17 -11
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +1 -0
  5. package/docs/commands.md +121 -7
  6. package/docs/development.md +3 -0
  7. package/docs/reviews.md +2 -0
  8. package/docs/troubleshooting.md +5 -1
  9. package/forge +28 -1
  10. package/package.json +1 -1
  11. package/references/dataset.md +3 -1
  12. package/references/decompose.md +199 -61
  13. package/references/runtime.md +29 -0
  14. package/references/ui.md +10 -0
  15. package/scripts/forge-compare.py +491 -0
  16. package/scripts/forge-config.py +3 -3
  17. package/scripts/forge-contract.py +34 -8
  18. package/scripts/forge-control.py +105 -13
  19. package/scripts/forge-dispatch.sh +9 -5
  20. package/scripts/forge-jev-options.sh +17 -4
  21. package/scripts/forge-ledger.py +387 -0
  22. package/scripts/forge-lib-plans.sh +11 -2
  23. package/scripts/forge-lib-task.sh +390 -28
  24. package/scripts/forge-parallel-options.sh +20 -4
  25. package/scripts/forge-parallel.sh +116 -12
  26. package/scripts/forge-plan-check.py +68 -3
  27. package/scripts/forge-pr.py +276 -0
  28. package/scripts/forge-route.py +350 -34
  29. package/scripts/forge-runs.py +18 -1
  30. package/scripts/forge-runtime.py +23 -7
  31. package/scripts/forge-schedule.py +303 -46
  32. package/scripts/forge-verify-failed.py +111 -0
  33. package/scripts/forge-watch.py +372 -0
  34. package/scripts/forge_dataset/harvest.py +3 -1
  35. package/scripts/forge_fractal/cli.py +23 -6
  36. package/scripts/forge_infra.py +274 -0
  37. package/scripts/forge_jev/client.py +13 -9
  38. package/ui/docs/api.md +51 -8
  39. package/ui/forge_ui/export.py +6 -2
  40. package/ui/forge_ui/reader.py +172 -6
  41. package/ui/forge_ui/static/app.js +2 -2
  42. package/ui/forge_ui/static/checksview.js +20 -7
  43. package/ui/forge_ui/static/controls.js +6 -3
  44. package/ui/forge_ui/static/panel.js +69 -4
  45. package/ui/forge_ui/static/runmodel.js +30 -4
  46. package/ui/forge_ui/static/scene3d.js +3 -2
  47. package/ui/forge_ui/static/style.css +11 -4
@@ -0,0 +1,276 @@
1
+ #!/usr/bin/env python3
2
+ """forge pr [RUN_DIR | --repo DIR] [--base BRANCH] [--head BRANCH] [--title T] [--texts] [--paths] [--out FILE] [--create]
3
+
4
+ A draft pull-request description for a finished forge run, written from what the run recorded: the goal,
5
+ which tasks merged and which did not, who implemented and reviewed each, the verification status, the
6
+ final review and its open findings, and the integration branch. It is printed on stdout (a suggested
7
+ title goes to stderr), so it can be read, edited or piped: `forge pr | gh pr create --draft --body-file -`.
8
+
9
+ With no RUN_DIR it describes the newest run of the current repo (the Git top level, or --repo) that is
10
+ not still running. A run still running is refused: describe it once it ends.
11
+
12
+ What could be private stays out, as in `forge ui export`: the request, the prompts and the deferrals
13
+ (--texts adds the request and the deferrals) and local paths, which are reduced to their last
14
+ component (--paths keeps them). Finding headlines, task titles and the goal are kept, so read the
15
+ body before it goes anywhere public.
16
+
17
+ `--create` is the only thing here that does more than print: it runs `gh pr create --draft` in the repo
18
+ with that body, on the run's integration branch (forge/<run id>-integration, or --head). It never
19
+ pushes: the branch must already have an upstream (git push -u origin <branch>), and gh must be signed in.
20
+ Without --create nothing is written and neither gh nor the network is used (--out FILE writes the body
21
+ to a file). Exit status: 0 done, 1 gh failed, 2 usage or nothing to describe.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import importlib.util
27
+ import os
28
+ from pathlib import Path
29
+ import re
30
+ import subprocess
31
+ import sys
32
+ import tempfile
33
+
34
+ SKILL = Path(__file__).resolve().parent.parent
35
+ sys.path.insert(0, str(SKILL / 'scripts'))
36
+ sys.path.insert(0, str(SKILL / 'ui'))
37
+
38
+ import forge_registry # noqa: E402
39
+ from forge_ui import reader # noqa: E402
40
+
41
+ DONE = {'MERGED', 'PASS', 'NOCHANGES'}
42
+ SETTLED = DONE | {'FAIL', 'ERROR', 'CONFLICT', 'INFRA', 'TIMEOUT', 'INVALIDATED', 'INTERRUPTED', 'UNKNOWN', 'BLOCKED'}
43
+ MAX_FINDINGS = 20
44
+ TITLE_MAX = 72
45
+
46
+
47
+ def load_runs():
48
+ """forge-runs.py's repo lookup and registry reader, so every command agrees on which runs a repo has."""
49
+ spec = importlib.util.spec_from_file_location('forge_runs', SKILL / 'scripts' / 'forge-runs.py')
50
+ module = importlib.util.module_from_spec(spec)
51
+ sys.modules.setdefault('forge_runs', module)
52
+ spec.loader.exec_module(module)
53
+ return module
54
+
55
+
56
+ def unfinished(summary: dict) -> list:
57
+ """Task statuses that mean the run is still going (a failed task is finished, and reported as failed)."""
58
+ return sorted({t['status'] for t in summary.get('task_statuses') or [] if t['status'] not in SETTLED})
59
+
60
+
61
+ def newest_finished(repo: Path, runs) -> Path | None:
62
+ best = None
63
+ for path, source in reader.discover(plans=runs.registered(forge_registry.runs_registry(repo)), registry=False):
64
+ try:
65
+ summary = reader.summarize(path, source)
66
+ except Exception:
67
+ continue
68
+ if summary.get('kind') != 'plan' or not summary.get('task_count') or unfinished(summary):
69
+ continue
70
+ if best is None or (summary['updated'] or 0) > best[0]:
71
+ best = (summary['updated'] or 0, path)
72
+ return best[1] if best else None
73
+
74
+
75
+ class Scrub:
76
+ """Local paths reduced to their last component (the run, the repo) or `~` (the home), as the export does."""
77
+
78
+ def __init__(self, keep: bool, *roots):
79
+ self.keep = keep
80
+ self.roots = sorted({str(r) for r in roots if r and str(r) not in ('', '/')}, key=len, reverse=True)
81
+ home = str(Path.home())
82
+ self.home = home if home not in ('', '/') else None
83
+
84
+ def __call__(self, text):
85
+ text = '' if text is None else str(text)
86
+ if self.keep:
87
+ return text
88
+ for root in self.roots:
89
+ text = text.replace(root, Path(root).name or root)
90
+ if self.home:
91
+ text = text.replace(self.home, '~')
92
+ return text
93
+
94
+
95
+ def cell(text) -> str:
96
+ return str(text if text not in (None, '') else '–').replace('|', '\\|').replace('\n', ' ').strip()
97
+
98
+
99
+ def title_of(detail: dict, scrub) -> str:
100
+ goal = scrub((detail.get('goal') or '').strip().splitlines()[0] if (detail.get('goal') or '').strip() else '')
101
+ if not goal:
102
+ return 'forge run %s' % (detail.get('run_id') or detail['key'])
103
+ return goal if len(goal) <= TITLE_MAX else goal[:TITLE_MAX - 1].rstrip() + '…'
104
+
105
+
106
+ def headline(item: dict) -> str:
107
+ """A finding's first line without its `[P1][CONFIRMED] path:line —` lead, which the list shows itself."""
108
+ text = re.sub(r'^\s*(?:[-*]\s*)?(?:\[[^\]]*\]\s*)*', '', item['summary'])
109
+ if item.get('location') and text.startswith(item['location']):
110
+ text = text[len(item['location']):]
111
+ return re.sub(r'^[\s:—–-]+', '', text).strip() or item['summary']
112
+
113
+
114
+ def fenced(text: str) -> list:
115
+ fence = '`' * max(3, max((len(m) for m in re.findall(r'`+', text)), default=0) + 1)
116
+ return [fence + 'text', text, fence]
117
+
118
+
119
+ def finding_lines(path: Path, source: str, scrub) -> list:
120
+ """Open findings of the newest final review, worst first: severity, location, headline (never the text)."""
121
+ try:
122
+ found = reader.run_findings(path, source) or {}
123
+ except Exception:
124
+ return []
125
+ finals = found.get('final_reviews') or []
126
+ if not finals:
127
+ return []
128
+ order = {'P0': 0, 'P1': 1, 'P2': 2, 'P3': 3, None: 4}
129
+ items = sorted(finals[0]['findings'], key=lambda f: order.get(f['severity'], 4))
130
+ lines = []
131
+ for item in items[:MAX_FINDINGS]:
132
+ where = ' `%s`' % scrub(item['location']) if item.get('location') else ''
133
+ label = item['severity'] or item['status'].lower()
134
+ lines.append('- **%s**%s %s' % (label, where, scrub(headline(item))))
135
+ if len(items) > MAX_FINDINGS:
136
+ lines.append('- … and %d more (see the run in `forge ui`)' % (len(items) - MAX_FINDINGS))
137
+ return lines
138
+
139
+
140
+ def integration_branch(detail: dict) -> str | None:
141
+ return 'forge/%s-integration' % detail['run_id'] if detail.get('run_id') else None
142
+
143
+
144
+ def build(path: Path, source: str, scrub, texts: bool) -> tuple[str, str]:
145
+ """(title, body) for a run."""
146
+ d = reader.detail(path, source)
147
+ rid = d.get('run_id') or d['key']
148
+ tasks = d['tasks']
149
+ merged = [t for t in tasks if t['status'] in DONE]
150
+ other = [t for t in tasks if t['status'] not in DONE]
151
+ out = []
152
+ goal = scrub((d.get('goal') or '').strip()) or 'Untitled run'
153
+ out += ['## Summary', '', goal, '',
154
+ 'Built by forge run `%s`: %d of %d tasks merged.' % (scrub(rid), len(merged), len(tasks)), '']
155
+ out += ['## Tasks', '', '| Task | Title | Difficulty | Status | Implementer | Reviewer |', '|---|---|---|---|---|---|']
156
+ for t in tasks:
157
+ out.append('| %s |' % ' | '.join(cell(scrub(v)) for v in (t['id'], t['title'], t['difficulty'], t['status'], t['dwarf'], t['qa'])))
158
+ out.append('')
159
+ if other:
160
+ out += ['## Not merged', '']
161
+ out += ['- `%s` %s: %s' % (scrub(t['id']), cell(scrub(t['title'])), t['status']) for t in other]
162
+ out += ['', 'These tasks are not part of the integration branch.', '']
163
+ verification = d.get('verification_status')
164
+ review = d.get('final_review')
165
+ out += ['## Checks', '', '- Verification: %s' % (verification or 'not recorded')]
166
+ if review:
167
+ note = ''
168
+ if review.get('outdated'):
169
+ later = ', '.join(scrub(i) for i in review.get('merged_since') or [])
170
+ note = ' (outdated: the integration branch has moved since%s)' % (f'; merged after it: {later}' if later else '')
171
+ out.append('- Final review: %s%s' % (review.get('verdict') or 'no verdict', note))
172
+ else:
173
+ out.append('- Final review: none recorded')
174
+ out.append('')
175
+ found = finding_lines(path, source, scrub)
176
+ if found:
177
+ out += ['## Open findings from the final review', ''] + found + ['']
178
+ integration = d.get('integration') or {}
179
+ branch = integration_branch(d)
180
+ out += ['## Branch', '', '- Integration branch: `%s`' % branch]
181
+ if integration.get('base'):
182
+ out.append('- Forked from: `%s`' % integration['base'][:12])
183
+ out.append('')
184
+ if texts:
185
+ if (d.get('request') or '').strip():
186
+ out += ['## Request', ''] + fenced(scrub(d['request'].strip())) + ['']
187
+ if d.get('deferrals'):
188
+ out += ['## Deferred', ''] + ['- %s' % scrub(x) for x in d['deferrals']] + ['']
189
+ out += ['---', '_Draft written by `forge pr` from forge run `%s`. Read it before it goes public._' % scrub(rid), '']
190
+ return title_of(d, scrub), '\n'.join(out)
191
+
192
+
193
+ def create(repo: Path, head: str, title: str, body: str, base: str | None) -> int:
194
+ """`gh pr create --draft` for a branch that is already pushed. Pushes nothing."""
195
+ local = subprocess.run(['git', '-C', str(repo), 'rev-parse', '--verify', '--quiet', 'refs/heads/' + head],
196
+ capture_output=True, text=True, stdin=subprocess.DEVNULL).returncode == 0
197
+ if local:
198
+ upstream = subprocess.run(['git', '-C', str(repo), 'for-each-ref', '--format=%(upstream)', 'refs/heads/' + head],
199
+ capture_output=True, text=True, stdin=subprocess.DEVNULL).stdout.strip()
200
+ if not upstream:
201
+ print(f'forge pr: {head} has not been pushed; forge pr never pushes. Run: git -C {repo} push -u origin {head}', file=sys.stderr)
202
+ return 2
203
+ elif ':' not in head:
204
+ print(f'forge pr: no branch {head} in {repo}; name the branch with --head', file=sys.stderr)
205
+ return 2
206
+ with tempfile.NamedTemporaryFile('w', suffix='.md', delete=False, encoding='utf-8') as handle:
207
+ handle.write(body)
208
+ try:
209
+ argv = ['gh', 'pr', 'create', '--draft', '--title', title, '--body-file', handle.name, '--head', head]
210
+ if base:
211
+ argv += ['--base', base]
212
+ try:
213
+ return 1 if subprocess.run(argv, cwd=repo, stdin=subprocess.DEVNULL).returncode else 0
214
+ except FileNotFoundError:
215
+ print('forge pr: --create needs the gh CLI (https://cli.github.com), signed in', file=sys.stderr)
216
+ return 2
217
+ finally:
218
+ os.unlink(handle.name)
219
+
220
+
221
+ def main(argv=None) -> int:
222
+ parser = argparse.ArgumentParser(prog='forge pr', description='A draft pull-request description for a finished forge run. Prints it; '
223
+ 'opens a draft PR with gh only when --create is given.')
224
+ parser.add_argument('run_dir', nargs='?', type=Path, metavar='RUN_DIR', help='the run (default: the newest finished run of the current repo)')
225
+ parser.add_argument('--repo', type=Path, metavar='DIR', help='the repo whose newest finished run to describe (default: the Git top level of the current directory)')
226
+ parser.add_argument('--title', help='the title (default: the goal, first line)')
227
+ parser.add_argument('--base', metavar='BRANCH', help="with --create: the branch to merge into (default: gh's default branch)")
228
+ parser.add_argument('--head', metavar='BRANCH', help="with --create: the branch to propose (default: the run's forge/<run id>-integration)")
229
+ parser.add_argument('--texts', action='store_true', help='also include the run\'s request and its deferrals')
230
+ parser.add_argument('--paths', action='store_true', help='keep local paths (default: their last component)')
231
+ parser.add_argument('--out', type=Path, metavar='FILE', help='also write the body to FILE')
232
+ parser.add_argument('--create', action='store_true', help='run `gh pr create --draft` with this body (never pushes)')
233
+ args = parser.parse_args(argv)
234
+ if args.run_dir is not None and args.repo is not None:
235
+ parser.error('RUN_DIR cannot be combined with --repo')
236
+ if args.repo is not None and not args.repo.is_dir():
237
+ parser.error(f'--repo: no such directory: {args.repo}')
238
+ if (args.base or args.head) and not args.create:
239
+ parser.error('--base and --head are used by --create only')
240
+ runs = load_runs()
241
+ if args.run_dir is not None:
242
+ path = args.run_dir.resolve()
243
+ else:
244
+ repo = runs.repo_of(args.repo if args.repo is not None else Path.cwd())
245
+ path = newest_finished(repo, runs)
246
+ if path is None:
247
+ print(f'forge pr: no finished run is registered for {repo} (forge runs lists them)', file=sys.stderr)
248
+ return 2
249
+ if reader._kind(path) != 'plan':
250
+ what = 'a solo run (no tasks or integration branch to describe)' if reader._kind(path) == 'solo' else 'not a forge run (no tasks.tsv)'
251
+ print(f'forge pr: {path} is {what}', file=sys.stderr)
252
+ return 2
253
+ summary = reader.summarize(path, 'plan')
254
+ if not summary.get('task_count'):
255
+ print(f'forge pr: {path} has no tasks yet', file=sys.stderr)
256
+ return 2
257
+ if unfinished(summary):
258
+ print(f"forge pr: run {summary.get('run_id') or path.name} is still running ({', '.join(unfinished(summary)).lower()} tasks); describe it once it ends", file=sys.stderr)
259
+ return 2
260
+ repo = Path(summary['repo']) if summary.get('repo') else None
261
+ title, body = build(path, 'plan', Scrub(args.paths, path, repo), args.texts)
262
+ title = args.title or title
263
+ if args.out is not None:
264
+ args.out.write_text(body, encoding='utf-8')
265
+ if args.create:
266
+ if repo is None or not repo.is_dir():
267
+ print('forge pr: the run records no repo that exists here; --create needs it', file=sys.stderr)
268
+ return 2
269
+ return create(repo, args.head or integration_branch(summary), title, body, args.base)
270
+ sys.stdout.write(body)
271
+ print(f'forge pr: suggested title: {title}\nforge pr: nothing was created; add --create to open a draft PR with gh', file=sys.stderr)
272
+ return 0
273
+
274
+
275
+ if __name__ == '__main__':
276
+ sys.exit(main())