@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
@@ -10,8 +10,14 @@
10
10
  needs --confirm: raising the cap is a person's decision),
11
11
  converge-window (reviews the non-converging signal looks at),
12
12
  summaries (on/off; with --task also inherit; on for a finished run
13
- also starts `forge summarize` detached, output in summaries.out)
13
+ also starts `forge summarize` detached, output in summaries.out;
14
+ refused while the plan has no summaries model),
15
+ summaries-model SPEC|default, brief-model SPEC|default
14
16
  pin <plan> <task> <spec> the model the task's next FULL implementer retry uses
17
+ models <plan> <tier> [--dwarf SPECS] [--qa SPECS]
18
+ the implementer and/or reviewer of every task of one difficulty
19
+ (low, medium, high) that has not started yet; SPECS is one spec or
20
+ a comma-separated pool, handed out in row order as `plan` does
15
21
  unpin <plan> <task>
16
22
  retry <plan> <task> [--dwarf SPEC] queue a retry of a stopped or failed task into the live run
17
23
  retry <plan> <task> --answer TEXT answer a NEEDS_INPUT task's question (or --answer-file F, - for stdin):
@@ -21,6 +27,9 @@
21
27
  a NEEDS_DECISION task (reviews that do not converge, or a stop with no
22
28
  stronger model) is resumed only by a decision: --decide retry=N or
23
29
  threshold=P0..P3, or --dwarf SPEC, each with --reason TEXT --approved
30
+ steer <plan> <task> TEXT|--file F queue a message for the task's next implementer attempt (1 to 8000
31
+ characters): tasks/<id>/steer.jsonl, given to the next dispatch
32
+ whatever starts it; it starts nothing, and control.log keeps no text
24
33
  accept <plan> <task> --reason TEXT --approved queue an accept of a FAIL, UNKNOWN or NEEDS_DECISION task into the
25
34
  live run: its findings become known issues, it merges, its dependents start
26
35
  add <plan> <task> queue a row added to tasks.tsv (with its prompt.md) into the live run
@@ -46,10 +55,18 @@ retry-budget, infra-retries, max-parallel, drain, resume, stop, retry and add.
46
55
  retry and add only queue a request in control.requests/ (one JSON file each): the scheduler
47
56
  applies or refuses it at its next pass and logs the outcome in control.log, with the same
48
57
  `request` id, as actor `scheduler`. A request never outlives the scheduler that was live
49
- when it was queued. A task-level change or a pin on a MERGED task, and a pin on a
50
- Fractal plan, are refused.
51
-
52
- A pin, a retry's --dwarf and an added row's specs are checked with `forge-dispatch.sh doctor
58
+ when it was queued. A task-level change or a pin on a MERGED task is refused.
59
+
60
+ `models` rewrites the dwarf and qa columns of tasks.tsv for the PENDING tasks of that tier that have
61
+ never started an attempt (a running, finished, merged or retried task keeps its model: a pin or a retry
62
+ changes that one), and leaves a scripted task's dwarf column alone. It needs no live run, so a plan can
63
+ be adjusted before `run`. The file is replaced atomically, and only if no other writer changed it in
64
+ between (an escalation rewrites a started task's row). `show --json` lists each tier's pending tasks
65
+ and their specs (`tiers`), the model each spec of the plan resolves to (`models`) and the registry
66
+ (`registry`, {alias: [[harness, model], ...]}, the first row the default), so forge-ui can show what a
67
+ spec runs before it is applied (#169, #187).
68
+
69
+ A pin, a retry's --dwarf, a `models` spec and an added row's specs are checked with `forge-dispatch.sh doctor
53
70
  --spec <spec> --role <role>`, which spends no quota, before the lock is taken.
54
71
  FORGE_CONTROL_DOCTOR replaces `bash forge-dispatch.sh doctor` with another command line, which
55
72
  then gets `--spec <spec> --role <role>`; tests use it.
@@ -58,15 +75,17 @@ An answer is 1 to 8000 characters (after stripping), with no NUL byte, and its r
58
75
  scheduler's 64 KiB limit. control.log records the retry with the value `answer` and `answer_chars`, never the text.
59
76
 
60
77
  Exit codes: 0 ok, 2 usage or invalid input (including an unsafe path), 3 refused (not live, MERGED,
61
- Fractal, a spec that fails doctor, the control lock busy for over 5 s).
78
+ a spec that fails doctor, the control lock busy for over 5 s).
62
79
  """
63
80
  from __future__ import annotations
64
81
 
65
82
  import argparse
66
83
  import contextlib
67
84
  import errno
85
+ import hashlib
68
86
  import json
69
87
  import os
88
+ import posixpath
70
89
  import re
71
90
  import shlex
72
91
  import stat
@@ -81,10 +100,14 @@ from pathlib import Path
81
100
  SCRIPTS = os.path.dirname(os.path.realpath(__file__))
82
101
  if SCRIPTS not in sys.path:
83
102
  sys.path.insert(0, SCRIPTS)
103
+ import forge_decompose # noqa: E402
84
104
  import forge_flock as fcntl # noqa: E402
85
105
  import forge_infra # noqa: E402
106
+ import forge_legacy # noqa: E402
107
+ import forge_models # noqa: E402
86
108
  import forge_posix # noqa: E402
87
109
  import forge_proc # noqa: E402
110
+ import forge_side # noqa: E402
88
111
 
89
112
  SKILL = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
90
113
  LOCK_WAIT = 5.0
@@ -100,11 +123,13 @@ STOP_MARKERS = ('escalation.stop', 'split.suggested', 'escalation.next')
100
123
  NEXT_ATTEMPT = "at the task's next attempt"
101
124
  NEXT_DECISION = 'at the next retry decision'
102
125
  NEXT_RETRY = 'at the next full retry (not QA-only resumes)'
126
+ NEXT_START = 'when each task starts'
103
127
  NEXT_VERIFY = 'at the next verification'
104
128
  NEXT_INFRA_WAIT = 'at the next infrastructure wait'
105
129
  NEXT_INFRA_STOP = 'at the next infrastructure stop'
106
130
  NEXT_DISPATCH = "at the scheduler's next dispatch decision"
107
131
  NEXT_CHANGE = "at the task's next change"
132
+ NEXT_BRIEF = 'at the next brief change proposal'
108
133
 
109
134
 
110
135
  class Invalid(Exception):
@@ -374,17 +399,6 @@ def is_live(plan):
374
399
  return forge_proc.pid_alive(pid)
375
400
 
376
401
 
377
- def is_fractal(plan):
378
- """fractal-selection.json present and not explicitly disabled (unreadable counts: fail closed)."""
379
- raw = read_file(plan, 'fractal-selection.json')
380
- if raw is None or not raw.strip():
381
- return False
382
- try:
383
- return bool(json.loads(raw).get('enabled'))
384
- except (ValueError, AttributeError):
385
- return True
386
-
387
-
388
402
  def task_status(plan, task, strict=False):
389
403
  try:
390
404
  if probe(plan, f'tasks/{task}/merged'):
@@ -397,12 +411,10 @@ def task_status(plan, task, strict=False):
397
411
  return words[0] if words else 'PENDING'
398
412
 
399
413
 
400
- def refuse_task(plan, task, pin=False, merged_ok=False):
414
+ def refuse_task(plan, task, merged_ok=False):
401
415
  # merged_ok: a switch that changes no run behaviour (summaries) may still be set on a finished task.
402
416
  if task_status(plan, task, strict=True) == 'MERGED' and not merged_ok:
403
417
  raise Refused(f'task {task} is MERGED: nothing left to change')
404
- if pin and is_fractal(plan):
405
- raise Refused('this plan runs under Fractal, which never applies pins')
406
418
 
407
419
 
408
420
  def number(text):
@@ -512,7 +524,65 @@ def show(plan, rows):
512
524
  if len(log) == LOG_SHOWN:
513
525
  break
514
526
  return dict(plan=plan, run_id=get('run_id') or os.path.basename(plan).removeprefix('forge-'),
515
- live=live, fractal=is_fractal(plan), run=run, tasks=tasks, log=log)
527
+ live=live, removed='Fractal' if forge_legacy.was_fractal(plan) else None, run=run, tasks=tasks, log=log,
528
+ tiers=tier_summary(plan, rows), models=spec_models(tasks), registry=registry_map(),
529
+ decomposition=decomposition(plan))
530
+
531
+
532
+ def decomposition(plan):
533
+ """The plan's limits and its tree of nodes, through every level (#153). A subtask is controlled in
534
+ its own plan dir (`plan` in each node): `forge control ... <that dir>`."""
535
+ try:
536
+ nodes = forge_decompose.tree(plan)
537
+ limits = dict(forge_decompose.limits(plan), frozen=forge_decompose.is_frozen(plan))
538
+ except (OSError, ValueError, forge_decompose.Invalid):
539
+ return None
540
+ keys = ('id', 'task', 'parent', 'level', 'plan', 'run', 'title', 'status', 'difficulty', 'model', 'qa', 'decision',
541
+ 'reason', 'by', 'children', 'merged')
542
+ return dict(limits=limits, nodes=[{k: n.get(k) for k in keys} for n in nodes])
543
+
544
+
545
+ def registry_map():
546
+ """{alias: [[harness, model], ...]} in registry order (the first row is the alias's default)."""
547
+ out = {}
548
+ for cells in forge_models.registry_rows():
549
+ out.setdefault(cells[0], []).append([cells[1], cells[2]])
550
+ return out
551
+
552
+
553
+ def spec_models(tasks):
554
+ """{spec: label} for every spec the controls show: each task's dwarf, qa, pin and next model."""
555
+ rows = forge_models.registry_rows()
556
+ out = {}
557
+ for info in tasks.values():
558
+ for key in ('dwarf', 'qa', 'pin', 'escalation_next'):
559
+ for spec in forge_models.pool(info.get(key) or ''):
560
+ if spec not in out:
561
+ out[spec] = forge_models.describe(spec, rows)
562
+ return out
563
+
564
+
565
+ def not_started(plan, task):
566
+ """A task `models` may change: PENDING and no attempt ever started."""
567
+ return task_status(plan, task) == 'PENDING' and not has(plan, f'tasks/{task}/attempt')
568
+
569
+
570
+ def tier_summary(plan, rows):
571
+ """{tier: {tasks, pending, dwarf: [specs], qa: [specs]}}: the specs the not-started tasks of the tier use."""
572
+ out = {tier: dict(tasks=0, pending=0, dwarf=[], qa=[]) for tier in DIFFICULTIES}
573
+ for row in rows:
574
+ if len(row) != 7 or row[2] not in out or not valid_task_id(row[0]):
575
+ continue
576
+ entry = out[row[2]]
577
+ entry['tasks'] += 1
578
+ if not not_started(plan, row[0]):
579
+ continue
580
+ entry['pending'] += 1
581
+ for column, key in ((4, 'dwarf'), (5, 'qa')):
582
+ for spec in forge_models.pool(row[column]):
583
+ if spec not in entry[key]:
584
+ entry[key].append(spec)
585
+ return out
516
586
 
517
587
 
518
588
  # ------------------------------------------------------------------------------------ changes
@@ -594,6 +664,51 @@ def _summaries(value, task):
594
664
  raise Invalid('needs on or off' + (' (or inherit to drop the override)' if task else ''))
595
665
 
596
666
 
667
+ def _summaries_model(value, _task):
668
+ """The model of a plan's task summaries (#162): a spec the doctor accepts, or default to drop the
669
+ plan's own and follow `forge config set summaries.model`."""
670
+ if value == 'default':
671
+ return value
672
+ if not value or re.search(r'[\s,\x00-\x1f\x7f]', value):
673
+ raise Invalid('needs one model spec such as haiku:low, or default')
674
+ doctor(value, 'qa')
675
+ return value
676
+
677
+
678
+ def _brief_model(value, _task):
679
+ """The model of a plan's brief-change dispatches (#163): as summaries-model."""
680
+ return _summaries_model(value, _task)
681
+
682
+
683
+ def summaries_on_anywhere(plan, rows):
684
+ """Whether summaries are on for the plan or for any one task's override."""
685
+ if forge_side.settings(plan)['summaries']['mode'] == 'on':
686
+ return True
687
+ return any(text_of(plan, f'tasks/{row[0]}/summaries') == 'on' for row in rows if valid_task_id(row[0]))
688
+
689
+
690
+ def refuse_model_gap(args, plan, rows, value):
691
+ """#163: summaries switched on, or a side model dropped while its feature is on, with no model left
692
+ for the plan. A planned plan does not read `forge config set ...model` again, so this names the key
693
+ that sets the model for this plan instead of letting every dispatch be skipped with `no-model`."""
694
+ where = shlex.quote(args.plan)
695
+ if args.key == 'summaries' and value == 'on' and not forge_side.settings(plan)['summaries']['model']:
696
+ raise Refused('summaries need a model and this plan has none (a planned plan keeps the settings it was '
697
+ 'planned with, so forge config set summaries.model does not reach it); set one first: '
698
+ f'forge control set {where} summaries-model SPEC, then switch summaries on')
699
+ if value != 'default':
700
+ return
701
+ if args.key == 'summaries-model' and not forge_side.fallback_model(plan, 'summaries') \
702
+ and summaries_on_anywhere(plan, rows):
703
+ raise Refused('summaries are on and default would leave this plan with no model (a planned plan does not '
704
+ 'read forge config set summaries.model); give another spec, or switch summaries off first: '
705
+ f'forge control set {where} summaries off')
706
+ if args.key == 'brief-model' and not forge_side.fallback_model(plan, 'brief') \
707
+ and forge_side.settings(plan)['brief']['level'] != 'off':
708
+ raise Refused('brief is on and default would leave this plan with no brief model (a planned plan does not '
709
+ 'read forge config set brief.model); give another spec')
710
+
711
+
597
712
  # key -> (plan only or both, validator, file, live only, when it applies)
598
713
  KEYS = {
599
714
  'qa-threshold': ('both', _qa, 'qa_threshold', False, NEXT_ATTEMPT),
@@ -611,6 +726,8 @@ KEYS = {
611
726
  'max-attempts': ('plan', _int, 'max_attempts', False, NEXT_DECISION),
612
727
  'converge-window': ('plan', _int, 'converge_window', False, NEXT_DECISION),
613
728
  'summaries': ('both', _summaries, 'summaries', False, NEXT_CHANGE),
729
+ 'summaries-model': ('plan', _summaries_model, 'summaries_model', False, NEXT_CHANGE),
730
+ 'brief-model': ('plan', _brief_model, 'brief_model', False, NEXT_BRIEF),
614
731
  }
615
732
 
616
733
 
@@ -638,15 +755,14 @@ def audit(plan, actor, action, task, key, value, previous, **extra):
638
755
  return entry
639
756
 
640
757
 
641
- def change(args, plan, rows, action, task, key, work, applies, summary, live_only=False, pin_guard=False,
642
- merged_ok=False):
758
+ def change(args, plan, rows, action, task, key, work, applies, summary, live_only=False, merged_ok=False):
643
759
  """Run work() -> (value, previous, changed) under the control lock, audit a change, report the result."""
644
760
  with control_lock(plan):
645
761
  probe(plan, 'control.log') # an unsafe log refuses the change instead of leaving it unaudited
646
762
  if live_only and not is_live(plan):
647
763
  raise Refused(f'{key or action} can only change while a run is live (no live scheduler for this plan)')
648
764
  if task:
649
- refuse_task(plan, task, pin_guard, merged_ok)
765
+ refuse_task(plan, task, merged_ok)
650
766
  value, previous, changed = work()
651
767
  if changed: # setting a value it already has, or unpinning nothing, is not a change
652
768
  audit(plan, args.actor, action, task, key, value, previous)
@@ -679,6 +795,7 @@ def cmd_set(args):
679
795
  value = check(args.value, task)
680
796
  except Invalid as error:
681
797
  raise Invalid(f'{args.key}: {error}')
798
+ refuse_model_gap(args, plan, rows, value)
682
799
  rel = f'tasks/{task}/{name}' if task else name
683
800
  drop = (value in ('inherit', 'default') or (args.key in ('escalate-effort', 'pre-review-tests') and value == 'off')
684
801
  or (args.key == 'infra-backoff' and value == 'none'))
@@ -750,7 +867,7 @@ def cmd_pin(args):
750
867
  spec = args.spec
751
868
  if not spec or re.search(r'[\s\x00-\x1f\x7f]', spec):
752
869
  raise Invalid('a pin is one dwarf spec such as sol:high:codex, without whitespace')
753
- refuse_task(plan, args.task, pin=True)
870
+ refuse_task(plan, args.task)
754
871
  doctor(spec) # before the lock: it takes a moment, and the lock is for check-and-write only
755
872
  rel = f'tasks/{args.task}/escalation.pin'
756
873
 
@@ -760,7 +877,7 @@ def cmd_pin(args):
760
877
  return spec, previous, previous != spec
761
878
 
762
879
  return change(args, plan, rows, 'pin', args.task, 'pin', work, NEXT_RETRY,
763
- lambda v: f'pinned task {args.task} to {v}', pin_guard=True)
880
+ lambda v: f'pinned task {args.task} to {v} ({forge_models.describe(v)})')
764
881
 
765
882
 
766
883
  def cmd_unpin(args):
@@ -777,6 +894,95 @@ def cmd_unpin(args):
777
894
  lambda v: f'unpinned task {args.task}')
778
895
 
779
896
 
897
+ def pool_specs(text, what):
898
+ """The specs of --dwarf/--qa: one spec or a comma-separated pool, each clean; Invalid otherwise."""
899
+ specs = [part.strip() for part in (text or '').split(',')]
900
+ if not specs or any(not s for s in specs):
901
+ raise Invalid(f'{what} must be one spec or a comma-separated pool such as sol:high,astra:xhigh')
902
+ for spec in specs:
903
+ clean_spec(spec, what)
904
+ return specs
905
+
906
+
907
+ def cmd_models(args):
908
+ """The implementer and/or reviewer of every not-started task of one difficulty tier (#169)."""
909
+ plan, rows = load(args.plan)
910
+ if args.tier not in DIFFICULTIES:
911
+ raise Invalid('the tier is low, medium or high')
912
+ if args.dwarf is None and args.qa is None:
913
+ raise Invalid('give --dwarf, --qa or both')
914
+ dwarfs = pool_specs(args.dwarf, '--dwarf') if args.dwarf is not None else None
915
+ qas = pool_specs(args.qa, '--qa') if args.qa is not None else None
916
+ for spec in dwarfs or []:
917
+ doctor(spec, 'dwarf')
918
+ for spec in qas or []:
919
+ doctor(spec, 'qa')
920
+ result = {}
921
+
922
+ def rewrite(text):
923
+ lines, changed, kept, d_i, q_i = text.split('\n'), [], {}, 0, 0
924
+ for i, line in enumerate(lines):
925
+ cells = line.split('\t')
926
+ if line.startswith('#') or len(cells) != 7 or cells[2] != args.tier or not valid_task_id(cells[0]):
927
+ continue
928
+ if not not_started(plan, cells[0]):
929
+ kept[cells[0]] = task_status(plan, cells[0])
930
+ continue
931
+ before = list(cells)
932
+ if dwarfs and cells[4] != 'script':
933
+ cells[4] = dwarfs[d_i % len(dwarfs)]
934
+ d_i += 1
935
+ if qas:
936
+ cells[5] = qas[q_i % len(qas)]
937
+ q_i += 1
938
+ if cells != before:
939
+ lines[i] = '\t'.join(cells)
940
+ changed.append(dict(task=cells[0], dwarf=[before[4], cells[4]], qa=[before[5], cells[5]]))
941
+ return '\n'.join(lines), changed, kept
942
+
943
+ def work():
944
+ for _ in range(5):
945
+ text = read_file(plan, 'tasks.tsv', strict=True)
946
+ new, changed, kept = rewrite(text)
947
+ result.update(changed=changed, kept=kept)
948
+ if not changed:
949
+ return None, None, False
950
+ # Compare and swap: an escalation may rewrite a started task's row meanwhile.
951
+ if read_file(plan, 'tasks.tsv', strict=True) != text:
952
+ continue
953
+ write_atomic(plan, 'tasks.tsv', new)
954
+ value = ';'.join(x for x in (f'dwarf={args.dwarf}' if dwarfs else '', f'qa={args.qa}' if qas else '') if x)
955
+ return value, None, True
956
+ raise Refused('tasks.tsv kept changing under the change; try again')
957
+
958
+ with control_lock(plan):
959
+ probe(plan, 'control.log')
960
+ value, previous, changed = work()
961
+ if changed:
962
+ audit(plan, args.actor, 'models', None, args.tier, value, previous,
963
+ tasks=[c['task'] for c in result['changed']])
964
+ controls = show(plan, load(args.plan)[1])
965
+ models = forge_models.registry_rows()
966
+ labels = {s: forge_models.describe(s, models) for s in (dwarfs or []) + (qas or [])}
967
+ if args.json:
968
+ json.dump(dict(ok=True, changed=dict(action='models', task=None, key=args.tier, value=value, previous=None),
969
+ tasks=result['changed'], kept=result['kept'], models=labels,
970
+ applies=NEXT_START, controls=controls), sys.stdout, indent=2)
971
+ sys.stdout.write('\n')
972
+ else:
973
+ n = len(result['changed'])
974
+ if not n:
975
+ print(f'no {args.tier} task that has not started needed a change; nothing logged')
976
+ else:
977
+ roles = ', '.join(f'{role} {" / ".join(f"{s} ({labels[s]})" for s in specs)}'
978
+ for role, specs in (('dwarf', dwarfs), ('qa', qas)) if specs)
979
+ print(f'{n} {args.tier} task{"s" if n != 1 else ""} ({", ".join(c["task"] for c in result["changed"])}) '
980
+ f'now use {roles}; applies {NEXT_START}')
981
+ if result['kept']:
982
+ print('kept (already started): ' + ', '.join(f'{t} ({st})' for t, st in sorted(result['kept'].items())))
983
+ return 0
984
+
985
+
780
986
  def run_command(args, action, rel, value, summary):
781
987
  """drain, resume and stop: a live-only plan file the scheduler reads at every pass.
782
988
  value None removes the file; logged with the action and no key."""
@@ -862,11 +1068,31 @@ def check_row(plan, rows, task):
862
1068
  return dwarf, qa
863
1069
 
864
1070
 
865
- def queue(args, plan, verb, task, dwarf, decision=None, accept_reason=None, answer=None):
1071
+ def brief_changed(plan, task):
1072
+ """#220: whether tasks/<task>/prompt.md or approach.md differs from what its last attempt was given
1073
+ (prompt.dispatched, approach.dispatched), or None when no attempt recorded that."""
1074
+ root = Path(plan) / 'tasks' / task
1075
+ if not (root / 'prompt.dispatched').is_file():
1076
+ return None
1077
+ for name in ('prompt', 'approach'):
1078
+ given = root / (name + '.dispatched')
1079
+ if not given.is_file():
1080
+ continue
1081
+ try:
1082
+ now = (root / (name + '.md')).read_bytes() if (root / (name + '.md')).is_file() else b''
1083
+ if given.read_bytes() != now:
1084
+ return True
1085
+ except OSError:
1086
+ return None
1087
+ return False
1088
+
1089
+
1090
+ def queue(args, plan, verb, task, dwarf, decision=None, accept_reason=None, answer=None, subtasks=None):
866
1091
  """Write the request under the control lock, live only; log it with its id.
867
1092
  decision: a retry's (--decide choice or None, reason, approved) for a NEEDS_DECISION task.
868
1093
  accept_reason: an accept's reason; it is given with --approved (#138).
869
- answer: a NEEDS_INPUT task's answer (#147); the log records that there was one, never the text."""
1094
+ answer: a NEEDS_INPUT task's answer (#147); the log records that there was one, never the text.
1095
+ subtasks: a split's checked subtasks (#153), as the name of the file they are stored in under the task."""
870
1096
  with control_lock(plan):
871
1097
  probe(plan, 'control.log')
872
1098
  if not is_live(plan):
@@ -875,11 +1101,13 @@ def queue(args, plan, verb, task, dwarf, decision=None, accept_reason=None, answ
875
1101
  f'directly: forge-parallel.sh accept {plan} {task} --reason TEXT --approved')
876
1102
  raise Refused(f'{verb} needs a live run (no live scheduler for this plan)')
877
1103
  if verb == 'retry':
878
- refuse_task(plan, task, pin=True)
1104
+ refuse_task(plan, task)
879
1105
  name = f'{time.time_ns()}-{os.getpid()}.json'
880
1106
  request = dict(verb=verb, task=task, dwarf=dwarf, at=time.time(), actor=args.actor)
881
1107
  if decision:
882
1108
  request.update(decide=decision[0], reason=decision[1], approved=True)
1109
+ if subtasks:
1110
+ request['subtasks'] = subtasks
883
1111
  extra = {}
884
1112
  if accept_reason is not None:
885
1113
  request.update(reason=accept_reason, approved=True)
@@ -887,6 +1115,8 @@ def queue(args, plan, verb, task, dwarf, decision=None, accept_reason=None, answ
887
1115
  if answer is not None:
888
1116
  request['answer'] = answer
889
1117
  extra['answer_chars'] = len(answer)
1118
+ if decision:
1119
+ extra['brief_changed'] = brief_changed(plan, task)
890
1120
  body = json.dumps(request) + '\n'
891
1121
  if len(body.encode('utf-8')) > REQUEST_MAX:
892
1122
  raise Refused(f'the answer does not fit in a request ({len(body.encode("utf-8"))} bytes, the scheduler reads '
@@ -904,7 +1134,72 @@ def queue(args, plan, verb, task, dwarf, decision=None, accept_reason=None, answ
904
1134
  return 0
905
1135
 
906
1136
 
907
- DECISION = re.compile(r'retry=(?:[1-9]|1[0-9]|20)|threshold=P[0-3]')
1137
+ DECISION = re.compile(r'retry=(?:[1-9]|1[0-9]|20)|threshold=P[0-3]|files\+=[^\s,]+(?:,[^\s,]+)*')
1138
+ FILES_ADD = 'files+='
1139
+
1140
+
1141
+ def files_paths(decide):
1142
+ """#199: the paths of a `files+=<path>[,<path>]` decision, normalized, or Invalid. Repo-relative paths
1143
+ only: no absolute path, no `..`, no `.forge`, at most 20."""
1144
+ paths = []
1145
+ for raw in decide[len(FILES_ADD):].split(','):
1146
+ path = posixpath.normpath(raw)
1147
+ if raw.startswith('/') or path in ('.', '..') or path.startswith('../') or '\0' in raw \
1148
+ or any(c.isspace() for c in raw) or path == '.forge' or path.startswith('.forge/'):
1149
+ raise Invalid(f'--decide files+=: {raw!r} is not a path inside the repository')
1150
+ if path not in paths:
1151
+ paths.append(path)
1152
+ if not paths or len(paths) > 20:
1153
+ raise Invalid('--decide files+= takes 1 to 20 paths, comma-separated')
1154
+ return paths
1155
+
1156
+
1157
+ def files_add(plan, task, decide, reason, check=False):
1158
+ """#199: add paths to a stopped task's files in tasks.tsv, the simplest plan choice for reason `plan`, on a live
1159
+ run or not. Refused (nothing written) when another task declares a path, or the task already owns every one.
1160
+ No path any task declares means no new overlap: the waves `plan` computed stay valid. With check, only checks.
1161
+ Logs `files-added` in control.log (the paths, the files before, the reason). Returns the new files column."""
1162
+ paths = files_paths(decide)
1163
+ schedule = schedule_module()
1164
+ for _ in range(5):
1165
+ text = read_file(plan, 'tasks.tsv', strict=True) or ''
1166
+ lines = text.splitlines()
1167
+ rows = [line.split('\t') for line in lines if line.strip() and not line.startswith('#')]
1168
+ mine = next((row for row in rows if row[0] == task), None)
1169
+ if mine is None or len(mine) < 7:
1170
+ raise Invalid(f'task {task!r} is not in this plan')
1171
+ for row in rows:
1172
+ if row[0] != task and len(row) > 3:
1173
+ owned = [path for path in paths if schedule.overlap(path, row[3])]
1174
+ if owned:
1175
+ raise Refused(f'{", ".join(owned)} overlaps the files of task {row[0]} ({row[3]}): that is a real '
1176
+ f'ownership conflict and needs the plan (make {task} depend on {row[0]}, or merge the rows)')
1177
+ before = mine[3].strip()
1178
+ current = [] if before in ('', '-') else [f for f in before.split(',') if f]
1179
+ new = [path for path in paths if not any(schedule.overlap(path, f) for f in current)]
1180
+ if not new:
1181
+ raise Refused(f'task {task} already owns {", ".join(paths)}')
1182
+ files = ','.join(current + new)
1183
+ if check:
1184
+ return files
1185
+ out = []
1186
+ for line in lines:
1187
+ cells = line.split('\t')
1188
+ if not line.startswith('#') and cells[0] == task:
1189
+ cells[3] = files
1190
+ line = '\t'.join(cells)
1191
+ out.append(line)
1192
+ if read_file(plan, 'tasks.tsv', strict=True) != text:
1193
+ continue
1194
+ write_atomic(plan, 'tasks.tsv', '\n'.join(out) + '\n')
1195
+ audit(plan, 'scheduler', 'files-added', task, 'files', ','.join(new), before or '-', reason=reason)
1196
+ return files
1197
+ raise Refused('tasks.tsv kept changing under the change; try again')
1198
+
1199
+
1200
+ SPLIT = re.compile(r'split(?:=keep|=fresh)?') # a split into subtasks (#153): not only for a NEEDS_DECISION task
1201
+ DECIDE_TAKES = ('--decide takes retry=N (1 to 20), threshold=P0|P1|P2|P3, files+=PATH[,PATH] (paths no task declares), '
1202
+ 'or split | split=fresh with --subtasks FILE')
908
1203
 
909
1204
 
910
1205
  def decision_of(plan, args, dwarf):
@@ -912,23 +1207,112 @@ def decision_of(plan, args, dwarf):
912
1207
  A NEEDS_DECISION task is resumed only by a decision: --decide or --dwarf, with --reason and
913
1208
  --approved. --decide is for no other task."""
914
1209
  status = task_status(plan, args.task, strict=True)
1210
+ if args.decide is not None and SPLIT.fullmatch(args.decide):
1211
+ if dwarf is not None:
1212
+ raise Invalid("--decide split does not take --dwarf: the subtasks are routed with the plan's pools")
1213
+ if status in forge_decompose.NOT_SPLITTABLE or status == 'NEEDS_INPUT':
1214
+ raise Refused(f'task {args.task} is {status}: only a task that has not passed, is not running and is not '
1215
+ 'waiting for an answer can be split')
1216
+ if forge_decompose.is_split(plan, args.task):
1217
+ raise Refused(f'task {args.task} is already split into subtasks ({forge_decompose.sub_dir(plan, args.task)}): '
1218
+ 'they are kept, never made twice')
1219
+ if not args.subtasks:
1220
+ raise Invalid('--decide split needs --subtasks FILE: the subtasks, as a forge-plan block or its JSON '
1221
+ '(forge-planner.py node-prompt describes it). To ask a planner instead, with no run live: '
1222
+ f'forge-parallel.sh retry {plan} {args.task} --decide split --planner SPEC --reason TEXT --approved')
1223
+ return args.decide, decision_words(args), True
1224
+ if args.subtasks:
1225
+ raise Invalid('--subtasks goes with --decide split')
915
1226
  if status != 'NEEDS_DECISION':
916
1227
  if args.decide is not None:
917
- raise Refused(f'task {args.task} is {status}, not waiting for a decision: --decide only decides a NEEDS_DECISION task')
1228
+ hint = ' (retry without --decide)' if status in (
1229
+ 'FAIL', 'UNKNOWN', 'ERROR', 'TIMEOUT', 'INTERRUPTED', 'INVALIDATED', 'CONFLICT',
1230
+ ) else ''
1231
+ raise Refused(f'task {args.task} is {status}, not waiting for a decision: --decide only decides a NEEDS_DECISION task{hint}')
918
1232
  return None
919
1233
  if args.decide is None and dwarf is None:
920
1234
  head = ' '.join(line.strip() for line in (read_file(plan, f'tasks/{args.task}/decision.md') or '').splitlines()[:3]
921
1235
  if line.strip())
922
1236
  raise Refused(f'task {args.task} is waiting for your decision, and only a decision resumes it: {head or "see decision.md"} '
923
- '(retry --decide retry=N | threshold=Pn, or --dwarf SPEC, each with --reason TEXT --approved)')
1237
+ '(retry --decide retry=N | threshold=Pn | split, or --dwarf SPEC, each with --reason TEXT --approved)')
924
1238
  if args.decide is not None and not DECISION.fullmatch(args.decide):
925
- raise Invalid('--decide takes retry=N (1 to 20) or threshold=P0|P1|P2|P3')
1239
+ raise Invalid(DECIDE_TAKES)
1240
+ if args.decide is not None and args.decide.startswith(FILES_ADD):
1241
+ # #199: checked now, so a path another task declares is refused with nothing queued. The scheduler writes
1242
+ # the row when it applies the request, and checks again.
1243
+ files_add(plan, args.task, args.decide, decision_words(args), check=True)
1244
+ return args.decide, decision_words(args), True
1245
+
1246
+
1247
+ def decision_words(args):
1248
+ """The reason of a decision, on one line. A decision needs it, and --approved."""
926
1249
  reason = re.sub(r'\s+', ' ', args.reason or '').strip()
927
1250
  if not reason:
928
1251
  raise Invalid('a decision needs --reason TEXT: it is recorded with the task')
929
1252
  if not args.approved:
930
1253
  raise Invalid('a decision needs --approved: it resumes a task forge stopped, and is only given on the user\'s instruction')
931
- return args.decide, reason, True
1254
+ return reason
1255
+
1256
+
1257
+ def forge_script(name):
1258
+ script = os.path.join(SKILL, 'scripts', name)
1259
+ return forge_proc.bash_cmd(script) if forge_proc.IS_WINDOWS else ['bash', script]
1260
+
1261
+
1262
+ def passed_through(args, command):
1263
+ """Run a forge command for this call. With --json, stdout is the JSON: the command's own words go to stderr."""
1264
+ if args.json:
1265
+ done = subprocess.run(command, stdin=subprocess.DEVNULL, capture_output=True, text=True)
1266
+ sys.stderr.write(done.stdout + done.stderr)
1267
+ else:
1268
+ done = subprocess.run(command, stdin=subprocess.DEVNULL)
1269
+ return done.returncode
1270
+
1271
+
1272
+ def retry_split(args, plan, decision):
1273
+ """A split into subtasks (#153). Live: the subtasks are checked now and stored beside the task, and the
1274
+ request names that file; the scheduler makes the sub-plan and runs it. Not live: the split is made
1275
+ now, as `forge-parallel.sh retry --decide split --no-dispatch` does, and the next `run` runs it."""
1276
+ if not os.path.isfile(args.subtasks):
1277
+ raise Invalid(f'--subtasks {args.subtasks}: not a readable file')
1278
+ if not is_live(plan):
1279
+ rc = passed_through(args, forge_script('forge-parallel.sh') + [
1280
+ 'retry', plan, args.task, '--decide', decision[0], '--subtasks', args.subtasks,
1281
+ '--reason', decision[1], '--approved', '--no-dispatch'])
1282
+ if rc == 0 and args.json:
1283
+ json.dump(dict(queued=False, prepared=True, split=True), sys.stdout)
1284
+ sys.stdout.write('\n')
1285
+ elif rc == 0:
1286
+ print(f'no run is live: task {args.task} is split; the next `forge-parallel.sh run {plan}` runs its subtasks')
1287
+ return rc
1288
+ name = f'split.request.{time.time_ns()}-{os.getpid()}.json'
1289
+ stored = os.path.join(plan, 'tasks', args.task, name)
1290
+ checked = subprocess.run([sys.executable, os.path.join(SKILL, 'scripts', 'forge-planner.py'), 'node-parse', '--plan', plan,
1291
+ '--task', args.task, '--reply', args.subtasks, '--out', stored],
1292
+ stdin=subprocess.DEVNULL, capture_output=True, text=True)
1293
+ if checked.returncode != 0:
1294
+ raise Refused((checked.stdout + checked.stderr).strip() or 'the subtasks were refused')
1295
+ try:
1296
+ proposal = json.loads(Path(stored).read_text(encoding='utf-8'))
1297
+ forge_decompose.check_split(plan, args.task, proposal.get('tasks'))
1298
+ except forge_decompose.Atomic:
1299
+ with contextlib.suppress(OSError):
1300
+ os.unlink(stored)
1301
+ raise Refused('the subtasks are one task, not a split: a split has at least two')
1302
+ except forge_decompose.Bounded as limit:
1303
+ with contextlib.suppress(OSError):
1304
+ os.unlink(stored)
1305
+ raise Refused(f'{limit}. {forge_decompose.describe(forge_decompose.limits(plan))}')
1306
+ except (OSError, ValueError, forge_decompose.Invalid) as error:
1307
+ with contextlib.suppress(OSError):
1308
+ os.unlink(stored)
1309
+ raise Refused(f'the subtasks were refused: {error}')
1310
+ try:
1311
+ return queue(args, plan, 'retry', args.task, None, decision, subtasks=name)
1312
+ except BaseException:
1313
+ with contextlib.suppress(OSError):
1314
+ os.unlink(stored)
1315
+ raise
932
1316
 
933
1317
 
934
1318
  ANSWER_MAX = 8000 # characters; the scheduler reads the same limit
@@ -988,6 +1372,301 @@ def answer_of(args):
988
1372
  return text
989
1373
 
990
1374
 
1375
+ STEER_MAX = 8000 # characters of one message for the next attempt (#134)
1376
+ STEER_QUEUE = 20 # messages waiting at once for one task
1377
+ STEER_FILE = 'steer.jsonl'
1378
+ STEER_LIVE = 'steer.live' # live steering (#252): the running attempt's feeder, while it takes messages
1379
+ STEER_INBOX = 'steer.inbox.jsonl' # messages for that running attempt, until the feeder sends them
1380
+ STEER_POLL = 0.5 # seconds between the feeder's looks at the inbox and the log
1381
+
1382
+
1383
+ def steer_text(args):
1384
+ """The message --file or TEXT gives (stripped), checked as an answer is."""
1385
+ if (args.text is None) == (args.file is None):
1386
+ raise Invalid('give the message as TEXT or with --file FILE (- for stdin), not both')
1387
+ text = args.text if args.file is None else answer_file_text(args.file)
1388
+ text = text.strip()
1389
+ if not text:
1390
+ raise Invalid('the message is empty')
1391
+ if '\0' in text:
1392
+ raise Invalid('the message contains a NUL byte')
1393
+ if len(text) > STEER_MAX:
1394
+ raise Invalid(f'the message is limited to {STEER_MAX} characters')
1395
+ return text
1396
+
1397
+
1398
+ def steer_entries(plan, rel):
1399
+ """The JSON lines of a steer file; a line that does not parse is skipped."""
1400
+ out = []
1401
+ for line in (read_file(plan, rel, strict=True) or '').splitlines():
1402
+ try:
1403
+ entry = json.loads(line)
1404
+ except ValueError:
1405
+ continue
1406
+ if isinstance(entry, dict) and isinstance(entry.get('text'), str):
1407
+ out.append(entry)
1408
+ return out
1409
+
1410
+
1411
+ def steer_digest(text):
1412
+ return hashlib.sha256(text.encode('utf-8')).hexdigest()
1413
+
1414
+
1415
+ def cmd_steer(args):
1416
+ """Queue a message for a task's next implementer attempt (#134): stored in tasks/<id>/steer.jsonl, given to
1417
+ the next dispatch of that task, whatever starts it, and logged without its text. It starts nothing."""
1418
+ plan, rows = load(args.plan)
1419
+ require_task(rows, args.task)
1420
+ text = steer_text(args)
1421
+ if args.now:
1422
+ return steer_now(args, plan, text)
1423
+ rel = f'tasks/{args.task}/{STEER_FILE}'
1424
+ with control_lock(plan):
1425
+ probe(plan, 'control.log')
1426
+ refuse_task(plan, args.task)
1427
+ if len(steer_entries(plan, rel)) >= STEER_QUEUE:
1428
+ raise Refused(f'task {args.task} already has {STEER_QUEUE} messages waiting for its next attempt')
1429
+ entry = dict(at=time.time(), actor=args.actor, text=text, sha256=steer_digest(text), chars=len(text))
1430
+ append_line(plan, rel, json.dumps(entry) + '\n')
1431
+ waiting = len(steer_entries(plan, rel))
1432
+ audit(plan, args.actor, 'steer', args.task, 'steer', 'queued', None, steer_chars=len(text),
1433
+ sha256=entry['sha256'], waiting=waiting)
1434
+ live = is_live(plan)
1435
+ if args.json:
1436
+ json.dump(dict(ok=True, queued=True, task=args.task, waiting=waiting, live=live, chars=len(text)), sys.stdout,
1437
+ indent=2)
1438
+ sys.stdout.write('\n')
1439
+ else:
1440
+ print(f'queued a message for task {args.task}\'s next attempt ({waiting} waiting); it starts nothing: '
1441
+ + ('the run gives it at the task\'s next dispatch' if live else
1442
+ 'the next run, retry or resume of the task gives it'))
1443
+ return 0
1444
+
1445
+
1446
+ def steer_feeder(plan, task):
1447
+ """The live feeder of the task's running attempt, {attempt, pid, harness, at}, or None when none takes
1448
+ messages: no steer.live, or its process is gone (a dispatch killed before it cleaned up)."""
1449
+ try:
1450
+ live = json.loads(read_file(plan, f'tasks/{task}/{STEER_LIVE}', strict=True) or '')
1451
+ pid = int(live['pid'])
1452
+ except (ValueError, KeyError, TypeError):
1453
+ return None
1454
+ return live if forge_proc.pid_alive(pid) else None
1455
+
1456
+
1457
+ def steer_now(args, plan, text):
1458
+ """--now (#252): the message goes to the running attempt's live feeder, which sends it to the implementer at
1459
+ its next tool boundary. Refused when the task's implementer is not running live: nothing is queued instead."""
1460
+ rel = f'tasks/{args.task}/{STEER_INBOX}'
1461
+ with control_lock(plan):
1462
+ probe(plan, 'control.log')
1463
+ refuse_task(plan, args.task)
1464
+ live = steer_feeder(plan, args.task)
1465
+ if live is None:
1466
+ raise Refused(f'task {args.task} has no implementer running with live steering (only a claude or '
1467
+ 'openclaude implementer runs live); queue the message for its next attempt instead '
1468
+ '(drop --now)')
1469
+ if len(steer_entries(plan, rel)) >= STEER_QUEUE:
1470
+ raise Refused(f'task {args.task} already has {STEER_QUEUE} messages waiting to be sent')
1471
+ entry = dict(at=time.time(), actor=args.actor, text=text, sha256=steer_digest(text), chars=len(text))
1472
+ append_line(plan, rel, json.dumps(entry) + '\n')
1473
+ waiting = len(steer_entries(plan, rel))
1474
+ attempt = live.get('attempt')
1475
+ audit(plan, args.actor, 'steer', args.task, 'steer', 'live', None, steer_chars=len(text),
1476
+ sha256=entry['sha256'], waiting=waiting, attempt=attempt)
1477
+ if args.json:
1478
+ json.dump(dict(ok=True, queued=False, sent=True, task=args.task, attempt=attempt, waiting=waiting, live=True,
1479
+ chars=len(text)), sys.stdout, indent=2)
1480
+ sys.stdout.write('\n')
1481
+ else:
1482
+ print(f'sending a message to task {args.task}\'s running implementer (attempt {attempt}); it arrives at '
1483
+ 'the next tool call. If the attempt ends first, it waits for the next attempt.')
1484
+ return 0
1485
+
1486
+
1487
+ def steer_requeue(plan, task, actor):
1488
+ """Moves the inbox's unsent messages back to the queue for the next attempt; how many moved. Under the
1489
+ control lock."""
1490
+ inbox = f'tasks/{task}/{STEER_INBOX}'
1491
+ entries = steer_entries(plan, inbox)
1492
+ if entries:
1493
+ probe(plan, 'control.log')
1494
+ for entry in entries:
1495
+ append_line(plan, f'tasks/{task}/{STEER_FILE}', json.dumps(entry) + '\n')
1496
+ remove_safe(plan, inbox)
1497
+ audit(plan, actor, 'steer-requeued', task, 'steer', str(len(entries)), None,
1498
+ sha256=[e.get('sha256') for e in entries])
1499
+ return len(entries)
1500
+
1501
+
1502
+ def cmd_steer_take(args):
1503
+ """forge-parallel.sh, as an implementer attempt starts: move the waiting messages to steered.<attempt>.jsonl
1504
+ (appended, so a re-dispatch of the same attempt keeps them) and log the delivery. Prints how many moved."""
1505
+ plan, rows = load(args.plan)
1506
+ require_task(rows, args.task)
1507
+ if not re.fullmatch(r'[1-9][0-9]{0,5}', args.attempt):
1508
+ raise Invalid('attempt must be a positive integer')
1509
+ rel, dest = f'tasks/{args.task}/{STEER_FILE}', f'tasks/{args.task}/steered.{args.attempt}.jsonl'
1510
+ with control_lock(plan):
1511
+ # What an earlier attempt's feeder left behind when its dispatch was killed: never sent, so still waiting.
1512
+ if steer_feeder(plan, args.task) is None:
1513
+ remove_safe(plan, f'tasks/{args.task}/{STEER_LIVE}')
1514
+ steer_requeue(plan, args.task, 'scheduler')
1515
+ entries = steer_entries(plan, rel)
1516
+ if entries:
1517
+ probe(plan, 'control.log')
1518
+ for entry in entries:
1519
+ append_line(plan, dest, json.dumps(entry) + '\n')
1520
+ remove_safe(plan, rel)
1521
+ audit(plan, 'scheduler', 'steer-delivered', args.task, 'steer', str(len(entries)), None,
1522
+ attempt=int(args.attempt), sha256=[e.get('sha256') for e in entries])
1523
+ print(len(entries))
1524
+ return 0
1525
+
1526
+
1527
+ class _Turns:
1528
+ """Reads a claude/openclaude stream-json log as it grows: whether the model has ended its turn, i.e. the last
1529
+ event is a `result` with only background-task events after it (forge-runtime.py's settled_result)."""
1530
+
1531
+ def __init__(self, path):
1532
+ self.path, self.offset, self.rest, self.ended = path, 0, b'', False
1533
+
1534
+ def poll(self):
1535
+ try:
1536
+ with open(self.path, 'rb') as handle:
1537
+ handle.seek(self.offset)
1538
+ chunk = handle.read()
1539
+ except OSError:
1540
+ return self.ended
1541
+ self.offset += len(chunk)
1542
+ *lines, self.rest = (self.rest + chunk).split(b'\n')
1543
+ for line in lines:
1544
+ try:
1545
+ event = json.loads(line)
1546
+ except ValueError:
1547
+ continue
1548
+ if not isinstance(event, dict):
1549
+ continue
1550
+ if event.get('type') == 'result':
1551
+ self.ended = True
1552
+ elif not (event.get('type') == 'system' and event.get('subtype') in _runtime().BACKGROUND_EVENTS):
1553
+ self.ended = False
1554
+ return self.ended
1555
+
1556
+
1557
+ _RUNTIME = None
1558
+
1559
+
1560
+ def _runtime():
1561
+ global _RUNTIME
1562
+ if _RUNTIME is None:
1563
+ import importlib.util
1564
+ spec = importlib.util.spec_from_file_location('forge_runtime', os.path.join(SKILL, 'scripts', 'forge-runtime.py'))
1565
+ _RUNTIME = importlib.util.module_from_spec(spec)
1566
+ spec.loader.exec_module(_RUNTIME)
1567
+ return _RUNTIME
1568
+
1569
+
1570
+ def user_message(text):
1571
+ """One stream-json input line: a user message, as claude and openclaude take it on --input-format stream-json."""
1572
+ return (json.dumps(dict(type='user', message=dict(role='user', content=[dict(type='text', text=text)])))
1573
+ + '\n').encode('utf-8')
1574
+
1575
+
1576
+ def cmd_steer_feed(args):
1577
+ """forge-dispatch.sh, as the stdin of a live claude/openclaude implementer (#252): sends the prompt as the first
1578
+ user message, then each message `steer --now` puts in the inbox, until the model ends its turn, the harness is
1579
+ gone or the dispatch says stop. Delivered messages join steered.<attempt>.jsonl (mode live). Its stdout is the
1580
+ harness's stdin, so it writes nothing else there."""
1581
+ plan, rows = load(args.plan)
1582
+ require_task(rows, args.task)
1583
+ if not re.fullmatch(r'[1-9][0-9]{0,5}', args.attempt):
1584
+ raise Invalid('attempt must be a positive integer')
1585
+ task, attempt = args.task, int(args.attempt)
1586
+ if args.pidfile:
1587
+ with contextlib.suppress(OSError):
1588
+ Path(args.pidfile).write_text(f'{os.getpid()}\n')
1589
+ out = sys.stdout.buffer
1590
+ parent = os.getppid() # the harness: the dispatch execs it with this process as its stdin
1591
+ turns = _Turns(args.log)
1592
+ with open(args.prompt_file, 'rb') as handle:
1593
+ prompt = handle.read().decode('utf-8', errors='replace')
1594
+
1595
+ def gone():
1596
+ return os.getppid() != parent or bool(args.stop and os.path.exists(args.stop))
1597
+
1598
+ try:
1599
+ out.write(user_message(prompt)) # first, so nothing below can keep the task from its implementer
1600
+ out.flush()
1601
+ except (BrokenPipeError, ConnectionResetError):
1602
+ return 0
1603
+ close = True
1604
+ try:
1605
+ with control_lock(plan):
1606
+ write_atomic(plan, f'tasks/{task}/{STEER_LIVE}', json.dumps(dict(
1607
+ attempt=attempt, pid=os.getpid(), harness=args.harness, at=time.time())) + '\n')
1608
+ while True:
1609
+ time.sleep(STEER_POLL)
1610
+ if gone() or turns.poll():
1611
+ break
1612
+ if probe(plan, f'tasks/{task}/{STEER_INBOX}'):
1613
+ steer_send(plan, task, attempt, out)
1614
+ except (BrokenPipeError, ConnectionResetError):
1615
+ pass # the harness closed its input: it is ending
1616
+ except (Invalid, Refused, OSError) as error:
1617
+ # Live steering stops; the implementer does not. Its input stays open, as a close mid-turn could end it.
1618
+ print(f'forge control: live steering of task {task} stopped: {error}', file=sys.stderr)
1619
+ close = False
1620
+ finally:
1621
+ with contextlib.suppress(Invalid, Refused, OSError):
1622
+ steer_close(plan, task, os.getpid())
1623
+ while not close and not gone():
1624
+ time.sleep(STEER_POLL)
1625
+ with contextlib.suppress(OSError):
1626
+ out.close()
1627
+ return 0
1628
+
1629
+
1630
+ def steer_send(plan, task, attempt, out):
1631
+ """Sends the inbox's messages to the implementer and records them as this attempt's (mode live)."""
1632
+ with control_lock(plan):
1633
+ entries = steer_entries(plan, f'tasks/{task}/{STEER_INBOX}')
1634
+ if not entries:
1635
+ return
1636
+ probe(plan, 'control.log')
1637
+ for entry in entries:
1638
+ out.write(user_message(entry['text']))
1639
+ out.flush() # a closed input raises here, before anything is recorded as sent
1640
+ now = time.time()
1641
+ for entry in entries:
1642
+ append_line(plan, f'tasks/{task}/steered.{attempt}.jsonl',
1643
+ json.dumps(dict(entry, mode='live', sent_at=now)) + '\n')
1644
+ remove_safe(plan, f'tasks/{task}/{STEER_INBOX}')
1645
+ audit(plan, 'scheduler', 'steer-sent', task, 'steer', str(len(entries)), None, attempt=attempt,
1646
+ sha256=[e.get('sha256') for e in entries])
1647
+
1648
+
1649
+ def steer_close(plan, task, pid=None):
1650
+ """Ends live steering of the task's attempt: removes steer.live (only the given feeder's, when pid is set)
1651
+ and moves unsent messages back to the queue. Prints nothing; how many went back."""
1652
+ with control_lock(plan):
1653
+ try:
1654
+ current = json.loads(read_file(plan, f'tasks/{task}/{STEER_LIVE}') or '').get('pid')
1655
+ except (ValueError, AttributeError):
1656
+ current = None
1657
+ if pid is None or current in (None, pid):
1658
+ remove_safe(plan, f'tasks/{task}/{STEER_LIVE}')
1659
+ return steer_requeue(plan, task, 'scheduler')
1660
+
1661
+
1662
+ def cmd_steer_close(args):
1663
+ """forge-dispatch.sh, once a live implementer has ended: whatever the feeder left (it may have been killed)."""
1664
+ plan, rows = load(args.plan)
1665
+ require_task(rows, args.task)
1666
+ print(steer_close(plan, args.task))
1667
+ return 0
1668
+
1669
+
991
1670
  def retry_prepared(args, plan, answer):
992
1671
  """No scheduler is live: prepare the answered task for the next `run`, as `forge-parallel.sh retry
993
1672
  --answer-file --no-dispatch` does, and pass its exit code through."""
@@ -995,23 +1674,18 @@ def retry_prepared(args, plan, answer):
995
1674
  try:
996
1675
  with os.fdopen(fd, 'w', encoding='utf-8') as handle:
997
1676
  handle.write(answer + '\n')
998
- command = ['bash', os.path.join(SKILL, 'scripts', 'forge-parallel.sh'), 'retry', plan, args.task,
999
- '--answer-file', tmp, '--no-dispatch']
1000
- if args.json: # stdout is the JSON: the command's own words go to stderr
1001
- done = subprocess.run(command, stdin=subprocess.DEVNULL, capture_output=True, text=True)
1002
- sys.stderr.write(done.stdout + done.stderr)
1003
- else:
1004
- done = subprocess.run(command, stdin=subprocess.DEVNULL)
1677
+ rc = passed_through(args, forge_script('forge-parallel.sh') + [
1678
+ 'retry', plan, args.task, '--answer-file', tmp, '--no-dispatch'])
1005
1679
  finally:
1006
1680
  with contextlib.suppress(OSError):
1007
1681
  os.unlink(tmp)
1008
- if done.returncode == 0 and args.json:
1682
+ if rc == 0 and args.json:
1009
1683
  json.dump(dict(queued=False, prepared=True), sys.stdout)
1010
1684
  sys.stdout.write('\n')
1011
- elif done.returncode == 0:
1685
+ elif rc == 0:
1012
1686
  print(f'no run is live: task {args.task} is prepared with your answer; the next `forge-parallel.sh run {plan}` '
1013
1687
  'dispatches it')
1014
- return done.returncode
1688
+ return rc
1015
1689
 
1016
1690
 
1017
1691
  def cmd_retry(args):
@@ -1019,7 +1693,7 @@ def cmd_retry(args):
1019
1693
  require_task(rows, args.task)
1020
1694
  answer = answer_of(args)
1021
1695
  if answer is not None:
1022
- refuse_task(plan, args.task, pin=True)
1696
+ refuse_task(plan, args.task)
1023
1697
  status = task_status(plan, args.task, strict=True)
1024
1698
  if status != 'NEEDS_INPUT':
1025
1699
  raise Refused(f'task {args.task} is {status}, not waiting for an answer: --answer only answers a NEEDS_INPUT task')
@@ -1029,8 +1703,10 @@ def cmd_retry(args):
1029
1703
  dwarf = None
1030
1704
  if args.dwarf is not None:
1031
1705
  dwarf = clean_spec(args.dwarf, '--dwarf')
1032
- refuse_task(plan, args.task, pin=True) # before the doctor: MERGED and Fractal need no model check
1706
+ refuse_task(plan, args.task) # before the doctor: a MERGED task needs no model check
1033
1707
  decision = decision_of(plan, args, dwarf)
1708
+ if decision and decision[0] and SPLIT.fullmatch(decision[0]):
1709
+ return retry_split(args, plan, decision)
1034
1710
  if dwarf:
1035
1711
  doctor(dwarf)
1036
1712
  return queue(args, plan, 'retry', args.task, dwarf, decision)
@@ -1085,8 +1761,9 @@ def cmd_show(args):
1085
1761
  return 0
1086
1762
  cell = lambda v: '-' if v is None else str(v) # noqa: E731
1087
1763
  run = controls['run']
1088
- print(f"{plan} run {cell(controls['run_id'])} live {'yes' if controls['live'] else 'no'}"
1089
- f" fractal {'yes' if controls['fractal'] else 'no'}")
1764
+ print(f"{plan} run {cell(controls['run_id'])} live {'yes' if controls['live'] else 'no'}")
1765
+ if controls['removed']:
1766
+ print(f'read-only: {forge_legacy.removed_note()}')
1090
1767
  print(' ' + ' '.join(f"{k.replace('_', '-')} {cell(v)}" + (' (default)' if k == 'qa_threshold' and run['qa_threshold_source'] == 'default' else '')
1091
1768
  for k, v in run.items() if k not in ('infra_paused', 'qa_threshold_source')))
1092
1769
  now = time.time()
@@ -1116,6 +1793,17 @@ def cmd_show(args):
1116
1793
  widths = [max(len(r[i]) for r in table) for i in range(len(columns))]
1117
1794
  for r in table:
1118
1795
  print(' ' + ' '.join(c.ljust(w) for c, w in zip(r, widths)).rstrip())
1796
+ tree = controls.get('decomposition')
1797
+ if tree:
1798
+ print(' decomposition limits: ' + forge_decompose.describe(tree['limits']) + (' (frozen)' if tree['limits'].get('frozen') else ''))
1799
+ drawn = forge_decompose.render(plan, split_only=True)
1800
+ if drawn:
1801
+ print('subtasks (each split task has a plan of its own; control a subtask there):')
1802
+ for line in drawn.splitlines():
1803
+ print(' ' + line)
1804
+ for node in tree['nodes']:
1805
+ if node['children']:
1806
+ print(f" {node['id']}: {forge_decompose.sub_dir(node['plan'], node['task'])}")
1119
1807
  if controls['log']:
1120
1808
  print('changes, newest first:')
1121
1809
  for e in controls['log']:
@@ -1131,7 +1819,7 @@ def cmd_show(args):
1131
1819
  def parser():
1132
1820
  top = argparse.ArgumentParser(prog='forge control', description="Show and change a plan's live controls.")
1133
1821
  sub = top.add_subparsers(dest='command', required=True,
1134
- metavar='{show,set,pin,unpin,retry,accept,add,drain,resume,stop}')
1822
+ metavar='{show,set,pin,unpin,retry,steer,accept,add,drain,resume,stop}')
1135
1823
 
1136
1824
  def common(p, mutator=True):
1137
1825
  p.add_argument('plan', metavar='PLAN_DIR', help="the plan dir (the one with tasks.tsv)")
@@ -1145,7 +1833,11 @@ def parser():
1145
1833
  p = sub.add_parser('set', help='change a control', description='Keys: ' + ', '.join(KEYS) + '. '
1146
1834
  'retry-budget, infra-retries and max-parallel change only while a run is live. '
1147
1835
  'qa-threshold, retry-budget and summaries also take --task (value inherit drops the override; at run level, default drops the file and none means P3). '
1148
- 'summaries on|off turns generated task summaries on or off; on for a finished run also starts them.')
1836
+ 'summaries on|off turns generated task summaries on or off; on for a finished run also starts them. '
1837
+ 'summaries-model SPEC changes the model they use (default drops the plan\'s own: before planning it '
1838
+ 'follows forge config set summaries.model, once planned it leaves none, so it is refused while '
1839
+ 'summaries are on; summaries on is refused while the plan has no model). '
1840
+ 'brief-model SPEC changes the model of brief change proposals the same way.')
1149
1841
  common(p)
1150
1842
  p.add_argument('key', choices=list(KEYS))
1151
1843
  p.add_argument('value')
@@ -1157,6 +1849,12 @@ def parser():
1157
1849
  p.add_argument('task')
1158
1850
  p.add_argument('spec', help='a dwarf spec, e.g. sol:high:codex')
1159
1851
  p.set_defaults(func=cmd_pin)
1852
+ p = sub.add_parser('models', help='the dwarf and/or qa model of every not-started task of one difficulty tier')
1853
+ common(p)
1854
+ p.add_argument('tier', help='low, medium or high')
1855
+ p.add_argument('--dwarf', metavar='SPECS', help='one spec or a comma-separated pool (handed out in row order)')
1856
+ p.add_argument('--qa', metavar='SPECS', help='one spec or a comma-separated pool')
1857
+ p.set_defaults(func=cmd_models)
1160
1858
  p = sub.add_parser('unpin', help='drop a task pin')
1161
1859
  common(p)
1162
1860
  p.add_argument('task')
@@ -1165,12 +1863,41 @@ def parser():
1165
1863
  common(p)
1166
1864
  p.add_argument('task')
1167
1865
  p.add_argument('--dwarf', metavar='SPEC', help='the implementer for this retry (an explicit escalation)')
1168
- p.add_argument('--decide', metavar='CHOICE', help='decide a NEEDS_DECISION task: retry=N (1 to 20) or threshold=P0..P3')
1866
+ p.add_argument('--decide', metavar='CHOICE', help='decide a NEEDS_DECISION task: retry=N (1 to 20) or threshold=P0..P3; '
1867
+ 'or split | split=fresh, which splits any task that has not passed into subtasks')
1868
+ p.add_argument('--subtasks', metavar='FILE', help='with --decide split: the subtasks, a forge-plan block or its JSON')
1169
1869
  p.add_argument('--answer', metavar='TEXT', help="answer a NEEDS_INPUT task's question (1 to 8000 characters)")
1170
1870
  p.add_argument('--answer-file', metavar='FILE', help='the answer, read from FILE (- for stdin)')
1171
1871
  p.add_argument('--reason', metavar='TEXT', help='why (a decision needs it)')
1172
1872
  p.add_argument('--approved', action='store_true', help='the decision is the user\'s (a decision needs it)')
1173
1873
  p.set_defaults(func=cmd_retry)
1874
+ p = sub.add_parser('steer', help="queue a message for a task's next implementer attempt (it starts nothing)")
1875
+ common(p)
1876
+ p.add_argument('task')
1877
+ p.add_argument('text', nargs='?', help=f'the message (1 to {STEER_MAX} characters)')
1878
+ p.add_argument('--file', metavar='FILE', help='the message, read from FILE (- for stdin)')
1879
+ p.add_argument('--now', action='store_true', help="send it to the task's running implementer instead, at its "
1880
+ 'next tool call (claude and openclaude implementers only; refused when none runs live)')
1881
+ p.set_defaults(func=cmd_steer)
1882
+ p = sub.add_parser('_steer-take') # forge-parallel.sh only
1883
+ p.add_argument('plan')
1884
+ p.add_argument('task')
1885
+ p.add_argument('attempt')
1886
+ p.set_defaults(func=cmd_steer_take)
1887
+ p = sub.add_parser('_steer-feed') # forge-dispatch.sh only
1888
+ p.add_argument('plan')
1889
+ p.add_argument('task')
1890
+ p.add_argument('attempt')
1891
+ p.add_argument('prompt_file')
1892
+ p.add_argument('log')
1893
+ p.add_argument('--harness', default='claude')
1894
+ p.add_argument('--stop', metavar='FILE', help='stop once this file exists')
1895
+ p.add_argument('--pidfile', metavar='FILE', help='write this process id here')
1896
+ p.set_defaults(func=cmd_steer_feed)
1897
+ p = sub.add_parser('_steer-close') # forge-dispatch.sh only
1898
+ p.add_argument('plan')
1899
+ p.add_argument('task')
1900
+ p.set_defaults(func=cmd_steer_close)
1174
1901
  p = sub.add_parser('accept', help="queue an accept of a FAIL or NEEDS_DECISION task into the live run: "
1175
1902
  "its findings become known issues and it merges (the user's decision only)")
1176
1903
  common(p)
@@ -1198,6 +1925,9 @@ def parser():
1198
1925
  def main(argv=None) -> int:
1199
1926
  args = parser().parse_args(argv)
1200
1927
  try:
1928
+ # A plan made with Fractal, which forge removed, can be shown and never changed: nothing runs it again.
1929
+ if args.func is not cmd_show and forge_legacy.was_fractal(args.plan):
1930
+ raise Refused(forge_legacy.refusal('this plan'))
1201
1931
  return args.func(args)
1202
1932
  except Invalid as error:
1203
1933
  print(f'forge control: {error}', file=sys.stderr)