@giamme/forge 0.17.0 → 0.19.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 +57 -0
- package/README.md +1 -0
- package/SKILL.md +32 -5
- package/VERSION +1 -1
- package/docs/artifacts.md +33 -1
- package/docs/commands.md +147 -16
- package/docs/dataset.md +5 -0
- package/docs/decomposed-runs.md +122 -1
- package/docs/development.md +2 -1
- package/docs/forge-ui.md +98 -8
- package/docs/memory.md +27 -4
- package/docs/models.md +8 -0
- package/docs/reviews.md +122 -0
- package/docs/safety.md +8 -0
- package/forge +44 -4
- package/package.json +2 -1
- package/references/dataset.md +39 -1
- package/references/decompose.md +737 -16
- package/references/harnesses.md +18 -3
- package/references/planning.md +43 -14
- package/references/solo.md +2 -1
- package/references/ui.md +56 -6
- package/registry.tsv +8 -3
- package/scripts/forge-artifact.sh +14 -0
- package/scripts/forge-brief.py +217 -0
- package/scripts/forge-compare.py +13 -2
- package/scripts/forge-config.py +176 -9
- package/scripts/forge-contract.py +246 -28
- package/scripts/forge-control.py +200 -15
- package/scripts/forge-dispatch.sh +48 -15
- package/scripts/forge-du.py +167 -0
- package/scripts/forge-group.py +496 -0
- package/scripts/forge-groups.py +89 -0
- package/scripts/forge-handoff.py +1128 -0
- package/scripts/forge-lib-adopt.sh +1 -0
- package/scripts/forge-lib-group.sh +641 -0
- package/scripts/forge-lib-plans.sh +343 -4
- package/scripts/forge-lib-review.sh +29 -1
- package/scripts/forge-lib-task.sh +197 -4
- package/scripts/forge-memory.sh +245 -3
- package/scripts/forge-metrics.sh +7 -3
- package/scripts/forge-parallel-options.sh +4 -0
- package/scripts/forge-parallel.sh +1216 -41
- package/scripts/forge-planner.py +104 -8
- package/scripts/forge-prompt.py +120 -0
- package/scripts/forge-retro.py +115 -0
- package/scripts/forge-route.py +190 -12
- package/scripts/forge-runs-compact.py +443 -0
- package/scripts/forge-runs-rm.py +2 -0
- package/scripts/forge-runs.py +27 -8
- package/scripts/forge-schedule.py +633 -49
- package/scripts/forge-shadow.py +7 -1
- package/scripts/forge-solo.sh +4 -0
- package/scripts/forge-summarize.py +698 -0
- package/scripts/forge-ui-options.sh +10 -0
- package/scripts/forge-worktrees.py +243 -0
- package/scripts/forge_brief/__init__.py +831 -0
- package/scripts/forge_brief/answers.py +506 -0
- package/scripts/forge_brief/proposals.py +1630 -0
- package/scripts/forge_dataset/__init__.py +10 -0
- package/scripts/forge_dataset/efforts.py +4 -3
- package/scripts/forge_dataset/export.py +36 -10
- package/scripts/forge_dataset/facts.py +8 -4
- package/scripts/forge_dataset/forecast.py +8 -18
- package/scripts/forge_dataset/harvest.py +241 -12
- package/scripts/forge_dataset/history.py +13 -6
- package/scripts/forge_dataset/importer.py +65 -1
- package/scripts/forge_dataset/names.py +66 -0
- package/scripts/forge_dataset/reviewers.py +5 -2
- package/scripts/forge_dataset/risk.py +6 -3
- package/scripts/forge_dataset/routing.py +6 -1
- package/scripts/forge_decide/__init__.py +11 -1
- package/scripts/forge_groups/__init__.py +308 -0
- package/scripts/forge_groups/attribute.py +289 -0
- package/scripts/forge_groups/review.py +286 -0
- package/scripts/forge_locations.py +366 -0
- package/scripts/forge_owner.py +152 -0
- package/scripts/forge_registry.py +19 -0
- package/scripts/forge_retro/__init__.py +417 -0
- package/scripts/forge_retro/issues.py +1193 -0
- package/scripts/forge_retro/report.py +671 -0
- package/scripts/forge_side/__init__.py +482 -0
- package/scripts/forge_storage.py +515 -0
- package/ui/README.md +68 -8
- package/ui/docs/api.md +375 -31
- package/ui/forge_ui/control.py +451 -11
- package/ui/forge_ui/executions.py +8 -1
- package/ui/forge_ui/export.py +53 -7
- package/ui/forge_ui/groups.py +264 -0
- package/ui/forge_ui/links.py +337 -0
- package/ui/forge_ui/models.py +125 -10
- package/ui/forge_ui/projects.py +4 -1
- package/ui/forge_ui/reader.py +919 -45
- package/ui/forge_ui/server.py +4 -0
- package/ui/forge_ui/static/app.js +173 -11
- package/ui/forge_ui/static/briefview.js +605 -0
- package/ui/forge_ui/static/checksview.js +6 -2
- package/ui/forge_ui/static/controls.js +5 -0
- package/ui/forge_ui/static/diffview.js +86 -1
- package/ui/forge_ui/static/groupsview.js +332 -0
- package/ui/forge_ui/static/index.html +4 -0
- package/ui/forge_ui/static/panel.js +394 -8
- package/ui/forge_ui/static/projectsview.js +189 -10
- package/ui/forge_ui/static/runmodel.js +27 -4
- package/ui/forge_ui/static/storageview.js +352 -0
- package/ui/forge_ui/static/style.css +176 -6
- package/ui/forge_ui/static/worktreesview.js +235 -14
- package/ui/forge_ui/storage.py +150 -0
- package/ui/forge_ui/transcripts.py +35 -10
- package/ui/forge_ui/worktrees.py +154 -13
|
@@ -27,7 +27,7 @@ import time
|
|
|
27
27
|
from pathlib import Path
|
|
28
28
|
from types import SimpleNamespace
|
|
29
29
|
|
|
30
|
-
from . import (BUSY_TIMEOUT_S, DatasetError, config_runs_dir, data_home, dataset_dir, enabled,
|
|
30
|
+
from . import (BUSY_TIMEOUT_S, DatasetError, config_runs_dir, connect, data_home, dataset_dir, enabled,
|
|
31
31
|
location_refused, put_blob, put_file, record, record_strict, repo_id, sha256, watch_blob_failures)
|
|
32
32
|
from . import harvest as h
|
|
33
33
|
from . import capture
|
|
@@ -196,6 +196,9 @@ def legacy_task_events(tdir: Path, task_attempts: list[Path], prov_base: dict) -
|
|
|
196
196
|
verdict = h.verdict_of(h.text(qa[-1] / 'qa.last')) if qa else None
|
|
197
197
|
data['status'], data['status_source'] = ((row['status'], 'attempts.tsv') if row else
|
|
198
198
|
(verdict, 'qa_verdict') if verdict else (None, None))
|
|
199
|
+
# task_event read the task dir's current status. This attempt's status is the
|
|
200
|
+
# attempts.tsv row, so the prompt_changed flag has to follow the row.
|
|
201
|
+
data['prompt_changed'] = h.attempt_prompt_changed(data.get('status'))
|
|
199
202
|
event['attempt'], data['attempt_source'] = ((row['attempt'], 'attempts.tsv') if row else
|
|
200
203
|
(index + 1, 'order'))
|
|
201
204
|
blocks = _DIFF_BLOCK.findall(h.text(qa[-1] / 'qa.prompt') or '') if qa else []
|
|
@@ -206,6 +209,7 @@ def legacy_task_events(tdir: Path, task_attempts: list[Path], prov_base: dict) -
|
|
|
206
209
|
else:
|
|
207
210
|
event['attempt'] = h.as_int(h.first_line(tdir / 'attempt'))
|
|
208
211
|
data['attempt_source'] = 'attempt_file'
|
|
212
|
+
h.annotate_group_attempt(event, tdir)
|
|
209
213
|
events.append(event)
|
|
210
214
|
return events
|
|
211
215
|
|
|
@@ -274,6 +278,8 @@ def import_tree(top: Path, mapper: Mapper, args, counts: dict) -> list[tuple[lis
|
|
|
274
278
|
for event in events:
|
|
275
279
|
if isinstance(event.get('data'), dict) and event['data'].get('root'):
|
|
276
280
|
event['data']['root'] = str(mapper(event['data']['root']))
|
|
281
|
+
if role == 'task' and event.get('kind') == 'attempt':
|
|
282
|
+
h.annotate_group_attempt(event, root)
|
|
277
283
|
# A live begin() recorded which code the execution started with; keep it.
|
|
278
284
|
capture.stamp(events, (stored or {}).get('provenance'), check_change=False)
|
|
279
285
|
batches.append((events, repo))
|
|
@@ -545,6 +551,57 @@ def _archive_mapper(work: Path, source: Path | None) -> tuple[Path, Mapper]:
|
|
|
545
551
|
return root, mapper
|
|
546
552
|
|
|
547
553
|
|
|
554
|
+
def link_stored_group_attempts(events: list) -> None:
|
|
555
|
+
"""Fill the group link onto an attempt live capture stored before the group judged it.
|
|
556
|
+
|
|
557
|
+
The rid stays the attempt dir name, so the import does not add a second event. Only
|
|
558
|
+
`review_scope`, `group` and `round` are written, and a copied task-level review
|
|
559
|
+
(`gate`, `blobs.forge_note`) is removed. A row that already carries the same link
|
|
560
|
+
is left as it was.
|
|
561
|
+
"""
|
|
562
|
+
pending = [event for event in events
|
|
563
|
+
if event.get('kind') == 'attempt' and isinstance(event.get('data'), dict)
|
|
564
|
+
and event['data'].get('review_scope') == 'group']
|
|
565
|
+
if not pending or not enabled():
|
|
566
|
+
return
|
|
567
|
+
db = connect()
|
|
568
|
+
try:
|
|
569
|
+
db.execute('BEGIN IMMEDIATE')
|
|
570
|
+
for event in pending:
|
|
571
|
+
row = db.execute('SELECT data FROM events WHERE rid = ?', (event['rid'],)).fetchone()
|
|
572
|
+
if not row:
|
|
573
|
+
continue
|
|
574
|
+
try:
|
|
575
|
+
data = json.loads(row[0])
|
|
576
|
+
except ValueError:
|
|
577
|
+
continue
|
|
578
|
+
if not isinstance(data, dict):
|
|
579
|
+
continue
|
|
580
|
+
blobs = data.get('blobs') if isinstance(data.get('blobs'), dict) else {}
|
|
581
|
+
same = (data.get('review_scope') == 'group' and data.get('group') == event['data'].get('group')
|
|
582
|
+
and data.get('round') == event['data'].get('round') and not data.get('gate')
|
|
583
|
+
and 'forge_note' not in blobs)
|
|
584
|
+
if same:
|
|
585
|
+
continue
|
|
586
|
+
data['review_scope'] = 'group'
|
|
587
|
+
data['group'] = event['data'].get('group')
|
|
588
|
+
data['round'] = event['data'].get('round')
|
|
589
|
+
data['gate'] = None
|
|
590
|
+
if isinstance(data.get('blobs'), dict):
|
|
591
|
+
data['blobs'].pop('forge_note', None)
|
|
592
|
+
db.execute('UPDATE events SET data = ? WHERE rid = ?',
|
|
593
|
+
(json.dumps(data, sort_keys=True, default=str), event['rid']))
|
|
594
|
+
db.execute('COMMIT')
|
|
595
|
+
except BaseException:
|
|
596
|
+
try:
|
|
597
|
+
db.execute('ROLLBACK')
|
|
598
|
+
except sqlite3.Error:
|
|
599
|
+
pass
|
|
600
|
+
raise
|
|
601
|
+
finally:
|
|
602
|
+
db.close()
|
|
603
|
+
|
|
604
|
+
|
|
548
605
|
def import_run(path, strict: bool = True, include_temp: bool = True) -> dict:
|
|
549
606
|
"""Import one run dir or `.tar.gz` and say exactly what happened: {events, new, failed, ...}.
|
|
550
607
|
|
|
@@ -561,6 +618,7 @@ def import_run(path, strict: bool = True, include_temp: bool = True) -> dict:
|
|
|
561
618
|
writer = record_strict if strict else record
|
|
562
619
|
|
|
563
620
|
def write(batches, blob_failures):
|
|
621
|
+
pending = []
|
|
564
622
|
for events, repo in batches:
|
|
565
623
|
if events:
|
|
566
624
|
counts['events'] += len(events)
|
|
@@ -574,8 +632,14 @@ def import_run(path, strict: bool = True, include_temp: bool = True) -> dict:
|
|
|
574
632
|
except DatasetError as error:
|
|
575
633
|
counts.setdefault('failed', []).append('store: %s' % error)
|
|
576
634
|
return
|
|
635
|
+
pending.extend(events)
|
|
577
636
|
if strict and blob_failures and not counts.get('failed'):
|
|
578
637
|
counts.setdefault('failed', []).extend(blob_failures)
|
|
638
|
+
if not counts.get('failed'):
|
|
639
|
+
try:
|
|
640
|
+
link_stored_group_attempts(pending)
|
|
641
|
+
except Exception as error:
|
|
642
|
+
counts.setdefault('failed', []).append('store: %s' % error)
|
|
579
643
|
|
|
580
644
|
with watch_blob_failures() as blob_failures:
|
|
581
645
|
if path.is_dir():
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""The name a recorded dispatch is counted under in statistics keyed by alias.
|
|
2
|
+
|
|
3
|
+
A dispatch records the alias it was asked for and the model id that alias resolved to then.
|
|
4
|
+
When an alias later moves to a newer model (`terra` from gpt-5.6-terra to gpt-6.1-terra), its
|
|
5
|
+
old dispatches must not be counted as the new model's. `dispatch_name` names such a dispatch
|
|
6
|
+
by the alias that resolves to its recorded model today on the same harness (`terra-5.6`).
|
|
7
|
+
When no alias does, it keeps the alias it recorded: moving an alias without a versioned alias for
|
|
8
|
+
the old model is a choice to count both together. Statistics keyed by model id (routing,
|
|
9
|
+
forecast, efforts, pairs) need none of this.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
# No package import: forge-ui loads this file on its own to name its model rows the same way.
|
|
17
|
+
SKILL = Path(__file__).resolve().parents[2]
|
|
18
|
+
|
|
19
|
+
_CACHE = {}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def registry_models() -> dict:
|
|
23
|
+
"""{alias: {harness: model id}}; the first row of an alias is its default."""
|
|
24
|
+
out = {}
|
|
25
|
+
path = Path(os.environ.get('FORGE_REGISTRY') or str(SKILL / 'registry.tsv'))
|
|
26
|
+
try:
|
|
27
|
+
lines = path.read_text().splitlines()
|
|
28
|
+
except OSError:
|
|
29
|
+
return out
|
|
30
|
+
for line in lines:
|
|
31
|
+
if not line.strip() or line.startswith('#'):
|
|
32
|
+
continue
|
|
33
|
+
cells = line.split('\t')
|
|
34
|
+
if len(cells) >= 3:
|
|
35
|
+
out.setdefault(cells[0], {}).setdefault(cells[1], cells[2])
|
|
36
|
+
return out
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _registry() -> dict:
|
|
40
|
+
key = os.environ.get('FORGE_REGISTRY') or ''
|
|
41
|
+
if key not in _CACHE:
|
|
42
|
+
_CACHE[key] = registry_models()
|
|
43
|
+
return _CACHE[key]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def dispatch_name(d: dict, registry: dict | None = None):
|
|
47
|
+
"""The alias (or model id) a dispatch's event data `d` is counted under, or None."""
|
|
48
|
+
alias, model, harness = d.get('alias'), d.get('model'), d.get('harness')
|
|
49
|
+
if not alias:
|
|
50
|
+
return model or None
|
|
51
|
+
rows = (_registry() if registry is None else registry).get(alias)
|
|
52
|
+
if not rows or not model:
|
|
53
|
+
return alias
|
|
54
|
+
current = rows.get(harness) if harness else None
|
|
55
|
+
if current is None:
|
|
56
|
+
current = next(iter(rows.values()))
|
|
57
|
+
if current == model:
|
|
58
|
+
return alias
|
|
59
|
+
table = _registry() if registry is None else registry
|
|
60
|
+
for other, other_rows in table.items():
|
|
61
|
+
if other == alias:
|
|
62
|
+
continue
|
|
63
|
+
found = other_rows.get(harness) if harness else next(iter(other_rows.values()), None)
|
|
64
|
+
if found == model:
|
|
65
|
+
return other
|
|
66
|
+
return alias
|
|
@@ -22,6 +22,7 @@ from collections import defaultdict
|
|
|
22
22
|
|
|
23
23
|
from . import connect, dataset_dir
|
|
24
24
|
from .export import SURVIVES_AT, Runs, Store
|
|
25
|
+
from .names import dispatch_name
|
|
25
26
|
from .routing import wilson
|
|
26
27
|
|
|
27
28
|
MIN_LANDED = 10
|
|
@@ -63,10 +64,12 @@ def report(runs: Runs, *, horizon_days: int = HORIZON_DAYS, repo: str = None) ->
|
|
|
63
64
|
continue
|
|
64
65
|
reviews = []
|
|
65
66
|
for run, task, attempt in attempts_of.get(commit, ()):
|
|
66
|
-
|
|
67
|
+
# scope group is one review of several tasks, not this task's reviewer.
|
|
68
|
+
reviews += [r for r in runs.dispatches.get((run, task, 'qa'), ())
|
|
69
|
+
if r['attempt'] == attempt and (r.get('d') or {}).get('scope') != 'group']
|
|
67
70
|
passed = {}
|
|
68
71
|
for r in sorted(reviews, key=lambda r: r['ts']):
|
|
69
|
-
name =
|
|
72
|
+
name = dispatch_name(r['d'])
|
|
70
73
|
if r['d'].get('verdict') == 'PASS' and name:
|
|
71
74
|
passed[name] = r['d']
|
|
72
75
|
if not passed:
|
|
@@ -22,7 +22,7 @@ import json
|
|
|
22
22
|
import os
|
|
23
23
|
|
|
24
24
|
from . import connect, dataset_dir
|
|
25
|
-
from .export import SURVIVES_AT, Runs, Store
|
|
25
|
+
from .export import SURVIVES_AT, Runs, Store, _attempts
|
|
26
26
|
from .facts import _kappa
|
|
27
27
|
|
|
28
28
|
LEVELS = ('low', 'medium', 'high')
|
|
@@ -54,9 +54,12 @@ def report(runs: Runs, repo: str = None) -> dict:
|
|
|
54
54
|
first_pass=0, serious=0, landed=0, did_not_hold=0))
|
|
55
55
|
cell['tasks'] += 1
|
|
56
56
|
attempts = runs.attempts.get((run, task)) or []
|
|
57
|
-
|
|
57
|
+
# Only attempts that spent one, as the export counts them: an execution whose prompt changed
|
|
58
|
+
# while it ran (STALE), an infrastructure stop or a refund is not a first attempt.
|
|
59
|
+
spent = _attempts(runs, run, task, attempts)
|
|
60
|
+
if spent:
|
|
58
61
|
cell['attempted'] += 1
|
|
59
|
-
cell['first_pass'] +=
|
|
62
|
+
cell['first_pass'] += spent[0]['events'][-1]['d'].get('status') == 'PASS'
|
|
60
63
|
reviews = runs.dispatches.get((run, task, 'qa')) or []
|
|
61
64
|
cell['serious'] += any(f.get('status') == 'CONFIRMED' and f.get('severity') in (0, 1)
|
|
62
65
|
for e in reviews for f in e['d'].get('findings') or [] if isinstance(f, dict))
|
|
@@ -100,13 +100,18 @@ def tasks(runs: Runs, *, repo=None, since=None) -> list:
|
|
|
100
100
|
continue
|
|
101
101
|
if since and not (events and events[0]['ts'] >= since):
|
|
102
102
|
continue
|
|
103
|
+
# The first counted attempt's dwarf cell. `script` ran tasks/<id>/run, not a model,
|
|
104
|
+
# so the task is not a model's result (history and the tier tables read this list).
|
|
105
|
+
ran = first['events'][0]['d'].get('dwarf') if first else None
|
|
106
|
+
if ran == 'script':
|
|
107
|
+
continue
|
|
103
108
|
started = _started(runs, run, tid, first) if first else None
|
|
104
109
|
decision = decision_before(decisions.get(tid), started)
|
|
105
110
|
resolved = runs.resolved(run, tid, 'dwarf', first['n']) if first else {}
|
|
106
111
|
model = ':'.join(x for x in (resolved.get('model'), resolved.get('effort')) if x) or None
|
|
107
112
|
out.append(dict(
|
|
108
113
|
run=run, task=tid, tier=row.get('declared_difficulty') or row.get('difficulty'),
|
|
109
|
-
ran=
|
|
114
|
+
ran=ran, model=model,
|
|
110
115
|
model_id=resolved.get('model'), effort=resolved.get('effort'),
|
|
111
116
|
first_pass=first['outcome'] if first else None,
|
|
112
117
|
censored=(first['reason'] if first and first['outcome'] is None else (None if first else 'not_run')),
|
|
@@ -26,7 +26,11 @@ File schema, the same at both levels (unknown keys are kept and ignored):
|
|
|
26
26
|
"shadow_rate": number in [0, 1],
|
|
27
27
|
"fast": ["dwarf"|"qa"|"planner"|"review", ...]},
|
|
28
28
|
"gates": {...as above...}, "budget": {...as above...}}},
|
|
29
|
-
"privacy": "never-send"
|
|
29
|
+
"privacy": "never-send",
|
|
30
|
+
"features": {"retro": "off"|"on",
|
|
31
|
+
"brief": {"level": "off"|"advisory"|"gated"|"strict",
|
|
32
|
+
"scope": "task"|"wave"|"plan", "model": "<spec>"},
|
|
33
|
+
"summaries": {"mode": "off"|"on", "model": "<spec>"}}}
|
|
30
34
|
|
|
31
35
|
A spec is alias[:effort[:harness]]. Every key of a profile is optional. Unknown keys inside
|
|
32
36
|
`routing` or `policy` (and unknown tiers under `dwarf`/`qa`) are refused by
|
|
@@ -35,6 +39,12 @@ ignored. `default_profile` names the profile a run uses when none is asked for (
|
|
|
35
39
|
file's beats the repo file's). Two built-in profiles, `balanced` and `lite`
|
|
36
40
|
(builtin_profiles.json, read-only), are found after both files; see profiles.py.
|
|
37
41
|
|
|
42
|
+
`features` is the user file's opt-in for retro, brief mode and generated task summaries.
|
|
43
|
+
`forge config` reads and writes it (keys `retro`, `brief`, `brief.scope`, `brief.model`,
|
|
44
|
+
`summaries`, `summaries.model`). A copy in the repo file is ignored. Plan files, and
|
|
45
|
+
`FORGE_RETRO=off`, `FORGE_BRIEF=off` and `FORGE_SUMMARIES=off`, override it when a run
|
|
46
|
+
resolves the features. `model` is a spec, the same shape as a profile routing spec.
|
|
47
|
+
|
|
38
48
|
A provider's key comes from `key_env` when that variable is set, else from `key_file`; it
|
|
39
49
|
may name both, or neither (a local server may need no key).
|
|
40
50
|
A gate may also be written as a bare mode string ("drift": "on"). USER_ONLY keys count only
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""groups.tsv: a frozen set of tasks with a title and goal.
|
|
2
|
+
|
|
3
|
+
Two opt-in features share it: group review (one QA review covers several tasks) and
|
|
4
|
+
brief mode part 2 (a wave-scoped answer acts on a group). This module is only the data
|
|
5
|
+
layer: parse, validate, derive from waves.tsv, resolve the QA spec, freeze.
|
|
6
|
+
|
|
7
|
+
<plan>/groups.tsv has six tab-separated columns, `#` lines and empty lines ignored:
|
|
8
|
+
|
|
9
|
+
id review qa members title goal
|
|
10
|
+
|
|
11
|
+
`review` is task or group, `qa` a spec or `-`, `members` a comma list of task ids in
|
|
12
|
+
order, `title` and `goal` one line each (`-` when absent). Stdlib only.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import os
|
|
18
|
+
import posixpath
|
|
19
|
+
import re
|
|
20
|
+
import tempfile
|
|
21
|
+
from collections import namedtuple
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
Group = namedtuple('Group', 'id review qa members title goal')
|
|
25
|
+
|
|
26
|
+
HEADER = '# id\treview\tqa\tmembers\ttitle\tgoal'
|
|
27
|
+
FROZEN_REASON = "groups.tsv or a member's deps/files changed since plan; run plan again"
|
|
28
|
+
ID_RE = re.compile(r'[a-z0-9][a-z0-9-]{0,39}')
|
|
29
|
+
SWEEP_ID_RE = re.compile(r'sweep-[0-9]+')
|
|
30
|
+
REVIEWS = ('task', 'group')
|
|
31
|
+
RANK = {'high': 3, 'medium': 2, 'low': 1}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class GroupError(Exception):
|
|
35
|
+
"""A malformed groups.tsv or a broken group rule; the message is one line."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# --- tasks.tsv ----------------------------------------------------------------
|
|
39
|
+
|
|
40
|
+
def _tasks(plan) -> dict:
|
|
41
|
+
"""tasks.tsv rows by id, in file order: id deps difficulty files dwarf qa title."""
|
|
42
|
+
path = Path(plan) / 'tasks.tsv'
|
|
43
|
+
try:
|
|
44
|
+
text = path.read_text()
|
|
45
|
+
except OSError as error:
|
|
46
|
+
raise GroupError('tasks.tsv could not be read: %s' % error.strerror)
|
|
47
|
+
rows = {}
|
|
48
|
+
for number, line in enumerate(text.splitlines(), 1):
|
|
49
|
+
if not line or line.startswith('#'):
|
|
50
|
+
continue
|
|
51
|
+
row = line.split('\t')
|
|
52
|
+
if len(row) != 7:
|
|
53
|
+
raise GroupError('tasks.tsv line %d: needs seven columns, has %d' % (number, len(row)))
|
|
54
|
+
rows[row[0]] = row
|
|
55
|
+
return rows
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _list(value: str) -> list:
|
|
59
|
+
return [item for item in value.split(',') if item and item != '-']
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def overlap(a: str, b: str) -> bool:
|
|
63
|
+
"""forge-schedule.py's overlap, ported exactly: a declared directory covers the
|
|
64
|
+
paths beneath it, and `.` covers everything. `-` declares nothing."""
|
|
65
|
+
def paths(value: str) -> list:
|
|
66
|
+
return [posixpath.normpath(p) for p in value.split(',') if p and p != '-']
|
|
67
|
+
|
|
68
|
+
return any(
|
|
69
|
+
x == '.' or y == '.' or x == y or x.startswith(y + '/') or y.startswith(x + '/')
|
|
70
|
+
for x in paths(a) for y in paths(b)
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# --- groups.tsv ---------------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
def load(plan) -> list:
|
|
77
|
+
path = Path(plan) / 'groups.tsv'
|
|
78
|
+
if not path.is_file():
|
|
79
|
+
return []
|
|
80
|
+
groups = []
|
|
81
|
+
seen = set()
|
|
82
|
+
for number, line in enumerate(path.read_text().splitlines(), 1):
|
|
83
|
+
if not line.strip() or line.startswith('#'):
|
|
84
|
+
continue
|
|
85
|
+
row = line.split('\t')
|
|
86
|
+
where = 'groups.tsv line %d' % number
|
|
87
|
+
if len(row) != 6:
|
|
88
|
+
raise GroupError('%s: needs six columns, has %d' % (where, len(row)))
|
|
89
|
+
gid, review, qa, members, title, goal = row
|
|
90
|
+
if not ID_RE.fullmatch(gid):
|
|
91
|
+
raise GroupError('%s: bad group id %r (use [a-z0-9][a-z0-9-]{0,39})' % (where, gid))
|
|
92
|
+
if gid in seen:
|
|
93
|
+
raise GroupError('%s: duplicate group id %s' % (where, gid))
|
|
94
|
+
seen.add(gid)
|
|
95
|
+
if review not in REVIEWS:
|
|
96
|
+
raise GroupError('%s: review must be task or group, not %r' % (where, review))
|
|
97
|
+
if not qa.strip():
|
|
98
|
+
raise GroupError('%s: qa is empty (use - for none)' % where)
|
|
99
|
+
names = [m.strip() for m in members.split(',')]
|
|
100
|
+
if members.strip() in ('', '-') or any(not m for m in names):
|
|
101
|
+
raise GroupError('%s: members is empty or has an empty entry' % where)
|
|
102
|
+
groups.append(Group(gid, review, qa, tuple(names), title or '-', goal or '-'))
|
|
103
|
+
return groups
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _is_sweep(plan, task: str) -> bool:
|
|
107
|
+
return bool(SWEEP_ID_RE.fullmatch(task)) or (Path(plan) / 'tasks' / task / 'sweep.json').is_file()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _reaches(tasks: dict, start: str, targets: set):
|
|
111
|
+
"""A target task reachable from start through deps (any task, transitively), or None.
|
|
112
|
+
Returns (target, path) where path lists the tasks passed through."""
|
|
113
|
+
stack = [(dep, []) for dep in reversed(_list(tasks[start][1]))]
|
|
114
|
+
seen = {start}
|
|
115
|
+
while stack:
|
|
116
|
+
task, via = stack.pop()
|
|
117
|
+
if task in seen:
|
|
118
|
+
continue
|
|
119
|
+
seen.add(task)
|
|
120
|
+
if task in targets:
|
|
121
|
+
return task, via
|
|
122
|
+
if task in tasks:
|
|
123
|
+
stack.extend((dep, via + [task]) for dep in reversed(_list(tasks[task][1])))
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def validate(plan, groups, max_tasks=6) -> None:
|
|
128
|
+
tasks = _tasks(plan)
|
|
129
|
+
owner = {}
|
|
130
|
+
ids = set()
|
|
131
|
+
for g in groups:
|
|
132
|
+
if g.id in ids:
|
|
133
|
+
raise GroupError('group %s: duplicate group id' % g.id)
|
|
134
|
+
ids.add(g.id)
|
|
135
|
+
for member in g.members:
|
|
136
|
+
if member not in tasks:
|
|
137
|
+
raise GroupError('group %s: member %s is not in tasks.tsv' % (g.id, member))
|
|
138
|
+
if member in owner:
|
|
139
|
+
raise GroupError('group %s: task %s is in two groups (%s and %s)'
|
|
140
|
+
% (g.id, member, owner[member], g.id))
|
|
141
|
+
owner[member] = g.id
|
|
142
|
+
if g.id in tasks:
|
|
143
|
+
raise GroupError('group %s: the id is also a task id' % g.id)
|
|
144
|
+
if g.review != 'group':
|
|
145
|
+
continue
|
|
146
|
+
if len(g.members) < 2:
|
|
147
|
+
raise GroupError('group %s: a review group needs at least 2 members' % g.id)
|
|
148
|
+
if len(g.members) > max_tasks:
|
|
149
|
+
raise GroupError('group %s: %d members, at most %d allowed' % (g.id, len(g.members), max_tasks))
|
|
150
|
+
for member in g.members:
|
|
151
|
+
others = set(g.members) - {member}
|
|
152
|
+
hit = _reaches(tasks, member, others)
|
|
153
|
+
if hit:
|
|
154
|
+
other, via = hit
|
|
155
|
+
how = 'through ' + ', '.join(via) if via else 'directly'
|
|
156
|
+
raise GroupError('group %s: member %s depends on member %s (%s)' % (g.id, member, other, how))
|
|
157
|
+
for i, a in enumerate(g.members):
|
|
158
|
+
for b in g.members[i + 1:]:
|
|
159
|
+
if overlap(tasks[a][3], tasks[b][3]):
|
|
160
|
+
raise GroupError('group %s: members %s and %s declare overlapping files' % (g.id, a, b))
|
|
161
|
+
for member in g.members:
|
|
162
|
+
if _is_sweep(plan, member):
|
|
163
|
+
raise GroupError('group %s: member %s is a sweep task' % (g.id, member))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def derive(plan, review='task', max_tasks=6) -> list:
|
|
167
|
+
"""One group per computed wave with at least two tasks (w1, w2, ...). A wave larger
|
|
168
|
+
than max_tasks splits into w3a, w3b, ... in tasks.tsv order. With review='group',
|
|
169
|
+
high-difficulty tasks stay out and keep their own review."""
|
|
170
|
+
if review not in REVIEWS:
|
|
171
|
+
raise GroupError('review must be task or group, not %r' % review)
|
|
172
|
+
if max_tasks < 2:
|
|
173
|
+
raise GroupError('max tasks must be at least 2')
|
|
174
|
+
tasks = _tasks(plan)
|
|
175
|
+
path = Path(plan) / 'waves.tsv'
|
|
176
|
+
try:
|
|
177
|
+
text = path.read_text()
|
|
178
|
+
except OSError as error:
|
|
179
|
+
raise GroupError('waves.tsv could not be read: %s' % error.strerror)
|
|
180
|
+
waves = {}
|
|
181
|
+
for number, line in enumerate(text.splitlines(), 1):
|
|
182
|
+
if not line or line.startswith('#'):
|
|
183
|
+
continue
|
|
184
|
+
row = line.split('\t')
|
|
185
|
+
if len(row) != 2 or not row[0].isdigit() or row[1] not in tasks:
|
|
186
|
+
raise GroupError('waves.tsv line %d: needs wave<TAB>task with a task from tasks.tsv' % number)
|
|
187
|
+
waves.setdefault(int(row[0]), set()).add(row[1])
|
|
188
|
+
groups = []
|
|
189
|
+
for wave in sorted(waves):
|
|
190
|
+
members = [t for t in tasks if t in waves[wave]]
|
|
191
|
+
if review == 'group':
|
|
192
|
+
members = [t for t in members if tasks[t][2] != 'high']
|
|
193
|
+
chunks = [members[i:i + max_tasks] for i in range(0, len(members), max_tasks)]
|
|
194
|
+
for index, chunk in enumerate(chunks):
|
|
195
|
+
if len(chunk) < 2:
|
|
196
|
+
continue
|
|
197
|
+
suffix = chr(ord('a') + index) if len(chunks) > 1 else ''
|
|
198
|
+
# A derived group has a title and no goal: nothing here knows what the wave is for.
|
|
199
|
+
# plan asks for one, and `forge group set` writes it.
|
|
200
|
+
groups.append(Group('w%d%s' % (wave, suffix), review, '-', tuple(chunk), 'Wave %d%s' % (wave, suffix), '-'))
|
|
201
|
+
return groups
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _cell(value: str) -> str:
|
|
205
|
+
value = ' '.join(str(value).split())
|
|
206
|
+
return value or '-'
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def write(plan, groups) -> None:
|
|
210
|
+
lines = [HEADER] + ['\t'.join([g.id, g.review, _cell(g.qa), ','.join(g.members),
|
|
211
|
+
_cell(g.title), _cell(g.goal)]) for g in groups]
|
|
212
|
+
_atomic(Path(plan) / 'groups.tsv', '\n'.join(lines) + '\n')
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _atomic(path: Path, text: str) -> None:
|
|
216
|
+
fd, temp = tempfile.mkstemp(dir=str(path.parent), prefix='.' + path.name + '.')
|
|
217
|
+
try:
|
|
218
|
+
# mkstemp makes the file 0600, and os.replace keeps that: give it the mode a plain open would.
|
|
219
|
+
mask = os.umask(0)
|
|
220
|
+
os.umask(mask)
|
|
221
|
+
os.fchmod(fd, 0o666 & ~mask)
|
|
222
|
+
with os.fdopen(fd, 'w') as handle:
|
|
223
|
+
handle.write(text)
|
|
224
|
+
os.replace(temp, path)
|
|
225
|
+
except BaseException:
|
|
226
|
+
try:
|
|
227
|
+
os.unlink(temp)
|
|
228
|
+
except OSError:
|
|
229
|
+
pass
|
|
230
|
+
raise
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def resolve_qa(plan, groups) -> list:
|
|
234
|
+
"""For review=group with qa `-`: the qa of the member with the highest difficulty
|
|
235
|
+
(high > medium > low, ties to the first listed), as tasks.tsv has it after plan."""
|
|
236
|
+
tasks = _tasks(plan)
|
|
237
|
+
out = []
|
|
238
|
+
for g in groups:
|
|
239
|
+
if g.review == 'group' and g.qa == '-':
|
|
240
|
+
best = None
|
|
241
|
+
for member in g.members:
|
|
242
|
+
if member in tasks and (best is None or RANK.get(tasks[member][2], 0) > RANK.get(tasks[best][2], 0)):
|
|
243
|
+
best = member
|
|
244
|
+
if best is not None:
|
|
245
|
+
g = g._replace(qa=tasks[best][5] or '-')
|
|
246
|
+
out.append(g)
|
|
247
|
+
return out
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
# --- freeze -------------------------------------------------------------------
|
|
251
|
+
|
|
252
|
+
def freeze_text(plan, groups) -> str:
|
|
253
|
+
"""One line per group with all six columns, each followed by one line per member:
|
|
254
|
+
member<TAB>deps<TAB>files. A member's dwarf column is not part of it."""
|
|
255
|
+
tasks = _tasks(plan)
|
|
256
|
+
lines = []
|
|
257
|
+
for g in groups:
|
|
258
|
+
lines.append('\t'.join([g.id, g.review, g.qa, ','.join(g.members), g.title, g.goal]))
|
|
259
|
+
for member in g.members:
|
|
260
|
+
row = tasks.get(member)
|
|
261
|
+
lines.append('\t'.join([member, row[1], row[3]]) if row else '%s\t<missing>\t<missing>' % member)
|
|
262
|
+
return '\n'.join(lines) + '\n' if lines else ''
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def fingerprint(plan, groups) -> str:
|
|
266
|
+
return hashlib.sha256(freeze_text(plan, groups).encode()).hexdigest()
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def freeze(plan) -> None:
|
|
270
|
+
plan = Path(plan)
|
|
271
|
+
groups = load(plan)
|
|
272
|
+
frozen = plan / 'groups.frozen'
|
|
273
|
+
if not groups:
|
|
274
|
+
try:
|
|
275
|
+
frozen.unlink()
|
|
276
|
+
except FileNotFoundError:
|
|
277
|
+
pass
|
|
278
|
+
return
|
|
279
|
+
_atomic(frozen, fingerprint(plan, groups) + '\n')
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def check_frozen(plan):
|
|
283
|
+
"""None when groups.tsv and its members still match groups.frozen (or neither
|
|
284
|
+
exists); otherwise the reason."""
|
|
285
|
+
plan = Path(plan)
|
|
286
|
+
frozen = plan / 'groups.frozen'
|
|
287
|
+
try:
|
|
288
|
+
groups = load(plan)
|
|
289
|
+
if not groups:
|
|
290
|
+
return FROZEN_REASON if frozen.exists() else None
|
|
291
|
+
if not frozen.is_file():
|
|
292
|
+
return FROZEN_REASON
|
|
293
|
+
return None if frozen.read_text().strip() == fingerprint(plan, groups) else FROZEN_REASON
|
|
294
|
+
except (GroupError, OSError):
|
|
295
|
+
return FROZEN_REASON
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
# --- lookups ------------------------------------------------------------------
|
|
299
|
+
|
|
300
|
+
def group_of(plan, task):
|
|
301
|
+
for g in load(plan):
|
|
302
|
+
if task in g.members:
|
|
303
|
+
return g
|
|
304
|
+
return None
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def members_in_review_groups(plan) -> set:
|
|
308
|
+
return {m for g in load(plan) if g.review == 'group' for m in g.members}
|