@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.
- package/CHANGELOG.md +61 -0
- package/README.md +19 -12
- package/SKILL.md +137 -216
- package/VERSION +1 -1
- package/docs/README.md +2 -3
- package/docs/add-ons.md +5 -3
- package/docs/artifacts.md +17 -2
- package/docs/commands.md +85 -63
- package/docs/decomposed-runs.md +195 -21
- package/docs/development.md +11 -9
- package/docs/forge-ui.md +33 -4
- package/docs/install.md +37 -5
- package/docs/memory.md +6 -1
- package/docs/models.md +36 -10
- package/docs/reviews.md +44 -25
- package/docs/safety.md +27 -2
- package/docs/troubleshooting.md +7 -10
- package/forge +25 -4
- package/package.json +2 -1
- package/references/dataset.md +10 -9
- package/references/decompose-integration.md +337 -0
- package/references/decompose-opt-in.md +527 -0
- package/references/decompose-recovery.md +569 -0
- package/references/decompose-review.md +256 -0
- package/references/decompose.md +99 -1606
- package/references/findings.md +68 -0
- package/references/harnesses.md +7 -12
- package/references/memory.md +13 -2
- package/references/planning.md +48 -18
- package/references/ripwire.md +38 -13
- package/references/runtime.md +22 -33
- package/references/setup.md +90 -0
- package/references/solo.md +13 -42
- package/references/ui.md +12 -5
- package/registry.tsv +40 -22
- package/scripts/forge-artifact.sh +143 -12
- package/scripts/forge-compare.py +5 -15
- package/scripts/forge-config.py +14 -1
- package/scripts/forge-contract.py +216 -53
- package/scripts/forge-control.py +777 -54
- package/scripts/forge-dispatch.sh +95 -12
- package/scripts/forge-du.py +13 -3
- package/scripts/forge-handoff.py +221 -39
- package/scripts/forge-install-ripwire.sh +100 -24
- package/scripts/forge-install.sh +18 -32
- package/scripts/forge-issues.py +6 -4
- package/scripts/forge-jev-options.sh +3 -5
- package/scripts/forge-lib-adopt.sh +169 -5
- package/scripts/forge-lib-attribute.sh +10 -3
- package/scripts/forge-lib-decompose.sh +454 -0
- package/scripts/forge-lib-env.sh +21 -0
- package/scripts/forge-lib-group.sh +4 -1
- package/scripts/forge-lib-plans.sh +30 -18
- package/scripts/forge-lib-review.sh +28 -8
- package/scripts/forge-lib-task.sh +225 -56
- package/scripts/forge-lib-verify.sh +59 -10
- package/scripts/forge-memory.sh +81 -4
- package/scripts/forge-metrics.sh +4 -2
- package/scripts/forge-parallel-options.sh +23 -4
- package/scripts/forge-parallel.sh +447 -175
- package/scripts/forge-plan-check.py +71 -8
- package/scripts/forge-planner.py +303 -17
- package/scripts/forge-pr.py +9 -1
- package/scripts/forge-prompt.py +2 -2
- package/scripts/forge-review-links.py +248 -0
- package/scripts/forge-ripwire.py +234 -16
- package/scripts/forge-route.py +19 -27
- package/scripts/forge-runs-rm.py +92 -21
- package/scripts/forge-runs.py +46 -5
- package/scripts/forge-runtime.py +37 -12
- package/scripts/forge-schedule.py +124 -33
- package/scripts/forge-setup-stale.py +236 -0
- package/scripts/forge-setup.py +804 -0
- package/scripts/forge-shadow.py +2 -20
- package/scripts/forge-solo-lock.py +46 -0
- package/scripts/forge-solo.sh +33 -56
- package/scripts/forge-sweep.py +2 -1
- package/scripts/forge-ui.py +8 -1
- package/scripts/forge-update.sh +2 -2
- package/scripts/forge-verify.py +16 -1
- package/scripts/forge-version.py +13 -1
- package/scripts/forge-watch.py +7 -2
- package/scripts/forge_dataset/__init__.py +1 -1
- package/scripts/forge_dataset/capture.py +0 -34
- package/scripts/forge_dataset/checks.py +0 -1
- package/scripts/forge_dataset/cli.py +5 -1
- package/scripts/forge_dataset/export.py +28 -6
- package/scripts/forge_dataset/facts.py +1 -2
- package/scripts/forge_dataset/forecast.py +1 -1
- package/scripts/forge_dataset/harvest.py +107 -7
- package/scripts/forge_dataset/importer.py +3 -2
- package/scripts/forge_dataset/pairs.py +3 -3
- package/scripts/forge_dataset/reviewers.py +4 -3
- package/scripts/forge_dataset/routing.py +6 -3
- package/scripts/forge_dataset/tiers.py +1 -1
- package/scripts/forge_decide/__init__.py +1 -1
- package/scripts/forge_decide/profiles.py +11 -14
- package/scripts/forge_decompose.py +987 -0
- package/scripts/forge_groups/review.py +6 -1
- package/scripts/forge_jev/__init__.py +1 -1
- package/scripts/forge_jev/cli.py +10 -1
- package/scripts/forge_jev/gates.py +10 -1
- package/scripts/forge_jev/verify.py +10 -2
- package/scripts/forge_legacy.py +86 -0
- package/scripts/forge_memory_home.py +57 -0
- package/scripts/forge_models.py +151 -0
- package/scripts/forge_prefs.py +138 -0
- package/scripts/forge_side/__init__.py +10 -0
- package/scripts/forge_storage.py +28 -15
- package/ui/README.md +22 -10
- package/ui/docs/api.md +121 -99
- package/ui/forge_ui/control.py +46 -14
- package/ui/forge_ui/export.py +0 -10
- package/ui/forge_ui/models.py +15 -2
- package/ui/forge_ui/projects.py +4 -1
- package/ui/forge_ui/reader.py +456 -59
- package/ui/forge_ui/server.py +0 -10
- package/ui/forge_ui/static/app.js +28 -9
- package/ui/forge_ui/static/checksview.js +12 -3
- package/ui/forge_ui/static/controls.js +147 -11
- package/ui/forge_ui/static/convo.js +5 -2
- package/ui/forge_ui/static/diffview.js +4 -5
- package/ui/forge_ui/static/panel.js +180 -77
- package/ui/forge_ui/static/projectsview.js +16 -2
- package/ui/forge_ui/static/runmodel.js +18 -4
- package/ui/forge_ui/static/scene3d.js +29 -29
- package/ui/forge_ui/static/settings.js +1 -1
- package/ui/forge_ui/static/storageview.js +2 -2
- package/ui/forge_ui/static/style.css +23 -6
- package/ui/forge_ui/static/worktreesview.js +8 -4
- package/ui/forge_ui/transcripts.py +6 -0
- package/ui/forge_ui/worktrees.py +13 -1
- package/docs/fractal.md +0 -181
- package/references/fractal-dashboard.md +0 -21
- package/references/fractal.md +0 -307
- package/scripts/forge-fractal-dispatch.sh +0 -4
- package/scripts/forge-fractal-options.sh +0 -54
- package/scripts/forge-fractal.py +0 -6
- package/scripts/forge-install-fractal.sh +0 -4
- package/scripts/forge_fractal/__init__.py +0 -88
- package/scripts/forge_fractal/bridge.py +0 -46
- package/scripts/forge_fractal/cli.py +0 -224
- package/scripts/forge_fractal/dashboard.css +0 -138
- package/scripts/forge_fractal/dashboard.html +0 -41
- package/scripts/forge_fractal/dashboard.js +0 -687
- package/scripts/forge_fractal/decomposition.py +0 -262
- package/scripts/forge_fractal/execution.py +0 -659
- package/scripts/forge_fractal/inspection.py +0 -261
- package/scripts/forge_fractal/install.py +0 -158
- package/scripts/forge_fractal/invocation.py +0 -95
- package/scripts/forge_fractal/pipeline.py +0 -125
- package/scripts/forge_fractal/selection.py +0 -180
- package/ui/forge_ui/fractal.py +0 -582
|
@@ -0,0 +1,987 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Recursive decomposition (#153): one node model for every level, the limits a plan freezes,
|
|
3
|
+
and the split of a task into a sub-plan.
|
|
4
|
+
|
|
5
|
+
A task of a plan may be split into subtasks. The subtasks are an ordinary plan, the task's
|
|
6
|
+
sub-plan, kept under the task: `<plan>/tasks/<id>/sub/`. It runs on forge's own scheduler,
|
|
7
|
+
worktrees, routing and QA, merges into the task's branch, and the task is then reviewed on its
|
|
8
|
+
cumulative diff. A subtask can split again, down to the depth the plan allows.
|
|
9
|
+
|
|
10
|
+
Every plan directory, a sub-plan included, keeps the decisions about its own tasks in
|
|
11
|
+
`decomposition.json`. One record per task (the node):
|
|
12
|
+
|
|
13
|
+
id, parent, goal, files, deps, difficulty what the node is
|
|
14
|
+
decision atomic | split | bounded
|
|
15
|
+
reason, by, at why, who decided (planner, user, auto, default), when
|
|
16
|
+
limits_used the node's level, the subtasks in the tree and the
|
|
17
|
+
children proposed when it was decided
|
|
18
|
+
|
|
19
|
+
`atomic` runs as one task. `split` has a sub-plan. `bounded` would have split but a limit said
|
|
20
|
+
no, and it runs as one task. The limits (depth, children per split, subtasks in the whole tree)
|
|
21
|
+
live in the root plan's file: `plan` sets them, the table shows them, and the first `run`
|
|
22
|
+
freezes them.
|
|
23
|
+
|
|
24
|
+
Command line, for the shell runners:
|
|
25
|
+
forge_decompose.py limits <plan> [--depth N] [--children N] [--nodes N] set (root plan, not frozen) and print
|
|
26
|
+
forge_decompose.py freeze <plan> freeze the limits (the first run)
|
|
27
|
+
forge_decompose.py split <plan> <task> --proposal FILE --reason TEXT [--by B] [--start keep|fresh]
|
|
28
|
+
0 the sub-plan was created | 3 refused | 4 bounded | 5 kept whole
|
|
29
|
+
forge_decompose.py record <plan> <task> --decision D --reason TEXT [--by B]
|
|
30
|
+
forge_decompose.py settle <plan> [--by B] apply the plan's stored proposals, record the rest atomic
|
|
31
|
+
forge_decompose.py tree <plan> [--json] the nodes of the plan, through every level
|
|
32
|
+
forge_decompose.py state <plan> <task> none | open | merged
|
|
33
|
+
forge_decompose.py waiting <plan> <task> one line per subtask that has not merged
|
|
34
|
+
forge_decompose.py root <plan> the root plan of a sub-plan (itself for a root)
|
|
35
|
+
forge_decompose.py subs <plan> every sub-plan directory under the plan, parents first
|
|
36
|
+
forge_decompose.py later <plan> [--json] the stages that follow this plan (goal -> plans)
|
|
37
|
+
forge_decompose.py next <plan> [--dir NEW] make the directory of the next stage's plan: its request,
|
|
38
|
+
its goal and its place in the chain; prints the directory
|
|
39
|
+
forge_decompose.py slot --root DIR --cap N --while-pid PID --ready FILE hold one slot of the tree
|
|
40
|
+
"""
|
|
41
|
+
from __future__ import annotations
|
|
42
|
+
|
|
43
|
+
import argparse
|
|
44
|
+
import json
|
|
45
|
+
import os
|
|
46
|
+
import re
|
|
47
|
+
import shutil
|
|
48
|
+
import sys
|
|
49
|
+
import time
|
|
50
|
+
from pathlib import Path
|
|
51
|
+
|
|
52
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
53
|
+
import forge_legacy # noqa: E402
|
|
54
|
+
|
|
55
|
+
FILE = 'decomposition.json'
|
|
56
|
+
SUB = 'sub' # <plan>/tasks/<id>/sub: the task's sub-plan
|
|
57
|
+
PARENT = 'parent.json' # in a sub-plan: the task it belongs to, and how the split started
|
|
58
|
+
MERGED = 'sub.merged' # <plan>/tasks/<id>/sub.merged: the sub-plan's work is on the task's branch
|
|
59
|
+
WAITING = 'sub.waiting' # why the task waits for its subtasks, for the run summary
|
|
60
|
+
PROPOSAL = 'split.proposal.json' # <plan>/tasks/<id>/: subtasks a planner proposed, applied by settle
|
|
61
|
+
REASON = 'split.reason' # <plan>/tasks/<id>/: why a planner kept the task whole, one line
|
|
62
|
+
SLOTS = 'tree.slots' # in the root plan: one lock file per dispatch the tree may run at once
|
|
63
|
+
LATER = 'later.json' # the stages a planner proposed after this plan: {"later": [{title, goal}, ...]}
|
|
64
|
+
CHAIN = 'chain.json' # in a plan `next` made: {first, stage, previous, remaining}
|
|
65
|
+
VERSION = 1
|
|
66
|
+
|
|
67
|
+
DEFAULT_LIMITS = {'depth': 2, 'children': 6, 'nodes': 24}
|
|
68
|
+
# What a limit may be set to: 0 depth or 0 nodes turns splitting off; a split has at least two children.
|
|
69
|
+
LIMIT_RANGE = {'depth': (0, 6), 'children': (2, 20), 'nodes': (0, 500)}
|
|
70
|
+
LIMIT_WORDS = {'depth': 'levels of subtasks', 'children': 'subtasks per split', 'nodes': 'subtasks in the whole run'}
|
|
71
|
+
DECISIONS = ('atomic', 'split', 'bounded')
|
|
72
|
+
DECIDERS = ('planner', 'user', 'auto', 'default')
|
|
73
|
+
STARTS = ('keep', 'fresh')
|
|
74
|
+
DIFFICULTIES = ('low', 'medium', 'high')
|
|
75
|
+
ID_RE = re.compile(r'[a-z0-9][a-z0-9-]{0,39}')
|
|
76
|
+
TSV_HEADER = '# id\tdeps\tdifficulty\tfiles\tdwarf\tqa\ttitle'
|
|
77
|
+
MAX_RUN_ID = 128 # a nested run id names branches and directories (forge runs rm takes no longer one)
|
|
78
|
+
# A task in one of these has nothing left to split, or is being worked on right now.
|
|
79
|
+
NOT_SPLITTABLE = ('MERGED', 'RUNNING', 'PASS', 'IMPLEMENTED')
|
|
80
|
+
# Plan files a sub-plan takes from its parent: the cost-bearing choices made for the plan apply to
|
|
81
|
+
# its subtasks too. Not verification (the parent's review and the root's verification judge the
|
|
82
|
+
# result), not groups, not the brief or the summaries, not `after`.
|
|
83
|
+
OPTION_FILES = ('no_ripwire', 'no_memory', 'yolo_dwarf', 'yolo_qa', 'reviewer_session', 'implementer_session',
|
|
84
|
+
'fast', 'pre_review_tests', 'pre_review_parallel', 'fail_first', 'qa_threshold', 'qa_test_minutes', 'timeout',
|
|
85
|
+
'setup_cmd', 'escalate_after', 'retry_per_model', 'max_attempts', 'converge_window',
|
|
86
|
+
'infra_fallback', 'infra_backoff', forge_legacy.POOLS, 'qa-routing.json', 'jev-selection.json',
|
|
87
|
+
'profile.json', 'repo.identity', 'planner', 'split_planner', 'auto_split')
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class Invalid(Exception):
|
|
91
|
+
"""A split that cannot be made. Nothing was written."""
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class Bounded(Exception):
|
|
95
|
+
"""A split a limit refuses. `limit` names it."""
|
|
96
|
+
|
|
97
|
+
def __init__(self, limit: str, message: str):
|
|
98
|
+
super().__init__(message)
|
|
99
|
+
self.limit = limit
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class Atomic(Exception):
|
|
103
|
+
"""A proposal of fewer than two subtasks: the node stays whole."""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# --- files ---------------------------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
def _write_atomic(path: Path, text: str) -> None:
|
|
109
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
110
|
+
tmp = path.with_name('%s.tmp-%d' % (path.name, os.getpid()))
|
|
111
|
+
try:
|
|
112
|
+
tmp.write_text(text, encoding='utf-8')
|
|
113
|
+
os.replace(tmp, path)
|
|
114
|
+
finally:
|
|
115
|
+
try:
|
|
116
|
+
tmp.unlink()
|
|
117
|
+
except OSError:
|
|
118
|
+
pass
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _read_json(path: Path):
|
|
122
|
+
try:
|
|
123
|
+
return json.loads(path.read_text(encoding='utf-8'))
|
|
124
|
+
except (OSError, ValueError):
|
|
125
|
+
return None
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _first_line(path: Path) -> str:
|
|
129
|
+
try:
|
|
130
|
+
with open(path, encoding='utf-8', errors='replace') as handle:
|
|
131
|
+
return handle.readline().strip()
|
|
132
|
+
except OSError:
|
|
133
|
+
return ''
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def load(plan) -> dict:
|
|
137
|
+
"""The plan's decomposition.json, always a well-formed dict (an unreadable file reads as empty)."""
|
|
138
|
+
data = _read_json(Path(plan) / FILE)
|
|
139
|
+
if not isinstance(data, dict):
|
|
140
|
+
data = {}
|
|
141
|
+
nodes = data.get('nodes')
|
|
142
|
+
data['nodes'] = {k: v for k, v in nodes.items() if isinstance(v, dict)} if isinstance(nodes, dict) else {}
|
|
143
|
+
data['version'] = VERSION
|
|
144
|
+
return data
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def save(plan, data: dict) -> None:
|
|
148
|
+
_write_atomic(Path(plan) / FILE, json.dumps(data, indent=1, sort_keys=True) + '\n')
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def read_rows(plan) -> list:
|
|
152
|
+
"""tasks.tsv as dicts, in file order. A missing or unreadable table is no rows."""
|
|
153
|
+
rows = []
|
|
154
|
+
try:
|
|
155
|
+
lines = (Path(plan) / 'tasks.tsv').read_text(encoding='utf-8').splitlines()
|
|
156
|
+
except (OSError, UnicodeDecodeError):
|
|
157
|
+
return rows
|
|
158
|
+
for line in lines:
|
|
159
|
+
if not line.strip() or line.startswith('#'):
|
|
160
|
+
continue
|
|
161
|
+
cells = (line.split('\t') + [''] * 7)[:7]
|
|
162
|
+
rows.append(dict(id=cells[0], deps=[d for d in cells[1].split(',') if d and d != '-'], difficulty=cells[2],
|
|
163
|
+
files=[f for f in cells[3].split(',') if f], dwarf=cells[4], qa=cells[5], title=cells[6]))
|
|
164
|
+
return rows
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def row_of(plan, task: str):
|
|
168
|
+
for row in read_rows(plan):
|
|
169
|
+
if row['id'] == task:
|
|
170
|
+
return row
|
|
171
|
+
return None
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def status_of(plan, task: str) -> str:
|
|
175
|
+
base = Path(plan) / 'tasks' / task
|
|
176
|
+
if (base / 'merged').exists():
|
|
177
|
+
return 'MERGED'
|
|
178
|
+
return _first_line(base / 'status') or 'PENDING'
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def run_id_of(plan) -> str:
|
|
182
|
+
plan = Path(plan)
|
|
183
|
+
text = _first_line(plan / 'run_id')
|
|
184
|
+
if text:
|
|
185
|
+
return text
|
|
186
|
+
name = plan.resolve().name
|
|
187
|
+
return name[len('forge-'):] if name.startswith('forge-') else name
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
# --- the tree ------------------------------------------------------------------------------
|
|
191
|
+
|
|
192
|
+
def sub_dir(plan, task: str) -> Path:
|
|
193
|
+
return Path(plan) / 'tasks' / task / SUB
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def is_split(plan, task: str) -> bool:
|
|
197
|
+
"""The task has a sub-plan."""
|
|
198
|
+
return (sub_dir(plan, task) / 'tasks.tsv').is_file()
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def is_open(plan, task: str) -> bool:
|
|
202
|
+
"""The task has a sub-plan whose work is not on the task's branch yet: the next entry runs the
|
|
203
|
+
sub-plan, not an implementer."""
|
|
204
|
+
return is_split(plan, task) and not (Path(plan) / 'tasks' / task / MERGED).exists()
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def parent_link(plan):
|
|
208
|
+
"""(parent plan, task) of a sub-plan, None for a root plan. The place says it: a sub-plan is
|
|
209
|
+
<parent>/tasks/<task>/sub and holds parent.json, so a moved plan directory keeps its tree."""
|
|
210
|
+
path = Path(plan).resolve()
|
|
211
|
+
if path.name != SUB or path.parent.parent.name != 'tasks' or not (path / PARENT).is_file():
|
|
212
|
+
return None
|
|
213
|
+
return path.parent.parent.parent, path.parent.name
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def ancestors(plan) -> list:
|
|
217
|
+
"""[(plan, task), ...] from the nearest parent up to the root plan. Empty for a root plan."""
|
|
218
|
+
found = []
|
|
219
|
+
link = parent_link(plan)
|
|
220
|
+
while link is not None and len(found) < 64:
|
|
221
|
+
found.append(link)
|
|
222
|
+
link = parent_link(link[0])
|
|
223
|
+
return found
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def root_of(plan) -> Path:
|
|
227
|
+
chain = ancestors(plan)
|
|
228
|
+
return chain[-1][0] if chain else Path(plan).resolve()
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def level_of(plan) -> int:
|
|
232
|
+
"""How many splits lie above this plan's tasks: 0 for the tasks of a root plan."""
|
|
233
|
+
return len(ancestors(plan))
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def node_path(plan, task: str) -> str:
|
|
237
|
+
"""The node's id in the tree: the task ids from the root plan down, joined by '/'."""
|
|
238
|
+
return '/'.join([t for _plan, t in reversed(ancestors(plan))] + [task])
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def count_subnodes(root) -> int:
|
|
242
|
+
"""Subtasks in the whole tree under a root plan: every row of every sub-plan."""
|
|
243
|
+
total = 0
|
|
244
|
+
stack = [Path(root)]
|
|
245
|
+
while stack:
|
|
246
|
+
plan = stack.pop()
|
|
247
|
+
for row in read_rows(plan):
|
|
248
|
+
sub = sub_dir(plan, row['id'])
|
|
249
|
+
if (sub / 'tasks.tsv').is_file():
|
|
250
|
+
total += len(read_rows(sub))
|
|
251
|
+
stack.append(sub)
|
|
252
|
+
return total
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
# --- limits --------------------------------------------------------------------------------
|
|
256
|
+
|
|
257
|
+
def limits(plan) -> dict:
|
|
258
|
+
"""The limits of the tree this plan is in: the root plan's, each default where it has none."""
|
|
259
|
+
stored = load(root_of(plan)).get('limits')
|
|
260
|
+
out = dict(DEFAULT_LIMITS)
|
|
261
|
+
if isinstance(stored, dict):
|
|
262
|
+
for key in DEFAULT_LIMITS:
|
|
263
|
+
value = stored.get(key)
|
|
264
|
+
low, high = LIMIT_RANGE[key]
|
|
265
|
+
if type(value) is int and low <= value <= high:
|
|
266
|
+
out[key] = value
|
|
267
|
+
return out
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def is_frozen(plan) -> bool:
|
|
271
|
+
return load(root_of(plan)).get('frozen') is True
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def set_limits(plan, **values) -> dict:
|
|
275
|
+
"""Set limits on a root plan before its first run. A value equal to the current one is always
|
|
276
|
+
accepted, so a re-plan with the same flags is not an error."""
|
|
277
|
+
plan = Path(plan)
|
|
278
|
+
changes = {k: v for k, v in values.items() if v is not None}
|
|
279
|
+
if parent_link(plan) is not None:
|
|
280
|
+
if changes:
|
|
281
|
+
raise Invalid('the limits belong to the root plan %s; a sub-plan has none of its own' % root_of(plan))
|
|
282
|
+
return limits(plan)
|
|
283
|
+
current = limits(plan)
|
|
284
|
+
for key, value in changes.items():
|
|
285
|
+
low, high = LIMIT_RANGE[key]
|
|
286
|
+
if type(value) is not int or not low <= value <= high:
|
|
287
|
+
raise Invalid('--split-%s takes a whole number from %d to %d' % (key, low, high))
|
|
288
|
+
wanted = {k: v for k, v in changes.items() if current[k] != v}
|
|
289
|
+
data = load(plan)
|
|
290
|
+
if wanted and data.get('frozen') is True:
|
|
291
|
+
raise Invalid('the decomposition limits were frozen when this plan first ran (%s); they do not change '
|
|
292
|
+
'mid-run. A new plan can have other limits' % describe(current))
|
|
293
|
+
current.update(wanted)
|
|
294
|
+
if wanted or not isinstance(data.get('limits'), dict):
|
|
295
|
+
data['limits'] = current
|
|
296
|
+
save(plan, data)
|
|
297
|
+
return current
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def freeze(plan) -> dict:
|
|
301
|
+
"""The first run freezes the limits. Idempotent; a sub-plan freezes nothing (its root did)."""
|
|
302
|
+
plan = Path(plan)
|
|
303
|
+
if parent_link(plan) is not None:
|
|
304
|
+
return limits(plan)
|
|
305
|
+
data = load(plan)
|
|
306
|
+
current = limits(plan)
|
|
307
|
+
if data.get('frozen') is not True or data.get('limits') != current:
|
|
308
|
+
data['limits'] = current
|
|
309
|
+
data['frozen'] = True
|
|
310
|
+
data.setdefault('frozen_at', time.time())
|
|
311
|
+
save(plan, data)
|
|
312
|
+
return current
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def describe(values: dict) -> str:
|
|
316
|
+
if values['depth'] == 0 or values['nodes'] == 0:
|
|
317
|
+
return 'no task is split into subtasks (depth %d, %d subtasks in all)' % (values['depth'], values['nodes'])
|
|
318
|
+
return ('depth %d, at most %d subtasks per split, %d subtasks in the whole run'
|
|
319
|
+
% (values['depth'], values['children'], values['nodes']))
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
# --- decisions -----------------------------------------------------------------------------
|
|
323
|
+
|
|
324
|
+
def record(plan, task: str, decision: str, reason: str, by: str = 'default', **extra) -> dict:
|
|
325
|
+
"""Write the node's decision. A `default` record (nobody decided) never replaces a decision
|
|
326
|
+
somebody made, and never replaces `split` or `bounded`."""
|
|
327
|
+
if decision not in DECISIONS:
|
|
328
|
+
raise Invalid('decision %r is not atomic, split or bounded' % decision)
|
|
329
|
+
if by not in DECIDERS:
|
|
330
|
+
raise Invalid('by %r is not planner, user, auto or default' % by)
|
|
331
|
+
plan = Path(plan)
|
|
332
|
+
data = load(plan)
|
|
333
|
+
old = data['nodes'].get(task)
|
|
334
|
+
if old and by == 'default' and (old.get('by') != 'default' or old.get('decision') != 'atomic'):
|
|
335
|
+
return old
|
|
336
|
+
row = row_of(plan, task) or {}
|
|
337
|
+
link = parent_link(plan)
|
|
338
|
+
node = dict(id=node_path(plan, task), task=task,
|
|
339
|
+
parent=node_path(link[0], link[1]) if link else None,
|
|
340
|
+
goal=row.get('title', ''), files=row.get('files', []), deps=row.get('deps', []),
|
|
341
|
+
difficulty=row.get('difficulty', ''), decision=decision,
|
|
342
|
+
reason=' '.join(str(reason).split())[:2000], by=by, at=time.time(),
|
|
343
|
+
limits_used=dict(depth=level_of(plan), nodes=count_subnodes(root_of(plan)),
|
|
344
|
+
children=extra.pop('children', None), limit=extra.pop('limit', None)))
|
|
345
|
+
node.update(extra)
|
|
346
|
+
data['nodes'][task] = node
|
|
347
|
+
save(plan, data)
|
|
348
|
+
return node
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def node_of(plan, task: str, data: dict = None) -> dict:
|
|
352
|
+
"""The node as recorded, or what an undecided task is: atomic, by default."""
|
|
353
|
+
data = load(plan) if data is None else data
|
|
354
|
+
node = data['nodes'].get(task)
|
|
355
|
+
if node:
|
|
356
|
+
return node
|
|
357
|
+
return dict(decision='split' if is_split(plan, task) else 'atomic', by='default',
|
|
358
|
+
reason='no split was proposed' if not is_split(plan, task) else '')
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
# --- validation ----------------------------------------------------------------------------
|
|
362
|
+
|
|
363
|
+
def _norm(path: str) -> str:
|
|
364
|
+
path = path.replace('\\', '/')
|
|
365
|
+
while path.startswith('./'):
|
|
366
|
+
path = path[2:]
|
|
367
|
+
return path.rstrip('/') or '.'
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def inside(path: str, owned: list) -> bool:
|
|
371
|
+
"""Whether a declared path lies inside what the parent declares: the same path, a path under a
|
|
372
|
+
declared directory, or anything when the parent declares `.` (the rule check_drift uses)."""
|
|
373
|
+
path = _norm(path)
|
|
374
|
+
for entry in owned:
|
|
375
|
+
entry = _norm(entry)
|
|
376
|
+
if entry == '.' or path == entry or path.startswith(entry + '/'):
|
|
377
|
+
return True
|
|
378
|
+
return False
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _check_children(children, parent_files: list) -> list:
|
|
382
|
+
if not isinstance(children, list) or not all(isinstance(c, dict) for c in children):
|
|
383
|
+
raise Invalid('the subtasks are not a list of task objects')
|
|
384
|
+
if len(children) < 2:
|
|
385
|
+
raise Atomic('a split needs at least two subtasks')
|
|
386
|
+
seen = set()
|
|
387
|
+
for child in children:
|
|
388
|
+
cid = child.get('id')
|
|
389
|
+
if not isinstance(cid, str) or not ID_RE.fullmatch(cid):
|
|
390
|
+
raise Invalid('subtask id %r does not match ^[a-z0-9][a-z0-9-]{0,39}$' % (cid,))
|
|
391
|
+
if cid in seen:
|
|
392
|
+
raise Invalid('subtask %s: duplicate id' % cid)
|
|
393
|
+
seen.add(cid)
|
|
394
|
+
if child.get('difficulty') not in DIFFICULTIES:
|
|
395
|
+
raise Invalid('subtask %s: difficulty %r is not low, medium or high' % (cid, child.get('difficulty')))
|
|
396
|
+
files = child.get('files')
|
|
397
|
+
if not isinstance(files, list) or not files or not all(isinstance(f, str) and f for f in files):
|
|
398
|
+
raise Invalid('subtask %s: files is not a non-empty list of paths' % cid)
|
|
399
|
+
for path in files:
|
|
400
|
+
if ',' in path or re.search(r'[\x00-\x1f\x7f]', path):
|
|
401
|
+
raise Invalid('subtask %s: file %r holds a comma, tab or control character' % (cid, path))
|
|
402
|
+
if path.startswith(('/', '\\')) or re.match(r'^[A-Za-z]:', path) or '..' in re.split(r'[\\/]', path):
|
|
403
|
+
raise Invalid('subtask %s: file %r is absolute or has a .. component' % (cid, path))
|
|
404
|
+
if not inside(path, parent_files):
|
|
405
|
+
raise Invalid('subtask %s: file %s is outside the files its parent declares (%s); a subtask '
|
|
406
|
+
'owns paths inside its parent\'s' % (cid, path, ', '.join(parent_files) or 'none'))
|
|
407
|
+
title = child.get('title')
|
|
408
|
+
if not isinstance(title, str) or not title.strip() or re.search(r'[\x00-\x1f\x7f]', title):
|
|
409
|
+
raise Invalid('subtask %s: title is not one non-empty line' % cid)
|
|
410
|
+
prompt = child.get('prompt')
|
|
411
|
+
if not isinstance(prompt, str) or not prompt.strip():
|
|
412
|
+
raise Invalid('subtask %s: prompt is empty' % cid)
|
|
413
|
+
deps = child.get('deps', [])
|
|
414
|
+
if not isinstance(deps, list) or not all(isinstance(d, str) for d in deps) or len(set(deps)) != len(deps):
|
|
415
|
+
raise Invalid('subtask %s: deps is not a list of distinct ids' % cid)
|
|
416
|
+
graph = {c['id']: list(c.get('deps', [])) for c in children}
|
|
417
|
+
for cid, deps in graph.items():
|
|
418
|
+
for dep in deps:
|
|
419
|
+
if dep not in graph:
|
|
420
|
+
raise Invalid('subtask %s: unknown dep %r (a subtask depends only on its siblings)' % (cid, dep))
|
|
421
|
+
state = {}
|
|
422
|
+
|
|
423
|
+
def visit(node, trail):
|
|
424
|
+
state[node] = 1
|
|
425
|
+
for nxt in graph[node]:
|
|
426
|
+
if state.get(nxt) == 1:
|
|
427
|
+
raise Invalid('dependency cycle among the subtasks: ' + ' -> '.join(trail + [nxt]))
|
|
428
|
+
if nxt not in state:
|
|
429
|
+
visit(nxt, trail + [nxt])
|
|
430
|
+
state[node] = 2
|
|
431
|
+
|
|
432
|
+
for cid in graph:
|
|
433
|
+
if cid not in state:
|
|
434
|
+
visit(cid, [cid])
|
|
435
|
+
return children
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def check_split(plan, task: str, children) -> None:
|
|
439
|
+
"""Raise Invalid (the split is wrong), Atomic (fewer than two subtasks) or Bounded (a limit
|
|
440
|
+
refuses it). Returns when the split may be made. Validity is judged before the limits, so a
|
|
441
|
+
wrong proposal is never recorded as bounded."""
|
|
442
|
+
plan = Path(plan)
|
|
443
|
+
row = row_of(plan, task)
|
|
444
|
+
if row is None:
|
|
445
|
+
raise Invalid('no task %r in %s' % (task, plan))
|
|
446
|
+
if row['dwarf'] == 'script':
|
|
447
|
+
raise Invalid('task %s is a script task: its command is one step, and it is not split' % task)
|
|
448
|
+
state = status_of(plan, task)
|
|
449
|
+
if state in NOT_SPLITTABLE:
|
|
450
|
+
raise Invalid('task %s is %s: only a task that has not passed and is not running can be split' % (task, state))
|
|
451
|
+
if is_split(plan, task):
|
|
452
|
+
raise Invalid('task %s is already split into subtasks (%s); its subtasks are kept, never made twice'
|
|
453
|
+
% (task, sub_dir(plan, task)))
|
|
454
|
+
_check_children(children, row['files'])
|
|
455
|
+
run_id = '%s--%s' % (run_id_of(plan), task)
|
|
456
|
+
if len(run_id) > MAX_RUN_ID:
|
|
457
|
+
raise Invalid('the run id of the sub-plan would be longer than %d characters' % MAX_RUN_ID)
|
|
458
|
+
lim = limits(plan)
|
|
459
|
+
level = level_of(plan)
|
|
460
|
+
if level >= lim['depth']:
|
|
461
|
+
raise Bounded('depth', 'task %s is at depth %d and the limit is %d: it is not split further'
|
|
462
|
+
% (node_path(plan, task), level, lim['depth']))
|
|
463
|
+
if len(children) > lim['children']:
|
|
464
|
+
raise Bounded('children', '%d subtasks were proposed for %s and the limit is %d per split'
|
|
465
|
+
% (len(children), node_path(plan, task), lim['children']))
|
|
466
|
+
used = count_subnodes(root_of(plan))
|
|
467
|
+
if used + len(children) > lim['nodes']:
|
|
468
|
+
raise Bounded('nodes', 'the run already has %d subtasks, %d more were proposed for %s, and the limit is %d'
|
|
469
|
+
% (used, len(children), node_path(plan, task), lim['nodes']))
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
# --- the sub-plan --------------------------------------------------------------------------
|
|
473
|
+
|
|
474
|
+
def _pools(path: Path) -> dict:
|
|
475
|
+
data = _read_json(path)
|
|
476
|
+
out = {}
|
|
477
|
+
if isinstance(data, dict):
|
|
478
|
+
for key in ('any', 'low', 'medium', 'high'):
|
|
479
|
+
specs = data.get(key)
|
|
480
|
+
if isinstance(specs, list):
|
|
481
|
+
specs = [s for s in specs if isinstance(s, str) and s and s != 'script']
|
|
482
|
+
if specs:
|
|
483
|
+
out[key] = specs
|
|
484
|
+
return out
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _route(children: list, pools: dict, fallback: str) -> list:
|
|
488
|
+
"""One spec per child from the plan's tier pools, each pool taken in turn, as `plan` does:
|
|
489
|
+
the child's tier, then the plain pool, then what the parent task has."""
|
|
490
|
+
turn = {}
|
|
491
|
+
picked = []
|
|
492
|
+
for child in children:
|
|
493
|
+
tier = child['difficulty'] if child['difficulty'] in pools else 'any'
|
|
494
|
+
if tier in pools:
|
|
495
|
+
index = turn.get(tier, 0)
|
|
496
|
+
turn[tier] = index + 1
|
|
497
|
+
picked.append(pools[tier][index % len(pools[tier])])
|
|
498
|
+
else:
|
|
499
|
+
picked.append(fallback)
|
|
500
|
+
return picked
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def create_sub(plan, task: str, children: list, reason: str, by: str = 'user', start: str = 'keep',
|
|
504
|
+
context: str = '') -> Path:
|
|
505
|
+
"""Make the task's sub-plan from validated children and record the split. The sub-plan appears
|
|
506
|
+
whole (written beside its place and renamed), so an interrupted split leaves none."""
|
|
507
|
+
if start not in STARTS:
|
|
508
|
+
raise Invalid('a split starts with keep or fresh, not %r' % start)
|
|
509
|
+
plan = Path(plan)
|
|
510
|
+
check_split(plan, task, children)
|
|
511
|
+
row = row_of(plan, task)
|
|
512
|
+
tdir = plan / 'tasks' / task
|
|
513
|
+
final = tdir / SUB
|
|
514
|
+
work = tdir / ('.%s.tmp-%d' % (SUB, os.getpid()))
|
|
515
|
+
shutil.rmtree(work, ignore_errors=True)
|
|
516
|
+
work.mkdir(parents=True)
|
|
517
|
+
try:
|
|
518
|
+
dwarfs = _route(children, _pools(forge_legacy.pools_path(plan)), row['dwarf'])
|
|
519
|
+
reviewers = _route(children, _pools(plan / 'qa-routing.json'), row['qa'])
|
|
520
|
+
declared, routed = [TSV_HEADER], [TSV_HEADER]
|
|
521
|
+
try:
|
|
522
|
+
parent_prompt = (tdir / 'prompt.md').read_text(encoding='utf-8')
|
|
523
|
+
except (OSError, UnicodeDecodeError):
|
|
524
|
+
parent_prompt = row['title'] + '\n'
|
|
525
|
+
for child, dwarf, qa in zip(children, dwarfs, reviewers):
|
|
526
|
+
cells = [child['id'], ','.join(child.get('deps', [])) or '-', child['difficulty'],
|
|
527
|
+
','.join(child['files']), '-', '-', ' '.join(child['title'].split())]
|
|
528
|
+
declared.append('\t'.join(cells))
|
|
529
|
+
routed.append('\t'.join(cells[:4] + [dwarf or '-', qa or '-'] + cells[6:]))
|
|
530
|
+
cdir = work / 'tasks' / child['id']
|
|
531
|
+
cdir.mkdir(parents=True)
|
|
532
|
+
text = child['prompt'].rstrip('\n') + '\n\n## The task this is a part of\n\n'
|
|
533
|
+
text += ('This is one of %d subtasks of the task "%s". The other subtasks own the rest of it; '
|
|
534
|
+
'do only the part above.\n\n' % (len(children), row['title']))
|
|
535
|
+
text += parent_prompt if parent_prompt.endswith('\n') else parent_prompt + '\n'
|
|
536
|
+
if context.strip():
|
|
537
|
+
text += '\n' + context.rstrip('\n') + '\n'
|
|
538
|
+
(cdir / 'prompt.md').write_text(text, encoding='utf-8')
|
|
539
|
+
approach = child.get('approach')
|
|
540
|
+
if isinstance(approach, str) and approach.strip():
|
|
541
|
+
(cdir / 'approach.md').write_text(approach, encoding='utf-8')
|
|
542
|
+
if child.get('risk') in DIFFICULTIES:
|
|
543
|
+
(cdir / 'risk').write_text(child['risk'] + '\n', encoding='utf-8')
|
|
544
|
+
nested = child.get('split')
|
|
545
|
+
if isinstance(nested, dict) and isinstance(nested.get('tasks'), list):
|
|
546
|
+
(cdir / PROPOSAL).write_text(json.dumps(nested), encoding='utf-8')
|
|
547
|
+
(work / 'tasks.declared.tsv').write_text('\n'.join(declared) + '\n', encoding='utf-8')
|
|
548
|
+
(work / 'tasks.tsv').write_text('\n'.join(routed) + '\n', encoding='utf-8')
|
|
549
|
+
(work / 'run_id').write_text('%s--%s\n' % (run_id_of(plan), task), encoding='utf-8')
|
|
550
|
+
(work / 'request.md').write_text(parent_prompt, encoding='utf-8')
|
|
551
|
+
(work / 'goal.txt').write_text(row['title'] + '\n', encoding='utf-8')
|
|
552
|
+
(work / 'orchestrator').write_text('split\n', encoding='utf-8')
|
|
553
|
+
for name in ('repo',) + OPTION_FILES:
|
|
554
|
+
source = plan / name
|
|
555
|
+
if source.is_file():
|
|
556
|
+
shutil.copy2(source, work / name)
|
|
557
|
+
(work / PARENT).write_text(json.dumps(dict(
|
|
558
|
+
task=task, run_id=run_id_of(plan), start=start, by=by, at=time.time(),
|
|
559
|
+
reason=' '.join(str(reason).split())[:2000]), indent=1) + '\n', encoding='utf-8')
|
|
560
|
+
if not (work / 'repo').is_file():
|
|
561
|
+
raise Invalid('%s has no repo file: plan it first (forge-parallel.sh plan)' % plan)
|
|
562
|
+
os.replace(work, final)
|
|
563
|
+
except BaseException:
|
|
564
|
+
shutil.rmtree(work, ignore_errors=True)
|
|
565
|
+
raise
|
|
566
|
+
try:
|
|
567
|
+
(tdir / MERGED).unlink()
|
|
568
|
+
except OSError:
|
|
569
|
+
pass
|
|
570
|
+
record(plan, task, 'split', reason, by, children=len(children), start=start,
|
|
571
|
+
subtasks=[c['id'] for c in children])
|
|
572
|
+
return final
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def split(plan, task: str, proposal: dict, reason: str = '', by: str = 'user', start: str = 'keep',
|
|
576
|
+
context: str = '') -> Path:
|
|
577
|
+
"""create_sub, with the outcome that is not a split recorded: a proposal of one task (or none)
|
|
578
|
+
is `atomic` with its reason, and a split a limit refuses is `bounded`. Both raise again, so
|
|
579
|
+
the caller says what happened; Invalid records nothing."""
|
|
580
|
+
children = proposal.get('tasks') if isinstance(proposal, dict) else None
|
|
581
|
+
why = reason or (proposal.get('reason') if isinstance(proposal, dict) else '') or ''
|
|
582
|
+
try:
|
|
583
|
+
made = create_sub(plan, task, children, why, by=by, start=start, context=context)
|
|
584
|
+
settle(made) # its subtasks are nodes too, and one may carry a proposal of its own
|
|
585
|
+
return made
|
|
586
|
+
except Atomic:
|
|
587
|
+
# The reason to keep a task whole is the one who answered gave, when there is one.
|
|
588
|
+
said = proposal.get('reason') if isinstance(proposal, dict) else ''
|
|
589
|
+
record(plan, task, 'atomic', (said if isinstance(said, str) and said.strip() else why)
|
|
590
|
+
or 'kept as one task: no split was proposed', by,
|
|
591
|
+
children=len(children) if isinstance(children, list) else 0)
|
|
592
|
+
raise
|
|
593
|
+
except Bounded as limit:
|
|
594
|
+
record(plan, task, 'bounded', '%s (%s)' % (limit, why) if why else str(limit), by,
|
|
595
|
+
children=len(children), limit=limit.limit)
|
|
596
|
+
raise
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def settle(plan, by: str = 'default') -> list:
|
|
600
|
+
"""After `plan` routed the table: turn every stored proposal (tasks/<id>/split.proposal.json,
|
|
601
|
+
written when a planner proposed subtasks) into a sub-plan, through every level, and record
|
|
602
|
+
every task nobody decided about as atomic. Returns one line per thing done, for the table.
|
|
603
|
+
A proposal is applied once: it is removed whatever its outcome."""
|
|
604
|
+
lines = []
|
|
605
|
+
stack = [Path(plan)]
|
|
606
|
+
while stack:
|
|
607
|
+
current = stack.pop()
|
|
608
|
+
for row in read_rows(current):
|
|
609
|
+
task = row['id']
|
|
610
|
+
stored = current / 'tasks' / task / PROPOSAL
|
|
611
|
+
if stored.is_file():
|
|
612
|
+
proposal = _read_json(stored)
|
|
613
|
+
try:
|
|
614
|
+
stored.unlink()
|
|
615
|
+
except OSError:
|
|
616
|
+
pass
|
|
617
|
+
who = by if by != 'default' else 'planner'
|
|
618
|
+
try:
|
|
619
|
+
sub = split(current, task, proposal if isinstance(proposal, dict) else {}, by=who)
|
|
620
|
+
lines.append('%s: split into %d subtasks' % (node_path(current, task), len(read_rows(sub))))
|
|
621
|
+
except Atomic:
|
|
622
|
+
lines.append('%s: kept whole' % node_path(current, task))
|
|
623
|
+
except Bounded as limit:
|
|
624
|
+
lines.append('%s: not split, at a limit (%s)' % (node_path(current, task), limit))
|
|
625
|
+
except Invalid as error:
|
|
626
|
+
lines.append('%s: the proposed split was refused (%s)' % (node_path(current, task), error))
|
|
627
|
+
if is_split(current, task):
|
|
628
|
+
stack.append(sub_dir(current, task))
|
|
629
|
+
else:
|
|
630
|
+
old = load(current)['nodes'].get(task)
|
|
631
|
+
if old and old.get('decision') == 'bounded':
|
|
632
|
+
continue # a limit said no: that stays the record
|
|
633
|
+
note = _first_line(current / 'tasks' / task / REASON)
|
|
634
|
+
record(current, task, 'atomic', note or 'kept as one task: no split was proposed',
|
|
635
|
+
'planner' if note else 'default')
|
|
636
|
+
return lines
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
# --- reading the tree ----------------------------------------------------------------------
|
|
640
|
+
|
|
641
|
+
def tree(plan, _parent: str = None, _level: int = None) -> list:
|
|
642
|
+
"""Every node at and below this plan, in tree order (a task, then its subtasks). Each is a
|
|
643
|
+
dict: id (the path from this plan's root), task, parent, level, plan (the directory the task
|
|
644
|
+
is a row of), run, title, status, difficulty, files, deps, model, qa, decision, reason, by,
|
|
645
|
+
children (how many subtasks it has)."""
|
|
646
|
+
plan = Path(plan)
|
|
647
|
+
out = []
|
|
648
|
+
data = load(plan)
|
|
649
|
+
level = level_of(plan) if _level is None else _level
|
|
650
|
+
run = run_id_of(plan)
|
|
651
|
+
for row in read_rows(plan):
|
|
652
|
+
task = row['id']
|
|
653
|
+
node = node_of(plan, task, data)
|
|
654
|
+
path = node_path(plan, task)
|
|
655
|
+
sub = sub_dir(plan, task)
|
|
656
|
+
kids = read_rows(sub) if is_split(plan, task) else []
|
|
657
|
+
out.append(dict(id=path, task=task, parent=_parent if _parent is not None else (
|
|
658
|
+
node_path(*parent_link(plan)) if parent_link(plan) else None),
|
|
659
|
+
level=level, plan=str(plan), run=run, title=row['title'], status=status_of(plan, task),
|
|
660
|
+
difficulty=row['difficulty'], files=row['files'], deps=row['deps'], model=row['dwarf'],
|
|
661
|
+
qa=row['qa'], decision=node.get('decision', 'atomic'), reason=node.get('reason', ''),
|
|
662
|
+
by=node.get('by', 'default'), children=len(kids),
|
|
663
|
+
merged=(plan / 'tasks' / task / MERGED).exists() if kids else None))
|
|
664
|
+
if kids:
|
|
665
|
+
out.extend(tree(sub, path, level + 1))
|
|
666
|
+
return out
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
def waiting(plan, task: str) -> list:
|
|
670
|
+
"""One line per subtask of the task that has not merged, with its status and where it is."""
|
|
671
|
+
sub = sub_dir(plan, task)
|
|
672
|
+
lines = []
|
|
673
|
+
for row in read_rows(sub):
|
|
674
|
+
state = status_of(sub, row['id'])
|
|
675
|
+
if state != 'MERGED':
|
|
676
|
+
lines.append('%s %s' % (row['id'], state))
|
|
677
|
+
return lines
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
def subs(plan) -> list:
|
|
681
|
+
"""Every sub-plan directory under the plan, a parent before its children."""
|
|
682
|
+
found = []
|
|
683
|
+
stack = [Path(plan)]
|
|
684
|
+
while stack:
|
|
685
|
+
current = stack.pop()
|
|
686
|
+
inner = [sub_dir(current, row['id']) for row in read_rows(current) if is_split(current, row['id'])]
|
|
687
|
+
found.extend(inner)
|
|
688
|
+
stack.extend(reversed(inner))
|
|
689
|
+
return found
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def render(plan, split_only: bool = False) -> str:
|
|
693
|
+
lines = []
|
|
694
|
+
for node in tree(plan):
|
|
695
|
+
if split_only and node['level'] == 0 and node['decision'] == 'atomic':
|
|
696
|
+
continue
|
|
697
|
+
mark = {'atomic': '', 'split': ' [split into %d]' % node['children'], 'bounded': ' [at a limit]'}[node['decision']]
|
|
698
|
+
lines.append('%s%-*s %-14s %s%s' % (' ' * node['level'], max(14, 28 - 2 * node['level']), node['task'],
|
|
699
|
+
node['status'], node['title'], mark))
|
|
700
|
+
if node['decision'] != 'atomic' and node['reason']:
|
|
701
|
+
lines.append('%s %s: %s' % (' ' * node['level'], node['decision'], node['reason']))
|
|
702
|
+
return '\n'.join(lines)
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
# --- goal -> plans: the stages after a plan ------------------------------------------------
|
|
706
|
+
# A planner that judges a goal larger than one plan plans its first stage and lists the others
|
|
707
|
+
# (later.json). Each later stage becomes a plan of its own, made by `next` once the plan before it
|
|
708
|
+
# has merged and planned from the code as it then is, on that plan's integration branch (--after).
|
|
709
|
+
|
|
710
|
+
def chain_of(plan) -> dict:
|
|
711
|
+
data = _read_json(Path(plan) / CHAIN)
|
|
712
|
+
return data if isinstance(data, dict) else {}
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
def _stages(raw) -> list:
|
|
716
|
+
out = []
|
|
717
|
+
if isinstance(raw, list):
|
|
718
|
+
for item in raw:
|
|
719
|
+
if isinstance(item, dict) and isinstance(item.get('title'), str) and isinstance(item.get('goal'), str) \
|
|
720
|
+
and item['title'].strip() and item['goal'].strip():
|
|
721
|
+
out.append(dict(title=' '.join(item['title'].split()), goal=item['goal']))
|
|
722
|
+
return out
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
def later(plan) -> list:
|
|
726
|
+
"""The stages that follow this plan, in order: what its own planner listed, else what is left of
|
|
727
|
+
the chain it was made from."""
|
|
728
|
+
own = _read_json(Path(plan) / LATER)
|
|
729
|
+
if isinstance(own, dict) and _stages(own.get('later')):
|
|
730
|
+
return _stages(own.get('later'))
|
|
731
|
+
return _stages(chain_of(plan).get('remaining'))
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
def unmerged(plan) -> list:
|
|
735
|
+
return [row['id'] for row in read_rows(plan) if status_of(plan, row['id']) != 'MERGED']
|
|
736
|
+
|
|
737
|
+
|
|
738
|
+
def next_stage(plan, new=None) -> Path:
|
|
739
|
+
"""Make the directory of the plan for the next stage: request.md (the stage's goal, then the
|
|
740
|
+
larger goal for context), goal.txt and chain.json. Nothing is planned or dispatched here."""
|
|
741
|
+
plan = Path(plan).resolve()
|
|
742
|
+
if parent_link(plan) is not None:
|
|
743
|
+
raise Invalid('%s is a sub-plan: the stages of a goal follow its root plan' % plan)
|
|
744
|
+
stages = later(plan)
|
|
745
|
+
if not stages:
|
|
746
|
+
raise Invalid('%s has no later stage: its planner proposed none' % plan)
|
|
747
|
+
if not read_rows(plan):
|
|
748
|
+
raise Invalid('%s has no tasks.tsv' % plan)
|
|
749
|
+
left = unmerged(plan)
|
|
750
|
+
if left:
|
|
751
|
+
raise Invalid('the next stage is planned when this plan has merged, and %d task(s) have not: %s'
|
|
752
|
+
% (len(left), ', '.join(left[:8])))
|
|
753
|
+
chain = chain_of(plan)
|
|
754
|
+
first = Path(chain['first']) if isinstance(chain.get('first'), str) and chain['first'] else plan
|
|
755
|
+
stage = (chain['stage'] if type(chain.get('stage')) is int else 1) + 1
|
|
756
|
+
target = Path(new).resolve() if new else first.with_name('%s-%d' % (first.name, stage))
|
|
757
|
+
if target.exists() and (not target.is_dir() or any(target.iterdir())):
|
|
758
|
+
raise Invalid('%s exists and is not empty: name another directory for the next plan' % target)
|
|
759
|
+
try:
|
|
760
|
+
whole = (first / 'request.md').read_text(encoding='utf-8')
|
|
761
|
+
except (OSError, UnicodeDecodeError):
|
|
762
|
+
whole = ''
|
|
763
|
+
head = stages[0]
|
|
764
|
+
request = '# %s\n\n%s\n' % (head['title'], head['goal'].strip())
|
|
765
|
+
request += ('\n## Where this stands\n\nThis is stage %d of a larger goal. The stages before it are done and '
|
|
766
|
+
'merged: plan only this stage, from the code as it is now.\n' % stage)
|
|
767
|
+
if stages[1:]:
|
|
768
|
+
request += 'Stages that follow, not to be planned now: %s.\n' % '; '.join(s['title'] for s in stages[1:])
|
|
769
|
+
if whole.strip():
|
|
770
|
+
request += '\n## The larger goal, for context\n\n' + whole
|
|
771
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
772
|
+
(target / 'request.md').write_text(request, encoding='utf-8')
|
|
773
|
+
(target / 'goal.txt').write_text(head['title'][:200] + '\n', encoding='utf-8')
|
|
774
|
+
_write_atomic(target / CHAIN, json.dumps(dict(first=str(first), stage=stage, previous=str(plan),
|
|
775
|
+
title=head['title'], remaining=stages[1:]), indent=1) + '\n')
|
|
776
|
+
return target
|
|
777
|
+
|
|
778
|
+
|
|
779
|
+
# --- one concurrency bound for the tree ----------------------------------------------------
|
|
780
|
+
# A run and the sub-plan runs under it share the root run's --max-parallel: each dispatch that
|
|
781
|
+
# works (an implementer or a review) holds one slot, a lock on a file of <root>/tree.slots. A split
|
|
782
|
+
# task waiting for its subtasks holds none. Locks end with their process, so a killed run leaves no
|
|
783
|
+
# slot taken. Any error here means "no bound from this file": a run is never stopped by its slots.
|
|
784
|
+
|
|
785
|
+
class Slots:
|
|
786
|
+
def __init__(self, root):
|
|
787
|
+
self.dir = Path(root) / SLOTS
|
|
788
|
+
self.broken = False
|
|
789
|
+
|
|
790
|
+
def take(self, cap: int):
|
|
791
|
+
"""A held slot (an open file to keep and later close), None when all `cap` are taken, or
|
|
792
|
+
False when slots cannot be used here (the caller dispatches without one)."""
|
|
793
|
+
if self.broken:
|
|
794
|
+
return False
|
|
795
|
+
try:
|
|
796
|
+
import forge_flock
|
|
797
|
+
self.dir.mkdir(parents=True, exist_ok=True)
|
|
798
|
+
for index in range(max(1, cap)):
|
|
799
|
+
handle = open(self.dir / str(index), 'a')
|
|
800
|
+
try:
|
|
801
|
+
forge_flock.flock(handle, forge_flock.LOCK_EX | forge_flock.LOCK_NB)
|
|
802
|
+
return handle
|
|
803
|
+
except OSError:
|
|
804
|
+
handle.close()
|
|
805
|
+
return None
|
|
806
|
+
except Exception:
|
|
807
|
+
self.broken = True
|
|
808
|
+
return False
|
|
809
|
+
|
|
810
|
+
@staticmethod
|
|
811
|
+
def give(handle) -> None:
|
|
812
|
+
if handle:
|
|
813
|
+
try:
|
|
814
|
+
handle.close()
|
|
815
|
+
except OSError:
|
|
816
|
+
pass
|
|
817
|
+
|
|
818
|
+
|
|
819
|
+
def _pid_alive(pid: int) -> bool:
|
|
820
|
+
try:
|
|
821
|
+
import forge_proc
|
|
822
|
+
return forge_proc.pid_alive(pid)
|
|
823
|
+
except Exception:
|
|
824
|
+
try:
|
|
825
|
+
os.kill(pid, 0)
|
|
826
|
+
return True
|
|
827
|
+
except OSError:
|
|
828
|
+
return False
|
|
829
|
+
|
|
830
|
+
|
|
831
|
+
def hold_slot(root, cap: int, pid: int, ready, wait: float = 0.2) -> int:
|
|
832
|
+
"""Take one slot of the tree, write `ready`, and hold the slot until process `pid` is gone.
|
|
833
|
+
Used by a split task for its own review: its scheduler gave its slot back while the subtasks ran."""
|
|
834
|
+
slots = Slots(root)
|
|
835
|
+
handle = None
|
|
836
|
+
while _pid_alive(pid):
|
|
837
|
+
handle = slots.take(cap)
|
|
838
|
+
if handle is not None: # a slot, or False: slots cannot be used, so nothing to wait for
|
|
839
|
+
break
|
|
840
|
+
time.sleep(wait)
|
|
841
|
+
try:
|
|
842
|
+
Path(ready).write_text('held\n' if handle else 'unbounded\n')
|
|
843
|
+
except OSError:
|
|
844
|
+
pass
|
|
845
|
+
while _pid_alive(pid):
|
|
846
|
+
time.sleep(wait)
|
|
847
|
+
Slots.give(handle)
|
|
848
|
+
return 0
|
|
849
|
+
|
|
850
|
+
|
|
851
|
+
# --- command line --------------------------------------------------------------------------
|
|
852
|
+
|
|
853
|
+
def _proposal(path: str) -> dict:
|
|
854
|
+
data = _read_json(Path(path))
|
|
855
|
+
if not isinstance(data, dict):
|
|
856
|
+
raise Invalid('%s is not a JSON object with the subtasks' % path)
|
|
857
|
+
return data
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def main(argv=None) -> int:
|
|
861
|
+
ap = argparse.ArgumentParser(prog='forge_decompose.py', description=__doc__.split('\n')[0])
|
|
862
|
+
sub = ap.add_subparsers(dest='cmd', required=True)
|
|
863
|
+
p = sub.add_parser('limits')
|
|
864
|
+
p.add_argument('plan')
|
|
865
|
+
for key in DEFAULT_LIMITS:
|
|
866
|
+
p.add_argument('--' + key, type=int)
|
|
867
|
+
p.add_argument('--json', action='store_true')
|
|
868
|
+
p = sub.add_parser('freeze')
|
|
869
|
+
p.add_argument('plan')
|
|
870
|
+
p = sub.add_parser('split')
|
|
871
|
+
p.add_argument('plan')
|
|
872
|
+
p.add_argument('task')
|
|
873
|
+
p.add_argument('--proposal', required=True)
|
|
874
|
+
p.add_argument('--reason', default='')
|
|
875
|
+
p.add_argument('--by', choices=DECIDERS, default='user')
|
|
876
|
+
p.add_argument('--start', choices=STARTS, default='keep')
|
|
877
|
+
p.add_argument('--context-file')
|
|
878
|
+
p.add_argument('--check', action='store_true', help='judge the split and write nothing')
|
|
879
|
+
p = sub.add_parser('record')
|
|
880
|
+
p.add_argument('plan')
|
|
881
|
+
p.add_argument('task')
|
|
882
|
+
p.add_argument('--decision', choices=DECISIONS, required=True)
|
|
883
|
+
p.add_argument('--reason', default='')
|
|
884
|
+
p.add_argument('--by', choices=DECIDERS, default='user')
|
|
885
|
+
p = sub.add_parser('settle')
|
|
886
|
+
p.add_argument('plan')
|
|
887
|
+
p.add_argument('--by', choices=DECIDERS, default='default')
|
|
888
|
+
p = sub.add_parser('tree')
|
|
889
|
+
p.add_argument('plan')
|
|
890
|
+
p.add_argument('--json', action='store_true')
|
|
891
|
+
p.add_argument('--split-only', action='store_true', help='only the tasks that were split or bounded, with their subtasks')
|
|
892
|
+
for name in ('state', 'waiting'):
|
|
893
|
+
p = sub.add_parser(name)
|
|
894
|
+
p.add_argument('plan')
|
|
895
|
+
p.add_argument('task')
|
|
896
|
+
for name in ('root', 'subs'):
|
|
897
|
+
p = sub.add_parser(name)
|
|
898
|
+
p.add_argument('plan')
|
|
899
|
+
p = sub.add_parser('later')
|
|
900
|
+
p.add_argument('plan')
|
|
901
|
+
p.add_argument('--json', action='store_true')
|
|
902
|
+
p = sub.add_parser('next')
|
|
903
|
+
p.add_argument('plan')
|
|
904
|
+
p.add_argument('--dir')
|
|
905
|
+
p = sub.add_parser('slot')
|
|
906
|
+
p.add_argument('--root', required=True)
|
|
907
|
+
p.add_argument('--cap', type=int, required=True)
|
|
908
|
+
p.add_argument('--while-pid', type=int, required=True)
|
|
909
|
+
p.add_argument('--ready', required=True)
|
|
910
|
+
args = ap.parse_args(argv)
|
|
911
|
+
try:
|
|
912
|
+
if args.cmd == 'limits':
|
|
913
|
+
values = set_limits(args.plan, depth=args.depth, children=args.children, nodes=args.nodes)
|
|
914
|
+
if args.json:
|
|
915
|
+
print(json.dumps(dict(values, frozen=is_frozen(args.plan), used=count_subnodes(root_of(args.plan)))))
|
|
916
|
+
else:
|
|
917
|
+
print('decomposition limits: %s%s' % (describe(values), ' (frozen)' if is_frozen(args.plan) else ''))
|
|
918
|
+
return 0
|
|
919
|
+
if args.cmd == 'freeze':
|
|
920
|
+
freeze(args.plan)
|
|
921
|
+
return 0
|
|
922
|
+
if args.cmd == 'split':
|
|
923
|
+
proposal = _proposal(args.proposal)
|
|
924
|
+
if args.check:
|
|
925
|
+
check_split(args.plan, args.task, proposal.get('tasks'))
|
|
926
|
+
return 0
|
|
927
|
+
context = ''
|
|
928
|
+
if args.context_file:
|
|
929
|
+
try:
|
|
930
|
+
context = Path(args.context_file).read_text(encoding='utf-8', errors='replace')
|
|
931
|
+
except OSError:
|
|
932
|
+
context = ''
|
|
933
|
+
print(split(args.plan, args.task, proposal, args.reason, args.by, args.start, context))
|
|
934
|
+
return 0
|
|
935
|
+
if args.cmd == 'record':
|
|
936
|
+
record(args.plan, args.task, args.decision, args.reason, args.by)
|
|
937
|
+
return 0
|
|
938
|
+
if args.cmd == 'settle':
|
|
939
|
+
for line in settle(args.plan, args.by):
|
|
940
|
+
print(line)
|
|
941
|
+
return 0
|
|
942
|
+
if args.cmd == 'tree':
|
|
943
|
+
text = json.dumps(tree(args.plan), indent=1) if args.json else render(args.plan, args.split_only)
|
|
944
|
+
if text:
|
|
945
|
+
print(text)
|
|
946
|
+
return 0
|
|
947
|
+
if args.cmd == 'state':
|
|
948
|
+
print('none' if not is_split(args.plan, args.task) else 'open' if is_open(args.plan, args.task) else 'merged')
|
|
949
|
+
return 0
|
|
950
|
+
if args.cmd == 'waiting':
|
|
951
|
+
for line in waiting(args.plan, args.task):
|
|
952
|
+
print(line)
|
|
953
|
+
return 0
|
|
954
|
+
if args.cmd == 'root':
|
|
955
|
+
print(root_of(args.plan))
|
|
956
|
+
return 0
|
|
957
|
+
if args.cmd == 'subs':
|
|
958
|
+
for path in subs(args.plan):
|
|
959
|
+
print(path)
|
|
960
|
+
return 0
|
|
961
|
+
if args.cmd == 'later':
|
|
962
|
+
stages = later(args.plan)
|
|
963
|
+
if args.json:
|
|
964
|
+
print(json.dumps(stages))
|
|
965
|
+
else:
|
|
966
|
+
for index, stage in enumerate(stages, 1):
|
|
967
|
+
print('%d. %s' % (index, stage['title']))
|
|
968
|
+
return 0
|
|
969
|
+
if args.cmd == 'next':
|
|
970
|
+
print(next_stage(args.plan, args.dir))
|
|
971
|
+
return 0
|
|
972
|
+
if args.cmd == 'slot':
|
|
973
|
+
return hold_slot(args.root, args.cap, args.while_pid, args.ready)
|
|
974
|
+
except Atomic as error:
|
|
975
|
+
print('kept whole: %s' % error, file=sys.stderr)
|
|
976
|
+
return 5
|
|
977
|
+
except Bounded as error:
|
|
978
|
+
print('bounded: %s' % error, file=sys.stderr)
|
|
979
|
+
return 4
|
|
980
|
+
except Invalid as error:
|
|
981
|
+
print('refused: %s' % error, file=sys.stderr)
|
|
982
|
+
return 3
|
|
983
|
+
return 2
|
|
984
|
+
|
|
985
|
+
|
|
986
|
+
if __name__ == '__main__':
|
|
987
|
+
sys.exit(main())
|