@giamme/forge 0.17.0 → 0.19.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 (110) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +1 -0
  3. package/SKILL.md +32 -5
  4. package/VERSION +1 -1
  5. package/docs/artifacts.md +33 -1
  6. package/docs/commands.md +147 -16
  7. package/docs/dataset.md +5 -0
  8. package/docs/decomposed-runs.md +122 -1
  9. package/docs/development.md +2 -1
  10. package/docs/forge-ui.md +98 -8
  11. package/docs/memory.md +27 -4
  12. package/docs/models.md +8 -0
  13. package/docs/reviews.md +122 -0
  14. package/docs/safety.md +8 -0
  15. package/forge +44 -4
  16. package/package.json +2 -1
  17. package/references/dataset.md +39 -1
  18. package/references/decompose.md +737 -16
  19. package/references/harnesses.md +18 -3
  20. package/references/planning.md +43 -14
  21. package/references/solo.md +2 -1
  22. package/references/ui.md +56 -6
  23. package/registry.tsv +8 -3
  24. package/scripts/forge-artifact.sh +14 -0
  25. package/scripts/forge-brief.py +217 -0
  26. package/scripts/forge-compare.py +13 -2
  27. package/scripts/forge-config.py +176 -9
  28. package/scripts/forge-contract.py +246 -28
  29. package/scripts/forge-control.py +200 -15
  30. package/scripts/forge-dispatch.sh +48 -15
  31. package/scripts/forge-du.py +167 -0
  32. package/scripts/forge-group.py +496 -0
  33. package/scripts/forge-groups.py +89 -0
  34. package/scripts/forge-handoff.py +1128 -0
  35. package/scripts/forge-lib-adopt.sh +1 -0
  36. package/scripts/forge-lib-group.sh +641 -0
  37. package/scripts/forge-lib-plans.sh +343 -4
  38. package/scripts/forge-lib-review.sh +29 -1
  39. package/scripts/forge-lib-task.sh +197 -4
  40. package/scripts/forge-memory.sh +245 -3
  41. package/scripts/forge-metrics.sh +7 -3
  42. package/scripts/forge-parallel-options.sh +4 -0
  43. package/scripts/forge-parallel.sh +1216 -41
  44. package/scripts/forge-planner.py +104 -8
  45. package/scripts/forge-prompt.py +120 -0
  46. package/scripts/forge-retro.py +115 -0
  47. package/scripts/forge-route.py +190 -12
  48. package/scripts/forge-runs-compact.py +443 -0
  49. package/scripts/forge-runs-rm.py +2 -0
  50. package/scripts/forge-runs.py +27 -8
  51. package/scripts/forge-schedule.py +633 -49
  52. package/scripts/forge-shadow.py +7 -1
  53. package/scripts/forge-solo.sh +4 -0
  54. package/scripts/forge-summarize.py +698 -0
  55. package/scripts/forge-ui-options.sh +10 -0
  56. package/scripts/forge-worktrees.py +243 -0
  57. package/scripts/forge_brief/__init__.py +831 -0
  58. package/scripts/forge_brief/answers.py +506 -0
  59. package/scripts/forge_brief/proposals.py +1630 -0
  60. package/scripts/forge_dataset/__init__.py +10 -0
  61. package/scripts/forge_dataset/efforts.py +4 -3
  62. package/scripts/forge_dataset/export.py +36 -10
  63. package/scripts/forge_dataset/facts.py +8 -4
  64. package/scripts/forge_dataset/forecast.py +8 -18
  65. package/scripts/forge_dataset/harvest.py +241 -12
  66. package/scripts/forge_dataset/history.py +13 -6
  67. package/scripts/forge_dataset/importer.py +65 -1
  68. package/scripts/forge_dataset/names.py +66 -0
  69. package/scripts/forge_dataset/reviewers.py +5 -2
  70. package/scripts/forge_dataset/risk.py +6 -3
  71. package/scripts/forge_dataset/routing.py +6 -1
  72. package/scripts/forge_decide/__init__.py +11 -1
  73. package/scripts/forge_groups/__init__.py +308 -0
  74. package/scripts/forge_groups/attribute.py +289 -0
  75. package/scripts/forge_groups/review.py +286 -0
  76. package/scripts/forge_locations.py +366 -0
  77. package/scripts/forge_owner.py +152 -0
  78. package/scripts/forge_registry.py +19 -0
  79. package/scripts/forge_retro/__init__.py +417 -0
  80. package/scripts/forge_retro/issues.py +1193 -0
  81. package/scripts/forge_retro/report.py +671 -0
  82. package/scripts/forge_side/__init__.py +482 -0
  83. package/scripts/forge_storage.py +515 -0
  84. package/ui/README.md +68 -8
  85. package/ui/docs/api.md +375 -31
  86. package/ui/forge_ui/control.py +451 -11
  87. package/ui/forge_ui/executions.py +8 -1
  88. package/ui/forge_ui/export.py +53 -7
  89. package/ui/forge_ui/groups.py +264 -0
  90. package/ui/forge_ui/links.py +337 -0
  91. package/ui/forge_ui/models.py +125 -10
  92. package/ui/forge_ui/projects.py +4 -1
  93. package/ui/forge_ui/reader.py +919 -45
  94. package/ui/forge_ui/server.py +4 -0
  95. package/ui/forge_ui/static/app.js +173 -11
  96. package/ui/forge_ui/static/briefview.js +605 -0
  97. package/ui/forge_ui/static/checksview.js +6 -2
  98. package/ui/forge_ui/static/controls.js +5 -0
  99. package/ui/forge_ui/static/diffview.js +86 -1
  100. package/ui/forge_ui/static/groupsview.js +332 -0
  101. package/ui/forge_ui/static/index.html +4 -0
  102. package/ui/forge_ui/static/panel.js +394 -8
  103. package/ui/forge_ui/static/projectsview.js +189 -10
  104. package/ui/forge_ui/static/runmodel.js +27 -4
  105. package/ui/forge_ui/static/storageview.js +352 -0
  106. package/ui/forge_ui/static/style.css +176 -6
  107. package/ui/forge_ui/static/worktreesview.js +235 -14
  108. package/ui/forge_ui/storage.py +150 -0
  109. package/ui/forge_ui/transcripts.py +35 -10
  110. package/ui/forge_ui/worktrees.py +154 -13
@@ -4,8 +4,9 @@ The server never writes a run dir, a repo or forge's config itself. A write is o
4
4
  `<forge root>/forge ...` with an argv list and no shell, in its own process group, under a lock;
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
- to `dispatch`. Profile create and edit are the one call that writes a JSON body to the CLI's
8
- stdin (`--file -`); every other call has no stdin.
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. Approving, rejecting and proposing a brief
9
+ change print text and take no stdin. Every other call has no stdin.
9
10
  """
10
11
  from __future__ import annotations
11
12
 
@@ -25,6 +26,25 @@ MAX_FIELD = 256
25
26
  ISSUES_LIST_TIMEOUT_S = 120 # a listing asks gh for the filed state
26
27
  ISSUES_FILE_TIMEOUT_S = 300 # filing up to 25 issues
27
28
  DELETE_TIMEOUT_S = 900 # removing worktrees, branches and the archive can be slow
29
+ COMPACT_TIMEOUT_S = 900 # `forge runs compact` can take minutes on a large store
30
+ MAX_PATHS = 200 # worktrees to remove, and memory keys to forget, in one request
31
+ MAX_TASK_ANSWER = 8000 # the answer to a task that waits for input, in characters, after stripping
32
+ # One brief model call, end to end. proposals.propose and forge_brief.write pass 900s to
33
+ # forge_side.run, which waits that plus _DISPATCH_GRACE_S (30) before it returns its own
34
+ # timeout. The extra minute is the CLI storing the result and exiting, so a call that uses
35
+ # its whole wait is a refusal on the page and not a process this route killed.
36
+ _BRIEF_MODEL_S = 900
37
+ _BRIEF_DISPATCH_GRACE_S = 30
38
+ _BRIEF_CALL_S = _BRIEF_MODEL_S + _BRIEF_DISPATCH_GRACE_S
39
+ _BRIEF_SETTLE_S = 60
40
+ BRIEF_PROPOSE_TIMEOUT_S = _BRIEF_CALL_S + _BRIEF_SETTLE_S
41
+ # apply may spend 120s refreshing waves.tsv, then regenerates each unstarted affected task:
42
+ # one model call, in order. The budget is forty of those calls (twice the planner's task
43
+ # ceiling) plus the waves refresh. A faster call releases the run lock when the CLI exits.
44
+ # Past this, a regeneration that is still running is killed, the same way a 60s cap was.
45
+ _WAVES_REFRESH_S = 120
46
+ _APPLY_TASKS = 40
47
+ BRIEF_APPLY_TIMEOUT_S = _WAVES_REFRESH_S + _APPLY_TASKS * _BRIEF_CALL_S + _BRIEF_SETTLE_S
28
48
  MAX_FPS = 25
29
49
  MAX_LABELS = 5
30
50
  MAX_LABEL = 50
@@ -34,6 +54,13 @@ MAX_DECIDE_VALUE = 256
34
54
  # The profile object written to `forge config profile … --file -`. The HTTP body is already capped
35
55
  # at 64 KiB by the server; this caps the stdin text itself, which a re-encode can make larger.
36
56
  MAX_PROFILE_BODY = 64 * 1024
57
+ # A brief answer, in characters. The CLI then keeps the leading 4 KiB of what remains after it
58
+ # strips control characters; this bound is the one the route enforces before that call.
59
+ MAX_ANSWER = 4096
60
+ _QID = re.compile(r'^q[0-9]+$')
61
+ # The page accepts the same width the route captures. The CLI's own ids are p1, p2, …; p0 still reaches it.
62
+ _PID = re.compile(r'^p[0-9]{1,6}$')
63
+ _TASK_ID = re.compile(r'^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$')
37
64
  _PROFILE_NAME = re.compile(r'^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$')
38
65
  _PROFILE_KEY = re.compile(r'^(routing|policy)\.[a-z_.]+$')
39
66
  _PROFILE_ACTIONS = ('create', 'edit', 'set', 'unset', 'rm', 'use')
@@ -133,8 +160,9 @@ def run_cli(argv, timeout, stdin=None):
133
160
  On timeout the whole group gets SIGTERM, then SIGKILL after TERM_WAIT_S, and the leader is
134
161
  reaped before this returns, so a caller that holds a lock can release it knowing nothing of
135
162
  the call is still running. The CLI's environment is the server's plus `cli_env`. `stdin` is
136
- bytes written to the process and then closed, or None. Only a profile create or edit passes
137
- any, and only after its size was checked; every other call keeps stdin closed.
163
+ bytes written to the process and then closed, or None. A profile create or edit passes the
164
+ profile object, and a brief answer passes the answer text, each only after its size was
165
+ checked; every other call keeps stdin closed.
138
166
  """
139
167
  env = dict(os.environ, **cli_env) if cli_env else None
140
168
  try:
@@ -205,6 +233,26 @@ def map_exit(result):
205
233
  return status, body
206
234
 
207
235
 
236
+ def _text_exit(result):
237
+ """(status, body) for a CLI that prints text. Exit 0 is success even with no JSON object.
238
+
239
+ A late brief answer prints a notice and exits 0. `output` is stdout, so the page can show it.
240
+ A non-zero exit uses the same status mapping as `map_exit` and also carries `exit` and `output`.
241
+ """
242
+ if result.timed_out:
243
+ return 504, {'error': 'timeout', 'detail': TIMEOUT_DETAIL}
244
+ if result.error:
245
+ return 502, {'error': 'bad gateway', 'detail': result.error[:DETAIL_MAX]}
246
+ output = result.stdout
247
+ if result.code == 0:
248
+ return 200, {'exit': 0, 'output': output}
249
+ status, error = _EXITS.get(result.code, (502, 'bad gateway'))
250
+ detail = _message(result.stderr) if result.code == 3 else _last_line(result.stderr)
251
+ body = {'error': error, 'detail': detail or f'the forge CLI exited {result.code}',
252
+ 'exit': result.code, 'output': output}
253
+ return status, body
254
+
255
+
208
256
  # -------------------------------------------------------------------------------------- validation
209
257
 
210
258
  class BadBody(Exception):
@@ -268,12 +316,14 @@ class Context:
268
316
  found = self.server.catalog.locate(self.key)
269
317
  return found[0] if found and found[1] in kinds else None
270
318
 
271
- def call(self, *args, limit=None, stdin=None):
319
+ def call(self, *args, limit=None, stdin=None, json_stdout=True):
272
320
  """One CLI call, mapped to (status, body); the run's lock is the caller's to hold.
273
321
 
274
322
  `limit` is the route's timeout; a timeout given to `dispatch` (a test's) replaces it.
275
- `stdin` is bytes for the one profile write that uses `--file -`, or None."""
276
- return map_exit(run_cli([str(self.cli), *args], self.timeout or limit or TIMEOUT_S, stdin=stdin))
323
+ `stdin` is bytes for a call that uses `--file -`, or None. `json_stdout` is false when a
324
+ successful CLI prints text (a brief answer, including a late-answer notice)."""
325
+ result = run_cli([str(self.cli), *args], self.timeout or limit or TIMEOUT_S, stdin=stdin)
326
+ return map_exit(result) if json_stdout else _text_exit(result)
277
327
 
278
328
  def locked(self, work):
279
329
  """work() under the run's lock; 409 busy when another write to this run is in flight."""
@@ -305,6 +355,139 @@ def _change(ctx):
305
355
  return ctx.locked(lambda: ctx.call('control', action, path, *tail, '--actor', 'ui', '--json'))
306
356
 
307
357
 
358
+ def _answer_text(value):
359
+ """The answer string, or BadBody. 1 to MAX_ANSWER characters, no NUL, encodable as UTF-8."""
360
+ if not isinstance(value, str):
361
+ raise BadBody('answer must be a string')
362
+ if '\x00' in value:
363
+ raise BadBody('answer must not contain a NUL')
364
+ if not 1 <= len(value) <= MAX_ANSWER:
365
+ raise BadBody(f'answer must be 1 to {MAX_ANSWER} characters')
366
+ try:
367
+ return value.encode('utf-8')
368
+ except UnicodeEncodeError:
369
+ raise BadBody('answer must be valid text')
370
+
371
+
372
+ def _brief_answer(ctx):
373
+ """POST an answer: `forge brief answer <plan> <task> <qid> --file - --actor ui`, text on stdin.
374
+
375
+ A late answer is exit 0 with a notice on stdout, so it is a success and the page can show it.
376
+ """
377
+ ctx.route = 'brief'
378
+ task, qid = ctx.parts
379
+ try:
380
+ if not isinstance(ctx.body, dict):
381
+ raise BadBody('body must be a JSON object')
382
+ if not _QID.fullmatch(qid):
383
+ raise BadBody('qid must match ^q[0-9]+$')
384
+ _check_fields(ctx.body, ('answer',))
385
+ stdin = _answer_text(ctx.body.get('answer'))
386
+ except BadBody as exc:
387
+ return _invalid(str(exc))
388
+ path = ctx.locate(('plan',))
389
+ if path is None:
390
+ return 404, {'error': 'not found'}
391
+ return ctx.locked(lambda: ctx.call('brief', 'answer', path, task, qid, '--file', '-', '--actor', 'ui',
392
+ stdin=stdin, json_stdout=False))
393
+
394
+
395
+ def _brief_pid(ctx):
396
+ pid = ctx.parts[0] if ctx.parts else ''
397
+ if not isinstance(pid, str) or not _PID.fullmatch(pid):
398
+ raise BadBody('pid must match ^p[0-9]{1,6}$')
399
+ return pid
400
+
401
+
402
+ def _optional_reason(value):
403
+ """None when the reason is absent, null or blank. BadBody when it is not acceptable text.
404
+
405
+ Newline and tab are allowed, as on a dismissal. A leading '-' is safe: the CLI gets `--reason=`.
406
+ """
407
+ if value is None:
408
+ return None
409
+ if not isinstance(value, str) or len(value) > MAX_REASON or not _no_control_chars(value.replace('\n', ' ').replace('\t', ' ')):
410
+ raise BadBody(f'reason must be a text of at most {MAX_REASON} characters, without control characters (newline and tab are allowed)')
411
+ return value.strip() or None
412
+
413
+
414
+ def _plan_or_404(ctx):
415
+ path = ctx.locate(('plan',))
416
+ if path is None:
417
+ return None
418
+ return path
419
+
420
+
421
+ def _brief_apply(ctx):
422
+ """POST `{hash}`: `forge brief apply <plan> <pid> --approve <hash> --actor ui`.
423
+
424
+ Exit 0 prints text (the files written, the notes, and the plan-again line), so the body is that text.
425
+ Regeneration is one brief model call per unstarted affected task, so the wait is
426
+ `BRIEF_APPLY_TIMEOUT_S` and not the 60s default. The plan files are written before that
427
+ regeneration; killing it here would leave it half-done and drop the text the page shows.
428
+ """
429
+ ctx.route = 'brief apply'
430
+ try:
431
+ if not isinstance(ctx.body, dict):
432
+ raise BadBody('body must be a JSON object')
433
+ pid = _brief_pid(ctx)
434
+ _check_fields(ctx.body, ('hash',))
435
+ digest = _text(ctx.body, 'hash')
436
+ except BadBody as exc:
437
+ return _invalid(str(exc))
438
+ path = _plan_or_404(ctx)
439
+ if path is None:
440
+ return 404, {'error': 'not found'}
441
+ return ctx.locked(lambda: ctx.call('brief', 'apply', path, pid, '--approve', digest, '--actor', 'ui',
442
+ json_stdout=False, limit=BRIEF_APPLY_TIMEOUT_S))
443
+
444
+
445
+ def _brief_reject(ctx):
446
+ """POST `{reason}`: `forge brief reject <plan> <pid> [--reason=TEXT] --actor ui`. The reason may be empty."""
447
+ ctx.route = 'brief reject'
448
+ try:
449
+ if not isinstance(ctx.body, dict):
450
+ raise BadBody('body must be a JSON object')
451
+ pid = _brief_pid(ctx)
452
+ _check_fields(ctx.body, ('reason',))
453
+ reason = _optional_reason(ctx.body.get('reason'))
454
+ except BadBody as exc:
455
+ return _invalid(str(exc))
456
+ path = _plan_or_404(ctx)
457
+ if path is None:
458
+ return 404, {'error': 'not found'}
459
+ argv = ['brief', 'reject', path, pid]
460
+ if reason:
461
+ argv.append('--reason=' + reason)
462
+ argv += ['--actor', 'ui']
463
+ return ctx.locked(lambda: ctx.call(*argv, json_stdout=False))
464
+
465
+
466
+ def _brief_propose(ctx):
467
+ """POST `{task, qid}`: `forge brief propose <plan> <task> <qid> --actor ui` for a parked wave or plan question.
468
+
469
+ One brief-change model call. The wait is `BRIEF_PROPOSE_TIMEOUT_S`, past the CLI's own 900s.
470
+ """
471
+ ctx.route = 'brief propose'
472
+ try:
473
+ if not isinstance(ctx.body, dict):
474
+ raise BadBody('body must be a JSON object')
475
+ _check_fields(ctx.body, ('task', 'qid'))
476
+ task = _text(ctx.body, 'task')
477
+ if not _TASK_ID.fullmatch(task):
478
+ raise BadBody('task must be a task id')
479
+ qid = _text(ctx.body, 'qid')
480
+ if not _QID.fullmatch(qid):
481
+ raise BadBody('qid must match ^q[0-9]+$')
482
+ except BadBody as exc:
483
+ return _invalid(str(exc))
484
+ path = _plan_or_404(ctx)
485
+ if path is None:
486
+ return 404, {'error': 'not found'}
487
+ return ctx.locked(lambda: ctx.call('brief', 'propose', path, task, qid, '--actor', 'ui',
488
+ json_stdout=False, limit=BRIEF_PROPOSE_TIMEOUT_S))
489
+
490
+
308
491
  # ----------------------------------------------------------------- issues, delete and config routes
309
492
 
310
493
  def _invalid(detail):
@@ -839,6 +1022,19 @@ def _project_memories(ctx):
839
1022
  return (404, {'error': 'not found'}) if found is None else (200, found)
840
1023
 
841
1024
 
1025
+ def _storage(ctx):
1026
+ # The Disk screen (#139): forge_storage's report, measured in the background and cached per server
1027
+ # (storage.CACHE_S); ?refresh=1 measures again.
1028
+ from forge_ui import storage
1029
+ ctx.route = 'storage'
1030
+ try:
1031
+ params = _query_params(ctx.query, ('refresh',))
1032
+ refresh = _bit(params, 'refresh')
1033
+ except BadBody as exc:
1034
+ return _invalid(str(exc))
1035
+ return 200, storage.with_keys(storage.screen(ctx.server).answer(refresh=refresh), ctx.server.catalog.keys())
1036
+
1037
+
842
1038
  def _worktrees(ctx):
843
1039
  # The Worktrees screen (#125): git and the run dirs, read here, plus the history `forge dataset worktrees`
844
1040
  # keeps, read through the CLI. Cached per server (worktrees.CACHE_S); ?refresh=1 reads everything again.
@@ -856,19 +1052,262 @@ def _worktrees(ctx):
856
1052
  return 200, worktrees.screen(ctx.server).answer(ctx.server.catalog, history, refresh=refresh)
857
1053
 
858
1054
 
1055
+ # ----------------------------------------------------------------- remove, forget, compact, answer (#147)
1056
+
1057
+ def _body_object(ctx, allowed):
1058
+ if not isinstance(ctx.body, dict):
1059
+ raise BadBody('body must be a JSON object')
1060
+ _check_fields(ctx.body, allowed)
1061
+ return ctx.body
1062
+
1063
+
1064
+ def _string_list(value, name, check):
1065
+ if not isinstance(value, list) or not 1 <= len(value) <= MAX_PATHS:
1066
+ raise BadBody(f'{name} must be a list of 1 to {MAX_PATHS} strings')
1067
+ for item in value:
1068
+ if not isinstance(item, str) or not item or len(item) > 4096 or not _no_control_chars(item) or not check(item):
1069
+ raise BadBody(f'{name} holds a value that is not acceptable')
1070
+ return list(dict.fromkeys(value))
1071
+
1072
+
1073
+ def invalidate_worktrees(server):
1074
+ """The next GET /api/worktrees reads git and the run dirs again."""
1075
+ from forge_ui import worktrees
1076
+ screen = worktrees.screen(server)
1077
+ with screen.lock:
1078
+ screen.result = None
1079
+
1080
+
1081
+ def invalidate_storage(server):
1082
+ """The next GET /api/storage measures again; the answer it has stays on show until then."""
1083
+ from forge_ui import storage
1084
+ screen = storage.screen(server)
1085
+ with screen.lock:
1086
+ if screen.result is not None:
1087
+ screen.result = dict(screen.result, computed=0)
1088
+
1089
+
1090
+ def invalidate_memories(server):
1091
+ """The next GET of a project's memories reads the CLI again (the project screen's `memory` answers)."""
1092
+ from forge_ui import projects
1093
+ screen = projects.screen(server)
1094
+ with screen.lock:
1095
+ for key in [k for k in screen.cli if isinstance(k, tuple) and k and k[0] == 'memory']:
1096
+ del screen.cli[key]
1097
+
1098
+
1099
+ def _worktrees_remove(ctx):
1100
+ """POST `{paths, branches?, dry_run?}`: `forge worktrees rm <paths> [--branches] [--dry-run] --json --actor ui`.
1101
+
1102
+ Each path must be one of the rows of the Worktrees screen. Exit 4 (a row failed) is a 200 with
1103
+ `ok: false`: the page needs the rows to say which one failed.
1104
+ """
1105
+ from forge_ui import worktrees
1106
+ ctx.route = 'worktrees remove'
1107
+ try:
1108
+ body = _body_object(ctx, ('paths', 'branches', 'dry_run'))
1109
+ paths = _string_list(body.get('paths'), 'paths', os.path.isabs)
1110
+ branches = _flag(body, 'branches')
1111
+ dry = _flag(body, 'dry_run')
1112
+ except BadBody as exc:
1113
+ return _invalid(str(exc))
1114
+
1115
+ def history():
1116
+ status, found = ctx.call('dataset', 'worktrees', '--json')
1117
+ return found if status == 200 else None
1118
+
1119
+ def listed(refresh):
1120
+ answer = worktrees.screen(ctx.server).answer(ctx.server.catalog, history, refresh=refresh)
1121
+ return {row.get('path') for row in answer.get('rows') or []}
1122
+ known = listed(False)
1123
+ if not all(path in known for path in paths):
1124
+ known = listed(True)
1125
+ missing = [path for path in paths if path not in known]
1126
+ if missing:
1127
+ return _invalid(f'{missing[0]!r} is not a worktree the Worktrees screen lists')
1128
+ lock = _server_lock(ctx.server, 'worktrees_lock')
1129
+ if not lock.acquire(blocking=False):
1130
+ return 409, {'error': 'busy'}
1131
+ try:
1132
+ argv = ['worktrees', 'rm', *paths]
1133
+ if branches:
1134
+ argv.append('--branches')
1135
+ if dry:
1136
+ argv.append('--dry-run')
1137
+ status, answer = ctx.call(*argv, '--json', '--actor', 'ui', limit=DELETE_TIMEOUT_S)
1138
+ if status == 500 and isinstance(answer.get('result'), dict) and isinstance(answer['result'].get('rows'), list):
1139
+ status, answer = 200, dict(answer['result'], ok=False)
1140
+ if not dry:
1141
+ invalidate_worktrees(ctx.server)
1142
+ invalidate_storage(ctx.server)
1143
+ return status, answer
1144
+ finally:
1145
+ lock.release()
1146
+
1147
+
1148
+ _MEMORY_KEY = re.compile(r'^[^:\s-][^:]*:.+$')
1149
+
1150
+
1151
+ def _forget_keys(value):
1152
+ return _string_list(value, 'keys', lambda key: len(key) <= MAX_FIELD and bool(_MEMORY_KEY.match(key)))
1153
+
1154
+
1155
+ def _memories_forget(ctx):
1156
+ """POST `{keys, dry_run?, path?}`: `forge memory forget <checkout> <keys> [--dry-run] --json --actor ui`,
1157
+ once per existing checkout of the project (or only the one `path` names)."""
1158
+ from forge_ui import projects
1159
+ ctx.route = 'memories forget'
1160
+ try:
1161
+ body = _body_object(ctx, ('keys', 'dry_run', 'path'))
1162
+ keys = _forget_keys(body.get('keys'))
1163
+ dry = _flag(body, 'dry_run')
1164
+ path = body.get('path')
1165
+ if path is not None and (not isinstance(path, str) or not path):
1166
+ raise BadBody('path must be a checkout path')
1167
+ except BadBody as exc:
1168
+ return _invalid(str(exc))
1169
+ project = projects.screen(ctx.server).projects(ctx.server.catalog).get(ctx.key)
1170
+ if project is None:
1171
+ return 404, {'error': 'not found'}
1172
+ existing = [c['path'] for c in projects.checkouts(project) if c['exists']]
1173
+ if path is not None:
1174
+ if path not in existing:
1175
+ return _invalid('path is not a checkout of this project')
1176
+ existing = [path]
1177
+ if not existing:
1178
+ return 409, {'error': 'refused', 'detail': 'no checkout of this project exists'}
1179
+ lock = _server_lock(ctx.server, 'memory_lock')
1180
+ if not lock.acquire(blocking=False):
1181
+ return 409, {'error': 'busy'}
1182
+ try:
1183
+ argv_tail = [*keys, *(['--dry-run'] if dry else []), '--json', '--actor', 'ui']
1184
+ results, failed = [], []
1185
+ for checkout in existing:
1186
+ status, answer = ctx.call('memory', 'forget', checkout, *argv_tail)
1187
+ if status == 200:
1188
+ results.append({'path': checkout, 'result': answer})
1189
+ else:
1190
+ failed.append((status, answer))
1191
+ results.append({'path': checkout, 'result': None, 'status': status, 'error': answer})
1192
+ if not dry:
1193
+ invalidate_memories(ctx.server)
1194
+ if failed and len(failed) == len(results):
1195
+ return failed[0]
1196
+ return 200, {'ok': not failed, 'dry_run': dry, 'checkouts': results}
1197
+ finally:
1198
+ lock.release()
1199
+
1200
+
1201
+ def _storage_compact(ctx):
1202
+ """POST `{run | all, dry_run?}`: `forge runs compact <run dir>|--all --logs --json [--dry-run]`."""
1203
+ ctx.route = 'compact'
1204
+ try:
1205
+ body = _body_object(ctx, ('run', 'all', 'dry_run'))
1206
+ dry = _flag(body, 'dry_run')
1207
+ run = body.get('run')
1208
+ if ('run' in body) == ('all' in body):
1209
+ raise BadBody('give exactly one of run and all')
1210
+ if 'all' in body and body['all'] is not True:
1211
+ raise BadBody('all must be true')
1212
+ if 'run' in body and (not isinstance(run, str) or not re.fullmatch(r'[0-9a-f]{12}', run)):
1213
+ raise BadBody('run must be a 12-hex run key')
1214
+ except BadBody as exc:
1215
+ return _invalid(str(exc))
1216
+ target = ['--all']
1217
+ if run is not None:
1218
+ ctx.key = run
1219
+ found = ctx.server.catalog.locate(run)
1220
+ if not found:
1221
+ return 404, {'error': 'not found'}
1222
+ target = [str(found[0])]
1223
+ lock = _server_lock(ctx.server, 'compact_lock')
1224
+ if not lock.acquire(blocking=False):
1225
+ return 409, {'error': 'busy'}
1226
+ try:
1227
+ status, answer = ctx.call('runs', 'compact', *target, '--logs', '--json', *(['--dry-run'] if dry else []),
1228
+ limit=COMPACT_TIMEOUT_S)
1229
+ if not dry:
1230
+ invalidate_storage(ctx.server)
1231
+ return status, answer
1232
+ finally:
1233
+ lock.release()
1234
+
1235
+
1236
+ def _scheduler_live(path):
1237
+ """Whether the plan's scheduler.live names a process that is alive (as reader._scheduler judges it)."""
1238
+ try:
1239
+ with open(os.path.join(path, 'scheduler.live'), encoding='utf-8') as handle:
1240
+ pid = json.load(handle).get('pid')
1241
+ except (OSError, ValueError, AttributeError, RecursionError):
1242
+ return False
1243
+ if type(pid) is not int or pid <= 0:
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
1252
+
1253
+
1254
+ def _task_answer(ctx):
1255
+ """POST `{text}`: `forge control retry <plan> <id> --answer-file - --actor ui --json`, the text on stdin.
1256
+
1257
+ forge control queues the answer for a live scheduler and prepares the retry itself when there is none."""
1258
+ ctx.route = 'answer'
1259
+ task = ctx.parts[0]
1260
+ try:
1261
+ body = _body_object(ctx, ('text',))
1262
+ text = body.get('text')
1263
+ if not isinstance(text, str):
1264
+ raise BadBody('text must be a string')
1265
+ text = text.strip()
1266
+ if '\x00' in text:
1267
+ raise BadBody('text must not contain a NUL')
1268
+ if not 1 <= len(text) <= MAX_TASK_ANSWER:
1269
+ raise BadBody(f'text must be 1 to {MAX_TASK_ANSWER} characters')
1270
+ try:
1271
+ stdin = text.encode('utf-8')
1272
+ except UnicodeEncodeError:
1273
+ raise BadBody('text must be valid text')
1274
+ except BadBody as exc:
1275
+ return _invalid(str(exc))
1276
+ path = ctx.locate(('plan',))
1277
+ if path is None:
1278
+ return 404, {'error': 'not found'}
1279
+
1280
+ def work():
1281
+ live = _scheduler_live(path)
1282
+ status, answer = ctx.call('control', 'retry', path, task, '--answer-file', '-', '--actor', 'ui', '--json',
1283
+ stdin=stdin)
1284
+ return (200, {'live': live, 'result': answer}) if status == 200 else (status, answer)
1285
+ return ctx.locked(work)
1286
+
1287
+
859
1288
  ROUTES = [
860
1289
  ('GET', re.compile(r'/api/runs/([0-9a-f]{12})/controls'), _show),
861
1290
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/controls'), _change),
1291
+ ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/tasks/([A-Za-z0-9][A-Za-z0-9._-]{0,127})/brief/([^/]+)'),
1292
+ _brief_answer),
1293
+ ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/proposals/([^/]+)/apply'), _brief_apply),
1294
+ ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/proposals/([^/]+)/reject'), _brief_reject),
1295
+ ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/proposals'), _brief_propose),
862
1296
  ('GET', re.compile(r'/api/runs/([0-9a-f]{12})/issues'), _issues_list),
863
1297
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/issues'), _issues_file),
864
1298
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/issues/dismiss'), _issues_dismiss),
865
1299
  ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/delete'), _delete),
1300
+ ('POST', re.compile(r'/api/runs/([0-9a-f]{12})/tasks/([A-Za-z0-9][A-Za-z0-9._-]{0,127})/answer'), _task_answer),
1301
+ ('POST', re.compile(r'/api/worktrees/remove()'), _worktrees_remove),
1302
+ ('POST', re.compile(r'/api/storage/compact()'), _storage_compact),
1303
+ ('POST', re.compile(r'/api/projects/([0-9a-f]{8})/memories/forget'), _memories_forget),
866
1304
  ('GET', re.compile(r'/api/config/profiles()'), _config_profiles_get),
867
1305
  ('POST', re.compile(r'/api/config/profiles()'), _config_profiles_set),
868
1306
  ('GET', re.compile(r'/api/config()'), _config_get),
869
1307
  ('POST', re.compile(r'/api/config()'), _config_set),
870
1308
  ('GET', re.compile(r'/api/models/reviewers()'), _reviewer_outcomes),
871
1309
  ('GET', re.compile(r'/api/worktrees()'), _worktrees),
1310
+ ('GET', re.compile(r'/api/storage()'), _storage),
872
1311
  ('GET', re.compile(r'/api/projects()'), _projects),
873
1312
  ('GET', re.compile(r'/api/projects/([0-9a-f]{8})'), _project),
874
1313
  ('GET', re.compile(r'/api/projects/([0-9a-f]{8})/findings'), _project_findings),
@@ -877,12 +1316,12 @@ ROUTES = [
877
1316
 
878
1317
 
879
1318
  def match(method, path):
880
- """(handler, run key) for a route, or None."""
1319
+ """(handler, match) for a route, or None. Group 1 of the match is the run key."""
881
1320
  for verb, pattern, handler in ROUTES:
882
1321
  if verb == method:
883
1322
  found = pattern.fullmatch(path)
884
1323
  if found:
885
- return handler, found.group(1)
1324
+ return handler, found
886
1325
  return None
887
1326
 
888
1327
 
@@ -895,7 +1334,8 @@ def dispatch(server, cli, method, path, body, timeout=None, query=''):
895
1334
  found = match(method, path)
896
1335
  if found is None:
897
1336
  return None
898
- handler, key = found
899
- ctx = Context(server, cli, key, body, timeout, query)
1337
+ handler, matched = found
1338
+ ctx = Context(server, cli, matched.group(1), body, timeout, query)
1339
+ ctx.parts = matched.groups()[1:]
900
1340
  status, obj = handler(ctx)
901
1341
  return status, obj, ctx.route, ctx.key
@@ -14,9 +14,13 @@ import time
14
14
  from forge_ui import findings
15
15
 
16
16
 
17
- NAME = re.compile(r'(task|dwarf|qa|solo|verification|parallel)-[0-9a-f]{32}')
17
+ # A model dispatch's id is <role>-<32 hex>. A scripted task's command is script-<16 hex>
18
+ # (forge-parallel.sh). It is an execution, not a model role.
19
+ NAME = re.compile(r'(?:(?:task|dwarf|qa|solo|verification|parallel)-[0-9a-f]{32}|script-[0-9a-f]{16})')
18
20
  _KIND = re.compile(r'(final-review|integrate)-([0-9]+)-([0-9]+)')
19
21
  _SHADOW = re.compile(r'[0-9]+-[0-9]+')
22
+ # A group dir under groups/. The same shape as a group id (forge_groups, the group route).
23
+ _GROUP_DIR = re.compile(r'[a-z0-9][a-z0-9-]{0,39}')
20
24
  CONTAINERS = ('task', 'solo')
21
25
  _MODEL_ROLES = ('dwarf', 'qa')
22
26
  # attempts.tsv is appended right after the task execution's EXIT trap ran finish().
@@ -445,6 +449,9 @@ def locate(run_path, name, task_ids):
445
449
  for child in kinds:
446
450
  if child.startswith('integrate-'):
447
451
  yield child + '/final-review/attempts'
452
+ # A review=group group's QA dispatch writes its attempts here, as a task's land in the task dir.
453
+ for child in listed('groups', _GROUP_DIR):
454
+ yield f'groups/{child}/attempts'
448
455
 
449
456
  for rel in candidates():
450
457
  try: