@giamme/forge 0.14.0 → 0.15.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 +26 -0
- package/SKILL.md +47 -14
- package/VERSION +1 -1
- package/docs/artifacts.md +2 -1
- package/docs/commands.md +301 -7
- package/docs/models.md +53 -0
- package/package.json +1 -1
- package/references/dataset.md +12 -3
- package/references/decompose.md +108 -7
- package/references/harnesses.md +21 -1
- package/references/planning.md +59 -0
- package/references/ui.md +39 -1
- package/scripts/forge-compare.py +6 -3
- package/scripts/forge-config.py +531 -4
- package/scripts/forge-dispatch.sh +132 -22
- package/scripts/forge-lib-plans.sh +19 -2
- package/scripts/forge-lib-review.sh +5 -3
- package/scripts/forge-lib-task.sh +119 -0
- package/scripts/forge-parallel-options.sh +12 -6
- package/scripts/forge-parallel.sh +572 -26
- package/scripts/forge-plan-check.py +591 -8
- package/scripts/forge-planner.py +480 -0
- package/scripts/forge-route.py +72 -23
- package/scripts/forge-runtime.py +157 -1
- package/scripts/forge-shadow.py +51 -7
- package/scripts/forge-solo.sh +81 -7
- package/scripts/forge_dataset/cli.py +10 -0
- package/scripts/forge_dataset/efforts.py +215 -0
- package/scripts/forge_dataset/harvest.py +44 -0
- package/scripts/forge_decide/__init__.py +19 -1
- package/scripts/forge_decide/builtin_profiles.json +25 -0
- package/scripts/forge_decide/cli.py +12 -0
- package/scripts/forge_decide/profiles.py +866 -0
- package/scripts/forge_decide/resolve.py +38 -6
- package/ui/docs/api.md +87 -8
- package/ui/forge_ui/control.py +173 -12
- package/ui/forge_ui/executions.py +28 -8
- package/ui/forge_ui/models.py +60 -1
- package/ui/forge_ui/reader.py +21 -1
- package/ui/forge_ui/static/leaderboard.js +5 -1
- package/ui/forge_ui/static/modelstats.js +25 -1
- package/ui/forge_ui/static/panel.js +19 -2
- package/ui/forge_ui/static/settings.js +788 -25
- package/ui/forge_ui/static/style.css +23 -0
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""The planner contract: the prompt a planner gets, the strict parse of its reply, the pre-plan
|
|
3
|
+
gate and the one-task plan. Standard library only; no shell wiring.
|
|
4
|
+
|
|
5
|
+
forge-planner.py prompt --plan P --goal-file F [--level low|medium|high]
|
|
6
|
+
Writes P/planner.prompt (the role, the request verbatim, the decomposition rules, the
|
|
7
|
+
reply format) and prints its path.
|
|
8
|
+
|
|
9
|
+
forge-planner.py parse --plan P --reply FILE
|
|
10
|
+
Turns the planner's reply into P/tasks.tsv, P/tasks/<id>/prompt.md and, when it is not
|
|
11
|
+
empty, P/tasks/<id>/approach.md. It never guesses or repairs: a reply that breaks one
|
|
12
|
+
rule writes nothing but P/planner.refused (the first reason and the reply's path), prints
|
|
13
|
+
both and exits 4. P/request.md must hold the user's request (exit 2 when it is missing);
|
|
14
|
+
it is attached to every task prompt so no requirement is lost.
|
|
15
|
+
|
|
16
|
+
forge-planner.py gate --plan P --goal-file F
|
|
17
|
+
Prints `one-task` when the request is small (at most MAX_CHARS characters and
|
|
18
|
+
MAX_REQUIREMENTS requirements), else `plan`, and records the signals in P/plan-gate.json.
|
|
19
|
+
|
|
20
|
+
forge-planner.py one-task --plan P --goal-file F [--difficulty low|medium|high]
|
|
21
|
+
Writes a one-row plan without a planner: id `task`, files `.`, the request as its prompt.
|
|
22
|
+
|
|
23
|
+
Every subcommand refuses (exit 2) a plan dir that already has tasks.tsv, so nothing is
|
|
24
|
+
overwritten. Exit codes: 0 done, 2 usage or input problem, 4 reply refused.
|
|
25
|
+
"""
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import argparse
|
|
29
|
+
import json
|
|
30
|
+
import os
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
import re
|
|
33
|
+
import sys
|
|
34
|
+
|
|
35
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
36
|
+
from forge_jev.coverage import split_requirements # noqa: E402 (read-only use)
|
|
37
|
+
|
|
38
|
+
# The gate: a request at or under both limits skips the planner. On #86's 16 benchmark plans
|
|
39
|
+
# size did not predict the plan's shape (element-web: 3262 characters, 15 requirements, one
|
|
40
|
+
# task; flipt: 3276, 22, two parallel tasks), so the limits only let small goals through.
|
|
41
|
+
MAX_CHARS = 1500
|
|
42
|
+
MAX_REQUIREMENTS = 6
|
|
43
|
+
|
|
44
|
+
MAX_TASKS = 20
|
|
45
|
+
TASK_KEYS = ('id', 'deps', 'difficulty', 'files', 'title', 'approach', 'prompt')
|
|
46
|
+
DIFFICULTIES = ('low', 'medium', 'high')
|
|
47
|
+
LEVELS = DIFFICULTIES
|
|
48
|
+
ID_RE = re.compile(r'[a-z0-9][a-z0-9-]{0,39}')
|
|
49
|
+
ACCEPTANCE_RE = re.compile(r'## Acceptance criteria[ \t]*:?[ \t]*')
|
|
50
|
+
FENCE_RE = re.compile(r'^ {0,3}(`{3,}|~{3,})(.*)$')
|
|
51
|
+
# Characters that break a one-line TSV field or a path: C0 controls (NUL, tab, newline, CR ...),
|
|
52
|
+
# DEL, and the Unicode line separators that str.splitlines() also splits on.
|
|
53
|
+
LINE_BREAKS_RE = re.compile('[\x00-\x1f\x7f\x85\u2028\u2029]')
|
|
54
|
+
OPEN_RE = re.compile(r'^```forge-plan[ \t]*$')
|
|
55
|
+
CLOSE_RE = re.compile(r'^```[ \t]*$')
|
|
56
|
+
PATH_RE = re.compile(r'(?<![\w/.-])(?:[\w.-]+/)*[\w-]+\.[A-Za-z][A-Za-z0-9]{0,7}(?![\w-])')
|
|
57
|
+
TSV_HEADER = '# id\tdeps\tdifficulty\tfiles\tdwarf\tqa\ttitle'
|
|
58
|
+
WHOLE_REQUEST = '## The whole request'
|
|
59
|
+
ONE_TASK_CRITERION = ('- Every requirement of the request above is met, and the tests for the '
|
|
60
|
+
'files you changed pass.')
|
|
61
|
+
|
|
62
|
+
LEVEL_GUIDANCE = {
|
|
63
|
+
'low': 'low: split only where the request holds obviously independent pieces; 2-3 coarse tasks.',
|
|
64
|
+
'medium': 'medium: one task per coherent unit (module, feature slice); typically 4-6 tasks.',
|
|
65
|
+
'high': ('high: the finest split in which each task is still independently reviewable and '
|
|
66
|
+
'independently correct; typically 7-12 tasks.'),
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
ROLE = """\
|
|
70
|
+
You are the planner of a software change. You are read-only: inspect the repository as much
|
|
71
|
+
as you need, and return a plan. Never edit, create or delete a file, and never run anything
|
|
72
|
+
that changes the repository. Your reply is a plan; other models carry it out, each task in a
|
|
73
|
+
worktree of its own, and a reviewer judges each task against its prompt."""
|
|
74
|
+
|
|
75
|
+
EXAMPLE = """\
|
|
76
|
+
```forge-plan
|
|
77
|
+
{"tasks": [
|
|
78
|
+
{"id": "parse-config", "deps": [], "difficulty": "medium",
|
|
79
|
+
"files": ["src/config.py", "tests/test_config.py"],
|
|
80
|
+
"title": "Parse the new config section",
|
|
81
|
+
"approach": "Add parse_section() beside load(); keep load()'s signature.",
|
|
82
|
+
"prompt": "Add the `limits` section to the config parser in src/config.py ...\\n\\n## Acceptance criteria\\n\\n- `limits` is read into Config.limits, with the defaults the request names.\\n- python3 -m unittest tests.test_config passes."}
|
|
83
|
+
]}
|
|
84
|
+
```"""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class Refusal(Exception):
|
|
88
|
+
"""A reply that breaks the contract. Carries the first reason."""
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def die(message: str, code: int = 2):
|
|
92
|
+
print(f'forge-planner: {message}', file=sys.stderr)
|
|
93
|
+
raise SystemExit(code)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# --- shared plumbing -----------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
def plan_dir(args) -> Path:
|
|
99
|
+
plan = Path(args.plan)
|
|
100
|
+
if (plan / 'tasks.tsv').exists():
|
|
101
|
+
die(f'{plan / "tasks.tsv"} already exists; refusing to overwrite a plan')
|
|
102
|
+
return plan
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def read_text(path, what: str) -> str:
|
|
106
|
+
try:
|
|
107
|
+
with open(path, encoding='utf-8', newline='') as handle: # newline='': CRLF stays CRLF
|
|
108
|
+
return handle.read()
|
|
109
|
+
except (OSError, UnicodeDecodeError) as err:
|
|
110
|
+
die(f'cannot read {what} {path}: {err}')
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def write_atomic(path: Path, data):
|
|
114
|
+
"""Write str (as UTF-8) or bytes to `path` through a temp file and a rename."""
|
|
115
|
+
if isinstance(data, str):
|
|
116
|
+
data = data.encode('utf-8')
|
|
117
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
118
|
+
tmp = path.with_name(path.name + '.tmp')
|
|
119
|
+
try:
|
|
120
|
+
tmp.write_bytes(data)
|
|
121
|
+
os.replace(tmp, path)
|
|
122
|
+
finally:
|
|
123
|
+
tmp.unlink(missing_ok=True)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# --- prompt --------------------------------------------------------------------------------
|
|
127
|
+
|
|
128
|
+
def build_prompt(request: str, level: str | None) -> str:
|
|
129
|
+
rules = []
|
|
130
|
+
if level:
|
|
131
|
+
rules.append(f'Decomposition level: {LEVEL_GUIDANCE[level]} The counts are guidance, '
|
|
132
|
+
'not quotas: a request with three natural seams yields three tasks at any level.')
|
|
133
|
+
rules += [
|
|
134
|
+
'**One task is a valid answer**, and the right one when the change is one coherent piece. '
|
|
135
|
+
'Do not split to look thorough.',
|
|
136
|
+
'**A pure chain is worse than one task.** In a chain no two tasks can run at once, and each '
|
|
137
|
+
'link pays its own implementation and review and sees the earlier links\' code only after '
|
|
138
|
+
'they merge. Prefer branches that can run in parallel; when the request allows none, return '
|
|
139
|
+
'one task.',
|
|
140
|
+
'Never split so fine that a task cannot be verified on its own: each task must be '
|
|
141
|
+
'reviewable and correct by itself.',
|
|
142
|
+
'**Never two tasks that edit the same file**, unless a dependency orders them. Either make '
|
|
143
|
+
'it one task or add a dep. `files` is a promise: it is what decides which tasks may run '
|
|
144
|
+
'concurrently, and an understated list is how two workers end up in the same file. List every '
|
|
145
|
+
'file the task will create or edit, tests included.',
|
|
146
|
+
'**A single-file deliverable** (one HTML page, one script, one notebook) is split by module '
|
|
147
|
+
'when it splits at all. Each task owns its own source file (for example `src/physics.js`), '
|
|
148
|
+
'and one final low-difficulty task assembles them into the required file. That keeps file '
|
|
149
|
+
'ownership per file and makes the parallel wave real.',
|
|
150
|
+
'Rate `difficulty` by what the task demands of the model, not by how much code it produces: '
|
|
151
|
+
'`low` is mechanical and local (rename, move, docs, a test for behaviour that already exists); '
|
|
152
|
+
'`medium` is a self-contained implementation against a clear spec; `high` needs design '
|
|
153
|
+
'judgment, touches cross-cutting behaviour, has subtle edge cases or state or concurrency, or '
|
|
154
|
+
'the right approach is not obvious from the request. A five-hundred-line mechanical rename is '
|
|
155
|
+
'`low`; a ten-line concurrency fix is `high`.',
|
|
156
|
+
'**Each task\'s `prompt`** carries the whole requirement it owns, written so that someone who '
|
|
157
|
+
'sees only that prompt can do it, and ends with a `## Acceptance criteria` section of checks '
|
|
158
|
+
'a reviewer can verify (a behaviour, a command that passes, a file that exists), not restated '
|
|
159
|
+
'goals. Its tests are the ones for the files it touches. Never ask for the whole test suite '
|
|
160
|
+
'(`tests/check.sh`, `npm test`, `make check` and the like): forge runs that after the merge.',
|
|
161
|
+
'Where tasks share a seam (an interface, a file format, a name), fix it in the `approach` of '
|
|
162
|
+
'every task that touches it, so both sides build the same thing.',
|
|
163
|
+
'**Keep each task** under about 7000 characters of prompt and 9 files. A smaller task with '
|
|
164
|
+
'stated acceptance criteria passes its first review far more often.',
|
|
165
|
+
f'At most {MAX_TASKS} tasks.',
|
|
166
|
+
]
|
|
167
|
+
numbered = '\n'.join(f'{n}. {rule}' for n, rule in enumerate(rules, 1))
|
|
168
|
+
return f"""\
|
|
169
|
+
# Role
|
|
170
|
+
|
|
171
|
+
{ROLE}
|
|
172
|
+
|
|
173
|
+
# The request
|
|
174
|
+
|
|
175
|
+
The request follows verbatim between the markers. It is the whole requirement.
|
|
176
|
+
|
|
177
|
+
<<<REQUEST
|
|
178
|
+
{request}{'' if request.endswith(chr(10)) else chr(10)}REQUEST>>>
|
|
179
|
+
|
|
180
|
+
# Decomposition rules
|
|
181
|
+
|
|
182
|
+
{numbered}
|
|
183
|
+
|
|
184
|
+
# Reply format
|
|
185
|
+
|
|
186
|
+
Reply with exactly one fenced block whose opening line is ```forge-plan and whose body is one
|
|
187
|
+
JSON object with exactly the key `tasks`: a list of 1 to {MAX_TASKS} objects, each with exactly
|
|
188
|
+
these keys and no others:
|
|
189
|
+
|
|
190
|
+
- `id`: lowercase slug matching `^[a-z0-9][a-z0-9-]{{0,39}}$`, unique in the plan;
|
|
191
|
+
- `deps`: list of ids of tasks that must land first (`[]` for none), no cycles;
|
|
192
|
+
- `difficulty`: `low`, `medium` or `high`;
|
|
193
|
+
- `files`: non-empty list of repo-relative paths the task creates or edits (no absolute path, no
|
|
194
|
+
`..`, no tab, comma or newline in a path);
|
|
195
|
+
- `title`: one line without a tab;
|
|
196
|
+
- `approach`: a few lines on the intended shape (a string; `""` for none);
|
|
197
|
+
- `prompt`: the task's full instruction, ending with a `## Acceptance criteria` section.
|
|
198
|
+
|
|
199
|
+
Put no other `forge-plan` block in the reply. Text outside the block is ignored. Anything that
|
|
200
|
+
breaks these rules makes the whole reply refused; nothing is repaired. A valid reply:
|
|
201
|
+
|
|
202
|
+
{EXAMPLE}
|
|
203
|
+
"""
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def cmd_prompt(args) -> int:
|
|
207
|
+
plan = plan_dir(args)
|
|
208
|
+
request = read_text(args.goal_file, 'goal file')
|
|
209
|
+
out = plan / 'planner.prompt'
|
|
210
|
+
write_atomic(out, build_prompt(request, args.level))
|
|
211
|
+
print(out)
|
|
212
|
+
return 0
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
# --- parse ---------------------------------------------------------------------------------
|
|
216
|
+
|
|
217
|
+
def extract_block(reply: str) -> str:
|
|
218
|
+
# Split on \n only: str.splitlines() would also cut at U+2028 and friends, which are legal
|
|
219
|
+
# inside a JSON string. A trailing \r (CRLF replies) is ignored when matching the fences.
|
|
220
|
+
lines = reply.split('\n')
|
|
221
|
+
openings = [i for i, line in enumerate(lines) if OPEN_RE.match(line.rstrip('\r'))]
|
|
222
|
+
if not openings:
|
|
223
|
+
raise Refusal('no forge-plan block in the reply')
|
|
224
|
+
if len(openings) > 1:
|
|
225
|
+
raise Refusal(f'{len(openings)} forge-plan blocks in the reply; exactly one is allowed')
|
|
226
|
+
for j in range(openings[0] + 1, len(lines)):
|
|
227
|
+
if CLOSE_RE.match(lines[j].rstrip('\r')):
|
|
228
|
+
return '\n'.join(lines[openings[0] + 1:j])
|
|
229
|
+
raise Refusal('the forge-plan block is never closed')
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def no_duplicate_keys(pairs):
|
|
233
|
+
keys = [k for k, _ in pairs]
|
|
234
|
+
for k in keys:
|
|
235
|
+
if keys.count(k) > 1:
|
|
236
|
+
raise Refusal(f'duplicate key {k!r} in the JSON')
|
|
237
|
+
return dict(pairs)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def check_keys(obj, expected, where: str):
|
|
241
|
+
if not isinstance(obj, dict):
|
|
242
|
+
raise Refusal(f'{where} is not a JSON object')
|
|
243
|
+
missing = [k for k in expected if k not in obj]
|
|
244
|
+
extra = [k for k in obj if k not in expected]
|
|
245
|
+
if missing or extra:
|
|
246
|
+
parts = []
|
|
247
|
+
if missing:
|
|
248
|
+
parts.append('missing ' + ', '.join(missing))
|
|
249
|
+
if extra:
|
|
250
|
+
parts.append('unexpected ' + ', '.join(extra))
|
|
251
|
+
raise Refusal(f'{where} must have exactly the keys {", ".join(expected)} ({"; ".join(parts)})')
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def has_acceptance_heading(prompt: str) -> bool:
|
|
255
|
+
"""True when a `## Acceptance criteria` heading line stands outside any fenced code block."""
|
|
256
|
+
fence = None
|
|
257
|
+
for line in prompt.split('\n'):
|
|
258
|
+
line = line.rstrip('\r')
|
|
259
|
+
found = FENCE_RE.match(line)
|
|
260
|
+
if fence is None:
|
|
261
|
+
if found and not (found.group(1)[0] == '`' and '`' in found.group(2)):
|
|
262
|
+
fence = (found.group(1)[0], len(found.group(1)))
|
|
263
|
+
elif ACCEPTANCE_RE.fullmatch(line):
|
|
264
|
+
return True
|
|
265
|
+
elif (found and found.group(1)[0] == fence[0] and len(found.group(1)) >= fence[1]
|
|
266
|
+
and not found.group(2).strip()):
|
|
267
|
+
fence = None
|
|
268
|
+
return False
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def check_text(value, where: str):
|
|
272
|
+
"""Refuse a string that cannot be written as UTF-8 (a lone surrogate from a \\ud800 escape)."""
|
|
273
|
+
try:
|
|
274
|
+
value.encode('utf-8')
|
|
275
|
+
except UnicodeEncodeError:
|
|
276
|
+
raise Refusal(f'{where}: holds a character that is not valid Unicode (a lone surrogate)')
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def check_path(path, where: str):
|
|
280
|
+
if not isinstance(path, str) or not path:
|
|
281
|
+
raise Refusal(f'{where}: a file is not a non-empty string: {path!r}')
|
|
282
|
+
if ',' in path or LINE_BREAKS_RE.search(path):
|
|
283
|
+
raise Refusal(f'{where}: file {path!r} holds a tab, comma, newline or control character')
|
|
284
|
+
check_text(path, where)
|
|
285
|
+
if path.startswith('/') or path.startswith('\\') or re.match(r'^[A-Za-z]:', path):
|
|
286
|
+
raise Refusal(f'{where}: file {path!r} is an absolute path')
|
|
287
|
+
if '..' in re.split(r'[\\/]', path):
|
|
288
|
+
raise Refusal(f'{where}: file {path!r} has a .. component')
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def check_task(task, index: int, seen: set) -> dict:
|
|
292
|
+
where = f'task {index + 1}'
|
|
293
|
+
check_keys(task, TASK_KEYS, where)
|
|
294
|
+
tid = task['id']
|
|
295
|
+
if not isinstance(tid, str) or not ID_RE.fullmatch(tid):
|
|
296
|
+
raise Refusal(f'{where}: id {tid!r} does not match ^[a-z0-9][a-z0-9-]{{0,39}}$')
|
|
297
|
+
where = f'task {tid}'
|
|
298
|
+
if tid in seen:
|
|
299
|
+
raise Refusal(f'{where}: duplicate id')
|
|
300
|
+
seen.add(tid)
|
|
301
|
+
deps = task['deps']
|
|
302
|
+
if not isinstance(deps, list) or not all(isinstance(d, str) for d in deps):
|
|
303
|
+
raise Refusal(f'{where}: deps is not a list of ids')
|
|
304
|
+
if len(set(deps)) != len(deps):
|
|
305
|
+
raise Refusal(f'{where}: deps repeats an id')
|
|
306
|
+
if task['difficulty'] not in DIFFICULTIES:
|
|
307
|
+
raise Refusal(f'{where}: difficulty {task["difficulty"]!r} is not low, medium or high')
|
|
308
|
+
files = task['files']
|
|
309
|
+
if not isinstance(files, list) or not files:
|
|
310
|
+
raise Refusal(f'{where}: files is not a non-empty list')
|
|
311
|
+
for path in files:
|
|
312
|
+
check_path(path, where)
|
|
313
|
+
title = task['title']
|
|
314
|
+
if not isinstance(title, str) or not title.strip() or LINE_BREAKS_RE.search(title):
|
|
315
|
+
raise Refusal(f'{where}: title is not one non-empty line without a tab')
|
|
316
|
+
check_text(title, where)
|
|
317
|
+
if not isinstance(task['approach'], str):
|
|
318
|
+
raise Refusal(f'{where}: approach is not a string')
|
|
319
|
+
check_text(task['approach'], where)
|
|
320
|
+
prompt = task['prompt']
|
|
321
|
+
if not isinstance(prompt, str) or not prompt.strip():
|
|
322
|
+
raise Refusal(f'{where}: prompt is empty')
|
|
323
|
+
check_text(prompt, where)
|
|
324
|
+
if not has_acceptance_heading(prompt):
|
|
325
|
+
raise Refusal(f'{where}: prompt has no "## Acceptance criteria" heading')
|
|
326
|
+
return task
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def check_graph(tasks: list):
|
|
330
|
+
ids = {t['id'] for t in tasks}
|
|
331
|
+
for t in tasks:
|
|
332
|
+
for dep in t['deps']:
|
|
333
|
+
if dep not in ids:
|
|
334
|
+
raise Refusal(f'task {t["id"]}: unknown dep {dep!r}')
|
|
335
|
+
deps = {t['id']: t['deps'] for t in tasks}
|
|
336
|
+
state: dict = {}
|
|
337
|
+
|
|
338
|
+
def visit(node, path):
|
|
339
|
+
state[node] = 1
|
|
340
|
+
for nxt in deps[node]:
|
|
341
|
+
if state.get(nxt) == 1:
|
|
342
|
+
cycle = path[path.index(nxt):] + [nxt] if nxt in path else [node, nxt]
|
|
343
|
+
raise Refusal('dependency cycle: ' + ' -> '.join(cycle))
|
|
344
|
+
if nxt not in state:
|
|
345
|
+
visit(nxt, path + [nxt])
|
|
346
|
+
state[node] = 2
|
|
347
|
+
|
|
348
|
+
for t in tasks:
|
|
349
|
+
if t['id'] not in state:
|
|
350
|
+
visit(t['id'], [t['id']])
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def parse_reply(reply: str) -> list:
|
|
354
|
+
body = extract_block(reply)
|
|
355
|
+
try:
|
|
356
|
+
data = json.loads(body, object_pairs_hook=no_duplicate_keys)
|
|
357
|
+
except (ValueError, RecursionError) as err:
|
|
358
|
+
# JSONDecodeError is a ValueError; so is Python's limit on integer digits. Nesting deeper
|
|
359
|
+
# than the interpreter allows raises RecursionError.
|
|
360
|
+
raise Refusal(f'the forge-plan body is not valid JSON: {type(err).__name__}: {str(err)[:200]}')
|
|
361
|
+
check_keys(data, ('tasks',), 'the forge-plan body')
|
|
362
|
+
tasks = data['tasks']
|
|
363
|
+
if not isinstance(tasks, list) or not 1 <= len(tasks) <= MAX_TASKS:
|
|
364
|
+
count = f' ({len(tasks)})' if isinstance(tasks, list) else ''
|
|
365
|
+
raise Refusal(f'tasks must be a list of 1 to {MAX_TASKS} objects{count}')
|
|
366
|
+
seen: set = set()
|
|
367
|
+
checked = [check_task(t, i, seen) for i, t in enumerate(tasks)]
|
|
368
|
+
check_graph(checked)
|
|
369
|
+
return checked
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def cmd_parse(args) -> int:
|
|
373
|
+
plan = plan_dir(args)
|
|
374
|
+
request_path = plan / 'request.md'
|
|
375
|
+
if not request_path.is_file():
|
|
376
|
+
die(f'{request_path} is missing; it holds the user\'s request')
|
|
377
|
+
request = read_text(request_path, 'request')
|
|
378
|
+
reply = read_text(args.reply, 'reply')
|
|
379
|
+
try:
|
|
380
|
+
tasks = parse_reply(reply)
|
|
381
|
+
except Refusal as err:
|
|
382
|
+
# A key or path may hold a lone surrogate; escape it so the reason can be written and printed.
|
|
383
|
+
reason = str(err).encode('utf-8', 'backslashreplace').decode('utf-8')
|
|
384
|
+
reply_path = str(args.reply).encode('utf-8', 'backslashreplace').decode('utf-8')
|
|
385
|
+
write_atomic(plan / 'planner.refused', f'{reason}\nreply: {reply_path}\n')
|
|
386
|
+
print(f'planner reply refused: {reason}')
|
|
387
|
+
print(f'reply: {reply_path}')
|
|
388
|
+
return 4
|
|
389
|
+
# Everything is encoded before the first file is written, so a text that cannot be written
|
|
390
|
+
# cannot leave half a plan behind.
|
|
391
|
+
rows = [TSV_HEADER] + ['\t'.join([
|
|
392
|
+
t['id'], ','.join(t['deps']) or '-', t['difficulty'], ','.join(t['files']), '-', '-', t['title'],
|
|
393
|
+
]) for t in tasks]
|
|
394
|
+
outputs = []
|
|
395
|
+
for t in tasks:
|
|
396
|
+
folder = plan / 'tasks' / t['id']
|
|
397
|
+
text = t['prompt'].rstrip('\n') + f'\n\n{WHOLE_REQUEST}\n\n' + request
|
|
398
|
+
outputs.append((folder / 'prompt.md', text.encode('utf-8')))
|
|
399
|
+
outputs.append((folder / 'approach.md', t['approach'].encode('utf-8') if t['approach'].strip() else None))
|
|
400
|
+
outputs.append((plan / 'tasks.tsv', ('\n'.join(rows) + '\n').encode('utf-8')))
|
|
401
|
+
for path, data in outputs:
|
|
402
|
+
if data is None:
|
|
403
|
+
path.unlink(missing_ok=True) # an empty approach must not keep an older one alive
|
|
404
|
+
else:
|
|
405
|
+
write_atomic(path, data)
|
|
406
|
+
(plan / 'planner.refused').unlink(missing_ok=True)
|
|
407
|
+
return 0
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
# --- gate ----------------------------------------------------------------------------------
|
|
411
|
+
|
|
412
|
+
def cmd_gate(args) -> int:
|
|
413
|
+
plan = plan_dir(args)
|
|
414
|
+
request = read_text(args.goal_file, 'goal file')
|
|
415
|
+
chars = len(request)
|
|
416
|
+
requirements = len(split_requirements(request))
|
|
417
|
+
paths = len(set(PATH_RE.findall(request)))
|
|
418
|
+
decision = 'one-task' if chars <= MAX_CHARS and requirements <= MAX_REQUIREMENTS else 'plan'
|
|
419
|
+
record = {'decision': decision,
|
|
420
|
+
'signals': {'chars': chars, 'requirements': requirements, 'paths': paths},
|
|
421
|
+
'thresholds': {'chars': MAX_CHARS, 'requirements': MAX_REQUIREMENTS},
|
|
422
|
+
'rule': 'size'}
|
|
423
|
+
write_atomic(plan / 'plan-gate.json', json.dumps(record, indent=2) + '\n')
|
|
424
|
+
print(decision)
|
|
425
|
+
return 0
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
# --- one-task ------------------------------------------------------------------------------
|
|
429
|
+
|
|
430
|
+
def request_title(request: str) -> str:
|
|
431
|
+
for line in request.splitlines():
|
|
432
|
+
line = line.strip()
|
|
433
|
+
if line:
|
|
434
|
+
title = LINE_BREAKS_RE.sub(' ', re.sub(r'^#+\s*', '', line)).strip()
|
|
435
|
+
return title[:80] or 'task'
|
|
436
|
+
return ''
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def cmd_one_task(args) -> int:
|
|
440
|
+
plan = plan_dir(args)
|
|
441
|
+
request = read_text(args.goal_file, 'goal file')
|
|
442
|
+
title = request_title(request)
|
|
443
|
+
if not title:
|
|
444
|
+
die(f'goal file {args.goal_file} is empty')
|
|
445
|
+
# The request stays a verbatim prefix; only a missing final newline is supplied.
|
|
446
|
+
prompt = (request + ('' if request.endswith('\n') else '\n')
|
|
447
|
+
+ f'\n## Acceptance criteria\n\n{ONE_TASK_CRITERION}\n')
|
|
448
|
+
write_atomic(plan / 'tasks' / 'task' / 'prompt.md', prompt)
|
|
449
|
+
row = '\t'.join(['task', '-', args.difficulty, '.', '-', '-', title])
|
|
450
|
+
write_atomic(plan / 'tasks.tsv', TSV_HEADER + '\n' + row + '\n')
|
|
451
|
+
return 0
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def main(argv=None) -> int:
|
|
455
|
+
ap = argparse.ArgumentParser(prog='forge-planner.py', description=__doc__.split('\n')[0])
|
|
456
|
+
sub = ap.add_subparsers(dest='cmd', required=True)
|
|
457
|
+
p = sub.add_parser('prompt', help='write the planner prompt')
|
|
458
|
+
p.add_argument('--plan', required=True)
|
|
459
|
+
p.add_argument('--goal-file', required=True)
|
|
460
|
+
p.add_argument('--level', choices=LEVELS)
|
|
461
|
+
p.set_defaults(fn=cmd_prompt)
|
|
462
|
+
p = sub.add_parser('parse', help='strictly parse a planner reply into a plan')
|
|
463
|
+
p.add_argument('--plan', required=True)
|
|
464
|
+
p.add_argument('--reply', required=True)
|
|
465
|
+
p.set_defaults(fn=cmd_parse)
|
|
466
|
+
p = sub.add_parser('gate', help='decide whether the request needs a planner')
|
|
467
|
+
p.add_argument('--plan', required=True)
|
|
468
|
+
p.add_argument('--goal-file', required=True)
|
|
469
|
+
p.set_defaults(fn=cmd_gate)
|
|
470
|
+
p = sub.add_parser('one-task', help='write a one-task plan without a planner')
|
|
471
|
+
p.add_argument('--plan', required=True)
|
|
472
|
+
p.add_argument('--goal-file', required=True)
|
|
473
|
+
p.add_argument('--difficulty', choices=DIFFICULTIES, default='medium')
|
|
474
|
+
p.set_defaults(fn=cmd_one_task)
|
|
475
|
+
args = ap.parse_args(argv)
|
|
476
|
+
return args.fn(args)
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
if __name__ == '__main__':
|
|
480
|
+
raise SystemExit(main())
|
package/scripts/forge-route.py
CHANGED
|
@@ -16,6 +16,12 @@ bias (inverse-propensity weighting needs the probability each choice had).
|
|
|
16
16
|
<plan>/tasks/<id>/route.jsonl (never rewritten) and marks a changed pick in tasks/<id>/route.explored for the table. A row
|
|
17
17
|
with no neighbour is not explored and records nothing.
|
|
18
18
|
|
|
19
|
+
forge-route.py assign --plan P --task ID --tier T --default SPEC --pools FILE [--epsilon E]
|
|
20
|
+
Called by `plan` for each row it resolves (one the user left to forge): `explore` above when E is
|
|
21
|
+
above 0, then tasks/<id>/running.tier for the spec it prints, with the tier of that pick (T, or the
|
|
22
|
+
neighbour's tier an exploration chose). A re-plan that re-resolves a row thus replaces whatever an
|
|
23
|
+
older escalation or pin recorded (#106); a row whose dwarf the plan keeps is never assigned.
|
|
24
|
+
|
|
19
25
|
forge-route.py escalation --plan P --task ID [--check] [--qa-only-next yes|no]
|
|
20
26
|
The retry policy: after <plan>/escalate_after (default 3; 0 = off) failed attempts on
|
|
21
27
|
one spec, the next attempt goes to the next tier up of the user's pools instead of
|
|
@@ -42,8 +48,8 @@ bias (inverse-propensity weighting needs the probability each choice had).
|
|
|
42
48
|
|
|
43
49
|
forge-route.py fallback --plan P --task ID [--exclude harness/model,...]
|
|
44
50
|
The lateral move of an infrastructure stop: prints the next free model of the pool of the
|
|
45
|
-
tier the task runs in (
|
|
46
|
-
|
|
51
|
+
tier the task runs in (the newest record of it: see running_tier), or exits 1 when there is none.
|
|
52
|
+
Never a model of another tier.
|
|
47
53
|
The move is recorded by `lateral` below, not as an escalation.
|
|
48
54
|
|
|
49
55
|
forge-route.py qa-fallback --plan P --task ID [--exclude harness/model,...]
|
|
@@ -56,7 +62,7 @@ bias (inverse-propensity weighting needs the probability each choice had).
|
|
|
56
62
|
forge-route.py record --plan P --task ID (--probe | --line TEXT)
|
|
57
63
|
Internal. Probe or append tasks/<id>/escalations.tsv through forge-control.py, which
|
|
58
64
|
walks from the plan one directory at a time and refuses a symlink at any component.
|
|
59
|
-
An appended row also writes tasks/<id>/running.tier: its target tier and
|
|
65
|
+
An appended row also writes tasks/<id>/running.tier: its target tier, spec and time.
|
|
60
66
|
`--probe` exits 0 when every component below the plan is a real directory and the file
|
|
61
67
|
is absent or a regular file. `--line` appends one record under those same conditions.
|
|
62
68
|
A missing parent exits 1 and writes nothing: the walk has no directory descriptor then,
|
|
@@ -369,31 +375,46 @@ def escalation_target(source: str, frm: str, to: str, running: str, pools: dict,
|
|
|
369
375
|
|
|
370
376
|
def running_tier(plan: Path, task: str, current: str = '') -> str:
|
|
371
377
|
"""The tier a task runs in, from what forge recorded when it assigned the model, never from which
|
|
372
|
-
pools list the model: one model can sit in several, and a re-plan can change them.
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
378
|
+
pools list the model: one model can sit in several, and a re-plan can change them. Two records
|
|
379
|
+
say it, each with its time: tasks/<id>/running.tier, written at every assignment (the plan's
|
|
380
|
+
resolution of the row, an escalation, a pin, `retry --dwarf`, a lateral move), and the last
|
|
381
|
+
exploration decision in route.jsonl, all an older plan has. The newer one counts, and only while
|
|
382
|
+
the task still runs its spec: an older record never beats a newer pick of the same model (#106).
|
|
383
|
+
With neither, or when the newest is for another spec (the table was edited by hand), the
|
|
384
|
+
difficulty. `current` is the spec the task runs, read from tasks.tsv when not given. '' when the
|
|
385
|
+
difficulty is no tier."""
|
|
377
386
|
tier = _row_cell(plan, task, 2)
|
|
378
387
|
if tier not in TIERS:
|
|
379
388
|
return ''
|
|
380
389
|
tdir = plan / 'tasks' / task
|
|
381
390
|
current = current or _dwarf_of(plan, task)
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
391
|
+
records = []
|
|
392
|
+
with contextlib.suppress(OSError, ValueError):
|
|
393
|
+
path = tdir / 'running.tier'
|
|
394
|
+
cells = path.read_text().strip().split('\t')
|
|
395
|
+
if len(cells) > 1 and cells[0] in TIERS:
|
|
396
|
+
# Written before records carried their time (forge 0.14): as old as the file.
|
|
397
|
+
records.append((float(cells[2]) if len(cells) > 2 else path.stat().st_mtime, cells[1], cells[0]))
|
|
398
|
+
with contextlib.suppress(OSError, ValueError, AttributeError, TypeError):
|
|
387
399
|
lines = (tdir / 'route.jsonl').read_text().splitlines()
|
|
388
400
|
decision = json.loads(lines[-1]) if lines else {}
|
|
389
|
-
if decision.get('
|
|
390
|
-
|
|
401
|
+
if decision.get('chosen_tier') in TIERS:
|
|
402
|
+
records.append((float(decision.get('at') or 0), decision.get('chosen'), decision['chosen_tier']))
|
|
403
|
+
if records:
|
|
404
|
+
_, spec, recorded = max(records, key=lambda record: record[0])
|
|
405
|
+
if spec == current:
|
|
406
|
+
return recorded
|
|
391
407
|
return tier
|
|
392
408
|
|
|
393
409
|
|
|
410
|
+
def write_running_tier(plan: str, task: str, tier: str, spec: str, control) -> None:
|
|
411
|
+
"""tasks/<id>/running.tier: `tier<TAB>spec<TAB>time`, the tier the task runs in while it runs `spec`."""
|
|
412
|
+
control.write_atomic(plan, 'tasks/%s/running.tier' % task, '%s\t%s\t%.6f\n' % (tier, spec, time.time()))
|
|
413
|
+
|
|
414
|
+
|
|
394
415
|
def record_running_tier(plan: str, task: str, row: str, control) -> None:
|
|
395
|
-
"""tasks/<id>/running.tier for an escalations.tsv row:
|
|
396
|
-
|
|
416
|
+
"""tasks/<id>/running.tier for an escalations.tsv row: the tier the row moved the task to, decided
|
|
417
|
+
here with the pools of this moment. A fallback stays in its tier."""
|
|
397
418
|
cells = row.rstrip('\n').split('\t')
|
|
398
419
|
frm, to, source = cells[2], cells[3], cells[4] if len(cells) > 4 else 'policy'
|
|
399
420
|
tier = running_tier(Path(plan), task, frm)
|
|
@@ -401,7 +422,7 @@ def record_running_tier(plan: str, task: str, row: str, control) -> None:
|
|
|
401
422
|
tier = escalation_target(source, frm, to, tier, load_pools(Path(plan) / 'fractal-routing.json'),
|
|
402
423
|
registry_models())
|
|
403
424
|
if tier:
|
|
404
|
-
|
|
425
|
+
write_running_tier(plan, task, tier, to, control)
|
|
405
426
|
|
|
406
427
|
|
|
407
428
|
def fallback(args) -> int:
|
|
@@ -433,13 +454,14 @@ def qa_fallback(args) -> int:
|
|
|
433
454
|
|
|
434
455
|
# --- exploration -------------------------------------------------------------------
|
|
435
456
|
|
|
436
|
-
def explore(args) ->
|
|
457
|
+
def explore(args) -> tuple:
|
|
458
|
+
"""(spec, tier): the pick and the tier it was picked from."""
|
|
437
459
|
epsilon = float(args.epsilon)
|
|
438
460
|
if not 0 < epsilon <= 1:
|
|
439
|
-
return args.default
|
|
461
|
+
return args.default, args.tier
|
|
440
462
|
alternative, alternative_tier = neighbour(args.default, args.tier, load_pools(args.pools), registry_models())
|
|
441
463
|
if not alternative:
|
|
442
|
-
return args.default
|
|
464
|
+
return args.default, args.tier
|
|
443
465
|
candidates = [args.default, alternative]
|
|
444
466
|
rng = rng_for(args.task)
|
|
445
467
|
draw = rng.random()
|
|
@@ -460,6 +482,26 @@ def explore(args) -> str:
|
|
|
460
482
|
marker.write_text(chosen + '\n')
|
|
461
483
|
elif marker.exists():
|
|
462
484
|
marker.unlink()
|
|
485
|
+
return chosen, decision['chosen_tier']
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def assign(args) -> str:
|
|
489
|
+
"""`plan`'s resolution of a row: the exploration draw, then the record of the tier its pick runs in,
|
|
490
|
+
newer than any record it replaces. A record that cannot be written is removed rather than left to
|
|
491
|
+
speak for the new pick. Prints the pick; any failure prints SPEC, as explore does."""
|
|
492
|
+
chosen, tier = args.default, args.tier
|
|
493
|
+
with contextlib.suppress(Exception):
|
|
494
|
+
chosen, tier = explore(args)
|
|
495
|
+
try:
|
|
496
|
+
control = _load_control()
|
|
497
|
+
plan = os.path.realpath(args.plan)
|
|
498
|
+
try:
|
|
499
|
+
write_running_tier(plan, args.task, tier, chosen, control)
|
|
500
|
+
except Exception as error:
|
|
501
|
+
print('%s: could not record the tier it runs in: %s' % (args.task, error), file=sys.stderr)
|
|
502
|
+
control.remove_safe(plan, 'tasks/%s/running.tier' % args.task)
|
|
503
|
+
except Exception:
|
|
504
|
+
pass
|
|
463
505
|
return chosen
|
|
464
506
|
|
|
465
507
|
|
|
@@ -968,7 +1010,7 @@ def record_lateral_tier(plan: str, task: str, row: str, control) -> None:
|
|
|
968
1010
|
frm, to = cells[3], cells[4]
|
|
969
1011
|
tier = running_tier(Path(plan), task, frm)
|
|
970
1012
|
if tier:
|
|
971
|
-
|
|
1013
|
+
write_running_tier(plan, task, tier, to, control)
|
|
972
1014
|
|
|
973
1015
|
|
|
974
1016
|
def main(argv=None) -> int:
|
|
@@ -977,6 +1019,10 @@ def main(argv=None) -> int:
|
|
|
977
1019
|
p = sub.add_parser('explore')
|
|
978
1020
|
for name in ('plan', 'task', 'tier', 'epsilon', 'default', 'pools'):
|
|
979
1021
|
p.add_argument('--' + name, required=True)
|
|
1022
|
+
p = sub.add_parser('assign', help="plan's resolution of a row: exploration, then the record of its tier")
|
|
1023
|
+
for name in ('plan', 'task', 'tier', 'default', 'pools'):
|
|
1024
|
+
p.add_argument('--' + name, required=True)
|
|
1025
|
+
p.add_argument('--epsilon', default='0')
|
|
980
1026
|
p = sub.add_parser('escalation')
|
|
981
1027
|
p.add_argument('--plan', required=True)
|
|
982
1028
|
p.add_argument('--task', required=True)
|
|
@@ -1004,10 +1050,13 @@ def main(argv=None) -> int:
|
|
|
1004
1050
|
args = ap.parse_args(argv)
|
|
1005
1051
|
if args.command == 'explore':
|
|
1006
1052
|
try:
|
|
1007
|
-
print(explore(args))
|
|
1053
|
+
print(explore(args)[0])
|
|
1008
1054
|
except Exception:
|
|
1009
1055
|
print(args.default)
|
|
1010
1056
|
return 0
|
|
1057
|
+
if args.command == 'assign':
|
|
1058
|
+
print(assign(args))
|
|
1059
|
+
return 0
|
|
1011
1060
|
if args.command == 'record':
|
|
1012
1061
|
return record_escalation(args)
|
|
1013
1062
|
if args.command == 'lateral':
|