@giamme/forge 0.19.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 +16 -0
- package/SKILL.md +3 -0
- package/VERSION +1 -1
- package/docs/commands.md +137 -5
- package/docs/forge-ui.md +70 -19
- package/forge +8 -2
- package/package.json +1 -1
- package/references/decompose.md +20 -8
- package/references/memory.md +30 -5
- package/scripts/forge-findings.py +675 -0
- package/scripts/forge-issues.py +228 -97
- package/scripts/forge-memory.sh +471 -19
- package/scripts/forge-parallel.sh +6 -4
- package/scripts/forge-schedule.py +63 -7
- package/scripts/forge-sweep.py +199 -44
- 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_identity.py +327 -0
- package/scripts/forge_memory_list.py +7 -3
- package/scripts/forge_side/__init__.py +217 -32
- package/ui/docs/api.md +130 -12
- package/ui/forge_ui/control.py +658 -5
- package/ui/forge_ui/export.py +1 -1
- package/ui/forge_ui/projects.py +209 -22
- package/ui/forge_ui/static/findingsactions.js +201 -0
- package/ui/forge_ui/static/index.html +2 -0
- package/ui/forge_ui/static/projectsview.js +600 -45
- package/ui/forge_ui/static/style.css +59 -0
- package/ui/forge_ui/static/triageview.js +423 -0
|
@@ -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
|
|
|
@@ -20,6 +20,12 @@ Precedence for each switch, first match wins:
|
|
|
20
20
|
A `brief-change` dispatch (a wave-scoped proposal, #136) follows the brief settings: the same
|
|
21
21
|
level, `FORGE_BRIEF=off`, model, `never-send` floor and its own cap.
|
|
22
22
|
|
|
23
|
+
A `triage` dispatch reads one repository's open findings from outside any plan. It is a
|
|
24
|
+
kind, but it has no plan dir: `allowed` and `run` raise ValueError (`use the triage
|
|
25
|
+
functions`). `triage_home` and `allocate_triage` place it at
|
|
26
|
+
`${XDG_STATE_HOME:-~/.local/state}/forge/triage/<key>/<n>/`. An empty or relative
|
|
27
|
+
`XDG_STATE_HOME` counts as unset. `triage_allowed` and `run_triage` are the entry points.
|
|
28
|
+
|
|
23
29
|
`allowed` refuses with `env`, `off`, `never-send` (the plan repo's privacy floor),
|
|
24
30
|
`no-model` or `cap`, in that order. For a summary, `tasks/<task>/summaries` (`on` or
|
|
25
31
|
`off`) overrides the plan's mode and nothing else. The cap is
|
|
@@ -33,7 +39,9 @@ from __future__ import annotations
|
|
|
33
39
|
import fcntl
|
|
34
40
|
import os
|
|
35
41
|
from pathlib import Path
|
|
42
|
+
import re
|
|
36
43
|
import signal
|
|
44
|
+
import stat
|
|
37
45
|
import subprocess
|
|
38
46
|
import sys
|
|
39
47
|
|
|
@@ -43,9 +51,12 @@ from forge_decide.providers import privacy_floor
|
|
|
43
51
|
SCRIPTS = Path(__file__).resolve().parent.parent
|
|
44
52
|
DISPATCH = SCRIPTS / 'forge-dispatch.sh'
|
|
45
53
|
|
|
46
|
-
KINDS = ('brief', 'brief-change', 'summary')
|
|
54
|
+
KINDS = ('brief', 'brief-change', 'summary', 'triage')
|
|
47
55
|
# Kinds that follow the brief settings: `FORGE_BRIEF=off`, the plan's brief level and brief model.
|
|
48
56
|
BRIEF_KINDS = ('brief', 'brief-change')
|
|
57
|
+
# Numbered triage dispatch dirs one repository key may keep. A non-numeric sibling is not one.
|
|
58
|
+
_TRIAGE_CAP = 200
|
|
59
|
+
_TRIAGE_KEY = re.compile(r'^[0-9a-f]{16}$')
|
|
49
60
|
ON_OFF = ('off', 'on')
|
|
50
61
|
BRIEF_LEVELS = ('off', 'advisory', 'gated', 'strict')
|
|
51
62
|
BRIEF_SCOPES = ('task', 'wave', 'plan')
|
|
@@ -65,6 +76,10 @@ class _Capped(Exception):
|
|
|
65
76
|
"""The per-kind dispatch cap is already full. Not an error for the caller."""
|
|
66
77
|
|
|
67
78
|
|
|
79
|
+
class TriageCapped(Exception):
|
|
80
|
+
"""This repository key already holds 200 triage dispatch dirs."""
|
|
81
|
+
|
|
82
|
+
|
|
68
83
|
def _read(path: Path) -> str | None:
|
|
69
84
|
try:
|
|
70
85
|
text = Path(path).read_text(encoding='utf-8')
|
|
@@ -287,11 +302,105 @@ def _allocate(plan: Path, kind: str, task: str) -> Path:
|
|
|
287
302
|
os.close(fd)
|
|
288
303
|
|
|
289
304
|
|
|
305
|
+
def _state_root() -> Path:
|
|
306
|
+
"""Absolute `XDG_STATE_HOME`, or `~/.local/state`. Empty or relative counts as unset.
|
|
307
|
+
|
|
308
|
+
A relative state home would name a directory below the current one, usually the
|
|
309
|
+
repository. The same rule as forge-issues' findings store.
|
|
310
|
+
"""
|
|
311
|
+
for candidate in (os.environ.get('XDG_STATE_HOME') or '', '~/.local/state'):
|
|
312
|
+
try:
|
|
313
|
+
base = Path(candidate).expanduser() if candidate else None
|
|
314
|
+
except RuntimeError: # no home directory to expand "~" against
|
|
315
|
+
base = None
|
|
316
|
+
if base is not None and base.is_absolute():
|
|
317
|
+
return base
|
|
318
|
+
raise ValueError('cannot place the triage home: no home directory and no absolute XDG_STATE_HOME')
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def triage_home(key) -> Path:
|
|
322
|
+
"""`${XDG_STATE_HOME:-~/.local/state}/forge/triage/<key>`.
|
|
323
|
+
|
|
324
|
+
`key` is 16 lowercase hex characters, the repository identity computed elsewhere.
|
|
325
|
+
This does not create the directory and does not import that computation.
|
|
326
|
+
"""
|
|
327
|
+
if not isinstance(key, str) or _TRIAGE_KEY.fullmatch(key) is None:
|
|
328
|
+
raise ValueError('triage key must be 16 lowercase hex chars, not %r' % (key,))
|
|
329
|
+
return _state_root() / 'forge' / 'triage' / key
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _refuse_symlink(path: Path, what: str) -> None:
|
|
333
|
+
"""Raise ValueError when `path` is a symlink. A path that is not there yet is fine."""
|
|
334
|
+
try:
|
|
335
|
+
info = path.lstat()
|
|
336
|
+
except FileNotFoundError:
|
|
337
|
+
return
|
|
338
|
+
except OSError as exc:
|
|
339
|
+
raise ValueError('%s: %s' % (what, exc.strerror or exc)) from exc
|
|
340
|
+
if stat.S_ISLNK(info.st_mode):
|
|
341
|
+
raise ValueError('%s must be a real directory, not a symlink' % what)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _triage_slots(home: Path) -> tuple[int, int]:
|
|
345
|
+
"""`(highest numeric n, how many real numeric dirs)`.
|
|
346
|
+
|
|
347
|
+
A sibling whose name is not numeric takes no number, as `_next_n` does, and is not
|
|
348
|
+
a dispatch dir. A symlinked numeric directory is refused rather than followed.
|
|
349
|
+
"""
|
|
350
|
+
highest = 0
|
|
351
|
+
count = 0
|
|
352
|
+
try:
|
|
353
|
+
children = list(home.iterdir())
|
|
354
|
+
except OSError:
|
|
355
|
+
return 0, 0
|
|
356
|
+
for child in children:
|
|
357
|
+
if not child.name.isdigit():
|
|
358
|
+
continue
|
|
359
|
+
try:
|
|
360
|
+
info = child.lstat()
|
|
361
|
+
except OSError:
|
|
362
|
+
continue
|
|
363
|
+
if stat.S_ISLNK(info.st_mode):
|
|
364
|
+
raise ValueError('triage dispatch dir must be a real directory, not a symlink')
|
|
365
|
+
if not stat.S_ISDIR(info.st_mode):
|
|
366
|
+
continue
|
|
367
|
+
highest = max(highest, int(child.name))
|
|
368
|
+
count += 1
|
|
369
|
+
return highest, count
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def allocate_triage(key) -> Path:
|
|
373
|
+
"""Create the next `<triage_home(key)>/<n>/` under an flock on `<home>/.lock`.
|
|
374
|
+
|
|
375
|
+
n starts at 1. A non-numeric sibling takes no number and does not count toward the
|
|
376
|
+
cap of 200 dispatch dirs. Past the cap this raises `TriageCapped`. A symlinked home
|
|
377
|
+
or numeric directory raises ValueError, and nothing is written through the link.
|
|
378
|
+
"""
|
|
379
|
+
home = triage_home(key)
|
|
380
|
+
_refuse_symlink(home, 'triage home')
|
|
381
|
+
fd = _lock(home)
|
|
382
|
+
try:
|
|
383
|
+
_refuse_symlink(home, 'triage home')
|
|
384
|
+
highest, count = _triage_slots(home)
|
|
385
|
+
if count >= _TRIAGE_CAP:
|
|
386
|
+
raise TriageCapped('200 triage dispatch dirs already exist for this repository')
|
|
387
|
+
dest = home / str(highest + 1)
|
|
388
|
+
_refuse_symlink(dest, 'triage dispatch dir')
|
|
389
|
+
dest.mkdir()
|
|
390
|
+
_refuse_symlink(dest, 'triage dispatch dir')
|
|
391
|
+
return dest
|
|
392
|
+
finally:
|
|
393
|
+
os.close(fd)
|
|
394
|
+
|
|
395
|
+
|
|
290
396
|
def allowed(kind, plan, task=None):
|
|
291
397
|
"""`(ok, reason)` for a `brief`, `brief-change` or `summary` dispatch. `reason` is None when it may run.
|
|
292
398
|
|
|
293
399
|
Reasons, in the order they are decided: `env`, `off`, `never-send`, `no-model`, `cap`.
|
|
400
|
+
`triage` is not a plan dispatch: it raises ValueError (`use the triage functions`).
|
|
294
401
|
"""
|
|
402
|
+
if kind == 'triage':
|
|
403
|
+
raise ValueError('use the triage functions')
|
|
295
404
|
if kind not in KINDS:
|
|
296
405
|
raise ValueError('kind must be brief, brief-change or summary, not %r' % (kind,))
|
|
297
406
|
plan = Path(plan)
|
|
@@ -318,6 +427,22 @@ def allowed(kind, plan, task=None):
|
|
|
318
427
|
return True, None
|
|
319
428
|
|
|
320
429
|
|
|
430
|
+
def triage_allowed(repo, spec):
|
|
431
|
+
"""`(ok, reason)` for a triage dispatch. `reason` is None when it may run.
|
|
432
|
+
|
|
433
|
+
Decided in order. No settings file is read: the caller names the spec each time.
|
|
434
|
+
`env` when `FORGE_TRIAGE` is off, `never-send` when `privacy_floor(repo)` says so,
|
|
435
|
+
`no-model` when `spec` is empty.
|
|
436
|
+
"""
|
|
437
|
+
if _env_off('FORGE_TRIAGE'):
|
|
438
|
+
return False, 'env'
|
|
439
|
+
if privacy_floor(repo):
|
|
440
|
+
return False, 'never-send'
|
|
441
|
+
if spec is None or (isinstance(spec, str) and not spec.strip()):
|
|
442
|
+
return False, 'no-model'
|
|
443
|
+
return True, None
|
|
444
|
+
|
|
445
|
+
|
|
321
446
|
def _last(dest: Path):
|
|
322
447
|
path = dest / 'side.last'
|
|
323
448
|
try:
|
|
@@ -399,6 +524,52 @@ def _stop_dispatch(proc: subprocess.Popen) -> None:
|
|
|
399
524
|
pass
|
|
400
525
|
|
|
401
526
|
|
|
527
|
+
def _dispatch_and_wait(dest: Path, repo, prompt, spec, limit: int, event_dir, task, kind) -> dict:
|
|
528
|
+
"""Write `prompt.txt` and run `forge-dispatch.sh side` in its own session.
|
|
529
|
+
|
|
530
|
+
Shared by `run` and `run_triage`. `event_dir` is the run dir on the `side_dispatch`
|
|
531
|
+
event: the plan, or the triage dest. Returns `{ok, last, dir, reason}` and does not
|
|
532
|
+
raise. A dispatch that outlives `limit` plus `_DISPATCH_GRACE_S` is stopped with
|
|
533
|
+
its session, including a preflight that has not exited.
|
|
534
|
+
"""
|
|
535
|
+
try:
|
|
536
|
+
text = prompt if isinstance(prompt, str) else ('' if prompt is None else str(prompt))
|
|
537
|
+
(dest / 'prompt.txt').write_text(text, encoding='utf-8')
|
|
538
|
+
except (OSError, UnicodeError):
|
|
539
|
+
return _finish(event_dir, task, kind, spec, False, None, dest, 'error')
|
|
540
|
+
if not repo:
|
|
541
|
+
return _finish(event_dir, task, kind, spec, False, None, dest, 'error')
|
|
542
|
+
argv = ['/bin/bash', str(DISPATCH), 'side', '' if spec is None else str(spec),
|
|
543
|
+
'--repo', str(repo), '--run-dir', str(dest), '--prompt-file', str(dest / 'prompt.txt'),
|
|
544
|
+
'--timeout', str(max(0, limit))]
|
|
545
|
+
# Own session, so a timeout can stop the preflight with the shell.
|
|
546
|
+
try:
|
|
547
|
+
proc = subprocess.Popen(
|
|
548
|
+
argv, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
549
|
+
start_new_session=True, close_fds=True)
|
|
550
|
+
except (OSError, subprocess.SubprocessError):
|
|
551
|
+
return _finish(event_dir, task, kind, spec, False, _last(dest), dest, 'error')
|
|
552
|
+
wait = None if limit <= 0 else limit + _DISPATCH_GRACE_S
|
|
553
|
+
try:
|
|
554
|
+
proc.wait(timeout=wait)
|
|
555
|
+
except subprocess.TimeoutExpired:
|
|
556
|
+
_stop_dispatch(proc)
|
|
557
|
+
return _finish(event_dir, task, kind, spec, False, _last(dest), dest, 'timeout')
|
|
558
|
+
except (OSError, subprocess.SubprocessError):
|
|
559
|
+
_stop_dispatch(proc)
|
|
560
|
+
return _finish(event_dir, task, kind, spec, False, _last(dest), dest, 'error')
|
|
561
|
+
ok = proc.returncode == 0
|
|
562
|
+
reason = None if ok else ('timeout' if proc.returncode == 7 else 'error')
|
|
563
|
+
return _finish(event_dir, task, kind, spec, ok, _last(dest), dest, reason)
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def _seconds(timeout, default: int) -> int:
|
|
567
|
+
try:
|
|
568
|
+
return int(timeout)
|
|
569
|
+
except (TypeError, ValueError):
|
|
570
|
+
return default
|
|
571
|
+
|
|
572
|
+
|
|
402
573
|
def run(kind, plan, task, prompt, spec, timeout=900) -> dict:
|
|
403
574
|
"""Dispatch once. Returns `{ok, last, dir, reason}` and never raises on a failure.
|
|
404
575
|
|
|
@@ -408,7 +579,10 @@ def run(kind, plan, task, prompt, spec, timeout=900) -> dict:
|
|
|
408
579
|
when this kind is already at its limit, `timeout` when the dispatch times out,
|
|
409
580
|
`missing` when the dispatch script is not there, and `error` otherwise. A timeout
|
|
410
581
|
stops the dispatch's session, including a preflight that has not exited.
|
|
582
|
+
`triage` is not a plan dispatch: it raises ValueError (`use the triage functions`).
|
|
411
583
|
"""
|
|
584
|
+
if kind == 'triage':
|
|
585
|
+
raise ValueError('use the triage functions')
|
|
412
586
|
if kind not in KINDS:
|
|
413
587
|
raise ValueError('kind must be brief, brief-change or summary, not %r' % (kind,))
|
|
414
588
|
plan = Path(plan)
|
|
@@ -416,46 +590,57 @@ def run(kind, plan, task, prompt, spec, timeout=900) -> dict:
|
|
|
416
590
|
return _finish(plan, task, kind, spec, False, None, None, 'error')
|
|
417
591
|
if not DISPATCH.is_file():
|
|
418
592
|
return _finish(plan, task, kind, spec, False, None, None, 'missing')
|
|
419
|
-
try:
|
|
420
|
-
limit = int(timeout)
|
|
421
|
-
except (TypeError, ValueError):
|
|
422
|
-
limit = 900
|
|
423
593
|
try:
|
|
424
594
|
dest = _allocate(plan, kind, task)
|
|
425
595
|
except _Capped:
|
|
426
596
|
return _finish(plan, task, kind, spec, False, None, None, 'cap')
|
|
427
597
|
except OSError:
|
|
428
598
|
return _finish(plan, task, kind, spec, False, None, None, 'error')
|
|
599
|
+
return _dispatch_and_wait(dest, _read(plan / 'repo'), prompt, spec, _seconds(timeout, 900),
|
|
600
|
+
plan, task, kind)
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def _path_or_none(value):
|
|
429
604
|
try:
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
605
|
+
return Path(value)
|
|
606
|
+
except (TypeError, ValueError):
|
|
607
|
+
return None
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _repo_text(repo) -> str:
|
|
611
|
+
if isinstance(repo, Path):
|
|
612
|
+
return str(repo)
|
|
613
|
+
if isinstance(repo, str):
|
|
614
|
+
return repo.strip()
|
|
615
|
+
return '' if repo is None else str(repo).strip()
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
def run_triage(dest, repo, prompt, spec, timeout=3600) -> dict:
|
|
619
|
+
"""Dispatch one triage read into an already allocated `dest`. Never raises.
|
|
620
|
+
|
|
621
|
+
The caller writes `findings.json` there first. `triage_allowed` is checked first
|
|
622
|
+
(`env`, `never-send`, `no-model`) and then nothing is started. Otherwise this is
|
|
623
|
+
the same `side` dispatch as `run`: `prompt.txt`, its own session, the grace past
|
|
624
|
+
the watchdog, and a session stop on timeout. `reason` is one of those, or
|
|
625
|
+
`timeout`, `missing` or `error`. The `side_dispatch` event has kind `triage`,
|
|
626
|
+
task None, and `dest` as its run dir.
|
|
627
|
+
"""
|
|
628
|
+
directory = _path_or_none(dest)
|
|
441
629
|
try:
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
return _finish(
|
|
447
|
-
|
|
630
|
+
ok, reason = triage_allowed(repo, spec)
|
|
631
|
+
except Exception:
|
|
632
|
+
return _finish(directory, None, 'triage', spec, False, None, None, 'error')
|
|
633
|
+
if not ok:
|
|
634
|
+
return _finish(directory, None, 'triage', spec, False, None, None, reason)
|
|
635
|
+
if directory is None:
|
|
636
|
+
return _finish(None, None, 'triage', spec, False, None, None, 'error')
|
|
637
|
+
if not DISPATCH.is_file():
|
|
638
|
+
return _finish(directory, None, 'triage', spec, False, None, None, 'missing')
|
|
448
639
|
try:
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
return _finish(
|
|
453
|
-
except (OSError, subprocess.SubprocessError):
|
|
454
|
-
_stop_dispatch(proc)
|
|
455
|
-
return _finish(plan, task, kind, spec, False, _last(dest), dest, 'error')
|
|
456
|
-
ok = proc.returncode == 0
|
|
457
|
-
reason = None if ok else ('timeout' if proc.returncode == 7 else 'error')
|
|
458
|
-
return _finish(plan, task, kind, spec, ok, _last(dest), dest, reason)
|
|
640
|
+
return _dispatch_and_wait(directory, _repo_text(repo), prompt, spec, _seconds(timeout, 3600),
|
|
641
|
+
directory, None, 'triage')
|
|
642
|
+
except Exception:
|
|
643
|
+
return _finish(directory, None, 'triage', spec, False, None, directory, 'error')
|
|
459
644
|
|
|
460
645
|
|
|
461
646
|
def cap(text, limit) -> str:
|