@giamme/forge 0.12.1 → 0.13.1
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 +66 -0
- package/README.md +1 -1
- package/SKILL.md +29 -12
- package/VERSION +1 -1
- package/docs/add-ons.md +11 -6
- package/docs/artifacts.md +12 -6
- package/docs/commands.md +179 -17
- package/docs/decomposed-runs.md +13 -5
- package/docs/forge-ui.md +14 -4
- package/docs/memory.md +2 -1
- package/docs/models.md +4 -2
- package/docs/reviews.md +49 -20
- package/docs/troubleshooting.md +3 -1
- package/forge +17 -1
- package/package.json +1 -1
- package/references/dataset.md +39 -13
- package/references/decision-models.md +763 -0
- package/references/decompose.md +166 -29
- package/references/harnesses.md +10 -3
- package/references/planning.md +8 -0
- package/references/solo.md +13 -3
- package/scripts/forge-artifact.sh +30 -4
- package/scripts/forge-config.py +238 -29
- package/scripts/forge-contract.py +95 -56
- package/scripts/forge-control.py +40 -9
- package/scripts/forge-decide.py +6 -0
- package/scripts/forge-dispatch.sh +38 -16
- package/scripts/forge-fail-first.py +2 -2
- package/scripts/forge-gate-addressed.sh +40 -0
- package/scripts/forge-gate-message.sh +64 -0
- package/scripts/forge-issues.py +321 -33
- package/scripts/forge-jev-options.sh +269 -42
- package/scripts/forge-lib-attribute.sh +447 -0
- package/scripts/forge-lib-gates.sh +32 -0
- package/scripts/forge-lib-plans.sh +22 -6
- package/scripts/forge-lib-review.sh +22 -17
- package/scripts/forge-lib-task.sh +217 -38
- package/scripts/forge-lib-verify.sh +45 -8
- package/scripts/forge-memory.sh +3 -3
- package/scripts/forge-parallel-options.sh +18 -5
- package/scripts/forge-parallel.sh +457 -303
- package/scripts/forge-plan-check.py +35 -1
- package/scripts/forge-pre-review.py +437 -0
- package/scripts/forge-prompt.py +25 -5
- package/scripts/forge-route.py +2 -2
- package/scripts/forge-runtime.py +10 -4
- package/scripts/forge-schedule.py +21 -5
- package/scripts/forge-shadow.py +2 -2
- package/scripts/forge-solo.sh +39 -9
- package/scripts/forge-submodules.py +389 -0
- package/scripts/forge-ui-options.sh +25 -0
- package/scripts/forge_dataset/cli.py +12 -6
- package/scripts/forge_dataset/export.py +140 -84
- package/scripts/forge_dataset/harvest.py +33 -5
- package/scripts/{forge_jev/outcome.py → forge_dataset/states.py} +21 -7
- package/scripts/forge_decide/__init__.py +141 -0
- package/scripts/forge_decide/budget.py +180 -0
- package/scripts/forge_decide/cache.py +66 -0
- package/scripts/forge_decide/cli.py +953 -0
- package/scripts/forge_decide/doctor.py +270 -0
- package/scripts/forge_decide/label_addressed.py +75 -0
- package/scripts/forge_decide/label_attribution.py +62 -0
- package/scripts/forge_decide/label_coverage.py +81 -0
- package/scripts/forge_decide/label_message.py +38 -0
- package/scripts/forge_decide/label_prompt.py +139 -0
- package/scripts/forge_decide/labels.py +328 -0
- package/scripts/forge_decide/metrics.py +125 -0
- package/scripts/forge_decide/migrate.py +226 -0
- package/scripts/forge_decide/providers.py +292 -0
- package/scripts/forge_decide/replay.py +350 -0
- package/scripts/forge_decide/report.py +382 -0
- package/scripts/forge_decide/resolve.py +397 -0
- package/scripts/forge_decide/sites.py +377 -0
- package/scripts/forge_jev/__init__.py +202 -104
- package/scripts/forge_jev/addressed.py +171 -0
- package/scripts/forge_jev/attribution.py +198 -0
- package/scripts/forge_jev/cli.py +460 -382
- package/scripts/forge_jev/client.py +155 -77
- package/scripts/forge_jev/coupling.py +19 -87
- package/scripts/forge_jev/coverage.py +303 -0
- package/scripts/forge_jev/findings.py +219 -0
- package/scripts/forge_jev/gates.py +225 -27
- package/scripts/forge_jev/memory.py +65 -4
- package/scripts/forge_jev/message.py +134 -0
- package/scripts/forge_jev/plan_gates.py +294 -0
- package/scripts/forge_jev/questions.py +173 -313
- package/scripts/forge_jev/verify.py +130 -104
- package/ui/README.md +2 -2
- package/ui/docs/api.md +92 -39
- package/ui/forge_ui/control.py +71 -14
- package/ui/forge_ui/export.py +2 -1
- package/ui/forge_ui/models.py +17 -16
- package/ui/forge_ui/reader.py +132 -21
- package/ui/forge_ui/repos.py +428 -0
- package/ui/forge_ui/static/app.js +24 -5
- package/ui/forge_ui/static/cloudmodel.js +8 -5
- package/ui/forge_ui/static/controls.js +20 -13
- package/ui/forge_ui/static/modelstats.js +12 -8
- package/ui/forge_ui/static/panel.js +63 -17
- package/ui/forge_ui/static/runmodel.js +48 -7
- package/ui/forge_ui/static/scene3d.js +2 -15
- package/ui/forge_ui/static/settings.js +481 -68
- package/ui/forge_ui/static/style.css +56 -9
- package/references/jev.md +0 -865
- package/scripts/forge_jev/backtest.py +0 -322
- package/scripts/forge_jev/corpus.py +0 -156
- package/scripts/forge_jev/features.py +0 -24
- package/scripts/forge_jev/predict.py +0 -204
- package/scripts/forge_jev/review.py +0 -73
- package/scripts/forge_jev/routing.py +0 -271
- package/scripts/forge_jev/subset.py +0 -123
package/ui/forge_ui/reader.py
CHANGED
|
@@ -12,7 +12,7 @@ import stat
|
|
|
12
12
|
import time
|
|
13
13
|
import urllib.parse
|
|
14
14
|
|
|
15
|
-
from forge_ui import checks, diffs, executions, findings, fractal, transcripts
|
|
15
|
+
from forge_ui import checks, diffs, executions, findings, fractal, repos, transcripts
|
|
16
16
|
from forge_ui.findings import verdict as _verdict
|
|
17
17
|
|
|
18
18
|
|
|
@@ -694,6 +694,8 @@ def _task_detail(reader, task, run_id, waves, branches):
|
|
|
694
694
|
reader, prefix + '/accepted.by', task['accepted_by'])
|
|
695
695
|
for field, filename in [('prompt', 'prompt.md'), ('approach', 'approach.md'), ('retry_findings', 'retry_findings.md')]:
|
|
696
696
|
task[field] = reader.cap(reader.text(prefix + '/' + filename), prefix + '/' + field)
|
|
697
|
+
# the implementer's question for the user, when the task stopped NEEDS_INPUT
|
|
698
|
+
task['needs_input'] = reader.cap(reader.text(prefix + '/needs_input.md'), prefix + '/needs_input')
|
|
697
699
|
task['route'] = []
|
|
698
700
|
for n, line in enumerate((reader.text(prefix + '/route.jsonl') or '').splitlines(), 1):
|
|
699
701
|
if line.strip():
|
|
@@ -702,16 +704,6 @@ def _task_detail(reader, task, run_id, waves, branches):
|
|
|
702
704
|
task['route'].append(obj)
|
|
703
705
|
task['explored'] = reader.exists(prefix + '/route.explored') or any(
|
|
704
706
|
item.get('explored') is True for item in task['route'])
|
|
705
|
-
task['clef'] = {'first_pass': reader.object(prefix + '/clef.first_pass'), 'retry_pass': {}}
|
|
706
|
-
for child in reader.children(prefix):
|
|
707
|
-
if child.name.startswith('clef.retry_pass.'):
|
|
708
|
-
suffix = child.name[len('clef.retry_pass.'):]
|
|
709
|
-
if not re.fullmatch(r'[0-9]+', suffix):
|
|
710
|
-
reader.warn(prefix + '/' + child.name, 'invalid attempt suffix')
|
|
711
|
-
continue
|
|
712
|
-
obj = reader.object(prefix + '/' + child.name)
|
|
713
|
-
if obj is not None:
|
|
714
|
-
task['clef']['retry_pass'][suffix] = obj
|
|
715
707
|
execs = _task_execs(reader, task)
|
|
716
708
|
task['executions'] = execs
|
|
717
709
|
task['now'] = _now(reader, prefix, execs) if task['status'] == 'RUNNING' else None
|
|
@@ -721,6 +713,7 @@ def _task_detail(reader, task, run_id, waves, branches):
|
|
|
721
713
|
task['gate'] = _gate(reader, prefix + '/qa.gate')
|
|
722
714
|
task['known_issues'] = _nonempty(reader, prefix + '/known_issues.md')
|
|
723
715
|
task['fail_first'] = _fail_first(reader, prefix + '/failfirst.json')
|
|
716
|
+
task['pre_review'] = _pre_review(reader, prefix + '/prereview.json')
|
|
724
717
|
task['sweep'] = _sweep_task(reader, prefix, task['status'])
|
|
725
718
|
task['swept'] = []
|
|
726
719
|
shadows = _shadows(reader, ident, execs)
|
|
@@ -812,6 +805,35 @@ _TASK_CONTROLS = ('qa_threshold', 'retry_budget', 'retries.used', 'escalation.pi
|
|
|
812
805
|
_FAIL_FIRST_RESULTS = ('proven', 'passes_without_change', 'inconclusive', 'error')
|
|
813
806
|
|
|
814
807
|
|
|
808
|
+
_PRE_REVIEW_STATUSES = ('passed', 'flaky', 'pre-existing', 'failed', 'skipped', 'error')
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
def _pre_review(reader, name):
|
|
812
|
+
"""prereview.json (forge-pre-review.py, opt-in #85): the tests the attempt affects, run before its review."""
|
|
813
|
+
obj = reader.object(name)
|
|
814
|
+
if obj is None:
|
|
815
|
+
return None
|
|
816
|
+
if obj.get('status') not in _PRE_REVIEW_STATUSES:
|
|
817
|
+
reader.warn(name, 'unknown pre-review status')
|
|
818
|
+
return None
|
|
819
|
+
|
|
820
|
+
def paths(key):
|
|
821
|
+
value = obj.get(key)
|
|
822
|
+
return [p for p in value if isinstance(p, str)] if isinstance(value, list) else []
|
|
823
|
+
|
|
824
|
+
tail = None
|
|
825
|
+
for run in reversed(obj.get('runs') if isinstance(obj.get('runs'), list) else []):
|
|
826
|
+
if isinstance(run, dict) and type(run.get('rc')) is int and run['rc'] != 0 and isinstance(run.get('tail'), str):
|
|
827
|
+
tail = run['tail'][-2000:]
|
|
828
|
+
break
|
|
829
|
+
seconds = obj.get('seconds')
|
|
830
|
+
return dict(status=obj['status'], reason=obj.get('reason') if isinstance(obj.get('reason'), str) else None,
|
|
831
|
+
command=obj.get('command') if isinstance(obj.get('command'), str) else None,
|
|
832
|
+
selected=paths('selected'), failing=paths('failing'), preexisting=paths('preexisting'),
|
|
833
|
+
flaky=paths('flaky'), seconds=seconds if isinstance(seconds, (int, float)) and not isinstance(seconds, bool) else None,
|
|
834
|
+
tail=tail)
|
|
835
|
+
|
|
836
|
+
|
|
815
837
|
def _fail_first(reader, name):
|
|
816
838
|
"""failfirst.json (forge-fail-first.py, opt-in): did each new test fail without the change?"""
|
|
817
839
|
obj = reader.object(name)
|
|
@@ -1233,6 +1255,21 @@ def _timeline(pool, runs, verifications):
|
|
|
1233
1255
|
runs=runs, verifications=verifications)
|
|
1234
1256
|
|
|
1235
1257
|
|
|
1258
|
+
# scripts/forge-contract.py DEFAULT_THRESHOLD: what a run with no qa_threshold file blocks on.
|
|
1259
|
+
_DEFAULT_THRESHOLD = 'P2'
|
|
1260
|
+
|
|
1261
|
+
|
|
1262
|
+
def _threshold(reader):
|
|
1263
|
+
"""(effective level, 'set' | 'default') from the qa_threshold file; `none` in a file means P3.
|
|
1264
|
+
Anything else that is not P0..P3 is ignored, as the gate and forge-control.py ignore it."""
|
|
1265
|
+
value = (reader.line('qa_threshold') or '').replace(' ', '').upper()
|
|
1266
|
+
if value == 'NONE':
|
|
1267
|
+
return 'P3', 'set'
|
|
1268
|
+
if value in ('P0', 'P1', 'P2', 'P3'):
|
|
1269
|
+
return value, 'set'
|
|
1270
|
+
return _DEFAULT_THRESHOLD, 'default'
|
|
1271
|
+
|
|
1272
|
+
|
|
1236
1273
|
_SOLO_SETTINGS = ('explore', 'shadow_rate', 'shadow_qa', 'timeout', 'max_parallel', 'qa_threshold',
|
|
1237
1274
|
'escalate_after', 'verify_retries', 'final_qa')
|
|
1238
1275
|
|
|
@@ -1242,7 +1279,9 @@ def _solo_detail(reader, source):
|
|
|
1242
1279
|
status = next(iter(result['counts']))
|
|
1243
1280
|
result['request'] = reader.cap(reader.text('request.md'), 'request')
|
|
1244
1281
|
result['settings'] = dict.fromkeys(_SOLO_SETTINGS)
|
|
1282
|
+
result['settings']['qa_threshold'], result['settings']['qa_threshold_source'] = _threshold(reader)
|
|
1245
1283
|
result['verification'] = None
|
|
1284
|
+
result['attribution'] = _attribution(reader)
|
|
1246
1285
|
result['waves'] = [['solo']]
|
|
1247
1286
|
attempts = _history(reader, 'attempts.tsv')
|
|
1248
1287
|
qa = reader.text('qa.last')
|
|
@@ -1252,13 +1291,13 @@ def _solo_detail(reader, source):
|
|
|
1252
1291
|
branch=None, attempt=max((item['attempt'] for item in attempts), default=None),
|
|
1253
1292
|
attempts=attempts, escalations=[], verdict=_verdict(qa), accepted_by=None,
|
|
1254
1293
|
accepted=False, accepted_attempt=None, accepted_over=None,
|
|
1255
|
-
explored=False, route=[],
|
|
1294
|
+
explored=False, route=[], shadow=[],
|
|
1256
1295
|
prompt=reader.cap(reader.text('prompt.md'), 'tasks/solo/prompt'), approach=None,
|
|
1257
|
-
retry_findings=None, qa_tail=reader.cap(qa, 'tasks/solo/qa_tail', 4000, True),
|
|
1296
|
+
retry_findings=None, needs_input=None, qa_tail=reader.cap(qa, 'tasks/solo/qa_tail', 4000, True),
|
|
1258
1297
|
dwarf_tail=reader.cap(reader.text('dwarf.last'), 'tasks/solo/dwarf_tail', 4000, True),
|
|
1259
1298
|
executions=execs, merged_at=None, findings=executions.summary_of(qa),
|
|
1260
1299
|
gate=_gate(reader, 'qa.gate'), known_issues=_nonempty(reader, 'known_issues.md'),
|
|
1261
|
-
fail_first=_fail_first(reader, 'failfirst.json'),
|
|
1300
|
+
fail_first=_fail_first(reader, 'failfirst.json'), pre_review=None,
|
|
1262
1301
|
now=_now(reader, '', execs) if status == 'RUNNING' else None, waiting=None, sweep=None, swept=[])
|
|
1263
1302
|
result.update(timeline=_timeline(execs, [], []), integration=None, final_review=None, final_reviews=[],
|
|
1264
1303
|
deferrals=[], findings_available=findings.available(), fractal=fractal.summary(reader),
|
|
@@ -1282,15 +1321,48 @@ def _waves(reader):
|
|
|
1282
1321
|
return waves, wave_map
|
|
1283
1322
|
|
|
1284
1323
|
|
|
1324
|
+
# --- attribution: the result of `forge-parallel.sh attribute` ------------------------------------
|
|
1325
|
+
|
|
1326
|
+
_ATTRIBUTION_KEYS = ('culprit', 'base_fails', 'inconclusive', 'verification_runs', 'gate')
|
|
1327
|
+
|
|
1328
|
+
|
|
1329
|
+
def _is_text_or_null(value):
|
|
1330
|
+
return value is None or isinstance(value, str)
|
|
1331
|
+
|
|
1332
|
+
|
|
1333
|
+
def _attribution(reader):
|
|
1334
|
+
"""RunDetail.attribution from attribution.json, or null when there is none or any field is missing or of the
|
|
1335
|
+
wrong type (warned): a half-valid file is not evidence for a culprit."""
|
|
1336
|
+
name = 'attribution.json'
|
|
1337
|
+
obj = reader.object(name)
|
|
1338
|
+
if obj is None:
|
|
1339
|
+
return None
|
|
1340
|
+
gate = obj.get('gate')
|
|
1341
|
+
outcome = gate.get('outcome') if isinstance(gate, dict) else None
|
|
1342
|
+
runs = obj.get('verification_runs')
|
|
1343
|
+
if not (all(key in obj for key in _ATTRIBUTION_KEYS)
|
|
1344
|
+
and _is_text_or_null(obj['culprit']) and _is_text_or_null(obj['inconclusive'])
|
|
1345
|
+
and isinstance(obj['base_fails'], bool)
|
|
1346
|
+
and isinstance(runs, int) and not isinstance(runs, bool)
|
|
1347
|
+
and (gate is None or isinstance(gate, dict)) and _is_text_or_null(outcome)):
|
|
1348
|
+
reader.warn(name, 'not an attribution')
|
|
1349
|
+
return None
|
|
1350
|
+
return dict(culprit=_text_or_none(obj['culprit'], 200), base_fails=obj['base_fails'],
|
|
1351
|
+
inconclusive=_text_or_none(obj['inconclusive'], 400), verification_runs=runs,
|
|
1352
|
+
gate_outcome=_text_or_none(outcome, 40))
|
|
1353
|
+
|
|
1354
|
+
|
|
1285
1355
|
def detail(path, source='plan') -> dict:
|
|
1286
1356
|
reader = _Read(path)
|
|
1287
1357
|
if _kind(reader.path) == 'solo':
|
|
1288
1358
|
return _solo_detail(reader, source)
|
|
1289
1359
|
result, tasks = _summary(reader, source)
|
|
1290
1360
|
result['request'] = reader.cap(reader.text('request.md'), 'request')
|
|
1361
|
+
threshold = _threshold(reader)
|
|
1291
1362
|
result['settings'] = dict(explore=reader.number('explore'), shadow_rate=reader.number('shadow_rate'),
|
|
1292
1363
|
shadow_qa=_list(reader.text('shadow_qa') or ''), timeout=reader.number('timeout', int),
|
|
1293
|
-
max_parallel=reader.number('max_parallel', int),
|
|
1364
|
+
max_parallel=reader.number('max_parallel', int),
|
|
1365
|
+
qa_threshold=threshold[0], qa_threshold_source=threshold[1],
|
|
1294
1366
|
escalate_after=reader.number('escalate_after', int),
|
|
1295
1367
|
verify_retries=reader.number('verify_retries', int), final_qa=reader.line('final_qa'))
|
|
1296
1368
|
waves, wave_map = _waves(reader)
|
|
@@ -1307,6 +1379,7 @@ def detail(path, source='plan') -> dict:
|
|
|
1307
1379
|
run_execs = _run_execs(reader)
|
|
1308
1380
|
result['verification'] = _verification(reader, result['verification_status'],
|
|
1309
1381
|
[item for item in run_execs if item['role'] == 'verification'])
|
|
1382
|
+
result['attribution'] = _attribution(reader)
|
|
1310
1383
|
items, integrations = executions.review_dirs(reader)
|
|
1311
1384
|
published = _published(reader)
|
|
1312
1385
|
reviews = []
|
|
@@ -2170,18 +2243,52 @@ def verification_log(path, lane=None, k=None, first=None, retry=False, source='p
|
|
|
2170
2243
|
return _log_tail(stream, info, name) if first is None else _log_range(stream, info, name, first)
|
|
2171
2244
|
|
|
2172
2245
|
|
|
2246
|
+
def batch(found):
|
|
2247
|
+
"""The runs among `found` ((path, source) pairs of discover) as [(path, source, entry)], and
|
|
2248
|
+
{run dir: identity} for them. An entry is (run dir, repo text, kind), what repos.resolve takes.
|
|
2249
|
+
|
|
2250
|
+
One repos.resolve call over the whole batch, so the base-commit step sees every known root; a
|
|
2251
|
+
run resolved on its own could miss its root.
|
|
2252
|
+
"""
|
|
2253
|
+
listed = []
|
|
2254
|
+
for path, source in found:
|
|
2255
|
+
kind = _kind(path)
|
|
2256
|
+
if kind:
|
|
2257
|
+
reader = _Read(path)
|
|
2258
|
+
listed.append((path, source, (str(reader.path), reader.line('repo'), kind)))
|
|
2259
|
+
return listed, repos.resolve([entry for _path, _source, entry in listed])
|
|
2260
|
+
|
|
2261
|
+
|
|
2262
|
+
def repo_root(identity, repo):
|
|
2263
|
+
"""A run's grouping key: its identity's root, or its repo text when nothing better is known."""
|
|
2264
|
+
return identity['root'] or repo
|
|
2265
|
+
|
|
2266
|
+
|
|
2267
|
+
def _with_repo(result, identity):
|
|
2268
|
+
"""A run summary or detail with its repository fields: repo_root (the grouping key), repo_worktree
|
|
2269
|
+
(the checkout it started in, null when that is the root) and repo_branch (null when unknown)."""
|
|
2270
|
+
result.update(repo_root=repo_root(identity, result['repo']), repo_worktree=identity['worktree'],
|
|
2271
|
+
repo_branch=identity['branch'])
|
|
2272
|
+
return result
|
|
2273
|
+
|
|
2274
|
+
|
|
2173
2275
|
class Catalog:
|
|
2174
2276
|
def __init__(self, plans=(), roots=(), registry=True, registry_dir=None):
|
|
2175
2277
|
self.options = dict(plans=tuple(plans), roots=tuple(roots), registry=registry, registry_dir=registry_dir)
|
|
2176
2278
|
|
|
2177
2279
|
def runs(self):
|
|
2178
|
-
|
|
2179
|
-
for path, source in
|
|
2180
|
-
result = summarize(path, source)
|
|
2181
|
-
if _kind(path):
|
|
2182
|
-
runs.append(result)
|
|
2280
|
+
listed, identities = batch(discover(**self.options))
|
|
2281
|
+
runs = [_with_repo(summarize(path, source), identities[entry[0]]) for path, source, entry in listed]
|
|
2183
2282
|
return sorted(runs, key=lambda item: item['updated'] if item['updated'] is not None else float('-inf'), reverse=True)
|
|
2184
2283
|
|
|
2284
|
+
def identity(self, key):
|
|
2285
|
+
"""The identity of the run with this key, resolved in the same batch as the list; None for no such run."""
|
|
2286
|
+
listed, identities = batch(discover(**self.options))
|
|
2287
|
+
for path, _source, entry in listed:
|
|
2288
|
+
if run_key(path) == key:
|
|
2289
|
+
return identities[entry[0]]
|
|
2290
|
+
return None
|
|
2291
|
+
|
|
2185
2292
|
def _find(self, key, read, *args):
|
|
2186
2293
|
for path, source in discover(**self.options):
|
|
2187
2294
|
if run_key(path) == key:
|
|
@@ -2200,7 +2307,11 @@ class Catalog:
|
|
|
2200
2307
|
return None
|
|
2201
2308
|
|
|
2202
2309
|
def get(self, key):
|
|
2203
|
-
|
|
2310
|
+
listed, identities = batch(discover(**self.options))
|
|
2311
|
+
for path, source, entry in listed:
|
|
2312
|
+
if run_key(path) == key:
|
|
2313
|
+
return _with_repo(detail(path, source=source), identities[entry[0]])
|
|
2314
|
+
return None
|
|
2204
2315
|
|
|
2205
2316
|
def task(self, key, task_id):
|
|
2206
2317
|
return self._find(key, task_detail, task_id)
|
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
"""Resolve which repository each forge run belongs to, for new and old runs.
|
|
2
|
+
|
|
3
|
+
forge-ui used to group runs by the literal text of each run's ``repo`` file, which is the checkout
|
|
4
|
+
the run started in. A run started from a git worktree therefore looked like one more repository,
|
|
5
|
+
and once the worktree was removed its path could never be resolved again. This module turns a run
|
|
6
|
+
into an identity instead. It is read-only: it never writes a run dir or a repository.
|
|
7
|
+
|
|
8
|
+
Public interface::
|
|
9
|
+
|
|
10
|
+
Run = (path, repo, kind)
|
|
11
|
+
path the run dir
|
|
12
|
+
repo the text of its ``repo`` file, or None
|
|
13
|
+
kind 'plan' or 'solo'
|
|
14
|
+
|
|
15
|
+
resolve(runs) -> {path: Identity}
|
|
16
|
+
Resolves a batch of runs, for example every run the catalog lists. Each Identity is a dict
|
|
17
|
+
{root, worktree, branch, source}:
|
|
18
|
+
root the repository's main working tree and the grouping key; never None when the
|
|
19
|
+
run has a ``repo`` text (None only when it has none)
|
|
20
|
+
worktree the physical checkout when it differs from root, else None
|
|
21
|
+
branch the branch checked out when the run was created, else None (unknown)
|
|
22
|
+
source how it was found: 'identity', 'live', 'base-commit' or 'path'
|
|
23
|
+
|
|
24
|
+
The order for each run:
|
|
25
|
+
|
|
26
|
+
1. ``repo.identity`` in the run dir (one JSON object written by forge: root, worktree, branch).
|
|
27
|
+
Used when ``root`` is an absolute path; ``worktree`` and ``branch`` are taken when strings.
|
|
28
|
+
``root`` is not checked for existence: the identity was right when it was written.
|
|
29
|
+
2. The ``repo`` path still exists and is a git checkout: root is the first entry of
|
|
30
|
+
``git worktree list --porcelain``. worktree is the linked checkout holding ``repo`` (None
|
|
31
|
+
when that is root itself); branch is unknown. Source 'live'.
|
|
32
|
+
3. The ``repo`` path is gone: the run's base commit (``integration.base`` or else the first
|
|
33
|
+
readable ``tasks/*/base_ref`` for a plan, ``dwarf.head.before`` for a solo run) is looked for in
|
|
34
|
+
the known roots, the roots steps 1 and 2 found in this batch that still exist. Exactly one
|
|
35
|
+
match: root is that one and worktree is the ``repo`` text. Source 'base-commit'.
|
|
36
|
+
4. Otherwise today's behaviour: root is the ``repo`` text. Source 'path'. A run is never grouped
|
|
37
|
+
under a repository it might not belong to.
|
|
38
|
+
|
|
39
|
+
Cost: every git call is an argument list with ``-C <absolute existing dir>``, stdin closed and a
|
|
40
|
+
short timeout; a failure or timeout means "not found". Within one ``resolve`` call ``git worktree
|
|
41
|
+
list`` runs at most once per distinct repo path and ``cat-file`` at most once per (root, sha).
|
|
42
|
+
Results from steps 2 and 3 are cached for the life of the process by run dir (the repository of a
|
|
43
|
+
run never changes); a step 4 result is cached with the known roots it was checked against and is
|
|
44
|
+
resolved again only when that set changes or its repo path appears or vanishes. Step 1 needs no
|
|
45
|
+
git and is not cached.
|
|
46
|
+
"""
|
|
47
|
+
from __future__ import annotations
|
|
48
|
+
|
|
49
|
+
import json
|
|
50
|
+
import os
|
|
51
|
+
import re
|
|
52
|
+
import stat
|
|
53
|
+
import subprocess
|
|
54
|
+
import threading
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
_GIT_TIMEOUT = 5
|
|
58
|
+
# repo.identity is a few hundred bytes; anything bigger is not ours.
|
|
59
|
+
_MAX_IDENTITY_BYTES = 64 * 1024
|
|
60
|
+
# A commit id is one short line.
|
|
61
|
+
_MAX_LINE_BYTES = 4096
|
|
62
|
+
_SHA = re.compile(r'(?:[0-9a-f]{40}|[0-9a-f]{64})')
|
|
63
|
+
|
|
64
|
+
# (path, repo) -> identity, for runs resolved by step 2 or 3.
|
|
65
|
+
_RESOLVED: dict = {}
|
|
66
|
+
# (path, repo) -> (frozenset of known roots, repo was a directory, identity), for runs that fell
|
|
67
|
+
# through to step 4.
|
|
68
|
+
_FALLTHROUGH: dict = {}
|
|
69
|
+
_LOCK = threading.Lock()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _identity(root, worktree=None, branch=None, source='path'):
|
|
73
|
+
return {'root': root, 'worktree': worktree, 'branch': branch, 'source': source}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _read_file(path, limit):
|
|
77
|
+
"""Up to ``limit`` bytes of a regular file as text, or None (missing, unreadable, not a file).
|
|
78
|
+
|
|
79
|
+
One byte more than the limit is read so an oversized file is told apart from one that fits:
|
|
80
|
+
that returns None as well.
|
|
81
|
+
"""
|
|
82
|
+
fd = None
|
|
83
|
+
try:
|
|
84
|
+
# O_NONBLOCK: opening a fifo someone left in a run dir must not hang the reader.
|
|
85
|
+
fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NONBLOCK', 0))
|
|
86
|
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
|
87
|
+
return None
|
|
88
|
+
data = b''
|
|
89
|
+
while len(data) <= limit:
|
|
90
|
+
chunk = os.read(fd, limit + 1 - len(data))
|
|
91
|
+
if not chunk:
|
|
92
|
+
break
|
|
93
|
+
data += chunk
|
|
94
|
+
except (OSError, ValueError):
|
|
95
|
+
return None
|
|
96
|
+
finally:
|
|
97
|
+
if fd is not None:
|
|
98
|
+
os.close(fd)
|
|
99
|
+
if len(data) > limit:
|
|
100
|
+
return None
|
|
101
|
+
return data.decode('utf-8', 'replace')
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _read_line(path):
|
|
105
|
+
text = _read_file(path, _MAX_LINE_BYTES)
|
|
106
|
+
if text is None:
|
|
107
|
+
return None
|
|
108
|
+
lines = text.strip().splitlines()
|
|
109
|
+
return lines[0].strip() if lines else None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _is_dir(path) -> bool:
|
|
113
|
+
try:
|
|
114
|
+
return os.path.isabs(path) and os.path.isdir(path)
|
|
115
|
+
except (OSError, ValueError):
|
|
116
|
+
return False
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _real(path):
|
|
120
|
+
try:
|
|
121
|
+
return os.path.realpath(path)
|
|
122
|
+
except (OSError, ValueError):
|
|
123
|
+
return path
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _run_git(cwd, *args):
|
|
127
|
+
"""CompletedProcess of ``git -C cwd <args>``, or None when git could not run or timed out.
|
|
128
|
+
|
|
129
|
+
``cwd`` is an absolute existing directory. No shell, stdin closed, output captured.
|
|
130
|
+
"""
|
|
131
|
+
try:
|
|
132
|
+
return subprocess.run(
|
|
133
|
+
['git', '-C', cwd, *args], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
|
134
|
+
stderr=subprocess.DEVNULL, timeout=_GIT_TIMEOUT, check=False,
|
|
135
|
+
env=dict(os.environ, GIT_TERMINAL_PROMPT='0'))
|
|
136
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
137
|
+
return None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# ---- step 1: repo.identity ---------------------------------------------------------------------
|
|
141
|
+
|
|
142
|
+
def _from_identity_file(run_dir):
|
|
143
|
+
text = _read_file(os.path.join(run_dir, 'repo.identity'), _MAX_IDENTITY_BYTES)
|
|
144
|
+
if text is None:
|
|
145
|
+
return None
|
|
146
|
+
try:
|
|
147
|
+
data = json.loads(text)
|
|
148
|
+
except (ValueError, RecursionError):
|
|
149
|
+
return None
|
|
150
|
+
if not isinstance(data, dict):
|
|
151
|
+
return None
|
|
152
|
+
root = data.get('root')
|
|
153
|
+
if not isinstance(root, str) or '\0' in root or not os.path.isabs(root):
|
|
154
|
+
return None
|
|
155
|
+
worktree, branch = data.get('worktree'), data.get('branch')
|
|
156
|
+
return _identity(root, worktree if isinstance(worktree, str) else None,
|
|
157
|
+
branch if isinstance(branch, str) else None, 'identity')
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
# ---- step 2: the repo path is a live checkout --------------------------------------------------
|
|
161
|
+
|
|
162
|
+
def _checkout_identity(repo):
|
|
163
|
+
"""``(ran, identity)`` for the checkout ``repo``: identity is None when ``repo`` is no checkout
|
|
164
|
+
or its listing could not be read safely; ran is False when git did not run or timed out.
|
|
165
|
+
|
|
166
|
+
``-z`` keeps a path that contains a newline in one piece. A git too old for it (exit 129)
|
|
167
|
+
falls back to ``_legacy_identity``.
|
|
168
|
+
"""
|
|
169
|
+
done = _run_git(repo, 'worktree', 'list', '--porcelain', '-z')
|
|
170
|
+
if done is None:
|
|
171
|
+
return False, None
|
|
172
|
+
if done.returncode == 129:
|
|
173
|
+
return _legacy_identity(repo)
|
|
174
|
+
if done.returncode != 0:
|
|
175
|
+
return True, None
|
|
176
|
+
return True, _live_identity(repo, _porcelain_z_paths(done.stdout) or [])
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _porcelain_z_paths(out):
|
|
180
|
+
"""The worktree paths of ``git worktree list --porcelain -z`` output, in order, or None unless
|
|
181
|
+
the whole output is well formed.
|
|
182
|
+
|
|
183
|
+
Every field ends with a NUL and every record with one more (an empty field). A record starts
|
|
184
|
+
with ``worktree <absolute path>``; the fields after it are not read but may not be empty.
|
|
185
|
+
"""
|
|
186
|
+
if not isinstance(out, bytes) or not out.endswith(b'\0'):
|
|
187
|
+
return None
|
|
188
|
+
fields = out[:-1].split(b'\0')
|
|
189
|
+
paths = []
|
|
190
|
+
at_start = True
|
|
191
|
+
for field in fields:
|
|
192
|
+
if at_start:
|
|
193
|
+
if not field.startswith(b'worktree '):
|
|
194
|
+
return None
|
|
195
|
+
path = os.fsdecode(field[len(b'worktree '):])
|
|
196
|
+
if not os.path.isabs(path):
|
|
197
|
+
return None
|
|
198
|
+
paths.append(path)
|
|
199
|
+
at_start = False
|
|
200
|
+
elif not field:
|
|
201
|
+
at_start = True
|
|
202
|
+
# The last field must have closed a record.
|
|
203
|
+
return paths if at_start and paths else None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _rev_parse_path(repo, option):
|
|
207
|
+
"""``(ran, path)`` for a ``git rev-parse`` option that prints one path, made absolute.
|
|
208
|
+
|
|
209
|
+
One value per call, so a newline inside the path cannot split it: only git's final newline
|
|
210
|
+
is dropped.
|
|
211
|
+
"""
|
|
212
|
+
done = _run_git(repo, 'rev-parse', option)
|
|
213
|
+
if done is None:
|
|
214
|
+
return False, None
|
|
215
|
+
out = done.stdout.decode('utf-8', 'replace')
|
|
216
|
+
if done.returncode != 0 or not out.endswith('\n') or out == '\n':
|
|
217
|
+
return True, None
|
|
218
|
+
return True, os.path.join(repo, out[:-1])
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _git_dir_of(root):
|
|
222
|
+
"""The git dir of the working tree ``root`` (its ``.git`` directory or the one a ``.git``
|
|
223
|
+
file names), or None."""
|
|
224
|
+
if not _is_dir(root):
|
|
225
|
+
return None
|
|
226
|
+
dot = os.path.join(root, '.git')
|
|
227
|
+
if os.path.isdir(dot):
|
|
228
|
+
return dot
|
|
229
|
+
text = _read_file(dot, _MAX_LINE_BYTES)
|
|
230
|
+
if text is None or not text.startswith('gitdir: '):
|
|
231
|
+
return None
|
|
232
|
+
lines = text[len('gitdir: '):].splitlines()
|
|
233
|
+
return os.path.join(root, lines[0]) if lines and lines[0] else None
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _legacy_identity(repo):
|
|
237
|
+
"""``(ran, identity)`` from line-separated porcelain output, for a git without ``-z``.
|
|
238
|
+
|
|
239
|
+
Without ``-z`` a path containing a newline is split over several lines, and its fragments can
|
|
240
|
+
look like porcelain fields or whole entries, including a path that names another repository.
|
|
241
|
+
No reading of the lines can tell, so the shape is not trusted at all: the first line's path is
|
|
242
|
+
taken as the main working tree only when its git dir is the common dir of ``repo``'s
|
|
243
|
+
repository. The checkout holding ``repo`` comes from ``--show-toplevel``, which prints one path.
|
|
244
|
+
"""
|
|
245
|
+
done = _run_git(repo, 'worktree', 'list', '--porcelain')
|
|
246
|
+
if done is None:
|
|
247
|
+
return False, None
|
|
248
|
+
if done.returncode != 0:
|
|
249
|
+
return True, None
|
|
250
|
+
first = done.stdout.decode('utf-8', 'replace').split('\n', 1)[0]
|
|
251
|
+
root = first[len('worktree '):] if first.startswith('worktree ') else ''
|
|
252
|
+
if not os.path.isabs(root):
|
|
253
|
+
return True, None
|
|
254
|
+
root_git_dir = _git_dir_of(root)
|
|
255
|
+
if root_git_dir is None:
|
|
256
|
+
return True, None
|
|
257
|
+
ran, common = _rev_parse_path(repo, '--git-common-dir')
|
|
258
|
+
if common is None or _real(common) != _real(root_git_dir):
|
|
259
|
+
return ran, None
|
|
260
|
+
ran, top = _rev_parse_path(repo, '--show-toplevel')
|
|
261
|
+
if not ran:
|
|
262
|
+
return False, None
|
|
263
|
+
# No toplevel (repo is inside a git dir): the verified root alone is listed.
|
|
264
|
+
return True, _live_identity(repo, [root] + ([top] if top else []))
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _live_identity(repo, entries):
|
|
268
|
+
"""Identity from the worktree list of ``repo``; None when it listed nothing usable."""
|
|
269
|
+
if not entries:
|
|
270
|
+
return None
|
|
271
|
+
root = entries[0]
|
|
272
|
+
here, real_root = _real(repo), _real(root)
|
|
273
|
+
holder = None
|
|
274
|
+
for entry in entries:
|
|
275
|
+
real = _real(entry)
|
|
276
|
+
if (here == real or here.startswith(real.rstrip(os.sep) + os.sep)) and (
|
|
277
|
+
holder is None or len(real) > len(holder[1])):
|
|
278
|
+
holder = (entry, real)
|
|
279
|
+
if holder is None:
|
|
280
|
+
worktree = None if here == real_root else here
|
|
281
|
+
else:
|
|
282
|
+
worktree = None if holder[1] == real_root else holder[0]
|
|
283
|
+
return _identity(root, worktree, None, 'live')
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
# ---- step 3: the base commit is in exactly one known root --------------------------------------
|
|
287
|
+
|
|
288
|
+
def _base_commit(run_dir, kind):
|
|
289
|
+
"""The run's base commit as lower-case hex, or None when unknown or not a commit id."""
|
|
290
|
+
if kind == 'plan':
|
|
291
|
+
line = _read_line(os.path.join(run_dir, 'integration.base'))
|
|
292
|
+
if not line:
|
|
293
|
+
try:
|
|
294
|
+
with os.scandir(os.path.join(run_dir, 'tasks')) as entries:
|
|
295
|
+
names = sorted(entry.name for entry in entries)
|
|
296
|
+
except (OSError, ValueError):
|
|
297
|
+
names = []
|
|
298
|
+
for name in names:
|
|
299
|
+
line = _read_line(os.path.join(run_dir, 'tasks', name, 'base_ref'))
|
|
300
|
+
if line:
|
|
301
|
+
break
|
|
302
|
+
elif kind == 'solo':
|
|
303
|
+
line = _read_line(os.path.join(run_dir, 'dwarf.head.before'))
|
|
304
|
+
else:
|
|
305
|
+
line = None
|
|
306
|
+
line = (line or '').lower()
|
|
307
|
+
# Only a full hex id ever reaches git: nothing that could be read as an option or a ref.
|
|
308
|
+
return line if _SHA.fullmatch(line) else None
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _distinct_roots(roots):
|
|
312
|
+
"""Known roots without duplicates that are only different spellings of one directory."""
|
|
313
|
+
seen = {}
|
|
314
|
+
for root in sorted(roots):
|
|
315
|
+
seen.setdefault(_real(root), root)
|
|
316
|
+
return list(seen.values())
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _by_base_commit(sha, roots, has_commit):
|
|
320
|
+
matches = [root for root in _distinct_roots(roots) if has_commit(root, sha)]
|
|
321
|
+
return matches[0] if len(matches) == 1 else None
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
# ---- the batch ---------------------------------------------------------------------------------
|
|
325
|
+
|
|
326
|
+
def resolve(runs):
|
|
327
|
+
"""{run dir: Identity} for every ``(path, repo, kind)`` in ``runs``; see the module docstring."""
|
|
328
|
+
runs = list(runs)
|
|
329
|
+
result = {}
|
|
330
|
+
checkouts = {}
|
|
331
|
+
commit_checks = {}
|
|
332
|
+
|
|
333
|
+
def checkout(repo):
|
|
334
|
+
if repo not in checkouts:
|
|
335
|
+
checkouts[repo] = _checkout_identity(repo)
|
|
336
|
+
found = checkouts[repo][1]
|
|
337
|
+
return dict(found) if found is not None else None
|
|
338
|
+
|
|
339
|
+
def has_commit(root, sha):
|
|
340
|
+
key = (root, sha)
|
|
341
|
+
if key not in commit_checks:
|
|
342
|
+
done = _run_git(root, 'cat-file', '-e', sha + '^{commit}')
|
|
343
|
+
commit_checks[key] = done is not None and done.returncode == 0
|
|
344
|
+
return commit_checks[key]
|
|
345
|
+
|
|
346
|
+
known_roots = set()
|
|
347
|
+
|
|
348
|
+
def found_by(given, found):
|
|
349
|
+
result[given] = found
|
|
350
|
+
if found['source'] != 'base-commit' and _is_dir(found['root']):
|
|
351
|
+
known_roots.add(found['root'])
|
|
352
|
+
|
|
353
|
+
def live_step(path, repo):
|
|
354
|
+
found = checkout(repo)
|
|
355
|
+
if found is not None:
|
|
356
|
+
with _LOCK:
|
|
357
|
+
_RESOLVED[(path, repo)] = dict(found)
|
|
358
|
+
return found
|
|
359
|
+
|
|
360
|
+
pending = []
|
|
361
|
+
# Runs with a step 4 answer from an earlier call, held back until the known roots are final.
|
|
362
|
+
waiting = []
|
|
363
|
+
# Steps 1 and 2 for the whole batch first: step 3 needs every root they found.
|
|
364
|
+
for given, repo, kind in runs:
|
|
365
|
+
path = os.fspath(given)
|
|
366
|
+
repo = repo if isinstance(repo, str) and repo.strip() else None
|
|
367
|
+
if repo is None:
|
|
368
|
+
result[given] = _identity(None)
|
|
369
|
+
continue
|
|
370
|
+
found = _from_identity_file(path)
|
|
371
|
+
if found is None:
|
|
372
|
+
with _LOCK:
|
|
373
|
+
found = _RESOLVED.get((path, repo))
|
|
374
|
+
cached = _FALLTHROUGH.get((path, repo))
|
|
375
|
+
if found is not None:
|
|
376
|
+
found = dict(found)
|
|
377
|
+
elif cached is not None:
|
|
378
|
+
waiting.append((given, path, repo, kind, _is_dir(repo), cached))
|
|
379
|
+
continue
|
|
380
|
+
elif _is_dir(repo):
|
|
381
|
+
found = live_step(path, repo)
|
|
382
|
+
if found is None:
|
|
383
|
+
pending.append((given, path, repo, kind))
|
|
384
|
+
continue
|
|
385
|
+
found_by(given, found)
|
|
386
|
+
|
|
387
|
+
# A step 4 answer holds while the repo path has neither appeared nor vanished and the known
|
|
388
|
+
# roots are the ones it was checked against. A stale one goes through step 2 again, which can
|
|
389
|
+
# add a root and so make another one stale: repeat until the known roots stop changing.
|
|
390
|
+
while True:
|
|
391
|
+
roots_key = frozenset(known_roots)
|
|
392
|
+
still = []
|
|
393
|
+
for item in waiting:
|
|
394
|
+
given, path, repo, kind, live, cached = item
|
|
395
|
+
if cached[0] == roots_key and cached[1] == live:
|
|
396
|
+
still.append(item)
|
|
397
|
+
continue
|
|
398
|
+
found = live_step(path, repo) if live else None
|
|
399
|
+
if found is None:
|
|
400
|
+
pending.append((given, path, repo, kind))
|
|
401
|
+
else:
|
|
402
|
+
found_by(given, found)
|
|
403
|
+
waiting = still
|
|
404
|
+
if frozenset(known_roots) == roots_key:
|
|
405
|
+
break
|
|
406
|
+
for given, _path, _repo, _kind, _live, cached in waiting:
|
|
407
|
+
result[given] = dict(cached[2])
|
|
408
|
+
|
|
409
|
+
roots_key = frozenset(known_roots)
|
|
410
|
+
for given, path, repo, kind in pending:
|
|
411
|
+
key = (path, repo)
|
|
412
|
+
live = _is_dir(repo)
|
|
413
|
+
found = None
|
|
414
|
+
if not live:
|
|
415
|
+
sha = _base_commit(path, kind)
|
|
416
|
+
root = _by_base_commit(sha, known_roots, has_commit) if sha else None
|
|
417
|
+
if root is not None:
|
|
418
|
+
found = _identity(root, repo, None, 'base-commit')
|
|
419
|
+
with _LOCK:
|
|
420
|
+
_RESOLVED[key] = dict(found)
|
|
421
|
+
if found is None:
|
|
422
|
+
found = _identity(repo)
|
|
423
|
+
# A live repo whose git call timed out is retried next time rather than remembered.
|
|
424
|
+
if not (live and not checkouts.get(repo, (True, None))[0]):
|
|
425
|
+
with _LOCK:
|
|
426
|
+
_FALLTHROUGH[key] = (roots_key, live, dict(found))
|
|
427
|
+
result[given] = found
|
|
428
|
+
return result
|