@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
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env python3
2
+ """Which task of a plan declares a path.
3
+
4
+ `<plan>/tasks.tsv` is tab-separated `id deps difficulty files dwarf qa title`.
5
+ `files` is a comma list of repo-relative paths or directories; `-` declares
6
+ nothing. A later decision asks this module which task owns a path, and whether
7
+ that path sits outside one task, using the same coverage rule the scheduler
8
+ uses to serialise tasks.
9
+
10
+ python3 scripts/forge_owner.py <plan> <path>... [--task ID]
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import os
17
+ from pathlib import Path
18
+ import posixpath
19
+ import sys
20
+
21
+
22
+ def _rows(plan: str | os.PathLike) -> list[tuple[str, str]]:
23
+ """`(id, files)` from tasks.tsv, in file order.
24
+
25
+ Comment lines, blank lines and rows with fewer than four columns are
26
+ skipped. A missing tasks.tsv raises FileNotFoundError.
27
+ """
28
+ text = (Path(plan) / 'tasks.tsv').read_text(encoding='utf-8').replace('\r', '')
29
+ found = []
30
+ for line in text.splitlines():
31
+ if not line or line.startswith('#'):
32
+ continue
33
+ columns = line.split('\t')
34
+ if len(columns) < 4:
35
+ continue
36
+ found.append((columns[0], columns[3]))
37
+ return found
38
+
39
+
40
+ def _entries(files: str) -> list[str]:
41
+ """Normalised paths in one files cell. Empty tokens and `-` declare nothing."""
42
+ return [posixpath.normpath(part) for part in files.split(',') if part and part != '-']
43
+
44
+
45
+ def declared(plan: str | os.PathLike, task: str) -> list[str]:
46
+ """That task's normalised `files` entries. `[]` for `-` or an unknown task."""
47
+ for ident, files in _rows(plan):
48
+ if ident == task:
49
+ return _entries(files)
50
+ return []
51
+
52
+
53
+ def covers(entry: str, path: str) -> bool:
54
+ """Whether one declared entry covers one path. An entry of `.` covers every path."""
55
+ # forge-schedule.py overlap: posixpath.normpath on each side, then equal or a '/' prefix; '.' covers all.
56
+ def piece(value: str) -> str | None:
57
+ if not value or value == '-':
58
+ return None
59
+ return posixpath.normpath(value)
60
+
61
+ left, right = piece(entry), piece(path)
62
+ if left is None or right is None:
63
+ return False
64
+ return (left == '.' or right == '.' or left == right
65
+ or left.startswith(right + '/') or right.startswith(left + '/'))
66
+
67
+
68
+ def _query(path: str) -> str | None:
69
+ """Repo-relative form of a path, or None when no task can own it.
70
+
71
+ Strip one leading `./`, then posixpath.normpath. An absolute result, or one
72
+ that starts with `..`, is outside the repository.
73
+ """
74
+ text = str(path)
75
+ if text.startswith('./'):
76
+ text = text[2:]
77
+ norm = posixpath.normpath(text)
78
+ if posixpath.isabs(norm) or norm.startswith('..'):
79
+ return None
80
+ return norm
81
+
82
+
83
+ def owners(plan: str | os.PathLike, path: str) -> list[str]:
84
+ """Every task id whose `files` cover `path`, in tasks.tsv order."""
85
+ rows = _rows(plan)
86
+ query = _query(path)
87
+ if query is None:
88
+ return []
89
+ found: list[str] = []
90
+ seen: set[str] = set()
91
+ for ident, files in rows:
92
+ if ident in seen:
93
+ continue
94
+ seen.add(ident) # the first row is the task's declaration, as declared() reads it
95
+ if any(covers(entry, query) for entry in _entries(files)):
96
+ found.append(ident)
97
+ return found
98
+
99
+
100
+ def owner(plan: str | os.PathLike, path: str) -> str | None:
101
+ """The first task in tasks.tsv order whose `files` cover `path`, or None."""
102
+ found = owners(plan, path)
103
+ return found[0] if found else None
104
+
105
+
106
+ def outside(plan: str | os.PathLike, task: str, path: str) -> bool:
107
+ """True when none of `task`'s declared entries covers `path`.
108
+
109
+ A task that declares `.` has nothing outside. A task whose `files` is `-`,
110
+ or an unknown task, has everything outside.
111
+ """
112
+ return not any(covers(entry, path) for entry in declared(plan, task))
113
+
114
+
115
+ def _report(plan: str, paths: list[str], task: str | None) -> dict:
116
+ idents = [ident for ident, _files in _rows(plan)]
117
+ if task is not None and task not in idents:
118
+ raise LookupError(task)
119
+ items = []
120
+ for path in paths:
121
+ found = owners(plan, path)
122
+ items.append({
123
+ 'path': path,
124
+ 'owner': found[0] if found else None,
125
+ 'owners': found,
126
+ 'outside': outside(plan, task, path) if task is not None else None,
127
+ })
128
+ return {'paths': items}
129
+
130
+
131
+ def main(argv: list[str] | None = None) -> int:
132
+ parser = argparse.ArgumentParser(
133
+ prog='forge_owner.py', description='Which task of a plan declares a path.')
134
+ parser.add_argument('plan', help='plan directory containing tasks.tsv')
135
+ parser.add_argument('paths', nargs='+', help='repo-relative paths to look up')
136
+ parser.add_argument('--task', help='also report whether each path is outside this task')
137
+ args = parser.parse_args(argv)
138
+ try:
139
+ report = _report(args.plan, args.paths, args.task)
140
+ except FileNotFoundError:
141
+ print("forge_owner: no tasks.tsv in '%s'" % args.plan, file=sys.stderr)
142
+ return 2
143
+ except LookupError as error:
144
+ print("forge_owner: unknown task '%s'" % error, file=sys.stderr)
145
+ return 2
146
+ json.dump(report, sys.stdout)
147
+ sys.stdout.write('\n')
148
+ return 0
149
+
150
+
151
+ if __name__ == '__main__':
152
+ sys.exit(main())
@@ -1,4 +1,4 @@
1
- """Whether a side dispatch (a brief or a task summary) may run, and running it.
1
+ """Whether a side dispatch (a brief, a brief change or a task summary) may run, and running it.
2
2
 
3
3
  Retro, brief mode and generated summaries are opt-in. `settings(plan)` resolves the
4
4
  effective choice for one plan dir. `allowed` says whether one dispatch may go out.
@@ -17,6 +17,15 @@ Precedence for each switch, first match wins:
17
17
  4. Off. `brief_scope` defaults to `task`. An env var forces the switch off and leaves
18
18
  the resolved scope and model in place.
19
19
 
20
+ A `brief-change` dispatch (a wave-scoped proposal, #136) follows the brief settings: the same
21
+ level, `FORGE_BRIEF=off`, model, `never-send` floor and its own cap.
22
+
23
+ A `triage` dispatch reads one repository's open findings from outside any plan. It is a
24
+ kind, but it has no plan dir: `allowed` and `run` raise ValueError (`use the triage
25
+ functions`). `triage_home` and `allocate_triage` place it at
26
+ `${XDG_STATE_HOME:-~/.local/state}/forge/triage/<key>/<n>/`. An empty or relative
27
+ `XDG_STATE_HOME` counts as unset. `triage_allowed` and `run_triage` are the entry points.
28
+
20
29
  `allowed` refuses with `env`, `off`, `never-send` (the plan repo's privacy floor),
21
30
  `no-model` or `cap`, in that order. For a summary, `tasks/<task>/summaries` (`on` or
22
31
  `off`) overrides the plan's mode and nothing else. The cap is
@@ -30,7 +39,9 @@ from __future__ import annotations
30
39
  import fcntl
31
40
  import os
32
41
  from pathlib import Path
42
+ import re
33
43
  import signal
44
+ import stat
34
45
  import subprocess
35
46
  import sys
36
47
 
@@ -40,7 +51,12 @@ from forge_decide.providers import privacy_floor
40
51
  SCRIPTS = Path(__file__).resolve().parent.parent
41
52
  DISPATCH = SCRIPTS / 'forge-dispatch.sh'
42
53
 
43
- KINDS = ('brief', 'summary')
54
+ KINDS = ('brief', 'brief-change', 'summary', 'triage')
55
+ # Kinds that follow the brief settings: `FORGE_BRIEF=off`, the plan's brief level and brief model.
56
+ BRIEF_KINDS = ('brief', 'brief-change')
57
+ # Numbered triage dispatch dirs one repository key may keep. A non-numeric sibling is not one.
58
+ _TRIAGE_CAP = 200
59
+ _TRIAGE_KEY = re.compile(r'^[0-9a-f]{16}$')
44
60
  ON_OFF = ('off', 'on')
45
61
  BRIEF_LEVELS = ('off', 'advisory', 'gated', 'strict')
46
62
  BRIEF_SCOPES = ('task', 'wave', 'plan')
@@ -60,6 +76,10 @@ class _Capped(Exception):
60
76
  """The per-kind dispatch cap is already full. Not an error for the caller."""
61
77
 
62
78
 
79
+ class TriageCapped(Exception):
80
+ """This repository key already holds 200 triage dispatch dirs."""
81
+
82
+
63
83
  def _read(path: Path) -> str | None:
64
84
  try:
65
85
  text = Path(path).read_text(encoding='utf-8')
@@ -282,20 +302,114 @@ def _allocate(plan: Path, kind: str, task: str) -> Path:
282
302
  os.close(fd)
283
303
 
284
304
 
305
+ def _state_root() -> Path:
306
+ """Absolute `XDG_STATE_HOME`, or `~/.local/state`. Empty or relative counts as unset.
307
+
308
+ A relative state home would name a directory below the current one, usually the
309
+ repository. The same rule as forge-issues' findings store.
310
+ """
311
+ for candidate in (os.environ.get('XDG_STATE_HOME') or '', '~/.local/state'):
312
+ try:
313
+ base = Path(candidate).expanduser() if candidate else None
314
+ except RuntimeError: # no home directory to expand "~" against
315
+ base = None
316
+ if base is not None and base.is_absolute():
317
+ return base
318
+ raise ValueError('cannot place the triage home: no home directory and no absolute XDG_STATE_HOME')
319
+
320
+
321
+ def triage_home(key) -> Path:
322
+ """`${XDG_STATE_HOME:-~/.local/state}/forge/triage/<key>`.
323
+
324
+ `key` is 16 lowercase hex characters, the repository identity computed elsewhere.
325
+ This does not create the directory and does not import that computation.
326
+ """
327
+ if not isinstance(key, str) or _TRIAGE_KEY.fullmatch(key) is None:
328
+ raise ValueError('triage key must be 16 lowercase hex chars, not %r' % (key,))
329
+ return _state_root() / 'forge' / 'triage' / key
330
+
331
+
332
+ def _refuse_symlink(path: Path, what: str) -> None:
333
+ """Raise ValueError when `path` is a symlink. A path that is not there yet is fine."""
334
+ try:
335
+ info = path.lstat()
336
+ except FileNotFoundError:
337
+ return
338
+ except OSError as exc:
339
+ raise ValueError('%s: %s' % (what, exc.strerror or exc)) from exc
340
+ if stat.S_ISLNK(info.st_mode):
341
+ raise ValueError('%s must be a real directory, not a symlink' % what)
342
+
343
+
344
+ def _triage_slots(home: Path) -> tuple[int, int]:
345
+ """`(highest numeric n, how many real numeric dirs)`.
346
+
347
+ A sibling whose name is not numeric takes no number, as `_next_n` does, and is not
348
+ a dispatch dir. A symlinked numeric directory is refused rather than followed.
349
+ """
350
+ highest = 0
351
+ count = 0
352
+ try:
353
+ children = list(home.iterdir())
354
+ except OSError:
355
+ return 0, 0
356
+ for child in children:
357
+ if not child.name.isdigit():
358
+ continue
359
+ try:
360
+ info = child.lstat()
361
+ except OSError:
362
+ continue
363
+ if stat.S_ISLNK(info.st_mode):
364
+ raise ValueError('triage dispatch dir must be a real directory, not a symlink')
365
+ if not stat.S_ISDIR(info.st_mode):
366
+ continue
367
+ highest = max(highest, int(child.name))
368
+ count += 1
369
+ return highest, count
370
+
371
+
372
+ def allocate_triage(key) -> Path:
373
+ """Create the next `<triage_home(key)>/<n>/` under an flock on `<home>/.lock`.
374
+
375
+ n starts at 1. A non-numeric sibling takes no number and does not count toward the
376
+ cap of 200 dispatch dirs. Past the cap this raises `TriageCapped`. A symlinked home
377
+ or numeric directory raises ValueError, and nothing is written through the link.
378
+ """
379
+ home = triage_home(key)
380
+ _refuse_symlink(home, 'triage home')
381
+ fd = _lock(home)
382
+ try:
383
+ _refuse_symlink(home, 'triage home')
384
+ highest, count = _triage_slots(home)
385
+ if count >= _TRIAGE_CAP:
386
+ raise TriageCapped('200 triage dispatch dirs already exist for this repository')
387
+ dest = home / str(highest + 1)
388
+ _refuse_symlink(dest, 'triage dispatch dir')
389
+ dest.mkdir()
390
+ _refuse_symlink(dest, 'triage dispatch dir')
391
+ return dest
392
+ finally:
393
+ os.close(fd)
394
+
395
+
285
396
  def allowed(kind, plan, task=None):
286
- """`(ok, reason)` for a `brief` or `summary` dispatch. `reason` is None when it may run.
397
+ """`(ok, reason)` for a `brief`, `brief-change` or `summary` dispatch. `reason` is None when it may run.
287
398
 
288
399
  Reasons, in the order they are decided: `env`, `off`, `never-send`, `no-model`, `cap`.
400
+ `triage` is not a plan dispatch: it raises ValueError (`use the triage functions`).
289
401
  """
402
+ if kind == 'triage':
403
+ raise ValueError('use the triage functions')
290
404
  if kind not in KINDS:
291
- raise ValueError('kind must be brief or summary, not %r' % (kind,))
405
+ raise ValueError('kind must be brief, brief-change or summary, not %r' % (kind,))
292
406
  plan = Path(plan)
293
- if kind == 'brief' and _env_off('FORGE_BRIEF'):
407
+ if kind in BRIEF_KINDS and _env_off('FORGE_BRIEF'):
294
408
  return False, 'env'
295
409
  if kind == 'summary' and _env_off('FORGE_SUMMARIES'):
296
410
  return False, 'env'
297
411
  found = settings(plan)
298
- if kind == 'brief':
412
+ if kind in BRIEF_KINDS:
299
413
  on = found['brief']['level'] in ('advisory', 'gated', 'strict')
300
414
  model = found['brief']['model']
301
415
  else:
@@ -313,6 +427,22 @@ def allowed(kind, plan, task=None):
313
427
  return True, None
314
428
 
315
429
 
430
+ def triage_allowed(repo, spec):
431
+ """`(ok, reason)` for a triage dispatch. `reason` is None when it may run.
432
+
433
+ Decided in order. No settings file is read: the caller names the spec each time.
434
+ `env` when `FORGE_TRIAGE` is off, `never-send` when `privacy_floor(repo)` says so,
435
+ `no-model` when `spec` is empty.
436
+ """
437
+ if _env_off('FORGE_TRIAGE'):
438
+ return False, 'env'
439
+ if privacy_floor(repo):
440
+ return False, 'never-send'
441
+ if spec is None or (isinstance(spec, str) and not spec.strip()):
442
+ return False, 'no-model'
443
+ return True, None
444
+
445
+
316
446
  def _last(dest: Path):
317
447
  path = dest / 'side.last'
318
448
  try:
@@ -394,6 +524,52 @@ def _stop_dispatch(proc: subprocess.Popen) -> None:
394
524
  pass
395
525
 
396
526
 
527
+ def _dispatch_and_wait(dest: Path, repo, prompt, spec, limit: int, event_dir, task, kind) -> dict:
528
+ """Write `prompt.txt` and run `forge-dispatch.sh side` in its own session.
529
+
530
+ Shared by `run` and `run_triage`. `event_dir` is the run dir on the `side_dispatch`
531
+ event: the plan, or the triage dest. Returns `{ok, last, dir, reason}` and does not
532
+ raise. A dispatch that outlives `limit` plus `_DISPATCH_GRACE_S` is stopped with
533
+ its session, including a preflight that has not exited.
534
+ """
535
+ try:
536
+ text = prompt if isinstance(prompt, str) else ('' if prompt is None else str(prompt))
537
+ (dest / 'prompt.txt').write_text(text, encoding='utf-8')
538
+ except (OSError, UnicodeError):
539
+ return _finish(event_dir, task, kind, spec, False, None, dest, 'error')
540
+ if not repo:
541
+ return _finish(event_dir, task, kind, spec, False, None, dest, 'error')
542
+ argv = ['/bin/bash', str(DISPATCH), 'side', '' if spec is None else str(spec),
543
+ '--repo', str(repo), '--run-dir', str(dest), '--prompt-file', str(dest / 'prompt.txt'),
544
+ '--timeout', str(max(0, limit))]
545
+ # Own session, so a timeout can stop the preflight with the shell.
546
+ try:
547
+ proc = subprocess.Popen(
548
+ argv, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
549
+ start_new_session=True, close_fds=True)
550
+ except (OSError, subprocess.SubprocessError):
551
+ return _finish(event_dir, task, kind, spec, False, _last(dest), dest, 'error')
552
+ wait = None if limit <= 0 else limit + _DISPATCH_GRACE_S
553
+ try:
554
+ proc.wait(timeout=wait)
555
+ except subprocess.TimeoutExpired:
556
+ _stop_dispatch(proc)
557
+ return _finish(event_dir, task, kind, spec, False, _last(dest), dest, 'timeout')
558
+ except (OSError, subprocess.SubprocessError):
559
+ _stop_dispatch(proc)
560
+ return _finish(event_dir, task, kind, spec, False, _last(dest), dest, 'error')
561
+ ok = proc.returncode == 0
562
+ reason = None if ok else ('timeout' if proc.returncode == 7 else 'error')
563
+ return _finish(event_dir, task, kind, spec, ok, _last(dest), dest, reason)
564
+
565
+
566
+ def _seconds(timeout, default: int) -> int:
567
+ try:
568
+ return int(timeout)
569
+ except (TypeError, ValueError):
570
+ return default
571
+
572
+
397
573
  def run(kind, plan, task, prompt, spec, timeout=900) -> dict:
398
574
  """Dispatch once. Returns `{ok, last, dir, reason}` and never raises on a failure.
399
575
 
@@ -403,54 +579,68 @@ def run(kind, plan, task, prompt, spec, timeout=900) -> dict:
403
579
  when this kind is already at its limit, `timeout` when the dispatch times out,
404
580
  `missing` when the dispatch script is not there, and `error` otherwise. A timeout
405
581
  stops the dispatch's session, including a preflight that has not exited.
582
+ `triage` is not a plan dispatch: it raises ValueError (`use the triage functions`).
406
583
  """
584
+ if kind == 'triage':
585
+ raise ValueError('use the triage functions')
407
586
  if kind not in KINDS:
408
- raise ValueError('kind must be brief or summary, not %r' % (kind,))
587
+ raise ValueError('kind must be brief, brief-change or summary, not %r' % (kind,))
409
588
  plan = Path(plan)
410
589
  if not _safe_component(task):
411
590
  return _finish(plan, task, kind, spec, False, None, None, 'error')
412
591
  if not DISPATCH.is_file():
413
592
  return _finish(plan, task, kind, spec, False, None, None, 'missing')
414
- try:
415
- limit = int(timeout)
416
- except (TypeError, ValueError):
417
- limit = 900
418
593
  try:
419
594
  dest = _allocate(plan, kind, task)
420
595
  except _Capped:
421
596
  return _finish(plan, task, kind, spec, False, None, None, 'cap')
422
597
  except OSError:
423
598
  return _finish(plan, task, kind, spec, False, None, None, 'error')
599
+ return _dispatch_and_wait(dest, _read(plan / 'repo'), prompt, spec, _seconds(timeout, 900),
600
+ plan, task, kind)
601
+
602
+
603
+ def _path_or_none(value):
424
604
  try:
425
- text = prompt if isinstance(prompt, str) else ('' if prompt is None else str(prompt))
426
- (dest / 'prompt.txt').write_text(text, encoding='utf-8')
427
- except (OSError, UnicodeError):
428
- return _finish(plan, task, kind, spec, False, None, dest, 'error')
429
- repo = _read(plan / 'repo')
430
- if not repo:
431
- return _finish(plan, task, kind, spec, False, None, dest, 'error')
432
- argv = ['/bin/bash', str(DISPATCH), 'side', '' if spec is None else str(spec),
433
- '--repo', repo, '--run-dir', str(dest), '--prompt-file', str(dest / 'prompt.txt'),
434
- '--timeout', str(max(0, limit))]
435
- # Own session, so a timeout can stop the preflight with the shell.
605
+ return Path(value)
606
+ except (TypeError, ValueError):
607
+ return None
608
+
609
+
610
+ def _repo_text(repo) -> str:
611
+ if isinstance(repo, Path):
612
+ return str(repo)
613
+ if isinstance(repo, str):
614
+ return repo.strip()
615
+ return '' if repo is None else str(repo).strip()
616
+
617
+
618
+ def run_triage(dest, repo, prompt, spec, timeout=3600) -> dict:
619
+ """Dispatch one triage read into an already allocated `dest`. Never raises.
620
+
621
+ The caller writes `findings.json` there first. `triage_allowed` is checked first
622
+ (`env`, `never-send`, `no-model`) and then nothing is started. Otherwise this is
623
+ the same `side` dispatch as `run`: `prompt.txt`, its own session, the grace past
624
+ the watchdog, and a session stop on timeout. `reason` is one of those, or
625
+ `timeout`, `missing` or `error`. The `side_dispatch` event has kind `triage`,
626
+ task None, and `dest` as its run dir.
627
+ """
628
+ directory = _path_or_none(dest)
436
629
  try:
437
- proc = subprocess.Popen(
438
- argv, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
439
- start_new_session=True, close_fds=True)
440
- except (OSError, subprocess.SubprocessError):
441
- return _finish(plan, task, kind, spec, False, _last(dest), dest, 'error')
442
- wait = None if limit <= 0 else limit + _DISPATCH_GRACE_S
630
+ ok, reason = triage_allowed(repo, spec)
631
+ except Exception:
632
+ return _finish(directory, None, 'triage', spec, False, None, None, 'error')
633
+ if not ok:
634
+ return _finish(directory, None, 'triage', spec, False, None, None, reason)
635
+ if directory is None:
636
+ return _finish(None, None, 'triage', spec, False, None, None, 'error')
637
+ if not DISPATCH.is_file():
638
+ return _finish(directory, None, 'triage', spec, False, None, None, 'missing')
443
639
  try:
444
- proc.wait(timeout=wait)
445
- except subprocess.TimeoutExpired:
446
- _stop_dispatch(proc)
447
- return _finish(plan, task, kind, spec, False, _last(dest), dest, 'timeout')
448
- except (OSError, subprocess.SubprocessError):
449
- _stop_dispatch(proc)
450
- return _finish(plan, task, kind, spec, False, _last(dest), dest, 'error')
451
- ok = proc.returncode == 0
452
- reason = None if ok else ('timeout' if proc.returncode == 7 else 'error')
453
- return _finish(plan, task, kind, spec, ok, _last(dest), dest, reason)
640
+ return _dispatch_and_wait(directory, _repo_text(repo), prompt, spec, _seconds(timeout, 3600),
641
+ directory, None, 'triage')
642
+ except Exception:
643
+ return _finish(directory, None, 'triage', spec, False, None, directory, 'error')
454
644
 
455
645
 
456
646
  def cap(text, limit) -> str: