@giamme/forge 0.14.1 → 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 +17 -0
- package/SKILL.md +47 -14
- package/VERSION +1 -1
- package/docs/commands.md +288 -6
- package/docs/models.md +53 -0
- package/package.json +1 -1
- package/references/dataset.md +12 -3
- package/references/decompose.md +103 -4
- package/references/harnesses.md +17 -0
- 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 +56 -2
- 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 +565 -21
- package/scripts/forge-plan-check.py +591 -8
- package/scripts/forge-planner.py +480 -0
- package/scripts/forge-runtime.py +86 -0
- 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-runtime.py
CHANGED
|
@@ -264,6 +264,84 @@ def session_id(log: str, harness: str) -> str | None:
|
|
|
264
264
|
return result_id if type(result_id) is str else None
|
|
265
265
|
|
|
266
266
|
|
|
267
|
+
_TIER_UNSUPPORTED = 'is not advertised as supported for model'
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def read_speed(log: str, harness: str) -> tuple[str | None, str | None]:
|
|
271
|
+
"""The speed the harness actually ran at, and why it was not fast.
|
|
272
|
+
|
|
273
|
+
claude: `usage.speed` of the last result, and `fast_mode_disabled_reason` when
|
|
274
|
+
that speed is not `fast`. codex: `default` and the error message when an
|
|
275
|
+
`item.completed` error says the tier is not advertised for the model; otherwise
|
|
276
|
+
the stream says nothing. Any other harness, or a log that does not say, is unknown.
|
|
277
|
+
"""
|
|
278
|
+
if harness == 'codex':
|
|
279
|
+
reason = None
|
|
280
|
+
for event in _events(log)[0]:
|
|
281
|
+
if event.get('type') != 'item.completed':
|
|
282
|
+
continue
|
|
283
|
+
item = event.get('item')
|
|
284
|
+
if not isinstance(item, dict) or item.get('type') != 'error':
|
|
285
|
+
continue
|
|
286
|
+
message = item.get('message')
|
|
287
|
+
if isinstance(message, str) and _TIER_UNSUPPORTED in message:
|
|
288
|
+
reason = message
|
|
289
|
+
return ('default', reason) if reason else (None, None)
|
|
290
|
+
if harness != 'claude':
|
|
291
|
+
return None, None
|
|
292
|
+
speed = reason = None
|
|
293
|
+
saw = False
|
|
294
|
+
for event in _events(log)[0]:
|
|
295
|
+
if event.get('type') != 'result':
|
|
296
|
+
continue
|
|
297
|
+
saw = True
|
|
298
|
+
usage = event.get('usage')
|
|
299
|
+
value = usage.get('speed') if isinstance(usage, dict) else None
|
|
300
|
+
speed = value if isinstance(value, str) and value else None
|
|
301
|
+
disabled = event.get('fast_mode_disabled_reason')
|
|
302
|
+
reason = disabled if isinstance(disabled, str) and disabled else None
|
|
303
|
+
if not saw or not speed:
|
|
304
|
+
return None, None
|
|
305
|
+
if speed == 'fast':
|
|
306
|
+
return speed, None
|
|
307
|
+
return speed, reason
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def speed_note(harness: str, asked: str | None, speed: str | None, reason: str | None) -> str | None:
|
|
311
|
+
"""The one line to print when `asked` is fast and the log ran slower, else None."""
|
|
312
|
+
if asked != 'fast' or not speed or speed == 'fast':
|
|
313
|
+
return None
|
|
314
|
+
if harness == 'claude' and reason:
|
|
315
|
+
return '%s ran at %s speed: fast mode is unavailable (%s)' % (harness, speed, reason)
|
|
316
|
+
if reason:
|
|
317
|
+
return '%s ran at %s speed: %s' % (harness, speed, reason)
|
|
318
|
+
return '%s ran at %s speed' % (harness, speed)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _resolved_service_tier(root: Path, role: str) -> str | None:
|
|
322
|
+
path = root / (role + '.resolved')
|
|
323
|
+
if not path.exists():
|
|
324
|
+
return None
|
|
325
|
+
found = None
|
|
326
|
+
prefix = 'service_tier='
|
|
327
|
+
for line in path.read_text(errors='replace').splitlines():
|
|
328
|
+
if line.startswith(prefix):
|
|
329
|
+
found = line[len(prefix):].strip() or None
|
|
330
|
+
return found
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def speed_command(log: str, harness: str) -> None:
|
|
334
|
+
"""Print the slower-speed note for a log, or nothing. Exit stays 0."""
|
|
335
|
+
try:
|
|
336
|
+
text = Path(log).read_text(errors='replace')
|
|
337
|
+
except OSError:
|
|
338
|
+
return
|
|
339
|
+
speed, reason = read_speed(text, harness)
|
|
340
|
+
note = speed_note(harness, 'fast', speed, reason)
|
|
341
|
+
if note:
|
|
342
|
+
print(note)
|
|
343
|
+
|
|
344
|
+
|
|
267
345
|
def finish(attempt: str, root: str, role: str, harness: str, rc: str) -> None:
|
|
268
346
|
try:
|
|
269
347
|
_finish(Path(attempt), Path(root), role, harness, rc)
|
|
@@ -279,6 +357,7 @@ def _finish(attempt: Path, root: Path, role: str, harness: str, rc: str) -> None
|
|
|
279
357
|
text = log.read_text(errors='replace') if structured and log.exists() else ''
|
|
280
358
|
final, usage = extract(text, harness)
|
|
281
359
|
found = session_id(text, harness)
|
|
360
|
+
speed, speed_reason = read_speed(text, harness)
|
|
282
361
|
if not last.exists() or not last.stat().st_size:
|
|
283
362
|
if final is not None:
|
|
284
363
|
last.write_text(final + '\n')
|
|
@@ -292,6 +371,9 @@ def _finish(attempt: Path, root: Path, role: str, harness: str, rc: str) -> None
|
|
|
292
371
|
harness=harness,
|
|
293
372
|
prompt_bytes=prompt.stat().st_size if prompt_ready else None,
|
|
294
373
|
session_id=found,
|
|
374
|
+
service_tier=_resolved_service_tier(root, role),
|
|
375
|
+
speed=speed,
|
|
376
|
+
speed_reason=speed_reason,
|
|
295
377
|
**usage,
|
|
296
378
|
)
|
|
297
379
|
infra = root / (role + '.infra')
|
|
@@ -761,6 +843,10 @@ def main() -> None:
|
|
|
761
843
|
settle(*args)
|
|
762
844
|
elif command == 'settled':
|
|
763
845
|
settled_command(*args)
|
|
846
|
+
elif command == 'speed':
|
|
847
|
+
if len(args) != 2:
|
|
848
|
+
raise ValueError('usage: forge-runtime.py speed LOG HARNESS')
|
|
849
|
+
speed_command(*args)
|
|
764
850
|
else:
|
|
765
851
|
raise ValueError('unknown runtime command: ' + command)
|
|
766
852
|
except (OSError, ValueError, RuntimeError) as error:
|
package/scripts/forge-shadow.py
CHANGED
|
@@ -11,7 +11,9 @@ turns this on for a sampled share of reviewed attempts (`--shadow-rate`, default
|
|
|
11
11
|
dir under <plan>/shadow/<id>/<attempt>-<k>/, reviews a byte-identical copy of the
|
|
12
12
|
primary's qa.input, and returns. Never exits nonzero.
|
|
13
13
|
forge-shadow.py preflight --plan P
|
|
14
|
-
Which listed shadow specs resolve here; writes <plan>/shadow_qa.ok.
|
|
14
|
+
Which listed shadow specs resolve here; writes <plan>/shadow_qa.ok. A spec that
|
|
15
|
+
cannot run here is skipped. A fast-tier refusal stops the run with dispatch's
|
|
16
|
+
own message and exit code, before any model call.
|
|
15
17
|
|
|
16
18
|
Guarantees, because the task waits for this process before it writes any status:
|
|
17
19
|
- nothing reads the shadow's result in the run path; it changes no status, memory,
|
|
@@ -49,6 +51,36 @@ STOP_WAIT_S = 10
|
|
|
49
51
|
PREPARE_TIMEOUT_S = 120
|
|
50
52
|
|
|
51
53
|
|
|
54
|
+
def plan_is_fractal(plan: Path) -> bool:
|
|
55
|
+
"""True when this plan's saved selection says Fractal runs the dispatches."""
|
|
56
|
+
try:
|
|
57
|
+
data = json.loads((plan / 'fractal-selection.json').read_text())
|
|
58
|
+
except (OSError, ValueError):
|
|
59
|
+
return False
|
|
60
|
+
return isinstance(data, dict) and bool(data.get('enabled'))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def service_tier_args(plan: Path, role: str) -> list[str]:
|
|
64
|
+
"""`--service-tier fast` when <role> is a line of <plan>/fast, and nothing otherwise.
|
|
65
|
+
|
|
66
|
+
Fractal dispatches through its own runner and does not take the option. A retry
|
|
67
|
+
preflights before that runner is selected, so a plan whose selection is already on
|
|
68
|
+
is the same case for every role it dispatches. A whole-run review is not one of them.
|
|
69
|
+
Specs never change.
|
|
70
|
+
"""
|
|
71
|
+
if os.environ.get('FORGE_FRACTAL_RUN'):
|
|
72
|
+
return []
|
|
73
|
+
try:
|
|
74
|
+
text = (plan / 'fast').read_text()
|
|
75
|
+
except OSError:
|
|
76
|
+
return []
|
|
77
|
+
if role not in [line.strip() for line in text.splitlines() if line.strip()]:
|
|
78
|
+
return []
|
|
79
|
+
if role != 'review' and plan_is_fractal(plan):
|
|
80
|
+
return []
|
|
81
|
+
return ['--service-tier', 'fast']
|
|
82
|
+
|
|
83
|
+
|
|
52
84
|
def rate_of(plan: Path) -> float:
|
|
53
85
|
try:
|
|
54
86
|
rate = float((plan / 'shadow_rate').read_text().strip())
|
|
@@ -207,6 +239,7 @@ def run(args) -> int:
|
|
|
207
239
|
'--output', 'summary']
|
|
208
240
|
if args.yolo:
|
|
209
241
|
argv.append('--yolo')
|
|
242
|
+
argv.extend(service_tier_args(plan, 'qa'))
|
|
210
243
|
with open(out / 'shadow.out', 'wb') as log:
|
|
211
244
|
STATE['child'] = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT,
|
|
212
245
|
env=env, close_fds=True)
|
|
@@ -269,16 +302,27 @@ def preflight(args) -> int:
|
|
|
269
302
|
ok = []
|
|
270
303
|
for spec in listed:
|
|
271
304
|
flags = ['--yolo'] if (plan / 'yolo_qa').exists() else []
|
|
305
|
+
flags.extend(service_tier_args(plan, 'qa'))
|
|
272
306
|
try:
|
|
273
307
|
result = subprocess.run(['/bin/bash', str(DISPATCH), 'doctor', '--spec', spec, '--role', 'qa', *flags],
|
|
274
|
-
stdout=subprocess.
|
|
275
|
-
good = result.returncode == 0
|
|
308
|
+
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=120, text=True)
|
|
276
309
|
except (OSError, subprocess.SubprocessError):
|
|
277
|
-
good = False
|
|
278
|
-
if good:
|
|
279
|
-
ok.append(spec)
|
|
280
|
-
else:
|
|
281
310
|
print('forge: shadow review spec %s is not usable here; it is skipped' % spec, file=sys.stderr)
|
|
311
|
+
continue
|
|
312
|
+
if result.returncode == 0:
|
|
313
|
+
ok.append(spec)
|
|
314
|
+
continue
|
|
315
|
+
# Dispatch refuses a fast tier the harness cannot take (exit 3) before it checks
|
|
316
|
+
# that the binary exists, and both failures share that exit. The message is how
|
|
317
|
+
# they differ. Re-emit it unchanged and stop: skipping the shadow would let the
|
|
318
|
+
# dwarf and the primary review run and be billed.
|
|
319
|
+
text = result.stdout or ''
|
|
320
|
+
if result.returncode == 3 and 'has no per-invocation fast tier' in text:
|
|
321
|
+
sys.stderr.write(text)
|
|
322
|
+
if text and not text.endswith('\n'):
|
|
323
|
+
sys.stderr.write('\n')
|
|
324
|
+
return 3
|
|
325
|
+
print('forge: shadow review spec %s is not usable here; it is skipped' % spec, file=sys.stderr)
|
|
282
326
|
write(plan / 'shadow_qa.ok', ','.join(ok) + '\n')
|
|
283
327
|
if listed and not ok:
|
|
284
328
|
print('forge: no shadow review spec is usable; shadow reviews are off for this run', file=sys.stderr)
|