@giamme/forge 0.22.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 (153) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +19 -12
  3. package/SKILL.md +137 -216
  4. package/VERSION +1 -1
  5. package/docs/README.md +2 -3
  6. package/docs/add-ons.md +5 -3
  7. package/docs/artifacts.md +17 -2
  8. package/docs/commands.md +85 -63
  9. package/docs/decomposed-runs.md +195 -21
  10. package/docs/development.md +11 -9
  11. package/docs/forge-ui.md +33 -4
  12. package/docs/install.md +37 -5
  13. package/docs/memory.md +6 -1
  14. package/docs/models.md +36 -10
  15. package/docs/reviews.md +44 -25
  16. package/docs/safety.md +27 -2
  17. package/docs/troubleshooting.md +7 -10
  18. package/forge +25 -4
  19. package/package.json +2 -1
  20. package/references/dataset.md +10 -9
  21. package/references/decompose-integration.md +337 -0
  22. package/references/decompose-opt-in.md +527 -0
  23. package/references/decompose-recovery.md +569 -0
  24. package/references/decompose-review.md +256 -0
  25. package/references/decompose.md +99 -1606
  26. package/references/findings.md +68 -0
  27. package/references/harnesses.md +7 -12
  28. package/references/memory.md +13 -2
  29. package/references/planning.md +48 -18
  30. package/references/ripwire.md +38 -13
  31. package/references/runtime.md +22 -33
  32. package/references/setup.md +90 -0
  33. package/references/solo.md +13 -42
  34. package/references/ui.md +12 -5
  35. package/registry.tsv +40 -22
  36. package/scripts/forge-artifact.sh +143 -12
  37. package/scripts/forge-compare.py +5 -15
  38. package/scripts/forge-config.py +14 -1
  39. package/scripts/forge-contract.py +216 -53
  40. package/scripts/forge-control.py +777 -54
  41. package/scripts/forge-dispatch.sh +95 -12
  42. package/scripts/forge-du.py +13 -3
  43. package/scripts/forge-handoff.py +221 -39
  44. package/scripts/forge-install-ripwire.sh +100 -24
  45. package/scripts/forge-install.sh +18 -32
  46. package/scripts/forge-issues.py +6 -4
  47. package/scripts/forge-jev-options.sh +3 -5
  48. package/scripts/forge-lib-adopt.sh +169 -5
  49. package/scripts/forge-lib-attribute.sh +10 -3
  50. package/scripts/forge-lib-decompose.sh +454 -0
  51. package/scripts/forge-lib-env.sh +21 -0
  52. package/scripts/forge-lib-group.sh +4 -1
  53. package/scripts/forge-lib-plans.sh +30 -18
  54. package/scripts/forge-lib-review.sh +28 -8
  55. package/scripts/forge-lib-task.sh +225 -56
  56. package/scripts/forge-lib-verify.sh +59 -10
  57. package/scripts/forge-memory.sh +81 -4
  58. package/scripts/forge-metrics.sh +4 -2
  59. package/scripts/forge-parallel-options.sh +23 -4
  60. package/scripts/forge-parallel.sh +447 -175
  61. package/scripts/forge-plan-check.py +71 -8
  62. package/scripts/forge-planner.py +303 -17
  63. package/scripts/forge-pr.py +9 -1
  64. package/scripts/forge-prompt.py +2 -2
  65. package/scripts/forge-review-links.py +248 -0
  66. package/scripts/forge-ripwire.py +234 -16
  67. package/scripts/forge-route.py +19 -27
  68. package/scripts/forge-runs-rm.py +92 -21
  69. package/scripts/forge-runs.py +46 -5
  70. package/scripts/forge-runtime.py +37 -12
  71. package/scripts/forge-schedule.py +124 -33
  72. package/scripts/forge-setup-stale.py +236 -0
  73. package/scripts/forge-setup.py +804 -0
  74. package/scripts/forge-shadow.py +2 -20
  75. package/scripts/forge-solo-lock.py +46 -0
  76. package/scripts/forge-solo.sh +33 -56
  77. package/scripts/forge-sweep.py +2 -1
  78. package/scripts/forge-ui.py +8 -1
  79. package/scripts/forge-update.sh +2 -2
  80. package/scripts/forge-verify.py +16 -1
  81. package/scripts/forge-version.py +13 -1
  82. package/scripts/forge-watch.py +7 -2
  83. package/scripts/forge_dataset/__init__.py +1 -1
  84. package/scripts/forge_dataset/capture.py +0 -34
  85. package/scripts/forge_dataset/checks.py +0 -1
  86. package/scripts/forge_dataset/cli.py +5 -1
  87. package/scripts/forge_dataset/export.py +28 -6
  88. package/scripts/forge_dataset/facts.py +1 -2
  89. package/scripts/forge_dataset/forecast.py +1 -1
  90. package/scripts/forge_dataset/harvest.py +107 -7
  91. package/scripts/forge_dataset/importer.py +3 -2
  92. package/scripts/forge_dataset/pairs.py +3 -3
  93. package/scripts/forge_dataset/reviewers.py +4 -3
  94. package/scripts/forge_dataset/routing.py +6 -3
  95. package/scripts/forge_dataset/tiers.py +1 -1
  96. package/scripts/forge_decide/__init__.py +1 -1
  97. package/scripts/forge_decide/profiles.py +11 -14
  98. package/scripts/forge_decompose.py +987 -0
  99. package/scripts/forge_groups/review.py +6 -1
  100. package/scripts/forge_jev/__init__.py +1 -1
  101. package/scripts/forge_jev/cli.py +10 -1
  102. package/scripts/forge_jev/gates.py +10 -1
  103. package/scripts/forge_jev/verify.py +10 -2
  104. package/scripts/forge_legacy.py +86 -0
  105. package/scripts/forge_memory_home.py +57 -0
  106. package/scripts/forge_models.py +151 -0
  107. package/scripts/forge_prefs.py +138 -0
  108. package/scripts/forge_side/__init__.py +10 -0
  109. package/scripts/forge_storage.py +28 -15
  110. package/ui/README.md +22 -10
  111. package/ui/docs/api.md +121 -99
  112. package/ui/forge_ui/control.py +46 -14
  113. package/ui/forge_ui/export.py +0 -10
  114. package/ui/forge_ui/models.py +15 -2
  115. package/ui/forge_ui/projects.py +4 -1
  116. package/ui/forge_ui/reader.py +456 -59
  117. package/ui/forge_ui/server.py +0 -10
  118. package/ui/forge_ui/static/app.js +28 -9
  119. package/ui/forge_ui/static/checksview.js +12 -3
  120. package/ui/forge_ui/static/controls.js +147 -11
  121. package/ui/forge_ui/static/convo.js +5 -2
  122. package/ui/forge_ui/static/diffview.js +4 -5
  123. package/ui/forge_ui/static/panel.js +180 -77
  124. package/ui/forge_ui/static/projectsview.js +16 -2
  125. package/ui/forge_ui/static/runmodel.js +18 -4
  126. package/ui/forge_ui/static/scene3d.js +29 -29
  127. package/ui/forge_ui/static/settings.js +1 -1
  128. package/ui/forge_ui/static/storageview.js +2 -2
  129. package/ui/forge_ui/static/style.css +23 -6
  130. package/ui/forge_ui/static/worktreesview.js +8 -4
  131. package/ui/forge_ui/transcripts.py +6 -0
  132. package/ui/forge_ui/worktrees.py +13 -1
  133. package/docs/fractal.md +0 -181
  134. package/references/fractal-dashboard.md +0 -21
  135. package/references/fractal.md +0 -307
  136. package/scripts/forge-fractal-dispatch.sh +0 -4
  137. package/scripts/forge-fractal-options.sh +0 -54
  138. package/scripts/forge-fractal.py +0 -6
  139. package/scripts/forge-install-fractal.sh +0 -4
  140. package/scripts/forge_fractal/__init__.py +0 -88
  141. package/scripts/forge_fractal/bridge.py +0 -46
  142. package/scripts/forge_fractal/cli.py +0 -224
  143. package/scripts/forge_fractal/dashboard.css +0 -138
  144. package/scripts/forge_fractal/dashboard.html +0 -41
  145. package/scripts/forge_fractal/dashboard.js +0 -687
  146. package/scripts/forge_fractal/decomposition.py +0 -262
  147. package/scripts/forge_fractal/execution.py +0 -659
  148. package/scripts/forge_fractal/inspection.py +0 -261
  149. package/scripts/forge_fractal/install.py +0 -158
  150. package/scripts/forge_fractal/invocation.py +0 -95
  151. package/scripts/forge_fractal/pipeline.py +0 -125
  152. package/scripts/forge_fractal/selection.py +0 -180
  153. 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`.
@@ -452,6 +494,241 @@ def _followers(listed, target):
452
494
  return found
453
495
 
454
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
+
455
732
  def _summary(reader, source):
456
733
  result = dict(key=run_key(reader.path), path=str(reader.path), source=source, kind='plan',
457
734
  run_id=reader.line('run_id'), repo=reader.line('repo'),
@@ -469,6 +746,13 @@ def _summary(reader, source):
469
746
  # accepted.integration (or the published verdict / review.meta) moves the activity time.
470
747
  final_review_outdated = _published_outdated(reader, tasks)
471
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
472
756
  result.update(updated=reader.updated, created=_created(reader.path, _PLAN_START_FILES),
473
757
  task_count=len(tasks), counts=counts,
474
758
  task_statuses=[dict(id=task['id'], status=task['status'], difficulty=task['difficulty'] or None,
@@ -505,7 +789,8 @@ def _solo_summary(reader, source):
505
789
  goal = reader.line('goal.txt')
506
790
  # Before `updated` is copied out: a present `after` file is part of what the summary read.
507
791
  after = _predecessor(reader)
508
- 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,
509
794
  run_id=reader.path.name, repo=reader.line('repo'), goal=goal,
510
795
  decompose_level=None, verification_status=None, updated=reader.updated,
511
796
  created=_created(reader.path, _SOLO_START_FILES),
@@ -717,7 +1002,7 @@ def _now(reader, owner_dir, execs):
717
1002
  def _scheduler(reader):
718
1003
  """RunDetail.scheduler: whether a scheduler runs this plan now, and, while one does, what holds it: a drain, a
719
1004
  stop, infrastructure pauses (scheduler-written infra.paused) and the capacity it dispatches up to."""
720
- pid = (reader.object('scheduler.live') or {}).get('pid') if reader.exists('scheduler.live') else None
1005
+ pid = _live_pid(reader, 'scheduler.live')
721
1006
  live = forge_proc.pid_alive(pid)
722
1007
  result = dict(live=live, drained=False, stopping=None, pauses=[], max_parallel=None)
723
1008
  if not live:
@@ -994,6 +1279,11 @@ def _waiting(reader, tasks, scheduler):
994
1279
  running = [task for task in tasks if task['status'] == 'RUNNING']
995
1280
  for task in tasks:
996
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
997
1287
  if task['status'] in ('RUNNING', 'MERGED'):
998
1288
  continue
999
1289
  stop = _escalation_stop(reader, task['id'])
@@ -1326,8 +1616,44 @@ def _attempt_review(execs, attempt):
1326
1616
  return chosen
1327
1617
 
1328
1618
 
1329
- def _trail(reader, rows, execs, sources_name, escalations, queue_times):
1330
- """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)."""
1331
1657
  sources = _retry_sources(reader, sources_name)
1332
1658
  manual = _manual_indexes(rows, queue_times)
1333
1659
  result = []
@@ -1344,7 +1670,9 @@ def _trail(reader, rows, execs, sources_name, escalations, queue_times):
1344
1670
  worst=summary.get('worst') if summary else None, reason=_attempt_reason(
1345
1671
  index, row, rows, sources, escalations, manual),
1346
1672
  executions=[item['id'] for item in execs
1347
- 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 []))
1348
1676
  return result
1349
1677
 
1350
1678
 
@@ -1669,7 +1997,10 @@ def _task_detail(reader, task, run_id, waves, branches, max_attempts, origin, re
1669
1997
  execs = _task_execs(reader, task)
1670
1998
  task['executions'] = execs
1671
1999
  task['header'] = _header(reader, task['title'], texts['prompt'], texts['approach'], request, prefix, origin)
1672
- 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)
1673
2004
  task['now'] = _now(reader, prefix, execs) if task['status'] == 'RUNNING' else None
1674
2005
  merged = reader.stat(prefix + '/merged') if task['status'] == 'MERGED' else None
1675
2006
  task['merged_at'] = float(merged.st_mtime) if merged is not None else None
@@ -1766,7 +2097,7 @@ def _sweep(reader, tasks):
1766
2097
  _RUN_CONTROLS = ('control.log', 'retry_budget', 'infra_budget', 'drain', 'stop', 'max_parallel', 'infra.paused', 'infra.last',
1767
2098
  'infra_backoff', 'escalate_effort', 'control.requests', 'summaries', 'summaries_model')
1768
2099
  _TASK_CONTROLS = ('qa_threshold', 'retry_budget', 'retries.used', 'escalation.pin', 'escalation.stop', 'escalation.next',
1769
- 'summaries')
2100
+ 'summaries', 'steer.jsonl', 'steer.live', 'steer.inbox.jsonl')
1770
2101
 
1771
2102
 
1772
2103
  _FAIL_FIRST_RESULTS = ('proven', 'passes_without_change', 'inconclusive', 'error')
@@ -2265,6 +2596,7 @@ def _solo_detail(reader, source):
2265
2596
  request = reader.text('request.md')
2266
2597
  result['request'] = reader.cap(request, 'request')
2267
2598
  result['retro'] = _retro(reader)
2599
+ result['handoff'] = _handoff(reader)
2268
2600
  result['summaries'] = None # generated summaries are for plan tasks only
2269
2601
  result['brief'] = None # brief mode is a plan's questions, not a solo run's
2270
2602
  result['settings'] = dict.fromkeys(_SOLO_SETTINGS)
@@ -2293,12 +2625,13 @@ def _solo_detail(reader, source):
2293
2625
  gate=_gate(reader, 'qa.gate'), known_issues=_nonempty(reader, 'known_issues.md'),
2294
2626
  fail_first=_fail_first(reader, 'failfirst.json'), pre_review=None,
2295
2627
  now=_now(reader, '', execs) if status == 'RUNNING' else None, waiting=None, sweep=None, swept=[],
2296
- summary=None, summaries_override=None, brief=None)
2628
+ summary=None, summaries_override=None, brief=None, steer_waiting=[], steer_live=None,
2629
+ steer_sending=[])
2297
2630
  task['header'] = _header(reader, task['title'], prompt, approach, request, 'tasks/solo',
2298
2631
  _github_origin(reader))
2299
2632
  task['trail'] = _trail(reader, logged, execs, 'retry_sources.tsv', [], _queued_retries(reader).get('solo', ()))
2300
2633
  result.update(timeline=_timeline(execs, [], []), integration=None, final_review=None, final_reviews=[], adoptions=[],
2301
- deferrals=[], findings_available=findings.available(), fractal=fractal.summary(reader),
2634
+ deferrals=[], findings_available=findings.available(),
2302
2635
  scheduler=None, sweep=None)
2303
2636
  result.update(tasks=[task], warnings=reader.warnings, truncated=reader.truncated, updated=reader.updated)
2304
2637
  return result
@@ -2385,6 +2718,59 @@ def _retro(reader):
2385
2718
  return dict(text=reader.cap(reader.text('retro.md'), 'retro'), **counts)
2386
2719
 
2387
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
+
2388
2774
  def detail(path, source='plan') -> dict:
2389
2775
  reader = _Read(path)
2390
2776
  if _kind(reader.path) == 'solo':
@@ -2393,6 +2779,7 @@ def detail(path, source='plan') -> dict:
2393
2779
  request = reader.text('request.md')
2394
2780
  result['request'] = reader.cap(request, 'request')
2395
2781
  result['retro'] = _retro(reader)
2782
+ result['handoff'] = _handoff(reader)
2396
2783
  threshold = _threshold(reader)
2397
2784
  result['settings'] = dict(explore=reader.number('explore'), shadow_rate=reader.number('shadow_rate'),
2398
2785
  shadow_qa=_list(reader.text('shadow_qa') or ''), timeout=reader.number('timeout', int),
@@ -2414,6 +2801,7 @@ def detail(path, source='plan') -> dict:
2414
2801
  for name in _RUN_CONTROLS:
2415
2802
  reader.stat(name)
2416
2803
  result['scheduler'] = _scheduler(reader)
2804
+ result['scheduler']['stale'] = [task['id'] for task in tasks if task.get('stale')]
2417
2805
  _waiting(reader, tasks, result['scheduler'])
2418
2806
  result['sweep'] = _sweep(reader, tasks)
2419
2807
  run_execs = _run_execs(reader)
@@ -2439,7 +2827,6 @@ def detail(path, source='plan') -> dict:
2439
2827
  result['adoptions'] = _adoptions(reader)
2440
2828
  result['deferrals'] = [line.strip() for line in (reader.text('deferrals.txt') or '').splitlines() if line.strip()]
2441
2829
  result['findings_available'] = findings.available()
2442
- result['fractal'] = fractal.summary(reader)
2443
2830
  brief = _attach_brief(reader, tasks)
2444
2831
  result['brief'] = brief
2445
2832
  # Absent, not empty, when brief is off: proposals/ is not listed, so the run JSON does not change.
@@ -2456,10 +2843,33 @@ def detail(path, source='plan') -> dict:
2456
2843
  owner.setdefault(member, item['id'])
2457
2844
  for task in tasks:
2458
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
2459
2850
  result.update(tasks=tasks, warnings=reader.warnings, truncated=reader.truncated, updated=reader.updated)
2460
2851
  return result
2461
2852
 
2462
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
+
2463
2873
  # --- lazy details: one task, one execution, one final review ------------------------------
2464
2874
 
2465
2875
  _TEXTS = (('prompt', 'prompt.md'), ('approach', 'approach.md'), ('retry_findings', 'retry_findings.md'),
@@ -3243,33 +3653,6 @@ def files_detail(path, source='plan'):
3243
3653
  overlaps=overlaps, deferrals=deferrals, truncated=truncated, warnings=reader.warnings)
3244
3654
 
3245
3655
 
3246
- # --- Fractal: the child tasks inside a task ---------------------------------------------------
3247
-
3248
- def _fractal(path, task_id, read, *args):
3249
- reader = _Read(path)
3250
- kind = _kind(reader.path)
3251
- if kind == 'solo' and task_id == 'solo':
3252
- target = str(reader.path)
3253
- elif kind == 'plan' and any(task['id'] == task_id for task in _tasks(reader)):
3254
- # forge hands Fractal the task dir as --run-dir, resolved: its realpath names the Fractal task.
3255
- target = os.path.realpath(reader.path / 'tasks' / task_id)
3256
- else:
3257
- return None
3258
- return read(reader, run_key(reader.path), task_id, target, *args)
3259
-
3260
-
3261
- def fractal_detail(path, task_id, source='plan'):
3262
- return _fractal(path, task_id, fractal.task)
3263
-
3264
-
3265
- def fractal_node(path, task_id, node, source='plan'):
3266
- return _fractal(path, task_id, fractal.node, node)
3267
-
3268
-
3269
- def fractal_node_diff(path, task_id, node, source='plan'):
3270
- return _fractal(path, task_id, fractal.node_diff, node)
3271
-
3272
-
3273
3656
  # --- verification logs by path ---------------------------------------------------------------
3274
3657
 
3275
3658
  LANE_NAME = re.compile(r'[A-Za-z0-9][A-Za-z0-9_-]{0,63}')
@@ -3423,33 +3806,56 @@ class Catalog:
3423
3806
  """The keys of every run the list shows, without summarizing any of them."""
3424
3807
  return {run_key(path) for path, _source in discover(**self.options)}
3425
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
+
3426
3831
  def identity(self, key):
3427
3832
  """The identity of the run with this key, resolved in the same batch as the list; None for no such run."""
3428
- listed, identities = batch(discover(**self.options))
3833
+ listed, identities = self._batch(key)
3429
3834
  for path, _source, entry in listed:
3430
3835
  if run_key(path) == key:
3431
3836
  return identities[entry[0]]
3432
3837
  return None
3433
3838
 
3434
3839
  def _find(self, key, read, *args):
3435
- for path, source in discover(**self.options):
3436
- if run_key(path) == key:
3437
- result = read(path, *args, source=source)
3438
- return result if _kind(path) else None
3439
- 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
3440
3846
 
3441
3847
  def locate(self, key):
3442
3848
  """(path, kind) of the run with this key, kind 'plan' or 'solo'; None for an unknown key.
3443
3849
 
3444
3850
  The only way a write finds a run dir: the client names a key, never a path."""
3445
- for path, _source in discover(**self.options):
3446
- if run_key(path) == key:
3447
- kind = _kind(path)
3448
- return (str(path), kind) if kind else None
3449
- 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
3450
3856
 
3451
3857
  def get(self, key):
3452
- listed, identities = batch(discover(**self.options))
3858
+ listed, identities = self._batch(key)
3453
3859
  for path, source, entry in listed:
3454
3860
  if run_key(path) == key:
3455
3861
  result = _with_repo(detail(path, source=source), identities[entry[0]])
@@ -3502,15 +3908,6 @@ class Catalog:
3502
3908
  def findings(self, key):
3503
3909
  return self._find(key, run_findings)
3504
3910
 
3505
- def fractal(self, key, task_id):
3506
- return self._find(key, fractal_detail, task_id)
3507
-
3508
- def fractal_node(self, key, task_id, node):
3509
- return self._find(key, fractal_node, task_id, node)
3510
-
3511
- def fractal_node_diff(self, key, task_id, node):
3512
- return self._find(key, fractal_node_diff, task_id, node)
3513
-
3514
3911
  def verification_log(self, key, lane=None, k=None, first=None, retry=False):
3515
3912
  return self._find(key, verification_log, lane, k, first, retry)
3516
3913