@giamme/forge 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +19 -2
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +25 -1
  6. package/docs/commands.md +217 -18
  7. package/docs/decomposed-runs.md +114 -1
  8. package/docs/development.md +2 -1
  9. package/docs/forge-ui.md +138 -18
  10. package/docs/memory.md +25 -4
  11. package/docs/models.md +8 -0
  12. package/docs/reviews.md +122 -0
  13. package/forge +26 -3
  14. package/package.json +2 -1
  15. package/references/dataset.md +20 -1
  16. package/references/decompose.md +641 -41
  17. package/references/harnesses.md +18 -3
  18. package/references/memory.md +30 -5
  19. package/references/planning.md +43 -14
  20. package/references/ui.md +53 -6
  21. package/registry.tsv +8 -3
  22. package/scripts/forge-brief.py +88 -3
  23. package/scripts/forge-compare.py +4 -3
  24. package/scripts/forge-contract.py +202 -27
  25. package/scripts/forge-control.py +117 -5
  26. package/scripts/forge-dispatch.sh +34 -5
  27. package/scripts/forge-findings.py +675 -0
  28. package/scripts/forge-group.py +496 -0
  29. package/scripts/forge-groups.py +89 -0
  30. package/scripts/forge-handoff.py +1128 -0
  31. package/scripts/forge-issues.py +228 -97
  32. package/scripts/forge-lib-group.sh +641 -0
  33. package/scripts/forge-lib-plans.sh +339 -3
  34. package/scripts/forge-lib-task.sh +197 -4
  35. package/scripts/forge-memory.sh +711 -17
  36. package/scripts/forge-parallel.sh +721 -38
  37. package/scripts/forge-planner.py +104 -8
  38. package/scripts/forge-route.py +190 -12
  39. package/scripts/forge-runs.py +9 -5
  40. package/scripts/forge-schedule.py +417 -52
  41. package/scripts/forge-solo.sh +2 -0
  42. package/scripts/forge-sweep.py +199 -44
  43. package/scripts/forge-worktrees.py +243 -0
  44. package/scripts/forge_brief/__init__.py +294 -50
  45. package/scripts/forge_brief/answers.py +58 -11
  46. package/scripts/forge_brief/proposals.py +1630 -0
  47. package/scripts/forge_dataset/efforts.py +4 -3
  48. package/scripts/forge_dataset/export.py +24 -12
  49. package/scripts/forge_dataset/facts.py +5 -3
  50. package/scripts/forge_dataset/forecast.py +8 -18
  51. package/scripts/forge_dataset/harvest.py +204 -9
  52. package/scripts/forge_dataset/history.py +11 -6
  53. package/scripts/forge_dataset/importer.py +65 -1
  54. package/scripts/forge_dataset/names.py +66 -0
  55. package/scripts/forge_dataset/reviewers.py +5 -2
  56. package/scripts/forge_dataset/risk.py +6 -3
  57. package/scripts/forge_dataset/routing.py +6 -1
  58. package/scripts/forge_findings/__init__.py +17 -0
  59. package/scripts/forge_findings/apply.py +441 -0
  60. package/scripts/forge_findings/status.py +43 -0
  61. package/scripts/forge_findings/store.py +583 -0
  62. package/scripts/forge_findings/tags.py +53 -0
  63. package/scripts/forge_findings/triage.py +603 -0
  64. package/scripts/forge_groups/__init__.py +308 -0
  65. package/scripts/forge_groups/attribute.py +289 -0
  66. package/scripts/forge_groups/review.py +286 -0
  67. package/scripts/forge_identity.py +327 -0
  68. package/scripts/forge_memory_list.py +7 -3
  69. package/scripts/forge_owner.py +152 -0
  70. package/scripts/forge_side/__init__.py +228 -38
  71. package/ui/docs/api.md +303 -29
  72. package/ui/forge_ui/control.py +1018 -6
  73. package/ui/forge_ui/executions.py +8 -1
  74. package/ui/forge_ui/export.py +31 -4
  75. package/ui/forge_ui/groups.py +264 -0
  76. package/ui/forge_ui/models.py +70 -8
  77. package/ui/forge_ui/projects.py +209 -22
  78. package/ui/forge_ui/reader.py +262 -19
  79. package/ui/forge_ui/server.py +4 -0
  80. package/ui/forge_ui/static/app.js +93 -13
  81. package/ui/forge_ui/static/briefview.js +350 -47
  82. package/ui/forge_ui/static/diffview.js +86 -1
  83. package/ui/forge_ui/static/findingsactions.js +201 -0
  84. package/ui/forge_ui/static/groupsview.js +332 -0
  85. package/ui/forge_ui/static/index.html +3 -0
  86. package/ui/forge_ui/static/panel.js +127 -7
  87. package/ui/forge_ui/static/projectsview.js +764 -30
  88. package/ui/forge_ui/static/runmodel.js +14 -3
  89. package/ui/forge_ui/static/storageview.js +91 -10
  90. package/ui/forge_ui/static/style.css +138 -5
  91. package/ui/forge_ui/static/triageview.js +423 -0
  92. package/ui/forge_ui/static/worktreesview.js +233 -12
  93. package/ui/forge_ui/storage.py +14 -0
@@ -5,15 +5,19 @@ The server never writes a run dir, a repo or forge's config itself. A write is o
5
5
  this module holds the route table, the body validation, the call and the mapping of the CLI's
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
- a brief answer writes the answer text the same way. Every other call has no stdin.
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. 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.
9
11
  """
10
12
  from __future__ import annotations
11
13
 
12
14
  import json
13
15
  import os
14
16
  import re
17
+ import shutil
15
18
  import signal
16
19
  import subprocess
20
+ import tempfile
17
21
  import threading
18
22
  import time
19
23
  import urllib.parse
@@ -25,10 +29,35 @@ MAX_FIELD = 256
25
29
  ISSUES_LIST_TIMEOUT_S = 120 # a listing asks gh for the filed state
26
30
  ISSUES_FILE_TIMEOUT_S = 300 # filing up to 25 issues
27
31
  DELETE_TIMEOUT_S = 900 # removing worktrees, branches and the archive can be slow
32
+ COMPACT_TIMEOUT_S = 900 # `forge runs compact` can take minutes on a large store
33
+ MAX_PATHS = 200 # worktrees to remove, and memory keys to forget, in one request
34
+ MAX_TASK_ANSWER = 8000 # the answer to a task that waits for input, in characters, after stripping
35
+ # One brief model call, end to end. proposals.propose and forge_brief.write pass 900s to
36
+ # forge_side.run, which waits that plus _DISPATCH_GRACE_S (30) before it returns its own
37
+ # timeout. The extra minute is the CLI storing the result and exiting, so a call that uses
38
+ # its whole wait is a refusal on the page and not a process this route killed.
39
+ _BRIEF_MODEL_S = 900
40
+ _BRIEF_DISPATCH_GRACE_S = 30
41
+ _BRIEF_CALL_S = _BRIEF_MODEL_S + _BRIEF_DISPATCH_GRACE_S
42
+ _BRIEF_SETTLE_S = 60
43
+ BRIEF_PROPOSE_TIMEOUT_S = _BRIEF_CALL_S + _BRIEF_SETTLE_S
44
+ # apply may spend 120s refreshing waves.tsv, then regenerates each unstarted affected task:
45
+ # one model call, in order. The budget is forty of those calls (twice the planner's task
46
+ # ceiling) plus the waves refresh. A faster call releases the run lock when the CLI exits.
47
+ # Past this, a regeneration that is still running is killed, the same way a 60s cap was.
48
+ _WAVES_REFRESH_S = 120
49
+ _APPLY_TASKS = 40
50
+ BRIEF_APPLY_TIMEOUT_S = _WAVES_REFRESH_S + _APPLY_TASKS * _BRIEF_CALL_S + _BRIEF_SETTLE_S
28
51
  MAX_FPS = 25
29
52
  MAX_LABELS = 5
30
53
  MAX_LABEL = 50
31
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
32
61
  MAX_CONFIG_VALUE = 4096
33
62
  MAX_DECIDE_VALUE = 256
34
63
  # The profile object written to `forge config profile … --file -`. The HTTP body is already capped
@@ -38,10 +67,16 @@ MAX_PROFILE_BODY = 64 * 1024
38
67
  # strips control characters; this bound is the one the route enforces before that call.
39
68
  MAX_ANSWER = 4096
40
69
  _QID = re.compile(r'^q[0-9]+$')
70
+ # The page accepts the same width the route captures. The CLI's own ids are p1, p2, …; p0 still reaches it.
71
+ _PID = re.compile(r'^p[0-9]{1,6}$')
72
+ _TASK_ID = re.compile(r'^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$')
41
73
  _PROFILE_NAME = re.compile(r'^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$')
42
74
  _PROFILE_KEY = re.compile(r'^(routing|policy)\.[a-z_.]+$')
43
75
  _PROFILE_ACTIONS = ('create', 'edit', 'set', 'unset', 'rm', 'use')
44
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')
45
80
  # Mirrored from forge_decide.GATES and MODES. The ui tests do not put scripts/ on the path, so this
46
81
  # module does not import forge_decide; ConfigTests.test_decide_names_match_forge_decide keeps them equal.
47
82
  DECIDE_GATES = ('drift', 'forward', 'prompt', 'memory-curate', 'memory-slice', 'memory-stale',
@@ -369,6 +404,102 @@ def _brief_answer(ctx):
369
404
  stdin=stdin, json_stdout=False))
370
405
 
371
406
 
407
+ def _brief_pid(ctx):
408
+ pid = ctx.parts[0] if ctx.parts else ''
409
+ if not isinstance(pid, str) or not _PID.fullmatch(pid):
410
+ raise BadBody('pid must match ^p[0-9]{1,6}$')
411
+ return pid
412
+
413
+
414
+ def _optional_reason(value):
415
+ """None when the reason is absent, null or blank. BadBody when it is not acceptable text.
416
+
417
+ Newline and tab are allowed, as on a dismissal. A leading '-' is safe: the CLI gets `--reason=`.
418
+ """
419
+ if value is None:
420
+ return None
421
+ if not isinstance(value, str) or len(value) > MAX_REASON or not _no_control_chars(value.replace('\n', ' ').replace('\t', ' ')):
422
+ raise BadBody(f'reason must be a text of at most {MAX_REASON} characters, without control characters (newline and tab are allowed)')
423
+ return value.strip() or None
424
+
425
+
426
+ def _plan_or_404(ctx):
427
+ path = ctx.locate(('plan',))
428
+ if path is None:
429
+ return None
430
+ return path
431
+
432
+
433
+ def _brief_apply(ctx):
434
+ """POST `{hash}`: `forge brief apply <plan> <pid> --approve <hash> --actor ui`.
435
+
436
+ Exit 0 prints text (the files written, the notes, and the plan-again line), so the body is that text.
437
+ Regeneration is one brief model call per unstarted affected task, so the wait is
438
+ `BRIEF_APPLY_TIMEOUT_S` and not the 60s default. The plan files are written before that
439
+ regeneration; killing it here would leave it half-done and drop the text the page shows.
440
+ """
441
+ ctx.route = 'brief apply'
442
+ try:
443
+ if not isinstance(ctx.body, dict):
444
+ raise BadBody('body must be a JSON object')
445
+ pid = _brief_pid(ctx)
446
+ _check_fields(ctx.body, ('hash',))
447
+ digest = _text(ctx.body, 'hash')
448
+ except BadBody as exc:
449
+ return _invalid(str(exc))
450
+ path = _plan_or_404(ctx)
451
+ if path is None:
452
+ return 404, {'error': 'not found'}
453
+ return ctx.locked(lambda: ctx.call('brief', 'apply', path, pid, '--approve', digest, '--actor', 'ui',
454
+ json_stdout=False, limit=BRIEF_APPLY_TIMEOUT_S))
455
+
456
+
457
+ def _brief_reject(ctx):
458
+ """POST `{reason}`: `forge brief reject <plan> <pid> [--reason=TEXT] --actor ui`. The reason may be empty."""
459
+ ctx.route = 'brief reject'
460
+ try:
461
+ if not isinstance(ctx.body, dict):
462
+ raise BadBody('body must be a JSON object')
463
+ pid = _brief_pid(ctx)
464
+ _check_fields(ctx.body, ('reason',))
465
+ reason = _optional_reason(ctx.body.get('reason'))
466
+ except BadBody as exc:
467
+ return _invalid(str(exc))
468
+ path = _plan_or_404(ctx)
469
+ if path is None:
470
+ return 404, {'error': 'not found'}
471
+ argv = ['brief', 'reject', path, pid]
472
+ if reason:
473
+ argv.append('--reason=' + reason)
474
+ argv += ['--actor', 'ui']
475
+ return ctx.locked(lambda: ctx.call(*argv, json_stdout=False))
476
+
477
+
478
+ def _brief_propose(ctx):
479
+ """POST `{task, qid}`: `forge brief propose <plan> <task> <qid> --actor ui` for a parked wave or plan question.
480
+
481
+ One brief-change model call. The wait is `BRIEF_PROPOSE_TIMEOUT_S`, past the CLI's own 900s.
482
+ """
483
+ ctx.route = 'brief propose'
484
+ try:
485
+ if not isinstance(ctx.body, dict):
486
+ raise BadBody('body must be a JSON object')
487
+ _check_fields(ctx.body, ('task', 'qid'))
488
+ task = _text(ctx.body, 'task')
489
+ if not _TASK_ID.fullmatch(task):
490
+ raise BadBody('task must be a task id')
491
+ qid = _text(ctx.body, 'qid')
492
+ if not _QID.fullmatch(qid):
493
+ raise BadBody('qid must match ^q[0-9]+$')
494
+ except BadBody as exc:
495
+ return _invalid(str(exc))
496
+ path = _plan_or_404(ctx)
497
+ if path is None:
498
+ return 404, {'error': 'not found'}
499
+ return ctx.locked(lambda: ctx.call('brief', 'propose', path, task, qid, '--actor', 'ui',
500
+ json_stdout=False, limit=BRIEF_PROPOSE_TIMEOUT_S))
501
+
502
+
372
503
  # ----------------------------------------------------------------- issues, delete and config routes
373
504
 
374
505
  def _invalid(detail):
@@ -882,11 +1013,18 @@ def _project_findings(ctx):
882
1013
  refresh = _bit(_query_params(ctx.query, ('refresh',)), 'refresh')
883
1014
  except BadBody as exc:
884
1015
  return _invalid(str(exc))
885
- # --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
+
886
1025
  found = projects.screen(ctx.server).findings(
887
- ctx.server.catalog, ctx.key, lambda: _project_call(ctx, 'dataset', 'history', '--json'),
888
- lambda path: _project_call(ctx, 'issues', path, '--json', '--offline', '--all-runs', '--include-plausible',
889
- '--include-dismissed'), refresh=refresh)
1026
+ ctx.server.catalog, ctx.key, lambda: _project_call(ctx, 'dataset', 'history', '--json'), listing,
1027
+ refresh=refresh)
890
1028
  return (404, {'error': 'not found'}) if found is None else (200, found)
891
1029
 
892
1030
 
@@ -913,7 +1051,7 @@ def _storage(ctx):
913
1051
  refresh = _bit(params, 'refresh')
914
1052
  except BadBody as exc:
915
1053
  return _invalid(str(exc))
916
- return 200, storage.screen(ctx.server).answer(refresh=refresh)
1054
+ return 200, storage.with_keys(storage.screen(ctx.server).answer(refresh=refresh), ctx.server.catalog.keys())
917
1055
 
918
1056
 
919
1057
  def _worktrees(ctx):
@@ -933,15 +1071,886 @@ def _worktrees(ctx):
933
1071
  return 200, worktrees.screen(ctx.server).answer(ctx.server.catalog, history, refresh=refresh)
934
1072
 
935
1073
 
1074
+ # ----------------------------------------------------------------- remove, forget, compact, answer (#147)
1075
+
1076
+ def _body_object(ctx, allowed):
1077
+ if not isinstance(ctx.body, dict):
1078
+ raise BadBody('body must be a JSON object')
1079
+ _check_fields(ctx.body, allowed)
1080
+ return ctx.body
1081
+
1082
+
1083
+ def _string_list(value, name, check):
1084
+ if not isinstance(value, list) or not 1 <= len(value) <= MAX_PATHS:
1085
+ raise BadBody(f'{name} must be a list of 1 to {MAX_PATHS} strings')
1086
+ for item in value:
1087
+ if not isinstance(item, str) or not item or len(item) > 4096 or not _no_control_chars(item) or not check(item):
1088
+ raise BadBody(f'{name} holds a value that is not acceptable')
1089
+ return list(dict.fromkeys(value))
1090
+
1091
+
1092
+ def invalidate_worktrees(server):
1093
+ """The next GET /api/worktrees reads git and the run dirs again."""
1094
+ from forge_ui import worktrees
1095
+ screen = worktrees.screen(server)
1096
+ with screen.lock:
1097
+ screen.result = None
1098
+
1099
+
1100
+ def invalidate_storage(server):
1101
+ """The next GET /api/storage measures again; the answer it has stays on show until then."""
1102
+ from forge_ui import storage
1103
+ screen = storage.screen(server)
1104
+ with screen.lock:
1105
+ if screen.result is not None:
1106
+ screen.result = dict(screen.result, computed=0)
1107
+
1108
+
1109
+ def invalidate_memories(server):
1110
+ """The next GET of a project's memories reads the CLI again (the project screen's `memory` answers)."""
1111
+ from forge_ui import projects
1112
+ screen = projects.screen(server)
1113
+ with screen.lock:
1114
+ for key in [k for k in screen.cli if isinstance(k, tuple) and k and k[0] == 'memory']:
1115
+ del screen.cli[key]
1116
+
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
+
1128
+ def _worktrees_remove(ctx):
1129
+ """POST `{paths, branches?, dry_run?}`: `forge worktrees rm <paths> [--branches] [--dry-run] --json --actor ui`.
1130
+
1131
+ Each path must be one of the rows of the Worktrees screen. Exit 4 (a row failed) is a 200 with
1132
+ `ok: false`: the page needs the rows to say which one failed.
1133
+ """
1134
+ from forge_ui import worktrees
1135
+ ctx.route = 'worktrees remove'
1136
+ try:
1137
+ body = _body_object(ctx, ('paths', 'branches', 'dry_run'))
1138
+ paths = _string_list(body.get('paths'), 'paths', os.path.isabs)
1139
+ branches = _flag(body, 'branches')
1140
+ dry = _flag(body, 'dry_run')
1141
+ except BadBody as exc:
1142
+ return _invalid(str(exc))
1143
+
1144
+ def history():
1145
+ status, found = ctx.call('dataset', 'worktrees', '--json')
1146
+ return found if status == 200 else None
1147
+
1148
+ def listed(refresh):
1149
+ answer = worktrees.screen(ctx.server).answer(ctx.server.catalog, history, refresh=refresh)
1150
+ return {row.get('path') for row in answer.get('rows') or []}
1151
+ known = listed(False)
1152
+ if not all(path in known for path in paths):
1153
+ known = listed(True)
1154
+ missing = [path for path in paths if path not in known]
1155
+ if missing:
1156
+ return _invalid(f'{missing[0]!r} is not a worktree the Worktrees screen lists')
1157
+ lock = _server_lock(ctx.server, 'worktrees_lock')
1158
+ if not lock.acquire(blocking=False):
1159
+ return 409, {'error': 'busy'}
1160
+ try:
1161
+ argv = ['worktrees', 'rm', *paths]
1162
+ if branches:
1163
+ argv.append('--branches')
1164
+ if dry:
1165
+ argv.append('--dry-run')
1166
+ status, answer = ctx.call(*argv, '--json', '--actor', 'ui', limit=DELETE_TIMEOUT_S)
1167
+ if status == 500 and isinstance(answer.get('result'), dict) and isinstance(answer['result'].get('rows'), list):
1168
+ status, answer = 200, dict(answer['result'], ok=False)
1169
+ if not dry:
1170
+ invalidate_worktrees(ctx.server)
1171
+ invalidate_storage(ctx.server)
1172
+ return status, answer
1173
+ finally:
1174
+ lock.release()
1175
+
1176
+
1177
+ _MEMORY_KEY = re.compile(r'^[^:\s-][^:]*:.+$')
1178
+
1179
+
1180
+ def _forget_keys(value):
1181
+ return _string_list(value, 'keys', lambda key: len(key) <= MAX_FIELD and bool(_MEMORY_KEY.match(key)))
1182
+
1183
+
1184
+ def _memories_forget(ctx):
1185
+ """POST `{keys, dry_run?, path?}`: `forge memory forget <checkout> <keys> [--dry-run] --json --actor ui`,
1186
+ once per existing checkout of the project (or only the one `path` names)."""
1187
+ from forge_ui import projects
1188
+ ctx.route = 'memories forget'
1189
+ try:
1190
+ body = _body_object(ctx, ('keys', 'dry_run', 'path'))
1191
+ keys = _forget_keys(body.get('keys'))
1192
+ dry = _flag(body, 'dry_run')
1193
+ path = body.get('path')
1194
+ if path is not None and (not isinstance(path, str) or not path):
1195
+ raise BadBody('path must be a checkout path')
1196
+ except BadBody as exc:
1197
+ return _invalid(str(exc))
1198
+ project = projects.screen(ctx.server).projects(ctx.server.catalog).get(ctx.key)
1199
+ if project is None:
1200
+ return 404, {'error': 'not found'}
1201
+ existing = [c['path'] for c in projects.checkouts(project) if c['exists']]
1202
+ if path is not None:
1203
+ if path not in existing:
1204
+ return _invalid('path is not a checkout of this project')
1205
+ existing = [path]
1206
+ if not existing:
1207
+ return 409, {'error': 'refused', 'detail': 'no checkout of this project exists'}
1208
+ lock = _server_lock(ctx.server, 'memory_lock')
1209
+ if not lock.acquire(blocking=False):
1210
+ return 409, {'error': 'busy'}
1211
+ try:
1212
+ argv_tail = [*keys, *(['--dry-run'] if dry else []), '--json', '--actor', 'ui']
1213
+ results, failed = [], []
1214
+ for checkout in existing:
1215
+ status, answer = ctx.call('memory', 'forget', checkout, *argv_tail)
1216
+ if status == 200:
1217
+ results.append({'path': checkout, 'result': answer})
1218
+ else:
1219
+ failed.append((status, answer))
1220
+ results.append({'path': checkout, 'result': None, 'status': status, 'error': answer})
1221
+ if not dry:
1222
+ invalidate_memories(ctx.server)
1223
+ if failed and len(failed) == len(results):
1224
+ return failed[0]
1225
+ return 200, {'ok': not failed, 'dry_run': dry, 'checkouts': results}
1226
+ finally:
1227
+ lock.release()
1228
+
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
+
1377
+ def _storage_compact(ctx):
1378
+ """POST `{run | all, dry_run?}`: `forge runs compact <run dir>|--all --logs --json [--dry-run]`."""
1379
+ ctx.route = 'compact'
1380
+ try:
1381
+ body = _body_object(ctx, ('run', 'all', 'dry_run'))
1382
+ dry = _flag(body, 'dry_run')
1383
+ run = body.get('run')
1384
+ if ('run' in body) == ('all' in body):
1385
+ raise BadBody('give exactly one of run and all')
1386
+ if 'all' in body and body['all'] is not True:
1387
+ raise BadBody('all must be true')
1388
+ if 'run' in body and (not isinstance(run, str) or not re.fullmatch(r'[0-9a-f]{12}', run)):
1389
+ raise BadBody('run must be a 12-hex run key')
1390
+ except BadBody as exc:
1391
+ return _invalid(str(exc))
1392
+ target = ['--all']
1393
+ if run is not None:
1394
+ ctx.key = run
1395
+ found = ctx.server.catalog.locate(run)
1396
+ if not found:
1397
+ return 404, {'error': 'not found'}
1398
+ target = [str(found[0])]
1399
+ lock = _server_lock(ctx.server, 'compact_lock')
1400
+ if not lock.acquire(blocking=False):
1401
+ return 409, {'error': 'busy'}
1402
+ try:
1403
+ status, answer = ctx.call('runs', 'compact', *target, '--logs', '--json', *(['--dry-run'] if dry else []),
1404
+ limit=COMPACT_TIMEOUT_S)
1405
+ if not dry:
1406
+ invalidate_storage(ctx.server)
1407
+ return status, answer
1408
+ finally:
1409
+ lock.release()
1410
+
1411
+
1412
+ def _scheduler_live(path):
1413
+ """Whether the plan's scheduler.live names a process that is alive (as reader._scheduler judges it)."""
1414
+ try:
1415
+ with open(os.path.join(path, 'scheduler.live'), encoding='utf-8') as handle:
1416
+ pid = json.load(handle).get('pid')
1417
+ except (OSError, ValueError, AttributeError, RecursionError):
1418
+ return False
1419
+ if type(pid) is not int or pid <= 0:
1420
+ return False
1421
+ try:
1422
+ os.kill(pid, 0)
1423
+ except PermissionError:
1424
+ return True
1425
+ except (OSError, OverflowError):
1426
+ return False
1427
+ return True
1428
+
1429
+
1430
+ def _task_answer(ctx):
1431
+ """POST `{text}`: `forge control retry <plan> <id> --answer-file - --actor ui --json`, the text on stdin.
1432
+
1433
+ forge control queues the answer for a live scheduler and prepares the retry itself when there is none."""
1434
+ ctx.route = 'answer'
1435
+ task = ctx.parts[0]
1436
+ try:
1437
+ body = _body_object(ctx, ('text',))
1438
+ text = body.get('text')
1439
+ if not isinstance(text, str):
1440
+ raise BadBody('text must be a string')
1441
+ text = text.strip()
1442
+ if '\x00' in text:
1443
+ raise BadBody('text must not contain a NUL')
1444
+ if not 1 <= len(text) <= MAX_TASK_ANSWER:
1445
+ raise BadBody(f'text must be 1 to {MAX_TASK_ANSWER} characters')
1446
+ try:
1447
+ stdin = text.encode('utf-8')
1448
+ except UnicodeEncodeError:
1449
+ raise BadBody('text must be valid text')
1450
+ except BadBody as exc:
1451
+ return _invalid(str(exc))
1452
+ path = ctx.locate(('plan',))
1453
+ if path is None:
1454
+ return 404, {'error': 'not found'}
1455
+
1456
+ def work():
1457
+ live = _scheduler_live(path)
1458
+ status, answer = ctx.call('control', 'retry', path, task, '--answer-file', '-', '--actor', 'ui', '--json',
1459
+ stdin=stdin)
1460
+ return (200, {'live': live, 'result': answer}) if status == 200 else (status, answer)
1461
+ return ctx.locked(work)
1462
+
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
+
936
1933
  ROUTES = [
937
1934
  ('GET', re.compile(r'/api/runs/([0-9a-f]{12})/controls'), _show),
938
1935
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/controls'), _change),
939
1936
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/tasks/([A-Za-z0-9][A-Za-z0-9._-]{0,127})/brief/([^/]+)'),
940
1937
  _brief_answer),
1938
+ ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/proposals/([^/]+)/apply'), _brief_apply),
1939
+ ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/proposals/([^/]+)/reject'), _brief_reject),
1940
+ ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/proposals'), _brief_propose),
941
1941
  ('GET', re.compile(r'/api/runs/([0-9a-f]{12})/issues'), _issues_list),
942
1942
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/issues'), _issues_file),
943
1943
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/issues/dismiss'), _issues_dismiss),
944
1944
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/delete'), _delete),
1945
+ ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/tasks/([A-Za-z0-9][A-Za-z0-9._-]{0,127})/answer'), _task_answer),
1946
+ ('POST', re.compile(r'/api/worktrees/remove()'), _worktrees_remove),
1947
+ ('POST', re.compile(r'/api/storage/compact()'), _storage_compact),
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),
945
1954
  ('GET', re.compile(r'/api/config/profiles()'), _config_profiles_get),
946
1955
  ('POST', re.compile(r'/api/config/profiles()'), _config_profiles_set),
947
1956
  ('GET', re.compile(r'/api/config()'), _config_get),
@@ -951,8 +1960,11 @@ ROUTES = [
951
1960
  ('GET', re.compile(r'/api/storage()'), _storage),
952
1961
  ('GET', re.compile(r'/api/projects()'), _projects),
953
1962
  ('GET', re.compile(r'/api/projects/([0-9a-f]{8})'), _project),
1963
+ ('POST', _FINDINGS_PATH, _findings_action),
954
1964
  ('GET', re.compile(r'/api/projects/([0-9a-f]{8})/findings'), _project_findings),
955
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),
956
1968
  ]
957
1969
 
958
1970