@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
@@ -0,0 +1,482 @@
1
+ """Whether a side dispatch (a brief, a brief change or a task summary) may run, and running it.
2
+
3
+ Retro, brief mode and generated summaries are opt-in. `settings(plan)` resolves the
4
+ effective choice for one plan dir. `allowed` says whether one dispatch may go out.
5
+ `run` performs it through `forge-dispatch.sh side` (read-only, default effort low) and
6
+ never raises on a dispatch failure.
7
+
8
+ Precedence for each switch, first match wins:
9
+
10
+ 1. `FORGE_RETRO=off`, `FORGE_BRIEF=off` or `FORGE_SUMMARIES=off` forces that switch off.
11
+ 2. The plan file, when it names a value: `retro_mode` (`on` or `off`; not `retro`, which is
12
+ the notes directory), `brief` (the level, or `off`), `brief_scope`, `brief_model`,
13
+ `summaries` (`on` or `off`), `summaries_model`. An `off` file is an explicit off (`plan
14
+ --no-retro`, `--brief off`, `--summaries off`) and beats the user setting.
15
+ 3. The user `features` object in decide.json (`forge_decide.load_user`), only before the
16
+ plan is planned: once `waves.tsv` exists the plan is frozen and this step is skipped.
17
+ 4. Off. `brief_scope` defaults to `task`. An env var forces the switch off and leaves
18
+ the resolved scope and model in place.
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
+ `allowed` refuses with `env`, `off`, `never-send` (the plan repo's privacy floor),
24
+ `no-model` or `cap`, in that order. For a summary, `tasks/<task>/summaries` (`on` or
25
+ `off`) overrides the plan's mode and nothing else. The cap is
26
+ `max(10, 3 × tasks in tasks.tsv)` dispatches of that kind in the run, counted from
27
+ `<plan>/side/<kind>/<task>/<n>/`, including a task id that starts with a dot.
28
+ A dispatch that outlives its wait is stopped with its session, so a hung preflight
29
+ does not keep running after `run` returns.
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import fcntl
34
+ import os
35
+ from pathlib import Path
36
+ import signal
37
+ import subprocess
38
+ import sys
39
+
40
+ from forge_decide import load_user
41
+ from forge_decide.providers import privacy_floor
42
+
43
+ SCRIPTS = Path(__file__).resolve().parent.parent
44
+ DISPATCH = SCRIPTS / 'forge-dispatch.sh'
45
+
46
+ KINDS = ('brief', 'brief-change', 'summary')
47
+ # Kinds that follow the brief settings: `FORGE_BRIEF=off`, the plan's brief level and brief model.
48
+ BRIEF_KINDS = ('brief', 'brief-change')
49
+ ON_OFF = ('off', 'on')
50
+ BRIEF_LEVELS = ('off', 'advisory', 'gated', 'strict')
51
+ BRIEF_SCOPES = ('task', 'wave', 'plan')
52
+ SUMMARY_MODES = ON_OFF
53
+ FEATURE_KEYS = ('retro', 'brief', 'brief.scope', 'brief.model', 'summaries', 'summaries.model', 'storage.compact', 'storage.warn-gb')
54
+ STORAGE_COMPACT = ('auto', 'off')
55
+ # Appended in full when a text is cut, so a reader can see the cut happened.
56
+ CAP_MARKER = '… (capped)'
57
+ # How long `run` waits past the dispatch watchdog for the script to exit and reap.
58
+ _DISPATCH_GRACE_S = 30
59
+ # How long a timed-out dispatch gets to run its EXIT trap (it sleeps 1s while it reaps a
60
+ # harness that moved to its own session) before the session is killed.
61
+ _STOP_GRACE_S = 2
62
+
63
+
64
+ class _Capped(Exception):
65
+ """The per-kind dispatch cap is already full. Not an error for the caller."""
66
+
67
+
68
+ def _read(path: Path) -> str | None:
69
+ try:
70
+ text = Path(path).read_text(encoding='utf-8')
71
+ except (OSError, UnicodeError):
72
+ return None
73
+ text = text.strip()
74
+ return text or None
75
+
76
+
77
+ def _choice(value, allowed: tuple) -> str | None:
78
+ if isinstance(value, str) and value.strip() in allowed:
79
+ return value.strip()
80
+ return None
81
+
82
+
83
+ def _model_of(value) -> str:
84
+ if isinstance(value, str) and value.strip():
85
+ return value.strip()
86
+ return ''
87
+
88
+
89
+ def _mapping(value) -> dict:
90
+ return value if isinstance(value, dict) else {}
91
+
92
+
93
+ def _user_features() -> dict:
94
+ data, error = load_user()
95
+ if error or not isinstance(data, dict):
96
+ return {}
97
+ features = data.get('features')
98
+ return features if isinstance(features, dict) else {}
99
+
100
+
101
+ def _env_off(name: str) -> bool:
102
+ return os.environ.get(name, '').strip().lower() == 'off'
103
+
104
+
105
+ def _safe_component(name) -> bool:
106
+ """A single path component. A task id is one; `..` or a slash would leave the plan."""
107
+ return (isinstance(name, str) and bool(name) and name not in ('.', '..')
108
+ and '/' not in name and '\\' not in name and '\0' not in name)
109
+
110
+
111
+ def stored_features() -> dict:
112
+ """The user `features` settings as `forge config show` lists them.
113
+
114
+ A missing field is its default (`off`, scope `task`, model None). This is the stored
115
+ user file only: plan files and the off env vars are applied by `settings`.
116
+ """
117
+ features = _user_features()
118
+ brief = _mapping(features.get('brief'))
119
+ summaries = _mapping(features.get('summaries'))
120
+ return {
121
+ 'retro': _choice(features.get('retro'), ON_OFF) or 'off',
122
+ 'brief': _choice(brief.get('level'), BRIEF_LEVELS) or 'off',
123
+ 'brief.scope': _choice(brief.get('scope'), BRIEF_SCOPES) or 'task',
124
+ 'brief.model': _model_of(brief.get('model')) or None,
125
+ 'summaries': _choice(summaries.get('mode'), SUMMARY_MODES) or 'off',
126
+ 'summaries.model': _model_of(summaries.get('model')) or None,
127
+ # forge_storage.settings reads the same fields; these are the stored words, defaults included
128
+ 'storage.compact': _choice(_mapping(features.get('storage')).get('compact'), STORAGE_COMPACT) or 'auto',
129
+ 'storage.warn-gb': _model_of(_mapping(features.get('storage')).get('warn_gb')) or '20',
130
+ }
131
+
132
+
133
+ def settings(plan) -> dict:
134
+ """Effective `{retro, brief: {level, scope, model}, summaries: {mode, model}}` for a plan dir.
135
+
136
+ `retro` is a bool. Levels, scopes and modes are the stored words (`off` when nothing
137
+ turns them on). A model is the spec string, or `''` when none is configured.
138
+ """
139
+ resolved = _resolve(Path(plan))
140
+ if _env_off('FORGE_RETRO'):
141
+ resolved['retro'] = False
142
+ if _env_off('FORGE_BRIEF'):
143
+ resolved['brief']['level'] = 'off'
144
+ if _env_off('FORGE_SUMMARIES'):
145
+ resolved['summaries']['mode'] = 'off'
146
+ return resolved
147
+
148
+
149
+ def plan_files(plan) -> dict:
150
+ """The six plan files that freeze `plan`'s choices as they stand, for a plan made from it.
151
+
152
+ `{retro_mode, brief, summaries}` are always present: `on`/the level when on, `off` when
153
+ off, so the new plan never falls back to the user setting. A feature that is on adds its
154
+ scope and model (`brief_scope`, `brief_model`, `summaries_model`) when it has one. The env
155
+ off switches are not applied: they are run-time switches, not this plan's choice.
156
+ """
157
+ resolved = _resolve(Path(plan))
158
+ out = {'retro_mode': 'on' if resolved['retro'] else 'off',
159
+ 'brief': resolved['brief']['level'], 'summaries': resolved['summaries']['mode']}
160
+ if out['brief'] != 'off':
161
+ out['brief_scope'] = resolved['brief']['scope']
162
+ if resolved['brief']['model']:
163
+ out['brief_model'] = resolved['brief']['model']
164
+ if out['summaries'] == 'on' and resolved['summaries']['model']:
165
+ out['summaries_model'] = resolved['summaries']['model']
166
+ return out
167
+
168
+
169
+ def _resolve(plan: Path) -> dict:
170
+ """`settings` before the env off switches: plan files, then (unplanned only) the user setting."""
171
+ # A planned plan (its waves.tsv exists) is frozen: `plan` read the user setting once, so
172
+ # a missing plan file now means off, not "ask the user setting again".
173
+ features = {} if (plan / 'waves.tsv').exists() else _user_features()
174
+ brief = _mapping(features.get('brief'))
175
+ summaries = _mapping(features.get('summaries'))
176
+
177
+ # An `off` file is a choice of its own (plan --no-retro, --brief off, --summaries off): it
178
+ # is a recognised value, so it beats the user setting even before planning.
179
+ file = _read(plan / 'retro_mode')
180
+ retro = (file == 'on') if file is not None else _choice(features.get('retro'), ON_OFF) == 'on'
181
+ level = _choice(_read(plan / 'brief'), BRIEF_LEVELS) or _choice(brief.get('level'), BRIEF_LEVELS) or 'off'
182
+ scope = _choice(_read(plan / 'brief_scope'), BRIEF_SCOPES) or _choice(brief.get('scope'), BRIEF_SCOPES) or 'task'
183
+ model = _model_of(_read(plan / 'brief_model')) or _model_of(brief.get('model'))
184
+ mode = (_choice(_read(plan / 'summaries'), SUMMARY_MODES)
185
+ or _choice(summaries.get('mode'), SUMMARY_MODES) or 'off')
186
+ summary_model = _model_of(_read(plan / 'summaries_model')) or _model_of(summaries.get('model'))
187
+ return {
188
+ 'retro': retro,
189
+ 'brief': {'level': level, 'scope': scope, 'model': model},
190
+ 'summaries': {'mode': mode, 'model': summary_model},
191
+ }
192
+
193
+
194
+ def _summary_mode(plan: Path, task, mode: str) -> str:
195
+ """`tasks/<task>/summaries` (`on` or `off`) overrides the plan mode. Anything else does not."""
196
+ if not _safe_component(task):
197
+ return mode
198
+ override = _choice(_read(plan / 'tasks' / task / 'summaries'), SUMMARY_MODES)
199
+ return override if override is not None else mode
200
+
201
+
202
+ def _task_count(plan: Path) -> int:
203
+ try:
204
+ text = (plan / 'tasks.tsv').read_text(encoding='utf-8')
205
+ except (OSError, UnicodeError):
206
+ return 0
207
+ return sum(1 for line in text.splitlines() if line and not line.startswith('#'))
208
+
209
+
210
+ def _limit(plan: Path) -> int:
211
+ return max(10, 3 * _task_count(plan))
212
+
213
+
214
+ def _count(kind_dir: Path) -> int:
215
+ """Dispatch dirs under `side/<kind>/<task>/<n>/`.
216
+
217
+ Every directory counts, including a task id that starts with a dot: `_safe_component`
218
+ accepts one, and skipping it would let that task dispatch past the cap. The lock is a
219
+ file, so it is not a directory and does not count. A task directory itself does not;
220
+ the directories inside it do.
221
+ """
222
+ total = 0
223
+ try:
224
+ children = list(kind_dir.iterdir())
225
+ except OSError:
226
+ return 0
227
+ for task_dir in children:
228
+ if not task_dir.is_dir():
229
+ continue
230
+ try:
231
+ nested = list(task_dir.iterdir())
232
+ except OSError:
233
+ continue
234
+ total += sum(1 for child in nested if child.is_dir())
235
+ return total
236
+
237
+
238
+ def _next_n(kind_dir: Path, task: str) -> int:
239
+ """1 + the highest numeric `<n>` already under this task. Other tasks have their own count."""
240
+ highest = 0
241
+ task_dir = kind_dir / task
242
+ if task_dir.is_dir():
243
+ try:
244
+ children = list(task_dir.iterdir())
245
+ except OSError:
246
+ children = []
247
+ for child in children:
248
+ if child.is_dir() and child.name.isdigit():
249
+ highest = max(highest, int(child.name))
250
+ return highest + 1
251
+
252
+
253
+ def _lock(kind_dir: Path):
254
+ """Exclusive lock on `side/<kind>/.lock`. Closing the fd releases it."""
255
+ kind_dir.mkdir(parents=True, exist_ok=True)
256
+ fd = os.open(kind_dir / '.lock', os.O_CREAT | os.O_RDWR, 0o644)
257
+ try:
258
+ fcntl.flock(fd, fcntl.LOCK_EX)
259
+ except BaseException:
260
+ os.close(fd)
261
+ raise
262
+ return fd
263
+
264
+
265
+ def _at_cap(plan: Path, kind: str) -> bool:
266
+ kind_dir = plan / 'side' / kind
267
+ if not kind_dir.is_dir():
268
+ return False
269
+ fd = _lock(kind_dir)
270
+ try:
271
+ return _count(kind_dir) >= _limit(plan)
272
+ finally:
273
+ os.close(fd)
274
+
275
+
276
+ def _allocate(plan: Path, kind: str, task: str) -> Path:
277
+ """Create the next `<plan>/side/<kind>/<task>/<n>/` under the kind lock, or raise `_Capped`."""
278
+ kind_dir = plan / 'side' / kind
279
+ fd = _lock(kind_dir)
280
+ try:
281
+ if _count(kind_dir) >= _limit(plan):
282
+ raise _Capped()
283
+ dest = kind_dir / task / str(_next_n(kind_dir, task))
284
+ dest.mkdir(parents=True)
285
+ return dest
286
+ finally:
287
+ os.close(fd)
288
+
289
+
290
+ def allowed(kind, plan, task=None):
291
+ """`(ok, reason)` for a `brief`, `brief-change` or `summary` dispatch. `reason` is None when it may run.
292
+
293
+ Reasons, in the order they are decided: `env`, `off`, `never-send`, `no-model`, `cap`.
294
+ """
295
+ if kind not in KINDS:
296
+ raise ValueError('kind must be brief, brief-change or summary, not %r' % (kind,))
297
+ plan = Path(plan)
298
+ if kind in BRIEF_KINDS and _env_off('FORGE_BRIEF'):
299
+ return False, 'env'
300
+ if kind == 'summary' and _env_off('FORGE_SUMMARIES'):
301
+ return False, 'env'
302
+ found = settings(plan)
303
+ if kind in BRIEF_KINDS:
304
+ on = found['brief']['level'] in ('advisory', 'gated', 'strict')
305
+ model = found['brief']['model']
306
+ else:
307
+ on = _summary_mode(plan, task, found['summaries']['mode']) == 'on'
308
+ model = found['summaries']['model']
309
+ if not on:
310
+ return False, 'off'
311
+ repo = _read(plan / 'repo')
312
+ if repo and privacy_floor(repo):
313
+ return False, 'never-send'
314
+ if not model:
315
+ return False, 'no-model'
316
+ if _at_cap(plan, kind):
317
+ return False, 'cap'
318
+ return True, None
319
+
320
+
321
+ def _last(dest: Path):
322
+ path = dest / 'side.last'
323
+ try:
324
+ return path.read_text(encoding='utf-8', errors='replace')
325
+ except OSError:
326
+ return None
327
+
328
+
329
+ def _emit(plan, task, kind, spec, result: dict) -> None:
330
+ """One `side_dispatch` point event. Fail-open, like every other capture."""
331
+ try:
332
+ scripts = str(SCRIPTS)
333
+ if scripts not in sys.path:
334
+ sys.path.insert(0, scripts)
335
+ from forge_dataset.capture import point
336
+ point('side_dispatch', str(plan), None if task is None else str(task), {
337
+ 'kind': kind,
338
+ 'task': None if task is None else str(task),
339
+ 'spec': spec,
340
+ 'ok': result['ok'],
341
+ 'reason': result['reason'],
342
+ })
343
+ except Exception:
344
+ pass
345
+
346
+
347
+ def _finish(plan, task, kind, spec, ok, last, directory, reason) -> dict:
348
+ result = {'ok': bool(ok), 'last': last,
349
+ 'dir': None if directory is None else str(directory), 'reason': reason}
350
+ _emit(plan, task, kind, spec, result)
351
+ return result
352
+
353
+
354
+ def _signal_group(pgid: int, sig: int, proc: subprocess.Popen) -> None:
355
+ """Signal the dispatch's session. Never this process's own group."""
356
+ if pgid == os.getpgrp():
357
+ try:
358
+ proc.send_signal(sig)
359
+ except OSError:
360
+ pass
361
+ return
362
+ try:
363
+ os.killpg(pgid, sig)
364
+ except (ProcessLookupError, PermissionError):
365
+ return
366
+ except OSError:
367
+ try:
368
+ proc.send_signal(sig)
369
+ except OSError:
370
+ pass
371
+
372
+
373
+ def _stop_dispatch(proc: subprocess.Popen) -> None:
374
+ """Stop a dispatch that outlived its wait, and everything it started.
375
+
376
+ The shell is its own session. SIGTERM lets its EXIT trap reap a harness that moved
377
+ to another session. SIGKILL then takes this session. Killing the shell alone leaves
378
+ a hung preflight running: that child is not the harness, so the trap does not know
379
+ its pid, and SIGKILL of the shell (what `subprocess.run` does on timeout) skips the
380
+ trap as well.
381
+ """
382
+ try:
383
+ try:
384
+ pgid = os.getpgid(proc.pid)
385
+ except OSError:
386
+ pgid = proc.pid
387
+ _signal_group(pgid, signal.SIGTERM, proc)
388
+ try:
389
+ proc.wait(timeout=_STOP_GRACE_S)
390
+ except subprocess.TimeoutExpired:
391
+ pass
392
+ # The shell can be gone while a preflight child is still in the session.
393
+ _signal_group(pgid, signal.SIGKILL, proc)
394
+ try:
395
+ proc.wait(timeout=_STOP_GRACE_S)
396
+ except subprocess.TimeoutExpired:
397
+ pass
398
+ except Exception:
399
+ pass
400
+
401
+
402
+ def run(kind, plan, task, prompt, spec, timeout=900) -> dict:
403
+ """Dispatch once. Returns `{ok, last, dir, reason}` and never raises on a failure.
404
+
405
+ Creates `<plan>/side/<kind>/<task>/<n>/` (n = 1 + the highest existing n for that
406
+ task), writes the prompt there, and runs `forge-dispatch.sh side`. `last` is the
407
+ text of `side.last` when dispatch wrote one. `reason` is None on success, `cap`
408
+ when this kind is already at its limit, `timeout` when the dispatch times out,
409
+ `missing` when the dispatch script is not there, and `error` otherwise. A timeout
410
+ stops the dispatch's session, including a preflight that has not exited.
411
+ """
412
+ if kind not in KINDS:
413
+ raise ValueError('kind must be brief, brief-change or summary, not %r' % (kind,))
414
+ plan = Path(plan)
415
+ if not _safe_component(task):
416
+ return _finish(plan, task, kind, spec, False, None, None, 'error')
417
+ if not DISPATCH.is_file():
418
+ return _finish(plan, task, kind, spec, False, None, None, 'missing')
419
+ try:
420
+ limit = int(timeout)
421
+ except (TypeError, ValueError):
422
+ limit = 900
423
+ try:
424
+ dest = _allocate(plan, kind, task)
425
+ except _Capped:
426
+ return _finish(plan, task, kind, spec, False, None, None, 'cap')
427
+ except OSError:
428
+ return _finish(plan, task, kind, spec, False, None, None, 'error')
429
+ try:
430
+ text = prompt if isinstance(prompt, str) else ('' if prompt is None else str(prompt))
431
+ (dest / 'prompt.txt').write_text(text, encoding='utf-8')
432
+ except (OSError, UnicodeError):
433
+ return _finish(plan, task, kind, spec, False, None, dest, 'error')
434
+ repo = _read(plan / 'repo')
435
+ if not repo:
436
+ return _finish(plan, task, kind, spec, False, None, dest, 'error')
437
+ argv = ['/bin/bash', str(DISPATCH), 'side', '' if spec is None else str(spec),
438
+ '--repo', repo, '--run-dir', str(dest), '--prompt-file', str(dest / 'prompt.txt'),
439
+ '--timeout', str(max(0, limit))]
440
+ # Own session, so a timeout can stop the preflight with the shell.
441
+ try:
442
+ proc = subprocess.Popen(
443
+ argv, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
444
+ start_new_session=True, close_fds=True)
445
+ except (OSError, subprocess.SubprocessError):
446
+ return _finish(plan, task, kind, spec, False, _last(dest), dest, 'error')
447
+ wait = None if limit <= 0 else limit + _DISPATCH_GRACE_S
448
+ try:
449
+ proc.wait(timeout=wait)
450
+ except subprocess.TimeoutExpired:
451
+ _stop_dispatch(proc)
452
+ return _finish(plan, task, kind, spec, False, _last(dest), dest, 'timeout')
453
+ except (OSError, subprocess.SubprocessError):
454
+ _stop_dispatch(proc)
455
+ return _finish(plan, task, kind, spec, False, _last(dest), dest, 'error')
456
+ ok = proc.returncode == 0
457
+ reason = None if ok else ('timeout' if proc.returncode == 7 else 'error')
458
+ return _finish(plan, task, kind, spec, ok, _last(dest), dest, reason)
459
+
460
+
461
+ def cap(text, limit) -> str:
462
+ """The start of `text`, cut to `limit` characters, with a visible `… (capped)` marker.
463
+
464
+ A text that already fits is returned unchanged. The marker is kept whole, so a tiny
465
+ limit still shows it.
466
+ """
467
+ if text is None:
468
+ text = ''
469
+ elif not isinstance(text, str):
470
+ text = str(text)
471
+ try:
472
+ limit = int(limit)
473
+ except (TypeError, ValueError):
474
+ limit = 0
475
+ if limit < 0:
476
+ limit = 0
477
+ if len(text) <= limit:
478
+ return text
479
+ room = limit - len(CAP_MARKER)
480
+ if room <= 0:
481
+ return CAP_MARKER
482
+ return text[:room] + CAP_MARKER