@giamme/forge 0.19.0 → 0.21.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 +32 -0
- package/README.md +7 -0
- package/SKILL.md +3 -0
- package/VERSION +1 -1
- package/docs/README.md +1 -0
- package/docs/commands.md +137 -5
- package/docs/development.md +1 -1
- 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-config.py +10 -9
- package/scripts/forge-control.py +51 -35
- package/scripts/forge-findings.py +675 -0
- package/scripts/forge-group.py +2 -1
- package/scripts/forge-guard.py +71 -33
- package/scripts/forge-handoff.py +14 -17
- package/scripts/forge-issues.py +233 -99
- package/scripts/forge-memory.sh +471 -19
- package/scripts/forge-parallel.sh +24 -14
- package/scripts/forge-planner.py +28 -2
- package/scripts/forge-pre-review.py +11 -4
- package/scripts/forge-ripwire.py +68 -22
- package/scripts/forge-route.py +10 -3
- package/scripts/forge-runs-compact.py +3 -2
- package/scripts/forge-runs-rm.py +14 -14
- package/scripts/forge-runtime.py +36 -19
- package/scripts/forge-schedule.py +135 -62
- package/scripts/forge-shadow.py +16 -9
- package/scripts/forge-summarize.py +7 -3
- package/scripts/forge-sweep.py +206 -46
- package/scripts/forge-ui.py +8 -13
- package/scripts/forge-verify.py +29 -23
- package/scripts/forge_brief/__init__.py +1 -1
- package/scripts/forge_brief/proposals.py +7 -2
- package/scripts/forge_decide/budget.py +6 -1
- package/scripts/forge_decide/replay.py +6 -1
- package/scripts/forge_findings/__init__.py +17 -0
- package/scripts/forge_findings/apply.py +442 -0
- package/scripts/forge_findings/status.py +43 -0
- package/scripts/forge_findings/store.py +595 -0
- package/scripts/forge_findings/tags.py +53 -0
- package/scripts/forge_findings/triage.py +594 -0
- package/scripts/forge_flock.py +87 -0
- package/scripts/forge_fractal/__init__.py +7 -3
- package/scripts/forge_fractal/cli.py +7 -2
- package/scripts/forge_fractal/execution.py +14 -14
- package/scripts/forge_fractal/invocation.py +3 -2
- package/scripts/forge_fractal/pipeline.py +2 -1
- package/scripts/forge_fractal/selection.py +2 -1
- package/scripts/forge_identity.py +328 -0
- package/scripts/forge_locations.py +14 -4
- package/scripts/forge_memory_list.py +7 -3
- package/scripts/forge_posix.py +108 -0
- package/scripts/forge_proc.py +399 -0
- package/scripts/forge_registry.py +15 -6
- package/scripts/forge_retro/__init__.py +8 -2
- package/scripts/forge_retro/issues.py +2 -1
- package/scripts/forge_side/__init__.py +232 -38
- package/scripts/forge_storage.py +11 -1
- package/ui/docs/api.md +130 -12
- package/ui/forge_ui/control.py +693 -17
- package/ui/forge_ui/export.py +1 -1
- package/ui/forge_ui/projects.py +209 -22
- package/ui/forge_ui/reader.py +18 -17
- package/ui/forge_ui/server.py +10 -1
- 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
package/ui/forge_ui/control.py
CHANGED
|
@@ -6,19 +6,33 @@ this module holds the route table, the body validation, the call and the mapping
|
|
|
6
6
|
exit code to an HTTP answer. server.py does the authentication and hands each authenticated POST
|
|
7
7
|
to `dispatch`. Profile create and edit write a JSON body to the CLI's stdin (`--file -`);
|
|
8
8
|
a brief answer writes the answer text the same way. Approving, rejecting and proposing a brief
|
|
9
|
-
change print text and take no stdin.
|
|
9
|
+
change print text and take no stdin. A finding's draft body and replacement text go through a
|
|
10
|
+
private temp file (`--body-file`, `--text-file`), never argv. Every other call has no stdin.
|
|
10
11
|
"""
|
|
11
12
|
from __future__ import annotations
|
|
12
13
|
|
|
13
14
|
import json
|
|
14
15
|
import os
|
|
15
16
|
import re
|
|
17
|
+
import shutil
|
|
16
18
|
import signal
|
|
17
19
|
import subprocess
|
|
20
|
+
import sys
|
|
21
|
+
import tempfile
|
|
18
22
|
import threading
|
|
19
23
|
import time
|
|
20
24
|
import urllib.parse
|
|
21
25
|
|
|
26
|
+
_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'scripts')
|
|
27
|
+
_inserted = _SCRIPTS not in sys.path
|
|
28
|
+
if _inserted:
|
|
29
|
+
sys.path.insert(0, _SCRIPTS)
|
|
30
|
+
try:
|
|
31
|
+
import forge_proc # noqa: E402
|
|
32
|
+
finally:
|
|
33
|
+
if _inserted and _SCRIPTS in sys.path:
|
|
34
|
+
sys.path.remove(_SCRIPTS)
|
|
35
|
+
|
|
22
36
|
|
|
23
37
|
TIMEOUT_S = 60 # one CLI call; a test sets a shorter one
|
|
24
38
|
TERM_WAIT_S = 5 # between SIGTERM and SIGKILL of a timed-out call's process group
|
|
@@ -49,11 +63,18 @@ MAX_FPS = 25
|
|
|
49
63
|
MAX_LABELS = 5
|
|
50
64
|
MAX_LABEL = 50
|
|
51
65
|
MAX_REASON = 500
|
|
66
|
+
MAX_FINDING_FPS = 200 # fingerprints in one finding-record write
|
|
67
|
+
MAX_NOTE = 2000
|
|
68
|
+
MAX_EDIT_TEXT = 4000
|
|
69
|
+
MAX_DRAFT_TITLE = 200
|
|
70
|
+
MAX_DRAFT_BODY = 20000
|
|
71
|
+
MAX_TAGS = 8
|
|
52
72
|
MAX_CONFIG_VALUE = 4096
|
|
53
73
|
MAX_DECIDE_VALUE = 256
|
|
54
74
|
# The profile object written to `forge config profile … --file -`. The HTTP body is already capped
|
|
55
75
|
# at 64 KiB by the server; this caps the stdin text itself, which a re-encode can make larger.
|
|
56
76
|
MAX_PROFILE_BODY = 64 * 1024
|
|
77
|
+
MAX_PROFILE_DEPTH = 64 # a profile is a few levels deep
|
|
57
78
|
# A brief answer, in characters. The CLI then keeps the leading 4 KiB of what remains after it
|
|
58
79
|
# strips control characters; this bound is the one the route enforces before that call.
|
|
59
80
|
MAX_ANSWER = 4096
|
|
@@ -65,6 +86,9 @@ _PROFILE_NAME = re.compile(r'^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$')
|
|
|
65
86
|
_PROFILE_KEY = re.compile(r'^(routing|policy)\.[a-z_.]+$')
|
|
66
87
|
_PROFILE_ACTIONS = ('create', 'edit', 'set', 'unset', 'rm', 'use')
|
|
67
88
|
FP_RE = re.compile(r'[0-9a-f]{12}')
|
|
89
|
+
_COMMIT_RE = re.compile(r'[0-9a-f]{7,40}')
|
|
90
|
+
_TAG_RE = re.compile(r'[a-z][a-z0-9-]{0,23}')
|
|
91
|
+
_FINDING_SEVERITIES = ('P0', 'P1', 'P2', 'P3')
|
|
68
92
|
# Mirrored from forge_decide.GATES and MODES. The ui tests do not put scripts/ on the path, so this
|
|
69
93
|
# module does not import forge_decide; ConfigTests.test_decide_names_match_forge_decide keeps them equal.
|
|
70
94
|
DECIDE_GATES = ('drift', 'forward', 'prompt', 'memory-curate', 'memory-slice', 'memory-stale',
|
|
@@ -148,6 +172,9 @@ class CliResult:
|
|
|
148
172
|
|
|
149
173
|
|
|
150
174
|
def _signal_group(pgid, sig):
|
|
175
|
+
if forge_proc.IS_WINDOWS:
|
|
176
|
+
forge_proc.kill_tree(pgid, force=(sig == forge_proc.SIGKILL))
|
|
177
|
+
return
|
|
151
178
|
try:
|
|
152
179
|
os.killpg(pgid, sig)
|
|
153
180
|
except (ProcessLookupError, PermissionError):
|
|
@@ -168,7 +195,7 @@ def run_cli(argv, timeout, stdin=None):
|
|
|
168
195
|
try:
|
|
169
196
|
proc = subprocess.Popen(argv, stdin=subprocess.PIPE if stdin is not None else subprocess.DEVNULL,
|
|
170
197
|
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
171
|
-
|
|
198
|
+
close_fds=True, env=env, **forge_proc.popen_group_kwargs())
|
|
172
199
|
except OSError as exc:
|
|
173
200
|
return CliResult(error=f'cannot run the forge CLI: {exc.strerror or exc}')
|
|
174
201
|
try:
|
|
@@ -180,14 +207,14 @@ def run_cli(argv, timeout, stdin=None):
|
|
|
180
207
|
while proc.poll() is None and time.monotonic() < deadline:
|
|
181
208
|
time.sleep(0.05)
|
|
182
209
|
# Children that outlive the leader (or ignore SIGTERM) die here; the leader is reaped by wait().
|
|
183
|
-
_signal_group(pgid,
|
|
210
|
+
_signal_group(pgid, forge_proc.SIGKILL)
|
|
184
211
|
proc.wait()
|
|
185
212
|
for pipe in (proc.stdin, proc.stdout, proc.stderr):
|
|
186
213
|
if pipe:
|
|
187
214
|
pipe.close()
|
|
188
215
|
return CliResult(timed_out=True)
|
|
189
216
|
except BaseException:
|
|
190
|
-
_signal_group(proc.pid,
|
|
217
|
+
_signal_group(proc.pid, forge_proc.SIGKILL)
|
|
191
218
|
proc.wait()
|
|
192
219
|
raise
|
|
193
220
|
return CliResult(code=proc.returncode, stdout=out.decode('utf-8', 'replace'), stderr=err.decode('utf-8', 'replace'))
|
|
@@ -826,10 +853,26 @@ def _profile_value(value):
|
|
|
826
853
|
return value
|
|
827
854
|
|
|
828
855
|
|
|
856
|
+
def _nested_deeper_than(value, limit):
|
|
857
|
+
"""Whether lists and objects nest more than `limit` levels, checked without recursion."""
|
|
858
|
+
stack = [(value, 1)]
|
|
859
|
+
while stack:
|
|
860
|
+
item, depth = stack.pop()
|
|
861
|
+
if isinstance(item, (dict, list)):
|
|
862
|
+
if depth > limit:
|
|
863
|
+
return True
|
|
864
|
+
stack.extend((child, depth + 1) for child in (item.values() if isinstance(item, dict) else item))
|
|
865
|
+
return False
|
|
866
|
+
|
|
867
|
+
|
|
829
868
|
def _profile_stdin(value):
|
|
830
869
|
"""The bytes `--file -` reads. A re-encode can be larger than the HTTP body, so it is capped on its own."""
|
|
831
870
|
if not isinstance(value, dict):
|
|
832
871
|
raise BadBody('body must be a JSON object')
|
|
872
|
+
# Up to Python 3.11 json.dumps raises RecursionError on a deep enough value; from 3.12 it
|
|
873
|
+
# goes much deeper, so the limit is explicit.
|
|
874
|
+
if _nested_deeper_than(value, MAX_PROFILE_DEPTH):
|
|
875
|
+
raise BadBody(f'body is nested more than {MAX_PROFILE_DEPTH} levels deep')
|
|
833
876
|
try:
|
|
834
877
|
raw = json.dumps(value, allow_nan=False).encode('utf-8')
|
|
835
878
|
except (TypeError, ValueError, RecursionError):
|
|
@@ -1001,11 +1044,18 @@ def _project_findings(ctx):
|
|
|
1001
1044
|
refresh = _bit(_query_params(ctx.query, ('refresh',)), 'refresh')
|
|
1002
1045
|
except BadBody as exc:
|
|
1003
1046
|
return _invalid(str(exc))
|
|
1004
|
-
#
|
|
1047
|
+
# The listing is read online (GitHub says which issues are closed), for at most 60 s; projects.py asks again
|
|
1048
|
+
# with --offline when that fails.
|
|
1049
|
+
def listing(path, online=True):
|
|
1050
|
+
args = ('issues', path, '--json', '--all-runs', '--include-plausible', '--include-dismissed')
|
|
1051
|
+
if online:
|
|
1052
|
+
status, body = ctx.call(*args, limit=projects.ONLINE_S)
|
|
1053
|
+
return body if status == 200 else None
|
|
1054
|
+
return _project_call(ctx, *args[:3], '--offline', *args[3:])
|
|
1055
|
+
|
|
1005
1056
|
found = projects.screen(ctx.server).findings(
|
|
1006
|
-
ctx.server.catalog, ctx.key, lambda: _project_call(ctx, 'dataset', 'history', '--json'),
|
|
1007
|
-
|
|
1008
|
-
'--include-dismissed'), refresh=refresh)
|
|
1057
|
+
ctx.server.catalog, ctx.key, lambda: _project_call(ctx, 'dataset', 'history', '--json'), listing,
|
|
1058
|
+
refresh=refresh)
|
|
1009
1059
|
return (404, {'error': 'not found'}) if found is None else (200, found)
|
|
1010
1060
|
|
|
1011
1061
|
|
|
@@ -1096,6 +1146,16 @@ def invalidate_memories(server):
|
|
|
1096
1146
|
del screen.cli[key]
|
|
1097
1147
|
|
|
1098
1148
|
|
|
1149
|
+
def invalidate_findings(server):
|
|
1150
|
+
"""The next GET of a project's findings reads `forge issues` again, and re-reads the run cache."""
|
|
1151
|
+
from forge_ui import projects
|
|
1152
|
+
screen = projects.screen(server)
|
|
1153
|
+
with screen.lock:
|
|
1154
|
+
for key in [k for k in screen.cli if isinstance(k, tuple) and k and k[0] == 'issues']:
|
|
1155
|
+
del screen.cli[key]
|
|
1156
|
+
screen.runs.clear()
|
|
1157
|
+
|
|
1158
|
+
|
|
1099
1159
|
def _worktrees_remove(ctx):
|
|
1100
1160
|
"""POST `{paths, branches?, dry_run?}`: `forge worktrees rm <paths> [--branches] [--dry-run] --json --actor ui`.
|
|
1101
1161
|
|
|
@@ -1198,6 +1258,153 @@ def _memories_forget(ctx):
|
|
|
1198
1258
|
lock.release()
|
|
1199
1259
|
|
|
1200
1260
|
|
|
1261
|
+
MAX_MEMORY_TEXT = 300
|
|
1262
|
+
MAX_MEMORY_PATHS = 20 # --path arguments on one memory add
|
|
1263
|
+
MAX_MEMORY_PATH = 300
|
|
1264
|
+
_MEMORY_CATEGORIES = ('verify', 'trap', 'finding')
|
|
1265
|
+
|
|
1266
|
+
|
|
1267
|
+
def _optional_checkout(body):
|
|
1268
|
+
path = body.get('path')
|
|
1269
|
+
if path is not None and (not isinstance(path, str) or not path):
|
|
1270
|
+
raise BadBody('path must be a checkout path')
|
|
1271
|
+
return path
|
|
1272
|
+
|
|
1273
|
+
|
|
1274
|
+
def _memory_text(value):
|
|
1275
|
+
"""One argv element: 1 to 300 characters, one line, no control character.
|
|
1276
|
+
|
|
1277
|
+
Spaces alone are empty after the CLI sanitizes them, so they are refused here.
|
|
1278
|
+
"""
|
|
1279
|
+
if (not isinstance(value, str) or not 1 <= len(value) <= MAX_MEMORY_TEXT
|
|
1280
|
+
or not value.strip(' ') or not _no_control_chars(value)):
|
|
1281
|
+
raise BadBody(f'text must be one line of 1 to {MAX_MEMORY_TEXT} characters')
|
|
1282
|
+
try:
|
|
1283
|
+
value.encode('utf-8')
|
|
1284
|
+
except UnicodeEncodeError:
|
|
1285
|
+
raise BadBody('text must be valid text')
|
|
1286
|
+
return value
|
|
1287
|
+
|
|
1288
|
+
|
|
1289
|
+
def _memory_paths(value):
|
|
1290
|
+
"""Relative paths for `--path`, at most 20, in first-seen order. Empty is no paths."""
|
|
1291
|
+
if not isinstance(value, list) or len(value) > MAX_MEMORY_PATHS:
|
|
1292
|
+
raise BadBody(f'paths must be a list of at most {MAX_MEMORY_PATHS} relative paths')
|
|
1293
|
+
out = []
|
|
1294
|
+
for item in value:
|
|
1295
|
+
if not isinstance(item, str) or not item or len(item) > MAX_MEMORY_PATH or not _no_control_chars(item):
|
|
1296
|
+
raise BadBody('paths holds a value that is not acceptable')
|
|
1297
|
+
if os.path.isabs(item) or item.startswith(('/', '\\')):
|
|
1298
|
+
raise BadBody('paths holds a value that is not acceptable')
|
|
1299
|
+
if any(part == '..' for part in re.split(r'[\\/]', item)):
|
|
1300
|
+
raise BadBody('paths holds a value that is not acceptable')
|
|
1301
|
+
if any(ch in item for ch in ',[]'):
|
|
1302
|
+
raise BadBody('paths holds a value that is not acceptable')
|
|
1303
|
+
if item not in out:
|
|
1304
|
+
out.append(item)
|
|
1305
|
+
return out
|
|
1306
|
+
|
|
1307
|
+
|
|
1308
|
+
def _memory_key(value):
|
|
1309
|
+
if (not isinstance(value, str) or not value or len(value) > MAX_FIELD or not _no_control_chars(value)
|
|
1310
|
+
or not _MEMORY_KEY.match(value)):
|
|
1311
|
+
raise BadBody('key must be category:key')
|
|
1312
|
+
return value
|
|
1313
|
+
|
|
1314
|
+
|
|
1315
|
+
def _memory_category(value):
|
|
1316
|
+
if value not in _MEMORY_CATEGORIES:
|
|
1317
|
+
raise BadBody('category must be verify, trap or finding')
|
|
1318
|
+
return value
|
|
1319
|
+
|
|
1320
|
+
|
|
1321
|
+
def _memory_checkouts(ctx, path):
|
|
1322
|
+
"""The checkouts a memory write runs in, or an error response.
|
|
1323
|
+
|
|
1324
|
+
One checkout when `path` names an existing one, else each existing checkout of the project.
|
|
1325
|
+
404 unknown project, 400 when path is not one of them, 409 when none exists.
|
|
1326
|
+
"""
|
|
1327
|
+
from forge_ui import projects
|
|
1328
|
+
project = projects.screen(ctx.server).projects(ctx.server.catalog).get(ctx.key)
|
|
1329
|
+
if project is None:
|
|
1330
|
+
return 404, {'error': 'not found'}
|
|
1331
|
+
existing = [c['path'] for c in projects.checkouts(project) if c['exists']]
|
|
1332
|
+
if path is not None:
|
|
1333
|
+
if path not in existing:
|
|
1334
|
+
return _invalid('path is not a checkout of this project')
|
|
1335
|
+
existing = [path]
|
|
1336
|
+
if not existing:
|
|
1337
|
+
return 409, {'error': 'refused', 'detail': 'no checkout of this project exists'}
|
|
1338
|
+
return existing
|
|
1339
|
+
|
|
1340
|
+
|
|
1341
|
+
def _memory_each(ctx, checkouts, argv_of):
|
|
1342
|
+
"""argv_of(checkout) once per checkout under memory_lock. The memories cache drops after the calls."""
|
|
1343
|
+
lock = _server_lock(ctx.server, 'memory_lock')
|
|
1344
|
+
if not lock.acquire(blocking=False):
|
|
1345
|
+
return 409, {'error': 'busy'}
|
|
1346
|
+
try:
|
|
1347
|
+
results, failed = [], []
|
|
1348
|
+
for checkout in checkouts:
|
|
1349
|
+
status, answer = ctx.call(*argv_of(checkout))
|
|
1350
|
+
if status == 200:
|
|
1351
|
+
results.append({'path': checkout, 'result': answer})
|
|
1352
|
+
else:
|
|
1353
|
+
failed.append((status, answer))
|
|
1354
|
+
results.append({'path': checkout, 'result': None, 'status': status, 'error': answer})
|
|
1355
|
+
invalidate_memories(ctx.server)
|
|
1356
|
+
if failed and len(failed) == len(results):
|
|
1357
|
+
return failed[0]
|
|
1358
|
+
return 200, {'ok': not failed, 'checkouts': results}
|
|
1359
|
+
finally:
|
|
1360
|
+
lock.release()
|
|
1361
|
+
|
|
1362
|
+
|
|
1363
|
+
def _memories_add(ctx):
|
|
1364
|
+
"""POST `{path?, category, text, paths?}`: `forge memory add <checkout> --category C --text T [--path P]…
|
|
1365
|
+
--actor ui --json`, once per checkout. Text is one argv element, never a shell string."""
|
|
1366
|
+
ctx.route = 'memories add'
|
|
1367
|
+
try:
|
|
1368
|
+
body = _body_object(ctx, ('path', 'category', 'text', 'paths'))
|
|
1369
|
+
path = _optional_checkout(body)
|
|
1370
|
+
category = _memory_category(body.get('category'))
|
|
1371
|
+
text = _memory_text(body.get('text'))
|
|
1372
|
+
paths = _memory_paths(body.get('paths', []))
|
|
1373
|
+
except BadBody as exc:
|
|
1374
|
+
return _invalid(str(exc))
|
|
1375
|
+
checkouts = _memory_checkouts(ctx, path)
|
|
1376
|
+
if not isinstance(checkouts, list):
|
|
1377
|
+
return checkouts
|
|
1378
|
+
|
|
1379
|
+
def argv(checkout):
|
|
1380
|
+
command = ['memory', 'add', checkout, '--category', category, '--text', text]
|
|
1381
|
+
for item in paths:
|
|
1382
|
+
command.extend(('--path', item))
|
|
1383
|
+
command.extend(('--actor', 'ui', '--json'))
|
|
1384
|
+
return command
|
|
1385
|
+
return _memory_each(ctx, checkouts, argv)
|
|
1386
|
+
|
|
1387
|
+
|
|
1388
|
+
def _memories_edit(ctx):
|
|
1389
|
+
"""POST `{path?, key, text}`: `forge memory edit <checkout> <key> --text T --actor ui --json`, once per checkout.
|
|
1390
|
+
Text is one argv element, never a shell string."""
|
|
1391
|
+
ctx.route = 'memories edit'
|
|
1392
|
+
try:
|
|
1393
|
+
body = _body_object(ctx, ('path', 'key', 'text'))
|
|
1394
|
+
path = _optional_checkout(body)
|
|
1395
|
+
key = _memory_key(body.get('key'))
|
|
1396
|
+
text = _memory_text(body.get('text'))
|
|
1397
|
+
except BadBody as exc:
|
|
1398
|
+
return _invalid(str(exc))
|
|
1399
|
+
checkouts = _memory_checkouts(ctx, path)
|
|
1400
|
+
if not isinstance(checkouts, list):
|
|
1401
|
+
return checkouts
|
|
1402
|
+
|
|
1403
|
+
def argv(checkout):
|
|
1404
|
+
return ['memory', 'edit', checkout, key, '--text', text, '--actor', 'ui', '--json']
|
|
1405
|
+
return _memory_each(ctx, checkouts, argv)
|
|
1406
|
+
|
|
1407
|
+
|
|
1201
1408
|
def _storage_compact(ctx):
|
|
1202
1409
|
"""POST `{run | all, dry_run?}`: `forge runs compact <run dir>|--all --logs --json [--dry-run]`."""
|
|
1203
1410
|
ctx.route = 'compact'
|
|
@@ -1240,15 +1447,7 @@ def _scheduler_live(path):
|
|
|
1240
1447
|
pid = json.load(handle).get('pid')
|
|
1241
1448
|
except (OSError, ValueError, AttributeError, RecursionError):
|
|
1242
1449
|
return False
|
|
1243
|
-
|
|
1244
|
-
return False
|
|
1245
|
-
try:
|
|
1246
|
-
os.kill(pid, 0)
|
|
1247
|
-
except PermissionError:
|
|
1248
|
-
return True
|
|
1249
|
-
except (OSError, OverflowError):
|
|
1250
|
-
return False
|
|
1251
|
-
return True
|
|
1450
|
+
return forge_proc.pid_alive(pid)
|
|
1252
1451
|
|
|
1253
1452
|
|
|
1254
1453
|
def _task_answer(ctx):
|
|
@@ -1285,6 +1484,475 @@ def _task_answer(ctx):
|
|
|
1285
1484
|
return ctx.locked(work)
|
|
1286
1485
|
|
|
1287
1486
|
|
|
1487
|
+
# ------------------------------------------------------- finding-record writes (#161)
|
|
1488
|
+
|
|
1489
|
+
# One pattern for every write. `dispatch` full-matches, so this does not swallow GET …/findings.
|
|
1490
|
+
_FINDINGS_FIELDS = {
|
|
1491
|
+
'fix': ('fps', 'commit', 'reason'),
|
|
1492
|
+
'dismiss': ('fps', 'reason'),
|
|
1493
|
+
'reopen': ('fps',),
|
|
1494
|
+
'to-file': ('fps', 'title', 'body'),
|
|
1495
|
+
'dup': ('fps', 'of'),
|
|
1496
|
+
'tag': ('fps', 'tags', 'remove'),
|
|
1497
|
+
'note': ('fps', 'text'),
|
|
1498
|
+
'edit': ('fps', 'severity', 'text'),
|
|
1499
|
+
}
|
|
1500
|
+
_FINDINGS_PATH = re.compile(
|
|
1501
|
+
r'/api/projects/([0-9a-f]{8})/findings/(' + '|'.join(_FINDINGS_FIELDS) + ')')
|
|
1502
|
+
_SINGLE_FINDING = frozenset(('dup', 'note', 'edit'))
|
|
1503
|
+
|
|
1504
|
+
|
|
1505
|
+
def _argv_text(value, name, limit):
|
|
1506
|
+
"""A string that will be one argv element: at most `limit` characters, no NUL, UTF-8."""
|
|
1507
|
+
if not isinstance(value, str) or len(value) > limit:
|
|
1508
|
+
raise BadBody(f'{name} must be a string of at most {limit} characters')
|
|
1509
|
+
if '\x00' in value:
|
|
1510
|
+
raise BadBody(f'{name} must not contain a NUL')
|
|
1511
|
+
try:
|
|
1512
|
+
value.encode('utf-8')
|
|
1513
|
+
except UnicodeEncodeError:
|
|
1514
|
+
raise BadBody(f'{name} must be valid text')
|
|
1515
|
+
return value
|
|
1516
|
+
|
|
1517
|
+
|
|
1518
|
+
def _file_text(value, name, limit):
|
|
1519
|
+
"""A string written to a temp file. A NUL is fine here; it cannot be an argv element."""
|
|
1520
|
+
if not isinstance(value, str) or len(value) > limit:
|
|
1521
|
+
raise BadBody(f'{name} must be a string of at most {limit} characters')
|
|
1522
|
+
try:
|
|
1523
|
+
value.encode('utf-8')
|
|
1524
|
+
except UnicodeEncodeError:
|
|
1525
|
+
raise BadBody(f'{name} must be valid text')
|
|
1526
|
+
return value
|
|
1527
|
+
|
|
1528
|
+
|
|
1529
|
+
def _optional_text(body, name, limit, loader):
|
|
1530
|
+
if name not in body:
|
|
1531
|
+
return None
|
|
1532
|
+
return loader(body[name], name, limit)
|
|
1533
|
+
|
|
1534
|
+
|
|
1535
|
+
def _finding_fps(value, single):
|
|
1536
|
+
limit = 1 if single else MAX_FINDING_FPS
|
|
1537
|
+
if not isinstance(value, list) or not 1 <= len(value) <= limit:
|
|
1538
|
+
if single:
|
|
1539
|
+
raise BadBody('fps must be a list of exactly one fingerprint')
|
|
1540
|
+
raise BadBody(f'fps must be a list of 1 to {MAX_FINDING_FPS} fingerprints')
|
|
1541
|
+
for item in value:
|
|
1542
|
+
if not isinstance(item, str) or not FP_RE.fullmatch(item):
|
|
1543
|
+
raise BadBody('fps holds a value that is not a 12-hex fingerprint')
|
|
1544
|
+
return list(dict.fromkeys(value)) # a repeated fingerprint is one finding
|
|
1545
|
+
|
|
1546
|
+
|
|
1547
|
+
def _finding_tags(value):
|
|
1548
|
+
if not isinstance(value, list) or not 1 <= len(value) <= MAX_TAGS:
|
|
1549
|
+
raise BadBody(f'tags must be a list of 1 to {MAX_TAGS} tags')
|
|
1550
|
+
for item in value:
|
|
1551
|
+
if not isinstance(item, str) or not _TAG_RE.fullmatch(item):
|
|
1552
|
+
raise BadBody('a tag is a lowercase letter, then lowercase letters, digits or dashes, at most 24 characters')
|
|
1553
|
+
return list(dict.fromkeys(value))
|
|
1554
|
+
|
|
1555
|
+
|
|
1556
|
+
def _append_option(argv, name, value):
|
|
1557
|
+
"""`--name value`. A value that starts with '-' is `--name=value`, so the CLI does not read it as a flag."""
|
|
1558
|
+
if value.startswith('-'):
|
|
1559
|
+
argv.append(f'--{name}={value}')
|
|
1560
|
+
else:
|
|
1561
|
+
argv.extend((f'--{name}', value))
|
|
1562
|
+
|
|
1563
|
+
|
|
1564
|
+
def _findings_request(op, body):
|
|
1565
|
+
"""`(fps, tokens, file)` for a validated body. BadBody otherwise.
|
|
1566
|
+
|
|
1567
|
+
`tokens` follow the fingerprints. `file` is `('--body-file'|'--text-file', text)` or None.
|
|
1568
|
+
For `note`, `tokens` is the one positional text and `file` is None.
|
|
1569
|
+
"""
|
|
1570
|
+
fps = _finding_fps(body.get('fps'), op in _SINGLE_FINDING)
|
|
1571
|
+
tokens, file = [], None
|
|
1572
|
+
if op == 'fix':
|
|
1573
|
+
commit = body['commit'] if 'commit' in body else None
|
|
1574
|
+
if commit is not None and (not isinstance(commit, str) or not _COMMIT_RE.fullmatch(commit)):
|
|
1575
|
+
raise BadBody('commit must be 7 to 40 lowercase hex characters')
|
|
1576
|
+
reason = _optional_text(body, 'reason', MAX_REASON, _argv_text)
|
|
1577
|
+
if commit is None and reason is None:
|
|
1578
|
+
raise BadBody('fix needs a commit or a reason')
|
|
1579
|
+
if commit is not None:
|
|
1580
|
+
tokens.extend(('--commit', commit))
|
|
1581
|
+
if reason is not None:
|
|
1582
|
+
_append_option(tokens, 'reason', reason)
|
|
1583
|
+
elif op == 'dismiss':
|
|
1584
|
+
if 'reason' not in body:
|
|
1585
|
+
raise BadBody('reason is required')
|
|
1586
|
+
_append_option(tokens, 'reason', _argv_text(body['reason'], 'reason', MAX_REASON))
|
|
1587
|
+
elif op == 'to-file':
|
|
1588
|
+
title = _optional_text(body, 'title', MAX_DRAFT_TITLE, _argv_text)
|
|
1589
|
+
text = _optional_text(body, 'body', MAX_DRAFT_BODY, _file_text)
|
|
1590
|
+
if title is not None:
|
|
1591
|
+
_append_option(tokens, 'title', title)
|
|
1592
|
+
if text is not None:
|
|
1593
|
+
file = ('--body-file', text)
|
|
1594
|
+
elif op == 'dup':
|
|
1595
|
+
other = body.get('of')
|
|
1596
|
+
if not isinstance(other, str) or not FP_RE.fullmatch(other):
|
|
1597
|
+
raise BadBody('of must be a 12-hex fingerprint')
|
|
1598
|
+
tokens.extend(('--of', other))
|
|
1599
|
+
elif op == 'tag':
|
|
1600
|
+
tags = _finding_tags(body.get('tags'))
|
|
1601
|
+
remove = _flag(body, 'remove')
|
|
1602
|
+
tokens.extend(('--', *tags, '--remove' if remove else '--add'))
|
|
1603
|
+
elif op == 'note':
|
|
1604
|
+
if 'text' not in body:
|
|
1605
|
+
raise BadBody('text is required')
|
|
1606
|
+
tokens.append(_argv_text(body['text'], 'text', MAX_NOTE))
|
|
1607
|
+
elif op == 'edit':
|
|
1608
|
+
severity = body['severity'] if 'severity' in body else None
|
|
1609
|
+
if severity is not None and severity not in _FINDING_SEVERITIES:
|
|
1610
|
+
raise BadBody('severity must be P0, P1, P2 or P3')
|
|
1611
|
+
text = _optional_text(body, 'text', MAX_EDIT_TEXT, _file_text)
|
|
1612
|
+
if severity is None and text is None:
|
|
1613
|
+
raise BadBody('edit needs a severity or text')
|
|
1614
|
+
if severity is not None:
|
|
1615
|
+
tokens.extend(('--severity', severity))
|
|
1616
|
+
if text is not None:
|
|
1617
|
+
file = ('--text-file', text)
|
|
1618
|
+
return fps, tokens, file
|
|
1619
|
+
|
|
1620
|
+
|
|
1621
|
+
def _note_argv(root, fp, text):
|
|
1622
|
+
"""`note REPO FP TEXT`. Text that starts with '-' sits after `--`, with the options in front of that."""
|
|
1623
|
+
if text.startswith('-'):
|
|
1624
|
+
return ['findings', 'note', '--actor', 'ui', '--json', root, fp, '--', text]
|
|
1625
|
+
return ['findings', 'note', root, fp, text, '--actor', 'ui', '--json']
|
|
1626
|
+
|
|
1627
|
+
|
|
1628
|
+
def _write_payload(directory, flag, text):
|
|
1629
|
+
"""`[flag, path]` for `text` in `directory` (mode 0600). The caller creates and removes the directory."""
|
|
1630
|
+
path = os.path.join(directory, 'payload')
|
|
1631
|
+
handle = os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), 'w', encoding='utf-8')
|
|
1632
|
+
try:
|
|
1633
|
+
handle.write(text)
|
|
1634
|
+
finally:
|
|
1635
|
+
handle.close()
|
|
1636
|
+
return [flag, path]
|
|
1637
|
+
|
|
1638
|
+
|
|
1639
|
+
def _findings_action(ctx):
|
|
1640
|
+
"""POST `{fps, …}`: `forge findings <op> <project root> … --actor ui --json`.
|
|
1641
|
+
|
|
1642
|
+
The path's last segment is the op (fix, dismiss, reopen, to-file, dup, tag, note, edit).
|
|
1643
|
+
A draft body and an edit's replacement text go to a private temp file (`--body-file`,
|
|
1644
|
+
`--text-file`). `findings_lock` makes a second write 409 `busy`. Exit 3 is 409 with the CLI's
|
|
1645
|
+
message. A successful call drops the project screen's issues listings and its run cache.
|
|
1646
|
+
"""
|
|
1647
|
+
from forge_ui import projects
|
|
1648
|
+
op = ctx.parts[0]
|
|
1649
|
+
ctx.route = 'findings ' + op
|
|
1650
|
+
try:
|
|
1651
|
+
body = _body_object(ctx, _FINDINGS_FIELDS[op])
|
|
1652
|
+
fps, tokens, file = _findings_request(op, body)
|
|
1653
|
+
except BadBody as exc:
|
|
1654
|
+
return _invalid(str(exc))
|
|
1655
|
+
# the identity root when it exists, else a checkout still on disk (as the triage routes): a project whose main
|
|
1656
|
+
# checkout was removed keeps a linked worktree the CLI can resolve the repository from
|
|
1657
|
+
root = _triage_repo(ctx)
|
|
1658
|
+
if not isinstance(root, str):
|
|
1659
|
+
return root
|
|
1660
|
+
lock = _server_lock(ctx.server, 'findings_lock')
|
|
1661
|
+
if not lock.acquire(blocking=False):
|
|
1662
|
+
return 409, {'error': 'busy'}
|
|
1663
|
+
directory = None
|
|
1664
|
+
try:
|
|
1665
|
+
file_argv = []
|
|
1666
|
+
if file is not None:
|
|
1667
|
+
directory = tempfile.mkdtemp(prefix='forge-ui-findings-')
|
|
1668
|
+
file_argv = _write_payload(directory, *file)
|
|
1669
|
+
if op == 'note':
|
|
1670
|
+
argv = _note_argv(root, fps[0], tokens[0])
|
|
1671
|
+
else:
|
|
1672
|
+
argv = ['findings', op, root, *fps, *tokens, *file_argv, '--actor', 'ui', '--json']
|
|
1673
|
+
status, answer = ctx.call(*argv)
|
|
1674
|
+
if status == 200:
|
|
1675
|
+
invalidate_findings(ctx.server)
|
|
1676
|
+
return status, answer
|
|
1677
|
+
finally:
|
|
1678
|
+
if directory is not None:
|
|
1679
|
+
shutil.rmtree(directory, ignore_errors=True)
|
|
1680
|
+
lock.release()
|
|
1681
|
+
|
|
1682
|
+
|
|
1683
|
+
# ------------------------------------------------------- triage routes and spec check (#161)
|
|
1684
|
+
|
|
1685
|
+
_SPEC_RE = re.compile(r'^[A-Za-z0-9._:/@+-]+$')
|
|
1686
|
+
# A triage number. Nine digits is past the directory cap; a longer digit string is not an id.
|
|
1687
|
+
_TRIAGE_N = re.compile(r'^[0-9]{1,9}$')
|
|
1688
|
+
_PROPOSAL_ID = re.compile(r'^p[0-9]{1,4}$')
|
|
1689
|
+
_RESOLVED_KEY = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
|
|
1690
|
+
_MAX_SPEC = 120
|
|
1691
|
+
_MAX_TRIAGE_FINDINGS = 2000
|
|
1692
|
+
# control.py is ui/forge_ui/control.py; the skill root is three directories up, as forge-control.py's
|
|
1693
|
+
# SKILL is two up from scripts/. Doctor is that script, never a model and never a shell string.
|
|
1694
|
+
_DISPATCH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))),
|
|
1695
|
+
'scripts', 'forge-dispatch.sh')
|
|
1696
|
+
|
|
1697
|
+
|
|
1698
|
+
def _triage_spec(value):
|
|
1699
|
+
"""A triage or doctor spec: 1 to 120 characters of the dispatch spec alphabet."""
|
|
1700
|
+
if not isinstance(value, str) or not 1 <= len(value) <= _MAX_SPEC or not _SPEC_RE.fullmatch(value):
|
|
1701
|
+
raise BadBody('spec must be 1 to 120 characters of letters, digits and . _ : / @ + -')
|
|
1702
|
+
return value
|
|
1703
|
+
|
|
1704
|
+
|
|
1705
|
+
def _max_findings(body):
|
|
1706
|
+
"""None when the body omits it. JSON true is a bool, and a bool is an int, so the type is exact."""
|
|
1707
|
+
if 'max_findings' not in body:
|
|
1708
|
+
return None
|
|
1709
|
+
value = body['max_findings']
|
|
1710
|
+
if type(value) is not int or not 1 <= value <= _MAX_TRIAGE_FINDINGS:
|
|
1711
|
+
raise BadBody(f'max_findings must be an integer from 1 to {_MAX_TRIAGE_FINDINGS}')
|
|
1712
|
+
return value
|
|
1713
|
+
|
|
1714
|
+
|
|
1715
|
+
def _triage_n(value):
|
|
1716
|
+
if not isinstance(value, str) or not _TRIAGE_N.fullmatch(value):
|
|
1717
|
+
raise BadBody('n must be a decimal integer')
|
|
1718
|
+
return value
|
|
1719
|
+
|
|
1720
|
+
|
|
1721
|
+
def _proposal_id(value):
|
|
1722
|
+
if not isinstance(value, str) or not _PROPOSAL_ID.fullmatch(value):
|
|
1723
|
+
raise BadBody('pid must match ^p[0-9]{1,4}$')
|
|
1724
|
+
return value
|
|
1725
|
+
|
|
1726
|
+
|
|
1727
|
+
def _proposal_hash(value):
|
|
1728
|
+
if not isinstance(value, str) or not FP_RE.fullmatch(value):
|
|
1729
|
+
raise BadBody('hash must be 12 lowercase hex characters')
|
|
1730
|
+
return value
|
|
1731
|
+
|
|
1732
|
+
|
|
1733
|
+
def _plan_dir(body):
|
|
1734
|
+
"""None when the field is absent. Present means an absolute path, whether or not it exists yet."""
|
|
1735
|
+
if 'plan_dir' not in body:
|
|
1736
|
+
return None
|
|
1737
|
+
value = body['plan_dir']
|
|
1738
|
+
if not isinstance(value, str) or not os.path.isabs(value) or not _no_control_chars(value):
|
|
1739
|
+
raise BadBody('plan_dir must be an absolute path')
|
|
1740
|
+
return value
|
|
1741
|
+
|
|
1742
|
+
|
|
1743
|
+
def _triage_target(ctx):
|
|
1744
|
+
"""`(n, pid)` from the path. BadBody when either segment is not the shape the CLI takes."""
|
|
1745
|
+
n, pid = ctx.parts[:2]
|
|
1746
|
+
return _triage_n(n), _proposal_id(pid)
|
|
1747
|
+
|
|
1748
|
+
|
|
1749
|
+
def _triage_repo(ctx):
|
|
1750
|
+
"""The project's identity root when that folder exists, else the first existing checkout.
|
|
1751
|
+
|
|
1752
|
+
`checkouts` lists the root first, then the other paths. A string is the repo to pass to the CLI.
|
|
1753
|
+
A tuple is the error response: 404 `not found` for an unknown project, 404 `no checkout` when
|
|
1754
|
+
the project has no directory left on this machine.
|
|
1755
|
+
"""
|
|
1756
|
+
from forge_ui import projects
|
|
1757
|
+
found = projects.screen(ctx.server).projects(ctx.server.catalog).get(ctx.key)
|
|
1758
|
+
if not isinstance(found, dict):
|
|
1759
|
+
return 404, {'error': 'not found'}
|
|
1760
|
+
root = found.get('root')
|
|
1761
|
+
if isinstance(root, str) and root and os.path.isdir(root):
|
|
1762
|
+
return root
|
|
1763
|
+
if not isinstance(root, str) or not isinstance(found.get('runs'), list):
|
|
1764
|
+
return 404, {'error': 'no checkout'}
|
|
1765
|
+
existing = [c['path'] for c in projects.checkouts(found) if c['exists']]
|
|
1766
|
+
if not existing:
|
|
1767
|
+
return 404, {'error': 'no checkout'}
|
|
1768
|
+
return existing[0]
|
|
1769
|
+
|
|
1770
|
+
|
|
1771
|
+
def _triage_repo_or_response(ctx):
|
|
1772
|
+
repo = _triage_repo(ctx)
|
|
1773
|
+
return (None, repo) if isinstance(repo, str) else (repo, None)
|
|
1774
|
+
|
|
1775
|
+
|
|
1776
|
+
def _no_triage(body):
|
|
1777
|
+
"""True when triage-status refused because no triage has run (or this number does not exist)."""
|
|
1778
|
+
if not isinstance(body, dict):
|
|
1779
|
+
return False
|
|
1780
|
+
parts = [str(body.get('detail') or '')]
|
|
1781
|
+
result = body.get('result')
|
|
1782
|
+
if isinstance(result, dict):
|
|
1783
|
+
parts.append(str(result.get('error') or ''))
|
|
1784
|
+
return 'no triage' in '\n'.join(parts).lower()
|
|
1785
|
+
|
|
1786
|
+
|
|
1787
|
+
def _findings_write(ctx, argv):
|
|
1788
|
+
"""One `forge findings` write under `findings_lock`. 409 `busy` when a write already holds it.
|
|
1789
|
+
|
|
1790
|
+
A 200 drops the project screen's findings cache, as a finding-record write does. A refusal
|
|
1791
|
+
wrote nothing, so the cache stays.
|
|
1792
|
+
"""
|
|
1793
|
+
lock = _server_lock(ctx.server, 'findings_lock')
|
|
1794
|
+
if not lock.acquire(blocking=False):
|
|
1795
|
+
return 409, {'error': 'busy'}
|
|
1796
|
+
try:
|
|
1797
|
+
status, answer = ctx.call(*argv)
|
|
1798
|
+
if status == 200:
|
|
1799
|
+
invalidate_findings(ctx.server)
|
|
1800
|
+
return status, answer
|
|
1801
|
+
finally:
|
|
1802
|
+
lock.release()
|
|
1803
|
+
|
|
1804
|
+
|
|
1805
|
+
def _triage_start(ctx):
|
|
1806
|
+
"""POST `{spec, max_findings?}`: `forge findings triage <root> --spec S [--max-findings N]
|
|
1807
|
+
--detach --actor ui --json`.
|
|
1808
|
+
|
|
1809
|
+
`--detach` makes the CLI print `{triage, state}` and return at once. Exit 3 is 409 with the
|
|
1810
|
+
CLI's message. This is the one route whose CLI starts a model; the route itself does not.
|
|
1811
|
+
"""
|
|
1812
|
+
ctx.route = 'triage'
|
|
1813
|
+
try:
|
|
1814
|
+
body = _body_object(ctx, ('spec', 'max_findings'))
|
|
1815
|
+
spec = _triage_spec(body.get('spec'))
|
|
1816
|
+
limit = _max_findings(body)
|
|
1817
|
+
except BadBody as exc:
|
|
1818
|
+
return _invalid(str(exc))
|
|
1819
|
+
error, repo = _triage_repo_or_response(ctx)
|
|
1820
|
+
if error:
|
|
1821
|
+
return error
|
|
1822
|
+
argv = ['findings', 'triage', repo]
|
|
1823
|
+
_append_option(argv, 'spec', spec)
|
|
1824
|
+
if limit is not None:
|
|
1825
|
+
argv += ['--max-findings', str(limit)]
|
|
1826
|
+
argv += ['--detach', '--actor', 'ui', '--json']
|
|
1827
|
+
return ctx.call(*argv)
|
|
1828
|
+
|
|
1829
|
+
|
|
1830
|
+
def _triage_get(ctx):
|
|
1831
|
+
"""GET `[?n=N]`: `{state, proposals}` from `triage-status` and `proposals`, each time, uncached.
|
|
1832
|
+
|
|
1833
|
+
No triage yet (the status command exits 3 with that message) is 200 `{state: null, proposals: null}`.
|
|
1834
|
+
A triage with no proposals yet leaves `proposals` null and still returns the state. A read: no lock.
|
|
1835
|
+
"""
|
|
1836
|
+
ctx.route = 'triage'
|
|
1837
|
+
try:
|
|
1838
|
+
params = _query_params(ctx.query, ('n',))
|
|
1839
|
+
n = _triage_n(params['n']) if 'n' in params else None
|
|
1840
|
+
except BadBody as exc:
|
|
1841
|
+
return _invalid(str(exc))
|
|
1842
|
+
error, repo = _triage_repo_or_response(ctx)
|
|
1843
|
+
if error:
|
|
1844
|
+
return error
|
|
1845
|
+
number = [n] if n else []
|
|
1846
|
+
status, state = ctx.call('findings', 'triage-status', repo, *number, '--json')
|
|
1847
|
+
if status != 200:
|
|
1848
|
+
if status == 409 and _no_triage(state):
|
|
1849
|
+
return 200, {'state': None, 'proposals': None}
|
|
1850
|
+
return status, state
|
|
1851
|
+
pstatus, proposals = ctx.call('findings', 'proposals', repo, *number, '--json')
|
|
1852
|
+
if pstatus == 409:
|
|
1853
|
+
proposals = None
|
|
1854
|
+
elif pstatus != 200:
|
|
1855
|
+
return pstatus, proposals
|
|
1856
|
+
return 200, {'state': state, 'proposals': proposals}
|
|
1857
|
+
|
|
1858
|
+
|
|
1859
|
+
def _triage_apply(ctx):
|
|
1860
|
+
"""POST `{hash, plan_dir?}`: `forge findings apply <root> N PID --approve HASH [--plan-dir D]
|
|
1861
|
+
--actor ui --json`. Exit 3 is 409 with the CLI's message."""
|
|
1862
|
+
ctx.route = 'triage apply'
|
|
1863
|
+
try:
|
|
1864
|
+
n, pid = _triage_target(ctx)
|
|
1865
|
+
body = _body_object(ctx, ('hash', 'plan_dir'))
|
|
1866
|
+
digest = _proposal_hash(body.get('hash'))
|
|
1867
|
+
plan_dir = _plan_dir(body)
|
|
1868
|
+
except BadBody as exc:
|
|
1869
|
+
return _invalid(str(exc))
|
|
1870
|
+
error, repo = _triage_repo_or_response(ctx)
|
|
1871
|
+
if error:
|
|
1872
|
+
return error
|
|
1873
|
+
argv = ['findings', 'apply', repo, n, pid, '--approve', digest]
|
|
1874
|
+
if plan_dir is not None:
|
|
1875
|
+
argv += ['--plan-dir', plan_dir]
|
|
1876
|
+
argv += ['--actor', 'ui', '--json']
|
|
1877
|
+
return _findings_write(ctx, argv)
|
|
1878
|
+
|
|
1879
|
+
|
|
1880
|
+
def _triage_reject(ctx):
|
|
1881
|
+
"""POST `{reason?}`: `forge findings reject <root> N PID [--reason T] --actor ui --json`.
|
|
1882
|
+
|
|
1883
|
+
The reason is at most 500 characters. Exit 3 is 409 with the CLI's message."""
|
|
1884
|
+
ctx.route = 'triage reject'
|
|
1885
|
+
try:
|
|
1886
|
+
n, pid = _triage_target(ctx)
|
|
1887
|
+
body = _body_object(ctx, ('reason',))
|
|
1888
|
+
reason = _optional_reason(body.get('reason'))
|
|
1889
|
+
except BadBody as exc:
|
|
1890
|
+
return _invalid(str(exc))
|
|
1891
|
+
error, repo = _triage_repo_or_response(ctx)
|
|
1892
|
+
if error:
|
|
1893
|
+
return error
|
|
1894
|
+
argv = ['findings', 'reject', repo, n, pid]
|
|
1895
|
+
if reason:
|
|
1896
|
+
_append_option(argv, 'reason', reason)
|
|
1897
|
+
argv += ['--actor', 'ui', '--json']
|
|
1898
|
+
return _findings_write(ctx, argv)
|
|
1899
|
+
|
|
1900
|
+
|
|
1901
|
+
def _spec_query(raw):
|
|
1902
|
+
"""The query of GET /api/specs/check. A spec may contain `+`, which form decoding would turn into
|
|
1903
|
+
a space, and a spec has no spaces, so a literal `+` here is a plus."""
|
|
1904
|
+
return _query_params((raw or '').replace('+', '%2B'), ('spec',))
|
|
1905
|
+
|
|
1906
|
+
|
|
1907
|
+
def _resolved_pairs(text):
|
|
1908
|
+
"""The `key=value` lines of a doctor's stdout. The prose line after them is not one of them."""
|
|
1909
|
+
resolved = {}
|
|
1910
|
+
for raw in text.splitlines():
|
|
1911
|
+
line = raw.strip()
|
|
1912
|
+
if '=' not in line:
|
|
1913
|
+
continue
|
|
1914
|
+
key, value = line.split('=', 1)
|
|
1915
|
+
if _RESOLVED_KEY.fullmatch(key.strip()):
|
|
1916
|
+
resolved[key.strip()] = value.strip()
|
|
1917
|
+
return resolved
|
|
1918
|
+
|
|
1919
|
+
|
|
1920
|
+
def _doctor_error(result):
|
|
1921
|
+
"""The refusal line. Doctor prints it on stderr (`forge: …`); stdout may hold a partial block."""
|
|
1922
|
+
for text in (result.stderr, result.stdout):
|
|
1923
|
+
for line in text.splitlines():
|
|
1924
|
+
line = line.strip()
|
|
1925
|
+
if line:
|
|
1926
|
+
return line[:REFUSAL_MAX]
|
|
1927
|
+
return f'the doctor exited {result.code}'
|
|
1928
|
+
|
|
1929
|
+
|
|
1930
|
+
def _specs_check(ctx):
|
|
1931
|
+
"""GET `?spec=S`: `{ok: true, resolved}` or `{ok: false, error}` from
|
|
1932
|
+
`bash scripts/forge-dispatch.sh doctor --spec S --role side`.
|
|
1933
|
+
|
|
1934
|
+
The same argv forge-control's doctor uses, with the role `side`. An argv list, not a shell.
|
|
1935
|
+
A spec that fails the same check as triage start is 400 and the doctor is not run. A doctor
|
|
1936
|
+
refusal is 200 with `ok: false`: the check finished. Read-only servers answer this GET.
|
|
1937
|
+
"""
|
|
1938
|
+
ctx.route = 'specs check'
|
|
1939
|
+
try:
|
|
1940
|
+
params = _spec_query(ctx.query)
|
|
1941
|
+
if 'spec' not in params:
|
|
1942
|
+
raise BadBody('spec is required')
|
|
1943
|
+
spec = _triage_spec(params['spec'])
|
|
1944
|
+
except BadBody as exc:
|
|
1945
|
+
return _invalid(str(exc))
|
|
1946
|
+
result = run_cli(['bash', _DISPATCH, 'doctor', '--spec', spec, '--role', 'side'], ctx.timeout or TIMEOUT_S)
|
|
1947
|
+
if result.timed_out:
|
|
1948
|
+
return 504, {'error': 'timeout', 'detail': TIMEOUT_DETAIL}
|
|
1949
|
+
if result.error:
|
|
1950
|
+
return 502, {'error': 'bad gateway', 'detail': result.error[:DETAIL_MAX]}
|
|
1951
|
+
if result.code == 0:
|
|
1952
|
+
return 200, {'ok': True, 'resolved': _resolved_pairs(result.stdout)}
|
|
1953
|
+
return 200, {'ok': False, 'error': _doctor_error(result)}
|
|
1954
|
+
|
|
1955
|
+
|
|
1288
1956
|
ROUTES = [
|
|
1289
1957
|
('GET', re.compile(r'/api/runs/([0-9a-f]{12})/controls'), _show),
|
|
1290
1958
|
('POST', re.compile(r'/api/runs/([0-9a-f]{12})/controls'), _change),
|
|
@@ -1301,6 +1969,11 @@ ROUTES = [
|
|
|
1301
1969
|
('POST', re.compile(r'/api/worktrees/remove()'), _worktrees_remove),
|
|
1302
1970
|
('POST', re.compile(r'/api/storage/compact()'), _storage_compact),
|
|
1303
1971
|
('POST', re.compile(r'/api/projects/([0-9a-f]{8})/memories/forget'), _memories_forget),
|
|
1972
|
+
('POST', re.compile(r'/api/projects/([0-9a-f]{8})/memories/add'), _memories_add),
|
|
1973
|
+
('POST', re.compile(r'/api/projects/([0-9a-f]{8})/memories/edit'), _memories_edit),
|
|
1974
|
+
('POST', re.compile(r'/api/projects/([0-9a-f]{8})/triage/([^/]+)/([^/]+)/apply'), _triage_apply),
|
|
1975
|
+
('POST', re.compile(r'/api/projects/([0-9a-f]{8})/triage/([^/]+)/([^/]+)/reject'), _triage_reject),
|
|
1976
|
+
('POST', re.compile(r'/api/projects/([0-9a-f]{8})/triage'), _triage_start),
|
|
1304
1977
|
('GET', re.compile(r'/api/config/profiles()'), _config_profiles_get),
|
|
1305
1978
|
('POST', re.compile(r'/api/config/profiles()'), _config_profiles_set),
|
|
1306
1979
|
('GET', re.compile(r'/api/config()'), _config_get),
|
|
@@ -1310,8 +1983,11 @@ ROUTES = [
|
|
|
1310
1983
|
('GET', re.compile(r'/api/storage()'), _storage),
|
|
1311
1984
|
('GET', re.compile(r'/api/projects()'), _projects),
|
|
1312
1985
|
('GET', re.compile(r'/api/projects/([0-9a-f]{8})'), _project),
|
|
1986
|
+
('POST', _FINDINGS_PATH, _findings_action),
|
|
1313
1987
|
('GET', re.compile(r'/api/projects/([0-9a-f]{8})/findings'), _project_findings),
|
|
1314
1988
|
('GET', re.compile(r'/api/projects/([0-9a-f]{8})/memories'), _project_memories),
|
|
1989
|
+
('GET', re.compile(r'/api/projects/([0-9a-f]{8})/triage'), _triage_get),
|
|
1990
|
+
('GET', re.compile(r'/api/specs/check()'), _specs_check),
|
|
1315
1991
|
]
|
|
1316
1992
|
|
|
1317
1993
|
|