@giamme/forge 0.14.1 → 0.16.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 +46 -0
- package/SKILL.md +47 -14
- package/VERSION +1 -1
- package/docs/artifacts.md +1 -1
- package/docs/commands.md +302 -9
- package/docs/forge-ui.md +14 -0
- package/docs/memory.md +22 -0
- package/docs/models.md +53 -0
- package/docs/reviews.md +7 -0
- package/forge +11 -0
- package/package.json +1 -1
- package/references/dataset.md +16 -4
- package/references/decompose.md +154 -9
- package/references/harnesses.md +21 -1
- package/references/planning.md +59 -0
- package/references/solo.md +5 -1
- package/references/ui.md +48 -1
- package/scripts/forge-artifact.sh +53 -0
- package/scripts/forge-compare.py +6 -3
- package/scripts/forge-config.py +531 -4
- package/scripts/forge-contract.py +55 -8
- package/scripts/forge-control.py +0 -2
- package/scripts/forge-dispatch.sh +84 -14
- package/scripts/forge-fail-first.py +3 -1
- package/scripts/forge-guard.py +247 -8
- package/scripts/forge-issues.py +12 -0
- package/scripts/forge-lib-adopt.sh +260 -0
- package/scripts/forge-lib-attribute.sh +10 -2
- package/scripts/forge-lib-plans.sh +35 -6
- package/scripts/forge-lib-review.sh +13 -5
- package/scripts/forge-lib-task.sh +138 -5
- package/scripts/forge-memory.sh +41 -4
- package/scripts/forge-metrics.sh +7 -0
- package/scripts/forge-parallel-options.sh +12 -6
- package/scripts/forge-parallel.sh +659 -32
- package/scripts/forge-plan-check.py +591 -8
- package/scripts/forge-planner.py +480 -0
- package/scripts/forge-route.py +16 -2
- package/scripts/forge-runs-rm.py +23 -7
- package/scripts/forge-runtime.py +111 -2
- package/scripts/forge-schedule.py +5 -2
- package/scripts/forge-shadow.py +53 -7
- package/scripts/forge-solo.sh +87 -7
- package/scripts/forge_dataset/cli.py +26 -0
- package/scripts/forge_dataset/efforts.py +215 -0
- package/scripts/forge_dataset/export.py +1 -0
- package/scripts/forge_dataset/harvest.py +55 -0
- package/scripts/forge_dataset/history.py +126 -0
- package/scripts/forge_dataset/worktrees.py +95 -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/scripts/forge_memory_list.py +153 -0
- package/scripts/forge_worktrees.py +88 -0
- package/ui/README.md +31 -0
- package/ui/docs/api.md +168 -12
- package/ui/forge_ui/__init__.py +14 -1
- package/ui/forge_ui/__main__.py +1 -1
- package/ui/forge_ui/control.py +250 -12
- package/ui/forge_ui/executions.py +28 -8
- package/ui/forge_ui/findings.py +7 -0
- package/ui/forge_ui/models.py +60 -1
- package/ui/forge_ui/projects.py +571 -0
- package/ui/forge_ui/reader.py +48 -8
- package/ui/forge_ui/static/app.js +99 -21
- package/ui/forge_ui/static/cloudui.js +6 -2
- package/ui/forge_ui/static/convo.js +1 -1
- package/ui/forge_ui/static/diffview.js +2 -2
- package/ui/forge_ui/static/files.js +1 -1
- package/ui/forge_ui/static/index.html +5 -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 +47 -4
- package/ui/forge_ui/static/projectsview.js +372 -0
- package/ui/forge_ui/static/settings.js +924 -29
- package/ui/forge_ui/static/style.css +116 -3
- package/ui/forge_ui/static/uikit.js +94 -1
- package/ui/forge_ui/static/worktreesview.js +250 -0
- package/ui/forge_ui/worktrees.py +570 -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
|
@@ -647,6 +647,19 @@ def attempt_rows(tdir: Path) -> list:
|
|
|
647
647
|
return rows
|
|
648
648
|
|
|
649
649
|
|
|
650
|
+
def held_attempts(tdir: Path, current: str) -> int:
|
|
651
|
+
"""N when the latest decision is `retry=N dwarf=<current>`: a person put the task on this model for N attempts.
|
|
652
|
+
|
|
653
|
+
Only on that model: once the policy, or a later --dwarf, moves the task, the usual patience applies again."""
|
|
654
|
+
try:
|
|
655
|
+
lines = (tdir / 'decisions.tsv').read_text().splitlines()
|
|
656
|
+
except OSError:
|
|
657
|
+
return 0
|
|
658
|
+
cells = lines[-1].split('\t') if lines else []
|
|
659
|
+
match = re.fullmatch(r'retry=([0-9]{1,3}) dwarf=(\S+)', cells[2]) if len(cells) > 2 else None
|
|
660
|
+
return int(match.group(1)) if match and match.group(2) == current else 0
|
|
661
|
+
|
|
662
|
+
|
|
650
663
|
def decided_attempt(tdir: Path) -> int:
|
|
651
664
|
"""The attempt number of the latest row of tasks/<id>/decisions.tsv (epoch, attempt, choice, reason);
|
|
652
665
|
0 when the task has no decision. The attempts counted against a model start after it."""
|
|
@@ -720,7 +733,7 @@ def granted_attempts(tdir: Path) -> int:
|
|
|
720
733
|
for line in lines:
|
|
721
734
|
cells = line.split('\t')
|
|
722
735
|
if len(cells) > 2:
|
|
723
|
-
match = re.
|
|
736
|
+
match = re.match(r'retry=([0-9]{1,3})(?: |$)', cells[2]) # `retry=2 dwarf=<spec>` grants 2 as well
|
|
724
737
|
if match:
|
|
725
738
|
total += int(match.group(1))
|
|
726
739
|
return total
|
|
@@ -895,7 +908,8 @@ def _decide(plan: Path, tdir: Path, args, after: int):
|
|
|
895
908
|
decided = decided_attempt(tdir)
|
|
896
909
|
rows = [row for row in attempt_rows(tdir) if row[0] > decided]
|
|
897
910
|
streak = failed_streak(rows, current, registry, by_effort=step, laterals=lateral_rows(tdir))
|
|
898
|
-
|
|
911
|
+
# `--decide retry=N --dwarf <spec>` (#118) is N attempts on that model, whatever the usual patience is.
|
|
912
|
+
if streak < max(after, held_attempts(tdir, current)):
|
|
899
913
|
return MARKERS, (), '', 0
|
|
900
914
|
target, why = stronger(current, load_pools(plan / 'fractal-routing.json'), registry)
|
|
901
915
|
# Only once no higher tier has a model. A tier-up is still the stronger move.
|
package/scripts/forge-runs-rm.py
CHANGED
|
@@ -20,10 +20,13 @@ reported per step; the run dir is kept when worktrees or branches could not be d
|
|
|
20
20
|
after a failed removal the files that identify the run are the last to go, so the same command
|
|
21
21
|
finishes the job. `forge runs rm` on a path that no longer exists only unregisters it.
|
|
22
22
|
|
|
23
|
-
What the run owns on the repo's side is decided here, not read from the run dir
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
forge/<run id
|
|
23
|
+
What the run owns on the repo's side is decided here, not read from the run dir, by the rule in
|
|
24
|
+
forge_worktrees.py that forge-ui's Worktrees screen shares: a worktree is the run's only under
|
|
25
|
+
<repo>/../.forge-worktrees/<run id>/ (as forge-parallel.sh derives it, not from the `wt_root` file)
|
|
26
|
+
on a branch forge/<run id>/<task> for a task in tasks.tsv or forge/<run id>-integration, or detached
|
|
27
|
+
and named like a scratch worktree forge left there (`_candidate-<n>`, `_attribute[-<n>]`). Any other
|
|
28
|
+
worktree in that place is `foreign`, and never touched. Each worktree removed is recorded in the
|
|
29
|
+
dataset as `worktree_removed`. A
|
|
27
30
|
worktree with uncommitted or untracked changes is `dirty`: never removed, and --worktrees then
|
|
28
31
|
keeps the run dir too.
|
|
29
32
|
|
|
@@ -60,7 +63,8 @@ SKILL = Path(__file__).resolve().parent.parent
|
|
|
60
63
|
sys.path.insert(0, str(SKILL / 'scripts'))
|
|
61
64
|
|
|
62
65
|
import forge_registry # noqa: E402
|
|
63
|
-
|
|
66
|
+
import forge_worktrees # noqa: E402
|
|
67
|
+
from forge_dataset import DatasetError, data_home, dataset_dir, enabled, harvest, importer, record, record_strict # noqa: E402
|
|
64
68
|
|
|
65
69
|
OK, REFUSED, BUSY, FAILED = 0, 2, 3, 4
|
|
66
70
|
# fullmatch: with `$` alone, a trailing newline would pass
|
|
@@ -249,6 +253,7 @@ class Run:
|
|
|
249
253
|
self.branches = []
|
|
250
254
|
self.removable = set() # paths of the worktrees --worktrees removes (or prunes, when missing on disk)
|
|
251
255
|
self.wt_root = None
|
|
256
|
+
self.owners = {} # worktree path -> forge_worktrees kind (None: foreign), for the dataset events
|
|
252
257
|
|
|
253
258
|
|
|
254
259
|
def identify(target):
|
|
@@ -285,7 +290,7 @@ def identify(target):
|
|
|
285
290
|
seen.add(task)
|
|
286
291
|
run.tasks.append(task)
|
|
287
292
|
# forge-parallel.sh: wt_root="$(cd "$REPO/.." && pwd)/.forge-worktrees/$run_id", a logical cd
|
|
288
|
-
run.wt_root =
|
|
293
|
+
run.wt_root = forge_worktrees.wt_root(run.repo, run.run_id)
|
|
289
294
|
if contains(path, run.wt_root) or contains(run.wt_root, path):
|
|
290
295
|
raise Refused('refusing to delete %s: it overlaps the run\'s worktree root %s' % (path, run.wt_root))
|
|
291
296
|
return run
|
|
@@ -446,8 +451,12 @@ def inspect_git(run):
|
|
|
446
451
|
ours = wt['branch'] in branch_refs
|
|
447
452
|
if not in_root and not ours:
|
|
448
453
|
continue # the main worktree, or another run's: not this command's business
|
|
454
|
+
# forge_worktrees.owner is the rule forge-ui's Worktrees screen uses too: a task or integration branch in
|
|
455
|
+
# the run's folder, or a scratch worktree integrate or the culprit search left there.
|
|
456
|
+
kind = forge_worktrees.owner(wt['path'], wt['branch'], run.run_id, run.tasks, run.wt_root)
|
|
457
|
+
run.owners[wt['path']] = kind
|
|
449
458
|
entry = dict(path=wt['path'], branch=(wt['branch'] or '').replace('refs/heads/', '', 1) or None,
|
|
450
|
-
kind='run' if
|
|
459
|
+
kind='run' if kind else 'foreign', dirty=None, removed=False, note='')
|
|
451
460
|
if entry['kind'] == 'run':
|
|
452
461
|
if not os.path.isdir(wt['path']):
|
|
453
462
|
entry.update(dirty=False, note='missing on disk; `git worktree prune` forgets it')
|
|
@@ -583,6 +592,13 @@ def remove_worktrees(run):
|
|
|
583
592
|
code, _, err = git(run.repo, 'worktree', 'remove', entry['path'])
|
|
584
593
|
if code == 0:
|
|
585
594
|
entry['removed'] = True
|
|
595
|
+
# Fail-open, like every capture: the removal happened whether or not the store took it.
|
|
596
|
+
kind = run.owners.get(entry['path']) or 'task'
|
|
597
|
+
removed = event(run, 'worktree_removed', path=entry['path'], branch=entry['branch'] or '-',
|
|
598
|
+
kind=kind, repo_path=run.repo, by='forge runs rm')
|
|
599
|
+
if kind == 'task' and entry['branch']:
|
|
600
|
+
removed['task'] = entry['branch'].split('/', 2)[-1]
|
|
601
|
+
record([removed], repo=run.repo, where='event:worktree_removed')
|
|
586
602
|
else:
|
|
587
603
|
entry['note'] = (err or 'git worktree remove exit %d' % code).splitlines()[0]
|
|
588
604
|
problems.append('%s: %s' % (entry['path'], entry['note']))
|