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