@giamme/forge 0.18.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 (78) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +16 -2
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +25 -1
  6. package/docs/commands.md +81 -14
  7. package/docs/decomposed-runs.md +114 -1
  8. package/docs/development.md +2 -1
  9. package/docs/forge-ui.md +84 -15
  10. package/docs/memory.md +25 -4
  11. package/docs/models.md +8 -0
  12. package/docs/reviews.md +122 -0
  13. package/forge +20 -3
  14. package/package.json +2 -1
  15. package/references/dataset.md +20 -1
  16. package/references/decompose.md +621 -33
  17. package/references/harnesses.md +18 -3
  18. package/references/planning.md +43 -14
  19. package/references/ui.md +53 -6
  20. package/registry.tsv +8 -3
  21. package/scripts/forge-brief.py +88 -3
  22. package/scripts/forge-compare.py +4 -3
  23. package/scripts/forge-contract.py +202 -27
  24. package/scripts/forge-control.py +117 -5
  25. package/scripts/forge-dispatch.sh +34 -5
  26. package/scripts/forge-group.py +496 -0
  27. package/scripts/forge-groups.py +89 -0
  28. package/scripts/forge-handoff.py +1128 -0
  29. package/scripts/forge-lib-group.sh +641 -0
  30. package/scripts/forge-lib-plans.sh +339 -3
  31. package/scripts/forge-lib-task.sh +197 -4
  32. package/scripts/forge-memory.sh +245 -3
  33. package/scripts/forge-parallel.sh +715 -34
  34. package/scripts/forge-planner.py +104 -8
  35. package/scripts/forge-route.py +190 -12
  36. package/scripts/forge-runs.py +9 -5
  37. package/scripts/forge-schedule.py +354 -45
  38. package/scripts/forge-solo.sh +2 -0
  39. package/scripts/forge-worktrees.py +243 -0
  40. package/scripts/forge_brief/__init__.py +294 -50
  41. package/scripts/forge_brief/answers.py +58 -11
  42. package/scripts/forge_brief/proposals.py +1630 -0
  43. package/scripts/forge_dataset/efforts.py +4 -3
  44. package/scripts/forge_dataset/export.py +24 -12
  45. package/scripts/forge_dataset/facts.py +5 -3
  46. package/scripts/forge_dataset/forecast.py +8 -18
  47. package/scripts/forge_dataset/harvest.py +204 -9
  48. package/scripts/forge_dataset/history.py +11 -6
  49. package/scripts/forge_dataset/importer.py +65 -1
  50. package/scripts/forge_dataset/names.py +66 -0
  51. package/scripts/forge_dataset/reviewers.py +5 -2
  52. package/scripts/forge_dataset/risk.py +6 -3
  53. package/scripts/forge_dataset/routing.py +6 -1
  54. package/scripts/forge_groups/__init__.py +308 -0
  55. package/scripts/forge_groups/attribute.py +289 -0
  56. package/scripts/forge_groups/review.py +286 -0
  57. package/scripts/forge_owner.py +152 -0
  58. package/scripts/forge_side/__init__.py +12 -7
  59. package/ui/docs/api.md +173 -17
  60. package/ui/forge_ui/control.py +361 -2
  61. package/ui/forge_ui/executions.py +8 -1
  62. package/ui/forge_ui/export.py +31 -4
  63. package/ui/forge_ui/groups.py +264 -0
  64. package/ui/forge_ui/models.py +70 -8
  65. package/ui/forge_ui/reader.py +262 -19
  66. package/ui/forge_ui/server.py +4 -0
  67. package/ui/forge_ui/static/app.js +93 -13
  68. package/ui/forge_ui/static/briefview.js +350 -47
  69. package/ui/forge_ui/static/diffview.js +86 -1
  70. package/ui/forge_ui/static/groupsview.js +332 -0
  71. package/ui/forge_ui/static/index.html +1 -0
  72. package/ui/forge_ui/static/panel.js +127 -7
  73. package/ui/forge_ui/static/projectsview.js +189 -10
  74. package/ui/forge_ui/static/runmodel.js +14 -3
  75. package/ui/forge_ui/static/storageview.js +91 -10
  76. package/ui/forge_ui/static/style.css +79 -5
  77. package/ui/forge_ui/static/worktreesview.js +233 -12
  78. package/ui/forge_ui/storage.py +14 -0
@@ -0,0 +1,1128 @@
1
+ #!/usr/bin/env python3
2
+ """forge handoff: a self-contained report of a run for the next session (#146).
3
+
4
+ show [RUN_DIR | --repo DIR] [--json] (the default subcommand: `forge handoff RUN_DIR`)
5
+ Everything a new session, or another harness, needs to carry a run on, in one output:
6
+ the run, the choices it was launched with, whether a scheduler lives, each task, what
7
+ needs a person, the last human changes, tasks left RUNNING by a dead scheduler, the
8
+ handoff notes and driver, and the exact commands to run next.
9
+ With no RUN_DIR it picks --repo's (default: this checkout's) newest run that is live or
10
+ has a task not MERGED, from forge's run registry.
11
+ Read-only: it writes nothing, takes no lock and never waits on one. A file that is
12
+ missing or unreadable becomes null and a `warnings` entry says why.
13
+
14
+ note RUN_DIR TEXT [--actor A] [--json]
15
+ Append one session note to handoff.notes.jsonl: what is not on disk, such as an
16
+ acceptance or a hand fix in progress. Whitespace in TEXT collapses to single spaces.
17
+ Empty text, text over 2000 characters, and text that is not valid UTF-8, is refused.
18
+ The actor defaults to cli.
19
+
20
+ claim RUN_DIR --harness H [--session S] [--take-over] [--json]
21
+ Record this session as the driver in handoff.driver.json (harness, session, since,
22
+ last_seen). The same harness and session keep since and refresh last_seen. A different
23
+ driver whose last_seen is under 12 hours ago is refused unless --take-over is given;
24
+ a different driver older than that is replaced. Replacing a different driver appends
25
+ one control.log take-over line through forge-control's audit. A control.log that is
26
+ not a regular file refuses that replacement before the driver file changes.
27
+
28
+ resume RUN_DIR [--take-over] [--harness H] [--session S] [--json]
29
+ Carry a decomposed run on from any harness. It claims the run first (like claim; a refused
30
+ claim exits 3 and does nothing else), then: with a live scheduler it only says so and points
31
+ at `forge control show` (nothing is started); a Fractal plan points at `forge fractal resume`;
32
+ otherwise each task left RUNNING by a dead scheduler has its worktree diff saved to
33
+ tasks/<id>/interrupted-<epoch>.diff, the worktree reset and cleaned (only after it passes a
34
+ guard: exactly <wt_root>/<id>, a git worktree on forge/<run_id>/<id>), the status set to
35
+ INTERRUPTED and the attempt counter rewound when attempts.tsv has no row for it. Every
36
+ INTERRUPTED task is prepared with `forge-parallel.sh retry --no-dispatch`, and the run is
37
+ started again, detached, from run.flags.json (log: resume-<epoch>.log; the exit code goes to
38
+ resume-<epoch>.done). Without run.flags.json it prints the run command to finish by hand.
39
+ FORGE_HANDOFF_NO_START=1 prints the command and starts nothing.
40
+
41
+ Exit codes: 0 ok, 2 usage or a path that is not a run dir, 3 no run to report, or another
42
+ driver still holds the run (claim without --take-over).
43
+ """
44
+ from __future__ import annotations
45
+
46
+ import argparse
47
+ import importlib.util
48
+ import json
49
+ import os
50
+ import re
51
+ import shlex
52
+ import shutil
53
+ import stat
54
+ import subprocess
55
+ import sys
56
+ import tempfile
57
+ import time
58
+ from pathlib import Path
59
+
60
+ SCRIPTS = Path(__file__).resolve().parent
61
+ sys.path.insert(0, str(SCRIPTS))
62
+ import forge_infra # noqa: E402
63
+ import forge_registry # noqa: E402
64
+
65
+ PARALLEL = str(SCRIPTS / 'forge-parallel.sh')
66
+ SWEEP_OK = re.compile(r'P[0-3]')
67
+ READ_CAP = 1 << 20 # bytes read from any one file
68
+ LOG_TAIL = 1 << 18 # bytes read from the end of control.log
69
+ GOAL_LINES = 5
70
+ CHANGES = 10
71
+ TASK_OK = frozenset('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-')
72
+ # The per-plan option files (forge-lib-plans.sh PLANS_OPTION_FILES, forge-compare.py OPTION_FILES) and the
73
+ # other choices a plan keeps. Listed here, in that order, because a shell variable cannot be imported.
74
+ OPTION_FILES = (
75
+ 'no_ripwire', 'no_memory', 'yolo_dwarf', 'yolo_qa', 'reviewer_session', 'reviewer_session_rate',
76
+ 'reviewer_session_tasks', 'implementer_session', 'fast', 'pre_review_tests', 'pre_review_parallel',
77
+ 'qa_threshold', 'timeout', 'verify_retries', 'verify_cmd', 'verify_parallel', 'setup_cmd', 'final_qa',
78
+ 'shadow_qa', 'shadow_rate', 'explore', 'escalate_after', 'retry_per_model', 'fail_first',
79
+ 'fractal-routing.json', 'fractal-selection.json', 'jev-selection.json', 'profile.json', 'routed.json',
80
+ 'qa-routing.json', 'retro_mode', 'brief', 'brief_scope', 'brief_model', 'summaries', 'summaries_model',
81
+ 'groups.tsv', 'groups.frozen', 'group_max_tasks', 'group_max_diff_kb', 'after', 'max_parallel')
82
+ FLAG_KEYS = ('retry_failed', 'infra_retries', 'sweep', 'sweep_max', 'sweep_plausible', 'sweep_ahead',
83
+ 'max_parallel', 'timeout', 'verify', 'fractal', 'argv', 'at')
84
+ JSON_KEYS = ('run', 'choices', 'flags', 'scheduler', 'tasks', 'needs_you', 'changes', 'stale', 'notes',
85
+ 'driver', 'next')
86
+ NOTE_MAX = 2000
87
+ SESSION_MAX = 200
88
+ # A different driver last seen longer ago than this is replaced without --take-over. Tests patch it.
89
+ DRIVER_STALE_S = 12 * 3600
90
+ HARNESS_ROLES = ('dwarf', 'qa') # the tasks/<id>/<role>.harness records, as forge-schedule.py stops them
91
+ GUARD_STOP_WAIT = 15.0 # seconds one forge-guard.py stop may take
92
+ HARNESS_RE = re.compile(r'[a-z0-9._-]{1,40}')
93
+ # Subcommands. Any other first word is a RUN_DIR for the default, show.
94
+ COMMANDS = ('show', 'note', 'claim', 'resume', '-h', '--help')
95
+
96
+ _control = None
97
+
98
+
99
+ class Usage(Exception):
100
+ pass
101
+
102
+
103
+ class Nothing(Exception):
104
+ pass
105
+
106
+
107
+ class Refused(Exception):
108
+ """A well-formed request the run's state does not allow. Exit 3."""
109
+
110
+
111
+ class Held(Refused):
112
+ """A different driver was seen inside the stale window. Nothing was written."""
113
+
114
+ def __init__(self, driver):
115
+ self.driver = driver
116
+
117
+ def __str__(self):
118
+ return held_message(self.driver)
119
+
120
+
121
+ class Plan:
122
+ """A run dir, read without ever blocking or writing. warnings collects what could not be read."""
123
+
124
+ def __init__(self, path):
125
+ # absolute, so the next commands still work from another directory
126
+ self.path = Path(os.path.abspath(path))
127
+ self.warnings = []
128
+
129
+ def warn(self, text):
130
+ if text not in self.warnings:
131
+ self.warnings.append(text)
132
+
133
+ def read(self, rel, tail=False):
134
+ """The text of a regular file under the run dir, or None (missing: silent; anything else warns)."""
135
+ try:
136
+ # O_NONBLOCK: a FIFO with no writer would block an open; it is not a regular file anyway.
137
+ fd = os.open(self.path / rel, os.O_RDONLY | os.O_NONBLOCK)
138
+ except FileNotFoundError:
139
+ return None
140
+ except (OSError, ValueError) as error:
141
+ self.warn(f'{rel}: unreadable ({error.__class__.__name__})')
142
+ return None
143
+ try:
144
+ info = os.fstat(fd)
145
+ if not stat.S_ISREG(info.st_mode):
146
+ self.warn(f'{rel}: not a regular file')
147
+ return None
148
+ if tail and info.st_size > LOG_TAIL:
149
+ os.lseek(fd, info.st_size - LOG_TAIL, os.SEEK_SET)
150
+ raw = os.read(fd, LOG_TAIL if tail else READ_CAP)
151
+ if not tail and info.st_size > READ_CAP:
152
+ self.warn(f'{rel}: longer than {READ_CAP} bytes, cut')
153
+ except OSError as error:
154
+ self.warn(f'{rel}: unreadable ({error.__class__.__name__})')
155
+ return None
156
+ finally:
157
+ os.close(fd)
158
+ return raw.decode('utf-8', errors='replace')
159
+
160
+ def exists(self, rel):
161
+ try:
162
+ return (self.path / rel).exists()
163
+ except (OSError, ValueError):
164
+ return False
165
+
166
+ def line(self, rel):
167
+ """The first line of a file, stripped; None when the file is missing, '' when it is empty."""
168
+ text = self.read(rel)
169
+ if text is None:
170
+ return None
171
+ return text.splitlines()[0].strip() if text.strip() else ''
172
+
173
+ def json(self, rel, kind=dict):
174
+ """A parsed JSON file of the given type, or None (a missing file is silent, bad content warns)."""
175
+ text = self.read(rel)
176
+ if text is None:
177
+ return None
178
+ try:
179
+ value = json.loads(text)
180
+ except ValueError:
181
+ self.warn(f'{rel}: not valid JSON')
182
+ return None
183
+ if not isinstance(value, kind):
184
+ self.warn(f'{rel}: not a JSON {"object" if kind is dict else "list"}')
185
+ return None
186
+ return value
187
+
188
+
189
+ # ------------------------------------------------------------------------------------ the sections
190
+
191
+ def kind_of(plan, fractal):
192
+ if (plan.path / 'tasks.tsv').is_file():
193
+ return 'fractal' if fractal else 'decomposed'
194
+ if (plan.path / 'prompt.md').is_file() and (plan.path / 'repo').is_file():
195
+ return 'solo'
196
+ return None
197
+
198
+
199
+ def is_fractal(plan):
200
+ data = plan.json('fractal-selection.json')
201
+ return bool(data and data.get('enabled'))
202
+
203
+
204
+ def run_section(plan, kind):
205
+ goal = None
206
+ text = plan.read('request.md')
207
+ if text is not None:
208
+ lines = [line.rstrip() for line in text.splitlines() if line.strip()]
209
+ goal = lines[:GOAL_LINES]
210
+ run_id = plan.line('run_id') or None
211
+ return dict(
212
+ run_id=run_id, kind=kind, goal=goal, plan=str(plan.path), repo=plan.line('repo') or None,
213
+ worktree_root=plan.line('wt_root') or None,
214
+ integration_branch=f'forge/{run_id}-integration' if run_id else None,
215
+ integration_base=plan.line('integration.base') or None,
216
+ accepted_integration=plan.line('accepted.integration') or None)
217
+
218
+
219
+ def choices_section(plan):
220
+ found = {}
221
+ for name in OPTION_FILES:
222
+ if not plan.exists(name):
223
+ continue
224
+ if name.endswith('.json'):
225
+ data = plan.json(name, (dict, list))
226
+ found[name] = json.dumps(data, separators=(',', ':'), ensure_ascii=False) if data is not None else None
227
+ else:
228
+ found[name] = plan.line(name)
229
+ return found
230
+
231
+
232
+ def flags_section(plan):
233
+ if not plan.exists('run.flags.json'):
234
+ plan.warn('run.flags.json missing (run from before 0.19)')
235
+ return None
236
+ data = plan.json('run.flags.json')
237
+ if data is None:
238
+ return None
239
+ return {key: data.get(key) for key in FLAG_KEYS} | {key: value for key, value in data.items() if key not in FLAG_KEYS}
240
+
241
+
242
+ def pid_alive(pid):
243
+ if type(pid) is not int or pid <= 0:
244
+ return False
245
+ try:
246
+ os.kill(pid, 0)
247
+ except ProcessLookupError:
248
+ return False
249
+ except PermissionError:
250
+ return True
251
+ except (OSError, OverflowError):
252
+ return False
253
+ return True
254
+
255
+
256
+ def scheduler_section(plan):
257
+ """scheduler.live names the pid; nothing here probes schedule.lock (a probe could fail a starting run)."""
258
+ live = plan.json('scheduler.live') or {}
259
+ holder = plan.json('schedule.holder') or {}
260
+ pid = live.get('pid') if type(live.get('pid')) is int else None
261
+ return dict(live=pid_alive(pid), pid=pid, started=live.get('started'),
262
+ holder=dict(pid=holder.get('pid'), command=holder.get('command'), at=holder.get('at')) if holder else None)
263
+
264
+
265
+ def tasks_section(plan):
266
+ rows, text = [], plan.read('tasks.tsv')
267
+ for line in (text or '').splitlines():
268
+ if not line.strip() or line.startswith('#'):
269
+ continue
270
+ cols = line.split('\t')
271
+ task = cols[0]
272
+ if not task or not set(task) <= TASK_OK or task in ('.', '..'):
273
+ plan.warn(f'tasks.tsv: skipped a row with the task id {task!r}')
274
+ continue
275
+ if plan.exists(f'tasks/{task}/merged'):
276
+ status = 'MERGED'
277
+ else:
278
+ words = (plan.read(f'tasks/{task}/status') or '').split()
279
+ status = words[0] if words else 'PENDING'
280
+ rows.append(dict(id=task, status=status, dwarf=(cols[4].strip() or None) if len(cols) > 4 else None))
281
+ return rows
282
+
283
+
284
+ def needs_you_section(plan, tasks, now):
285
+ items = []
286
+ pauses = None
287
+ for task in tasks:
288
+ base = f'tasks/{task["id"]}/'
289
+ if task['status'] == 'NEEDS_INPUT':
290
+ question = plan.read(base + 'needs_input.md')
291
+ items.append(dict(task=task['id'], kind='NEEDS_INPUT', question=question.rstrip() if question else None))
292
+ elif task['status'] == 'NEEDS_DECISION':
293
+ text = plan.read(base + 'decision.md')
294
+ first = text.splitlines()[0].strip() if text and text.strip() else None
295
+ items.append(dict(task=task['id'], kind='NEEDS_DECISION', reasons=first))
296
+ elif task['status'] == 'INFRA':
297
+ if pauses is None:
298
+ pauses = forge_infra.parse_pauses(plan.read('infra.paused')) or forge_infra.parse_pauses(plan.read('infra.last'))
299
+ info = forge_infra.parse_stop(plan.read(base + 'infra.txt'))
300
+ stop = forge_infra.stop_of(task['id'], info, pauses, now)
301
+ items.append(dict(task=task['id'], kind='INFRA', cause=stop['cause'], harness=stop['harness'],
302
+ model=stop['model'], stage=stop['stage'], reset_at=stop['reset_at'],
303
+ needs_you=stop['needs_you'], hint=stop['hint']))
304
+ return items
305
+
306
+
307
+ def changes_section(plan):
308
+ text = plan.read('control.log', tail=True)
309
+ entries, bad = [], 0
310
+ for line in (text or '').splitlines():
311
+ try:
312
+ entry = json.loads(line)
313
+ except ValueError:
314
+ bad += 1
315
+ continue
316
+ if isinstance(entry, dict):
317
+ entries.append(entry)
318
+ else:
319
+ bad += 1
320
+ # The first line of a tail read may be cut in the middle; that is not worth a warning.
321
+ if bad and not (bad == 1 and text and len(text) >= LOG_TAIL):
322
+ plan.warn(f'control.log: {bad} line(s) are not JSON objects, skipped')
323
+ return list(reversed(entries))[:CHANGES]
324
+
325
+
326
+ def notes_section(plan):
327
+ text = plan.read('handoff.notes.jsonl')
328
+ notes, bad = [], 0
329
+ for line in (text or '').splitlines():
330
+ if not line.strip():
331
+ continue
332
+ try:
333
+ note = json.loads(line)
334
+ except ValueError:
335
+ bad += 1
336
+ continue
337
+ if isinstance(note, dict):
338
+ notes.append(dict(at=note.get('at'), actor=note.get('actor'), text=note.get('text')))
339
+ else:
340
+ bad += 1
341
+ if bad:
342
+ plan.warn(f'handoff.notes.jsonl: {bad} line(s) are not JSON objects, skipped')
343
+ return list(reversed(notes))
344
+
345
+
346
+ def driver_section(plan):
347
+ data = plan.json('handoff.driver.json')
348
+ if data is None:
349
+ return None
350
+ return {key: data.get(key) for key in ('harness', 'session', 'since', 'last_seen')}
351
+
352
+
353
+ def next_section(plan, run, scheduler, tasks, needs):
354
+ here = str(plan.path)
355
+ q = shlex.quote
356
+ steps = []
357
+ open_tasks = [task for task in tasks if task['status'] != 'MERGED']
358
+ live = scheduler['live']
359
+ if live:
360
+ steps.append(dict(command=f'forge control show {q(here)}', why='the run is live: its state and controls'))
361
+ elif open_tasks:
362
+ steps.append(dict(command=f'forge handoff resume {q(here)}', why='no scheduler is live and work is left'))
363
+ if run['kind'] == 'fractal':
364
+ steps.append(dict(command=f'forge fractal resume {q(run["run_id"] or here)}',
365
+ why='a Fractal-backed run: recover its recorded executions'))
366
+ for item in needs:
367
+ if item['kind'] == 'NEEDS_INPUT':
368
+ verb = f'forge control retry {q(here)} {q(item["task"])}' if live else f'{PARALLEL} retry {q(here)} {q(item["task"])}'
369
+ steps.append(dict(command=verb + ' --answer "…"', why=f'answer the question of {item["task"]}'))
370
+ elif item['kind'] == 'NEEDS_DECISION' and live:
371
+ steps.append(dict(command=f'forge control retry {q(here)} {q(item["task"])} --decide retry=N --reason "…" --approved',
372
+ why=f'{item["task"]} needs a decision (or --decide threshold=Pn, or --dwarf SPEC)'))
373
+ if tasks and not open_tasks and run['kind'] != 'solo':
374
+ steps.append(dict(command=f'{PARALLEL} integrate {q(here)} --approved',
375
+ why='every task is merged; run this only on the user\'s word'))
376
+ return steps
377
+
378
+
379
+ # ------------------------------------------------------------------------------------ the report
380
+
381
+ def report(path):
382
+ plan = Plan(path)
383
+ fractal = is_fractal(plan)
384
+ kind = kind_of(plan, fractal)
385
+ if kind is None:
386
+ raise Usage(f'{path}: not a forge run dir (no tasks.tsv, and no prompt.md with a repo file)')
387
+ run = run_section(plan, kind)
388
+ scheduler = scheduler_section(plan)
389
+ tasks = tasks_section(plan)
390
+ needs = needs_you_section(plan, tasks, time.time())
391
+ stale = [] if scheduler['live'] else [dict(task=task['id'], note='left RUNNING with no live process')
392
+ for task in tasks if task['status'] == 'RUNNING']
393
+ out = dict(run=run, choices=choices_section(plan), flags=flags_section(plan), scheduler=scheduler, tasks=tasks,
394
+ needs_you=needs, changes=changes_section(plan), stale=stale, notes=notes_section(plan),
395
+ driver=driver_section(plan), next=next_section(plan, run, scheduler, tasks, needs))
396
+ out['warnings'] = plan.warnings
397
+ return out
398
+
399
+
400
+ def when(value):
401
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
402
+ try:
403
+ return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(value))
404
+ except (ValueError, OverflowError, OSError):
405
+ pass
406
+ return '' if value is None else str(value)
407
+
408
+
409
+ def render(data):
410
+ out = []
411
+ run, sched = data['run'], data['scheduler']
412
+
413
+ def head(title):
414
+ out.extend(['', title])
415
+
416
+ out.append(f'forge handoff: run {run["run_id"] or "(no run_id)"}')
417
+ head('The run')
418
+ out.append(f' kind {run["kind"]}')
419
+ if run['goal'] is None:
420
+ out.append(' goal (no request.md)')
421
+ else:
422
+ out.extend([' goal ' + (line if i == 0 else ' ' + line) for i, line in enumerate(run['goal'])] or [' goal (empty)'])
423
+ for label, key in (('plan', 'plan'), ('repo', 'repo'), ('worktrees', 'worktree_root'),
424
+ ('integration', 'integration_branch'), ('base', 'integration_base'),
425
+ ('accepted', 'accepted_integration')):
426
+ if run[key]:
427
+ out.append(f' {label:<12} {run[key]}')
428
+ head('Launch choices')
429
+ for name, value in data['choices'].items():
430
+ out.append(f' {name:<24} {"(present)" if value == "" else "(unreadable)" if value is None else value}')
431
+ if not data['choices']:
432
+ out.append(' (no option files)')
433
+ if data['flags'] is None:
434
+ out.append(' run.flags.json missing (run from before 0.19)' if not any('run.flags.json:' in w for w in data['warnings'])
435
+ else ' run.flags.json unreadable')
436
+ else:
437
+ for key, value in data['flags'].items():
438
+ shown = when(value) if key == 'at' else json.dumps(value, ensure_ascii=False)
439
+ out.append(f' {key:<24} {shown}')
440
+ head('Scheduler')
441
+ if sched['live']:
442
+ out.append(f' live, pid {sched["pid"]}, started {when(sched["started"])}')
443
+ else:
444
+ out.append(' not live' + (f' (scheduler.live names pid {sched["pid"]}, which is gone)' if sched['pid'] else ''))
445
+ if sched['holder']:
446
+ h = sched['holder']
447
+ out.append(f' schedule.holder: {h["command"]} (pid {h["pid"]}, since {when(h["at"])})')
448
+ head('Tasks')
449
+ for task in data['tasks']:
450
+ out.append(f' {task["id"]:<24} {task["status"]:<15} {task["dwarf"] or "-"}')
451
+ if not data['tasks']:
452
+ out.append(' (none)')
453
+ head('Needs you')
454
+ for item in data['needs_you']:
455
+ if item['kind'] == 'NEEDS_INPUT':
456
+ out.append(f' {item["task"]}: NEEDS_INPUT, the question:')
457
+ out.extend(' ' + line for line in (item['question'] or '(needs_input.md missing)').splitlines())
458
+ elif item['kind'] == 'NEEDS_DECISION':
459
+ out.append(f' {item["task"]}: NEEDS_DECISION {item["reasons"] or "(decision.md missing)"}')
460
+ else:
461
+ where = '/'.join(part for part in (item['harness'], item['model']) if part) or 'unknown'
462
+ line = f' {item["task"]}: INFRA, {item["cause"]} on {where}'
463
+ if item['stage']:
464
+ line += f' ({item["stage"]} stage)'
465
+ if item['needs_you']:
466
+ line += ', needs you'
467
+ out.append(line)
468
+ if item['hint']:
469
+ out.append(f' {item["hint"]}')
470
+ if not data['needs_you']:
471
+ out.append(' nothing')
472
+ head(f'Human changes (last {CHANGES}, newest first)')
473
+ for entry in data['changes']:
474
+ bits = [when(entry.get('at')), str(entry.get('actor') or '?'), str(entry.get('action') or '?')]
475
+ for key in ('task', 'key', 'value'):
476
+ if entry.get(key) not in (None, ''):
477
+ bits.append(f'{key}={entry[key]}')
478
+ if entry.get('previous') not in (None, ''):
479
+ bits.append(f'(was {entry["previous"]})')
480
+ out.append(' ' + ' '.join(bits))
481
+ if not data['changes']:
482
+ out.append(' none')
483
+ head('Stale')
484
+ for item in data['stale']:
485
+ out.append(f' {item["task"]}: {item["note"]}')
486
+ if not data['stale']:
487
+ out.append(' none')
488
+ head('Notes and driver')
489
+ driver = data['driver']
490
+ if driver:
491
+ out.append(' driver: ' + ', '.join(f'{k} {when(v) if k in ("since", "last_seen") else v}' for k, v in driver.items() if v is not None))
492
+ else:
493
+ out.append(' driver: none')
494
+ for note in data['notes']:
495
+ out.append(f' {when(note["at"])} {note["actor"] or "?"}: {note["text"]}')
496
+ if not data['notes']:
497
+ out.append(' notes: none')
498
+ head('Next commands')
499
+ for step in data['next']:
500
+ out.append(f' {step["command"]}')
501
+ out.append(f' # {step["why"]}')
502
+ if not data['next']:
503
+ out.append(' (nothing to run)')
504
+ if data['warnings']:
505
+ head('Warnings')
506
+ out.extend(' ' + w for w in data['warnings'])
507
+ return '\n'.join(out) + '\n'
508
+
509
+
510
+ # ------------------------------------------------------------------------------------ choosing a run
511
+
512
+ def git_top(directory):
513
+ try:
514
+ result = subprocess.run(['git', '-C', str(directory), 'rev-parse', '--show-toplevel'], capture_output=True,
515
+ text=True, timeout=20)
516
+ except (OSError, subprocess.SubprocessError):
517
+ return None
518
+ return result.stdout.strip() or None if result.returncode == 0 else None
519
+
520
+
521
+ def newest_open_run(repo):
522
+ """The repo's newest registered run (by run dir mtime) that is live or has a task not MERGED."""
523
+ registry = forge_registry.runs_registry(repo)
524
+ try:
525
+ lines = registry.read_text(errors='replace').splitlines()
526
+ except OSError:
527
+ return None
528
+ candidates = []
529
+ for line in lines:
530
+ line = line.strip()
531
+ if not line or line.startswith('#') or not os.path.isabs(line):
532
+ continue
533
+ try:
534
+ candidates.append((os.stat(line).st_mtime, line))
535
+ except (OSError, ValueError):
536
+ continue
537
+ for _, path in sorted(candidates, reverse=True):
538
+ plan = Plan(path)
539
+ if not (plan.path / 'tasks.tsv').is_file():
540
+ continue
541
+ if scheduler_section(plan)['live'] or any(task['status'] != 'MERGED' for task in tasks_section(plan)):
542
+ return path
543
+ return None
544
+
545
+
546
+ def resolve(args):
547
+ if args.run_dir and args.repo:
548
+ raise Usage('give a RUN_DIR or --repo, not both')
549
+ if args.run_dir:
550
+ return args.run_dir
551
+ if args.repo:
552
+ if not os.path.isdir(args.repo):
553
+ raise Usage(f'{args.repo}: not a directory')
554
+ repo = git_top(args.repo) or args.repo
555
+ else:
556
+ repo = git_top(os.getcwd())
557
+ if repo is None:
558
+ raise Usage('not inside a git checkout: give a RUN_DIR or --repo DIR')
559
+ found = newest_open_run(repo)
560
+ if found is None:
561
+ raise Nothing(f'no active or unfinished run for {repo}')
562
+ return found
563
+
564
+
565
+ def cmd_show(args):
566
+ try:
567
+ path = resolve(args)
568
+ data = report(path)
569
+ except Usage as error:
570
+ print(f'forge handoff: {error}', file=sys.stderr)
571
+ return 2
572
+ except Nothing as error:
573
+ print(f'forge handoff: {error}', file=sys.stderr)
574
+ return 3
575
+ if args.json:
576
+ print(json.dumps(data, indent=2, ensure_ascii=False))
577
+ else:
578
+ sys.stdout.write(render(data))
579
+ return 0
580
+
581
+
582
+ # ------------------------------------------------------------------------------------ notes and driver
583
+
584
+ def control():
585
+ """forge-control.py, loaded by path: its file name is not importable.
586
+
587
+ audit, append_line, write_atomic and control_lock are the writers to reuse.
588
+ """
589
+ global _control
590
+ if _control is None:
591
+ spec = importlib.util.spec_from_file_location('forge_control_handoff', SCRIPTS / 'forge-control.py')
592
+ module = importlib.util.module_from_spec(spec)
593
+ spec.loader.exec_module(module)
594
+ _control = module
595
+ return _control
596
+
597
+
598
+ def require_run(path):
599
+ """The canonical plan dir, or Usage. The same shape show accepts."""
600
+ message = f'{path}: not a forge run dir (no tasks.tsv, and no prompt.md with a repo file)'
601
+ if not os.path.isdir(path):
602
+ raise Usage(message)
603
+ plan = os.path.realpath(path)
604
+ root = Path(plan)
605
+ if (root / 'tasks.tsv').is_file() or ((root / 'prompt.md').is_file() and (root / 'repo').is_file()):
606
+ return plan
607
+ raise Usage(message)
608
+
609
+
610
+ def collapse_text(text):
611
+ return re.sub(r'\s+', ' ', text).strip()
612
+
613
+
614
+ def require_utf8(value, what):
615
+ """Usage when value cannot be stored as UTF-8.
616
+
617
+ A non-UTF-8 argv byte arrives surrogate-escaped. The writers encode with UTF-8,
618
+ which would otherwise raise UnicodeEncodeError and exit 1.
619
+ """
620
+ try:
621
+ value.encode('utf-8')
622
+ except UnicodeEncodeError:
623
+ raise Usage(f'the {what} is not valid text') from None
624
+ return value
625
+
626
+
627
+ def note_text(text):
628
+ collapsed = collapse_text(text)
629
+ if not collapsed:
630
+ raise Usage('the note is empty')
631
+ if len(collapsed) > NOTE_MAX:
632
+ raise Usage(f'the note is longer than {NOTE_MAX} characters')
633
+ return require_utf8(collapsed, 'note')
634
+
635
+
636
+ def check_harness(harness):
637
+ if not isinstance(harness, str) or HARNESS_RE.fullmatch(harness) is None:
638
+ raise Usage('harness must match [a-z0-9._-]{1,40}')
639
+
640
+
641
+ def check_session(session):
642
+ """None when omitted. A present id has no whitespace and is at most 200 characters."""
643
+ if session is None:
644
+ return None
645
+ if (not isinstance(session, str) or not session or any(ch.isspace() for ch in session)
646
+ or len(session) > SESSION_MAX):
647
+ raise Usage('session must be an id with no whitespace, at most 200 characters')
648
+ return require_utf8(session, 'session')
649
+
650
+
651
+ def _epoch(value):
652
+ """A finite JSON number, or None. Bool is a subclass of int and is not a timestamp."""
653
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
654
+ return None
655
+ if value != value or value in (float('inf'), float('-inf')):
656
+ return None
657
+ return value
658
+
659
+
660
+ def parse_driver(raw):
661
+ """The driver record, or None when the file is missing, unreadable or not that record."""
662
+ if not raw or not str(raw).strip():
663
+ return None
664
+ try:
665
+ data = json.loads(raw)
666
+ except ValueError:
667
+ return None
668
+ if not isinstance(data, dict):
669
+ return None
670
+ harness = data.get('harness')
671
+ if not isinstance(harness, str) or HARNESS_RE.fullmatch(harness) is None:
672
+ return None
673
+ if 'session' not in data or data.get('session') is None:
674
+ session = None
675
+ else:
676
+ session = data.get('session')
677
+ if (not isinstance(session, str) or not session or any(ch.isspace() for ch in session)
678
+ or len(session) > SESSION_MAX):
679
+ return None
680
+ since, last_seen = _epoch(data.get('since')), _epoch(data.get('last_seen'))
681
+ if since is None or last_seen is None:
682
+ return None
683
+ return {'harness': harness, 'session': session, 'since': since, 'last_seen': last_seen}
684
+
685
+
686
+ def read_driver(ctrl, plan):
687
+ """None when the file is absent, unreadable, or not a driver record."""
688
+ try:
689
+ raw = ctrl.read_file(plan, 'handoff.driver.json')
690
+ except OSError:
691
+ return None
692
+ return parse_driver(raw)
693
+
694
+
695
+ def driver_ref(driver):
696
+ """'<harness>/<session>' as control.log records a driver. An omitted session is empty."""
697
+ session = driver.get('session') or ''
698
+ return f"{driver['harness']}/{session}"
699
+
700
+
701
+ def held_message(driver):
702
+ session = driver.get('session')
703
+ name = driver['harness'] if not session else f"{driver['harness']}/{session}"
704
+ return f'{name} holds this run, last seen {when(driver["last_seen"])} ({driver["last_seen"]})'
705
+
706
+
707
+ def under_lock(ctrl, plan, work):
708
+ """Run work(ctrl) while holding the plan's control lock. Map control's errors to ours."""
709
+ try:
710
+ with ctrl.control_lock(plan):
711
+ return work(ctrl)
712
+ except Held:
713
+ raise # a refused claim, not a control error: nothing was written
714
+ except ctrl.Invalid as error:
715
+ raise Usage(str(error)) from error
716
+ except ctrl.Refused as error:
717
+ raise Refused(str(error)) from error
718
+
719
+
720
+ def cmd_note(args):
721
+ text = note_text(args.text)
722
+ actor = args.actor.strip()
723
+ if not actor:
724
+ raise Usage('the actor is empty')
725
+ actor = require_utf8(actor, 'actor')
726
+ plan = require_run(args.run_dir)
727
+ line = json.dumps({'at': time.time(), 'actor': actor, 'text': text}, ensure_ascii=False) + '\n'
728
+
729
+ def write(ctrl):
730
+ ctrl.append_line(plan, 'handoff.notes.jsonl', line)
731
+
732
+ under_lock(control(), plan, write)
733
+ print(json.dumps({'noted': True}) if args.json else 'noted')
734
+ return 0
735
+
736
+
737
+ def claim_run(plan, harness, session, take_over):
738
+ """Record harness/session as the run's driver. (record, took_over, previous); Held when refused."""
739
+
740
+ def decide(ctrl):
741
+ now = time.time()
742
+ previous = read_driver(ctrl, plan)
743
+ if previous is None:
744
+ record = {'harness': harness, 'session': session, 'since': now, 'last_seen': now}
745
+ took_over = False
746
+ elif previous['harness'] == harness and previous['session'] == session:
747
+ record = {'harness': harness, 'session': session, 'since': previous['since'], 'last_seen': now}
748
+ took_over = False
749
+ elif now - previous['last_seen'] < DRIVER_STALE_S and not take_over:
750
+ raise Held(previous)
751
+ else:
752
+ record = {'harness': harness, 'session': session, 'since': now, 'last_seen': now}
753
+ took_over = True
754
+ if took_over:
755
+ # Same order as forge-control change: an unsafe log refuses the take-over
756
+ # before the driver file changes, so a failed audit cannot leave the new driver.
757
+ ctrl.probe(plan, 'control.log')
758
+ ctrl.write_atomic(plan, 'handoff.driver.json', json.dumps(record, ensure_ascii=False) + '\n')
759
+ if took_over:
760
+ ctrl.audit(plan, 'cli', 'take-over', None, 'driver', driver_ref(record), driver_ref(previous))
761
+ return record, took_over, previous
762
+
763
+ return under_lock(control(), plan, decide)
764
+
765
+
766
+ def cmd_claim(args):
767
+ check_harness(args.harness)
768
+ session = check_session(args.session)
769
+ plan = require_run(args.run_dir)
770
+ record, took_over, previous = claim_run(plan, args.harness, session, args.take_over)
771
+ if args.json:
772
+ print(json.dumps({'driver': record, 'took_over': took_over, 'previous': previous}, ensure_ascii=False))
773
+ else:
774
+ print('took over' if took_over else 'claimed')
775
+ return 0
776
+
777
+
778
+ # ------------------------------------------------------------------------------------ resume
779
+
780
+ def parallel_script():
781
+ """forge-parallel.sh, or FORGE_HANDOFF_PARALLEL (tests point it at a fake)."""
782
+ return os.environ.get('FORGE_HANDOFF_PARALLEL') or PARALLEL
783
+
784
+
785
+ def run_command(plan, flags):
786
+ """The `forge-parallel.sh run` argv that repeats a run from its run.flags.json (a dict or None)."""
787
+ flags = flags if isinstance(flags, dict) else {}
788
+
789
+ def whole(key, least):
790
+ value = flags.get(key)
791
+ return value if type(value) is int and value >= least else None
792
+
793
+ command = ['/bin/bash', parallel_script(), 'run', str(plan)]
794
+ for key, option, least in (('retry_failed', '--retry-failed', 0), ('infra_retries', '--infra-retries', 0)):
795
+ if whole(key, least) is not None:
796
+ command += [option, str(flags[key])]
797
+ sweep = flags.get('sweep')
798
+ if isinstance(sweep, str) and SWEEP_OK.fullmatch(sweep):
799
+ command += ['--sweep', sweep]
800
+ if whole('sweep_max', 1) is not None:
801
+ command += ['--sweep-max', str(flags['sweep_max'])]
802
+ if flags.get('sweep_plausible') is True:
803
+ command.append('--sweep-plausible')
804
+ if flags.get('sweep_ahead') is True:
805
+ command.append('--sweep-ahead')
806
+ if whole('max_parallel', 1) is not None:
807
+ command += ['--max-parallel', str(flags['max_parallel'])]
808
+ if whole('timeout', 1) is not None:
809
+ command += ['--timeout', str(flags['timeout'])]
810
+ if isinstance(flags.get('verify'), str) and flags['verify']:
811
+ command += ['--verify', flags['verify']]
812
+ if flags.get('fractal') is True:
813
+ command.append('--fractal')
814
+ elif flags.get('fractal') is False:
815
+ command.append('--no-fractal')
816
+ return command
817
+
818
+
819
+ def git_env():
820
+ env = dict(os.environ)
821
+ for key in ('GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_PREFIX'):
822
+ env.pop(key, None)
823
+ return env
824
+
825
+
826
+ def git(wt, *args, env=None, check=False):
827
+ result = subprocess.run(['git', '-C', str(wt), *args], capture_output=True, env=env or git_env(), timeout=600)
828
+ if check and result.returncode != 0:
829
+ raise OSError(f'git {args[0]} failed: {result.stderr.decode("utf-8", "replace").strip()[:200]}')
830
+ return result
831
+
832
+
833
+ def worktree_guard(wt_root, run_id, task):
834
+ """(worktree path, None) when it is safe to reset, else (None, why not).
835
+
836
+ The path must be exactly realpath(<wt_root>/<id>): not a symlink, not reached through one. It must be a
837
+ directory, the top of a linked git worktree, with forge/<run_id>/<id> checked out.
838
+ """
839
+ if not wt_root or not run_id:
840
+ return None, 'the plan has no wt_root or run_id'
841
+ lexical = os.path.join(wt_root, task)
842
+ try:
843
+ real = os.path.realpath(lexical)
844
+ if os.path.islink(lexical) or real != os.path.join(os.path.realpath(wt_root), task):
845
+ return None, f'{lexical} is not exactly <wt_root>/{task} (a symlink)'
846
+ if not os.path.isdir(real):
847
+ return None, f'{real} is not a directory'
848
+ top = git(real, 'rev-parse', '--show-toplevel')
849
+ if top.returncode != 0 or os.path.realpath(top.stdout.decode('utf-8', 'replace').strip()) != real:
850
+ return None, f'{real} is not the top of a git worktree'
851
+ gdir = git(real, 'rev-parse', '--absolute-git-dir')
852
+ common = git(real, 'rev-parse', '--git-common-dir')
853
+ if gdir.returncode != 0 or common.returncode != 0:
854
+ return None, f'{real} is not a git worktree'
855
+ common_dir = os.path.realpath(os.path.join(real, common.stdout.decode('utf-8', 'replace').strip()))
856
+ if os.path.realpath(gdir.stdout.decode('utf-8', 'replace').strip()) == common_dir:
857
+ return None, f'{real} is a main checkout, not a linked worktree'
858
+ branch = git(real, 'symbolic-ref', '-q', '--short', 'HEAD')
859
+ wanted = f'forge/{run_id}/{task}'
860
+ if branch.stdout.decode('utf-8', 'replace').strip() != wanted:
861
+ return None, f'{real} is not on branch {wanted}'
862
+ except (OSError, ValueError, subprocess.SubprocessError) as error:
863
+ return None, f'{lexical}: {error}'
864
+ return real, None
865
+
866
+
867
+ def save_diff(wt, dest):
868
+ """Everything uncommitted in wt, untracked files included, written to dest. The real index is not touched:
869
+ the changes are staged in a scratch index (GIT_INDEX_FILE) and read from there."""
870
+ scratch = tempfile.mkdtemp(prefix='forge-handoff-index.')
871
+ try:
872
+ env = dict(git_env(), GIT_INDEX_FILE=os.path.join(scratch, 'index'))
873
+ git(wt, 'read-tree', 'HEAD', env=env, check=True)
874
+ git(wt, 'add', '-A', env=env, check=True)
875
+ diff = git(wt, 'diff', '--cached', '--binary', 'HEAD', env=env, check=True).stdout
876
+ tmp = f'{dest}.{os.getpid()}.tmp'
877
+ try:
878
+ with open(tmp, 'wb') as handle:
879
+ handle.write(diff)
880
+ handle.flush()
881
+ os.fsync(handle.fileno())
882
+ os.replace(tmp, dest)
883
+ finally:
884
+ if os.path.exists(tmp):
885
+ os.unlink(tmp)
886
+ finally:
887
+ shutil.rmtree(scratch, ignore_errors=True)
888
+
889
+
890
+ def attempt_rewound(ctrl, plan, task):
891
+ """Write the attempt counter back by one when attempts.tsv has no row for it. Whether it did."""
892
+ text = ctrl.read_file(plan, f'tasks/{task}/attempt')
893
+ word = (text or '').split()
894
+ if not word or not word[0].isdigit() or int(word[0]) < 1:
895
+ return False
896
+ number = int(word[0])
897
+ rows = (ctrl.read_file(plan, f'tasks/{task}/attempts.tsv') or '').splitlines()
898
+ for row in rows:
899
+ cols = row.split('\t')
900
+ if len(cols) > 1 and cols[1].strip() == str(number):
901
+ return False
902
+ ctrl.write_atomic(plan, f'tasks/{task}/attempt', f'{number - 1}\n')
903
+ return True
904
+
905
+
906
+ def stop_task_harnesses(plan, task):
907
+ """Stop what a dead scheduler left running for this task: forge-guard.py stop on each tasks/<id>/<role>.harness.
908
+
909
+ The next scheduler start does this for RUNNING tasks, but resume turns them INTERRUPTED first, and a
910
+ new attempt deletes the record without stopping its process. (ok, why not): not ok means a record could
911
+ not be stopped, and the worktree must not be reset under a worker that may still be writing to it.
912
+ """
913
+ guard = str(SCRIPTS / 'forge-guard.py')
914
+ tdir = os.path.join(str(plan), 'tasks', task)
915
+ for role in HARNESS_ROLES:
916
+ record = os.path.join(tdir, f'{role}.harness')
917
+ if not os.path.lexists(record):
918
+ continue
919
+ if os.path.islink(record) or not os.path.isfile(record):
920
+ return False, f'{role}.harness is not a regular file'
921
+ try:
922
+ result = subprocess.run([sys.executable, guard, 'stop', record], capture_output=True, text=True,
923
+ stdin=subprocess.DEVNULL, timeout=GUARD_STOP_WAIT)
924
+ except (OSError, subprocess.SubprocessError) as error:
925
+ return False, f'the {role} harness could not be stopped ({error.__class__.__name__})'
926
+ if result.returncode != 0 or os.path.lexists(record):
927
+ return False, f'the {role} harness could not be stopped'
928
+ return True, None
929
+
930
+
931
+ def interrupted_event(plan, task):
932
+ """The run dataset's record of a task the scheduler would have marked INTERRUPTED. Fail-open."""
933
+ try:
934
+ if str(SCRIPTS) not in sys.path:
935
+ sys.path.insert(0, str(SCRIPTS))
936
+ from forge_dataset.capture import point
937
+ point('sched_terminal', str(plan), task, dict(status='INTERRUPTED'))
938
+ except Exception:
939
+ pass
940
+
941
+
942
+ def recover_task(ctrl, plan, wt_root, run_id, task, warn):
943
+ """Save, reset and mark one stale RUNNING task. The result row, or None when it was skipped."""
944
+ wt, why = worktree_guard(wt_root, run_id, task)
945
+ if wt is None:
946
+ warn(f'{task}: skipped, {why}')
947
+ return None
948
+ if scheduler_section(Plan(plan))['live']:
949
+ warn(f'{task}: skipped, a scheduler started while resume was running')
950
+ return None
951
+ stopped, why = stop_task_harnesses(plan, task)
952
+ if not stopped:
953
+ warn(f'{task}: skipped, {why}; the worktree is untouched')
954
+ return None
955
+ dest = os.path.join(str(plan), 'tasks', task, f'interrupted-{int(time.time())}.diff')
956
+ try:
957
+ save_diff(wt, dest)
958
+ except (OSError, subprocess.SubprocessError) as error:
959
+ warn(f'{task}: skipped, the diff could not be saved ({error}); the worktree is untouched')
960
+ return None
961
+ row = {'task': task, 'diff': dest, 'reset': False, 'attempt_rewound': False}
962
+ try:
963
+ git(wt, 'reset', '--hard', 'HEAD', check=True)
964
+ git(wt, 'clean', '-fd', check=True)
965
+ row['reset'] = True
966
+ except (OSError, subprocess.SubprocessError) as error:
967
+ warn(f'{task}: the worktree reset failed ({error}); the diff is saved in {dest}')
968
+ return row
969
+ try:
970
+ ctrl.write_atomic(str(plan), f'tasks/{task}/status', 'INTERRUPTED\n')
971
+ interrupted_event(plan, task)
972
+ row['attempt_rewound'] = attempt_rewound(ctrl, str(plan), task)
973
+ except (OSError, ctrl.Invalid) as error:
974
+ warn(f'{task}: could not update its status or attempt counter ({error})')
975
+ return row
976
+
977
+
978
+ def prepare_task(plan, task):
979
+ """forge-parallel.sh retry PLAN TASK --no-dispatch. {task, ok, message}."""
980
+ command = ['/bin/bash', parallel_script(), 'retry', str(plan), task, '--no-dispatch']
981
+ try:
982
+ result = subprocess.run(command, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=600)
983
+ except (OSError, subprocess.SubprocessError) as error:
984
+ return {'task': task, 'ok': False, 'message': str(error)}
985
+ message = (result.stderr.strip() or result.stdout.strip()).splitlines()
986
+ return {'task': task, 'ok': result.returncode == 0, 'message': message[-1] if message else ''}
987
+
988
+
989
+ def start_run(plan, command):
990
+ """Start the run detached. {pid, log, done}. The wrapper writes the exit code to <done> when the run ends."""
991
+ stamp = int(time.time())
992
+ log, done = os.path.join(plan, f'resume-{stamp}.log'), os.path.join(plan, f'resume-{stamp}.done')
993
+ wrapper = '"${@:2}"; rc=$?; printf "%s\\n" "$rc" > "$1.tmp" && mv -f "$1.tmp" "$1"; exit "$rc"'
994
+ with open(log, 'ab') as out:
995
+ process = subprocess.Popen(['/bin/bash', '-c', wrapper, 'forge-resume', done, *command], stdin=subprocess.DEVNULL,
996
+ stdout=out, stderr=subprocess.STDOUT, start_new_session=True, cwd=plan)
997
+ return {'pid': process.pid, 'log': log, 'done': done}
998
+
999
+
1000
+ def cmd_resume(args):
1001
+ check_harness(args.harness)
1002
+ session = check_session(args.session)
1003
+ plan = require_run(args.run_dir)
1004
+ warnings = []
1005
+
1006
+ def warn(text):
1007
+ warnings.append(text)
1008
+ print(f'forge handoff: warning: {text}', file=sys.stderr)
1009
+
1010
+ if not (Path(plan) / 'tasks.tsv').is_file():
1011
+ raise Usage(f'{plan}: resume needs a decomposed run (tasks.tsv)') # before the claim: a solo run is not marked
1012
+ claim_run(plan, args.harness, session, args.take_over) # Held (a refused claim) exits 3 before anything else
1013
+ out = dict(live=False, recovered=[], prepared=[], started=None, command=[])
1014
+ view = Plan(plan)
1015
+ scheduler = scheduler_section(view)
1016
+ quote = shlex.quote
1017
+
1018
+ def finish(*lines):
1019
+ if args.json:
1020
+ print(json.dumps(out, indent=2, ensure_ascii=False))
1021
+ else:
1022
+ for line in lines:
1023
+ print(line)
1024
+ return 0
1025
+
1026
+ if scheduler['live']:
1027
+ out['live'] = True
1028
+ return finish(f'the run is live (scheduler pid {scheduler["pid"]}) and is being followed; nothing was started',
1029
+ f'forge control show {quote(plan)}')
1030
+ if is_fractal(view):
1031
+ run_id = view.line('run_id')
1032
+ return finish('a Fractal plan is not restarted here; recover its recorded executions:',
1033
+ f'forge fractal resume {quote(run_id or plan)}')
1034
+
1035
+ ctrl, wt_root, run_id = control(), view.line('wt_root'), view.line('run_id')
1036
+ for task in tasks_section(view):
1037
+ if task['status'] == 'RUNNING':
1038
+ row = recover_task(ctrl, plan, wt_root, run_id, task['id'], warn)
1039
+ if row is not None:
1040
+ out['recovered'].append(row)
1041
+ for task in tasks_section(Plan(plan)):
1042
+ if task['status'] == 'INTERRUPTED':
1043
+ result = prepare_task(plan, task['id'])
1044
+ out['prepared'].append(result)
1045
+ if not result['ok']:
1046
+ warn(f'{task["id"]}: could not be prepared for a retry: {result["message"]}')
1047
+
1048
+ flags_view = Plan(plan)
1049
+ flags = flags_view.json('run.flags.json')
1050
+ flags_unreadable = flags is None and flags_view.exists('run.flags.json')
1051
+ out['command'] = run_command(plan, flags)
1052
+ lines = [f'recovered {len(out["recovered"])} task(s), prepared {sum(1 for p in out["prepared"] if p["ok"])}']
1053
+ if flags_unreadable:
1054
+ lines += ['run.flags.json is not readable, so the run is not restarted. Complete it by hand:',
1055
+ ' ' + shlex.join(out['command'])]
1056
+ return finish(*lines)
1057
+ if flags is None:
1058
+ lines += ['this run predates 0.19 (no run.flags.json), so it is not restarted. Complete it by hand:',
1059
+ ' ' + shlex.join(out['command'])]
1060
+ return finish(*lines)
1061
+ if os.environ.get('FORGE_HANDOFF_NO_START') == '1':
1062
+ lines += ['FORGE_HANDOFF_NO_START=1: not started. The command:', ' ' + shlex.join(out['command'])]
1063
+ return finish(*lines)
1064
+ try:
1065
+ out['started'] = start_run(plan, out['command'])
1066
+ except OSError as error:
1067
+ print(f'forge handoff: the run could not be started: {error}', file=sys.stderr)
1068
+ return 1
1069
+ started = out['started']
1070
+ lines += [f'started the run, pid {started["pid"]}', f' log {started["log"]}',
1071
+ f' done {started["done"]} (written with the exit code when the run ends)',
1072
+ f'forge control show {quote(plan)}']
1073
+ return finish(*lines)
1074
+
1075
+
1076
+ def build_parser():
1077
+ parser = argparse.ArgumentParser(prog='forge handoff', description=__doc__.split('\n\n')[0])
1078
+ sub = parser.add_subparsers(dest='command', metavar='{show,note,claim,resume}')
1079
+ show = sub.add_parser('show', help='report a run (the default)')
1080
+ show.add_argument('run_dir', nargs='?', metavar='RUN_DIR')
1081
+ show.add_argument('--repo', metavar='DIR', help="report DIR's newest active or unfinished run")
1082
+ show.add_argument('--json', action='store_true', help='one JSON object instead of text')
1083
+ show.set_defaults(func=cmd_show)
1084
+ note = sub.add_parser('note', help='append a session note to handoff.notes.jsonl')
1085
+ note.add_argument('run_dir', metavar='RUN_DIR')
1086
+ note.add_argument('text', metavar='TEXT')
1087
+ note.add_argument('--actor', default='cli', help='who is writing (default cli)')
1088
+ note.add_argument('--json', action='store_true', help='print {"noted": true}')
1089
+ note.set_defaults(func=cmd_note)
1090
+ claim = sub.add_parser('claim', help='claim the run, or take it over from another driver')
1091
+ claim.add_argument('run_dir', metavar='RUN_DIR')
1092
+ claim.add_argument('--harness', required=True, metavar='H', help='a short word: [a-z0-9._-]{1,40}')
1093
+ claim.add_argument('--session', metavar='S', help='an opaque id, no whitespace, at most 200 characters')
1094
+ claim.add_argument('--take-over', action='store_true', help='replace a different driver that was seen recently')
1095
+ claim.add_argument('--json', action='store_true', help='print the driver, whether it took over, and the previous one')
1096
+ claim.set_defaults(func=cmd_claim)
1097
+ resume = sub.add_parser('resume', help='follow a live run, or restart it safely')
1098
+ resume.add_argument('run_dir', metavar='RUN_DIR')
1099
+ resume.add_argument('--take-over', action='store_true', help='replace a different driver that was seen recently')
1100
+ resume.add_argument('--harness', default='unknown', metavar='H', help='a short word: [a-z0-9._-]{1,40} (default unknown)')
1101
+ resume.add_argument('--session', metavar='S', help='an opaque id, no whitespace, at most 200 characters')
1102
+ resume.add_argument('--json', action='store_true', help='print what was recovered, prepared and started')
1103
+ resume.set_defaults(func=cmd_resume)
1104
+ return parser
1105
+
1106
+
1107
+ def main(argv=None):
1108
+ argv = list(sys.argv[1:] if argv is None else argv)
1109
+ parser = build_parser()
1110
+ # `forge handoff RUN_DIR` and `forge handoff --repo DIR` mean `show`; a bare `forge handoff` too.
1111
+ if not argv or argv[0] not in COMMANDS:
1112
+ argv = ['show'] + argv
1113
+ try:
1114
+ args = parser.parse_args(argv)
1115
+ except SystemExit as error:
1116
+ return error.code if isinstance(error.code, int) else 2
1117
+ try:
1118
+ return args.func(args)
1119
+ except Usage as error:
1120
+ print(f'forge handoff: {error}', file=sys.stderr)
1121
+ return 2
1122
+ except Refused as error:
1123
+ print(f'forge handoff: {error}', file=sys.stderr)
1124
+ return 3
1125
+
1126
+
1127
+ if __name__ == '__main__':
1128
+ sys.exit(main())