@giamme/forge 0.9.0 → 0.10.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 (46) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/SKILL.md +19 -1
  3. package/VERSION +1 -1
  4. package/docs/artifacts.md +17 -2
  5. package/docs/commands.md +50 -0
  6. package/docs/dataset.md +9 -0
  7. package/docs/decomposed-runs.md +42 -0
  8. package/docs/forge-ui.md +42 -6
  9. package/docs/reviews.md +14 -0
  10. package/forge +15 -0
  11. package/package.json +1 -1
  12. package/references/dataset.md +18 -1
  13. package/references/decompose.md +19 -1
  14. package/references/ui.md +27 -5
  15. package/scripts/forge-config.py +347 -0
  16. package/scripts/forge-control.py +645 -0
  17. package/scripts/forge-issues.py +806 -0
  18. package/scripts/forge-lib-task.sh +234 -35
  19. package/scripts/forge-parallel-options.sh +3 -1
  20. package/scripts/forge-parallel.sh +3 -2
  21. package/scripts/forge-route.py +184 -27
  22. package/scripts/forge-runs-rm.py +840 -0
  23. package/scripts/forge-runs.py +19 -1
  24. package/scripts/forge-schedule.py +227 -11
  25. package/scripts/forge-ui.py +85 -19
  26. package/scripts/forge_dataset/__init__.py +77 -6
  27. package/scripts/forge_dataset/capture.py +5 -2
  28. package/scripts/forge_dataset/harvest.py +22 -0
  29. package/scripts/forge_dataset/importer.py +419 -17
  30. package/scripts/forge_registry.py +168 -16
  31. package/ui/README.md +37 -4
  32. package/ui/docs/api.md +184 -6
  33. package/ui/forge_ui/__main__.py +10 -2
  34. package/ui/forge_ui/control.py +575 -0
  35. package/ui/forge_ui/export.py +17 -3
  36. package/ui/forge_ui/reader.py +26 -1
  37. package/ui/forge_ui/server.py +125 -4
  38. package/ui/forge_ui/static/app.js +80 -8
  39. package/ui/forge_ui/static/controls.js +619 -0
  40. package/ui/forge_ui/static/findingsview.js +412 -0
  41. package/ui/forge_ui/static/index.html +7 -1
  42. package/ui/forge_ui/static/panel.js +24 -4
  43. package/ui/forge_ui/static/rundelete.js +388 -0
  44. package/ui/forge_ui/static/settings.js +399 -0
  45. package/ui/forge_ui/static/style.css +177 -2
  46. package/ui/forge_ui/static/uikit.js +161 -0
@@ -7,6 +7,10 @@ run dir under it, so you can see what happened without a browser and get the dir
7
7
  or open with `forge ui open`. The repo is the Git top level of the current directory unless
8
8
  `--repo` names one; `--all` lists the runs of every repo. It reads the same run summaries as
9
9
  forge-ui and never writes anything.
10
+
11
+ `forge runs rm <run-dir> [--dry-run] [--yes] [--no-archive] [--worktrees] [--branches] [--json]`
12
+ is the one thing here that changes anything: it deletes a run, after its traces are in the dataset
13
+ and an archive exists (scripts/forge-runs-rm.py).
10
14
  """
11
15
  from __future__ import annotations
12
16
 
@@ -86,8 +90,22 @@ def line(run: dict, now: float, with_repo: bool = False) -> str:
86
90
  return f"{run['run_id'] or run['key']} {run['kind']}{repo} {age(run['updated'], now)} {counts}{checks} {goal}\n {run['path']}"
87
91
 
88
92
 
93
+ def remove(argv) -> int:
94
+ """`forge runs rm`: loaded on demand, so listing never pays for the dataset package."""
95
+ import importlib.util
96
+ spec = importlib.util.spec_from_file_location('forge_runs_rm', Path(__file__).resolve().with_name('forge-runs-rm.py'))
97
+ module = importlib.util.module_from_spec(spec)
98
+ sys.modules['forge_runs_rm'] = module
99
+ spec.loader.exec_module(module)
100
+ return module.main(argv)
101
+
102
+
89
103
  def main(argv=None) -> int:
90
- parser = argparse.ArgumentParser(prog='forge runs', description="This repo's recent forge runs, newest first. Read-only.")
104
+ argv = sys.argv[1:] if argv is None else list(argv)
105
+ if argv[:1] == ['rm']:
106
+ return remove(argv[1:])
107
+ parser = argparse.ArgumentParser(prog='forge runs', description="This repo's recent forge runs, newest first. Listing is read-only.",
108
+ epilog='Delete a run, keeping its traces: forge runs rm <run-dir> (forge runs rm --help)')
91
109
  which = parser.add_mutually_exclusive_group()
92
110
  which.add_argument('--repo', type=Path, metavar='DIR', help='the repo whose runs to list (default: the Git top level of the current directory)')
93
111
  which.add_argument('--all', action='store_true', help='list the runs of every repo')
@@ -10,17 +10,26 @@ Two opt-in behaviours live here, both off by default so a plain `run` is unchang
10
10
  network, empty output) up to M times instead of stopping. Without it the scheduler
11
11
  stops dispatching, lets running tasks drain and exits 8: nothing was the task's fault
12
12
  and no attempt was spent, so the next `run` simply resumes.
13
+
14
+ Both numbers are per invocation, but while the scheduler runs they are mirrored into the
15
+ plan dir (retry_budget, infra_budget, tasks/<id>/retry_budget) and re-read at every
16
+ decision, so `forge control` can change them mid-run. See "live control files" below.
13
17
  """
14
18
  from __future__ import annotations
15
19
 
16
20
  import argparse
21
+ import contextlib
22
+ import errno
17
23
  import fcntl
24
+ import json
18
25
  import os
19
26
  from pathlib import Path
20
27
  import posixpath
21
28
  import signal
29
+ import stat
22
30
  import subprocess
23
31
  import sys
32
+ import tempfile
24
33
  import time
25
34
 
26
35
 
@@ -80,6 +89,157 @@ def infra_wait(info: dict, cycle: int) -> float:
80
89
  return min(base * (2 ** cycle), max(base, 1800.0))
81
90
 
82
91
 
92
+ # --- live control files ------------------------------------------------------------------
93
+ # Created at start and removed at exit, so a later `run` never inherits a budget it did not
94
+ # ask for. Writers replace files atomically, so readers need no lock; the control lock only
95
+ # orders a lifecycle write against `forge control`'s liveness check. It is never held across
96
+ # a model dispatch and never taken together with schedule.lock.
97
+ CONTROL_LOCK_WAIT = 5.0 # seconds; a busy lock must never fail a run
98
+ SWEEP_EVERY = 1.0 # seconds between looks at tasks that already ended FAIL/UNKNOWN
99
+
100
+
101
+ def _warn(message: str) -> None:
102
+ print('forge: ' + message, file=sys.stderr, flush=True)
103
+
104
+
105
+ def _task_id_ok(name: str) -> bool:
106
+ return bool(name) and name not in ('.', '..') and '/' not in name and '\0' not in name
107
+
108
+
109
+ def _resolve(plan: object, *parts: str) -> str:
110
+ """plan/<parts> if every directory on the way is a real one (no symlink) inside the
111
+ canonical plan dir and an existing target is a regular file. OSError otherwise."""
112
+ if not all(_task_id_ok(part) for part in parts):
113
+ raise OSError(errno.EINVAL, 'invalid path component', '/'.join(parts))
114
+ path = os.path.realpath(plan)
115
+ for part in parts[:-1]:
116
+ path = os.path.join(path, part)
117
+ if not stat.S_ISDIR(os.lstat(path).st_mode):
118
+ raise OSError(errno.ENOTDIR, 'not a real directory', path)
119
+ path = os.path.join(path, parts[-1])
120
+ try:
121
+ if not stat.S_ISREG(os.lstat(path).st_mode):
122
+ raise OSError(errno.EPERM, 'not a regular file', path)
123
+ except FileNotFoundError:
124
+ pass
125
+ return path
126
+
127
+
128
+ def _write_atomic(plan: object, text: str, *parts: str) -> bool:
129
+ """Temp file in the same directory, then rename. A failure warns and returns False."""
130
+ tmp = None
131
+ try:
132
+ path = _resolve(plan, *parts)
133
+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix='.' + parts[-1] + '.')
134
+ with os.fdopen(fd, 'w') as handle:
135
+ os.fchmod(handle.fileno(), 0o644)
136
+ handle.write(text)
137
+ os.replace(tmp, path)
138
+ return True
139
+ except OSError as error:
140
+ _warn('could not write ' + '/'.join(parts) + ': ' + str(error))
141
+ if tmp:
142
+ with contextlib.suppress(OSError):
143
+ os.unlink(tmp)
144
+ return False
145
+
146
+
147
+ def _remove(plan: object, *parts: str) -> None:
148
+ try:
149
+ os.unlink(_resolve(plan, *parts))
150
+ except FileNotFoundError:
151
+ pass
152
+ except OSError as error:
153
+ _warn('could not remove ' + '/'.join(parts) + ': ' + str(error))
154
+
155
+
156
+ def _read_budget(plan: object, *parts: str) -> int | None:
157
+ """A non-negative integer from a control file; None when it is missing, empty, a
158
+ symlink or anything else, so the caller falls through to its next source."""
159
+ try:
160
+ fd = os.open(_resolve(plan, *parts), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
161
+ try:
162
+ data = os.read(fd, 65)
163
+ finally:
164
+ os.close(fd)
165
+ text = data.decode('ascii').strip()
166
+ except (OSError, UnicodeDecodeError):
167
+ return None
168
+ return int(text) if len(data) <= 64 and text.isdigit() else None
169
+
170
+
171
+ @contextlib.contextmanager
172
+ def _control_lock(plan: object):
173
+ """flock on control.lock, retried for CONTROL_LOCK_WAIT seconds. On timeout or any
174
+ error: warn and proceed without it (yielding False), never fail the run."""
175
+ fd = None
176
+ try:
177
+ fd = os.open(_resolve(plan, 'control.lock'), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o644)
178
+ deadline = time.monotonic() + CONTROL_LOCK_WAIT
179
+ while True:
180
+ try:
181
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
182
+ break
183
+ except BlockingIOError:
184
+ if time.monotonic() >= deadline:
185
+ raise OSError(errno.EWOULDBLOCK, 'busy for ' + ('%g' % CONTROL_LOCK_WAIT) + 's')
186
+ time.sleep(0.05)
187
+ except OSError as error:
188
+ _warn('control.lock not taken, continuing without it: ' + str(error))
189
+ if fd is not None:
190
+ os.close(fd)
191
+ fd = None
192
+ try:
193
+ yield fd is not None
194
+ finally:
195
+ if fd is not None:
196
+ os.close(fd)
197
+
198
+
199
+ def _task_dirs(plan: object, names: object) -> list[str]:
200
+ """The planned tasks plus any other task dir, since `forge control` accepts an id
201
+ that is not in tasks.tsv and its file must not outlive the invocation either."""
202
+ found = set(names)
203
+ try:
204
+ with os.scandir(os.path.join(os.path.realpath(plan), 'tasks')) as entries:
205
+ found.update(e.name for e in entries if _task_id_ok(e.name) and e.is_dir(follow_symlinks=False))
206
+ except OSError:
207
+ pass
208
+ return sorted(found)
209
+
210
+
211
+ def _pinned(plan: object, name: str) -> bool:
212
+ try:
213
+ return os.path.lexists(_resolve(plan, 'tasks', name, 'escalation.pin'))
214
+ except OSError:
215
+ return False
216
+
217
+
218
+ def live_start(plan: object, names: object, retry_failed: int, infra_retries: int) -> None:
219
+ """Publish the flags and that this scheduler is live. Stale per-task overrides and
220
+ usage counters from an earlier invocation go first."""
221
+ with _control_lock(plan):
222
+ for name in _task_dirs(plan, names):
223
+ _remove(plan, 'tasks', name, 'retry_budget')
224
+ _remove(plan, 'tasks', name, 'retries.used')
225
+ _write_atomic(plan, str(retry_failed), 'retry_budget')
226
+ _write_atomic(plan, str(infra_retries), 'infra_budget')
227
+ _write_atomic(plan, json.dumps({'pid': os.getpid(), 'started': time.time()}), 'scheduler.live')
228
+
229
+
230
+ def live_stop(plan: object, names: object) -> None:
231
+ """Withdraw liveness first, then every budget. retries.used stays for the UI."""
232
+ try:
233
+ with _control_lock(plan):
234
+ _remove(plan, 'scheduler.live')
235
+ _remove(plan, 'retry_budget')
236
+ _remove(plan, 'infra_budget')
237
+ for name in _task_dirs(plan, names):
238
+ _remove(plan, 'tasks', name, 'retry_budget')
239
+ except Exception as error:
240
+ _warn('could not withdraw the live control files: ' + str(error))
241
+
242
+
83
243
  def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
84
244
  infra_retries: int = 0) -> int:
85
245
  if capacity <= 0:
@@ -97,16 +257,18 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
97
257
  if len(tasks) != len(rows):
98
258
  raise ValueError('duplicate task IDs')
99
259
  for name in tasks:
100
- if not name or name in ('.', '..') or '/' in name:
260
+ if not _task_id_ok(name):
101
261
  raise ValueError('invalid task ID: ' + name)
102
262
  (plan / 'tasks' / name).mkdir(parents=True, exist_ok=True)
103
263
  active = {}
104
264
  pending = list(tasks)
105
265
  interrupted = False
106
266
  retries = {} # automatic reviewer-driven retries used per task, this run
267
+ refused = {} # task -> budget at the time its retry could not be prepared
107
268
  retried = set() # tasks whose next dispatch is a retry (FORGE_FRACTAL_RETRY=1)
108
269
  offsets = {} # how much of each task.out was already echoed under --output full
109
270
  infra_seen = [] # tasks stopped by an infrastructure failure, awaiting resume
271
+ held = set() # INFRA tasks not resumed: their pin could not be applied
110
272
  infra_cycles = 0 # how many times this run already waited out an infrastructure pause
111
273
  paused = False # an infrastructure failure was seen: dispatch nothing new
112
274
  resume_at = 0.0
@@ -127,30 +289,61 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
127
289
  if result.returncode and status(name) == 'PASS':
128
290
  mark(name, 'ERROR')
129
291
 
292
+ def budget(name: str) -> int:
293
+ """Automatic retries this task may use. Read at every decision, never cached: the
294
+ task's own file, then the run-wide file, then the flag."""
295
+ for parts in (('tasks', name, 'retry_budget'), ('retry_budget',)):
296
+ value = _read_budget(plan, *parts)
297
+ if value is not None:
298
+ return value
299
+ return retry_failed
300
+
301
+ def infra_budget() -> int:
302
+ value = _read_budget(plan, 'infra_budget')
303
+ return infra_retries if value is None else value
304
+
130
305
  def retryable(name: str) -> bool:
306
+ root = plan / 'tasks' / name
131
307
  return (
132
- retry_failed > 0
133
- and retries.get(name, 0) < retry_failed
134
- and status(name) in ('FAIL', 'UNKNOWN')
308
+ status(name) in ('FAIL', 'UNKNOWN')
309
+ and retries.get(name, 0) < budget(name)
135
310
  # A task that produced no new work (empty diff, byte-identical retry) would
136
311
  # only repeat itself; its marker says so and it is left for a human.
137
- and not (plan / 'tasks' / name / 'noretry').exists()
312
+ and not (root / 'noretry').exists()
138
313
  # The retry policy found no stronger model after repeated failures on one: a
139
- # split, or an explicit `retry --dwarf`, is the human's call.
140
- and not (plan / 'tasks' / name / 'escalation.stop').exists()
314
+ # split, or an explicit `retry --dwarf`, is the human's call. A pin is exactly
315
+ # that call, made ahead of time: the next full retry applies it.
316
+ and (not (root / 'escalation.stop').exists() or _pinned(plan, name))
141
317
  )
142
318
 
143
319
  def requeue(name: str) -> bool:
144
320
  """Prepare a retry exactly as `retry` does, then put the task at the queue head."""
145
321
  result = subprocess.run(['/bin/bash', script, '_prepare_retry', str(plan), name])
146
322
  if result.returncode:
323
+ refused[name] = budget(name)
147
324
  return False
325
+ refused.pop(name, None)
148
326
  retries[name] = retries.get(name, 0) + 1
327
+ _write_atomic(plan, str(retries[name]), 'tasks', name, 'retries.used')
149
328
  retried.add(name)
150
329
  if name not in pending:
151
330
  pending.insert(0, name)
152
331
  print('forge: retrying ' + name + ' (automatic retry ' + str(retries[name]) + '/'
153
- + str(retry_failed) + ')', file=sys.stderr, flush=True)
332
+ + str(budget(name)) + ')', file=sys.stderr, flush=True)
333
+ return True
334
+
335
+ def resume(name: str) -> bool:
336
+ """Prepare an INFRA task's next entry. Not a retry, so nothing is counted, but a
337
+ pending pin applies when that entry is a full implementer attempt. False when a
338
+ claimed pin could not be put in place: the task then stays INFRA, as `retry` would."""
339
+ if not _pinned(plan, name):
340
+ return True
341
+ result = subprocess.run(['/bin/bash', script, '_prepare_retry', str(plan), name, '--resume'])
342
+ if result.returncode:
343
+ held.add(name)
344
+ print('forge: ' + name + ' is not resumed: its escalation pin could not be applied',
345
+ file=sys.stderr, flush=True)
346
+ return False
154
347
  return True
155
348
 
156
349
  def echo_output(name: str) -> None:
@@ -171,6 +364,7 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
171
364
  signal.signal(signal.SIGTERM, stop)
172
365
  signal.signal(signal.SIGINT, stop)
173
366
  try:
367
+ live_start(plan, tasks, retry_failed, infra_retries)
174
368
  # Failures require an explicit retry unless this run asked for automatic ones.
175
369
  # Saved PASS results use the same fingerprint checks without paying for
176
370
  # implementation or QA again; an INFRA stop is not a failure of the work, so it
@@ -183,13 +377,19 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
183
377
  mark(name, 'INTERRUPTED')
184
378
  if state in ('FAIL', 'UNKNOWN') and retryable(name):
185
379
  requeue(name)
380
+ if state == 'INFRA' and not resume(name):
381
+ pending.remove(name)
382
+ continue
186
383
  if status(name) not in ('PENDING', 'BLOCKED', 'INFRA'):
187
384
  pending.remove(name)
385
+ swept = time.monotonic()
188
386
  while pending or active:
189
387
  if interrupted:
190
388
  break
389
+ ended = set()
191
390
  for name, (process, log) in list(active.items()):
192
391
  if process.poll() is not None:
392
+ ended.add(name)
193
393
  log.close()
194
394
  del active[name]
195
395
  if os.environ.get('FORGE_OUTPUT') == 'full':
@@ -205,7 +405,18 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
205
405
  infra_seen.append(name)
206
406
  elif state in ('FAIL', 'UNKNOWN') and retryable(name):
207
407
  requeue(name)
208
- if paused and not active and infra_seen and infra_cycles < infra_retries:
408
+ if time.monotonic() - swept >= SWEEP_EVERY:
409
+ # A human can raise a budget after a task already ended FAIL while others
410
+ # still run. The initial pass's predicate, for tasks nothing else will look
411
+ # at again; one whose retry could not be prepared waits for a new budget.
412
+ swept = time.monotonic()
413
+ for name in tasks:
414
+ if name in pending or name in active or name in ended:
415
+ continue
416
+ if status(name) in ('FAIL', 'UNKNOWN') and retryable(name) \
417
+ and refused.get(name) != budget(name):
418
+ requeue(name)
419
+ if paused and not active and infra_seen and infra_cycles < infra_budget():
209
420
  # Everything running has drained. Wait out the outage once for all the
210
421
  # tasks it stopped, then dispatch them again.
211
422
  wait = max(infra_wait(infra_info(plan / 'tasks' / n), infra_cycles) for n in infra_seen)
@@ -218,8 +429,10 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
218
429
  time.sleep(min(0.05, max(resume_at - time.time(), 0)))
219
430
  if interrupted:
220
431
  break
432
+ # A pin set before or during the wait applies to the entries that run the
433
+ # implementer again; a QA-stage stop keeps it for the next full retry.
221
434
  for name in reversed(infra_seen):
222
- if name not in pending:
435
+ if name not in pending and resume(name):
223
436
  pending.insert(0, name)
224
437
  infra_seen.clear()
225
438
  paused = False
@@ -249,15 +462,18 @@ def schedule(script: str, plan: str, capacity: int, retry_failed: int = 0,
249
462
  pending.remove(name)
250
463
  print('forge: dispatched ' + name + ' -> ' + str(root), file=sys.stderr, flush=True)
251
464
  if not active:
252
- if paused:
465
+ if paused or held:
253
466
  # Infrastructure stop: leave everything not yet run PENDING. Marking it
254
467
  # BLOCKED would turn "the provider was down" into a recorded failure.
468
+ # A task held back by its pin is still an infrastructure stop.
255
469
  break
256
470
  for name in pending:
257
471
  mark(name, 'BLOCKED')
258
472
  break
259
473
  time.sleep(0.05)
260
474
  finally:
475
+ # Not live from here on: a late `forge control` must not edit budgets nobody reads.
476
+ live_stop(plan, tasks)
261
477
  for process, log in active.values():
262
478
  try:
263
479
  os.killpg(process.pid, signal.SIGTERM)
@@ -5,6 +5,13 @@
5
5
  prints a link to the run; every later `open` reuses it. State lives in
6
6
  `${XDG_STATE_HOME:-~/.local/state}/forge/ui`: `server.json` (what we started), `server.log`
7
7
  and `lock` (serialises launchers). The server exits by itself after FORGE_UI_IDLE_S idle seconds.
8
+
9
+ FORGE_UI_READONLY=1 starts (or insists on) a server that answers no write. The mode is recorded
10
+ with the server, and a running server of the other mode is replaced like one running old code.
11
+
12
+ The server runs without the shell's FORGE_* variables, but the CLIs its writes call need the forge
13
+ configuration (control.CLI_ENV_NAMES): `open` writes those to `cli-env.json` (0600) for the server to
14
+ load, records them in server.json, and refuses (exit 5) to reuse a server started with other values.
8
15
  """
9
16
  from __future__ import annotations
10
17
 
@@ -38,6 +45,7 @@ LOCK_WAIT_S = 10
38
45
  START_WAIT_S = 5
39
46
  STOP_WAIT_S = 2
40
47
  BROWSER_WAIT_S = 2 # a browser command that hangs must not hold `open` past its budget
48
+ CLI_ENV_FILE = 'cli-env.json'
41
49
 
42
50
 
43
51
  def state_dir() -> Path:
@@ -123,13 +131,13 @@ def read_state(state):
123
131
  return data if isinstance(data, dict) else None
124
132
 
125
133
 
126
- def write_state(state, data):
127
- handle, temp = tempfile.mkstemp(prefix='server.json.', dir=str(state))
134
+ def write_state(state, data, name='server.json'):
135
+ handle, temp = tempfile.mkstemp(prefix=name + '.', dir=str(state)) # mkstemp makes it 0600
128
136
  try:
129
137
  with os.fdopen(handle, 'w') as out:
130
138
  json.dump(data, out, indent=1, sort_keys=True)
131
139
  out.write('\n')
132
- os.replace(temp, state / 'server.json')
140
+ os.replace(temp, state / name)
133
141
  except BaseException:
134
142
  try:
135
143
  os.unlink(temp)
@@ -187,12 +195,25 @@ def terminate(pid) -> bool:
187
195
  return wait_dead(pid, STOP_WAIT_S)
188
196
 
189
197
 
190
- def _spawn(state, port, registry, idle):
198
+ def read_only_wanted() -> bool:
199
+ return os.environ.get('FORGE_UI_READONLY', '').strip().lower() in ('1', 'true', 'yes', 'on')
200
+
201
+
202
+ def is_read_only(answer) -> bool:
203
+ """Whether a live /api/health answer is a read-only server (a server too old to say is one)."""
204
+ return answer.get('controls') is not True
205
+
206
+
207
+ def _spawn(state, port, registry, idle, read_only=False, cli_env=None):
191
208
  """Start the server; returns (process, port) or (None, error text)."""
192
209
  log = state / 'server.log'
193
210
  env = {k: v for k, v in os.environ.items() if not k.startswith('FORGE_')}
194
- command = [sys.executable, '-I', str(Path(__file__).resolve()), '_serve', '--port', str(port),
195
- '--quiet', '--registry-dir', registry, '--idle-exit', str(idle)]
211
+ # The forge configuration goes to the server's CLIs only, through a file: never into its own environment.
212
+ write_state(state, cli_env or {}, CLI_ENV_FILE)
213
+ command = [sys.executable, '-I', str(Path(__file__).resolve()), '_serve', '--cli-env', str(state / CLI_ENV_FILE),
214
+ '--port', str(port), '--quiet', '--registry-dir', registry, '--idle-exit', str(idle)]
215
+ if read_only: # the server's environment has no FORGE_* variables, so the mode goes as a flag
216
+ command.append('--read-only')
196
217
  with os.fdopen(open_regular(log, os.O_WRONLY | os.O_CREAT | os.O_TRUNC), 'w') as out:
197
218
  proc = subprocess.Popen(command, cwd=str(state), stdin=subprocess.DEVNULL, stdout=out, stderr=out,
198
219
  start_new_session=True, close_fds=True, env=env)
@@ -211,11 +232,11 @@ def _spawn(state, port, registry, idle):
211
232
  return None, None
212
233
 
213
234
 
214
- def start_server(state, port, registry, idle):
235
+ def start_server(state, port, registry, idle, read_only=False, cli_env=None):
215
236
  """Spawn a server, falling back once to a free port when the preferred one is taken."""
216
- proc, result = _spawn(state, port, registry, idle)
237
+ proc, result = _spawn(state, port, registry, idle, read_only, cli_env)
217
238
  if proc is None and result == 2 and port != 0:
218
- proc, result = _spawn(state, 0, registry, idle)
239
+ proc, result = _spawn(state, 0, registry, idle, read_only, cli_env)
219
240
  if proc is None:
220
241
  return None
221
242
  return {'pid': proc.pid, 'port': result}
@@ -258,6 +279,14 @@ def browse(url):
258
279
  return 0
259
280
 
260
281
 
282
+ def config_change(recorded, current):
283
+ """How the running server's forge configuration differs from this shell's, as text; '' when it does not."""
284
+ recorded = recorded if isinstance(recorded, dict) else {} # a record without one has none
285
+ names = sorted(name for name in set(recorded) | set(current) if recorded.get(name) != current.get(name))
286
+ return '; '.join(f'{name} is {current.get(name, "unset")} here, {recorded.get(name, "unset")} in the server'
287
+ for name in names)
288
+
289
+
261
290
  def run_info(directory):
262
291
  """(repo, None) for a run dir, or (None, why not). Never raises and never blocks."""
263
292
  marker = directory / 'repo'
@@ -269,7 +298,10 @@ def run_info(directory):
269
298
  # a FIFO or a device named `repo` would block the read: only a regular file is read
270
299
  if not stat.S_ISREG(os.stat(marker).st_mode):
271
300
  return None, f'{marker} is not a regular file'
272
- repo = marker.read_text().strip()
301
+ # only the first line names the repo, as in forge_registry._repo_of (the runners register
302
+ # the same run dir under that line; anything after it must not change where it lands)
303
+ lines = marker.read_text().splitlines()
304
+ repo = lines[0].strip() if lines else ''
273
305
  except (OSError, ValueError) as exc: # ValueError: not decodable text
274
306
  return None, f'cannot read {marker}: {getattr(exc, "strerror", None) or exc}'
275
307
  if not repo:
@@ -282,6 +314,7 @@ def run_info(directory):
282
314
  def cmd_open(args):
283
315
  import forge_registry
284
316
  from forge_ui import __version__, build_id
317
+ from forge_ui.control import cli_env_from
285
318
  from forge_ui.reader import run_key
286
319
 
287
320
  try:
@@ -307,6 +340,8 @@ def cmd_open(args):
307
340
  state = state_dir()
308
341
  log = state / 'server.log'
309
342
  registry = str(forge_registry.registry_dir())
343
+ read_only = read_only_wanted()
344
+ cli_env = cli_env_from(os.environ)
310
345
  spawned = None
311
346
  # Any OSError below is state we cannot use (state dir, lock, server.log, server.json) or a
312
347
  # spawn that failed: exit 4. An unreadable or invalid server.json is not one: it means no server.
@@ -317,26 +352,35 @@ def cmd_open(args):
317
352
  server = read_state(state)
318
353
  answer = confirmed(server) if server else None
319
354
  if answer:
320
- # the record and the live answer must both name this code
321
- if server.get('build') == build and answer.get('build') == build and server.get('registry') == registry:
322
- pass # reuse
355
+ # the record and the live answer must both name this code and the mode asked for
356
+ if (server.get('build') == build and answer.get('build') == build and server.get('registry') == registry
357
+ and bool(server.get('read_only')) == read_only and is_read_only(answer) == read_only):
358
+ # Reused, it would run this shell's writes with another registry and dataset, and a
359
+ # restart could cut off a write in flight: say so instead, and how to restart it.
360
+ change = config_change(server.get('cli_env'), cli_env)
361
+ if change:
362
+ _say(f'error: the running forge-ui (pid {server["pid"]}) has another forge configuration '
363
+ f'for its writes: {change}. Run `forge ui stop`, then open again.')
364
+ return 5
323
365
  else:
324
366
  terminate(server['pid'])
325
367
  server = None
326
368
  else:
327
369
  server = None # dead, or a pid that is not our forge-ui: never signal it
328
370
  if server is None:
329
- spawned = start_server(state, port, registry, idle)
371
+ spawned = start_server(state, port, registry, idle, read_only, cli_env)
330
372
  if spawned is None:
331
373
  _say(f'error: the server did not start; see {log}')
332
374
  return 4
333
- server = dict(spawned, version=__version__, build=build, registry=registry, log=str(log),
334
- started=datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'), opened=[])
375
+ server = dict(spawned, version=__version__, build=build, registry=registry, log=str(log), read_only=read_only,
376
+ cli_env=cli_env, started=datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'), opened=[])
335
377
  opened = server.get('opened')
336
378
  opened = opened if isinstance(opened, list) else []
337
379
  mark = key or ''
338
380
  # a key counts as opened only when a browser is really launched for it
339
- first = mark not in opened and browser_wanted(args)
381
+ wanted = browser_wanted(args)
382
+ first = mark not in opened and wanted
383
+ again = mark in opened and wanted # say so, or a repeated `open` looks like it did nothing
340
384
  if first:
341
385
  opened.append(mark)
342
386
  server['opened'] = opened
@@ -354,6 +398,8 @@ def cmd_open(args):
354
398
  print(f'forge-ui: {url}')
355
399
  if first:
356
400
  launch_browser(url)
401
+ elif again:
402
+ _say('a browser tab was already opened for this link, so no new one was opened; use the link above')
357
403
  return 0
358
404
 
359
405
 
@@ -368,11 +414,13 @@ def cmd_status(args):
368
414
  return 1
369
415
  info = {'running': True, 'pid': server['pid'], 'port': server['port'],
370
416
  'url': f'http://{HOST}:{server["port"]}/', 'version': answer.get('version'),
371
- 'build': answer.get('build'), 'started': server.get('started'), 'log': server.get('log')}
417
+ 'build': answer.get('build'), 'started': server.get('started'), 'log': server.get('log'),
418
+ 'read_only': is_read_only(answer)}
372
419
  if args.json:
373
420
  print(json.dumps(info, sort_keys=True))
374
421
  else:
375
- print(f'forge-ui: running at {info["url"]} (pid {info["pid"]}, started {info["started"]})')
422
+ mode = 'read-only' if info['read_only'] else 'read-write'
423
+ print(f'forge-ui: running at {info["url"]} (pid {info["pid"]}, started {info["started"]}, {mode})')
376
424
  return 0
377
425
 
378
426
 
@@ -403,8 +451,26 @@ def cmd_stop(args):
403
451
  return 0
404
452
 
405
453
 
454
+ def load_cli_env(path):
455
+ """The forge configuration `_spawn` wrote for the server's CLIs; OSError or ValueError otherwise."""
456
+ from forge_ui import control
457
+ with os.fdopen(open_regular(path, os.O_RDONLY), 'rb') as handle:
458
+ return control.check_cli_env(json.loads(handle.read()))
459
+
460
+
406
461
  def serve(argv):
462
+ from forge_ui import control
407
463
  from forge_ui.__main__ import main
464
+ if argv[:1] == ['--cli-env']:
465
+ if len(argv) < 2:
466
+ _say('error: --cli-env needs a file')
467
+ return 1 # not 2: start_server reads 2 as a taken port
468
+ try:
469
+ control.cli_env = load_cli_env(argv[1])
470
+ except (OSError, ValueError, RecursionError) as exc:
471
+ _say(f'error: cannot load the CLI configuration {argv[1]}: {getattr(exc, "strerror", None) or exc}')
472
+ return 1
473
+ argv = argv[2:]
408
474
  return main(argv)
409
475
 
410
476