@giamme/forge 0.18.0 → 0.20.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 +49 -0
- package/README.md +1 -0
- package/SKILL.md +19 -2
- package/VERSION +1 -1
- package/docs/artifacts.md +25 -1
- package/docs/commands.md +217 -18
- package/docs/decomposed-runs.md +114 -1
- package/docs/development.md +2 -1
- package/docs/forge-ui.md +138 -18
- package/docs/memory.md +25 -4
- package/docs/models.md +8 -0
- package/docs/reviews.md +122 -0
- package/forge +26 -3
- package/package.json +2 -1
- package/references/dataset.md +20 -1
- package/references/decompose.md +641 -41
- package/references/harnesses.md +18 -3
- package/references/memory.md +30 -5
- package/references/planning.md +43 -14
- package/references/ui.md +53 -6
- package/registry.tsv +8 -3
- package/scripts/forge-brief.py +88 -3
- package/scripts/forge-compare.py +4 -3
- package/scripts/forge-contract.py +202 -27
- package/scripts/forge-control.py +117 -5
- package/scripts/forge-dispatch.sh +34 -5
- package/scripts/forge-findings.py +675 -0
- package/scripts/forge-group.py +496 -0
- package/scripts/forge-groups.py +89 -0
- package/scripts/forge-handoff.py +1128 -0
- package/scripts/forge-issues.py +228 -97
- package/scripts/forge-lib-group.sh +641 -0
- package/scripts/forge-lib-plans.sh +339 -3
- package/scripts/forge-lib-task.sh +197 -4
- package/scripts/forge-memory.sh +711 -17
- package/scripts/forge-parallel.sh +721 -38
- package/scripts/forge-planner.py +104 -8
- package/scripts/forge-route.py +190 -12
- package/scripts/forge-runs.py +9 -5
- package/scripts/forge-schedule.py +417 -52
- package/scripts/forge-solo.sh +2 -0
- package/scripts/forge-sweep.py +199 -44
- package/scripts/forge-worktrees.py +243 -0
- package/scripts/forge_brief/__init__.py +294 -50
- package/scripts/forge_brief/answers.py +58 -11
- package/scripts/forge_brief/proposals.py +1630 -0
- package/scripts/forge_dataset/efforts.py +4 -3
- package/scripts/forge_dataset/export.py +24 -12
- package/scripts/forge_dataset/facts.py +5 -3
- package/scripts/forge_dataset/forecast.py +8 -18
- package/scripts/forge_dataset/harvest.py +204 -9
- package/scripts/forge_dataset/history.py +11 -6
- package/scripts/forge_dataset/importer.py +65 -1
- package/scripts/forge_dataset/names.py +66 -0
- package/scripts/forge_dataset/reviewers.py +5 -2
- package/scripts/forge_dataset/risk.py +6 -3
- package/scripts/forge_dataset/routing.py +6 -1
- package/scripts/forge_findings/__init__.py +17 -0
- package/scripts/forge_findings/apply.py +441 -0
- package/scripts/forge_findings/status.py +43 -0
- package/scripts/forge_findings/store.py +583 -0
- package/scripts/forge_findings/tags.py +53 -0
- package/scripts/forge_findings/triage.py +603 -0
- package/scripts/forge_groups/__init__.py +308 -0
- package/scripts/forge_groups/attribute.py +289 -0
- package/scripts/forge_groups/review.py +286 -0
- package/scripts/forge_identity.py +327 -0
- package/scripts/forge_memory_list.py +7 -3
- package/scripts/forge_owner.py +152 -0
- package/scripts/forge_side/__init__.py +228 -38
- package/ui/docs/api.md +303 -29
- package/ui/forge_ui/control.py +1018 -6
- package/ui/forge_ui/executions.py +8 -1
- package/ui/forge_ui/export.py +31 -4
- package/ui/forge_ui/groups.py +264 -0
- package/ui/forge_ui/models.py +70 -8
- package/ui/forge_ui/projects.py +209 -22
- package/ui/forge_ui/reader.py +262 -19
- package/ui/forge_ui/server.py +4 -0
- package/ui/forge_ui/static/app.js +93 -13
- package/ui/forge_ui/static/briefview.js +350 -47
- package/ui/forge_ui/static/diffview.js +86 -1
- package/ui/forge_ui/static/findingsactions.js +201 -0
- package/ui/forge_ui/static/groupsview.js +332 -0
- package/ui/forge_ui/static/index.html +3 -0
- package/ui/forge_ui/static/panel.js +127 -7
- package/ui/forge_ui/static/projectsview.js +764 -30
- package/ui/forge_ui/static/runmodel.js +14 -3
- package/ui/forge_ui/static/storageview.js +91 -10
- package/ui/forge_ui/static/style.css +138 -5
- package/ui/forge_ui/static/triageview.js +423 -0
- package/ui/forge_ui/static/worktreesview.js +233 -12
- package/ui/forge_ui/storage.py +14 -0
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""The text side of one group review (#140): the prompt, the decision files, the round's facts.
|
|
3
|
+
|
|
4
|
+
forge-lib-group.sh builds the candidate and dispatches the reviewer; this prints what the reviewer
|
|
5
|
+
reads and what a person reads when the round stops for a decision. Stdlib only.
|
|
6
|
+
|
|
7
|
+
python3 -I scripts/forge_groups/review.py prompt PLAN GID [--threshold P2]
|
|
8
|
+
python3 -I scripts/forge_groups/review.py decision PLAN GID oversized --size BYTES --limit KB
|
|
9
|
+
python3 -I scripts/forge_groups/review.py decision PLAN GID ambiguous --attribution FILE
|
|
10
|
+
python3 -I scripts/forge_groups/review.py facts ATTRIBUTION_JSON
|
|
11
|
+
|
|
12
|
+
`prompt` reads, under the plan and `groups/GID/`: groups.tsv, tasks.tsv, each member's task dir, the
|
|
13
|
+
group's `candidate.base`, `candidate.commit`, `members.tsv` and `round`, and the combined diff in
|
|
14
|
+
`combined.diff` (computed from the repository when absent). `facts` prints one line:
|
|
15
|
+
implicated<TAB>ambiguous<TAB>findings<TAB>blocking, the two lists comma separated or `-`.
|
|
16
|
+
Exit 0, or 2 on bad input with the reason on stderr.
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import argparse
|
|
21
|
+
import json
|
|
22
|
+
import subprocess
|
|
23
|
+
import sys
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
27
|
+
import forge_groups # noqa: E402
|
|
28
|
+
from forge_groups import attribute # noqa: E402
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ReviewError(Exception):
|
|
32
|
+
"""Bad input; the message is one line."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _read(path: Path) -> str:
|
|
36
|
+
try:
|
|
37
|
+
return path.read_text(encoding='utf-8', errors='replace')
|
|
38
|
+
except OSError:
|
|
39
|
+
return ''
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _git(repo: str, *args) -> str:
|
|
43
|
+
done = subprocess.run(['git', '-C', repo, '-c', 'core.quotepath=off', *args],
|
|
44
|
+
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False)
|
|
45
|
+
if done.returncode != 0:
|
|
46
|
+
raise ReviewError('git %s failed' % ' '.join(args[:2]))
|
|
47
|
+
return done.stdout.decode('utf-8', 'replace')
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _group(plan: Path, gid: str):
|
|
51
|
+
for group in forge_groups.load(plan):
|
|
52
|
+
if group.id == gid:
|
|
53
|
+
return group
|
|
54
|
+
raise ReviewError('%s is not a group of %s' % (gid, plan))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _tasks(plan: Path) -> dict:
|
|
58
|
+
return forge_groups._tasks(plan)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _rows(path: Path) -> list:
|
|
62
|
+
"""members.tsv rows as (round, task, commit, attempt)."""
|
|
63
|
+
rows = []
|
|
64
|
+
for line in _read(path).splitlines():
|
|
65
|
+
parts = line.split('\t')
|
|
66
|
+
if len(parts) == 4 and parts[0].isdigit():
|
|
67
|
+
rows.append((int(parts[0]), parts[1], parts[2], parts[3]))
|
|
68
|
+
return rows
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _round(gdir: Path) -> int:
|
|
72
|
+
text = _read(gdir / 'round').strip()
|
|
73
|
+
return int(text) if text.isdigit() else 1
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _attribution(gdir: Path):
|
|
77
|
+
try:
|
|
78
|
+
data = json.loads(_read(gdir / 'attribution.json'))
|
|
79
|
+
except ValueError:
|
|
80
|
+
return None
|
|
81
|
+
return data if isinstance(data, dict) and isinstance(data.get('findings'), list) else None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _finding_text(finding: dict, blocks: dict) -> str:
|
|
85
|
+
text = blocks.get(finding.get('n'))
|
|
86
|
+
if text:
|
|
87
|
+
return text.strip('\n')
|
|
88
|
+
where = finding.get('file') or 'no file'
|
|
89
|
+
if finding.get('line'):
|
|
90
|
+
where += ':%s' % finding['line']
|
|
91
|
+
return '- [%s][%s] %s' % (finding.get('severity') or '?', finding.get('status') or '?', where)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _earlier(gdir: Path):
|
|
95
|
+
"""The findings of the last reviewed round: (round, rows, {n: text}), or None."""
|
|
96
|
+
data = _attribution(gdir)
|
|
97
|
+
if not data or not isinstance(data.get('round'), int) or data['round'] >= _round(gdir):
|
|
98
|
+
return None
|
|
99
|
+
reply = _read(gdir / ('qa.round-%d.last' % data['round']))
|
|
100
|
+
blocks = {number: finding.text for number, finding in
|
|
101
|
+
enumerate(attribute._contract().parse_findings(reply), 1)}
|
|
102
|
+
return data['round'], [f for f in data['findings'] if isinstance(f, dict)], blocks
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _stat(repo: str, base: str, commit: str) -> str:
|
|
106
|
+
try:
|
|
107
|
+
return _git(repo, 'diff', '--stat', base, commit, '--', '.', ':(exclude).forge').rstrip('\n')
|
|
108
|
+
except ReviewError:
|
|
109
|
+
return '(the diff stat could not be read)'
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _member(plan: Path, repo: str, task: str, row: list, gdir: Path, current: int, earlier, history: dict) -> list:
|
|
113
|
+
tdir = plan / 'tasks' / task
|
|
114
|
+
commit = _read(tdir / 'reviewed.commit').strip()
|
|
115
|
+
base = _read(tdir / 'base_ref').strip()
|
|
116
|
+
out = ['## Task %s: %s' % (task, row[6] if len(row) > 6 else task), '', _read(tdir / 'prompt.md').rstrip('\n')]
|
|
117
|
+
approach = _read(tdir / 'approach.md').strip('\n')
|
|
118
|
+
if approach:
|
|
119
|
+
out += ['', 'Intended approach:', approach]
|
|
120
|
+
out += ['', 'Files this task declared it would touch: %s' % (row[3] if len(row) > 3 else '-'),
|
|
121
|
+
'Reviewed commit: %s' % commit]
|
|
122
|
+
if base and commit:
|
|
123
|
+
out += ['Its own diff against its base (%s):' % base[:7], _stat(repo, base, commit)]
|
|
124
|
+
# The same wording the task review uses, so a reviewer reads one vocabulary.
|
|
125
|
+
prereview = _read(tdir / 'prereview.txt').rstrip('\n')
|
|
126
|
+
if prereview.strip():
|
|
127
|
+
out += ['', prereview]
|
|
128
|
+
guard = [line for line in _read(tdir / 'guard.txt').splitlines() if line.strip()]
|
|
129
|
+
if guard:
|
|
130
|
+
out += ['', 'Implementer guard notes (observed by forge, not claimed by the implementer):']
|
|
131
|
+
out += [' - ' + line for line in guard]
|
|
132
|
+
out += ["A promise of later work means a check may never have run; judge the diff on its own merits."]
|
|
133
|
+
drift = [line for line in _read(tdir / 'drift.txt').splitlines() if line.strip()]
|
|
134
|
+
if drift:
|
|
135
|
+
out += ['', 'Scope note: this task declared it would touch %s, and the' % (row[3] if len(row) > 3 else '-'),
|
|
136
|
+
'diff also changes files it did not declare:']
|
|
137
|
+
out += [' - ' + line for line in drift]
|
|
138
|
+
out += ['That is not automatically wrong — judge whether each was actually necessary. It',
|
|
139
|
+
'matters because another task may own those files.']
|
|
140
|
+
if earlier:
|
|
141
|
+
number, findings, blocks = earlier
|
|
142
|
+
mine = [f for f in findings if task in (f.get('tasks') or [])]
|
|
143
|
+
if mine:
|
|
144
|
+
out += ['', "Round %d findings attributed to this task (check each one against the code now):" % number]
|
|
145
|
+
for finding in mine:
|
|
146
|
+
out += [_finding_text(finding, blocks)]
|
|
147
|
+
previous = history.get(task)
|
|
148
|
+
now = history.get((task, current))
|
|
149
|
+
if previous is not None and now is not None and previous != now:
|
|
150
|
+
reply = _read(tdir / 'dwarf.last').strip('\n')
|
|
151
|
+
out += ['', 'This task was reworked since round %d (attempt %s, then attempt %s).' % (number, previous, now)]
|
|
152
|
+
if reply:
|
|
153
|
+
out += ["The implementer's reply for the new attempt, to check against the code:", reply]
|
|
154
|
+
return out
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _combined(repo: str, gdir: Path, base: str, commit: str) -> str:
|
|
158
|
+
text = _read(gdir / 'combined.diff')
|
|
159
|
+
if text:
|
|
160
|
+
return text
|
|
161
|
+
return _git(repo, 'diff', '--binary', '--irreversible-delete', base, commit, '--', '.', ':(exclude).forge')
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def prompt(plan: Path, gid: str, threshold) -> str:
|
|
165
|
+
group = _group(plan, gid)
|
|
166
|
+
tasks = _tasks(plan)
|
|
167
|
+
repo = _read(plan / 'repo').strip()
|
|
168
|
+
gdir = plan / 'groups' / gid
|
|
169
|
+
base = _read(gdir / 'candidate.base').strip()
|
|
170
|
+
commit = _read(gdir / 'candidate.commit').strip()
|
|
171
|
+
if not base or not commit:
|
|
172
|
+
raise ReviewError('group %s has no candidate yet' % gid)
|
|
173
|
+
current = _round(gdir)
|
|
174
|
+
rows = _rows(gdir / 'members.tsv')
|
|
175
|
+
history = {}
|
|
176
|
+
for number, task, _, attempt in rows:
|
|
177
|
+
if number < current:
|
|
178
|
+
history[task] = attempt # the last round before this one that held the task
|
|
179
|
+
elif number == current:
|
|
180
|
+
history[(task, current)] = attempt
|
|
181
|
+
earlier = _earlier(gdir)
|
|
182
|
+
contract = attribute._contract()
|
|
183
|
+
out = [contract.qa_text('head', 'group').rstrip('\n'), '']
|
|
184
|
+
out += ['# Group %s: %s' % (gid, group.title if group.title != '-' else gid)]
|
|
185
|
+
if group.goal != '-':
|
|
186
|
+
out += ['', 'Goal of the group: %s' % group.goal]
|
|
187
|
+
out += ['', 'Members, in merge order: %s.' % ', '.join(group.members), '']
|
|
188
|
+
if earlier:
|
|
189
|
+
number, findings, blocks = earlier
|
|
190
|
+
loose = [f for f in findings if not f.get('tasks')]
|
|
191
|
+
if loose:
|
|
192
|
+
out += ['## Round %d findings that named no task' % number]
|
|
193
|
+
out += [_finding_text(f, blocks) for f in loose] + ['']
|
|
194
|
+
for task in group.members:
|
|
195
|
+
out += _member(plan, repo, task, tasks.get(task, []), gdir, current, earlier, history) + ['']
|
|
196
|
+
out += [contract.qa_text('tail', 'group', threshold).rstrip('\n'), '']
|
|
197
|
+
out += ['```diff', _combined(repo, gdir, base, commit).rstrip('\n'), '```']
|
|
198
|
+
return '\n'.join(out) + '\n'
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def decision(plan: Path, gid: str, reason: str, size: int, limit: int, attribution: str) -> str:
|
|
202
|
+
gdir = plan / 'groups' / gid
|
|
203
|
+
lines = ['reasons: %s' % reason, '']
|
|
204
|
+
if reason == 'oversized':
|
|
205
|
+
lines += [
|
|
206
|
+
'Group %s was not reviewed: its combined diff is %d bytes (%.1f KB), over the limit of %d KB'
|
|
207
|
+
% (gid, size, size / 1024.0, limit),
|
|
208
|
+
'(group_max_diff_kb in the plan). Nothing was dispatched, truncated or re-routed.',
|
|
209
|
+
'',
|
|
210
|
+
'Choices:',
|
|
211
|
+
' split the group: edit %s/groups.tsv so its members form smaller groups, then run plan again' % plan,
|
|
212
|
+
' review each task alone: set the review of %s to `task` in %s/groups.tsv, then run plan again' % (gid, plan),
|
|
213
|
+
]
|
|
214
|
+
else:
|
|
215
|
+
try:
|
|
216
|
+
data = json.loads(_read(Path(attribution)))
|
|
217
|
+
except ValueError:
|
|
218
|
+
data = None
|
|
219
|
+
wanted = set((data or {}).get('ambiguous') or [])
|
|
220
|
+
reply = _read(gdir / 'qa.last')
|
|
221
|
+
blocks = {number: finding.text for number, finding in
|
|
222
|
+
enumerate(attribute._contract().parse_findings(reply), 1)}
|
|
223
|
+
lines += ['Group %s stopped for your decision: the reviewer reported a blocking finding that names no' % gid,
|
|
224
|
+
'member task (no file of any member, or a task id outside the group), so forge cannot tell',
|
|
225
|
+
'which task has to change. Nothing retried.', '', 'Ambiguous blocking findings:']
|
|
226
|
+
for finding in (data or {}).get('findings') or []:
|
|
227
|
+
if finding.get('n') in wanted:
|
|
228
|
+
lines += ['', _finding_text(finding, blocks)]
|
|
229
|
+
lines += ['', 'The full review is in %s/qa.last.' % gdir, '',
|
|
230
|
+
'Choices:',
|
|
231
|
+
' name the task: answer with the member task id(s) each finding belongs to, then review again',
|
|
232
|
+
' review each task alone: set the review of %s to `task` in %s/groups.tsv, then run plan again' % (gid, plan)]
|
|
233
|
+
return '\n'.join(lines) + '\n'
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def facts(path: str) -> str:
|
|
237
|
+
try:
|
|
238
|
+
data = json.loads(_read(Path(path)))
|
|
239
|
+
except ValueError:
|
|
240
|
+
data = None
|
|
241
|
+
if not isinstance(data, dict):
|
|
242
|
+
raise ReviewError('%s is not an attribution' % path)
|
|
243
|
+
|
|
244
|
+
def listed(values):
|
|
245
|
+
return ','.join(str(v) for v in values) if values else '-'
|
|
246
|
+
|
|
247
|
+
return '%s\t%s\t%d\t%d' % (listed(data.get('implicated')), listed(data.get('ambiguous')),
|
|
248
|
+
len(data.get('findings') or []), 1 if data.get('blocking') else 0)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def main(argv=None) -> int:
|
|
252
|
+
parser = argparse.ArgumentParser(prog='review.py', description=__doc__.split('\n')[0])
|
|
253
|
+
sub = parser.add_subparsers(dest='command', required=True)
|
|
254
|
+
p = sub.add_parser('prompt')
|
|
255
|
+
p.add_argument('plan')
|
|
256
|
+
p.add_argument('gid')
|
|
257
|
+
p.add_argument('--threshold', default=None)
|
|
258
|
+
d = sub.add_parser('decision')
|
|
259
|
+
d.add_argument('plan')
|
|
260
|
+
d.add_argument('gid')
|
|
261
|
+
d.add_argument('reason', choices=('oversized', 'ambiguous'))
|
|
262
|
+
d.add_argument('--size', type=int, default=0)
|
|
263
|
+
d.add_argument('--limit', type=int, default=0)
|
|
264
|
+
d.add_argument('--attribution', default='')
|
|
265
|
+
f = sub.add_parser('facts')
|
|
266
|
+
f.add_argument('attribution')
|
|
267
|
+
args = parser.parse_args(argv)
|
|
268
|
+
try:
|
|
269
|
+
if args.command == 'facts':
|
|
270
|
+
text = facts(args.attribution) + '\n'
|
|
271
|
+
else:
|
|
272
|
+
plan = Path(args.plan)
|
|
273
|
+
if args.command == 'prompt':
|
|
274
|
+
text = prompt(plan, args.gid, args.threshold)
|
|
275
|
+
else:
|
|
276
|
+
_group(plan, args.gid)
|
|
277
|
+
text = decision(plan, args.gid, args.reason, args.size, args.limit, args.attribution)
|
|
278
|
+
except (ReviewError, forge_groups.GroupError, ValueError) as error:
|
|
279
|
+
sys.stderr.write('review: %s\n' % ' '.join(str(error).split()))
|
|
280
|
+
return 2
|
|
281
|
+
sys.stdout.write(text)
|
|
282
|
+
return 0
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
if __name__ == '__main__':
|
|
286
|
+
sys.exit(main())
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"""Which repository a checkout or a run belongs to, and every checkout forge has seen of it.
|
|
2
|
+
|
|
3
|
+
The run registry and the dismissal store are keyed by the checkout path, so a run
|
|
4
|
+
started from a linked worktree is filed under that worktree. Once the worktree is
|
|
5
|
+
gone, that path no longer names the repository. This module answers for the
|
|
6
|
+
repository itself: the main working tree, the same identity key `forge_registry`
|
|
7
|
+
uses for that tree, the checkouts forge has recorded and the run dirs registered
|
|
8
|
+
under any of them.
|
|
9
|
+
|
|
10
|
+
It only reads. A missing path, an unreadable file and a git failure are unknown,
|
|
11
|
+
never an exception. `identity` and `checkouts` are cached per process.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import stat
|
|
20
|
+
import subprocess
|
|
21
|
+
|
|
22
|
+
import forge_locations
|
|
23
|
+
import forge_registry
|
|
24
|
+
|
|
25
|
+
# A file in <run>/tasks/<id>/ sits three directories under the run dir.
|
|
26
|
+
_RUN_DIR_WALK = 3
|
|
27
|
+
_REPO_READ_MAX = 64 * 1024
|
|
28
|
+
_REGISTRY_READ_MAX = 1 << 20
|
|
29
|
+
_GIT_TIMEOUT = 10
|
|
30
|
+
# Same shape as forge-issues.py github_slug.
|
|
31
|
+
_ORIGIN_SLUG = re.compile(r'github\.com[:/]([^/\s]+)/([^/\s]+?)(?:\.git)?/?$')
|
|
32
|
+
|
|
33
|
+
_identity_cache: dict = {}
|
|
34
|
+
_checkouts_cache: dict = {}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def identity(path) -> dict | None:
|
|
38
|
+
"""`{"root", "git", "key", "checkout"}` for a checkout, a run dir, or a file inside a run dir.
|
|
39
|
+
|
|
40
|
+
None when `path` is neither an existing directory nor a run dir with a `repo` file.
|
|
41
|
+
"""
|
|
42
|
+
key = _cache_key(path)
|
|
43
|
+
if key is not None and key in _identity_cache:
|
|
44
|
+
return _copy(_identity_cache[key])
|
|
45
|
+
try:
|
|
46
|
+
result = _identity_uncached(path)
|
|
47
|
+
except Exception: # noqa: BLE001 -- a missing path or a git failure is unknown, not an error
|
|
48
|
+
result = _directory_fallback(path)
|
|
49
|
+
if key is not None:
|
|
50
|
+
_identity_cache[key] = result
|
|
51
|
+
return _copy(result)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def checkouts(ident) -> list[str]:
|
|
55
|
+
"""Every checkout of this repository forge has seen, root first, then sorted.
|
|
56
|
+
|
|
57
|
+
The root, the `checkout` and `root` of every locations entry for the same git dir
|
|
58
|
+
or the same root (gone entries included), and the checkout named by the `repo` file
|
|
59
|
+
of every run dir in those checkouts' registry files. Existing or not. Deduplicated
|
|
60
|
+
by realpath.
|
|
61
|
+
"""
|
|
62
|
+
try:
|
|
63
|
+
if not isinstance(ident, dict) or not isinstance(ident.get('root'), str) or not ident['root']:
|
|
64
|
+
return []
|
|
65
|
+
root = ident['root']
|
|
66
|
+
git = ident.get('git') if isinstance(ident.get('git'), str) else None
|
|
67
|
+
cache_key = (_safe_real(root), git)
|
|
68
|
+
if cache_key in _checkouts_cache:
|
|
69
|
+
return list(_checkouts_cache[cache_key])
|
|
70
|
+
result = _checkouts_uncached(root, git)
|
|
71
|
+
_checkouts_cache[cache_key] = result
|
|
72
|
+
return list(result)
|
|
73
|
+
except Exception: # noqa: BLE001 -- an unreadable locations or registry file is unknown
|
|
74
|
+
return []
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def run_dirs(ident) -> list[str]:
|
|
78
|
+
"""Run dirs registered under any checkout of `ident`, existing directories, newest first."""
|
|
79
|
+
try:
|
|
80
|
+
found: dict[str, str] = {}
|
|
81
|
+
for checkout in checkouts(ident):
|
|
82
|
+
for line in _registry_lines(checkout):
|
|
83
|
+
if not os.path.isdir(line):
|
|
84
|
+
continue
|
|
85
|
+
real = _safe_real(line)
|
|
86
|
+
if real not in found and os.path.isdir(real):
|
|
87
|
+
found[real] = real
|
|
88
|
+
paths = list(found)
|
|
89
|
+
paths.sort(key=lambda item: (-_mtime(item), item))
|
|
90
|
+
return paths
|
|
91
|
+
except Exception: # noqa: BLE001 -- a missing registry is an empty list
|
|
92
|
+
return []
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def github_slug(ident) -> str | None:
|
|
96
|
+
"""`owner/repo` from `origin` of the first existing checkout, or None when none answers."""
|
|
97
|
+
try:
|
|
98
|
+
candidates = checkouts(ident)
|
|
99
|
+
except Exception: # noqa: BLE001
|
|
100
|
+
return None
|
|
101
|
+
for checkout in candidates:
|
|
102
|
+
try:
|
|
103
|
+
exists = bool(checkout) and os.path.isdir(checkout)
|
|
104
|
+
except OSError:
|
|
105
|
+
continue
|
|
106
|
+
if not exists:
|
|
107
|
+
continue
|
|
108
|
+
url = _origin(checkout)
|
|
109
|
+
if not url:
|
|
110
|
+
return None
|
|
111
|
+
match = _ORIGIN_SLUG.search(url.strip())
|
|
112
|
+
return f'{match.group(1)}/{match.group(2)}' if match else None
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _identity_uncached(path) -> dict | None:
|
|
117
|
+
text = os.fspath(path)
|
|
118
|
+
found = _find_run(text)
|
|
119
|
+
if found is not None:
|
|
120
|
+
run_dir, checkout = found
|
|
121
|
+
if os.path.isdir(checkout):
|
|
122
|
+
return _live(checkout)
|
|
123
|
+
return _gone(run_dir, checkout)
|
|
124
|
+
if os.path.isdir(text):
|
|
125
|
+
return _live(text)
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _directory_fallback(path) -> dict | None:
|
|
130
|
+
try:
|
|
131
|
+
text = os.fspath(path)
|
|
132
|
+
if os.path.isdir(text):
|
|
133
|
+
return _live(text)
|
|
134
|
+
except Exception: # noqa: BLE001
|
|
135
|
+
return None
|
|
136
|
+
return None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _find_run(path: str) -> tuple[str, str] | None:
|
|
140
|
+
"""`(run dir, checkout path)` when `path` is a run dir, or a file at most three levels inside one."""
|
|
141
|
+
if os.path.isdir(path):
|
|
142
|
+
line = _first_line(os.path.join(path, 'repo'))
|
|
143
|
+
return (path, line) if line else None
|
|
144
|
+
current = os.path.dirname(os.path.abspath(path))
|
|
145
|
+
for _ in range(_RUN_DIR_WALK):
|
|
146
|
+
line = _first_line(os.path.join(current, 'repo'))
|
|
147
|
+
if line:
|
|
148
|
+
return current, line
|
|
149
|
+
parent = os.path.dirname(current)
|
|
150
|
+
if parent == current:
|
|
151
|
+
break
|
|
152
|
+
current = parent
|
|
153
|
+
return None
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _live(checkout: str) -> dict:
|
|
157
|
+
git, root = forge_locations.repository(checkout)
|
|
158
|
+
checkout_real = _safe_real(checkout)
|
|
159
|
+
if not root:
|
|
160
|
+
root = checkout_real
|
|
161
|
+
return {'root': root, 'git': git, 'key': _key(root), 'checkout': checkout_real}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _gone(run_dir: str, checkout: str) -> dict:
|
|
165
|
+
# The checkout is gone, so git cannot be asked. repo.identity keeps the main
|
|
166
|
+
# working tree; without it the path recorded in `repo` is all forge still has.
|
|
167
|
+
root = _recorded_root(run_dir) or checkout
|
|
168
|
+
return {'root': root, 'git': None, 'key': _key(root), 'checkout': None}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _checkouts_uncached(root: str, git: str | None) -> list[str]:
|
|
172
|
+
paths = [root]
|
|
173
|
+
for entry in forge_locations.entries(present=False):
|
|
174
|
+
if _matches(entry, git, root):
|
|
175
|
+
for name in ('checkout', 'root'):
|
|
176
|
+
value = entry.get(name)
|
|
177
|
+
if isinstance(value, str) and value:
|
|
178
|
+
paths.append(value)
|
|
179
|
+
# One pass over the checkouts already collected. A checkout that shows up only
|
|
180
|
+
# as a run's `repo` path is not itself scanned for further runs.
|
|
181
|
+
for checkout in list(paths):
|
|
182
|
+
for run_dir in _registry_lines(checkout):
|
|
183
|
+
recorded = _first_line(os.path.join(run_dir, 'repo'))
|
|
184
|
+
if recorded:
|
|
185
|
+
paths.append(recorded)
|
|
186
|
+
return _ordered(root, paths)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _matches(entry: dict, git: str | None, root: str) -> bool:
|
|
190
|
+
entry_root = entry.get('root')
|
|
191
|
+
if isinstance(entry_root, str) and _same_path(entry_root, root):
|
|
192
|
+
return True
|
|
193
|
+
entry_git = entry.get('git')
|
|
194
|
+
return git is not None and isinstance(entry_git, str) and _same_path(entry_git, git)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _ordered(root: str, paths: list[str]) -> list[str]:
|
|
198
|
+
seen = {_safe_real(root)}
|
|
199
|
+
extras = []
|
|
200
|
+
for path in paths:
|
|
201
|
+
if not isinstance(path, str) or not path:
|
|
202
|
+
continue
|
|
203
|
+
real = _safe_real(path)
|
|
204
|
+
if real in seen:
|
|
205
|
+
continue
|
|
206
|
+
seen.add(real)
|
|
207
|
+
extras.append(real)
|
|
208
|
+
extras.sort()
|
|
209
|
+
return [root, *extras]
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _recorded_root(run_dir: str) -> str | None:
|
|
213
|
+
data = _read_bytes(os.path.join(run_dir, 'repo.identity'), _REPO_READ_MAX)
|
|
214
|
+
if not data:
|
|
215
|
+
return None
|
|
216
|
+
try:
|
|
217
|
+
parsed = json.loads(data.decode('utf-8', 'replace'))
|
|
218
|
+
except ValueError:
|
|
219
|
+
return None
|
|
220
|
+
if not isinstance(parsed, dict):
|
|
221
|
+
return None
|
|
222
|
+
recorded = parsed.get('root')
|
|
223
|
+
if not isinstance(recorded, str):
|
|
224
|
+
return None
|
|
225
|
+
return recorded or None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _registry_lines(checkout: str) -> list[str]:
|
|
229
|
+
try:
|
|
230
|
+
raw = _read_bytes(forge_registry.runs_registry(checkout), _REGISTRY_READ_MAX)
|
|
231
|
+
except (OSError, ValueError, RuntimeError, TypeError):
|
|
232
|
+
return []
|
|
233
|
+
if not raw:
|
|
234
|
+
return []
|
|
235
|
+
lines = []
|
|
236
|
+
for line in raw.decode('utf-8', 'replace').splitlines():
|
|
237
|
+
line = line.strip()
|
|
238
|
+
if line and not line.startswith('#'):
|
|
239
|
+
lines.append(line)
|
|
240
|
+
return lines
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _first_line(path: str) -> str | None:
|
|
244
|
+
data = _read_bytes(path, _REPO_READ_MAX)
|
|
245
|
+
if not data:
|
|
246
|
+
return None
|
|
247
|
+
parts = data.splitlines()
|
|
248
|
+
if not parts:
|
|
249
|
+
return None
|
|
250
|
+
line = parts[0].decode('utf-8', 'replace').strip()
|
|
251
|
+
return line or None
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _read_bytes(path, limit: int) -> bytes | None:
|
|
255
|
+
"""The start of a regular file. A FIFO, a directory or a missing path is unknown, and never blocks."""
|
|
256
|
+
try:
|
|
257
|
+
fd = os.open(os.fspath(path), os.O_RDONLY | os.O_NONBLOCK)
|
|
258
|
+
except OSError:
|
|
259
|
+
return None
|
|
260
|
+
try:
|
|
261
|
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
|
262
|
+
return None
|
|
263
|
+
chunks = []
|
|
264
|
+
left = limit
|
|
265
|
+
while left > 0:
|
|
266
|
+
try:
|
|
267
|
+
block = os.read(fd, left)
|
|
268
|
+
except OSError:
|
|
269
|
+
return None
|
|
270
|
+
if not block:
|
|
271
|
+
break
|
|
272
|
+
chunks.append(block)
|
|
273
|
+
left -= len(block)
|
|
274
|
+
return b''.join(chunks)
|
|
275
|
+
finally:
|
|
276
|
+
os.close(fd)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _origin(checkout: str) -> str | None:
|
|
280
|
+
try:
|
|
281
|
+
env = {k: v for k, v in os.environ.items()
|
|
282
|
+
if not k.startswith('GIT_') or k in ('GIT_CONFIG_GLOBAL', 'GIT_CONFIG_NOSYSTEM')}
|
|
283
|
+
done = subprocess.run(
|
|
284
|
+
['git', '--no-optional-locks', '-C', os.fspath(checkout), 'remote', 'get-url', 'origin'],
|
|
285
|
+
capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=_GIT_TIMEOUT,
|
|
286
|
+
errors='replace', env=env)
|
|
287
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
288
|
+
return None
|
|
289
|
+
if done.returncode != 0:
|
|
290
|
+
return None
|
|
291
|
+
return done.stdout.strip() or None
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _key(root: str) -> str:
|
|
295
|
+
try:
|
|
296
|
+
return forge_registry.repo_key(root)
|
|
297
|
+
except (OSError, ValueError, RuntimeError, UnicodeError):
|
|
298
|
+
return hashlib.sha256(_safe_real(root).encode('utf-8', 'replace')).hexdigest()[:16]
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _cache_key(path) -> str | None:
|
|
302
|
+
try:
|
|
303
|
+
return os.path.realpath(os.fspath(path))
|
|
304
|
+
except (OSError, ValueError, TypeError):
|
|
305
|
+
return None
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _safe_real(path: str) -> str:
|
|
309
|
+
try:
|
|
310
|
+
return os.path.realpath(path)
|
|
311
|
+
except (OSError, ValueError, TypeError):
|
|
312
|
+
return path
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _same_path(left: str, right: str) -> bool:
|
|
316
|
+
return left == right or _safe_real(left) == _safe_real(right)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _mtime(path: str) -> float:
|
|
320
|
+
try:
|
|
321
|
+
return os.stat(path).st_mtime
|
|
322
|
+
except OSError:
|
|
323
|
+
return 0.0
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _copy(result):
|
|
327
|
+
return None if result is None else dict(result)
|
|
@@ -12,7 +12,8 @@ so the state shown is the one forge's bash decided, never a second implementatio
|
|
|
12
12
|
muted every row of it was marked not injectable (Jev's curation)
|
|
13
13
|
|
|
14
14
|
A learning is a (category, key) group, as rebuild groups the ledger: `count` is the number of distinct runs
|
|
15
|
-
it appeared in, `text` the latest wording. `
|
|
15
|
+
it appeared in, `text` the latest wording. `manual` is true when a person wrote any row of it (role
|
|
16
|
+
`person`); the field is absent otherwise. `memory` is the repo's current .forge/memory.md by section, with
|
|
16
17
|
the roles each section reaches; `rebuilt_differs` says the current file is not what a rebuild makes now (an
|
|
17
18
|
older forge wrote it, or a `prune` asked Jev to drop facts). Stdlib only.
|
|
18
19
|
"""
|
|
@@ -119,8 +120,11 @@ def classify(groups, rebuilt, drops):
|
|
|
119
120
|
else:
|
|
120
121
|
state = 'dropped' # not reached by today's rebuild; kept honest if it changes
|
|
121
122
|
rows = g['rows']
|
|
122
|
-
|
|
123
|
-
|
|
123
|
+
item = dict(category=cat, key=key, text=text, count=count, state=state,
|
|
124
|
+
first=min(r['ts'] for r in rows), last=max(r['ts'] for r in rows), rows=rows)
|
|
125
|
+
if any(r['role'] == 'person' for r in rows):
|
|
126
|
+
item['manual'] = True
|
|
127
|
+
out.append(item)
|
|
124
128
|
out.sort(key=lambda r: (r['last'], r['category'], r['key']), reverse=True)
|
|
125
129
|
return out
|
|
126
130
|
|