@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
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
|
-
"""Advisory checks on a plan's tasks,
|
|
2
|
+
"""Advisory checks on a plan's tasks, plus the plan's shape and chain collapse.
|
|
3
3
|
|
|
4
4
|
forge-plan-check.py size --plan P
|
|
5
5
|
Names the tasks that are large by the measure that predicts a failed first attempt, the
|
|
@@ -9,13 +9,27 @@
|
|
|
9
9
|
|
|
10
10
|
forge-plan-check.py gates PLAN
|
|
11
11
|
Prints the decision-model gate block (what drift, forward, prompt and coverage did to this
|
|
12
|
-
plan) from PLAN/plan-gates.json. Prints nothing when no gate recorded anything.
|
|
12
|
+
plan) from PLAN/plan-gates.json. Prints nothing when no gate recorded anything. The
|
|
13
|
+
slow-effort notes under the table are not this file's: it builds the planner's send-back
|
|
14
|
+
prompt, which must not read the dataset (`forge-dataset.py slow-notes PLAN` prints them).
|
|
13
15
|
|
|
14
16
|
forge-plan-check.py sendback PLAN
|
|
15
17
|
Writes PLAN/plan.sendback.md from the items the gates marked in this `plan` call and prints
|
|
16
18
|
it, exiting 4. Prints nothing and exits 0 when nothing was marked.
|
|
17
19
|
|
|
18
|
-
|
|
20
|
+
sendback and gates print nothing and exit 0 if forge_jev.plan_gates cannot be imported.
|
|
21
|
+
|
|
22
|
+
forge-plan-check.py shape PLAN [--write]
|
|
23
|
+
Prints {"shape", "tasks", "waves", "widest"}. shape is one (a single task), chain (two or
|
|
24
|
+
more tasks and every wave has one) or branches (some wave has two or more). The waves are
|
|
25
|
+
forge-parallel.sh compute_waves: deps in earlier waves, no file overlap within a wave.
|
|
26
|
+
--write also saves PLAN/plan-shape.json. A cycle or a dep with no row exits 2.
|
|
27
|
+
|
|
28
|
+
forge-plan-check.py collapse PLAN
|
|
29
|
+
Collapses a chain into one task named combined. The original table is kept as
|
|
30
|
+
tasks.precollapse.tsv and each tasks/<id>/ moves to tasks.precollapse/<id>/. A one or
|
|
31
|
+
branches plan is not changed. A plan that already has tasks.precollapse.tsv or
|
|
32
|
+
collapsed.json exits 2.
|
|
19
33
|
|
|
20
34
|
Why these two: in forge's run history (269 first attempts, measured 2026-10-17) the share of
|
|
21
35
|
first attempts a reviewer passed falls steadily with prompt length (62% under 3K characters,
|
|
@@ -26,8 +40,12 @@ intervention the numbers point at, rather than a model's guess at difficulty.
|
|
|
26
40
|
from __future__ import annotations
|
|
27
41
|
|
|
28
42
|
import argparse
|
|
43
|
+
import json
|
|
44
|
+
import os
|
|
29
45
|
import re
|
|
46
|
+
import shutil
|
|
30
47
|
import sys
|
|
48
|
+
import tempfile
|
|
31
49
|
from pathlib import Path
|
|
32
50
|
|
|
33
51
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
@@ -171,6 +189,557 @@ def size_notes(plan: Path) -> list:
|
|
|
171
189
|
return notes
|
|
172
190
|
|
|
173
191
|
|
|
192
|
+
# --- shape and chain collapse -------------------------------------------------
|
|
193
|
+
# Waves follow compute_waves in forge-parallel.sh: walk the table, and a task joins the
|
|
194
|
+
# current wave only when every dep is already in an earlier wave and its files do not
|
|
195
|
+
# overlap a file already placed in this wave. lists_overlap's rule, including the `-`
|
|
196
|
+
# short-circuit and the single `./` / trailing-slash strip, is copied so a chain here is
|
|
197
|
+
# a chain there.
|
|
198
|
+
TASK_COLS = ('id', 'deps', 'difficulty', 'files', 'dwarf', 'qa', 'title')
|
|
199
|
+
DIFFICULTY_RANK = {'low': 0, 'medium': 1, 'high': 2}
|
|
200
|
+
SHAPE_KEYS = ('shape', 'tasks', 'waves', 'widest')
|
|
201
|
+
COLLAPSE_INTRO = (
|
|
202
|
+
'This task combines the %d parts of a plan that could only run one after another. '
|
|
203
|
+
'Do them in order, in this one task; each part\'s requirements and acceptance criteria still hold.')
|
|
204
|
+
NO_CRITERIA = '- (no criteria were written for this part)'
|
|
205
|
+
PRECOLLAPSE_TSV = 'tasks.precollapse.tsv'
|
|
206
|
+
PRECOLLAPSE_DIR = 'tasks.precollapse'
|
|
207
|
+
COLLAPSED_JSON = 'collapsed.json'
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
class PlanShapeError(Exception):
|
|
211
|
+
"""The waves cannot be computed: a dependency cycle, or a dep that has no row."""
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def parse_task_rows(text: str) -> list:
|
|
215
|
+
"""Task rows of a tasks.tsv. Comment lines and rows with fewer than 7 columns are skipped."""
|
|
216
|
+
out = []
|
|
217
|
+
for line in text.splitlines():
|
|
218
|
+
if not line.strip() or line.startswith('#'):
|
|
219
|
+
continue
|
|
220
|
+
cells = line.split('\t')
|
|
221
|
+
if len(cells) < 7:
|
|
222
|
+
continue
|
|
223
|
+
out.append({name: cells[index] for index, name in enumerate(TASK_COLS)})
|
|
224
|
+
return out
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _norm_path(path: str) -> str:
|
|
228
|
+
"""One leading `./` and one trailing `/`, the same two strips lists_overlap does."""
|
|
229
|
+
if path.startswith('./'):
|
|
230
|
+
path = path[2:]
|
|
231
|
+
if path.endswith('/'):
|
|
232
|
+
path = path[:-1]
|
|
233
|
+
return path
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def lists_overlap(files: str, wave_files: str) -> bool:
|
|
237
|
+
"""True when a task's comma-list overlaps the space-separated files already in the wave.
|
|
238
|
+
|
|
239
|
+
`files` of exactly `-` overlaps nothing. `.` overlaps every path already in the wave.
|
|
240
|
+
A path overlaps another when the two are equal or one is a directory prefix of the
|
|
241
|
+
other (`src` overlaps `src/a.py`, not `src2`).
|
|
242
|
+
"""
|
|
243
|
+
if files == '-':
|
|
244
|
+
return False
|
|
245
|
+
for raw in files.replace(',', ' ').split():
|
|
246
|
+
path = _norm_path(raw)
|
|
247
|
+
for other_raw in wave_files.split():
|
|
248
|
+
other = _norm_path(other_raw)
|
|
249
|
+
if (path + '/').startswith(other + '/') or (other + '/').startswith(path + '/'):
|
|
250
|
+
return True
|
|
251
|
+
if path == '.' or other == '.':
|
|
252
|
+
return True
|
|
253
|
+
return False
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def waves(rows: list) -> list:
|
|
257
|
+
"""Waves of task ids, in the order compute_waves places them. Raises PlanShapeError."""
|
|
258
|
+
order, by_id = [], {}
|
|
259
|
+
for row in rows:
|
|
260
|
+
task_id = row.get('id') or ''
|
|
261
|
+
if not task_id:
|
|
262
|
+
continue
|
|
263
|
+
order.append(task_id)
|
|
264
|
+
by_id.setdefault(task_id, row)
|
|
265
|
+
known = set(by_id)
|
|
266
|
+
missing = []
|
|
267
|
+
for task_id in order:
|
|
268
|
+
deps = by_id[task_id].get('deps')
|
|
269
|
+
if deps is None:
|
|
270
|
+
deps = '-'
|
|
271
|
+
if deps == '-':
|
|
272
|
+
continue
|
|
273
|
+
for dep in deps.replace(',', ' ').split():
|
|
274
|
+
if dep not in known:
|
|
275
|
+
missing.append('%s depends on %s' % (task_id, dep))
|
|
276
|
+
if missing:
|
|
277
|
+
raise PlanShapeError('unknown dep: ' + '; '.join(missing))
|
|
278
|
+
|
|
279
|
+
remaining = list(order)
|
|
280
|
+
done = set()
|
|
281
|
+
grouped = []
|
|
282
|
+
while remaining:
|
|
283
|
+
wave_files = ''
|
|
284
|
+
current, nxt = [], []
|
|
285
|
+
for task_id in remaining:
|
|
286
|
+
row = by_id.get(task_id) or {}
|
|
287
|
+
deps = row.get('deps')
|
|
288
|
+
if deps is None:
|
|
289
|
+
deps = '-'
|
|
290
|
+
files = row.get('files') or ''
|
|
291
|
+
ok = True
|
|
292
|
+
if deps != '-':
|
|
293
|
+
for dep in deps.replace(',', ' ').split():
|
|
294
|
+
if dep not in done:
|
|
295
|
+
ok = False
|
|
296
|
+
break
|
|
297
|
+
if ok and lists_overlap(files, wave_files):
|
|
298
|
+
ok = False
|
|
299
|
+
if ok:
|
|
300
|
+
current.append(task_id)
|
|
301
|
+
wave_files = wave_files + ' ' + files.replace(',', ' ')
|
|
302
|
+
else:
|
|
303
|
+
nxt.append(task_id)
|
|
304
|
+
if not current:
|
|
305
|
+
raise PlanShapeError('dependency cycle or unsatisfiable deps among: ' + ' '.join(nxt))
|
|
306
|
+
done.update(current)
|
|
307
|
+
grouped.append(current)
|
|
308
|
+
remaining = nxt
|
|
309
|
+
return grouped
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def shape(rows: list) -> dict:
|
|
313
|
+
"""`{"shape", "tasks", "waves", "widest"}` for these task rows.
|
|
314
|
+
|
|
315
|
+
`one` is a single task. `chain` is two or more tasks whose every wave has one task.
|
|
316
|
+
`branches` is anything with a wave of two or more.
|
|
317
|
+
"""
|
|
318
|
+
grouped = waves(rows)
|
|
319
|
+
count = sum(len(group) for group in grouped)
|
|
320
|
+
if count == 0:
|
|
321
|
+
raise PlanShapeError('no tasks')
|
|
322
|
+
widest = max(len(group) for group in grouped)
|
|
323
|
+
if count == 1:
|
|
324
|
+
name = 'one'
|
|
325
|
+
elif widest == 1:
|
|
326
|
+
name = 'chain'
|
|
327
|
+
else:
|
|
328
|
+
name = 'branches'
|
|
329
|
+
return {'shape': name, 'tasks': count, 'waves': len(grouped), 'widest': widest}
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def shape_text(info: dict) -> str:
|
|
333
|
+
return json.dumps({key: info[key] for key in SHAPE_KEYS}) + '\n'
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _highest_difficulty(parts: list) -> str:
|
|
337
|
+
known = [part.get('difficulty') or '' for part in parts if (part.get('difficulty') or '') in DIFFICULTY_RANK]
|
|
338
|
+
if known:
|
|
339
|
+
return max(known, key=lambda value: DIFFICULTY_RANK[value])
|
|
340
|
+
values = [part.get('difficulty') or '' for part in parts]
|
|
341
|
+
if values and all(value == values[0] for value in values):
|
|
342
|
+
return values[0]
|
|
343
|
+
return '-'
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _common(parts: list, key: str) -> str:
|
|
347
|
+
values = [part.get(key, '-') for part in parts]
|
|
348
|
+
if values and all(value == values[0] for value in values):
|
|
349
|
+
return values[0]
|
|
350
|
+
return '-'
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _union_files(parts: list) -> str:
|
|
354
|
+
seen, ordered = set(), []
|
|
355
|
+
for part in parts:
|
|
356
|
+
files = part.get('files') or ''
|
|
357
|
+
if files == '-':
|
|
358
|
+
continue
|
|
359
|
+
for token in files.split(','):
|
|
360
|
+
token = token.strip()
|
|
361
|
+
if not token or token == '-' or token in seen:
|
|
362
|
+
continue
|
|
363
|
+
seen.add(token)
|
|
364
|
+
ordered.append(token)
|
|
365
|
+
return ','.join(ordered) if ordered else '-'
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
# Collapse follows CommonMark for ATX headings and fenced code. The size advisory above keeps
|
|
369
|
+
# its own simpler scan; changing that would change which tasks it flags.
|
|
370
|
+
_FENCE_LINE = re.compile(r'^( {0,3})(`{3,}|~{3,})(.*)$')
|
|
371
|
+
_CRITERIA_TEXT = re.compile(r'acceptance criteria\s*:?', re.IGNORECASE)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _strip_closing_hashes(content: str) -> str:
|
|
375
|
+
"""Drop a closing `#` run that is the whole content or is preceded by a space or tab."""
|
|
376
|
+
end = len(content)
|
|
377
|
+
while end > 0 and content[end - 1] == '#':
|
|
378
|
+
end -= 1
|
|
379
|
+
if end == len(content):
|
|
380
|
+
return content
|
|
381
|
+
if end == 0 or content[end - 1] in ' \t':
|
|
382
|
+
return content[:end].strip(' \t')
|
|
383
|
+
return content
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _atx_heading(line: str):
|
|
387
|
+
"""(indent, opening hashes, content) of a CommonMark ATX heading, else None.
|
|
388
|
+
|
|
389
|
+
Up to three leading spaces. A leading tab is a code indent, not a heading. The opening
|
|
390
|
+
`#` run is 1-6 and must be followed by a space or a tab, or the end of the line. A
|
|
391
|
+
closing `#` run, preceded by a space or tab and followed only by spaces or tabs, is not
|
|
392
|
+
part of the content (`## Acceptance criteria ##` is that heading, and so is the same
|
|
393
|
+
line with a tab in place of the space). Leading and trailing spaces and tabs are not
|
|
394
|
+
part of the content.
|
|
395
|
+
"""
|
|
396
|
+
if not line or line[0] == '\t' or line.startswith(' '):
|
|
397
|
+
return None
|
|
398
|
+
indent_len = 0
|
|
399
|
+
while indent_len < 3 and indent_len < len(line) and line[indent_len] == ' ':
|
|
400
|
+
indent_len += 1
|
|
401
|
+
marks_end = indent_len
|
|
402
|
+
while marks_end < len(line) and line[marks_end] == '#':
|
|
403
|
+
marks_end += 1
|
|
404
|
+
marks = line[indent_len:marks_end]
|
|
405
|
+
if not marks or len(marks) > 6:
|
|
406
|
+
return None
|
|
407
|
+
if marks_end < len(line) and line[marks_end] not in ' \t':
|
|
408
|
+
return None
|
|
409
|
+
raw = line[marks_end + 1:] if marks_end < len(line) else ''
|
|
410
|
+
return line[:indent_len], marks, _strip_closing_hashes(raw.strip(' \t'))
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _fence_step(line: str, open_fence):
|
|
414
|
+
"""(line is fence content or a fence marker, fence state after the line).
|
|
415
|
+
|
|
416
|
+
`open_fence` is None or `(marker, length)`. A fence opens on three or more backticks
|
|
417
|
+
or tildes, indented at most three spaces. A backtick fence whose info string contains
|
|
418
|
+
a backtick does not open. It closes only on the same marker, at least as long, with
|
|
419
|
+
nothing after it but spaces or tabs, so a shorter or different marker inside the block
|
|
420
|
+
is content. A tab after the closing marker still closes the fence.
|
|
421
|
+
"""
|
|
422
|
+
found = _FENCE_LINE.match(line)
|
|
423
|
+
if open_fence is None:
|
|
424
|
+
if not found:
|
|
425
|
+
return False, None
|
|
426
|
+
marker, rest = found.group(2), found.group(3)
|
|
427
|
+
if marker[0] == '`' and '`' in rest:
|
|
428
|
+
return False, None
|
|
429
|
+
return True, (marker[0], len(marker))
|
|
430
|
+
if found:
|
|
431
|
+
marker, rest = found.group(2), found.group(3)
|
|
432
|
+
if marker[0] == open_fence[0] and len(marker) >= open_fence[1] and rest.strip(' \t') == '':
|
|
433
|
+
return True, None
|
|
434
|
+
return True, open_fence
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def split_acceptance(text: str):
|
|
438
|
+
"""(body without acceptance-criteria sections, criteria lines or None).
|
|
439
|
+
|
|
440
|
+
Criteria is None when no acceptance-criteria heading sits outside a fence. The heading
|
|
441
|
+
is a CommonMark ATX heading (`## Acceptance criteria`, `## Acceptance criteria ##`,
|
|
442
|
+
the same indented up to three spaces, or with a tab where a space would separate the
|
|
443
|
+
hashes from the text). The lines under every such heading are kept
|
|
444
|
+
as written, fence markers included, and the headings themselves are not part of either piece.
|
|
445
|
+
"""
|
|
446
|
+
body, criteria = [], []
|
|
447
|
+
found = False
|
|
448
|
+
fence = None
|
|
449
|
+
level = None
|
|
450
|
+
for line in (text or '').splitlines():
|
|
451
|
+
inside, fence = _fence_step(line, fence)
|
|
452
|
+
if inside:
|
|
453
|
+
(criteria if level is not None else body).append(line)
|
|
454
|
+
continue
|
|
455
|
+
heading = _atx_heading(line)
|
|
456
|
+
if level is not None and heading and len(heading[1]) <= level:
|
|
457
|
+
level = None
|
|
458
|
+
if level is None and heading and _CRITERIA_TEXT.fullmatch(heading[2]):
|
|
459
|
+
found = True
|
|
460
|
+
level = len(heading[1])
|
|
461
|
+
continue
|
|
462
|
+
if level is not None:
|
|
463
|
+
criteria.append(line)
|
|
464
|
+
else:
|
|
465
|
+
body.append(line)
|
|
466
|
+
return '\n'.join(body), (criteria if found else None)
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def demote_headings(text: str) -> str:
|
|
470
|
+
"""One extra `#` on every ATX heading outside a fence. `## X` becomes `### X`.
|
|
471
|
+
|
|
472
|
+
An indented heading keeps its indent (` ## X` becomes ` ### X`). A heading inside
|
|
473
|
+
a fence, including one opened by a longer marker, stays as written.
|
|
474
|
+
"""
|
|
475
|
+
if not text:
|
|
476
|
+
return ''
|
|
477
|
+
out, fence = [], None
|
|
478
|
+
for line in text.splitlines():
|
|
479
|
+
inside, fence = _fence_step(line, fence)
|
|
480
|
+
if inside:
|
|
481
|
+
out.append(line)
|
|
482
|
+
continue
|
|
483
|
+
heading = _atx_heading(line)
|
|
484
|
+
if heading:
|
|
485
|
+
indent = heading[0]
|
|
486
|
+
out.append(indent + '#' + line[len(indent):])
|
|
487
|
+
continue
|
|
488
|
+
out.append(line)
|
|
489
|
+
return '\n'.join(out)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def _render_criteria(criteria) -> str:
|
|
493
|
+
if criteria is None:
|
|
494
|
+
return NO_CRITERIA
|
|
495
|
+
rendered = '\n'.join(criteria).strip('\n')
|
|
496
|
+
return rendered
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def build_prompt(parts: list, prompts: dict) -> str:
|
|
500
|
+
"""The combined prompt: parts in wave order, then one acceptance-criteria section."""
|
|
501
|
+
blocks = [COLLAPSE_INTRO % len(parts), '']
|
|
502
|
+
tail = ['## Acceptance criteria', '']
|
|
503
|
+
for index, part in enumerate(parts, 1):
|
|
504
|
+
raw = (prompts or {}).get(part['id']) or ''
|
|
505
|
+
body, criteria = split_acceptance(raw)
|
|
506
|
+
body = demote_headings(body).strip('\n')
|
|
507
|
+
title = part.get('title') or ''
|
|
508
|
+
blocks.append('## Part %d: %s (%s)' % (index, title, part['id']))
|
|
509
|
+
blocks.append('')
|
|
510
|
+
if body:
|
|
511
|
+
blocks.append(body)
|
|
512
|
+
blocks.append('')
|
|
513
|
+
tail.append('### Part %d: %s' % (index, title))
|
|
514
|
+
tail.append('')
|
|
515
|
+
rendered = _render_criteria(criteria)
|
|
516
|
+
if rendered:
|
|
517
|
+
tail.append(rendered)
|
|
518
|
+
tail.append('')
|
|
519
|
+
return '\n'.join(blocks).rstrip('\n') + '\n\n' + '\n'.join(tail).rstrip('\n') + '\n'
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def build_approach(parts: list, approaches: dict):
|
|
523
|
+
"""Approaches that exist, in wave order, each under `### Part i`. None when none do."""
|
|
524
|
+
blocks = []
|
|
525
|
+
for index, part in enumerate(parts, 1):
|
|
526
|
+
text = (approaches or {}).get(part['id'])
|
|
527
|
+
if text is None or not text.strip():
|
|
528
|
+
continue
|
|
529
|
+
blocks.append('### Part %d\n\n%s\n' % (index, text.strip()))
|
|
530
|
+
if not blocks:
|
|
531
|
+
return None
|
|
532
|
+
return '\n'.join(blocks)
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def _parts_in_wave_order(rows: list) -> list:
|
|
536
|
+
by_id = {}
|
|
537
|
+
for row in rows:
|
|
538
|
+
by_id.setdefault(row.get('id'), row)
|
|
539
|
+
return [by_id[task_id] for group in waves(rows) for task_id in group]
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def collapse_rows(rows: list, prompts: dict, approaches: dict):
|
|
543
|
+
"""(row, prompt, approach) of a chain merged in wave order.
|
|
544
|
+
|
|
545
|
+
The row is the single `combined` task. `approach` is None when no part had one.
|
|
546
|
+
Callers decide whether the plan is a chain; this only merges.
|
|
547
|
+
"""
|
|
548
|
+
parts = _parts_in_wave_order(rows)
|
|
549
|
+
if not parts:
|
|
550
|
+
raise PlanShapeError('no tasks')
|
|
551
|
+
title = ('%d parts: %s' % (len(parts), parts[0].get('title') or ''))[:100]
|
|
552
|
+
row = {
|
|
553
|
+
'id': 'combined',
|
|
554
|
+
'deps': '-',
|
|
555
|
+
'difficulty': _highest_difficulty(parts),
|
|
556
|
+
'files': _union_files(parts),
|
|
557
|
+
'dwarf': _common(parts, 'dwarf'),
|
|
558
|
+
'qa': _common(parts, 'qa'),
|
|
559
|
+
'title': title,
|
|
560
|
+
}
|
|
561
|
+
return row, build_prompt(parts, prompts), build_approach(parts, approaches)
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def _atomic_write(path: Path, data) -> None:
|
|
565
|
+
"""Write via a temp file in the same directory, then rename into place."""
|
|
566
|
+
raw = data.encode('utf-8', 'surrogateescape') if isinstance(data, str) else data
|
|
567
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
568
|
+
fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix='.' + path.name + '.')
|
|
569
|
+
try:
|
|
570
|
+
with os.fdopen(fd, 'wb') as handle:
|
|
571
|
+
handle.write(raw)
|
|
572
|
+
handle.flush()
|
|
573
|
+
os.fsync(handle.fileno())
|
|
574
|
+
os.chmod(tmp, 0o644)
|
|
575
|
+
os.replace(tmp, path)
|
|
576
|
+
except BaseException:
|
|
577
|
+
try:
|
|
578
|
+
os.unlink(tmp)
|
|
579
|
+
except OSError:
|
|
580
|
+
pass
|
|
581
|
+
raise
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def _read_task_file(path: Path):
|
|
585
|
+
"""The text of a task file, or None when it is absent.
|
|
586
|
+
|
|
587
|
+
A file that exists but cannot be read raises PlanShapeError. Treating that as an empty
|
|
588
|
+
prompt would drop the part's requirements and still collapse.
|
|
589
|
+
"""
|
|
590
|
+
try:
|
|
591
|
+
if not path.is_file():
|
|
592
|
+
return None
|
|
593
|
+
return path.read_text(errors='replace')
|
|
594
|
+
except OSError as err:
|
|
595
|
+
raise PlanShapeError('cannot read %s' % path) from err
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def read_plan(plan: Path):
|
|
599
|
+
"""(original tasks.tsv bytes, parsed rows). PlanShapeError when the table cannot be read."""
|
|
600
|
+
path = Path(plan) / 'tasks.tsv'
|
|
601
|
+
try:
|
|
602
|
+
data = path.read_bytes()
|
|
603
|
+
except OSError as err:
|
|
604
|
+
raise PlanShapeError('cannot read %s' % path) from err
|
|
605
|
+
return data, parse_task_rows(data.decode('utf-8', 'surrogateescape'))
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def render_tasks(original: bytes, row: dict) -> bytes:
|
|
609
|
+
"""The preamble of the old table (comments and blank lines) plus the one combined row."""
|
|
610
|
+
text = original.decode('utf-8', 'surrogateescape')
|
|
611
|
+
preamble = []
|
|
612
|
+
for line in text.splitlines(keepends=True):
|
|
613
|
+
if line.startswith('#') or not line.strip():
|
|
614
|
+
preamble.append(line)
|
|
615
|
+
continue
|
|
616
|
+
break
|
|
617
|
+
body = ''.join(preamble)
|
|
618
|
+
if body and not body.endswith('\n'):
|
|
619
|
+
body += '\n'
|
|
620
|
+
cells = '\t'.join(row[name] for name in TASK_COLS)
|
|
621
|
+
return (body + cells + '\n').encode('utf-8', 'surrogateescape')
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def _collapsed_text(ids: list, info: dict) -> str:
|
|
625
|
+
payload = {
|
|
626
|
+
'from': ids,
|
|
627
|
+
'into': 'combined',
|
|
628
|
+
'shape': {key: info[key] for key in SHAPE_KEYS},
|
|
629
|
+
}
|
|
630
|
+
return json.dumps(payload, indent=2) + '\n'
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def _rollback(plan: Path, original: bytes, moved: list, made_pre: bool, replaced: bool, made_combined: bool) -> None:
|
|
634
|
+
"""Put back what collapse had changed. Leftover part dirs are not deleted."""
|
|
635
|
+
if made_combined:
|
|
636
|
+
combined = plan / 'tasks' / 'combined'
|
|
637
|
+
if combined.exists():
|
|
638
|
+
shutil.rmtree(combined)
|
|
639
|
+
marker = plan / COLLAPSED_JSON
|
|
640
|
+
if marker.exists():
|
|
641
|
+
marker.unlink()
|
|
642
|
+
if replaced:
|
|
643
|
+
_atomic_write(plan / 'tasks.tsv', original)
|
|
644
|
+
pre = plan / PRECOLLAPSE_DIR
|
|
645
|
+
for task_id in moved:
|
|
646
|
+
src = pre / task_id
|
|
647
|
+
dst = plan / 'tasks' / task_id
|
|
648
|
+
if src.exists() and not dst.exists():
|
|
649
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
650
|
+
shutil.move(src, dst)
|
|
651
|
+
copy = plan / PRECOLLAPSE_TSV
|
|
652
|
+
if copy.exists():
|
|
653
|
+
copy.unlink()
|
|
654
|
+
if made_pre and pre.exists() and not any(pre.iterdir()):
|
|
655
|
+
pre.rmdir()
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def commit_collapse(plan: Path, original: bytes, rows: list, row: dict, prompt: str, approach, info: dict) -> None:
|
|
659
|
+
"""Move the chain aside and write the combined task. A failure restores the plan."""
|
|
660
|
+
moved, made_pre, replaced, made_combined = [], False, False, False
|
|
661
|
+
try:
|
|
662
|
+
_atomic_write(plan / PRECOLLAPSE_TSV, original)
|
|
663
|
+
pre = plan / PRECOLLAPSE_DIR
|
|
664
|
+
pre.mkdir()
|
|
665
|
+
made_pre = True
|
|
666
|
+
for task in rows:
|
|
667
|
+
src = plan / 'tasks' / task['id']
|
|
668
|
+
if src.exists():
|
|
669
|
+
shutil.move(src, pre / task['id'])
|
|
670
|
+
moved.append(task['id'])
|
|
671
|
+
_atomic_write(plan / 'tasks.tsv', render_tasks(original, row))
|
|
672
|
+
replaced = True
|
|
673
|
+
combined = plan / 'tasks' / 'combined'
|
|
674
|
+
combined.mkdir(parents=True)
|
|
675
|
+
made_combined = True
|
|
676
|
+
_atomic_write(combined / 'prompt.md', prompt)
|
|
677
|
+
if approach is not None:
|
|
678
|
+
_atomic_write(combined / 'approach.md', approach)
|
|
679
|
+
ids = [task['id'] for task in _parts_in_wave_order(rows)]
|
|
680
|
+
_atomic_write(plan / COLLAPSED_JSON, _collapsed_text(ids, info))
|
|
681
|
+
except Exception as err:
|
|
682
|
+
try:
|
|
683
|
+
_rollback(plan, original, moved, made_pre, replaced, made_combined)
|
|
684
|
+
except Exception as restore_err:
|
|
685
|
+
raise PlanShapeError('collapse failed (%s) and the plan could not be restored (%s)'
|
|
686
|
+
% (err, restore_err)) from err
|
|
687
|
+
raise
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
def command_shape(plan: Path, write: bool) -> int:
|
|
691
|
+
try:
|
|
692
|
+
info = shape(read_plan(plan)[1])
|
|
693
|
+
except PlanShapeError as err:
|
|
694
|
+
print('forge-plan-check: %s' % err, file=sys.stderr)
|
|
695
|
+
return 2
|
|
696
|
+
text = shape_text(info)
|
|
697
|
+
if write:
|
|
698
|
+
try:
|
|
699
|
+
_atomic_write(Path(plan) / 'plan-shape.json', text)
|
|
700
|
+
except OSError as err:
|
|
701
|
+
print('forge-plan-check: %s' % err, file=sys.stderr)
|
|
702
|
+
return 2
|
|
703
|
+
sys.stdout.write(text)
|
|
704
|
+
return 0
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def command_collapse(plan: Path) -> int:
|
|
708
|
+
plan = Path(plan)
|
|
709
|
+
for name in (PRECOLLAPSE_TSV, COLLAPSED_JSON):
|
|
710
|
+
if (plan / name).exists():
|
|
711
|
+
print('forge-plan-check: %s already exists' % name, file=sys.stderr)
|
|
712
|
+
return 2
|
|
713
|
+
try:
|
|
714
|
+
original, rows = read_plan(plan)
|
|
715
|
+
info = shape(rows)
|
|
716
|
+
except PlanShapeError as err:
|
|
717
|
+
print('forge-plan-check: %s' % err, file=sys.stderr)
|
|
718
|
+
return 2
|
|
719
|
+
if info['shape'] != 'chain':
|
|
720
|
+
print('not collapsed: %s' % info['shape'])
|
|
721
|
+
return 0
|
|
722
|
+
try:
|
|
723
|
+
prompts, approaches = {}, {}
|
|
724
|
+
for row in rows:
|
|
725
|
+
root = plan / 'tasks' / row['id']
|
|
726
|
+
prompts[row['id']] = _read_task_file(root / 'prompt.md') or ''
|
|
727
|
+
approach = _read_task_file(root / 'approach.md')
|
|
728
|
+
if approach is not None:
|
|
729
|
+
approaches[row['id']] = approach
|
|
730
|
+
combined, prompt, approach = collapse_rows(rows, prompts, approaches)
|
|
731
|
+
commit_collapse(plan, original, rows, combined, prompt, approach, info)
|
|
732
|
+
except PlanShapeError as err:
|
|
733
|
+
print('forge-plan-check: %s' % err, file=sys.stderr)
|
|
734
|
+
return 2
|
|
735
|
+
except Exception as err:
|
|
736
|
+
print('forge-plan-check: collapse failed: %s' % err, file=sys.stderr)
|
|
737
|
+
return 2
|
|
738
|
+
print('collapsed a sequential plan of %d tasks into one (%s keeps the original)'
|
|
739
|
+
% (info['tasks'], PRECOLLAPSE_TSV))
|
|
740
|
+
return 0
|
|
741
|
+
|
|
742
|
+
|
|
174
743
|
def plan_gates():
|
|
175
744
|
try:
|
|
176
745
|
from forge_jev import plan_gates as module
|
|
@@ -186,21 +755,35 @@ def main(argv=None) -> int:
|
|
|
186
755
|
p.add_argument('--plan', required=True)
|
|
187
756
|
for name in ('gates', 'sendback'):
|
|
188
757
|
sub.add_parser(name).add_argument('plan')
|
|
758
|
+
shape_cmd = sub.add_parser('shape')
|
|
759
|
+
shape_cmd.add_argument('plan')
|
|
760
|
+
shape_cmd.add_argument('--write', action='store_true')
|
|
761
|
+
sub.add_parser('collapse').add_argument('plan')
|
|
189
762
|
args = ap.parse_args(argv)
|
|
190
|
-
if args.command
|
|
763
|
+
if args.command == 'shape':
|
|
764
|
+
return command_shape(Path(args.plan), args.write)
|
|
765
|
+
if args.command == 'collapse':
|
|
766
|
+
return command_collapse(Path(args.plan))
|
|
767
|
+
if args.command == 'sendback':
|
|
191
768
|
module = plan_gates()
|
|
192
769
|
if module is None:
|
|
193
770
|
return 0
|
|
194
771
|
try:
|
|
195
|
-
if args.
|
|
196
|
-
for line in module.marks(args.plan):
|
|
197
|
-
print(line)
|
|
198
|
-
elif module.sendback(args.plan):
|
|
772
|
+
if module.sendback(args.plan):
|
|
199
773
|
sys.stdout.write((Path(args.plan) / module.SENDBACK_FILE).read_text())
|
|
200
774
|
return 4
|
|
201
775
|
except Exception:
|
|
202
776
|
return 0
|
|
203
777
|
return 0
|
|
778
|
+
if args.command == 'gates':
|
|
779
|
+
try:
|
|
780
|
+
module = plan_gates()
|
|
781
|
+
if module is not None:
|
|
782
|
+
for line in module.marks(args.plan):
|
|
783
|
+
print(line)
|
|
784
|
+
except Exception:
|
|
785
|
+
pass
|
|
786
|
+
return 0
|
|
204
787
|
try:
|
|
205
788
|
notes = size_notes(Path(args.plan))
|
|
206
789
|
except Exception:
|