@giamme/forge 0.15.0 → 0.17.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 +48 -0
- package/VERSION +1 -1
- package/docs/artifacts.md +1 -1
- package/docs/commands.md +14 -3
- package/docs/dataset.md +8 -0
- package/docs/forge-ui.md +14 -0
- package/docs/memory.md +22 -0
- package/docs/reviews.md +22 -1
- package/forge +11 -0
- package/package.json +1 -1
- package/references/dataset.md +129 -7
- package/references/decision-models.md +15 -2
- package/references/decompose.md +95 -13
- package/references/harnesses.md +4 -1
- package/references/planning.md +3 -2
- package/references/solo.md +5 -1
- package/references/ui.md +10 -1
- package/scripts/forge-artifact.sh +53 -0
- package/scripts/forge-contract.py +107 -9
- package/scripts/forge-control.py +0 -2
- package/scripts/forge-dispatch.sh +28 -12
- package/scripts/forge-fail-first.py +3 -1
- package/scripts/forge-guard.py +247 -8
- package/scripts/forge-issues.py +16 -3
- package/scripts/forge-ledger.py +3 -1
- package/scripts/forge-lib-adopt.sh +266 -0
- package/scripts/forge-lib-attribute.sh +10 -2
- package/scripts/forge-lib-plans.sh +16 -4
- package/scripts/forge-lib-review.sh +8 -2
- package/scripts/forge-lib-task.sh +19 -5
- package/scripts/forge-memory.sh +41 -4
- package/scripts/forge-metrics.sh +29 -0
- package/scripts/forge-parallel.sh +99 -14
- package/scripts/forge-plan-check.py +25 -2
- package/scripts/forge-planner.py +20 -6
- package/scripts/forge-route.py +16 -2
- package/scripts/forge-runs-rm.py +23 -7
- package/scripts/forge-runtime.py +25 -2
- package/scripts/forge-schedule.py +5 -2
- package/scripts/forge-shadow.py +30 -9
- package/scripts/forge-solo.sh +6 -0
- package/scripts/forge-sweep.py +25 -10
- package/scripts/forge_dataset/cli.py +99 -0
- package/scripts/forge_dataset/export.py +1 -0
- package/scripts/forge_dataset/facts.py +278 -0
- package/scripts/forge_dataset/harvest.py +27 -3
- package/scripts/forge_dataset/history.py +126 -0
- package/scripts/forge_dataset/outcomes.py +206 -58
- package/scripts/forge_dataset/pairs.py +174 -0
- package/scripts/forge_dataset/risk.py +108 -0
- package/scripts/forge_dataset/tiers.py +427 -0
- package/scripts/forge_dataset/worktrees.py +95 -0
- package/scripts/forge_decide/cli.py +23 -2
- package/scripts/forge_decide/labels.py +30 -6
- package/scripts/forge_decide/replay.py +10 -4
- package/scripts/forge_memory_list.py +153 -0
- package/scripts/forge_worktrees.py +88 -0
- package/ui/README.md +31 -0
- package/ui/docs/api.md +92 -6
- package/ui/forge_ui/__init__.py +14 -1
- package/ui/forge_ui/__main__.py +1 -1
- package/ui/forge_ui/control.py +77 -0
- package/ui/forge_ui/export.py +9 -2
- package/ui/forge_ui/findings.py +11 -2
- package/ui/forge_ui/projects.py +571 -0
- package/ui/forge_ui/reader.py +96 -9
- package/ui/forge_ui/server.py +8 -0
- package/ui/forge_ui/static/app.js +105 -22
- package/ui/forge_ui/static/cloudui.js +6 -2
- package/ui/forge_ui/static/convo.js +1 -1
- package/ui/forge_ui/static/diffview.js +9 -5
- package/ui/forge_ui/static/files.js +1 -1
- package/ui/forge_ui/static/index.html +5 -1
- package/ui/forge_ui/static/panel.js +69 -2
- package/ui/forge_ui/static/projectsview.js +372 -0
- package/ui/forge_ui/static/settings.js +136 -4
- package/ui/forge_ui/static/style.css +94 -3
- package/ui/forge_ui/static/uikit.js +94 -1
- package/ui/forge_ui/static/worktreesview.js +250 -0
- package/ui/forge_ui/worktrees.py +570 -0
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
"""The Worktrees screen (#125): every worktree forge created, in any repository it knows, with its state and
|
|
2
|
+
the command that removes it safely.
|
|
3
|
+
|
|
4
|
+
Read-only: the commands are text to copy, never run, so the screen works with --read-only too. Who owns a
|
|
5
|
+
worktree is forge's own rule (scripts/forge_worktrees.py, which `forge runs rm` uses), loaded read-only the
|
|
6
|
+
way findings.py loads forge-contract.py, never a second rule.
|
|
7
|
+
|
|
8
|
+
Sources, merged by worktree path:
|
|
9
|
+
git `git worktree list --porcelain -z` in every repository forge-ui knows: the roots of the runs it
|
|
10
|
+
lists and the repositories the dataset names. Then `git status` per forge worktree on disk, one
|
|
11
|
+
`git show` per repository for the last commits, and `for-each-ref --merged` for merged branches.
|
|
12
|
+
disk folders under each `.forge-worktrees` that no repository lists (unknown to git).
|
|
13
|
+
run dirs each plan's tasks, statuses and whether its scheduler runs now.
|
|
14
|
+
dataset `forge dataset worktrees --json` (through the CLI): created and removed events, and the tasks with
|
|
15
|
+
an attempt, which name worktrees from before the events were recorded (derived rows, no dates).
|
|
16
|
+
|
|
17
|
+
Cost: none of this happens on the normal poll. The screen asks /api/worktrees when it opens and at a slow
|
|
18
|
+
interval; the result is cached for CACHE_S and recomputed sooner only on ?refresh=1. Sizes are walked in one
|
|
19
|
+
background thread and fill in later (`sizes_pending`).
|
|
20
|
+
|
|
21
|
+
Row statuses: in_use, dirty, locked, needed, failed, finished, missing, foreign, unknown, removed.
|
|
22
|
+
"""
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import importlib.machinery
|
|
26
|
+
import importlib.util
|
|
27
|
+
import os
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
import shlex
|
|
30
|
+
import stat
|
|
31
|
+
import subprocess
|
|
32
|
+
import threading
|
|
33
|
+
import time
|
|
34
|
+
|
|
35
|
+
from forge_ui import reader
|
|
36
|
+
|
|
37
|
+
RULES = Path(__file__).resolve().parents[2] / 'scripts' / 'forge_worktrees.py'
|
|
38
|
+
CACHE_S = 60
|
|
39
|
+
_GIT_TIMEOUT = 10
|
|
40
|
+
_SIZE_BUDGET_S = 120 # one tree's walk stops here and its size is a lower bound
|
|
41
|
+
_MAX_ROWS = 5000
|
|
42
|
+
STATUSES = ('in_use', 'dirty', 'locked', 'needed', 'failed', 'finished', 'missing', 'foreign', 'unknown', 'removed')
|
|
43
|
+
_ON_DISK = ('in_use', 'dirty', 'locked', 'needed', 'failed', 'finished', 'foreign', 'unknown')
|
|
44
|
+
_STATE = {}
|
|
45
|
+
_LOCK = threading.Lock()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _ReadOnlyLoader(importlib.machinery.SourceFileLoader):
|
|
49
|
+
def set_data(self, *args, **kwargs):
|
|
50
|
+
pass # no .pyc beside forge's scripts
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def rules():
|
|
54
|
+
"""forge's ownership rule module (scripts/forge_worktrees.py), or None when it cannot be loaded."""
|
|
55
|
+
with _LOCK:
|
|
56
|
+
if 'rules' not in _STATE:
|
|
57
|
+
try:
|
|
58
|
+
spec = importlib.util.spec_from_file_location(
|
|
59
|
+
'forge_worktrees_for_ui', RULES, loader=_ReadOnlyLoader('forge_worktrees_for_ui', str(RULES)))
|
|
60
|
+
module = importlib.util.module_from_spec(spec)
|
|
61
|
+
spec.loader.exec_module(module)
|
|
62
|
+
if not (callable(module.owner) and callable(module.parse_porcelain)):
|
|
63
|
+
raise TypeError('not the forge worktree rule module')
|
|
64
|
+
_STATE['rules'] = module
|
|
65
|
+
except Exception:
|
|
66
|
+
_STATE['rules'] = None
|
|
67
|
+
return _STATE['rules']
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _git(cwd, *args, timeout=_GIT_TIMEOUT):
|
|
71
|
+
"""(returncode, stdout text) of `git -C cwd <args>`, or (None, '') when git could not run."""
|
|
72
|
+
try:
|
|
73
|
+
done = subprocess.run(['git', '--no-optional-locks', '-C', cwd, *args], stdin=subprocess.DEVNULL,
|
|
74
|
+
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout, check=False,
|
|
75
|
+
env=dict(os.environ, GIT_TERMINAL_PROMPT='0', LC_ALL='C'))
|
|
76
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
77
|
+
return None, ''
|
|
78
|
+
return done.returncode, done.stdout.decode('utf-8', 'surrogateescape')
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _isdir(path):
|
|
82
|
+
try:
|
|
83
|
+
return os.path.isabs(path) and stat.S_ISDIR(os.lstat(path).st_mode)
|
|
84
|
+
except (OSError, ValueError):
|
|
85
|
+
return False
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _exists(path):
|
|
89
|
+
try:
|
|
90
|
+
return os.path.lexists(path)
|
|
91
|
+
except (OSError, ValueError):
|
|
92
|
+
return False
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _real(path):
|
|
96
|
+
try:
|
|
97
|
+
return os.path.realpath(path)
|
|
98
|
+
except (OSError, ValueError):
|
|
99
|
+
return path
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def quote(text):
|
|
103
|
+
return shlex.quote(str(text))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def commands(row):
|
|
107
|
+
"""What to copy for a row: [{label, command}]. Never --force; paths quoted for the shell."""
|
|
108
|
+
st, repo, path, branch = row['status'], row.get('git_dir') or row.get('repo'), row['path'], row.get('branch')
|
|
109
|
+
if st == 'dirty':
|
|
110
|
+
return [dict(label='see what is uncommitted', command='git -C %s status' % quote(path))]
|
|
111
|
+
if st == 'missing' and repo:
|
|
112
|
+
return [dict(label='forget the missing folder', command='git -C %s worktree prune' % quote(repo))]
|
|
113
|
+
if st in ('failed', 'finished') and repo:
|
|
114
|
+
out = [dict(label='remove the worktree', command='git -C %s worktree remove %s' % (quote(repo), quote(path)))]
|
|
115
|
+
if st == 'finished' and branch and row.get('merged'):
|
|
116
|
+
out.append(dict(label='delete its merged branch', command='git -C %s branch -d %s' % (quote(repo), quote(branch))))
|
|
117
|
+
return out
|
|
118
|
+
return []
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _note(row):
|
|
122
|
+
st = row['status']
|
|
123
|
+
if st == 'in_use':
|
|
124
|
+
return 'its run %s is active' % (row.get('run_id') or '')
|
|
125
|
+
if st == 'locked':
|
|
126
|
+
return ('locked by git' + (': ' + row['locked'] if row.get('locked') else '')
|
|
127
|
+
+ ('' if os.path.lexists(row['path']) else '; its folder is gone'))
|
|
128
|
+
if st == 'needed':
|
|
129
|
+
return 'the integration worktree of a run not integrated yet'
|
|
130
|
+
if st == 'failed':
|
|
131
|
+
return ('the branch stays, so a retry can recreate the worktree, but it runs the worktree setup again'
|
|
132
|
+
if row.get('branch') else 'not merged')
|
|
133
|
+
if st == 'foreign':
|
|
134
|
+
return row.get('why') or "not forge's: it fails forge's ownership rule"
|
|
135
|
+
if st == 'unknown':
|
|
136
|
+
return 'a folder git does not list as a worktree'
|
|
137
|
+
if st == 'removed':
|
|
138
|
+
if row.get('derived'):
|
|
139
|
+
return 'derived from the run dir or the dataset; removed at an unknown date'
|
|
140
|
+
return 'removed' if row.get('removed') else 'removed outside forge, at an unknown date'
|
|
141
|
+
return ''
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
# ---- the run dirs ------------------------------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
def _runs(catalog):
|
|
147
|
+
"""[{key, path, run_id, repo, root, tasks: {id: status}, live, integration}] for each plan forge-ui lists."""
|
|
148
|
+
out = []
|
|
149
|
+
try:
|
|
150
|
+
listed = catalog.runs()
|
|
151
|
+
except Exception:
|
|
152
|
+
return out
|
|
153
|
+
for run in listed:
|
|
154
|
+
if run.get('kind') != 'plan' or not run.get('repo') or not run.get('run_id'):
|
|
155
|
+
continue
|
|
156
|
+
read = reader._Read(run['path'])
|
|
157
|
+
try:
|
|
158
|
+
live = reader._scheduler(read)['live']
|
|
159
|
+
except Exception:
|
|
160
|
+
live = False
|
|
161
|
+
tasks = {t['id']: t['status'] for t in run.get('task_statuses') or [] if t.get('id')}
|
|
162
|
+
live = live or any(s == 'RUNNING' for s in tasks.values())
|
|
163
|
+
out.append(dict(key=run['key'], path=run['path'], run_id=run['run_id'], repo=run['repo'],
|
|
164
|
+
root=run.get('repo_root') or run['repo'], tasks=tasks, live=live,
|
|
165
|
+
integration=read.exists('accepted.integration') or read.exists('integration.base')))
|
|
166
|
+
return out
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# ---- the computation ---------------------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
def _repo_listing(R, repo):
|
|
172
|
+
"""(main working tree, [worktree records]) of the repository holding `repo`, or (None, [])."""
|
|
173
|
+
code, out = _git(repo, 'worktree', 'list', '--porcelain', '-z')
|
|
174
|
+
z = True
|
|
175
|
+
if code == 129:
|
|
176
|
+
code, out = _git(repo, 'worktree', 'list', '--porcelain')
|
|
177
|
+
z = False
|
|
178
|
+
if code != 0:
|
|
179
|
+
return None, []
|
|
180
|
+
found = R.parse_porcelain(out, z=z)
|
|
181
|
+
return (found[0]['path'], found) if found else (None, [])
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _layout(path):
|
|
185
|
+
"""(the `.forge-worktrees` folder, run id, name) when `path` is `<x>/.forge-worktrees/<run id>/<name>`,
|
|
186
|
+
(folder, None, name) when it sits directly in that folder, else None."""
|
|
187
|
+
real = _real(path)
|
|
188
|
+
parent, name = os.path.split(real)
|
|
189
|
+
grand, run_id = os.path.split(parent)
|
|
190
|
+
if os.path.basename(grand) == '.forge-worktrees':
|
|
191
|
+
return grand, run_id, name
|
|
192
|
+
if os.path.basename(parent) == '.forge-worktrees':
|
|
193
|
+
return parent, None, name
|
|
194
|
+
return None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def compute(catalog, history):
|
|
198
|
+
"""The screen's rows, without sizes. `history` is the dataset's answer (a dict) or None."""
|
|
199
|
+
R = rules()
|
|
200
|
+
if R is None:
|
|
201
|
+
return dict(rows=[], runs=[], repos=[], notes=["forge's worktree rule (scripts/forge_worktrees.py) could not be loaded"],
|
|
202
|
+
dataset=None, computed=time.time())
|
|
203
|
+
hist = history if isinstance(history, dict) else None
|
|
204
|
+
runs = _runs(catalog)
|
|
205
|
+
by_root = {} # real wt_root -> run
|
|
206
|
+
for run in runs:
|
|
207
|
+
by_root[R.wt_root(run['repo'], run['run_id'])] = run
|
|
208
|
+
integrated = {(_real(i['repo_path']), i['run_id']) for i in (hist or {}).get('integrated') or []
|
|
209
|
+
if isinstance(i, dict) and i.get('repo_path') and i.get('run_id')}
|
|
210
|
+
dataset_tasks = {} # (real wt_root) -> set of task ids with an attempt
|
|
211
|
+
for a in (hist or {}).get('attempts') or []:
|
|
212
|
+
if isinstance(a, dict) and a.get('repo_path') and a.get('run_id') and a.get('task'):
|
|
213
|
+
dataset_tasks.setdefault((R.wt_root(a['repo_path'], a['run_id']), a['repo_path'], a['run_id']), set()).add(a['task'])
|
|
214
|
+
events = [e for e in (hist or {}).get('events') or [] if isinstance(e, dict) and isinstance(e.get('path'), str)]
|
|
215
|
+
|
|
216
|
+
# every repository to ask: run checkouts and roots, then the dataset's
|
|
217
|
+
candidates = []
|
|
218
|
+
for run in runs:
|
|
219
|
+
candidates += [run['root'], run['repo']]
|
|
220
|
+
for r in (hist or {}).get('repos') or []:
|
|
221
|
+
if isinstance(r, dict) and isinstance(r.get('path'), str):
|
|
222
|
+
candidates.append(r['path'])
|
|
223
|
+
for e in events:
|
|
224
|
+
if e.get('repo_path'):
|
|
225
|
+
candidates.append(e['repo_path'])
|
|
226
|
+
roots, listed, asked = {}, {}, set()
|
|
227
|
+
for repo in candidates:
|
|
228
|
+
if not repo or not _isdir(repo) or _real(repo) in asked:
|
|
229
|
+
continue
|
|
230
|
+
root, found = _repo_listing(R, repo)
|
|
231
|
+
for wt in found:
|
|
232
|
+
asked.add(_real(wt['path']))
|
|
233
|
+
asked.add(_real(repo))
|
|
234
|
+
if root is None or _real(root) in roots:
|
|
235
|
+
continue
|
|
236
|
+
roots[_real(root)] = dict(root=root, worktrees=found)
|
|
237
|
+
for wt in found:
|
|
238
|
+
listed[_real(wt['path'])] = (root, wt)
|
|
239
|
+
|
|
240
|
+
rows = {}
|
|
241
|
+
|
|
242
|
+
def tasks_of(root_key, repo, run_id):
|
|
243
|
+
run = by_root.get(root_key)
|
|
244
|
+
if run is not None:
|
|
245
|
+
return set(run['tasks']), run
|
|
246
|
+
out = set()
|
|
247
|
+
for (wroot, _repo, _rid), ids in dataset_tasks.items():
|
|
248
|
+
if wroot == root_key:
|
|
249
|
+
out |= ids
|
|
250
|
+
for e in events:
|
|
251
|
+
if e.get('run_id') == run_id and e.get('task') and e.get('repo_path') and R.wt_root(e['repo_path'], run_id) == root_key:
|
|
252
|
+
out.add(e['task'])
|
|
253
|
+
return out, None
|
|
254
|
+
|
|
255
|
+
# merged branches per repository: into HEAD (for `branch -d`), and task branches into each integration branch
|
|
256
|
+
merged_head = {}
|
|
257
|
+
for key, info in roots.items():
|
|
258
|
+
code, out = _git(info['root'], 'for-each-ref', '--merged', 'HEAD', '--format=%(refname)', 'refs/heads/forge/')
|
|
259
|
+
merged_head[key] = set(out.split()) if code == 0 else set()
|
|
260
|
+
|
|
261
|
+
pending_status = []
|
|
262
|
+
heads = {}
|
|
263
|
+
for real, (root, wt) in listed.items():
|
|
264
|
+
where = _layout(wt['path'])
|
|
265
|
+
if where is None or wt.get('bare'):
|
|
266
|
+
continue
|
|
267
|
+
folder, run_id, name = where
|
|
268
|
+
root_key = _real(root)
|
|
269
|
+
row = dict(path=wt['path'], repo=root, git_dir=root, run=None, run_id=run_id, run_path=None, task=None,
|
|
270
|
+
branch=(wt['branch'] or '').replace('refs/heads/', '', 1) or None, kind=None, status=None,
|
|
271
|
+
merged=None, head=wt.get('head'), commit=None, created=None, removed=None, derived=False,
|
|
272
|
+
locked=wt.get('locked'), size=None, why=None)
|
|
273
|
+
if run_id is None:
|
|
274
|
+
row.update(status='foreign', why="not forge's: not inside a run's folder of .forge-worktrees")
|
|
275
|
+
else:
|
|
276
|
+
wroot = os.path.join(folder, run_id)
|
|
277
|
+
ids, run = tasks_of(wroot, root, run_id)
|
|
278
|
+
kind = R.owner(wt['path'], wt['branch'], run_id, ids, wroot)
|
|
279
|
+
if run is not None:
|
|
280
|
+
row.update(run=run['key'], run_path=run['path'])
|
|
281
|
+
row['kind'] = kind
|
|
282
|
+
if kind == 'task':
|
|
283
|
+
row['task'] = row['branch'].split('/', 2)[-1]
|
|
284
|
+
if not os.path.lexists(wt['path']) or wt.get('prunable') is not None:
|
|
285
|
+
# git keeps a locked worktree whose folder is gone (an unplugged disk): prune would not forget it
|
|
286
|
+
row['status'] = 'locked' if row['locked'] is not None else 'missing'
|
|
287
|
+
elif kind is None:
|
|
288
|
+
row.update(status='foreign', why="not forge's: " + ("its branch is not one of the run's" if run is not None or ids
|
|
289
|
+
else 'no run dir or dataset record names its run'))
|
|
290
|
+
elif run is not None and run['live']:
|
|
291
|
+
row['status'] = 'in_use'
|
|
292
|
+
else:
|
|
293
|
+
pending_status.append(row)
|
|
294
|
+
if row['branch']:
|
|
295
|
+
row['merged'] = ('refs/heads/' + row['branch']) in merged_head.get(root_key, set())
|
|
296
|
+
if row['head']:
|
|
297
|
+
heads.setdefault(root, set()).add(row['head'])
|
|
298
|
+
rows[real] = row
|
|
299
|
+
|
|
300
|
+
for row in pending_status:
|
|
301
|
+
code, out = _git(row['path'], 'status', '--porcelain', '--untracked-files=normal')
|
|
302
|
+
if code != 0 or out.strip():
|
|
303
|
+
row['status'] = 'dirty'
|
|
304
|
+
if code != 0:
|
|
305
|
+
row['why'] = 'git status failed, treated as uncommitted changes'
|
|
306
|
+
elif row['locked'] is not None:
|
|
307
|
+
row['status'] = 'locked'
|
|
308
|
+
else:
|
|
309
|
+
run = by_root.get(_real(os.path.dirname(row['path'])))
|
|
310
|
+
row['status'] = _settled(row, run, integrated, roots)
|
|
311
|
+
|
|
312
|
+
# the last commit of each worktree, one call per repository
|
|
313
|
+
for root, shas in heads.items():
|
|
314
|
+
code, out = _git(root, 'show', '-s', '--format=%H%x00%ct%x00%s%x1e', *sorted(shas))
|
|
315
|
+
if code != 0:
|
|
316
|
+
continue
|
|
317
|
+
info = {}
|
|
318
|
+
for record in out.split('\x1e'):
|
|
319
|
+
parts = record.strip('\n').split('\x00')
|
|
320
|
+
if len(parts) == 3 and parts[0]:
|
|
321
|
+
try:
|
|
322
|
+
info[parts[0]] = dict(sha=parts[0], time=int(parts[1]), subject=parts[2][:200])
|
|
323
|
+
except ValueError:
|
|
324
|
+
pass
|
|
325
|
+
for row in rows.values():
|
|
326
|
+
if row['repo'] == root and row['head'] in info:
|
|
327
|
+
row['commit'] = info[row['head']]
|
|
328
|
+
|
|
329
|
+
# folders git does not list
|
|
330
|
+
folders = set()
|
|
331
|
+
for info in roots.values():
|
|
332
|
+
for wt in info['worktrees']:
|
|
333
|
+
folders.add(os.path.join(os.path.dirname(_real(wt['path'])), '.forge-worktrees'))
|
|
334
|
+
where = _layout(wt['path'])
|
|
335
|
+
if where:
|
|
336
|
+
folders.add(where[0])
|
|
337
|
+
for run in runs:
|
|
338
|
+
folders.add(os.path.join(os.path.dirname(_real(run['repo'])), '.forge-worktrees'))
|
|
339
|
+
for folder in sorted(folders):
|
|
340
|
+
for first in _children(folder):
|
|
341
|
+
if _real(first) in listed:
|
|
342
|
+
continue
|
|
343
|
+
if _exists(os.path.join(first, '.git')):
|
|
344
|
+
_unknown(rows, first, None, by_root)
|
|
345
|
+
continue
|
|
346
|
+
for second in _children(first):
|
|
347
|
+
if _real(second) not in listed:
|
|
348
|
+
_unknown(rows, second, os.path.basename(first), by_root)
|
|
349
|
+
|
|
350
|
+
# what the dataset and the run dirs say was there: removed unless it is on disk now
|
|
351
|
+
last_created, last_removed, by = {}, {}, {}
|
|
352
|
+
for e in events:
|
|
353
|
+
real = _real(e['path']) if os.path.isabs(e['path']) else e['path']
|
|
354
|
+
if e['name'] == 'worktree_created':
|
|
355
|
+
last_created[real] = e
|
|
356
|
+
else:
|
|
357
|
+
last_removed[real] = e
|
|
358
|
+
by.setdefault(real, e)
|
|
359
|
+
for real in set(last_created) | set(last_removed):
|
|
360
|
+
created, removed = last_created.get(real), last_removed.get(real)
|
|
361
|
+
if removed is not None and created is not None and removed['ts'] < created['ts']:
|
|
362
|
+
removed = None
|
|
363
|
+
if real in rows:
|
|
364
|
+
if created is not None:
|
|
365
|
+
rows[real]['created'] = created['ts']
|
|
366
|
+
continue
|
|
367
|
+
e = created or removed
|
|
368
|
+
root_key = R.wt_root(e['repo_path'], e['run_id']) if e.get('repo_path') and e.get('run_id') else None
|
|
369
|
+
run = by_root.get(root_key) if root_key else None
|
|
370
|
+
rows[real] = dict(path=e['path'], repo=e.get('repo_path'), git_dir=None, run=run['key'] if run else None,
|
|
371
|
+
run_id=e.get('run_id'), run_path=run['path'] if run else None, task=e.get('task'),
|
|
372
|
+
branch=e.get('branch'), kind=e.get('kind'), status='removed', merged=None, head=None,
|
|
373
|
+
commit=None, created=created['ts'] if created else None,
|
|
374
|
+
removed=removed['ts'] if removed else None, derived=False, locked=None, size=None, why=None)
|
|
375
|
+
for run in runs:
|
|
376
|
+
wroot = R.wt_root(run['repo'], run['run_id'])
|
|
377
|
+
names = [t for t, s in run['tasks'].items() if s not in ('PENDING', 'BLOCKED', None)]
|
|
378
|
+
if run['integration']:
|
|
379
|
+
names.append('_integration')
|
|
380
|
+
for name in names:
|
|
381
|
+
_derived(rows, os.path.join(wroot, name), run['repo'], run['run_id'], name, run)
|
|
382
|
+
for (wroot, repo, run_id), ids in sorted(dataset_tasks.items()):
|
|
383
|
+
run = by_root.get(wroot)
|
|
384
|
+
for name in sorted(ids) + ['_integration']:
|
|
385
|
+
_derived(rows, os.path.join(wroot, name), repo, run_id, name, run)
|
|
386
|
+
|
|
387
|
+
out = []
|
|
388
|
+
for row in rows.values():
|
|
389
|
+
row['commands'] = commands(row)
|
|
390
|
+
row['note'] = _note(row)
|
|
391
|
+
row.pop('why', None)
|
|
392
|
+
out.append(row)
|
|
393
|
+
out.sort(key=lambda r: (r['status'] == 'removed', STATUSES.index(r['status']), -(r['removed'] or r['created'] or 0), r['path']))
|
|
394
|
+
run_groups = []
|
|
395
|
+
for run in runs:
|
|
396
|
+
if not any(r['run'] == run['key'] for r in out):
|
|
397
|
+
continue
|
|
398
|
+
group = dict(key=run['key'], run_id=run['run_id'], path=run['path'], repo=run['root'], active=run['live'], command=None)
|
|
399
|
+
if not run['live'] and _isdir(run['path']):
|
|
400
|
+
group['command'] = 'forge runs rm %s --worktrees --branches --dry-run' % quote(run['path'])
|
|
401
|
+
run_groups.append(group)
|
|
402
|
+
notes = []
|
|
403
|
+
if hist is None:
|
|
404
|
+
notes.append('the dataset could not be read: only what git and the run dirs say is listed')
|
|
405
|
+
elif not hist.get('enabled'):
|
|
406
|
+
notes.append('the dataset is off (FORGE_DATASET=off): forge keeps no history of its worktrees, so only what git and the run dirs say is listed')
|
|
407
|
+
return dict(rows=out[:_MAX_ROWS], truncated=len(out) > _MAX_ROWS, runs=run_groups,
|
|
408
|
+
repos=sorted(info['root'] for info in roots.values()), notes=notes,
|
|
409
|
+
dataset=None if hist is None else dict(enabled=bool(hist.get('enabled')), since=hist.get('since')),
|
|
410
|
+
computed=time.time())
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _settled(row, run, integrated, roots):
|
|
414
|
+
"""finished, failed or needed for a clean, unlocked forge worktree of a run that is not active."""
|
|
415
|
+
kind = row['kind']
|
|
416
|
+
if kind == 'integration':
|
|
417
|
+
if run is None:
|
|
418
|
+
return 'finished' # no run dir is left to need it
|
|
419
|
+
# Integrated per the dataset, or its branch is in the user's and no task is left to retry into it: a branch
|
|
420
|
+
# nothing was merged into yet is an ancestor of HEAD too, and the run still needs it.
|
|
421
|
+
done = (_real(run['repo']), run['run_id']) in integrated or (
|
|
422
|
+
bool(row['merged']) and all(status == 'MERGED' for status in run['tasks'].values()))
|
|
423
|
+
return 'finished' if done else 'needed'
|
|
424
|
+
if kind == 'task':
|
|
425
|
+
if run is not None and row['task'] in run['tasks']:
|
|
426
|
+
return 'finished' if run['tasks'][row['task']] == 'MERGED' else 'failed'
|
|
427
|
+
if row['merged']:
|
|
428
|
+
return 'finished'
|
|
429
|
+
int_br = 'forge/%s-integration' % row['run_id']
|
|
430
|
+
code, _ = _git(row['git_dir'], 'merge-base', '--is-ancestor', 'refs/heads/' + row['branch'], 'refs/heads/' + int_br)
|
|
431
|
+
return 'finished' if code == 0 else 'failed'
|
|
432
|
+
return 'finished' # a scratch worktree forge left behind
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _children(folder):
|
|
436
|
+
try:
|
|
437
|
+
with os.scandir(folder) as entries:
|
|
438
|
+
return sorted(os.path.join(folder, e.name) for e in entries if e.is_dir(follow_symlinks=False))
|
|
439
|
+
except (OSError, ValueError):
|
|
440
|
+
return []
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _unknown(rows, path, run_id, by_root):
|
|
444
|
+
real = _real(path)
|
|
445
|
+
if real in rows:
|
|
446
|
+
return
|
|
447
|
+
run = by_root.get(_real(os.path.dirname(path))) if run_id else None
|
|
448
|
+
name = os.path.basename(path)
|
|
449
|
+
kind = 'integration' if name == '_integration' else 'candidate' if name.startswith('_candidate-') else \
|
|
450
|
+
'attribute' if name.startswith('_attribute') else 'task' if run_id else None
|
|
451
|
+
rows[real] = dict(path=path, repo=run['root'] if run else None, git_dir=None, run=run['key'] if run else None,
|
|
452
|
+
run_id=run_id, run_path=run['path'] if run else None, task=name if kind == 'task' else None,
|
|
453
|
+
branch=None, kind=kind, status='unknown', merged=None, head=None, commit=None, created=None,
|
|
454
|
+
removed=None, derived=False, locked=None, size=None, why=None)
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _derived(rows, path, repo, run_id, name, run):
|
|
458
|
+
real = _real(path)
|
|
459
|
+
if real in rows or _exists(path):
|
|
460
|
+
return
|
|
461
|
+
kind = 'integration' if name == '_integration' else 'task'
|
|
462
|
+
rows[real] = dict(path=path, repo=repo, git_dir=None, run=run['key'] if run else None, run_id=run_id,
|
|
463
|
+
run_path=run['path'] if run else None, task=name if kind == 'task' else None,
|
|
464
|
+
branch='forge/%s-integration' % run_id if kind == 'integration' else 'forge/%s/%s' % (run_id, name),
|
|
465
|
+
kind=kind, status='removed', merged=None, head=None, commit=None, created=None, removed=None,
|
|
466
|
+
derived=True, locked=None, size=None, why=None)
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
# ---- sizes, in the background ------------------------------------------------------------------
|
|
470
|
+
|
|
471
|
+
def tree_size(path, budget=_SIZE_BUDGET_S):
|
|
472
|
+
"""(bytes on disk, complete) of a tree, symlinks not followed; stops after `budget` seconds."""
|
|
473
|
+
total, stack, start = 0, [path], time.monotonic()
|
|
474
|
+
while stack:
|
|
475
|
+
if time.monotonic() - start > budget:
|
|
476
|
+
return total, False
|
|
477
|
+
here = stack.pop()
|
|
478
|
+
try:
|
|
479
|
+
with os.scandir(here) as entries:
|
|
480
|
+
for entry in entries:
|
|
481
|
+
try:
|
|
482
|
+
info = entry.stat(follow_symlinks=False)
|
|
483
|
+
except OSError:
|
|
484
|
+
continue
|
|
485
|
+
total += getattr(info, 'st_blocks', 0) * 512 or info.st_size
|
|
486
|
+
if stat.S_ISDIR(info.st_mode):
|
|
487
|
+
stack.append(entry.path)
|
|
488
|
+
except (OSError, ValueError):
|
|
489
|
+
continue
|
|
490
|
+
return total, True
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
class Sizes:
|
|
494
|
+
"""Sizes of worktree folders, walked one at a time in a daemon thread."""
|
|
495
|
+
|
|
496
|
+
def __init__(self):
|
|
497
|
+
self.lock = threading.Lock()
|
|
498
|
+
self.known = {} # path -> bytes
|
|
499
|
+
self.queue = []
|
|
500
|
+
self.thread = None
|
|
501
|
+
|
|
502
|
+
def want(self, paths, again=False):
|
|
503
|
+
with self.lock:
|
|
504
|
+
for path in paths:
|
|
505
|
+
if (again or path not in self.known) and path not in self.queue:
|
|
506
|
+
self.queue.append(path)
|
|
507
|
+
if self.queue and (self.thread is None or not self.thread.is_alive()):
|
|
508
|
+
self.thread = threading.Thread(target=self._work, name='forge-ui-sizes', daemon=True)
|
|
509
|
+
self.thread.start()
|
|
510
|
+
|
|
511
|
+
def _work(self):
|
|
512
|
+
while True:
|
|
513
|
+
with self.lock:
|
|
514
|
+
if not self.queue:
|
|
515
|
+
return
|
|
516
|
+
path = self.queue[0]
|
|
517
|
+
size, _complete = tree_size(path)
|
|
518
|
+
with self.lock:
|
|
519
|
+
self.known[path] = size
|
|
520
|
+
if self.queue and self.queue[0] == path:
|
|
521
|
+
self.queue.pop(0)
|
|
522
|
+
|
|
523
|
+
def pending(self):
|
|
524
|
+
with self.lock:
|
|
525
|
+
return len(self.queue)
|
|
526
|
+
|
|
527
|
+
def get(self, path):
|
|
528
|
+
with self.lock:
|
|
529
|
+
return self.known.get(path)
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
class Screen:
|
|
533
|
+
"""The cached answer of /api/worktrees for one server."""
|
|
534
|
+
|
|
535
|
+
def __init__(self):
|
|
536
|
+
self.lock = threading.Lock()
|
|
537
|
+
self.result = None
|
|
538
|
+
self.sizes = Sizes()
|
|
539
|
+
|
|
540
|
+
def answer(self, catalog, history, refresh=False, now=None):
|
|
541
|
+
"""The rows with the sizes known so far. `history()` is called only when the cache is recomputed."""
|
|
542
|
+
now = time.time() if now is None else now
|
|
543
|
+
with self.lock:
|
|
544
|
+
if refresh or self.result is None or now - self.result['computed'] > CACHE_S:
|
|
545
|
+
self.result = compute(catalog, history())
|
|
546
|
+
on_disk = [r['path'] for r in self.result['rows'] if r['status'] in _ON_DISK]
|
|
547
|
+
self.sizes.want(on_disk, again=refresh)
|
|
548
|
+
result = self.result
|
|
549
|
+
rows = []
|
|
550
|
+
totals = dict(count=0, on_disk=0, bytes=0, by_status={s: 0 for s in STATUSES})
|
|
551
|
+
for row in result['rows']:
|
|
552
|
+
row = dict(row)
|
|
553
|
+
if row['status'] in _ON_DISK:
|
|
554
|
+
row['size'] = self.sizes.get(row['path'])
|
|
555
|
+
totals['on_disk'] += 1
|
|
556
|
+
totals['bytes'] += row['size'] or 0
|
|
557
|
+
totals['count'] += 1
|
|
558
|
+
totals['by_status'][row['status']] += 1
|
|
559
|
+
rows.append(row)
|
|
560
|
+
out = dict(result, rows=rows, totals=totals, sizes_pending=self.sizes.pending())
|
|
561
|
+
return out
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def screen(server):
|
|
565
|
+
"""The server's Screen, made on first use."""
|
|
566
|
+
with _LOCK:
|
|
567
|
+
found = getattr(server, 'worktree_screen', None)
|
|
568
|
+
if found is None:
|
|
569
|
+
found = server.worktree_screen = Screen()
|
|
570
|
+
return found
|