@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.
@@ -6,15 +6,18 @@ 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. Every other call has 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 tempfile
18
21
  import threading
19
22
  import time
20
23
  import urllib.parse
@@ -49,6 +52,12 @@ MAX_FPS = 25
49
52
  MAX_LABELS = 5
50
53
  MAX_LABEL = 50
51
54
  MAX_REASON = 500
55
+ MAX_FINDING_FPS = 200 # fingerprints in one finding-record write
56
+ MAX_NOTE = 2000
57
+ MAX_EDIT_TEXT = 4000
58
+ MAX_DRAFT_TITLE = 200
59
+ MAX_DRAFT_BODY = 20000
60
+ MAX_TAGS = 8
52
61
  MAX_CONFIG_VALUE = 4096
53
62
  MAX_DECIDE_VALUE = 256
54
63
  # The profile object written to `forge config profile … --file -`. The HTTP body is already capped
@@ -65,6 +74,9 @@ _PROFILE_NAME = re.compile(r'^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$')
65
74
  _PROFILE_KEY = re.compile(r'^(routing|policy)\.[a-z_.]+$')
66
75
  _PROFILE_ACTIONS = ('create', 'edit', 'set', 'unset', 'rm', 'use')
67
76
  FP_RE = re.compile(r'[0-9a-f]{12}')
77
+ _COMMIT_RE = re.compile(r'[0-9a-f]{7,40}')
78
+ _TAG_RE = re.compile(r'[a-z][a-z0-9-]{0,23}')
79
+ _FINDING_SEVERITIES = ('P0', 'P1', 'P2', 'P3')
68
80
  # Mirrored from forge_decide.GATES and MODES. The ui tests do not put scripts/ on the path, so this
69
81
  # module does not import forge_decide; ConfigTests.test_decide_names_match_forge_decide keeps them equal.
70
82
  DECIDE_GATES = ('drift', 'forward', 'prompt', 'memory-curate', 'memory-slice', 'memory-stale',
@@ -1001,11 +1013,18 @@ def _project_findings(ctx):
1001
1013
  refresh = _bit(_query_params(ctx.query, ('refresh',)), 'refresh')
1002
1014
  except BadBody as exc:
1003
1015
  return _invalid(str(exc))
1004
- # --offline: no gh call; the listing says which findings are dismissed, filed (as recorded) or swept.
1016
+ # The listing is read online (GitHub says which issues are closed), for at most 60 s; projects.py asks again
1017
+ # with --offline when that fails.
1018
+ def listing(path, online=True):
1019
+ args = ('issues', path, '--json', '--all-runs', '--include-plausible', '--include-dismissed')
1020
+ if online:
1021
+ status, body = ctx.call(*args, limit=projects.ONLINE_S)
1022
+ return body if status == 200 else None
1023
+ return _project_call(ctx, *args[:3], '--offline', *args[3:])
1024
+
1005
1025
  found = projects.screen(ctx.server).findings(
1006
- ctx.server.catalog, ctx.key, lambda: _project_call(ctx, 'dataset', 'history', '--json'),
1007
- lambda path: _project_call(ctx, 'issues', path, '--json', '--offline', '--all-runs', '--include-plausible',
1008
- '--include-dismissed'), refresh=refresh)
1026
+ ctx.server.catalog, ctx.key, lambda: _project_call(ctx, 'dataset', 'history', '--json'), listing,
1027
+ refresh=refresh)
1009
1028
  return (404, {'error': 'not found'}) if found is None else (200, found)
1010
1029
 
1011
1030
 
@@ -1096,6 +1115,16 @@ def invalidate_memories(server):
1096
1115
  del screen.cli[key]
1097
1116
 
1098
1117
 
1118
+ def invalidate_findings(server):
1119
+ """The next GET of a project's findings reads `forge issues` again, and re-reads the run cache."""
1120
+ from forge_ui import projects
1121
+ screen = projects.screen(server)
1122
+ with screen.lock:
1123
+ for key in [k for k in screen.cli if isinstance(k, tuple) and k and k[0] == 'issues']:
1124
+ del screen.cli[key]
1125
+ screen.runs.clear()
1126
+
1127
+
1099
1128
  def _worktrees_remove(ctx):
1100
1129
  """POST `{paths, branches?, dry_run?}`: `forge worktrees rm <paths> [--branches] [--dry-run] --json --actor ui`.
1101
1130
 
@@ -1198,6 +1227,153 @@ def _memories_forget(ctx):
1198
1227
  lock.release()
1199
1228
 
1200
1229
 
1230
+ MAX_MEMORY_TEXT = 300
1231
+ MAX_MEMORY_PATHS = 20 # --path arguments on one memory add
1232
+ MAX_MEMORY_PATH = 300
1233
+ _MEMORY_CATEGORIES = ('verify', 'trap', 'finding')
1234
+
1235
+
1236
+ def _optional_checkout(body):
1237
+ path = body.get('path')
1238
+ if path is not None and (not isinstance(path, str) or not path):
1239
+ raise BadBody('path must be a checkout path')
1240
+ return path
1241
+
1242
+
1243
+ def _memory_text(value):
1244
+ """One argv element: 1 to 300 characters, one line, no control character.
1245
+
1246
+ Spaces alone are empty after the CLI sanitizes them, so they are refused here.
1247
+ """
1248
+ if (not isinstance(value, str) or not 1 <= len(value) <= MAX_MEMORY_TEXT
1249
+ or not value.strip(' ') or not _no_control_chars(value)):
1250
+ raise BadBody(f'text must be one line of 1 to {MAX_MEMORY_TEXT} characters')
1251
+ try:
1252
+ value.encode('utf-8')
1253
+ except UnicodeEncodeError:
1254
+ raise BadBody('text must be valid text')
1255
+ return value
1256
+
1257
+
1258
+ def _memory_paths(value):
1259
+ """Relative paths for `--path`, at most 20, in first-seen order. Empty is no paths."""
1260
+ if not isinstance(value, list) or len(value) > MAX_MEMORY_PATHS:
1261
+ raise BadBody(f'paths must be a list of at most {MAX_MEMORY_PATHS} relative paths')
1262
+ out = []
1263
+ for item in value:
1264
+ if not isinstance(item, str) or not item or len(item) > MAX_MEMORY_PATH or not _no_control_chars(item):
1265
+ raise BadBody('paths holds a value that is not acceptable')
1266
+ if os.path.isabs(item) or item.startswith(('/', '\\')):
1267
+ raise BadBody('paths holds a value that is not acceptable')
1268
+ if any(part == '..' for part in re.split(r'[\\/]', item)):
1269
+ raise BadBody('paths holds a value that is not acceptable')
1270
+ if any(ch in item for ch in ',[]'):
1271
+ raise BadBody('paths holds a value that is not acceptable')
1272
+ if item not in out:
1273
+ out.append(item)
1274
+ return out
1275
+
1276
+
1277
+ def _memory_key(value):
1278
+ if (not isinstance(value, str) or not value or len(value) > MAX_FIELD or not _no_control_chars(value)
1279
+ or not _MEMORY_KEY.match(value)):
1280
+ raise BadBody('key must be category:key')
1281
+ return value
1282
+
1283
+
1284
+ def _memory_category(value):
1285
+ if value not in _MEMORY_CATEGORIES:
1286
+ raise BadBody('category must be verify, trap or finding')
1287
+ return value
1288
+
1289
+
1290
+ def _memory_checkouts(ctx, path):
1291
+ """The checkouts a memory write runs in, or an error response.
1292
+
1293
+ One checkout when `path` names an existing one, else each existing checkout of the project.
1294
+ 404 unknown project, 400 when path is not one of them, 409 when none exists.
1295
+ """
1296
+ from forge_ui import projects
1297
+ project = projects.screen(ctx.server).projects(ctx.server.catalog).get(ctx.key)
1298
+ if project is None:
1299
+ return 404, {'error': 'not found'}
1300
+ existing = [c['path'] for c in projects.checkouts(project) if c['exists']]
1301
+ if path is not None:
1302
+ if path not in existing:
1303
+ return _invalid('path is not a checkout of this project')
1304
+ existing = [path]
1305
+ if not existing:
1306
+ return 409, {'error': 'refused', 'detail': 'no checkout of this project exists'}
1307
+ return existing
1308
+
1309
+
1310
+ def _memory_each(ctx, checkouts, argv_of):
1311
+ """argv_of(checkout) once per checkout under memory_lock. The memories cache drops after the calls."""
1312
+ lock = _server_lock(ctx.server, 'memory_lock')
1313
+ if not lock.acquire(blocking=False):
1314
+ return 409, {'error': 'busy'}
1315
+ try:
1316
+ results, failed = [], []
1317
+ for checkout in checkouts:
1318
+ status, answer = ctx.call(*argv_of(checkout))
1319
+ if status == 200:
1320
+ results.append({'path': checkout, 'result': answer})
1321
+ else:
1322
+ failed.append((status, answer))
1323
+ results.append({'path': checkout, 'result': None, 'status': status, 'error': answer})
1324
+ invalidate_memories(ctx.server)
1325
+ if failed and len(failed) == len(results):
1326
+ return failed[0]
1327
+ return 200, {'ok': not failed, 'checkouts': results}
1328
+ finally:
1329
+ lock.release()
1330
+
1331
+
1332
+ def _memories_add(ctx):
1333
+ """POST `{path?, category, text, paths?}`: `forge memory add <checkout> --category C --text T [--path P]…
1334
+ --actor ui --json`, once per checkout. Text is one argv element, never a shell string."""
1335
+ ctx.route = 'memories add'
1336
+ try:
1337
+ body = _body_object(ctx, ('path', 'category', 'text', 'paths'))
1338
+ path = _optional_checkout(body)
1339
+ category = _memory_category(body.get('category'))
1340
+ text = _memory_text(body.get('text'))
1341
+ paths = _memory_paths(body.get('paths', []))
1342
+ except BadBody as exc:
1343
+ return _invalid(str(exc))
1344
+ checkouts = _memory_checkouts(ctx, path)
1345
+ if not isinstance(checkouts, list):
1346
+ return checkouts
1347
+
1348
+ def argv(checkout):
1349
+ command = ['memory', 'add', checkout, '--category', category, '--text', text]
1350
+ for item in paths:
1351
+ command.extend(('--path', item))
1352
+ command.extend(('--actor', 'ui', '--json'))
1353
+ return command
1354
+ return _memory_each(ctx, checkouts, argv)
1355
+
1356
+
1357
+ def _memories_edit(ctx):
1358
+ """POST `{path?, key, text}`: `forge memory edit <checkout> <key> --text T --actor ui --json`, once per checkout.
1359
+ Text is one argv element, never a shell string."""
1360
+ ctx.route = 'memories edit'
1361
+ try:
1362
+ body = _body_object(ctx, ('path', 'key', 'text'))
1363
+ path = _optional_checkout(body)
1364
+ key = _memory_key(body.get('key'))
1365
+ text = _memory_text(body.get('text'))
1366
+ except BadBody as exc:
1367
+ return _invalid(str(exc))
1368
+ checkouts = _memory_checkouts(ctx, path)
1369
+ if not isinstance(checkouts, list):
1370
+ return checkouts
1371
+
1372
+ def argv(checkout):
1373
+ return ['memory', 'edit', checkout, key, '--text', text, '--actor', 'ui', '--json']
1374
+ return _memory_each(ctx, checkouts, argv)
1375
+
1376
+
1201
1377
  def _storage_compact(ctx):
1202
1378
  """POST `{run | all, dry_run?}`: `forge runs compact <run dir>|--all --logs --json [--dry-run]`."""
1203
1379
  ctx.route = 'compact'
@@ -1285,6 +1461,475 @@ def _task_answer(ctx):
1285
1461
  return ctx.locked(work)
1286
1462
 
1287
1463
 
1464
+ # ------------------------------------------------------- finding-record writes (#161)
1465
+
1466
+ # One pattern for every write. `dispatch` full-matches, so this does not swallow GET …/findings.
1467
+ _FINDINGS_FIELDS = {
1468
+ 'fix': ('fps', 'commit', 'reason'),
1469
+ 'dismiss': ('fps', 'reason'),
1470
+ 'reopen': ('fps',),
1471
+ 'to-file': ('fps', 'title', 'body'),
1472
+ 'dup': ('fps', 'of'),
1473
+ 'tag': ('fps', 'tags', 'remove'),
1474
+ 'note': ('fps', 'text'),
1475
+ 'edit': ('fps', 'severity', 'text'),
1476
+ }
1477
+ _FINDINGS_PATH = re.compile(
1478
+ r'/api/projects/([0-9a-f]{8})/findings/(' + '|'.join(_FINDINGS_FIELDS) + ')')
1479
+ _SINGLE_FINDING = frozenset(('dup', 'note', 'edit'))
1480
+
1481
+
1482
+ def _argv_text(value, name, limit):
1483
+ """A string that will be one argv element: at most `limit` characters, no NUL, UTF-8."""
1484
+ if not isinstance(value, str) or len(value) > limit:
1485
+ raise BadBody(f'{name} must be a string of at most {limit} characters')
1486
+ if '\x00' in value:
1487
+ raise BadBody(f'{name} must not contain a NUL')
1488
+ try:
1489
+ value.encode('utf-8')
1490
+ except UnicodeEncodeError:
1491
+ raise BadBody(f'{name} must be valid text')
1492
+ return value
1493
+
1494
+
1495
+ def _file_text(value, name, limit):
1496
+ """A string written to a temp file. A NUL is fine here; it cannot be an argv element."""
1497
+ if not isinstance(value, str) or len(value) > limit:
1498
+ raise BadBody(f'{name} must be a string of at most {limit} characters')
1499
+ try:
1500
+ value.encode('utf-8')
1501
+ except UnicodeEncodeError:
1502
+ raise BadBody(f'{name} must be valid text')
1503
+ return value
1504
+
1505
+
1506
+ def _optional_text(body, name, limit, loader):
1507
+ if name not in body:
1508
+ return None
1509
+ return loader(body[name], name, limit)
1510
+
1511
+
1512
+ def _finding_fps(value, single):
1513
+ limit = 1 if single else MAX_FINDING_FPS
1514
+ if not isinstance(value, list) or not 1 <= len(value) <= limit:
1515
+ if single:
1516
+ raise BadBody('fps must be a list of exactly one fingerprint')
1517
+ raise BadBody(f'fps must be a list of 1 to {MAX_FINDING_FPS} fingerprints')
1518
+ for item in value:
1519
+ if not isinstance(item, str) or not FP_RE.fullmatch(item):
1520
+ raise BadBody('fps holds a value that is not a 12-hex fingerprint')
1521
+ return list(dict.fromkeys(value)) # a repeated fingerprint is one finding
1522
+
1523
+
1524
+ def _finding_tags(value):
1525
+ if not isinstance(value, list) or not 1 <= len(value) <= MAX_TAGS:
1526
+ raise BadBody(f'tags must be a list of 1 to {MAX_TAGS} tags')
1527
+ for item in value:
1528
+ if not isinstance(item, str) or not _TAG_RE.fullmatch(item):
1529
+ raise BadBody('a tag is a lowercase letter, then lowercase letters, digits or dashes, at most 24 characters')
1530
+ return list(dict.fromkeys(value))
1531
+
1532
+
1533
+ def _append_option(argv, name, value):
1534
+ """`--name value`. A value that starts with '-' is `--name=value`, so the CLI does not read it as a flag."""
1535
+ if value.startswith('-'):
1536
+ argv.append(f'--{name}={value}')
1537
+ else:
1538
+ argv.extend((f'--{name}', value))
1539
+
1540
+
1541
+ def _findings_request(op, body):
1542
+ """`(fps, tokens, file)` for a validated body. BadBody otherwise.
1543
+
1544
+ `tokens` follow the fingerprints. `file` is `('--body-file'|'--text-file', text)` or None.
1545
+ For `note`, `tokens` is the one positional text and `file` is None.
1546
+ """
1547
+ fps = _finding_fps(body.get('fps'), op in _SINGLE_FINDING)
1548
+ tokens, file = [], None
1549
+ if op == 'fix':
1550
+ commit = body['commit'] if 'commit' in body else None
1551
+ if commit is not None and (not isinstance(commit, str) or not _COMMIT_RE.fullmatch(commit)):
1552
+ raise BadBody('commit must be 7 to 40 lowercase hex characters')
1553
+ reason = _optional_text(body, 'reason', MAX_REASON, _argv_text)
1554
+ if commit is None and reason is None:
1555
+ raise BadBody('fix needs a commit or a reason')
1556
+ if commit is not None:
1557
+ tokens.extend(('--commit', commit))
1558
+ if reason is not None:
1559
+ _append_option(tokens, 'reason', reason)
1560
+ elif op == 'dismiss':
1561
+ if 'reason' not in body:
1562
+ raise BadBody('reason is required')
1563
+ _append_option(tokens, 'reason', _argv_text(body['reason'], 'reason', MAX_REASON))
1564
+ elif op == 'to-file':
1565
+ title = _optional_text(body, 'title', MAX_DRAFT_TITLE, _argv_text)
1566
+ text = _optional_text(body, 'body', MAX_DRAFT_BODY, _file_text)
1567
+ if title is not None:
1568
+ _append_option(tokens, 'title', title)
1569
+ if text is not None:
1570
+ file = ('--body-file', text)
1571
+ elif op == 'dup':
1572
+ other = body.get('of')
1573
+ if not isinstance(other, str) or not FP_RE.fullmatch(other):
1574
+ raise BadBody('of must be a 12-hex fingerprint')
1575
+ tokens.extend(('--of', other))
1576
+ elif op == 'tag':
1577
+ tags = _finding_tags(body.get('tags'))
1578
+ remove = _flag(body, 'remove')
1579
+ tokens.extend(('--', *tags, '--remove' if remove else '--add'))
1580
+ elif op == 'note':
1581
+ if 'text' not in body:
1582
+ raise BadBody('text is required')
1583
+ tokens.append(_argv_text(body['text'], 'text', MAX_NOTE))
1584
+ elif op == 'edit':
1585
+ severity = body['severity'] if 'severity' in body else None
1586
+ if severity is not None and severity not in _FINDING_SEVERITIES:
1587
+ raise BadBody('severity must be P0, P1, P2 or P3')
1588
+ text = _optional_text(body, 'text', MAX_EDIT_TEXT, _file_text)
1589
+ if severity is None and text is None:
1590
+ raise BadBody('edit needs a severity or text')
1591
+ if severity is not None:
1592
+ tokens.extend(('--severity', severity))
1593
+ if text is not None:
1594
+ file = ('--text-file', text)
1595
+ return fps, tokens, file
1596
+
1597
+
1598
+ def _note_argv(root, fp, text):
1599
+ """`note REPO FP TEXT`. Text that starts with '-' sits after `--`, with the options in front of that."""
1600
+ if text.startswith('-'):
1601
+ return ['findings', 'note', '--actor', 'ui', '--json', root, fp, '--', text]
1602
+ return ['findings', 'note', root, fp, text, '--actor', 'ui', '--json']
1603
+
1604
+
1605
+ def _write_payload(directory, flag, text):
1606
+ """`[flag, path]` for `text` in `directory` (mode 0600). The caller creates and removes the directory."""
1607
+ path = os.path.join(directory, 'payload')
1608
+ handle = os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), 'w', encoding='utf-8')
1609
+ try:
1610
+ handle.write(text)
1611
+ finally:
1612
+ handle.close()
1613
+ return [flag, path]
1614
+
1615
+
1616
+ def _findings_action(ctx):
1617
+ """POST `{fps, …}`: `forge findings <op> <project root> … --actor ui --json`.
1618
+
1619
+ The path's last segment is the op (fix, dismiss, reopen, to-file, dup, tag, note, edit).
1620
+ A draft body and an edit's replacement text go to a private temp file (`--body-file`,
1621
+ `--text-file`). `findings_lock` makes a second write 409 `busy`. Exit 3 is 409 with the CLI's
1622
+ message. A successful call drops the project screen's issues listings and its run cache.
1623
+ """
1624
+ from forge_ui import projects
1625
+ op = ctx.parts[0]
1626
+ ctx.route = 'findings ' + op
1627
+ try:
1628
+ body = _body_object(ctx, _FINDINGS_FIELDS[op])
1629
+ fps, tokens, file = _findings_request(op, body)
1630
+ except BadBody as exc:
1631
+ return _invalid(str(exc))
1632
+ # the identity root when it exists, else a checkout still on disk (as the triage routes): a project whose main
1633
+ # checkout was removed keeps a linked worktree the CLI can resolve the repository from
1634
+ root = _triage_repo(ctx)
1635
+ if not isinstance(root, str):
1636
+ return root
1637
+ lock = _server_lock(ctx.server, 'findings_lock')
1638
+ if not lock.acquire(blocking=False):
1639
+ return 409, {'error': 'busy'}
1640
+ directory = None
1641
+ try:
1642
+ file_argv = []
1643
+ if file is not None:
1644
+ directory = tempfile.mkdtemp(prefix='forge-ui-findings-')
1645
+ file_argv = _write_payload(directory, *file)
1646
+ if op == 'note':
1647
+ argv = _note_argv(root, fps[0], tokens[0])
1648
+ else:
1649
+ argv = ['findings', op, root, *fps, *tokens, *file_argv, '--actor', 'ui', '--json']
1650
+ status, answer = ctx.call(*argv)
1651
+ if status == 200:
1652
+ invalidate_findings(ctx.server)
1653
+ return status, answer
1654
+ finally:
1655
+ if directory is not None:
1656
+ shutil.rmtree(directory, ignore_errors=True)
1657
+ lock.release()
1658
+
1659
+
1660
+ # ------------------------------------------------------- triage routes and spec check (#161)
1661
+
1662
+ _SPEC_RE = re.compile(r'^[A-Za-z0-9._:/@+-]+$')
1663
+ # A triage number. Nine digits is past the directory cap; a longer digit string is not an id.
1664
+ _TRIAGE_N = re.compile(r'^[0-9]{1,9}$')
1665
+ _PROPOSAL_ID = re.compile(r'^p[0-9]{1,4}$')
1666
+ _RESOLVED_KEY = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
1667
+ _MAX_SPEC = 120
1668
+ _MAX_TRIAGE_FINDINGS = 2000
1669
+ # control.py is ui/forge_ui/control.py; the skill root is three directories up, as forge-control.py's
1670
+ # SKILL is two up from scripts/. Doctor is that script, never a model and never a shell string.
1671
+ _DISPATCH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))),
1672
+ 'scripts', 'forge-dispatch.sh')
1673
+
1674
+
1675
+ def _triage_spec(value):
1676
+ """A triage or doctor spec: 1 to 120 characters of the dispatch spec alphabet."""
1677
+ if not isinstance(value, str) or not 1 <= len(value) <= _MAX_SPEC or not _SPEC_RE.fullmatch(value):
1678
+ raise BadBody('spec must be 1 to 120 characters of letters, digits and . _ : / @ + -')
1679
+ return value
1680
+
1681
+
1682
+ def _max_findings(body):
1683
+ """None when the body omits it. JSON true is a bool, and a bool is an int, so the type is exact."""
1684
+ if 'max_findings' not in body:
1685
+ return None
1686
+ value = body['max_findings']
1687
+ if type(value) is not int or not 1 <= value <= _MAX_TRIAGE_FINDINGS:
1688
+ raise BadBody(f'max_findings must be an integer from 1 to {_MAX_TRIAGE_FINDINGS}')
1689
+ return value
1690
+
1691
+
1692
+ def _triage_n(value):
1693
+ if not isinstance(value, str) or not _TRIAGE_N.fullmatch(value):
1694
+ raise BadBody('n must be a decimal integer')
1695
+ return value
1696
+
1697
+
1698
+ def _proposal_id(value):
1699
+ if not isinstance(value, str) or not _PROPOSAL_ID.fullmatch(value):
1700
+ raise BadBody('pid must match ^p[0-9]{1,4}$')
1701
+ return value
1702
+
1703
+
1704
+ def _proposal_hash(value):
1705
+ if not isinstance(value, str) or not FP_RE.fullmatch(value):
1706
+ raise BadBody('hash must be 12 lowercase hex characters')
1707
+ return value
1708
+
1709
+
1710
+ def _plan_dir(body):
1711
+ """None when the field is absent. Present means an absolute path, whether or not it exists yet."""
1712
+ if 'plan_dir' not in body:
1713
+ return None
1714
+ value = body['plan_dir']
1715
+ if not isinstance(value, str) or not os.path.isabs(value) or not _no_control_chars(value):
1716
+ raise BadBody('plan_dir must be an absolute path')
1717
+ return value
1718
+
1719
+
1720
+ def _triage_target(ctx):
1721
+ """`(n, pid)` from the path. BadBody when either segment is not the shape the CLI takes."""
1722
+ n, pid = ctx.parts[:2]
1723
+ return _triage_n(n), _proposal_id(pid)
1724
+
1725
+
1726
+ def _triage_repo(ctx):
1727
+ """The project's identity root when that folder exists, else the first existing checkout.
1728
+
1729
+ `checkouts` lists the root first, then the other paths. A string is the repo to pass to the CLI.
1730
+ A tuple is the error response: 404 `not found` for an unknown project, 404 `no checkout` when
1731
+ the project has no directory left on this machine.
1732
+ """
1733
+ from forge_ui import projects
1734
+ found = projects.screen(ctx.server).projects(ctx.server.catalog).get(ctx.key)
1735
+ if not isinstance(found, dict):
1736
+ return 404, {'error': 'not found'}
1737
+ root = found.get('root')
1738
+ if isinstance(root, str) and root and os.path.isdir(root):
1739
+ return root
1740
+ if not isinstance(root, str) or not isinstance(found.get('runs'), list):
1741
+ return 404, {'error': 'no checkout'}
1742
+ existing = [c['path'] for c in projects.checkouts(found) if c['exists']]
1743
+ if not existing:
1744
+ return 404, {'error': 'no checkout'}
1745
+ return existing[0]
1746
+
1747
+
1748
+ def _triage_repo_or_response(ctx):
1749
+ repo = _triage_repo(ctx)
1750
+ return (None, repo) if isinstance(repo, str) else (repo, None)
1751
+
1752
+
1753
+ def _no_triage(body):
1754
+ """True when triage-status refused because no triage has run (or this number does not exist)."""
1755
+ if not isinstance(body, dict):
1756
+ return False
1757
+ parts = [str(body.get('detail') or '')]
1758
+ result = body.get('result')
1759
+ if isinstance(result, dict):
1760
+ parts.append(str(result.get('error') or ''))
1761
+ return 'no triage' in '\n'.join(parts).lower()
1762
+
1763
+
1764
+ def _findings_write(ctx, argv):
1765
+ """One `forge findings` write under `findings_lock`. 409 `busy` when a write already holds it.
1766
+
1767
+ A 200 drops the project screen's findings cache, as a finding-record write does. A refusal
1768
+ wrote nothing, so the cache stays.
1769
+ """
1770
+ lock = _server_lock(ctx.server, 'findings_lock')
1771
+ if not lock.acquire(blocking=False):
1772
+ return 409, {'error': 'busy'}
1773
+ try:
1774
+ status, answer = ctx.call(*argv)
1775
+ if status == 200:
1776
+ invalidate_findings(ctx.server)
1777
+ return status, answer
1778
+ finally:
1779
+ lock.release()
1780
+
1781
+
1782
+ def _triage_start(ctx):
1783
+ """POST `{spec, max_findings?}`: `forge findings triage <root> --spec S [--max-findings N]
1784
+ --detach --actor ui --json`.
1785
+
1786
+ `--detach` makes the CLI print `{triage, state}` and return at once. Exit 3 is 409 with the
1787
+ CLI's message. This is the one route whose CLI starts a model; the route itself does not.
1788
+ """
1789
+ ctx.route = 'triage'
1790
+ try:
1791
+ body = _body_object(ctx, ('spec', 'max_findings'))
1792
+ spec = _triage_spec(body.get('spec'))
1793
+ limit = _max_findings(body)
1794
+ except BadBody as exc:
1795
+ return _invalid(str(exc))
1796
+ error, repo = _triage_repo_or_response(ctx)
1797
+ if error:
1798
+ return error
1799
+ argv = ['findings', 'triage', repo]
1800
+ _append_option(argv, 'spec', spec)
1801
+ if limit is not None:
1802
+ argv += ['--max-findings', str(limit)]
1803
+ argv += ['--detach', '--actor', 'ui', '--json']
1804
+ return ctx.call(*argv)
1805
+
1806
+
1807
+ def _triage_get(ctx):
1808
+ """GET `[?n=N]`: `{state, proposals}` from `triage-status` and `proposals`, each time, uncached.
1809
+
1810
+ No triage yet (the status command exits 3 with that message) is 200 `{state: null, proposals: null}`.
1811
+ A triage with no proposals yet leaves `proposals` null and still returns the state. A read: no lock.
1812
+ """
1813
+ ctx.route = 'triage'
1814
+ try:
1815
+ params = _query_params(ctx.query, ('n',))
1816
+ n = _triage_n(params['n']) if 'n' in params else None
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
+ number = [n] if n else []
1823
+ status, state = ctx.call('findings', 'triage-status', repo, *number, '--json')
1824
+ if status != 200:
1825
+ if status == 409 and _no_triage(state):
1826
+ return 200, {'state': None, 'proposals': None}
1827
+ return status, state
1828
+ pstatus, proposals = ctx.call('findings', 'proposals', repo, *number, '--json')
1829
+ if pstatus == 409:
1830
+ proposals = None
1831
+ elif pstatus != 200:
1832
+ return pstatus, proposals
1833
+ return 200, {'state': state, 'proposals': proposals}
1834
+
1835
+
1836
+ def _triage_apply(ctx):
1837
+ """POST `{hash, plan_dir?}`: `forge findings apply <root> N PID --approve HASH [--plan-dir D]
1838
+ --actor ui --json`. Exit 3 is 409 with the CLI's message."""
1839
+ ctx.route = 'triage apply'
1840
+ try:
1841
+ n, pid = _triage_target(ctx)
1842
+ body = _body_object(ctx, ('hash', 'plan_dir'))
1843
+ digest = _proposal_hash(body.get('hash'))
1844
+ plan_dir = _plan_dir(body)
1845
+ except BadBody as exc:
1846
+ return _invalid(str(exc))
1847
+ error, repo = _triage_repo_or_response(ctx)
1848
+ if error:
1849
+ return error
1850
+ argv = ['findings', 'apply', repo, n, pid, '--approve', digest]
1851
+ if plan_dir is not None:
1852
+ argv += ['--plan-dir', plan_dir]
1853
+ argv += ['--actor', 'ui', '--json']
1854
+ return _findings_write(ctx, argv)
1855
+
1856
+
1857
+ def _triage_reject(ctx):
1858
+ """POST `{reason?}`: `forge findings reject <root> N PID [--reason T] --actor ui --json`.
1859
+
1860
+ The reason is at most 500 characters. Exit 3 is 409 with the CLI's message."""
1861
+ ctx.route = 'triage reject'
1862
+ try:
1863
+ n, pid = _triage_target(ctx)
1864
+ body = _body_object(ctx, ('reason',))
1865
+ reason = _optional_reason(body.get('reason'))
1866
+ except BadBody as exc:
1867
+ return _invalid(str(exc))
1868
+ error, repo = _triage_repo_or_response(ctx)
1869
+ if error:
1870
+ return error
1871
+ argv = ['findings', 'reject', repo, n, pid]
1872
+ if reason:
1873
+ _append_option(argv, 'reason', reason)
1874
+ argv += ['--actor', 'ui', '--json']
1875
+ return _findings_write(ctx, argv)
1876
+
1877
+
1878
+ def _spec_query(raw):
1879
+ """The query of GET /api/specs/check. A spec may contain `+`, which form decoding would turn into
1880
+ a space, and a spec has no spaces, so a literal `+` here is a plus."""
1881
+ return _query_params((raw or '').replace('+', '%2B'), ('spec',))
1882
+
1883
+
1884
+ def _resolved_pairs(text):
1885
+ """The `key=value` lines of a doctor's stdout. The prose line after them is not one of them."""
1886
+ resolved = {}
1887
+ for raw in text.splitlines():
1888
+ line = raw.strip()
1889
+ if '=' not in line:
1890
+ continue
1891
+ key, value = line.split('=', 1)
1892
+ if _RESOLVED_KEY.fullmatch(key.strip()):
1893
+ resolved[key.strip()] = value.strip()
1894
+ return resolved
1895
+
1896
+
1897
+ def _doctor_error(result):
1898
+ """The refusal line. Doctor prints it on stderr (`forge: …`); stdout may hold a partial block."""
1899
+ for text in (result.stderr, result.stdout):
1900
+ for line in text.splitlines():
1901
+ line = line.strip()
1902
+ if line:
1903
+ return line[:REFUSAL_MAX]
1904
+ return f'the doctor exited {result.code}'
1905
+
1906
+
1907
+ def _specs_check(ctx):
1908
+ """GET `?spec=S`: `{ok: true, resolved}` or `{ok: false, error}` from
1909
+ `bash scripts/forge-dispatch.sh doctor --spec S --role side`.
1910
+
1911
+ The same argv forge-control's doctor uses, with the role `side`. An argv list, not a shell.
1912
+ A spec that fails the same check as triage start is 400 and the doctor is not run. A doctor
1913
+ refusal is 200 with `ok: false`: the check finished. Read-only servers answer this GET.
1914
+ """
1915
+ ctx.route = 'specs check'
1916
+ try:
1917
+ params = _spec_query(ctx.query)
1918
+ if 'spec' not in params:
1919
+ raise BadBody('spec is required')
1920
+ spec = _triage_spec(params['spec'])
1921
+ except BadBody as exc:
1922
+ return _invalid(str(exc))
1923
+ result = run_cli(['bash', _DISPATCH, 'doctor', '--spec', spec, '--role', 'side'], ctx.timeout or TIMEOUT_S)
1924
+ if result.timed_out:
1925
+ return 504, {'error': 'timeout', 'detail': TIMEOUT_DETAIL}
1926
+ if result.error:
1927
+ return 502, {'error': 'bad gateway', 'detail': result.error[:DETAIL_MAX]}
1928
+ if result.code == 0:
1929
+ return 200, {'ok': True, 'resolved': _resolved_pairs(result.stdout)}
1930
+ return 200, {'ok': False, 'error': _doctor_error(result)}
1931
+
1932
+
1288
1933
  ROUTES = [
1289
1934
  ('GET', re.compile(r'/api/runs/([0-9a-f]{12})/controls'), _show),
1290
1935
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/controls'), _change),
@@ -1301,6 +1946,11 @@ ROUTES = [
1301
1946
  ('POST', re.compile(r'/api/worktrees/remove()'), _worktrees_remove),
1302
1947
  ('POST', re.compile(r'/api/storage/compact()'), _storage_compact),
1303
1948
  ('POST', re.compile(r'/api/projects/([0-9a-f]{8})/memories/forget'), _memories_forget),
1949
+ ('POST', re.compile(r'/api/projects/([0-9a-f]{8})/memories/add'), _memories_add),
1950
+ ('POST', re.compile(r'/api/projects/([0-9a-f]{8})/memories/edit'), _memories_edit),
1951
+ ('POST', re.compile(r'/api/projects/([0-9a-f]{8})/triage/([^/]+)/([^/]+)/apply'), _triage_apply),
1952
+ ('POST', re.compile(r'/api/projects/([0-9a-f]{8})/triage/([^/]+)/([^/]+)/reject'), _triage_reject),
1953
+ ('POST', re.compile(r'/api/projects/([0-9a-f]{8})/triage'), _triage_start),
1304
1954
  ('GET', re.compile(r'/api/config/profiles()'), _config_profiles_get),
1305
1955
  ('POST', re.compile(r'/api/config/profiles()'), _config_profiles_set),
1306
1956
  ('GET', re.compile(r'/api/config()'), _config_get),
@@ -1310,8 +1960,11 @@ ROUTES = [
1310
1960
  ('GET', re.compile(r'/api/storage()'), _storage),
1311
1961
  ('GET', re.compile(r'/api/projects()'), _projects),
1312
1962
  ('GET', re.compile(r'/api/projects/([0-9a-f]{8})'), _project),
1963
+ ('POST', _FINDINGS_PATH, _findings_action),
1313
1964
  ('GET', re.compile(r'/api/projects/([0-9a-f]{8})/findings'), _project_findings),
1314
1965
  ('GET', re.compile(r'/api/projects/([0-9a-f]{8})/memories'), _project_memories),
1966
+ ('GET', re.compile(r'/api/projects/([0-9a-f]{8})/triage'), _triage_get),
1967
+ ('GET', re.compile(r'/api/specs/check()'), _specs_check),
1315
1968
  ]
1316
1969
 
1317
1970