@giamme/forge 0.13.1 → 0.14.1

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 (48) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/SKILL.md +17 -11
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +2 -0
  5. package/docs/commands.md +134 -8
  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 +201 -61
  13. package/references/harnesses.md +4 -1
  14. package/references/runtime.md +29 -0
  15. package/references/ui.md +10 -0
  16. package/scripts/forge-compare.py +491 -0
  17. package/scripts/forge-config.py +3 -3
  18. package/scripts/forge-contract.py +34 -8
  19. package/scripts/forge-control.py +105 -13
  20. package/scripts/forge-dispatch.sh +85 -25
  21. package/scripts/forge-jev-options.sh +17 -4
  22. package/scripts/forge-ledger.py +387 -0
  23. package/scripts/forge-lib-plans.sh +11 -2
  24. package/scripts/forge-lib-task.sh +390 -28
  25. package/scripts/forge-parallel-options.sh +20 -4
  26. package/scripts/forge-parallel.sh +123 -17
  27. package/scripts/forge-plan-check.py +68 -3
  28. package/scripts/forge-pr.py +276 -0
  29. package/scripts/forge-route.py +403 -38
  30. package/scripts/forge-runs.py +18 -1
  31. package/scripts/forge-runtime.py +94 -8
  32. package/scripts/forge-schedule.py +303 -46
  33. package/scripts/forge-verify-failed.py +111 -0
  34. package/scripts/forge-watch.py +372 -0
  35. package/scripts/forge_dataset/harvest.py +3 -1
  36. package/scripts/forge_fractal/cli.py +23 -6
  37. package/scripts/forge_infra.py +274 -0
  38. package/scripts/forge_jev/client.py +13 -9
  39. package/ui/docs/api.md +51 -8
  40. package/ui/forge_ui/export.py +6 -2
  41. package/ui/forge_ui/reader.py +172 -6
  42. package/ui/forge_ui/static/app.js +2 -2
  43. package/ui/forge_ui/static/checksview.js +20 -7
  44. package/ui/forge_ui/static/controls.js +6 -3
  45. package/ui/forge_ui/static/panel.js +69 -4
  46. package/ui/forge_ui/static/runmodel.js +30 -4
  47. package/ui/forge_ui/static/scene3d.js +3 -2
  48. package/ui/forge_ui/static/style.css +11 -4
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env python3
2
+ """The test files a failed verification names, and the command that reruns only those (#112).
3
+
4
+ forge-verify-failed.py command --checkout DIR --log LOG --subset FILE
5
+ Prints the repository's `.forge/verify-subset` command with {files} (and {changed}) set to
6
+ the tracked test files LOG names as failing, and exits 0. Exits 1, printing nothing, when the
7
+ subset command has neither placeholder or LOG names no tracked test file.
8
+
9
+ A failed verification used to be rerun whole to tell a flaky test from a regression: one more
10
+ full suite for a failure that is usually deterministic. forge now reruns the failing files first.
11
+ If they fail again on their own, the regression is confirmed and the full rerun is skipped; if they
12
+ pass, the full command reruns as before, so a pass always comes from the whole command.
13
+
14
+ Recognised failure lines:
15
+ unittest `FAIL: test_x (module.Class.test_x)` and `ERROR: ...`, the module mapped to a tracked
16
+ `<module>.py` (a dotted module to `<a>/<b>.py`); an import failure
17
+ (`unittest.loader._FailedTest.<module>`) names its module last
18
+ pytest `FAILED path/test_x.py::...` and `ERROR path/test_x.py`
19
+ node:test the spec reporter's `test at path/x.test.js:L:C` and TAP's `location: '/abs/x.test.js:L:C'`
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import os
25
+ import re
26
+ import shlex
27
+ import subprocess
28
+ import sys
29
+
30
+ UNITTEST = re.compile(r'^(?:FAIL|ERROR): \S+ \(([\w.]+)\)\s*$')
31
+ PYTEST = re.compile(r'^(?:FAILED|ERROR) (\S+?\.py)(?:::|\s|$)')
32
+ # node --test names a failing test's file only in its location: `test at <file>:L:C` under the spec
33
+ # reporter's failing-tests list, `location: '<file>:L:C'` in a TAP failure's diagnostics.
34
+ NODE = re.compile(r"^\s*(?:test at |location: ')(\S+\.(?:m?js|cjs|mts|ts)):\d+:\d+")
35
+ FAILED_IMPORT = 'unittest.loader._FailedTest.'
36
+
37
+
38
+ def tracked(checkout: str) -> list:
39
+ try:
40
+ out = subprocess.run(['git', '-C', checkout, 'ls-files', '-z'], capture_output=True, check=True).stdout
41
+ except (OSError, subprocess.CalledProcessError):
42
+ return []
43
+ return [p for p in out.decode('utf-8', 'replace').split('\0') if p]
44
+
45
+
46
+ def module_files(dotted: str, files: list) -> list:
47
+ """Tracked files for a unittest id: its longest module prefix that names one."""
48
+ if dotted.startswith(FAILED_IMPORT):
49
+ dotted = dotted[len(FAILED_IMPORT):]
50
+ parts = dotted.split('.')
51
+ for end in range(len(parts), 0, -1):
52
+ tail = '/'.join(parts[:end]) + '.py'
53
+ found = [f for f in files if f == tail or f.endswith('/' + tail)]
54
+ if found:
55
+ return found
56
+ return []
57
+
58
+
59
+ def path_file(path: str, checkout: str, files: set) -> list:
60
+ if os.path.isabs(path): # runners print real paths; the checkout may be named through a symlink
61
+ path = os.path.relpath(os.path.realpath(path), os.path.realpath(checkout))
62
+ path = os.path.normpath(path)
63
+ return [path] if path in files else []
64
+
65
+
66
+ def failing_files(log_text: str, checkout: str) -> list:
67
+ files = tracked(checkout)
68
+ known = set(files)
69
+ found = []
70
+ for line in log_text.splitlines():
71
+ match = UNITTEST.match(line)
72
+ if match:
73
+ names = module_files(match.group(1), files)
74
+ else:
75
+ match = PYTEST.match(line) or NODE.match(line)
76
+ names = path_file(match.group(1), checkout, known) if match else []
77
+ for name in names:
78
+ if name not in found:
79
+ found.append(name)
80
+ return found
81
+
82
+
83
+ def subset_command(template: str, files: list) -> str:
84
+ quoted = ' '.join(shlex.quote(f) for f in files)
85
+ return template.replace('{files}', quoted).replace('{changed}', quoted)
86
+
87
+
88
+ def main(argv=None) -> int:
89
+ ap = argparse.ArgumentParser(prog='forge-verify-failed.py')
90
+ sub = ap.add_subparsers(dest='command', required=True)
91
+ p = sub.add_parser('command')
92
+ p.add_argument('--checkout', required=True)
93
+ p.add_argument('--log', required=True)
94
+ p.add_argument('--subset', required=True)
95
+ args = ap.parse_args(argv)
96
+ try:
97
+ template = open(args.subset, encoding='utf-8', errors='replace').read().strip()
98
+ log_text = open(args.log, encoding='utf-8', errors='replace').read()
99
+ except OSError:
100
+ return 1
101
+ if '{files}' not in template and '{changed}' not in template:
102
+ return 1
103
+ files = failing_files(log_text, args.checkout)
104
+ if not files:
105
+ return 1
106
+ print(subset_command(template, files))
107
+ return 0
108
+
109
+
110
+ if __name__ == '__main__':
111
+ sys.exit(main())
@@ -0,0 +1,372 @@
1
+ #!/usr/bin/env python3
2
+ """forge watch [RUN_DIR | --repo DIR | --all] [--interval S] [--until-done] [--no-notify] [--exec CMD]
3
+
4
+ Follow forge runs from the terminal and hear about them without keeping forge-ui open.
5
+
6
+ A line is printed whenever a task changes status. A run that finishes or fails, a task that fails
7
+ and a final review's verdict are also events: each raises a desktop notification where one can be
8
+ shown (notify-send on Linux, osascript on macOS; on a headless machine or in CI there is no
9
+ notifier and the events only print), and runs the optional hooks:
10
+
11
+ --exec CMD run through the shell on every event
12
+ .forge/on-finish an executable file of the run's repo, run when a run finishes or fails
13
+
14
+ Both get the event in the environment: FORGE_WATCH_EVENT (run-done, run-failed, task-failed or
15
+ review), FORGE_WATCH_RUN_ID, FORGE_WATCH_RUN_DIR, FORGE_WATCH_REPO, FORGE_WATCH_GOAL,
16
+ FORGE_WATCH_TASK (task-failed only), FORGE_WATCH_VERDICT (the review's PASS/FAIL, the failing
17
+ task's status, else the run's final review or verification status, else PASS/FAIL for a run that
18
+ is done/failed) and FORGE_WATCH_MESSAGE (the line that was printed). A hook that fails or runs
19
+ past 30 seconds is reported on stderr and never stops the watch.
20
+
21
+ What counts as an event is what the forge-ui bell tells you about (ui/forge_ui/static/runmodel.js,
22
+ statusEvents); a run that has not changed for two hours never raises one. The first poll is only
23
+ a baseline, so a watch reports what happens after it starts. Runs are read with forge-ui's own
24
+ reader, and nothing is ever written.
25
+
26
+ With RUN_DIR, the watch ends when that run does (exit 0 done, 1 failed, 3 when its process looks
27
+ dead: no change for two hours). With --repo, or the repo of the current directory, it follows
28
+ every run registered for that repo, new ones included, and with --all every repo's, until
29
+ interrupted; --until-done ends it once nothing is running.
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import argparse
34
+ import importlib.util
35
+ import os
36
+ from pathlib import Path
37
+ import shutil
38
+ import subprocess
39
+ import sys
40
+ import time
41
+
42
+ SKILL = Path(__file__).resolve().parent.parent
43
+ sys.path.insert(0, str(SKILL / 'scripts'))
44
+ sys.path.insert(0, str(SKILL / 'ui'))
45
+
46
+ import forge_registry # noqa: E402
47
+ from forge_ui import reader # noqa: E402
48
+
49
+ DONE = {'MERGED', 'PASS', 'NOCHANGES'}
50
+ BAD = {'FAIL', 'ERROR', 'CONFLICT', 'INFRA', 'TIMEOUT', 'INVALIDATED', 'INTERRUPTED', 'UNKNOWN', 'BLOCKED'}
51
+ FAILING = {'FAIL', 'ERROR', 'CONFLICT', 'TIMEOUT', 'INVALIDATED', 'INTERRUPTED', 'BLOCKED'}
52
+ STALE_AFTER = 7200 # seconds without a change: a RUNNING run whose process died
53
+ IDLE_RECHECK = 60 # seconds between looks at an ended run that has not changed for STALE_AFTER
54
+ HOOK_TIMEOUT = 30
55
+ NOTIFY_TIMEOUT = 10
56
+
57
+
58
+ def run_state(summary: dict) -> str:
59
+ """The run's state as forge-ui draws it: live, failed, done or pending."""
60
+ counts = {status: n for status, n in (summary.get('counts') or {}).items() if n}
61
+ if counts.get('RUNNING'):
62
+ return 'live'
63
+ if any(status in BAD for status in counts):
64
+ return 'failed'
65
+ if counts and all(status in DONE for status in counts):
66
+ return 'done'
67
+ return 'pending'
68
+
69
+
70
+ def statuses(summary: dict) -> dict:
71
+ return {item['id']: item['status'] for item in summary.get('task_statuses') or []}
72
+
73
+
74
+ def goal_of(summary: dict) -> str:
75
+ text = str(summary.get('goal') or 'Untitled run').strip()
76
+ return text.splitlines()[0] if text else 'Untitled run'
77
+
78
+
79
+ def base_of(summary: dict) -> dict:
80
+ return dict(run_id=summary.get('run_id') or summary['key'], path=summary['path'], repo=summary.get('repo') or '',
81
+ goal=goal_of(summary), task='', status='', verdict='')
82
+
83
+
84
+ def stale(summary: dict, now: float) -> bool:
85
+ updated = summary.get('updated')
86
+ return updated is not None and now - updated > STALE_AFTER
87
+
88
+
89
+ def events(prev: dict, summary: dict, now: float) -> list:
90
+ """A task that has just failed and a final review's new verdict: forge-ui's bell rules (runmodel.js, statusEvents)."""
91
+ out = []
92
+ if stale(summary, now):
93
+ return out
94
+ old = statuses(prev)
95
+ for task, status in statuses(summary).items():
96
+ if status in FAILING and task in old and old[task] != status:
97
+ out.append(dict(base_of(summary), kind='task-failed', task=task, status=status, verdict=status))
98
+ verdict = summary.get('final_review')
99
+ if verdict in ('PASS', 'FAIL') and prev.get('final_review') != verdict:
100
+ out.append(dict(base_of(summary), kind='review', verdict=verdict))
101
+ return out
102
+
103
+
104
+ def finish(summary: dict) -> dict:
105
+ """The event for a run that has stopped: done when every task is, else failed."""
106
+ done = run_state(summary) == 'done'
107
+ verdict = summary.get('final_review') or summary.get('verification_status') or ('PASS' if done else 'FAIL')
108
+ return dict(base_of(summary), kind='run-done' if done else 'run-failed', verdict=str(verdict).upper())
109
+
110
+
111
+ def describe(event: dict) -> str:
112
+ run = event['run_id']
113
+ if event['kind'] == 'run-done':
114
+ return f'run {run} finished: {event["goal"]}'
115
+ if event['kind'] == 'run-failed':
116
+ return f'run {run} ended with failures: {event["goal"]}'
117
+ if event['kind'] == 'task-failed':
118
+ return f'run {run}: task {event["task"]} {event["status"]}'
119
+ return f'run {run}: final review {event["verdict"]}'
120
+
121
+
122
+ def clean(text: str, limit: int = 200) -> str:
123
+ text = ''.join(ch if ch.isprintable() else ' ' for ch in str(text)).strip()
124
+ return text if len(text) <= limit else text[:limit - 1] + '…'
125
+
126
+
127
+ # --- desktop notifications ---------------------------------------------------------------------
128
+
129
+ def notifier():
130
+ """(name, argv builder) for the desktop notifier this machine has, else (None, why)."""
131
+ if os.environ.get('FORGE_WATCH_NOTIFY', '').lower() in ('off', '0', 'false', 'no'):
132
+ return None, 'FORGE_WATCH_NOTIFY=off'
133
+ if sys.platform == 'darwin' and shutil.which('osascript'):
134
+ return 'osascript', lambda title, body: ['osascript', '-e', 'on run argv', '-e',
135
+ 'display notification (item 1 of argv) with title (item 2 of argv)',
136
+ '-e', 'end run', body, title]
137
+ if shutil.which('notify-send'):
138
+ if sys.platform.startswith('linux') and not any(os.environ.get(v) for v in ('DISPLAY', 'WAYLAND_DISPLAY', 'DBUS_SESSION_BUS_ADDRESS')):
139
+ return None, 'no desktop session (headless)'
140
+ return 'notify-send', lambda title, body: ['notify-send', '--app-name=forge', '--', title, body]
141
+ return None, 'no notify-send or osascript on PATH'
142
+
143
+
144
+ def notify(build, event: dict) -> None:
145
+ title = 'forge: ' + {'run-done': 'run finished', 'run-failed': 'run failed', 'task-failed': 'task failed',
146
+ 'review': 'final review ' + event['verdict']}[event['kind']]
147
+ try:
148
+ subprocess.run(build(title, clean(describe(event))), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
149
+ stderr=subprocess.DEVNULL, timeout=NOTIFY_TIMEOUT)
150
+ except (OSError, subprocess.SubprocessError):
151
+ pass # a notifier that fails must not stop the watch
152
+
153
+
154
+ # --- hooks ---------------------------------------------------------------------------------------
155
+
156
+ def hook_env(event: dict) -> dict:
157
+ env = dict(os.environ)
158
+ env.update(FORGE_WATCH_EVENT=event['kind'], FORGE_WATCH_RUN_ID=event['run_id'], FORGE_WATCH_RUN_DIR=event['path'],
159
+ FORGE_WATCH_REPO=event['repo'], FORGE_WATCH_GOAL=event['goal'], FORGE_WATCH_TASK=event['task'],
160
+ FORGE_WATCH_VERDICT=event['verdict'], FORGE_WATCH_MESSAGE=describe(event))
161
+ return env
162
+
163
+
164
+ def run_hook(argv_or_cmd, event: dict, cwd, shell: bool, label: str) -> None:
165
+ try:
166
+ done = subprocess.run(argv_or_cmd, shell=shell, cwd=cwd, env=hook_env(event), stdin=subprocess.DEVNULL,
167
+ stdout=sys.stderr, stderr=sys.stderr, timeout=HOOK_TIMEOUT)
168
+ if done.returncode != 0:
169
+ print(f'forge watch: {label} exited {done.returncode}', file=sys.stderr, flush=True)
170
+ except subprocess.TimeoutExpired:
171
+ print(f'forge watch: {label} ran past {HOOK_TIMEOUT}s and was stopped', file=sys.stderr, flush=True)
172
+ except OSError as error:
173
+ print(f'forge watch: {label} did not start: {error}', file=sys.stderr, flush=True)
174
+
175
+
176
+ def tracked(path: Path, repo: Path) -> bool:
177
+ try:
178
+ return subprocess.run(['git', '-C', str(repo), 'ls-files', '--error-unmatch', '--', str(path)], stdin=subprocess.DEVNULL,
179
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10).returncode == 0
180
+ except (OSError, subprocess.SubprocessError):
181
+ return True # cannot tell: do not run it
182
+
183
+
184
+ def repo_hook(event: dict, warned: set):
185
+ """The repo's .forge/on-finish when it is safe to run, else None (said once on stderr).
186
+
187
+ `.forge/` is often committed, so a cloned repository could ship a hook that runs on the first
188
+ `forge watch`: only a hook git does not track, owned by this user and not writable by others runs.
189
+ """
190
+ if event['kind'] not in ('run-done', 'run-failed') or not event['repo']:
191
+ return None
192
+ repo = Path(event['repo'])
193
+ path = repo / '.forge' / 'on-finish'
194
+ try:
195
+ info = path.stat()
196
+ except OSError:
197
+ return None
198
+ if not path.is_file() or not os.access(path, os.X_OK):
199
+ return None
200
+ why = None
201
+ if tracked(path, repo):
202
+ why = 'it is tracked by git (a cloned repo could ship one); keep it untracked, or use --exec'
203
+ elif hasattr(os, 'getuid') and info.st_uid != os.getuid():
204
+ why = 'it is not owned by you'
205
+ elif info.st_mode & 0o022:
206
+ why = 'it is writable by others'
207
+ if why is None:
208
+ return path
209
+ if path not in warned:
210
+ warned.add(path)
211
+ print(f'forge watch: not running {path}: {why}', file=sys.stderr, flush=True)
212
+ return None
213
+
214
+
215
+ # --- the watch -----------------------------------------------------------------------------------
216
+
217
+ def load_runs():
218
+ """forge-runs.py's repo lookup and registry reader, so both commands agree on which runs a repo has."""
219
+ spec = importlib.util.spec_from_file_location('forge_runs', SKILL / 'scripts' / 'forge-runs.py')
220
+ module = importlib.util.module_from_spec(spec)
221
+ sys.modules.setdefault('forge_runs', module)
222
+ spec.loader.exec_module(module)
223
+ return module
224
+
225
+
226
+ class Targets:
227
+ """Which run dirs are followed, and how a poll finds them."""
228
+
229
+ def __init__(self, run_dir, repo, runs_module):
230
+ self.run_dir, self.repo, self.runs = run_dir, repo, runs_module
231
+
232
+ def poll(self) -> list:
233
+ if self.run_dir is not None:
234
+ return [(self.run_dir, 'plan')]
235
+ if self.repo is None:
236
+ return reader.discover(registry=True, registry_dir=forge_registry.registry_dir())
237
+ return reader.discover(plans=self.runs.registered(forge_registry.runs_registry(self.repo)), registry=False)
238
+
239
+
240
+ def stamp(now: float) -> str:
241
+ return time.strftime('%H:%M:%S', time.localtime(now))
242
+
243
+
244
+ def watch(targets: Targets, interval: float, settle: float, until_done: bool, single: bool, hook, build, out=None) -> int:
245
+ out = out or sys.stdout
246
+ known: dict = {} # run dir -> last summary
247
+ recheck: dict = {} # run dir -> earliest time to read it again (ended and quiet)
248
+ running: dict = {} # run dir -> True from the poll it was live until its end was announced
249
+ stopped: dict = {} # run dir -> when it was first seen not live after running
250
+ warned: set = set()
251
+ first = True
252
+
253
+ def say(text: str, now: float) -> None:
254
+ print(f'{stamp(now)} {text}', file=out, flush=True)
255
+
256
+ def fire(event: dict, now: float) -> None:
257
+ label = {'run-done': 'DONE ', 'run-failed': 'FAILED', 'task-failed': 'FAIL ', 'review': 'REVIEW'}[event['kind']]
258
+ say(f'{label} {describe(event)}', now)
259
+ if build is not None:
260
+ notify(build, event)
261
+ if hook:
262
+ run_hook(hook, event, None, True, '--exec')
263
+ script = repo_hook(event, warned)
264
+ if script is not None:
265
+ run_hook([str(script)], event, str(script.parent.parent), False, str(script))
266
+
267
+ while True:
268
+ now = time.time()
269
+ for path, source in targets.poll():
270
+ key = str(path)
271
+ if recheck.get(key, 0) > now:
272
+ continue
273
+ try:
274
+ summary = reader.summarize(path, source)
275
+ except Exception: # one unreadable run must not stop the watch
276
+ continue
277
+ before = known.get(key)
278
+ known[key] = summary
279
+ state, name = run_state(summary), summary.get('run_id') or summary['key']
280
+ recheck[key] = now + IDLE_RECHECK if stale(summary, now) and state != 'live' else 0
281
+ if before is None:
282
+ say(f'{"following" if first else "new run"} {name} {state} {goal_of(summary)}', now)
283
+ running[key] = state == 'live' or (not first and state != 'pending' and not stale(summary, now))
284
+ if running[key] and state != 'live':
285
+ stopped[key] = now # began and ended between two looks: it still owes its finish
286
+ continue
287
+ old, new = statuses(before), statuses(summary)
288
+ for task, status in new.items():
289
+ if task in old and old[task] != status:
290
+ say(f'{name} {task} {old[task]} -> {status}', now)
291
+ elif task not in old:
292
+ say(f'{name} {task} added: {status}', now)
293
+ for event in events(before, summary, now):
294
+ fire(event, now)
295
+ if state == 'live':
296
+ running[key] = True
297
+ stopped.pop(key, None)
298
+ elif running.get(key) and not stale(summary, now):
299
+ # Not live may only be the gap before an automatic retry: announce the end once it has held.
300
+ stopped.setdefault(key, now)
301
+ if now - stopped[key] >= settle:
302
+ running[key] = False
303
+ stopped.pop(key, None)
304
+ fire(finish(summary), now)
305
+ first = False
306
+ states = {key: run_state(summary) for key, summary in known.items()}
307
+ if single:
308
+ summary = known.get(str(targets.run_dir))
309
+ if summary is None:
310
+ print(f'forge watch: {targets.run_dir} is not a forge run', file=sys.stderr)
311
+ return 2
312
+ key, state = str(targets.run_dir), states[str(targets.run_dir)]
313
+ if state in ('done', 'failed') and not running.get(key):
314
+ return 0 if state == 'done' else 1
315
+ if state == 'live' and stale(summary, now):
316
+ say(f'no change for {STALE_AFTER // 3600} hours: its process probably died', now)
317
+ return 3
318
+ elif until_done and not any(running.get(key) or state == 'live' for key, state in states.items()):
319
+ say('nothing is running' if states else 'no runs to follow', now)
320
+ return 0
321
+ time.sleep(interval)
322
+
323
+
324
+ def main(argv=None) -> int:
325
+ parser = argparse.ArgumentParser(prog='forge watch', description='Follow forge runs in the terminal and get a desktop notification (and an optional hook) '
326
+ 'when one finishes, a task fails or a final review gives its verdict. Read-only.')
327
+ parser.add_argument('run_dir', nargs='?', type=Path, metavar='RUN_DIR', help='follow this run until it ends (default: the runs of the current repo)')
328
+ which = parser.add_mutually_exclusive_group()
329
+ which.add_argument('--repo', type=Path, metavar='DIR', help='follow every run registered for this repo (default: the Git top level of the current directory)')
330
+ which.add_argument('--all', action='store_true', help="follow every repo's runs")
331
+ parser.add_argument('--interval', type=float, default=5.0, metavar='S', help='seconds between looks (default 5)')
332
+ parser.add_argument('--settle', type=float, default=10.0, metavar='S',
333
+ help='seconds a run must stay stopped before its end is announced, so an automatic retry is not reported as a failure (default 10)')
334
+ parser.add_argument('--until-done', action='store_true', help='with --repo or --all: stop once no run is running (RUN_DIR always stops when its run ends)')
335
+ parser.add_argument('--no-notify', action='store_true', help='print only; raise no desktop notification (FORGE_WATCH_NOTIFY=off does the same)')
336
+ parser.add_argument('--exec', dest='command', metavar='CMD', help='run CMD through the shell on every event, with FORGE_WATCH_* in its environment')
337
+ args = parser.parse_args(argv)
338
+ if not args.interval >= 0.05:
339
+ parser.error('--interval must be at least 0.05')
340
+ if args.settle < 0:
341
+ parser.error('--settle must not be negative')
342
+ if args.run_dir is not None and (args.repo is not None or args.all):
343
+ parser.error('RUN_DIR cannot be combined with --repo or --all')
344
+ if args.repo is not None and not args.repo.is_dir():
345
+ parser.error(f'--repo: no such directory: {args.repo}')
346
+ runs = load_runs()
347
+ run_dir = None
348
+ if args.run_dir is not None:
349
+ run_dir = args.run_dir.resolve()
350
+ if reader._kind(run_dir) is None:
351
+ print(f'forge watch: {run_dir} is not a forge run (no tasks.tsv, and no prompt.md with repo)', file=sys.stderr)
352
+ return 2
353
+ repo = None
354
+ else:
355
+ repo = None if args.all else runs.repo_of(args.repo if args.repo is not None else Path.cwd())
356
+ build = None
357
+ if not args.no_notify:
358
+ name, build = notifier()
359
+ if name is None:
360
+ print(f'forge watch: no desktop notifications ({build}); events print here', file=sys.stderr, flush=True)
361
+ build = None
362
+ where = f'run {run_dir}' if run_dir else ('every repo' if repo is None else f'repo {repo}')
363
+ print(f'forge watch: following {where}; Ctrl-C stops', flush=True)
364
+ try:
365
+ return watch(Targets(run_dir, repo, runs), args.interval, args.settle, args.until_done, run_dir is not None, args.command, build)
366
+ except KeyboardInterrupt:
367
+ print(file=sys.stderr)
368
+ return 130
369
+
370
+
371
+ if __name__ == '__main__':
372
+ sys.exit(main())
@@ -45,7 +45,8 @@ WATCHED = (
45
45
  'verification.retry.log', 'verification.flaky', 'verification.coverage.txt',
46
46
  'verification.jev.json', 'verification.runs.tsv', 'verification.commit', 'verification.fingerprint',
47
47
  'verification.lanes.json', 'results.tsv',
48
- 'prereview.failed', 'bounced', 'message.failed', 'needs_input.md',
48
+ 'prereview.failed', 'bounced', 'message.failed', 'needs_input.md', 'lateral.tsv',
49
+ 'decision.md', 'decisions.tsv', 'ledger.tsv',
49
50
  )
50
51
 
51
52
  # The markers of an attempt forge sent back without a review, and the kind each one records.
@@ -358,6 +359,7 @@ def run_uid(run_dir: Path, create: bool) -> str:
358
359
 
359
360
  INTERVENTIONS = {
360
361
  'escalation': ('after_attempt', 'from', 'to', 'source'),
362
+ 'lateral': ('attempt', 'role', 'from', 'to', 'cause'),
361
363
  'control': ('at', 'actor', 'action', 'key', 'value', 'previous'),
362
364
  }
363
365
 
@@ -12,21 +12,38 @@ import subprocess
12
12
  from . import DEFAULTS, identifier, managed_run, read_json, safe_file, write_json
13
13
 
14
14
 
15
+ # One line each in `forge fractal --help`. status, tree, activity, costs, messages and config
16
+ # print the same captured run view (references/fractal.md); --task and --node narrow it.
17
+ _HELP = dict(
18
+ status="a run's captured state as JSON; --html PATH writes a page",
19
+ tree='the same view as status, read for task and node ids',
20
+ activity='the same view as status; page history with --offset and --limit',
21
+ logs='the same view with logs; --follow prints each change',
22
+ costs='the same view as status, read for usage and costs',
23
+ messages='the same view as status, read for messages',
24
+ config="the same view as status, read for the run's config",
25
+ report='a portable HTML report with full history and logs (default RUN.html)',
26
+ pause='pause a run, or one --task (and --node) in it',
27
+ resume="resume a run's whole pipeline, or one --task",
28
+ stop='stop a run; work and artifacts are kept',
29
+ )
30
+
31
+
15
32
  def parser() -> argparse.ArgumentParser:
16
33
  p = argparse.ArgumentParser(prog='forge fractal', description='Opt-in Fractal execution and read-only observability for Forge')
17
34
  sub = p.add_subparsers(dest='command', required=True)
18
- install = sub.add_parser('install')
35
+ install = sub.add_parser('install', help='install the Fractal runtime; --dry-run previews')
19
36
  for flag in ('dry-run', 'yes', 'with-prerequisites'):
20
37
  install.add_argument('--' + flag, action='store_true')
21
- doctor = sub.add_parser('doctor')
38
+ doctor = sub.add_parser('doctor', help='whether Fractal is ready to run (exit 3 when not)')
22
39
  doctor.add_argument('--spec', action='append', default=[])
23
40
  doctor.add_argument('--json', action='store_true')
24
- listing = sub.add_parser('runs')
41
+ listing = sub.add_parser('runs', help="a repo's managed Fractal runs and their RUN ids")
25
42
  listing.add_argument('--repo')
26
43
  listing.add_argument('--json', action='store_true')
27
44
  listing.add_argument('--html', type=Path)
28
45
  for name in ('status', 'tree', 'activity', 'logs', 'costs', 'messages', 'config', 'report', 'pause', 'resume', 'stop'):
29
- command = sub.add_parser(name)
46
+ command = sub.add_parser(name, help=_HELP[name])
30
47
  command.add_argument('run')
31
48
  command.add_argument('--task')
32
49
  command.add_argument('--node')
@@ -36,10 +53,10 @@ def parser() -> argparse.ArgumentParser:
36
53
  command.add_argument('--limit', type=int, default=100)
37
54
  if name == 'logs':
38
55
  command.add_argument('--follow', action='store_true')
39
- opening = sub.add_parser('open')
56
+ opening = sub.add_parser('open', help="the run inspector in a browser: every run, or RUN's live detail")
40
57
  opening.add_argument('run', nargs='?')
41
58
  opening.add_argument('--port', type=int, default=0)
42
- selection = sub.add_parser('select')
59
+ selection = sub.add_parser('select', help="used by the runners: resolve and record a run's Fractal selection")
43
60
  selection.add_argument('--run-dir', required=True)
44
61
  selection.add_argument('--repo', required=True)
45
62
  selection.add_argument('--mode', choices=('solo', 'parallel'), required=True)