@giamme/forge 0.21.0 → 0.23.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 (165) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/README.md +25 -15
  3. package/SKILL.md +137 -216
  4. package/VERSION +1 -1
  5. package/bin/forge.js +104 -0
  6. package/docs/README.md +2 -3
  7. package/docs/add-ons.md +5 -3
  8. package/docs/artifacts.md +17 -2
  9. package/docs/commands.md +85 -63
  10. package/docs/decomposed-runs.md +195 -21
  11. package/docs/development.md +12 -10
  12. package/docs/forge-ui.md +33 -4
  13. package/docs/install.md +127 -6
  14. package/docs/memory.md +6 -1
  15. package/docs/models.md +36 -10
  16. package/docs/reviews.md +50 -29
  17. package/docs/safety.md +27 -2
  18. package/docs/troubleshooting.md +8 -11
  19. package/forge +29 -4
  20. package/forge.cmd +56 -0
  21. package/package.json +6 -3
  22. package/references/dataset.md +10 -9
  23. package/references/decompose-integration.md +337 -0
  24. package/references/decompose-opt-in.md +527 -0
  25. package/references/decompose-recovery.md +569 -0
  26. package/references/decompose-review.md +256 -0
  27. package/references/decompose.md +99 -1606
  28. package/references/findings.md +68 -0
  29. package/references/harnesses.md +7 -12
  30. package/references/memory.md +13 -2
  31. package/references/planning.md +48 -18
  32. package/references/ripwire.md +38 -13
  33. package/references/runtime.md +22 -33
  34. package/references/setup.md +90 -0
  35. package/references/solo.md +13 -42
  36. package/references/ui.md +12 -5
  37. package/registry.tsv +40 -22
  38. package/scripts/forge-artifact.sh +148 -13
  39. package/scripts/forge-compare.py +5 -15
  40. package/scripts/forge-config.py +14 -1
  41. package/scripts/forge-contract.py +216 -53
  42. package/scripts/forge-control.py +781 -51
  43. package/scripts/forge-dispatch.sh +202 -42
  44. package/scripts/forge-du.py +13 -3
  45. package/scripts/forge-guard.py +137 -6
  46. package/scripts/forge-handoff.py +221 -39
  47. package/scripts/forge-install-ripwire.sh +100 -24
  48. package/scripts/forge-install.sh +100 -41
  49. package/scripts/forge-issues.py +6 -4
  50. package/scripts/forge-jev-options.sh +3 -5
  51. package/scripts/forge-lib-adopt.sh +169 -5
  52. package/scripts/forge-lib-attribute.sh +10 -3
  53. package/scripts/forge-lib-decompose.sh +454 -0
  54. package/scripts/forge-lib-env.sh +179 -0
  55. package/scripts/forge-lib-group.sh +9 -6
  56. package/scripts/forge-lib-plans.sh +38 -21
  57. package/scripts/forge-lib-review.sh +28 -8
  58. package/scripts/forge-lib-task.sh +263 -69
  59. package/scripts/forge-lib-verify.sh +59 -10
  60. package/scripts/forge-memory.sh +83 -4
  61. package/scripts/forge-metrics.sh +10 -3
  62. package/scripts/forge-parallel-options.sh +23 -4
  63. package/scripts/forge-parallel.sh +602 -217
  64. package/scripts/forge-plan-check.py +71 -8
  65. package/scripts/forge-planner.py +303 -17
  66. package/scripts/forge-pr.py +9 -1
  67. package/scripts/forge-prompt.py +2 -2
  68. package/scripts/forge-review-links.py +248 -0
  69. package/scripts/forge-ripwire.py +234 -16
  70. package/scripts/forge-route.py +19 -27
  71. package/scripts/forge-runs-rm.py +92 -21
  72. package/scripts/forge-runs.py +46 -5
  73. package/scripts/forge-runtime.py +39 -14
  74. package/scripts/forge-schedule.py +141 -33
  75. package/scripts/forge-setup-stale.py +236 -0
  76. package/scripts/forge-setup.py +804 -0
  77. package/scripts/forge-shadow.py +2 -20
  78. package/scripts/forge-solo-lock.py +46 -0
  79. package/scripts/forge-solo.sh +39 -58
  80. package/scripts/forge-sweep.py +3 -2
  81. package/scripts/forge-ui.py +8 -1
  82. package/scripts/forge-update.sh +8 -3
  83. package/scripts/forge-verify.py +17 -1
  84. package/scripts/forge-version.py +13 -1
  85. package/scripts/forge-watch.py +7 -2
  86. package/scripts/forge-win.sh +156 -0
  87. package/scripts/forge_brief/__init__.py +6 -1
  88. package/scripts/forge_brief/proposals.py +6 -1
  89. package/scripts/forge_dataset/__init__.py +1 -1
  90. package/scripts/forge_dataset/capture.py +0 -34
  91. package/scripts/forge_dataset/checks.py +0 -1
  92. package/scripts/forge_dataset/cli.py +5 -1
  93. package/scripts/forge_dataset/export.py +28 -6
  94. package/scripts/forge_dataset/facts.py +1 -2
  95. package/scripts/forge_dataset/forecast.py +1 -1
  96. package/scripts/forge_dataset/harvest.py +107 -7
  97. package/scripts/forge_dataset/importer.py +3 -2
  98. package/scripts/forge_dataset/pairs.py +3 -3
  99. package/scripts/forge_dataset/reviewers.py +4 -3
  100. package/scripts/forge_dataset/routing.py +6 -3
  101. package/scripts/forge_dataset/tiers.py +1 -1
  102. package/scripts/forge_decide/__init__.py +1 -1
  103. package/scripts/forge_decide/budget.py +12 -7
  104. package/scripts/forge_decide/profiles.py +11 -14
  105. package/scripts/forge_decide/replay.py +9 -4
  106. package/scripts/forge_decompose.py +987 -0
  107. package/scripts/forge_flock.py +17 -2
  108. package/scripts/forge_groups/review.py +6 -1
  109. package/scripts/forge_jev/__init__.py +1 -1
  110. package/scripts/forge_jev/cli.py +10 -1
  111. package/scripts/forge_jev/gates.py +10 -1
  112. package/scripts/forge_jev/verify.py +10 -2
  113. package/scripts/forge_legacy.py +86 -0
  114. package/scripts/forge_memory_home.py +57 -0
  115. package/scripts/forge_models.py +151 -0
  116. package/scripts/forge_posix.py +17 -0
  117. package/scripts/forge_prefs.py +138 -0
  118. package/scripts/forge_proc.py +108 -0
  119. package/scripts/forge_registry.py +2 -2
  120. package/scripts/forge_side/__init__.py +23 -4
  121. package/scripts/forge_storage.py +28 -15
  122. package/ui/README.md +22 -10
  123. package/ui/docs/api.md +121 -99
  124. package/ui/forge_ui/control.py +53 -16
  125. package/ui/forge_ui/export.py +0 -10
  126. package/ui/forge_ui/models.py +15 -2
  127. package/ui/forge_ui/projects.py +4 -1
  128. package/ui/forge_ui/reader.py +462 -60
  129. package/ui/forge_ui/server.py +0 -10
  130. package/ui/forge_ui/static/app.js +28 -9
  131. package/ui/forge_ui/static/checksview.js +12 -3
  132. package/ui/forge_ui/static/controls.js +147 -11
  133. package/ui/forge_ui/static/convo.js +5 -2
  134. package/ui/forge_ui/static/diffview.js +4 -5
  135. package/ui/forge_ui/static/panel.js +180 -77
  136. package/ui/forge_ui/static/projectsview.js +16 -2
  137. package/ui/forge_ui/static/runmodel.js +18 -4
  138. package/ui/forge_ui/static/scene3d.js +52 -31
  139. package/ui/forge_ui/static/settings.js +1 -1
  140. package/ui/forge_ui/static/storageview.js +2 -2
  141. package/ui/forge_ui/static/style.css +23 -6
  142. package/ui/forge_ui/static/worktreesview.js +8 -4
  143. package/ui/forge_ui/transcripts.py +6 -0
  144. package/ui/forge_ui/worktrees.py +13 -1
  145. package/docs/fractal.md +0 -181
  146. package/references/fractal-dashboard.md +0 -21
  147. package/references/fractal.md +0 -307
  148. package/scripts/forge-fractal-dispatch.sh +0 -4
  149. package/scripts/forge-fractal-options.sh +0 -54
  150. package/scripts/forge-fractal.py +0 -6
  151. package/scripts/forge-install-fractal.sh +0 -4
  152. package/scripts/forge_fractal/__init__.py +0 -88
  153. package/scripts/forge_fractal/bridge.py +0 -46
  154. package/scripts/forge_fractal/cli.py +0 -224
  155. package/scripts/forge_fractal/dashboard.css +0 -138
  156. package/scripts/forge_fractal/dashboard.html +0 -41
  157. package/scripts/forge_fractal/dashboard.js +0 -687
  158. package/scripts/forge_fractal/decomposition.py +0 -262
  159. package/scripts/forge_fractal/execution.py +0 -659
  160. package/scripts/forge_fractal/inspection.py +0 -261
  161. package/scripts/forge_fractal/install.py +0 -158
  162. package/scripts/forge_fractal/invocation.py +0 -95
  163. package/scripts/forge_fractal/pipeline.py +0 -125
  164. package/scripts/forge_fractal/selection.py +0 -180
  165. package/ui/forge_ui/fractal.py +0 -582
@@ -9,6 +9,7 @@ import os
9
9
  from pathlib import Path
10
10
  import posixpath
11
11
  import re
12
+ import shlex
12
13
  import stat
13
14
  import sys
14
15
  import time
@@ -25,7 +26,7 @@ finally:
25
26
  if _inserted and _SCRIPTS in sys.path:
26
27
  sys.path.remove(_SCRIPTS)
27
28
 
28
- from forge_ui import checks, diffs, executions, findings, fractal, groups, links, repos, transcripts
29
+ from forge_ui import checks, diffs, executions, findings, groups, links, repos, transcripts
29
30
  from forge_ui.findings import verdict as _verdict
30
31
 
31
32
 
@@ -351,9 +352,50 @@ def _tasks(reader):
351
352
  qa=_nullable(qa), status=status,
352
353
  merged_at=float(merged.st_mtime) if merged is not None else None,
353
354
  accepted=_nonempty(reader, prefix + '/accepted.by')))
355
+ _mark_stale(reader, tasks)
354
356
  return tasks
355
357
 
356
358
 
359
+ # The forge commands that run a plan's tasks while they hold its lock: `run` (from before its scheduler starts
360
+ # until after it ends) and `retry`, which dispatches a task with no scheduler at all.
361
+ _DISPATCHING_HOLDERS = ('run', 'retry')
362
+
363
+
364
+ def _live_pid(reader, name):
365
+ """The pid a JSON file of the run dir names, or None."""
366
+ pid = (reader.object(name) or {}).get('pid') if reader.exists(name) else None
367
+ return pid if type(pid) is int else None
368
+
369
+
370
+ def run_live(reader):
371
+ """Whether a forge process runs this plan's tasks now: its scheduler (scheduler.live names a live pid), or
372
+ the `run` or `retry` command holding the plan lock (schedule.holder, which each command that takes the lock
373
+ writes). forge-handoff.py's `scheduler.live` check alone would read a starting run, or a retry, as gone."""
374
+ if forge_proc.pid_alive(_live_pid(reader, 'scheduler.live')):
375
+ return True
376
+ holder = (reader.object('schedule.holder') or {}) if reader.exists('schedule.holder') else {}
377
+ return holder.get('command') in _DISPATCHING_HOLDERS and forge_proc.pid_alive(_live_pid(reader, 'schedule.holder'))
378
+
379
+
380
+ def _run_gone(reader):
381
+ """Whether the run dir records the forge process that ran it (scheduler.live, which a run that ends normally
382
+ removes, or schedule.holder) and none of it runs now. A dir with neither record tells nothing, and is left
383
+ as it reads."""
384
+ recorded = reader.exists('scheduler.live') or reader.exists('schedule.holder')
385
+ return recorded and not run_live(reader)
386
+
387
+
388
+ def _mark_stale(reader, tasks):
389
+ """#229: a task left RUNNING by a forge process that is gone (a crash, a SIGKILL, a closed terminal: nothing
390
+ marked it INTERRUPTED) reads as INTERRUPTED with `stale` set, so the page stops its clock, the run and its
391
+ project stop counting as live and its worktrees as in use. Nothing is probed while no task says RUNNING."""
392
+ running = [task for task in tasks if task['status'] == 'RUNNING']
393
+ if not running or not _run_gone(reader):
394
+ return
395
+ for task in running:
396
+ task.update(status='INTERRUPTED', stale=True)
397
+
398
+
357
399
  _TITLE_CAP = 160
358
400
  # Files a run writes once, when it starts: their earliest time is when the run began. Stat'ed
359
401
  # outside _Read.track, so they never move `updated`.
@@ -368,7 +410,12 @@ def _created(path, names):
368
410
  info = os.stat(path / name)
369
411
  except (OSError, ValueError):
370
412
  continue
371
- value = getattr(info, 'st_birthtime', None) or info.st_mtime
413
+ birth = getattr(info, 'st_birthtime', None)
414
+ if birth and sys.platform in ('win32', 'cygwin'):
415
+ # Windows keeps a file's creation time when its mtime is set earlier, where macOS moves
416
+ # the birth time back with it: the earlier of the two is the start there too.
417
+ birth = min(birth, info.st_mtime)
418
+ value = birth or info.st_mtime
372
419
  if math.isfinite(value):
373
420
  times.append(float(value))
374
421
  return min(times) if times else None
@@ -447,6 +494,241 @@ def _followers(listed, target):
447
494
  return found
448
495
 
449
496
 
497
+ # scripts/forge_legacy.REMOVED_IN and its selection file: a run made with Fractal stays readable.
498
+ _REMOVED_IN = '0.23'
499
+ _OLD_SELECTION = 'fractal-selection.json'
500
+
501
+
502
+ def _removed(reader):
503
+ """RunSummary `removed`: {name, since, note} for a run made with Fractal, which forge removed, else None.
504
+
505
+ The rule of scripts/forge_legacy.was_fractal: the old selection file says `enabled`, and one that
506
+ cannot be read or parsed counts, since nothing may resume a run whose backend cannot be told."""
507
+ if not reader.exists(_OLD_SELECTION):
508
+ return None
509
+ raw = reader.text(_OLD_SELECTION)
510
+ if raw is not None and not raw.strip():
511
+ return None
512
+ try:
513
+ data = json.loads(raw) if raw is not None else None
514
+ except ValueError:
515
+ data = None
516
+ if isinstance(data, dict) and not data.get('enabled', True):
517
+ return None
518
+ return dict(name='Fractal', since=_REMOVED_IN,
519
+ note=f'made with Fractal, which forge {_REMOVED_IN} removed: it can be read here, '
520
+ 'not run, retried or resumed')
521
+
522
+
523
+ # --- decomposition (#153): a split task's subtasks are a plan of their own, <plan>/tasks/<id>/sub ---
524
+
525
+ _DECISIONS = ('atomic', 'split', 'bounded')
526
+ _DECIDERS = ('planner', 'user', 'auto', 'default')
527
+ _DEFAULT_LIMITS = dict(depth=2, children=6, nodes=24) # scripts/forge_decompose.DEFAULT_LIMITS
528
+ _MAX_TREE_NODES = 600 # the limit on subtasks in a run tops out at 500
529
+ _MAX_TREE_DEPTH = 8 # the depth limit tops out at 6
530
+
531
+
532
+ def sub_plan(path, ident):
533
+ """The sub-plan of a split task, `<plan>/tasks/<id>/sub` with a task table, or None."""
534
+ sub = Path(path) / 'tasks' / ident / 'sub'
535
+ try:
536
+ return sub if (sub / 'tasks.tsv').is_file() else None
537
+ except (OSError, ValueError):
538
+ return None
539
+
540
+
541
+ def sub_plans(path, depth=0):
542
+ """Every sub-plan under a plan dir, a task's before those of its subtasks. A plan with no
543
+ decomposition.json has none: a split always writes one, so an older plan costs one stat."""
544
+ path = Path(path)
545
+ try:
546
+ if depth >= _MAX_TREE_DEPTH or not (path / 'decomposition.json').is_file():
547
+ return
548
+ children = sorted((path / 'tasks').iterdir())
549
+ except (OSError, ValueError):
550
+ return
551
+ for child in children:
552
+ sub = sub_plan(path, child.name)
553
+ if sub is not None:
554
+ yield sub
555
+ yield from sub_plans(sub, depth + 1)
556
+
557
+
558
+ def _parent_plan(path):
559
+ """(plan dir, task id) of the task a sub-plan belongs to, read off its path; None for any other plan."""
560
+ path = Path(path)
561
+ if path.name != 'sub' or path.parent.parent.name != 'tasks':
562
+ return None
563
+ try:
564
+ if not (path / 'parent.json').is_file() or not (path.parents[2] / 'tasks.tsv').is_file():
565
+ return None
566
+ except (OSError, ValueError):
567
+ return None
568
+ return path.parents[2], path.parent.name
569
+
570
+
571
+ def _parent(reader):
572
+ """RunSummary `parent`: `{key, task, run_id, path}` of the split task a sub-plan holds the subtasks of, else None."""
573
+ found = _parent_plan(reader.path)
574
+ if found is None:
575
+ return None
576
+ plan, task = found
577
+ reader.exists('parent.json')
578
+ return dict(key=run_key(plan), task=task, run_id=_first_line(plan, 'run_id'), path=str(plan))
579
+
580
+
581
+ def _nodes_file(reader):
582
+ """decomposition.json as ({task: record}, limits or None, frozen); empty for a plan that has none."""
583
+ if not reader.exists('decomposition.json'):
584
+ return {}, None, False
585
+ data = reader.object('decomposition.json') or {}
586
+ nodes = data.get('nodes')
587
+ limits = data.get('limits')
588
+ if isinstance(limits, dict):
589
+ limits = {key: limits[key] if type(limits.get(key)) is int else default for key, default in _DEFAULT_LIMITS.items()}
590
+ else:
591
+ limits = None
592
+ return (nodes if isinstance(nodes, dict) else {}), limits, data.get('frozen') is True
593
+
594
+
595
+ def _node_decision(record, split):
596
+ """(decision, reason, by, at) of one task's record. An undecided task is what it is on disk."""
597
+ record = record if isinstance(record, dict) else {}
598
+ decision = record.get('decision') if record.get('decision') in _DECISIONS else ('split' if split else 'atomic')
599
+ if split:
600
+ decision = 'split'
601
+ elif decision == 'split':
602
+ decision = 'atomic' # recorded as split, and its sub-plan is gone
603
+ by = record.get('by') if record.get('by') in _DECIDERS else 'default'
604
+ reason = record.get('reason') if isinstance(record.get('reason'), str) else ''
605
+ at = record.get('at') if _is_number(record.get('at')) else None
606
+ return decision, reason[:2000] or None, by, at
607
+
608
+
609
+ def _run_limits(reader):
610
+ """The limits of the run a plan belongs to: the root plan's, with whether its first run froze them."""
611
+ path, hops = reader.path, 0
612
+ while hops < _MAX_TREE_DEPTH:
613
+ found = _parent_plan(path)
614
+ if found is None:
615
+ break
616
+ path, hops = found[0], hops + 1
617
+ if path == reader.path:
618
+ _nodes, limits, frozen = _nodes_file(reader)
619
+ else:
620
+ _nodes, limits, frozen = _nodes_file(_Read(path))
621
+ return dict(limits or _DEFAULT_LIMITS, frozen=frozen)
622
+
623
+
624
+ def _sub_statuses(reader, plan_path, ids, prefix='', depth=0):
625
+ """[{id, status}] for the tasks of the sub-plans of these tasks of a plan dir, through every level, in
626
+ tree order. An id is the path from the plan's own task (`d/a`, `d/a/one`). The sub-plans' status files
627
+ move `updated`, so a run whose subtasks are working reads as active."""
628
+ out = []
629
+ if depth >= _MAX_TREE_DEPTH:
630
+ return out
631
+ for ident in ids:
632
+ sub_path = sub_plan(plan_path, ident)
633
+ if sub_path is None:
634
+ continue
635
+ sub = _Read(sub_path)
636
+ for child in _tasks(sub):
637
+ out.append(dict(id=f"{prefix}{ident}/{child['id']}", status=child['status']))
638
+ out += _sub_statuses(reader, sub.path, [child['id']], f'{prefix}{ident}/', depth + 1)
639
+ if sub.updated is not None and (reader.updated is None or sub.updated > reader.updated):
640
+ reader.updated = sub.updated
641
+ if len(out) > _MAX_TREE_NODES:
642
+ break
643
+ return out
644
+
645
+
646
+ def _decomposition_summary(reader, tasks):
647
+ """RunSummary `decomposition`: `{limits, split, subtasks, statuses}`, or None for a plan no decision was
648
+ recorded in.
649
+
650
+ `split` counts this plan's tasks that have a sub-plan, `subtasks` the tasks of every sub-plan below it,
651
+ and `statuses` is `[{id, status}]` for those, in tree order."""
652
+ if not reader.exists('decomposition.json'):
653
+ return None
654
+ split = sum(1 for task in tasks if sub_plan(reader.path, task['id']) is not None)
655
+ statuses = _sub_statuses(reader, reader.path, [task['id'] for task in tasks]) if split else []
656
+ return dict(limits=_run_limits(reader), split=split, subtasks=len(statuses), statuses=statuses)
657
+
658
+
659
+ def _node_tokens(sub, task):
660
+ """What a subtask spent, summed over its executions: {input, cached, output}, or None when none reported any."""
661
+ total, seen = dict(input=0, cached=0, output=0), False
662
+ for item in _task_execs(sub, task):
663
+ tokens = item.get('tokens')
664
+ if isinstance(tokens, dict):
665
+ for key in total:
666
+ if _is_number(tokens.get(key)):
667
+ total[key] += tokens[key]
668
+ seen = True
669
+ return total if seen else None
670
+
671
+
672
+ def _tree_nodes(reader, sub_path, parent_id, level, budget):
673
+ """The nodes of one sub-plan and of every sub-plan below it, in tree order. `budget` is a one-item
674
+ list: how many more nodes may be read, so a damaged tree cannot grow the answer without bound."""
675
+ sub = _Read(sub_path)
676
+ records = _nodes_file(sub)[0]
677
+ key, run_id, out = run_key(sub.path), sub.line('run_id'), []
678
+ for task in _tasks(sub):
679
+ if budget[0] <= 0:
680
+ reader.truncated.append('decomposition')
681
+ break
682
+ budget[0] -= 1
683
+ ident = task['id']
684
+ below = sub_plan(sub.path, ident) if level < _MAX_TREE_DEPTH else None
685
+ decision, reason, by, _at = _node_decision(records.get(ident), below is not None)
686
+ task['attempts'], task['attempt'] = _attempt_state(sub, f'tasks/{ident}')
687
+ node_id = f'{parent_id}/{ident}'
688
+ out.append(dict(id=node_id, parent=parent_id, run=key, run_id=run_id, task=ident, level=level,
689
+ title=_brief(task['title']), status=task['status'], difficulty=task['difficulty'] or None,
690
+ model=task['dwarf'], qa=task['qa'], decision=decision, reason=reason, by=by,
691
+ attempts=len(task['attempts']), tokens=_node_tokens(sub, task),
692
+ has_diff=_nonempty(sub, f'tasks/{ident}/changes.diff')))
693
+ if below is not None:
694
+ out += _tree_nodes(reader, below, node_id, level + 1, budget)
695
+ if sub.updated is not None and (reader.updated is None or sub.updated > reader.updated):
696
+ reader.updated = sub.updated
697
+ reader.warnings += [f'{parent_id}/sub: {warning}' for warning in sub.warnings]
698
+ return out
699
+
700
+
701
+ def _attach_decomposition(reader, tasks):
702
+ """Set `decomposition` on every task of a plan (#153): the decision about it and, for a split task,
703
+ its subtasks through every level. A plan that has no decomposition.json gains nothing: no key.
704
+
705
+ {decision, reason, by, at, sub: {key, run_id, path} | None, merged, waiting, start, kept, nodes}:
706
+ `merged` says the subtasks' work is on the task's branch, `waiting` lists the subtasks it waits for,
707
+ `start` is keep or fresh, and `kept` the commit a fresh split set the earlier work aside at."""
708
+ records = _nodes_file(reader)[0]
709
+ present = reader.exists('decomposition.json')
710
+ budget = [_MAX_TREE_NODES]
711
+ for task in tasks:
712
+ ident = task['id']
713
+ sub = sub_plan(reader.path, ident)
714
+ if not present and sub is None:
715
+ continue
716
+ decision, reason, by, at = _node_decision(records.get(ident), sub is not None)
717
+ entry = dict(decision=decision, reason=reason, by=by, at=at, sub=None, merged=None, waiting=None, start=None,
718
+ kept=None, nodes=[])
719
+ if sub is not None:
720
+ prefix = f'tasks/{ident}'
721
+ link = reader.object(prefix + '/sub/parent.json') or {}
722
+ entry.update(sub=dict(key=run_key(sub), run_id=_first_line(sub, 'run_id'), path=str(sub)),
723
+ merged=reader.exists(prefix + '/sub.merged'),
724
+ waiting=[line.strip() for line in (reader.text(prefix + '/sub.waiting') or '').splitlines()
725
+ if line.strip()][:50] or None,
726
+ start=link.get('start') if link.get('start') in ('keep', 'fresh') else 'keep',
727
+ kept=reader.line(prefix + '/sub.kept'),
728
+ nodes=_tree_nodes(reader, sub, ident, 1, budget))
729
+ task['decomposition'] = entry
730
+
731
+
450
732
  def _summary(reader, source):
451
733
  result = dict(key=run_key(reader.path), path=str(reader.path), source=source, kind='plan',
452
734
  run_id=reader.line('run_id'), repo=reader.line('repo'),
@@ -464,6 +746,13 @@ def _summary(reader, source):
464
746
  # accepted.integration (or the published verdict / review.meta) moves the activity time.
465
747
  final_review_outdated = _published_outdated(reader, tasks)
466
748
  after = _predecessor(reader)
749
+ result['removed'] = _removed(reader)
750
+ # Recursive decomposition (#153). Absent, not null, on a plan that has none of it: its JSON does not change.
751
+ parent, tree = _parent(reader), _decomposition_summary(reader, tasks)
752
+ if parent is not None:
753
+ result['parent'] = parent
754
+ if tree is not None:
755
+ result['decomposition'] = tree
467
756
  result.update(updated=reader.updated, created=_created(reader.path, _PLAN_START_FILES),
468
757
  task_count=len(tasks), counts=counts,
469
758
  task_statuses=[dict(id=task['id'], status=task['status'], difficulty=task['difficulty'] or None,
@@ -500,7 +789,8 @@ def _solo_summary(reader, source):
500
789
  goal = reader.line('goal.txt')
501
790
  # Before `updated` is copied out: a present `after` file is part of what the summary read.
502
791
  after = _predecessor(reader)
503
- return dict(key=run_key(reader.path), path=str(reader.path), source=source, kind='solo',
792
+ removed = _removed(reader)
793
+ return dict(key=run_key(reader.path), path=str(reader.path), source=source, kind='solo', removed=removed,
504
794
  run_id=reader.path.name, repo=reader.line('repo'), goal=goal,
505
795
  decompose_level=None, verification_status=None, updated=reader.updated,
506
796
  created=_created(reader.path, _SOLO_START_FILES),
@@ -712,7 +1002,7 @@ def _now(reader, owner_dir, execs):
712
1002
  def _scheduler(reader):
713
1003
  """RunDetail.scheduler: whether a scheduler runs this plan now, and, while one does, what holds it: a drain, a
714
1004
  stop, infrastructure pauses (scheduler-written infra.paused) and the capacity it dispatches up to."""
715
- pid = (reader.object('scheduler.live') or {}).get('pid') if reader.exists('scheduler.live') else None
1005
+ pid = _live_pid(reader, 'scheduler.live')
716
1006
  live = forge_proc.pid_alive(pid)
717
1007
  result = dict(live=live, drained=False, stopping=None, pauses=[], max_parallel=None)
718
1008
  if not live:
@@ -989,6 +1279,11 @@ def _waiting(reader, tasks, scheduler):
989
1279
  running = [task for task in tasks if task['status'] == 'RUNNING']
990
1280
  for task in tasks:
991
1281
  task['waiting'] = None
1282
+ if task.pop('stale', False):
1283
+ # #229: left RUNNING by a forge process that is gone. handoff resume saves its work and resets it.
1284
+ task['waiting'] = dict(kind='stale', status='RUNNING',
1285
+ command='forge handoff resume ' + shlex.quote(str(reader.path)))
1286
+ continue
992
1287
  if task['status'] in ('RUNNING', 'MERGED'):
993
1288
  continue
994
1289
  stop = _escalation_stop(reader, task['id'])
@@ -1321,8 +1616,44 @@ def _attempt_review(execs, attempt):
1321
1616
  return chosen
1322
1617
 
1323
1618
 
1324
- def _trail(reader, rows, execs, sources_name, escalations, queue_times):
1325
- """One entry per attempts.tsv row: its review, why it ran, and its execution ids."""
1619
+ _STEER_LIMIT = 50 # messages read from one steer file
1620
+
1621
+
1622
+ def _steer_list(reader, name, with_text=False):
1623
+ """The messages of a steer file (#134: `forge control steer`), oldest first: `{actor, at, chars}`, and `text`
1624
+ (capped) when asked. A line that is not such an object is warned and skipped."""
1625
+ out = []
1626
+ for n, line in enumerate((reader.text(name) or '').splitlines()[:_STEER_LIMIT], 1):
1627
+ if not line.strip():
1628
+ continue
1629
+ obj = reader.object(f'{name} line {n}', line)
1630
+ if not isinstance(obj, dict) or not isinstance(obj.get('text'), str):
1631
+ if obj is not None:
1632
+ reader.warn(name, f'line {n} is not a message')
1633
+ continue
1634
+ item = dict(actor=obj.get('actor') if isinstance(obj.get('actor'), str) else None,
1635
+ at=obj.get('at') if _is_number(obj.get('at')) else None, chars=len(obj['text']))
1636
+ if obj.get('mode') == 'live': # sent to the running implementer (#252)
1637
+ item['mode'] = 'live'
1638
+ if with_text:
1639
+ item['text'] = reader.cap(obj['text'], name, size=8000)
1640
+ out.append(item)
1641
+ return out
1642
+
1643
+
1644
+ def _steer_live(reader, prefix):
1645
+ """The attempt whose implementer takes messages live now (#252: steer.live names a live feeder), or None."""
1646
+ name = prefix + '/steer.live'
1647
+ obj = (reader.object(name) or {}) if reader.exists(name) else {}
1648
+ pid, attempt = obj.get('pid'), obj.get('attempt')
1649
+ if type(pid) is not int or type(attempt) is not int or not forge_proc.pid_alive(pid):
1650
+ return None
1651
+ return attempt
1652
+
1653
+
1654
+ def _trail(reader, rows, execs, sources_name, escalations, queue_times, prefix=None):
1655
+ """One entry per attempts.tsv row: its review, why it ran, its execution ids, and the messages a person sent it
1656
+ (`steered`, a plan task's only)."""
1326
1657
  sources = _retry_sources(reader, sources_name)
1327
1658
  manual = _manual_indexes(rows, queue_times)
1328
1659
  result = []
@@ -1339,7 +1670,9 @@ def _trail(reader, rows, execs, sources_name, escalations, queue_times):
1339
1670
  worst=summary.get('worst') if summary else None, reason=_attempt_reason(
1340
1671
  index, row, rows, sources, escalations, manual),
1341
1672
  executions=[item['id'] for item in execs
1342
- if item.get('attempt') == row['attempt'] and not item.get('shadow')]))
1673
+ if item.get('attempt') == row['attempt'] and not item.get('shadow')],
1674
+ steered=_steer_list(reader, f"{prefix}/steered.{row['attempt']}.jsonl")
1675
+ if prefix and isinstance(row['attempt'], int) else []))
1343
1676
  return result
1344
1677
 
1345
1678
 
@@ -1664,7 +1997,10 @@ def _task_detail(reader, task, run_id, waves, branches, max_attempts, origin, re
1664
1997
  execs = _task_execs(reader, task)
1665
1998
  task['executions'] = execs
1666
1999
  task['header'] = _header(reader, task['title'], texts['prompt'], texts['approach'], request, prefix, origin)
1667
- task['trail'] = _trail(reader, logged, execs, prefix + '/retry_sources.tsv', task['escalations'], queues)
2000
+ task['trail'] = _trail(reader, logged, execs, prefix + '/retry_sources.tsv', task['escalations'], queues, prefix)
2001
+ task['steer_waiting'] = _steer_list(reader, prefix + '/steer.jsonl', with_text=True)
2002
+ task['steer_live'] = _steer_live(reader, prefix)
2003
+ task['steer_sending'] = _steer_list(reader, prefix + '/steer.inbox.jsonl', with_text=True)
1668
2004
  task['now'] = _now(reader, prefix, execs) if task['status'] == 'RUNNING' else None
1669
2005
  merged = reader.stat(prefix + '/merged') if task['status'] == 'MERGED' else None
1670
2006
  task['merged_at'] = float(merged.st_mtime) if merged is not None else None
@@ -1761,7 +2097,7 @@ def _sweep(reader, tasks):
1761
2097
  _RUN_CONTROLS = ('control.log', 'retry_budget', 'infra_budget', 'drain', 'stop', 'max_parallel', 'infra.paused', 'infra.last',
1762
2098
  'infra_backoff', 'escalate_effort', 'control.requests', 'summaries', 'summaries_model')
1763
2099
  _TASK_CONTROLS = ('qa_threshold', 'retry_budget', 'retries.used', 'escalation.pin', 'escalation.stop', 'escalation.next',
1764
- 'summaries')
2100
+ 'summaries', 'steer.jsonl', 'steer.live', 'steer.inbox.jsonl')
1765
2101
 
1766
2102
 
1767
2103
  _FAIL_FIRST_RESULTS = ('proven', 'passes_without_change', 'inconclusive', 'error')
@@ -2260,6 +2596,7 @@ def _solo_detail(reader, source):
2260
2596
  request = reader.text('request.md')
2261
2597
  result['request'] = reader.cap(request, 'request')
2262
2598
  result['retro'] = _retro(reader)
2599
+ result['handoff'] = _handoff(reader)
2263
2600
  result['summaries'] = None # generated summaries are for plan tasks only
2264
2601
  result['brief'] = None # brief mode is a plan's questions, not a solo run's
2265
2602
  result['settings'] = dict.fromkeys(_SOLO_SETTINGS)
@@ -2288,12 +2625,13 @@ def _solo_detail(reader, source):
2288
2625
  gate=_gate(reader, 'qa.gate'), known_issues=_nonempty(reader, 'known_issues.md'),
2289
2626
  fail_first=_fail_first(reader, 'failfirst.json'), pre_review=None,
2290
2627
  now=_now(reader, '', execs) if status == 'RUNNING' else None, waiting=None, sweep=None, swept=[],
2291
- summary=None, summaries_override=None, brief=None)
2628
+ summary=None, summaries_override=None, brief=None, steer_waiting=[], steer_live=None,
2629
+ steer_sending=[])
2292
2630
  task['header'] = _header(reader, task['title'], prompt, approach, request, 'tasks/solo',
2293
2631
  _github_origin(reader))
2294
2632
  task['trail'] = _trail(reader, logged, execs, 'retry_sources.tsv', [], _queued_retries(reader).get('solo', ()))
2295
2633
  result.update(timeline=_timeline(execs, [], []), integration=None, final_review=None, final_reviews=[], adoptions=[],
2296
- deferrals=[], findings_available=findings.available(), fractal=fractal.summary(reader),
2634
+ deferrals=[], findings_available=findings.available(),
2297
2635
  scheduler=None, sweep=None)
2298
2636
  result.update(tasks=[task], warnings=reader.warnings, truncated=reader.truncated, updated=reader.updated)
2299
2637
  return result
@@ -2380,6 +2718,59 @@ def _retro(reader):
2380
2718
  return dict(text=reader.cap(reader.text('retro.md'), 'retro'), **counts)
2381
2719
 
2382
2720
 
2721
+ # --- handoff: who drives the run, and the notes sessions left for the next one (forge handoff, #146) ----
2722
+
2723
+ _DRIVER_STALE_S = 12 * 3600 # forge-handoff.py DRIVER_STALE_S: past this, another session may claim the run
2724
+ _HANDOFF_NOTES_MAX = 50 # newest first; older ones stay in handoff.notes.jsonl
2725
+ _HANDOFF_NOTE_CHARS = 2000 # forge-handoff.py NOTE_MAX
2726
+
2727
+
2728
+ def _short(value, size):
2729
+ return value if isinstance(value, str) and value and len(value) <= size else None
2730
+
2731
+
2732
+ def _handoff(reader):
2733
+ """RunDetail.handoff from handoff.driver.json and handoff.notes.jsonl, or null when the run has neither.
2734
+
2735
+ driver: {harness, session, since, last_seen, stale} or null (absent or not a driver record, warned); stale
2736
+ when last_seen is over 12 hours ago, so another session may claim the run without --take-over.
2737
+ notes: [{at, actor, text}], newest first, at most 50; a line that is not a note is skipped with one warning."""
2738
+ has_driver, has_notes = reader.exists('handoff.driver.json'), reader.exists('handoff.notes.jsonl')
2739
+ if not (has_driver or has_notes):
2740
+ return None
2741
+ driver = None
2742
+ if has_driver:
2743
+ name = 'handoff.driver.json'
2744
+ obj = reader.object(name)
2745
+ since, seen = (obj.get('since'), obj.get('last_seen')) if obj is not None else (None, None)
2746
+ harness, session = (obj.get('harness'), obj.get('session')) if obj is not None else (None, None)
2747
+ if (_short(harness, 40) and (session is None or _short(session, 200))
2748
+ and _finite(since) is not None and _finite(seen) is not None):
2749
+ driver = dict(harness=harness, session=session, since=_finite(since), last_seen=_finite(seen),
2750
+ stale=time.time() - _finite(seen) > _DRIVER_STALE_S)
2751
+ elif obj is not None:
2752
+ reader.warn(name, 'not a driver record')
2753
+ notes, skipped = [], 0
2754
+ for line in (reader.text('handoff.notes.jsonl') or '').split('\n'):
2755
+ if not line.strip():
2756
+ continue
2757
+ try:
2758
+ note = json.loads(line)
2759
+ except (ValueError, RecursionError):
2760
+ note = None
2761
+ text = note.get('text') if isinstance(note, dict) else None
2762
+ if not (isinstance(text, str) and text.strip()):
2763
+ skipped += 1
2764
+ continue
2765
+ if len(text) > _HANDOFF_NOTE_CHARS:
2766
+ text = text[:_HANDOFF_NOTE_CHARS] + '…'
2767
+ notes.append(dict(at=_finite(note.get('at')),
2768
+ actor=_short(note.get('actor'), 40), text=text))
2769
+ if skipped:
2770
+ reader.warn('handoff.notes.jsonl', f'{skipped} malformed line{"" if skipped == 1 else "s"} skipped')
2771
+ return dict(driver=driver, notes=notes[::-1][:_HANDOFF_NOTES_MAX], notes_total=len(notes))
2772
+
2773
+
2383
2774
  def detail(path, source='plan') -> dict:
2384
2775
  reader = _Read(path)
2385
2776
  if _kind(reader.path) == 'solo':
@@ -2388,6 +2779,7 @@ def detail(path, source='plan') -> dict:
2388
2779
  request = reader.text('request.md')
2389
2780
  result['request'] = reader.cap(request, 'request')
2390
2781
  result['retro'] = _retro(reader)
2782
+ result['handoff'] = _handoff(reader)
2391
2783
  threshold = _threshold(reader)
2392
2784
  result['settings'] = dict(explore=reader.number('explore'), shadow_rate=reader.number('shadow_rate'),
2393
2785
  shadow_qa=_list(reader.text('shadow_qa') or ''), timeout=reader.number('timeout', int),
@@ -2409,6 +2801,7 @@ def detail(path, source='plan') -> dict:
2409
2801
  for name in _RUN_CONTROLS:
2410
2802
  reader.stat(name)
2411
2803
  result['scheduler'] = _scheduler(reader)
2804
+ result['scheduler']['stale'] = [task['id'] for task in tasks if task.get('stale')]
2412
2805
  _waiting(reader, tasks, result['scheduler'])
2413
2806
  result['sweep'] = _sweep(reader, tasks)
2414
2807
  run_execs = _run_execs(reader)
@@ -2434,7 +2827,6 @@ def detail(path, source='plan') -> dict:
2434
2827
  result['adoptions'] = _adoptions(reader)
2435
2828
  result['deferrals'] = [line.strip() for line in (reader.text('deferrals.txt') or '').splitlines() if line.strip()]
2436
2829
  result['findings_available'] = findings.available()
2437
- result['fractal'] = fractal.summary(reader)
2438
2830
  brief = _attach_brief(reader, tasks)
2439
2831
  result['brief'] = brief
2440
2832
  # Absent, not empty, when brief is off: proposals/ is not listed, so the run JSON does not change.
@@ -2451,10 +2843,33 @@ def detail(path, source='plan') -> dict:
2451
2843
  owner.setdefault(member, item['id'])
2452
2844
  for task in tasks:
2453
2845
  task['group'] = owner.get(task['id'])
2846
+ _attach_decomposition(reader, tasks)
2847
+ later = _later(reader)
2848
+ if later is not None:
2849
+ result['later'] = later
2454
2850
  result.update(tasks=tasks, warnings=reader.warnings, truncated=reader.truncated, updated=reader.updated)
2455
2851
  return result
2456
2852
 
2457
2853
 
2854
+ def _later(reader):
2855
+ """RunDetail `later`: the stages a planner proposed after this plan (goal -> plans, #153), and where this
2856
+ plan stands in its chain: `{stages: [{title, goal}], stage, first}`. None (and no key) for a plan that is
2857
+ the whole goal."""
2858
+ stages = []
2859
+ if reader.exists('later.json'):
2860
+ raw = (reader.object('later.json') or {}).get('later')
2861
+ for item in raw if isinstance(raw, list) else []:
2862
+ if isinstance(item, dict) and isinstance(item.get('title'), str) and item['title'].strip():
2863
+ goal = item.get('goal') if isinstance(item.get('goal'), str) else ''
2864
+ stages.append(dict(title=item['title'].strip()[:200], goal=goal[:4000]))
2865
+ chain = (reader.object('chain.json') or {}) if reader.exists('chain.json') else {}
2866
+ stage = chain.get('stage') if type(chain.get('stage')) is int else None
2867
+ if not stages and stage is None:
2868
+ return None
2869
+ first = chain.get('first') if isinstance(chain.get('first'), str) else None
2870
+ return dict(stages=stages[:10], stage=stage, first=dict(key=run_key(first), path=_real_path(first)) if first else None)
2871
+
2872
+
2458
2873
  # --- lazy details: one task, one execution, one final review ------------------------------
2459
2874
 
2460
2875
  _TEXTS = (('prompt', 'prompt.md'), ('approach', 'approach.md'), ('retry_findings', 'retry_findings.md'),
@@ -3238,33 +3653,6 @@ def files_detail(path, source='plan'):
3238
3653
  overlaps=overlaps, deferrals=deferrals, truncated=truncated, warnings=reader.warnings)
3239
3654
 
3240
3655
 
3241
- # --- Fractal: the child tasks inside a task ---------------------------------------------------
3242
-
3243
- def _fractal(path, task_id, read, *args):
3244
- reader = _Read(path)
3245
- kind = _kind(reader.path)
3246
- if kind == 'solo' and task_id == 'solo':
3247
- target = str(reader.path)
3248
- elif kind == 'plan' and any(task['id'] == task_id for task in _tasks(reader)):
3249
- # forge hands Fractal the task dir as --run-dir, resolved: its realpath names the Fractal task.
3250
- target = os.path.realpath(reader.path / 'tasks' / task_id)
3251
- else:
3252
- return None
3253
- return read(reader, run_key(reader.path), task_id, target, *args)
3254
-
3255
-
3256
- def fractal_detail(path, task_id, source='plan'):
3257
- return _fractal(path, task_id, fractal.task)
3258
-
3259
-
3260
- def fractal_node(path, task_id, node, source='plan'):
3261
- return _fractal(path, task_id, fractal.node, node)
3262
-
3263
-
3264
- def fractal_node_diff(path, task_id, node, source='plan'):
3265
- return _fractal(path, task_id, fractal.node_diff, node)
3266
-
3267
-
3268
3656
  # --- verification logs by path ---------------------------------------------------------------
3269
3657
 
3270
3658
  LANE_NAME = re.compile(r'[A-Za-z0-9][A-Za-z0-9_-]{0,63}')
@@ -3418,33 +3806,56 @@ class Catalog:
3418
3806
  """The keys of every run the list shows, without summarizing any of them."""
3419
3807
  return {run_key(path) for path, _source in discover(**self.options)}
3420
3808
 
3809
+ def _where(self, key, found=None):
3810
+ """(found, (path, source)) for the run with this key; the pair is None for an unknown key.
3811
+
3812
+ A sub-plan (#153, the subtasks of a split task) is never listed: it is found under the listed
3813
+ plan it belongs to, with source `sub`, and only when no listed run has the key."""
3814
+ found = discover(**self.options) if found is None else found
3815
+ for path, source in found:
3816
+ if run_key(path) == key:
3817
+ return found, (path, source)
3818
+ for path, _source in found:
3819
+ for sub in sub_plans(path):
3820
+ if run_key(sub) == key:
3821
+ return found, (Path(os.path.realpath(sub)), 'sub')
3822
+ return found, None
3823
+
3824
+ def _batch(self, key):
3825
+ """batch() over the listed runs, with the run of this key added when it is a sub-plan."""
3826
+ found, where = self._where(key)
3827
+ if where is not None and where[1] == 'sub':
3828
+ found = found + [where]
3829
+ return batch(found)
3830
+
3421
3831
  def identity(self, key):
3422
3832
  """The identity of the run with this key, resolved in the same batch as the list; None for no such run."""
3423
- listed, identities = batch(discover(**self.options))
3833
+ listed, identities = self._batch(key)
3424
3834
  for path, _source, entry in listed:
3425
3835
  if run_key(path) == key:
3426
3836
  return identities[entry[0]]
3427
3837
  return None
3428
3838
 
3429
3839
  def _find(self, key, read, *args):
3430
- for path, source in discover(**self.options):
3431
- if run_key(path) == key:
3432
- result = read(path, *args, source=source)
3433
- return result if _kind(path) else None
3434
- return None
3840
+ _found, where = self._where(key)
3841
+ if where is None:
3842
+ return None
3843
+ path, source = where
3844
+ result = read(path, *args, source=source)
3845
+ return result if _kind(path) else None
3435
3846
 
3436
3847
  def locate(self, key):
3437
3848
  """(path, kind) of the run with this key, kind 'plan' or 'solo'; None for an unknown key.
3438
3849
 
3439
3850
  The only way a write finds a run dir: the client names a key, never a path."""
3440
- for path, _source in discover(**self.options):
3441
- if run_key(path) == key:
3442
- kind = _kind(path)
3443
- return (str(path), kind) if kind else None
3444
- return None
3851
+ _found, where = self._where(key)
3852
+ if where is None:
3853
+ return None
3854
+ kind = _kind(where[0])
3855
+ return (str(where[0]), kind) if kind else None
3445
3856
 
3446
3857
  def get(self, key):
3447
- listed, identities = batch(discover(**self.options))
3858
+ listed, identities = self._batch(key)
3448
3859
  for path, source, entry in listed:
3449
3860
  if run_key(path) == key:
3450
3861
  result = _with_repo(detail(path, source=source), identities[entry[0]])
@@ -3497,15 +3908,6 @@ class Catalog:
3497
3908
  def findings(self, key):
3498
3909
  return self._find(key, run_findings)
3499
3910
 
3500
- def fractal(self, key, task_id):
3501
- return self._find(key, fractal_detail, task_id)
3502
-
3503
- def fractal_node(self, key, task_id, node):
3504
- return self._find(key, fractal_node, task_id, node)
3505
-
3506
- def fractal_node_diff(self, key, task_id, node):
3507
- return self._find(key, fractal_node_diff, task_id, node)
3508
-
3509
3911
  def verification_log(self, key, lane=None, k=None, first=None, retry=False):
3510
3912
  return self._find(key, verification_log, lane, k, first, retry)
3511
3913