@giamme/forge 0.17.0 → 0.18.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 +24 -0
- package/SKILL.md +16 -3
- package/VERSION +1 -1
- package/docs/artifacts.md +8 -0
- package/docs/commands.md +70 -6
- package/docs/dataset.md +5 -0
- package/docs/decomposed-runs.md +8 -0
- package/docs/forge-ui.md +23 -2
- package/docs/memory.md +2 -0
- package/docs/safety.md +8 -0
- package/forge +24 -1
- package/package.json +1 -1
- package/references/dataset.md +19 -0
- package/references/decompose.md +134 -1
- package/references/solo.md +2 -1
- package/references/ui.md +5 -2
- package/scripts/forge-artifact.sh +14 -0
- package/scripts/forge-brief.py +132 -0
- package/scripts/forge-compare.py +11 -1
- package/scripts/forge-config.py +176 -9
- package/scripts/forge-contract.py +46 -3
- package/scripts/forge-control.py +86 -13
- package/scripts/forge-dispatch.sh +14 -10
- package/scripts/forge-du.py +167 -0
- package/scripts/forge-lib-adopt.sh +1 -0
- package/scripts/forge-lib-plans.sh +5 -2
- package/scripts/forge-lib-review.sh +29 -1
- package/scripts/forge-metrics.sh +7 -3
- package/scripts/forge-parallel-options.sh +4 -0
- package/scripts/forge-parallel.sh +503 -9
- package/scripts/forge-prompt.py +120 -0
- package/scripts/forge-retro.py +115 -0
- package/scripts/forge-runs-compact.py +443 -0
- package/scripts/forge-runs-rm.py +2 -0
- package/scripts/forge-runs.py +18 -3
- package/scripts/forge-schedule.py +279 -4
- package/scripts/forge-shadow.py +7 -1
- package/scripts/forge-solo.sh +2 -0
- package/scripts/forge-summarize.py +698 -0
- package/scripts/forge-ui-options.sh +10 -0
- package/scripts/forge_brief/__init__.py +587 -0
- package/scripts/forge_brief/answers.py +459 -0
- package/scripts/forge_dataset/__init__.py +10 -0
- package/scripts/forge_dataset/export.py +18 -4
- package/scripts/forge_dataset/facts.py +6 -4
- package/scripts/forge_dataset/harvest.py +40 -6
- package/scripts/forge_dataset/history.py +5 -3
- package/scripts/forge_decide/__init__.py +11 -1
- package/scripts/forge_locations.py +366 -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 +477 -0
- package/scripts/forge_storage.py +515 -0
- package/ui/README.md +68 -8
- package/ui/docs/api.md +205 -17
- package/ui/forge_ui/control.py +92 -11
- package/ui/forge_ui/export.py +24 -5
- package/ui/forge_ui/links.py +337 -0
- package/ui/forge_ui/models.py +57 -4
- package/ui/forge_ui/projects.py +4 -1
- package/ui/forge_ui/reader.py +661 -30
- package/ui/forge_ui/static/app.js +86 -4
- package/ui/forge_ui/static/briefview.js +302 -0
- package/ui/forge_ui/static/checksview.js +6 -2
- package/ui/forge_ui/static/controls.js +5 -0
- package/ui/forge_ui/static/index.html +3 -0
- package/ui/forge_ui/static/panel.js +268 -2
- package/ui/forge_ui/static/runmodel.js +13 -1
- package/ui/forge_ui/static/storageview.js +271 -0
- package/ui/forge_ui/static/style.css +99 -3
- package/ui/forge_ui/static/worktreesview.js +3 -3
- package/ui/forge_ui/storage.py +136 -0
- package/ui/forge_ui/transcripts.py +35 -10
- package/ui/forge_ui/worktrees.py +154 -13
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""forge runs compact [RUN_DIR ... | --repo DIR | --all] [--older-than DAYS] [--logs] [--dry-run] [--json]
|
|
3
|
+
|
|
4
|
+
Takes back the space a run dir holds for nothing, and keeps every run on disk and viewable (#139).
|
|
5
|
+
Per run, with the run's own lock held from the first step to the last (`schedule.lock` of a plan,
|
|
6
|
+
`pipeline.lock` of a solo run, as `forge runs rm` takes it), so a run started meanwhile fails to
|
|
7
|
+
start instead of racing the compaction:
|
|
8
|
+
|
|
9
|
+
check the same identity and safety rules as `forge runs rm`; an active run is skipped
|
|
10
|
+
preserve a strict dataset import of the run, as `forge runs rm` starts with: if any event
|
|
11
|
+
cannot be stored, nothing in that run is touched
|
|
12
|
+
snapshots remove every review snapshot (forge_storage.py has the rule); nothing reads one once
|
|
13
|
+
its review has ended, and the importer and the archive never did
|
|
14
|
+
logs --logs: gzip each dwarf's and reviewer's log copy in its execution record
|
|
15
|
+
(attempts/<role>-<id>/<role>.log, 64 KB or more) into <log>.gz, same mode and times;
|
|
16
|
+
forge-ui reads either. The logs in the task dirs, which running agents write and retries
|
|
17
|
+
read, are never touched.
|
|
18
|
+
record the dataset event run_compacted (fail-open)
|
|
19
|
+
|
|
20
|
+
Never touched: an active run, a worktree, the logs in task dirs, and anything forge does not create.
|
|
21
|
+
A dependency install or a `.git` found inside a run dir is reported with its size (`strays`), not
|
|
22
|
+
removed. Without RUN_DIR, `--repo DIR` takes every registered run of that repository and `--all` every
|
|
23
|
+
registered run; there an active run, or one changed less than an hour ago, is skipped, not an error.
|
|
24
|
+
|
|
25
|
+
`--auto` is what forge itself starts in the background when a run starts (storage.compact auto, the
|
|
26
|
+
default): `--logs` over the repository's runs, never the run named by `--exclude`, silent, and
|
|
27
|
+
snapshots are kept when FORGE_KEEP_SNAPSHOTS=1. It also refreshes the repository's footprint, which
|
|
28
|
+
`--start-check` compares with storage.warn-gb (20 GB by default) and warns about at run start.
|
|
29
|
+
|
|
30
|
+
--json prints one object on stdout, on failure too:
|
|
31
|
+
{ok, dry_run, bytes_freed, runs: [{run_dir, run_id, repo, status, steps: [{step, ok, detail}],
|
|
32
|
+
size_bytes, bytes_freed, snapshots: {count, bytes, removed}, logs: {count, bytes, compressed},
|
|
33
|
+
strays: [{path, bytes, kind}]}]}
|
|
34
|
+
status: compacted, nothing (nothing to take back), would-compact (dry run), active, recent, refused, failed.
|
|
35
|
+
Exit 0 ok, 2 refused input, 3 the one run named is active, 4 something failed.
|
|
36
|
+
"""
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
import argparse
|
|
40
|
+
import hashlib
|
|
41
|
+
import importlib.util
|
|
42
|
+
import json
|
|
43
|
+
import os
|
|
44
|
+
from pathlib import Path
|
|
45
|
+
import subprocess
|
|
46
|
+
import sys
|
|
47
|
+
import time
|
|
48
|
+
|
|
49
|
+
SKILL = Path(__file__).resolve().parent.parent
|
|
50
|
+
sys.path.insert(0, str(SKILL / 'scripts'))
|
|
51
|
+
|
|
52
|
+
import forge_storage # noqa: E402
|
|
53
|
+
|
|
54
|
+
OK, REFUSED, BUSY, FAILED = 0, 2, 3, 4
|
|
55
|
+
RECENT_S = 3600
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _rm():
|
|
59
|
+
"""forge-runs-rm.py, for its identity, lock and safety rules: one set for both commands."""
|
|
60
|
+
module = sys.modules.get('forge_runs_rm')
|
|
61
|
+
if module is None:
|
|
62
|
+
spec = importlib.util.spec_from_file_location('forge_runs_rm', Path(__file__).resolve().with_name('forge-runs-rm.py'))
|
|
63
|
+
module = importlib.util.module_from_spec(spec)
|
|
64
|
+
sys.modules['forge_runs_rm'] = module
|
|
65
|
+
spec.loader.exec_module(module)
|
|
66
|
+
return module
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class UsageError(Exception):
|
|
70
|
+
pass
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class Parser(argparse.ArgumentParser):
|
|
74
|
+
def error(self, message):
|
|
75
|
+
raise UsageError(message)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def registered(repo: Path | None) -> list[str]:
|
|
79
|
+
"""The run dirs the registry lists, for one repository or (None) every one; existing dirs only, no repeats."""
|
|
80
|
+
return [path for path, _ in forge_storage.run_dirs(repo)]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def repo_of(start: Path) -> Path:
|
|
84
|
+
try:
|
|
85
|
+
out = subprocess.run(['git', '-C', str(start), 'rev-parse', '--show-toplevel'], capture_output=True, text=True,
|
|
86
|
+
stdin=subprocess.DEVNULL, timeout=10)
|
|
87
|
+
if out.returncode == 0 and out.stdout.strip():
|
|
88
|
+
return Path(out.stdout.strip()).resolve()
|
|
89
|
+
except (OSError, subprocess.SubprocessError):
|
|
90
|
+
pass
|
|
91
|
+
return start.resolve()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def last_change(path: str) -> float:
|
|
95
|
+
"""The newest mtime among the run dir's top-level entries and its task dirs (lock files aside)."""
|
|
96
|
+
newest = 0.0
|
|
97
|
+
for directory in (path, os.path.join(path, 'tasks')):
|
|
98
|
+
try:
|
|
99
|
+
with os.scandir(directory) as listing:
|
|
100
|
+
for entry in listing:
|
|
101
|
+
if entry.name.endswith('.lock'):
|
|
102
|
+
continue # opened by every command that checks it: the lock, not its file, says a run is live
|
|
103
|
+
try:
|
|
104
|
+
newest = max(newest, entry.stat(follow_symlinks=False).st_mtime)
|
|
105
|
+
except OSError:
|
|
106
|
+
continue
|
|
107
|
+
except OSError:
|
|
108
|
+
continue
|
|
109
|
+
return newest
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class Outcome:
|
|
113
|
+
def __init__(self, run_dir, quiet):
|
|
114
|
+
self.data = dict(run_dir=run_dir, run_id=None, repo=None, status=None, steps=[], size_bytes=None, bytes_freed=0,
|
|
115
|
+
snapshots=dict(count=0, bytes=0, removed=0), logs=dict(count=0, bytes=0, compressed=0), strays=[])
|
|
116
|
+
self.quiet = quiet
|
|
117
|
+
self.ok = True
|
|
118
|
+
|
|
119
|
+
def step(self, name, ok, detail):
|
|
120
|
+
self.data['steps'].append(dict(step=name, ok=bool(ok), detail=detail))
|
|
121
|
+
if not ok:
|
|
122
|
+
self.ok = False
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def event(run, name, **values):
|
|
126
|
+
stamp = json.dumps([run.uid, name, run.path, time.time_ns()])
|
|
127
|
+
return dict(rid='event:%s:%s' % (name, hashlib.sha256(stamp.encode()).hexdigest()[:24]), kind='event',
|
|
128
|
+
ts=time.time(), run=run.uid, run_id=run.run_id, mode=run.mode, task=None,
|
|
129
|
+
parent=os.environ.get('FORGE_DATASET_PARENT') or None,
|
|
130
|
+
inv=os.environ.get('FORGE_DATASET_INVOCATION') or None,
|
|
131
|
+
data=dict(values, name=name, blobs={}))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def compact_one(run_dir, args, batch) -> tuple[Outcome, int]:
|
|
135
|
+
"""One run dir. Returns its outcome and the exit code it would give on its own."""
|
|
136
|
+
rm = _rm()
|
|
137
|
+
out = Outcome(run_dir, args.json)
|
|
138
|
+
try:
|
|
139
|
+
target = rm.locate(run_dir)
|
|
140
|
+
if target.info is None:
|
|
141
|
+
raise rm.Refused('no such directory')
|
|
142
|
+
run = rm.identify(target)
|
|
143
|
+
except rm.Refused as error:
|
|
144
|
+
out.data['status'] = 'refused'
|
|
145
|
+
out.step('check', False, str(error))
|
|
146
|
+
return out, REFUSED
|
|
147
|
+
out.data.update(run_dir=run.path, run_id=run.run_id, repo=run.repo)
|
|
148
|
+
if batch and time.time() - last_change(run.path) < RECENT_S:
|
|
149
|
+
out.data['status'] = 'recent'
|
|
150
|
+
out.step('check', True, 'skipped: changed less than an hour ago')
|
|
151
|
+
return out, OK
|
|
152
|
+
if args.older_than is not None and time.time() - last_change(run.path) < args.older_than * 86400:
|
|
153
|
+
out.data['status'] = 'recent'
|
|
154
|
+
out.step('check', True, 'skipped: changed less than %g day(s) ago' % args.older_than)
|
|
155
|
+
return out, OK
|
|
156
|
+
fd = None
|
|
157
|
+
try:
|
|
158
|
+
if not args.dry_run:
|
|
159
|
+
try:
|
|
160
|
+
fd = rm.take_lock(run)
|
|
161
|
+
except rm.Busy as error:
|
|
162
|
+
out.data['status'] = 'active'
|
|
163
|
+
out.step('lock', not batch, 'skipped: ' + str(error))
|
|
164
|
+
return out, BUSY
|
|
165
|
+
rm.pause_for_test()
|
|
166
|
+
pid = rm.scheduler_pid(run)
|
|
167
|
+
if pid:
|
|
168
|
+
out.data['status'] = 'active'
|
|
169
|
+
out.step('lock', not batch, 'skipped: scheduler.live names a live process (pid %d)' % pid)
|
|
170
|
+
return out, BUSY
|
|
171
|
+
found = forge_storage.scan(run.path)
|
|
172
|
+
keep_snapshots = args.auto and os.environ.get('FORGE_KEEP_SNAPSHOTS', '0') == '1'
|
|
173
|
+
snaps = [] if keep_snapshots else found['snapshots']['items']
|
|
174
|
+
logs = found['logs']['compressible'] if args.logs else []
|
|
175
|
+
out.data.update(size_bytes=found['total'], strays=found['strays'])
|
|
176
|
+
out.data['snapshots'].update(count=len(snaps), bytes=sum(s['bytes'] for s in snaps))
|
|
177
|
+
out.data['logs'].update(count=len(logs), bytes=sum(entry['bytes'] for entry in logs))
|
|
178
|
+
out.step('check', True, '%s dir, run id %s, %s: %d snapshot(s) (%s)%s%s' % (
|
|
179
|
+
run.kind, run.run_id, forge_storage.size_text(found['total']), len(snaps),
|
|
180
|
+
forge_storage.size_text(out.data['snapshots']['bytes']),
|
|
181
|
+
', %d log(s) to gzip (%s)' % (len(logs), forge_storage.size_text(out.data['logs']['bytes'])) if args.logs else '',
|
|
182
|
+
'; FORGE_KEEP_SNAPSHOTS=1 keeps the snapshots' if keep_snapshots else ''))
|
|
183
|
+
for stray in found['strays']:
|
|
184
|
+
out.step('stray', True, 'not forge\'s, left in place: %s (%s)' % (stray['path'], forge_storage.size_text(stray['bytes'])))
|
|
185
|
+
if not snaps and not logs and not found['parts']:
|
|
186
|
+
out.data['status'] = 'nothing'
|
|
187
|
+
return out, OK
|
|
188
|
+
if args.dry_run:
|
|
189
|
+
out.data['status'] = 'would-compact'
|
|
190
|
+
out.step('preserve', True, 'would import the run into the dataset, strictly' if rm.enabled() else
|
|
191
|
+
'skipped: FORGE_DATASET=off')
|
|
192
|
+
if snaps:
|
|
193
|
+
out.step('snapshots', True, 'would remove %d snapshot(s), %s' % (len(snaps), forge_storage.size_text(out.data['snapshots']['bytes'])))
|
|
194
|
+
if logs:
|
|
195
|
+
out.step('logs', True, 'would gzip %d log(s), %s now, about %s after' % (
|
|
196
|
+
len(logs), forge_storage.size_text(out.data['logs']['bytes']),
|
|
197
|
+
forge_storage.size_text(out.data['logs']['bytes'] * forge_storage.GZIP_RATIO)))
|
|
198
|
+
out.data['bytes_freed'] = out.data['snapshots']['bytes'] + int(out.data['logs']['bytes'] * (1 - forge_storage.GZIP_RATIO))
|
|
199
|
+
return out, OK
|
|
200
|
+
try:
|
|
201
|
+
run.uid = rm.harvest.run_uid(Path(run.path), create=False)
|
|
202
|
+
except Exception: # noqa: BLE001 -- an identity we cannot read only costs the event its run column
|
|
203
|
+
run.uid = None
|
|
204
|
+
if rm.enabled():
|
|
205
|
+
try:
|
|
206
|
+
result = rm.importer.import_run(run.path, strict=True)
|
|
207
|
+
except (rm.DatasetError, OSError) as error:
|
|
208
|
+
out.data['status'] = 'failed'
|
|
209
|
+
out.step('preserve', False, 'the dataset could not take the run, nothing was changed: %s' % error)
|
|
210
|
+
return out, FAILED
|
|
211
|
+
out.step('preserve', True, 'imported %d event(s), %d new' % (result['events'], result['new']))
|
|
212
|
+
else:
|
|
213
|
+
out.step('preserve', True, 'skipped: FORGE_DATASET=off (snapshots and log encodings hold nothing the dataset keeps)')
|
|
214
|
+
rm.check_unchanged(run, 'during the compaction')
|
|
215
|
+
freed, problems = 0, []
|
|
216
|
+
for snap in snaps:
|
|
217
|
+
why = forge_storage.remove_snapshot(snap['path'], run.path)
|
|
218
|
+
if why:
|
|
219
|
+
problems.append('%s: %s' % (snap['path'], why))
|
|
220
|
+
else:
|
|
221
|
+
freed += snap['bytes']
|
|
222
|
+
out.data['snapshots']['removed'] += 1
|
|
223
|
+
if snaps:
|
|
224
|
+
out.step('snapshots', not problems, 'removed %d of %d snapshot(s), %s%s' % (
|
|
225
|
+
out.data['snapshots']['removed'], len(snaps), forge_storage.size_text(freed),
|
|
226
|
+
'; ' + '; '.join(problems[:3]) if problems else ''))
|
|
227
|
+
log_problems, log_freed = [], 0
|
|
228
|
+
for entry in logs:
|
|
229
|
+
gained, why = forge_storage.compress_log(entry['path'])
|
|
230
|
+
if why:
|
|
231
|
+
log_problems.append('%s: %s' % (entry['path'], why))
|
|
232
|
+
else:
|
|
233
|
+
log_freed += gained
|
|
234
|
+
out.data['logs']['compressed'] += 1
|
|
235
|
+
for part in found['parts']:
|
|
236
|
+
# a gzip an interrupted compaction left beside an execution record's log: ours by name and place
|
|
237
|
+
if forge_storage.ATTEMPT_DIR.fullmatch(os.path.basename(os.path.dirname(part))):
|
|
238
|
+
try:
|
|
239
|
+
os.unlink(part)
|
|
240
|
+
except OSError:
|
|
241
|
+
pass
|
|
242
|
+
if logs:
|
|
243
|
+
out.step('logs', not log_problems, 'gzipped %d of %d log(s), %s taken back%s' % (
|
|
244
|
+
out.data['logs']['compressed'], len(logs), forge_storage.size_text(log_freed),
|
|
245
|
+
'; ' + '; '.join(log_problems[:3]) if log_problems else ''))
|
|
246
|
+
out.data['bytes_freed'] = freed + log_freed
|
|
247
|
+
if rm.enabled():
|
|
248
|
+
rm.record([event(run, 'run_compacted', path=run.path, bytes_freed=freed + log_freed,
|
|
249
|
+
snapshots_removed=out.data['snapshots']['removed'], snapshot_bytes=freed,
|
|
250
|
+
logs_compressed=out.data['logs']['compressed'], log_bytes_freed=log_freed,
|
|
251
|
+
auto=bool(args.auto))], repo=run.repo, where='event:run_compacted')
|
|
252
|
+
out.data['status'] = 'compacted' if out.ok else 'failed'
|
|
253
|
+
return out, OK if out.ok else FAILED
|
|
254
|
+
except (rm.Busy, rm.Failed) as error:
|
|
255
|
+
out.data['status'] = 'failed'
|
|
256
|
+
out.step('check', False, str(error))
|
|
257
|
+
return out, FAILED
|
|
258
|
+
finally:
|
|
259
|
+
if fd is not None:
|
|
260
|
+
os.close(fd)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def user_settings() -> dict:
|
|
264
|
+
try:
|
|
265
|
+
from forge_decide import load_user
|
|
266
|
+
data, error = load_user()
|
|
267
|
+
except Exception: # noqa: BLE001 -- a broken user file must not stop a run from starting
|
|
268
|
+
return forge_storage.settings(None)
|
|
269
|
+
features = data.get('features') if not error and isinstance(data, dict) else None
|
|
270
|
+
return forge_storage.settings(features if isinstance(features, dict) else None)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def start_check(args) -> int:
|
|
274
|
+
"""At run start: warn when the repository's last measured footprint passes storage.warn-gb, then start
|
|
275
|
+
the background compaction. Prints at most a few lines on stderr; never fails the run."""
|
|
276
|
+
try:
|
|
277
|
+
repo = str(Path(args.repo).resolve())
|
|
278
|
+
policy = user_settings()
|
|
279
|
+
home = _rm().data_home()
|
|
280
|
+
known = forge_storage.load_footprints(home).get(repo) or {}
|
|
281
|
+
size = known.get('bytes')
|
|
282
|
+
if policy['warn_gb'] is not None and isinstance(size, (int, float)) and size > policy['warn_gb'] * forge_storage.GB:
|
|
283
|
+
print('forge: this repository\'s forge files take %s (run dirs %s, worktrees %s), over storage.warn-gb %g.\n'
|
|
284
|
+
' See what: forge du --repo %s\n'
|
|
285
|
+
' Take back the review snapshots and gzip old logs: forge runs compact --repo %s --logs\n'
|
|
286
|
+
' (forge config set storage.warn-gb N|off changes this warning)'
|
|
287
|
+
% (forge_storage.size_text(size), forge_storage.size_text(known.get('runs')),
|
|
288
|
+
forge_storage.size_text(known.get('worktrees')), policy['warn_gb'], repo, repo), file=sys.stderr)
|
|
289
|
+
if policy['compact'] == 'auto' or policy['warn_gb'] is not None:
|
|
290
|
+
log = forge_storage.footprint_path(home).with_name('auto.log')
|
|
291
|
+
log.parent.mkdir(parents=True, exist_ok=True)
|
|
292
|
+
argv = [sys.executable, '-I', str(Path(__file__).resolve()), '--auto', '--repo', repo]
|
|
293
|
+
if args.exclude:
|
|
294
|
+
argv += ['--exclude', args.exclude]
|
|
295
|
+
with open(log, 'ab') as sink:
|
|
296
|
+
subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=sink, stderr=sink, start_new_session=True,
|
|
297
|
+
close_fds=True)
|
|
298
|
+
except Exception: # noqa: BLE001 -- a run never fails over its storage check
|
|
299
|
+
pass
|
|
300
|
+
return OK
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def parser():
|
|
304
|
+
p = Parser(prog='forge runs compact', description='Take back the space run dirs hold for nothing: review snapshots, '
|
|
305
|
+
'and with --logs the dwarf and reviewer log copies (gzipped). Every run stays on disk, viewable, and in the '
|
|
306
|
+
'dataset. See scripts/forge-runs-compact.py for the steps and the safety rules.')
|
|
307
|
+
p.add_argument('run_dirs', nargs='*', metavar='RUN_DIR', help='the plan dirs or solo run dirs to compact')
|
|
308
|
+
which = p.add_mutually_exclusive_group()
|
|
309
|
+
which.add_argument('--repo', metavar='DIR', help='every registered run of this repository')
|
|
310
|
+
which.add_argument('--all', action='store_true', help='every registered run of every repository')
|
|
311
|
+
p.add_argument('--older-than', type=float, metavar='DAYS', help='only runs unchanged for at least DAYS days')
|
|
312
|
+
p.add_argument('--logs', action='store_true', help='also gzip the dwarf and reviewer log copies of 64 KB or more')
|
|
313
|
+
p.add_argument('--dry-run', action='store_true', help='change nothing; report what would be taken back')
|
|
314
|
+
p.add_argument('--json', action='store_true', help='print one JSON object, on failure too')
|
|
315
|
+
p.add_argument('--auto', action='store_true', help=argparse.SUPPRESS)
|
|
316
|
+
p.add_argument('--exclude', metavar='RUN_DIR', help=argparse.SUPPRESS)
|
|
317
|
+
p.add_argument('--start-check', action='store_true', help=argparse.SUPPRESS)
|
|
318
|
+
return p
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def print_run(out, dry_run, index=None, count=None):
|
|
322
|
+
"""One run's result, printed as soon as it is done."""
|
|
323
|
+
data = out.data
|
|
324
|
+
head = '%s%s %s' % ('[%d/%d] ' % (index, count) if index else '', data['run_id'] or os.path.basename(data['run_dir'] or ''),
|
|
325
|
+
data['status'])
|
|
326
|
+
if data['bytes_freed']:
|
|
327
|
+
head += (', about %s to take back' if dry_run else ', %s taken back') % forge_storage.size_text(data['bytes_freed'])
|
|
328
|
+
print(head)
|
|
329
|
+
print(' %s' % data['run_dir'])
|
|
330
|
+
for step in data['steps']:
|
|
331
|
+
print(' %-4s %-9s %s' % ('ok' if step['ok'] else 'FAIL', step['step'], step['detail']),
|
|
332
|
+
file=sys.stdout if step['ok'] else sys.stderr)
|
|
333
|
+
sys.stdout.flush()
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def print_text(results, total, dry_run):
|
|
337
|
+
counted = sum(1 for out in results if out.data['status'] in ('compacted', 'would-compact'))
|
|
338
|
+
by = {}
|
|
339
|
+
for out in results:
|
|
340
|
+
by[out.data['status']] = by.get(out.data['status'], 0) + 1
|
|
341
|
+
rest = ', '.join('%d %s' % (by[k], label) for k, label in (('nothing', 'with nothing to take back'), ('active', 'active, skipped'),
|
|
342
|
+
('recent', 'changed recently, skipped'), ('refused', 'refused'), ('failed', 'FAILED')) if by.get(k))
|
|
343
|
+
if dry_run:
|
|
344
|
+
print('forge runs compact: dry run, nothing was changed; %d run(s) to compact, about %s to take back%s' % (
|
|
345
|
+
counted, forge_storage.size_text(total), '; ' + rest if rest else ''))
|
|
346
|
+
else:
|
|
347
|
+
print('forge runs compact: %d run(s) compacted, %s taken back%s' % (counted, forge_storage.size_text(total), '; ' + rest if rest else ''))
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def main(argv=None) -> int:
|
|
351
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
352
|
+
try:
|
|
353
|
+
args = parser().parse_args(argv)
|
|
354
|
+
if args.older_than is not None and args.older_than < 0:
|
|
355
|
+
raise UsageError('--older-than must be 0 or more')
|
|
356
|
+
if args.start_check:
|
|
357
|
+
if not args.repo:
|
|
358
|
+
raise UsageError('--start-check needs --repo')
|
|
359
|
+
return start_check(args)
|
|
360
|
+
if args.auto:
|
|
361
|
+
if not args.repo:
|
|
362
|
+
raise UsageError('--auto needs --repo')
|
|
363
|
+
args.logs, args.json = True, False
|
|
364
|
+
if args.run_dirs and (args.repo or args.all):
|
|
365
|
+
raise UsageError('name run dirs, or use --repo or --all, not both')
|
|
366
|
+
if not args.run_dirs and not args.repo and not args.all:
|
|
367
|
+
raise UsageError('name a run dir, or use --repo DIR (every run of a repository) or --all')
|
|
368
|
+
if args.repo and not os.path.isdir(args.repo):
|
|
369
|
+
raise UsageError('--repo: no such directory: %s' % args.repo)
|
|
370
|
+
except UsageError as error:
|
|
371
|
+
if '--json' in argv:
|
|
372
|
+
json.dump(dict(ok=False, dry_run='--dry-run' in argv, bytes_freed=0, runs=[], error='usage: %s' % error), sys.stdout, indent=2)
|
|
373
|
+
sys.stdout.write('\n')
|
|
374
|
+
else:
|
|
375
|
+
parser().print_usage(sys.stderr)
|
|
376
|
+
print('forge runs compact: %s' % error, file=sys.stderr)
|
|
377
|
+
return REFUSED
|
|
378
|
+
batch = not args.run_dirs
|
|
379
|
+
if batch:
|
|
380
|
+
import forge_locations
|
|
381
|
+
forge_locations.ensure_imported() # once: what the run registry and the disk already hold
|
|
382
|
+
repo = str(repo_of(Path(args.repo))) if args.repo else None
|
|
383
|
+
dirs = args.run_dirs if args.run_dirs else registered(Path(repo) if repo else None)
|
|
384
|
+
excluded = os.path.realpath(args.exclude) if args.exclude else None
|
|
385
|
+
results, codes = [], []
|
|
386
|
+
policy = user_settings() if args.auto else None
|
|
387
|
+
if policy is not None and policy['compact'] != 'auto':
|
|
388
|
+
dirs = [] # storage.compact off: only the footprint is measured
|
|
389
|
+
dirs = [path for path in dirs if not (excluded and os.path.realpath(path) == excluded)]
|
|
390
|
+
live = not args.json and not args.auto # in a terminal, each run is reported as it ends: a batch takes minutes
|
|
391
|
+
if live and len(dirs) > 1:
|
|
392
|
+
print('forge runs compact: %d run(s) to look at%s; each one is reported when it is done' % (
|
|
393
|
+
len(dirs), ' (dry run: nothing is changed)' if args.dry_run else ''))
|
|
394
|
+
sys.stdout.flush()
|
|
395
|
+
for index, path in enumerate(dirs, 1):
|
|
396
|
+
if live and len(dirs) > 1 and sys.stderr.isatty():
|
|
397
|
+
sys.stderr.write('\r\033[K[%d/%d] %s…' % (index, len(dirs), os.path.basename(path)))
|
|
398
|
+
sys.stderr.flush()
|
|
399
|
+
try:
|
|
400
|
+
out, code = compact_one(path, args, batch)
|
|
401
|
+
except KeyboardInterrupt:
|
|
402
|
+
out, code = Outcome(path, args.json), 130
|
|
403
|
+
out.data['status'] = 'failed'
|
|
404
|
+
out.step('interrupted', False, 'interrupted; see the steps above for what was done')
|
|
405
|
+
results.append(out)
|
|
406
|
+
codes.append(code)
|
|
407
|
+
break
|
|
408
|
+
except Exception as error: # noqa: BLE001 -- --json must still print one object
|
|
409
|
+
out, code = Outcome(path, args.json), FAILED
|
|
410
|
+
out.data['status'] = 'failed'
|
|
411
|
+
out.step('internal', False, '%s: %s' % (type(error).__name__, error))
|
|
412
|
+
results.append(out)
|
|
413
|
+
codes.append(code)
|
|
414
|
+
if live:
|
|
415
|
+
if len(dirs) > 1 and sys.stderr.isatty():
|
|
416
|
+
sys.stderr.write('\r\033[K')
|
|
417
|
+
print_run(out, args.dry_run, index if len(dirs) > 1 else None, len(dirs))
|
|
418
|
+
if args.auto and repo and (policy['warn_gb'] is not None or policy['compact'] == 'auto'):
|
|
419
|
+
measured = forge_storage.footprints_of(forge_storage.report(Path(repo), budget_s=600))
|
|
420
|
+
forge_storage.save_footprints(_rm().data_home(), {repo: measured.get(repo) or dict(bytes=0, runs=0, worktrees=0, count=0)})
|
|
421
|
+
total = sum(out.data['bytes_freed'] for out in results)
|
|
422
|
+
if batch:
|
|
423
|
+
codes = [c for c in codes if c != BUSY]
|
|
424
|
+
code = max(codes) if codes else OK
|
|
425
|
+
if args.auto:
|
|
426
|
+
stamp = time.strftime('%Y-%m-%d %H:%M:%S')
|
|
427
|
+
for out in results:
|
|
428
|
+
if out.data['status'] in ('compacted', 'failed'):
|
|
429
|
+
print('%s %s %s %s' % (stamp, out.data['status'], out.data['run_dir'], forge_storage.size_text(out.data['bytes_freed'])))
|
|
430
|
+
return OK
|
|
431
|
+
if args.json:
|
|
432
|
+
json.dump(dict(ok=code == OK, dry_run=args.dry_run, bytes_freed=total, runs=[out.data for out in results]), sys.stdout, indent=2)
|
|
433
|
+
sys.stdout.write('\n')
|
|
434
|
+
else:
|
|
435
|
+
if not results:
|
|
436
|
+
print('forge runs compact: no registered runs%s' % (' for ' + repo if repo else ''))
|
|
437
|
+
else:
|
|
438
|
+
print_text(results, total, args.dry_run)
|
|
439
|
+
return code
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
if __name__ == '__main__':
|
|
443
|
+
sys.exit(main())
|
package/scripts/forge-runs-rm.py
CHANGED
|
@@ -62,6 +62,7 @@ from pathlib import Path
|
|
|
62
62
|
SKILL = Path(__file__).resolve().parent.parent
|
|
63
63
|
sys.path.insert(0, str(SKILL / 'scripts'))
|
|
64
64
|
|
|
65
|
+
import forge_locations # noqa: E402
|
|
65
66
|
import forge_registry # noqa: E402
|
|
66
67
|
import forge_worktrees # noqa: E402
|
|
67
68
|
from forge_dataset import DatasetError, data_home, dataset_dir, enabled, harvest, importer, record, record_strict # noqa: E402
|
|
@@ -599,6 +600,7 @@ def remove_worktrees(run):
|
|
|
599
600
|
if kind == 'task' and entry['branch']:
|
|
600
601
|
removed['task'] = entry['branch'].split('/', 2)[-1]
|
|
601
602
|
record([removed], repo=run.repo, where='event:worktree_removed')
|
|
603
|
+
forge_locations.gone('worktree', entry['path'], by='forge runs rm')
|
|
602
604
|
else:
|
|
603
605
|
entry['note'] = (err or 'git worktree remove exit %d' % code).splitlines()[0]
|
|
604
606
|
problems.append('%s: %s' % (entry['path'], entry['note']))
|
package/scripts/forge-runs.py
CHANGED
|
@@ -9,8 +9,10 @@ or open with `forge ui open`. The repo is the Git top level of the current direc
|
|
|
9
9
|
forge-ui and never writes anything.
|
|
10
10
|
|
|
11
11
|
`forge runs rm <run-dir> [--dry-run] [--yes] [--no-archive] [--worktrees] [--branches] [--json]`
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
deletes a run, after its traces are in the dataset and an archive exists (scripts/forge-runs-rm.py).
|
|
13
|
+
`forge runs compact [RUN_DIR ... | --repo DIR | --all] [--logs] [--older-than DAYS] [--dry-run] [--json]`
|
|
14
|
+
keeps every run and takes back what it holds for nothing: leftover review snapshots and, with
|
|
15
|
+
--logs, gzipped log copies (scripts/forge-runs-compact.py). Both change things; listing never does.
|
|
14
16
|
|
|
15
17
|
`forge runs rerun <run-dir> --dwarf SPEC` and `forge runs compare <run-dir-A> <run-dir-B>` (scripts/forge-compare.py)
|
|
16
18
|
run a plan again under another implementer, from the same starting commit and never merging, and set two runs
|
|
@@ -104,6 +106,16 @@ def remove(argv) -> int:
|
|
|
104
106
|
return module.main(argv)
|
|
105
107
|
|
|
106
108
|
|
|
109
|
+
def compact(argv) -> int:
|
|
110
|
+
"""`forge runs compact`: loaded on demand, like rm."""
|
|
111
|
+
import importlib.util
|
|
112
|
+
spec = importlib.util.spec_from_file_location('forge_runs_compact', Path(__file__).resolve().with_name('forge-runs-compact.py'))
|
|
113
|
+
module = importlib.util.module_from_spec(spec)
|
|
114
|
+
sys.modules['forge_runs_compact'] = module
|
|
115
|
+
spec.loader.exec_module(module)
|
|
116
|
+
return module.main(argv)
|
|
117
|
+
|
|
118
|
+
|
|
107
119
|
def compare_runs(argv) -> int:
|
|
108
120
|
"""`forge runs rerun` and `forge runs compare`: loaded on demand, like rm."""
|
|
109
121
|
import importlib.util
|
|
@@ -118,10 +130,13 @@ def main(argv=None) -> int:
|
|
|
118
130
|
argv = sys.argv[1:] if argv is None else list(argv)
|
|
119
131
|
if argv[:1] == ['rm']:
|
|
120
132
|
return remove(argv[1:])
|
|
133
|
+
if argv[:1] == ['compact']:
|
|
134
|
+
return compact(argv[1:])
|
|
121
135
|
if argv[:1] in (['rerun'], ['compare']):
|
|
122
136
|
return compare_runs(argv)
|
|
123
137
|
parser = argparse.ArgumentParser(prog='forge runs', description="This repo's recent forge runs, newest first. Listing is read-only.",
|
|
124
|
-
epilog='Delete a run, keeping its traces: forge runs rm <run-dir> (forge runs rm --help).
|
|
138
|
+
epilog='Delete a run, keeping its traces: forge runs rm <run-dir> (forge runs rm --help). Take back the space runs '
|
|
139
|
+
'hold for nothing, keeping every run: forge runs compact --help. Rerun a plan with another '
|
|
125
140
|
'implementer and compare: forge runs rerun --help, forge runs compare --help')
|
|
126
141
|
which = parser.add_mutually_exclusive_group()
|
|
127
142
|
which.add_argument('--repo', type=Path, metavar='DIR', help='the repo whose runs to list (default: the Git top level of the current directory)')
|