@giamme/forge 0.20.0 → 0.22.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 (71) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +13 -3
  3. package/VERSION +1 -1
  4. package/bin/forge.js +104 -0
  5. package/docs/README.md +1 -0
  6. package/docs/development.md +1 -1
  7. package/docs/install.md +91 -2
  8. package/docs/reviews.md +6 -4
  9. package/docs/troubleshooting.md +1 -1
  10. package/forge +4 -0
  11. package/forge.cmd +56 -0
  12. package/package.json +5 -3
  13. package/scripts/forge-artifact.sh +5 -1
  14. package/scripts/forge-config.py +10 -9
  15. package/scripts/forge-control.py +61 -38
  16. package/scripts/forge-dispatch.sh +108 -31
  17. package/scripts/forge-group.py +2 -1
  18. package/scripts/forge-guard.py +207 -38
  19. package/scripts/forge-handoff.py +14 -17
  20. package/scripts/forge-install.sh +82 -9
  21. package/scripts/forge-issues.py +5 -2
  22. package/scripts/forge-lib-env.sh +158 -0
  23. package/scripts/forge-lib-group.sh +5 -5
  24. package/scripts/forge-lib-plans.sh +8 -3
  25. package/scripts/forge-lib-task.sh +40 -15
  26. package/scripts/forge-memory.sh +2 -0
  27. package/scripts/forge-metrics.sh +6 -1
  28. package/scripts/forge-parallel.sh +174 -53
  29. package/scripts/forge-planner.py +28 -2
  30. package/scripts/forge-pre-review.py +11 -4
  31. package/scripts/forge-ripwire.py +68 -22
  32. package/scripts/forge-route.py +10 -3
  33. package/scripts/forge-runs-compact.py +3 -2
  34. package/scripts/forge-runs-rm.py +14 -14
  35. package/scripts/forge-runtime.py +38 -21
  36. package/scripts/forge-schedule.py +90 -56
  37. package/scripts/forge-shadow.py +16 -9
  38. package/scripts/forge-solo.sh +6 -2
  39. package/scripts/forge-summarize.py +7 -3
  40. package/scripts/forge-sweep.py +8 -3
  41. package/scripts/forge-ui.py +8 -13
  42. package/scripts/forge-update.sh +6 -1
  43. package/scripts/forge-verify.py +30 -23
  44. package/scripts/forge-win.sh +156 -0
  45. package/scripts/forge_brief/__init__.py +7 -2
  46. package/scripts/forge_brief/proposals.py +13 -3
  47. package/scripts/forge_decide/budget.py +18 -8
  48. package/scripts/forge_decide/replay.py +15 -5
  49. package/scripts/forge_findings/apply.py +2 -1
  50. package/scripts/forge_findings/store.py +16 -4
  51. package/scripts/forge_findings/triage.py +6 -15
  52. package/scripts/forge_flock.py +102 -0
  53. package/scripts/forge_fractal/__init__.py +7 -3
  54. package/scripts/forge_fractal/cli.py +7 -2
  55. package/scripts/forge_fractal/execution.py +14 -14
  56. package/scripts/forge_fractal/invocation.py +3 -2
  57. package/scripts/forge_fractal/pipeline.py +2 -1
  58. package/scripts/forge_fractal/selection.py +2 -1
  59. package/scripts/forge_identity.py +2 -1
  60. package/scripts/forge_locations.py +14 -4
  61. package/scripts/forge_posix.py +125 -0
  62. package/scripts/forge_proc.py +507 -0
  63. package/scripts/forge_registry.py +17 -8
  64. package/scripts/forge_retro/__init__.py +8 -2
  65. package/scripts/forge_retro/issues.py +2 -1
  66. package/scripts/forge_side/__init__.py +32 -14
  67. package/scripts/forge_storage.py +11 -1
  68. package/ui/forge_ui/control.py +42 -14
  69. package/ui/forge_ui/reader.py +24 -18
  70. package/ui/forge_ui/server.py +10 -1
  71. package/ui/forge_ui/static/scene3d.js +23 -2
@@ -53,6 +53,12 @@ import sys
53
53
  import tempfile
54
54
  import time
55
55
 
56
+ _SCRIPTS = str(Path(__file__).resolve().parent)
57
+ if _SCRIPTS not in sys.path:
58
+ sys.path.insert(0, _SCRIPTS)
59
+ import forge_posix # noqa: E402
60
+ import forge_proc # noqa: E402
61
+
56
62
  sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
57
63
  import forge_verify_reports as reports # noqa: E402 next to this script
58
64
 
@@ -204,7 +210,7 @@ def run_stoppable(argv: list[str], stopped=None, **kwargs) -> tuple[int, bytes,
204
210
  """Run a command in its own process group and wait for it, stopping the group (TERM, then
205
211
  KILL after KILL_AFTER seconds) and raising Stopped as soon as ``stopped()`` is true."""
206
212
  proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
207
- stderr=subprocess.PIPE, start_new_session=True, **kwargs)
213
+ stderr=subprocess.PIPE, **forge_proc.popen_group_kwargs(), **kwargs)
208
214
  while True:
209
215
  try:
210
216
  out, err = proc.communicate(timeout=TICK)
@@ -212,11 +218,8 @@ def run_stoppable(argv: list[str], stopped=None, **kwargs) -> tuple[int, bytes,
212
218
  except subprocess.TimeoutExpired:
213
219
  if stopped is None or not stopped():
214
220
  continue
215
- for sig, wait in ((signal.SIGTERM, KILL_AFTER), (signal.SIGKILL, KILL_AFTER)):
216
- try:
217
- os.killpg(proc.pid, sig)
218
- except (ProcessLookupError, PermissionError):
219
- pass
221
+ for force, wait in ((False, KILL_AFTER), (True, KILL_AFTER)):
222
+ forge_proc.kill_tree(proc.pid, force=force)
220
223
  try:
221
224
  proc.communicate(timeout=wait)
222
225
  break
@@ -264,7 +267,7 @@ def fingerprint(checkout: str, command: str | None, stopped=None) -> str:
264
267
  """The checkout's fingerprint; Stopped when ``stopped()`` turns true meanwhile."""
265
268
  if not command:
266
269
  return default_fingerprint(checkout, stopped)
267
- rc, out, err = run_stoppable(['/bin/bash', '-c', command], stopped, cwd=checkout)
270
+ rc, out, err = run_stoppable(forge_proc.bash_cmd('-c', command), stopped, cwd=checkout)
268
271
  if rc != 0:
269
272
  raise RuntimeError(f'fingerprint command exited {rc}: {_text(err)}')
270
273
  return _text(out)
@@ -430,12 +433,16 @@ class Verification:
430
433
  try:
431
434
  if os.path.islink(log):
432
435
  os.unlink(log) # the log name is ours: never written through a link left in --out
433
- fd = os.open(log, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o666)
436
+ fd = forge_posix.open_nofollow(
437
+ log,
438
+ os.O_WRONLY | os.O_APPEND | os.O_CREAT | forge_posix.O_NOFOLLOW,
439
+ 0o666,
440
+ )
434
441
  with os.fdopen(fd, 'ab') as fh:
435
442
  offset = fh.tell()
436
- proc = subprocess.Popen(['/bin/bash', '-c', lane['command']], cwd=self.checkout,
443
+ proc = subprocess.Popen(forge_proc.bash_cmd('-c', lane['command']), cwd=self.checkout,
437
444
  stdin=subprocess.DEVNULL, stdout=fh,
438
- stderr=subprocess.STDOUT, start_new_session=True)
445
+ stderr=subprocess.STDOUT, **forge_proc.popen_group_kwargs())
439
446
  except (OSError, ValueError) as exc: # ValueError: an embedded NUL in the command
440
447
  with open(log, 'ab') as fh:
441
448
  fh.write(f'forge-verify: cannot start lane: {exc}\n'.encode())
@@ -462,7 +469,7 @@ class Verification:
462
469
  lane = self.by_name[name]
463
470
  rc = live.proc.poll()
464
471
  if rc is None: # still there after the KILL: a process stuck in the kernel
465
- rc = -signal.SIGKILL
472
+ rc = -forge_proc.SIGKILL
466
473
  self._pump({name: live}) # what is left to read, capped; an interrupt still gets through
467
474
  live.close()
468
475
  self._end(lane, lane['runs'][-1], rc if rc >= 0 else 128 - rc, interrupted)
@@ -644,7 +651,7 @@ class Verification:
644
651
  if live.exists() and not kept.exists():
645
652
  shutil.copyfile(live, kept)
646
653
  if truncate:
647
- os.close(os.open(live, os.O_WRONLY | os.O_TRUNC | os.O_NOFOLLOW))
654
+ os.close(forge_posix.open_nofollow(live, os.O_WRONLY | os.O_TRUNC | forge_posix.O_NOFOLLOW))
648
655
  except OSError as exc:
649
656
  print(f'forge-verify: cannot keep {kept.name}: {exc}', file=sys.stderr)
650
657
 
@@ -670,7 +677,7 @@ class Verification:
670
677
  time.sleep(TICK)
671
678
  for pgid in groups:
672
679
  if self._group_alive(pgid):
673
- self._signal(pgid, signal.SIGKILL)
680
+ self._signal(pgid, forge_proc.SIGKILL)
674
681
  deadline = time.monotonic() + 3 * KILL_AFTER # SIGKILL cannot be caught; do not hang on D state
675
682
  while time.monotonic() < deadline and any(self._group_alive(g) for g in groups):
676
683
  time.sleep(TICK)
@@ -685,26 +692,25 @@ class Verification:
685
692
  if not self._group_alive(pgid) or now >= give_up:
686
693
  continue
687
694
  if now >= deadline:
688
- self._signal(pgid, signal.SIGKILL)
695
+ self._signal(pgid, forge_proc.SIGKILL)
689
696
  keep.append((pgid, deadline, group, give_up))
690
697
  self.lingering = keep
691
698
 
692
699
  @staticmethod
693
700
  def _signal(pgid: int, sig: int) -> None:
694
- try:
695
- os.killpg(pgid, sig)
696
- except (ProcessLookupError, PermissionError):
697
- pass
701
+ forge_proc.kill_tree(pgid, force=(sig == forge_proc.SIGKILL))
698
702
 
699
703
  def _group_alive(self, pgid: int) -> bool:
700
704
  for live in self.running.values():
701
705
  if live.proc.pid == pgid:
702
706
  live.proc.poll() # reap a leader that exited, or it stays a zombie of the group
703
- try:
704
- os.killpg(pgid, 0)
705
- except (ProcessLookupError, PermissionError):
706
- return False
707
- return True
707
+ if not forge_proc.IS_WINDOWS:
708
+ try:
709
+ os.killpg(pgid, 0)
710
+ except (ProcessLookupError, PermissionError):
711
+ return False
712
+ return True
713
+ return forge_proc.group_alive(pgid)
708
714
 
709
715
  # the whole verification ------------------------------------------------------------
710
716
 
@@ -850,6 +856,7 @@ def cmd_run(args: argparse.Namespace) -> int:
850
856
 
851
857
  signal.signal(signal.SIGTERM, interrupt)
852
858
  signal.signal(signal.SIGINT, interrupt)
859
+ forge_proc.install_signal(forge_proc.SIGBREAK, interrupt)
853
860
  return verification.run()
854
861
 
855
862
 
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env bash
2
+ # forge-win.sh — sourced first by forge's entry scripts. Does nothing except on Windows in
3
+ # MSYS2 mode.
4
+ #
5
+ # On Windows forge runs natively by default: Git Bash with Windows' own Python. MSYS2 mode is
6
+ # the alternative for POSIX behaviour as on Linux: forge runs inside MSYS2, whose bash, git,
7
+ # python3 and ps agree on process ids, process groups, signals, flock and symlinks. It is opt-in:
8
+ #
9
+ # FORGE_WIN_MODE=msys2 an entry script started from Git Bash re-runs itself inside MSYS2
10
+ # an MSYS2 shell forge started there runs there, whatever FORGE_WIN_MODE says
11
+ #
12
+ # Inside MSYS2 this file exports FORGE_WIN_MODE=msys2, so helpers that adapt forge to native
13
+ # Windows can tell they are not in native mode.
14
+ #
15
+ # pacman -S python git procps-ng diffutils in the MSYS2 at FORGE_MSYS2_ROOT (default C:/msys64)
16
+ #
17
+ # Symlinks are made as real Windows symlinks (Developer Mode must be on). A link to a target
18
+ # that does not exist yet falls back to an MSYS-only link, which native programs see as a file.
19
+ #
20
+ # FORGE_WIN_AGENT_PATH is the PATH forge started with, in Git Bash or an MSYS2 shell, before
21
+ # /usr/bin goes first. forge-dispatch.sh gives it back to the agent CLIs, so they see what they
22
+ # would outside forge rather than MSYS2's tools first.
23
+ #
24
+ # This file is sourced on macOS too, so it keeps to Bash 3.2: no mapfile, no ${var,,}.
25
+ if [ "${BASH_SOURCE[0]}" = "$0" ]; then
26
+ # Run, not sourced: the landing side of the hop below. The original command line arrives in
27
+ # FORGE_WIN_ARGV, NUL-separated and base64-encoded, because a Windows command line cannot
28
+ # carry every argument unchanged (a double quote inside one is lost).
29
+ [ -n "${FORGE_WIN_ARGV:-}" ] || { echo "forge-win.sh is sourced by forge's entry scripts; it is not a command" >&2; exit 2; }
30
+ _forge_argv=()
31
+ while IFS= read -r -d '' _forge_arg; do _forge_argv+=("$_forge_arg"); done \
32
+ < <(printf '%s' "$FORGE_WIN_ARGV" | /usr/bin/base64 -d)
33
+ unset FORGE_WIN_ARGV _forge_arg
34
+ exec /usr/bin/bash "${_forge_argv[@]}"
35
+ fi
36
+ case "${OSTYPE:-}" in msys*|cygwin*) ;; *) return 0 ;; esac
37
+ case "${FORGE_WIN_MODE:-native}" in
38
+ native|msys2) ;;
39
+ *) echo "forge: FORGE_WIN_MODE is '$FORGE_WIN_MODE'; use native (the default) or msys2" >&2; exit 2 ;;
40
+ esac
41
+
42
+ # MSYS2 has pacman; Git for Windows has git-bash.exe at its root (its SDK, which has both, is
43
+ # Git Bash too). Only file tests here: native mode must not pay for a single extra process.
44
+ if [ ! -x /usr/bin/pacman ] || [ -e /git-bash.exe ]; then
45
+ [ "${FORGE_WIN_MODE:-native}" = msys2 ] || return 0 # native mode: Git Bash runs forge itself
46
+ _forge_msys="${FORGE_MSYS2_ROOT:-C:/msys64}"
47
+ _forge_msys="${_forge_msys%/}"
48
+ if [ ! -x "$_forge_msys/usr/bin/bash.exe" ]; then
49
+ echo "forge: FORGE_WIN_MODE=msys2, but MSYS2 was not found at $_forge_msys (set FORGE_MSYS2_ROOT)" >&2
50
+ exit 127
51
+ fi
52
+ # One hop only: landing anywhere but an MSYS2 would otherwise re-run the script for ever.
53
+ if [ -n "${FORGE_WIN_REEXEC:-}" ]; then
54
+ echo "forge: re-ran inside $_forge_msys, which does not look like MSYS2 (no /usr/bin/pacman)" >&2
55
+ exit 127
56
+ fi
57
+ # The hop goes through a native program. Started directly, MSYS2's bash would get almost none of
58
+ # this environment: two copies of the MSYS runtime cannot hand it to each other.
59
+ _forge_native=""
60
+ for _forge_tool in python3 python py; do
61
+ if "$_forge_tool" -c 'import sys; sys.exit(sys.platform != "win32")' 2>/dev/null; then _forge_native="$_forge_tool"; break; fi
62
+ done
63
+ if [ -z "$_forge_native" ]; then
64
+ echo "forge: MSYS2 mode needs a native Windows Python on the Git Bash PATH to hand over to MSYS2; or start forge from an MSYS2 shell" >&2
65
+ exit 127
66
+ fi
67
+ FORGE_WIN_ARGV="$(printf '%s\0' "$(/usr/bin/cygpath -m "$0")" "$@" | /usr/bin/base64 -w0)"
68
+ export FORGE_WIN_ARGV FORGE_WIN_REEXEC=1 FORGE_WIN_MSYSTEM="${MSYSTEM-}"
69
+ # Ctrl-C reaches MSYS2's bash as well, and forge's own handlers clean up (worktrees, agents).
70
+ # The hand-over only waits for it: subprocess.call would kill it on KeyboardInterrupt.
71
+ MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*' exec "$_forge_native" -c '
72
+ import subprocess, sys
73
+ child = subprocess.Popen(sys.argv[1:])
74
+ while True:
75
+ try:
76
+ sys.exit(child.wait())
77
+ except KeyboardInterrupt:
78
+ pass
79
+ ' "$_forge_msys/usr/bin/bash.exe" "$(/usr/bin/cygpath -m "${BASH_SOURCE[0]}")"
80
+ fi
81
+
82
+ # Inside MSYS2: started from an MSYS2 shell, or just arrived from Git Bash.
83
+ _forge_msys="$(/usr/bin/cygpath -m /)"
84
+ _forge_msys="${_forge_msys%/}"
85
+ for _forge_tool in python3 git procps cmp diff; do
86
+ if [ ! -x "/usr/bin/$_forge_tool" ]; then
87
+ echo "forge: the MSYS2 at $_forge_msys has no $_forge_tool; run there: pacman -S python git procps-ng diffutils" >&2
88
+ exit 127
89
+ fi
90
+ done
91
+ [ -z "${FORGE_WIN_REEXEC:-}" ] || unset FORGE_WIN_REEXEC MSYS_NO_PATHCONV MSYS2_ARG_CONV_EXCL
92
+ # The PATH and MSYSTEM forge started with (Git Bash's, or the MSYS2 shell's) are what an agent
93
+ # CLI should see. forge itself needs MSYS2's python3 and git ahead of everything: a UCRT64 or
94
+ # MINGW64 shell puts /ucrt64/bin or /mingw64/bin first, where a MinGW Python is a native Windows
95
+ # Python. Child scripts inherit both, so this runs once.
96
+ if [ -z "${FORGE_WIN_AGENT_PATH:-}" ]; then
97
+ export FORGE_WIN_AGENT_PATH="$PATH"
98
+ [ -n "${FORGE_WIN_MSYSTEM+set}" ] || export FORGE_WIN_MSYSTEM="${MSYSTEM-}"
99
+ fi
100
+ case "$PATH" in /usr/bin:*) ;; *) export PATH="/usr/bin:$PATH" ;; esac
101
+ # Real Windows symlinks, unless the user already chose how MSYS2 makes them.
102
+ case " ${MSYS-} " in *" winsymlinks"*) ;; *) MSYS="${MSYS:+$MSYS }winsymlinks:native" ;; esac
103
+ # FORGE_WIN_MODE says which mode runs, to every child script and helper, also when forge was
104
+ # started from an MSYS2 shell without it: native-port helpers must treat MSYS2 mode as POSIX.
105
+ export MSYSTEM=MSYS MSYS FORGE_WIN_MODE=msys2
106
+ # Worktree links must be relative: Git for Windows, which the native agent CLIs use, cannot follow
107
+ # the /c/... paths MSYS2's git writes. The setting travels in the environment, but the first
108
+ # worktree made with it adds extensions.relativeWorktrees to the repository's config, and from
109
+ # then on Git older than 2.48 (and libgit2- or JGit-based tools) refuses to open the repository.
110
+ # So both gits must be 2.48 or newer; children of this script inherit the result.
111
+ if [ -z "${FORGE_WIN_GIT_CHECKED:-}" ]; then
112
+ _forge_git_too_old() { # _forge_git_too_old <git> <how to update>: says why and succeeds when < 2.48
113
+ local version major minor
114
+ version="$("$1" --version 2>/dev/null)"
115
+ version="${version#git version }"
116
+ major="${version%%.*}"
117
+ minor="${version#*.}"
118
+ minor="${minor%%.*}"
119
+ case "$major.$minor" in
120
+ [0-9]*.[0-9]*) ;;
121
+ *) echo "forge: cannot read the version of $1 ('$version'); MSYS2 mode needs Git 2.48 or newer" >&2; return 0 ;;
122
+ esac
123
+ if [ "$major" -gt 2 ] || { [ "$major" -eq 2 ] && [ "$minor" -ge 48 ]; }; then return 1; fi
124
+ echo "forge: MSYS2 mode needs Git 2.48 or newer for relative worktree links; $1 is $version: $2" >&2
125
+ return 0
126
+ }
127
+ if _forge_git_too_old /usr/bin/git 'update MSYS2 with pacman -Syu'; then exit 127; fi
128
+ _forge_agent_git="$(PATH="${FORGE_WIN_AGENT_PATH:-$PATH}" command -v git)"
129
+ if [ -n "$_forge_agent_git" ] && [ "$_forge_agent_git" != /usr/bin/git ] \
130
+ && _forge_git_too_old "$_forge_agent_git" 'update Git for Windows'; then exit 127; fi
131
+ unset -f _forge_git_too_old
132
+ export FORGE_WIN_GIT_CHECKED=1
133
+ fi
134
+ case " ${GIT_CONFIG_KEY_0-} ${GIT_CONFIG_KEY_1-} ${GIT_CONFIG_KEY_2-} ${GIT_CONFIG_KEY_3-} " in
135
+ *" worktree.useRelativePaths "*) ;;
136
+ *) _forge_n="${GIT_CONFIG_COUNT:-0}"
137
+ export "GIT_CONFIG_KEY_$_forge_n=worktree.useRelativePaths" "GIT_CONFIG_VALUE_$_forge_n=true"
138
+ export GIT_CONFIG_COUNT="$((_forge_n + 1))" ;;
139
+ esac
140
+ # procps' pkill reads every /proc/<pid>/stat, which Cygwin fills by asking Windows: about half a
141
+ # second per process. forge only runs `pkill [-SIGNAL] -P <parent>`, which /proc/<pid>/ppid answers
142
+ # at once. Anything else goes to the real pkill. Scripts sourced after this file (forge-metrics.sh)
143
+ # get the function too.
144
+ pkill() {
145
+ local sig=TERM parent="" arg dir ppid found=1
146
+ for arg in "$@"; do
147
+ case "$arg" in -P) ;; -[A-Z]*|-[0-9]*) sig="${arg#-}" ;; [0-9]*) parent="$arg" ;; *) command pkill "$@"; return ;; esac
148
+ done
149
+ [ -n "$parent" ] || { command pkill "$@"; return; }
150
+ for dir in /proc/[0-9]*; do
151
+ read -r ppid < "$dir/ppid" 2>/dev/null || continue
152
+ [ "$ppid" = "$parent" ] && kill -s "$sig" "${dir#/proc/}" 2>/dev/null && found=0
153
+ done
154
+ return "$found"
155
+ }
156
+ unset _forge_msys _forge_tool _forge_n _forge_native _forge_agent_git
@@ -34,7 +34,6 @@ from __future__ import annotations
34
34
 
35
35
  import concurrent.futures
36
36
  import contextlib
37
- import fcntl
38
37
  import json
39
38
  import os
40
39
  from pathlib import Path
@@ -48,6 +47,7 @@ SCRIPTS = Path(__file__).resolve().parent.parent
48
47
  if str(SCRIPTS) not in sys.path:
49
48
  sys.path.insert(0, str(SCRIPTS))
50
49
 
50
+ import forge_flock as fcntl # noqa: E402
51
51
  import forge_groups # noqa: E402
52
52
  import forge_side # noqa: E402
53
53
 
@@ -392,7 +392,12 @@ def _task_lock(plan: Path, task: str):
392
392
  fcntl.flock(fd, fcntl.LOCK_EX)
393
393
  yield
394
394
  finally:
395
- os.close(fd)
395
+ # Unlocked before the close, not by it: on Cygwin a lock that only the close releases can leave
396
+ # another thread of this process waiting on it for ever.
397
+ try:
398
+ fcntl.flock(fd, fcntl.LOCK_UN)
399
+ finally:
400
+ os.close(fd)
396
401
 
397
402
 
398
403
  def _record(plan: Path, task: str, model: str, level: str, questions, error) -> dict:
@@ -79,7 +79,6 @@ import argparse
79
79
  import contextlib
80
80
  import difflib
81
81
  import io
82
- import fcntl
83
82
  import hashlib
84
83
  import json
85
84
  import os
@@ -87,10 +86,16 @@ from pathlib import Path
87
86
  import re
88
87
  import shlex
89
88
  import subprocess
89
+ import sys
90
90
  import tempfile
91
91
  import calendar
92
92
  import time
93
93
 
94
+ _SCRIPTS = str(Path(__file__).resolve().parents[1])
95
+ if _SCRIPTS not in sys.path:
96
+ sys.path.insert(0, _SCRIPTS)
97
+ import forge_flock as fcntl # noqa: E402
98
+ import forge_proc # noqa: E402
94
99
  import forge_brief
95
100
  import forge_brief.answers as answers
96
101
  import forge_groups
@@ -501,7 +506,12 @@ def _proposals_lock(plan):
501
506
  fcntl.flock(fd, fcntl.LOCK_EX)
502
507
  yield
503
508
  finally:
504
- os.close(fd)
509
+ # Unlocked before the close, not by it: on Cygwin a lock that only the close releases can leave
510
+ # another thread of this process waiting on it for ever.
511
+ try:
512
+ fcntl.flock(fd, fcntl.LOCK_UN)
513
+ finally:
514
+ os.close(fd)
505
515
 
506
516
 
507
517
  @contextlib.contextmanager
@@ -858,7 +868,7 @@ def _recompute_waves(plan) -> str | None:
858
868
  return None # an unplanned plan gains nothing, and waves.tsv is what marks one as planned
859
869
  script = Path(forge_brief.SCRIPTS) / 'forge-parallel.sh'
860
870
  try:
861
- done = subprocess.run(['/bin/bash', str(script), '_waves', str(plan)], stdin=subprocess.DEVNULL,
871
+ done = subprocess.run(forge_proc.bash_cmd(script, '_waves', str(plan)), stdin=subprocess.DEVNULL,
862
872
  capture_output=True, text=True, timeout=120)
863
873
  except (OSError, subprocess.SubprocessError) as error:
864
874
  return 'waves.tsv was not refreshed: %s' % error
@@ -16,13 +16,18 @@ library only.
16
16
  """
17
17
  from __future__ import annotations
18
18
 
19
- import fcntl
20
19
  import json
21
20
  import math
22
21
  import os
23
22
  from pathlib import Path
23
+ import sys
24
24
  import time
25
25
 
26
+ _SCRIPTS = str(Path(__file__).resolve().parents[1])
27
+ if _SCRIPTS not in sys.path:
28
+ sys.path.insert(0, _SCRIPTS)
29
+ import forge_flock as fcntl # noqa: E402
30
+
26
31
  from . import state_dir
27
32
 
28
33
  RUN_FILE = 'decide.budget.json'
@@ -114,15 +119,20 @@ def _add(path: Path, tokens: int, usd: float) -> None:
114
119
  path.parent.mkdir(parents=True, exist_ok=True)
115
120
  with open(f'{path}.lock', 'a') as lock:
116
121
  fcntl.flock(lock, fcntl.LOCK_EX)
117
- total = _read(path)
118
- total['tokens'] += tokens
119
- total['usd'] = _sum_usd(total['usd'], usd)
120
- tmp = path.with_name(f'{path.name}.{os.getpid()}.tmp')
121
122
  try:
122
- tmp.write_text(json.dumps(total))
123
- os.replace(tmp, path)
123
+ total = _read(path)
124
+ total['tokens'] += tokens
125
+ total['usd'] = _sum_usd(total['usd'], usd)
126
+ tmp = path.with_name(f'{path.name}.{os.getpid()}.tmp')
127
+ try:
128
+ tmp.write_text(json.dumps(total))
129
+ os.replace(tmp, path)
130
+ finally:
131
+ tmp.unlink(missing_ok=True)
124
132
  finally:
125
- tmp.unlink(missing_ok=True)
133
+ # Unlocked before the close, not by it: on Cygwin a lock that only the close releases
134
+ # can leave another thread of this process waiting on it for ever.
135
+ fcntl.flock(lock, fcntl.LOCK_UN)
126
136
  except Exception: # fail-open: a charge that cannot be recorded is dropped
127
137
  pass
128
138
 
@@ -19,14 +19,19 @@ from __future__ import annotations
19
19
 
20
20
  from concurrent.futures import ThreadPoolExecutor
21
21
  from dataclasses import dataclass, field
22
- import fcntl
23
22
  import json
24
23
  import os
25
24
  from pathlib import Path
25
+ import sys
26
26
  import threading
27
27
  import time
28
28
  from urllib.parse import quote
29
29
 
30
+ _SCRIPTS = str(Path(__file__).resolve().parents[1])
31
+ if _SCRIPTS not in sys.path:
32
+ sys.path.insert(0, _SCRIPTS)
33
+ import forge_flock as fcntl # noqa: E402
34
+
30
35
  from . import _save, providers, state_dir
31
36
  from . import labels, metrics, sites
32
37
 
@@ -292,10 +297,15 @@ def record(gate: str, result: dict) -> Path:
292
297
  _private_dir(path.parent)
293
298
  with open(f'{path}.lock', 'a') as lock:
294
299
  fcntl.flock(lock, fcntl.LOCK_EX)
295
- data = _load(path)
296
- results = data.get('results') if isinstance(data.get('results'), dict) else {}
297
- results['%s/%s' % (result['provider'], result['model'])] = {k: result[k] for k in _RECORDED if k in result}
298
- _save(path, dict(data, version=VERSION, results=results), 0o600)
300
+ try:
301
+ data = _load(path)
302
+ results = data.get('results') if isinstance(data.get('results'), dict) else {}
303
+ results['%s/%s' % (result['provider'], result['model'])] = {k: result[k] for k in _RECORDED if k in result}
304
+ _save(path, dict(data, version=VERSION, results=results), 0o600)
305
+ finally:
306
+ # Unlocked before the close, not by it: on Cygwin a lock that only the close releases
307
+ # can leave another thread of this process waiting on it for ever.
308
+ fcntl.flock(lock, fcntl.LOCK_UN)
299
309
  return path
300
310
 
301
311
 
@@ -28,6 +28,7 @@ if str(SCRIPTS) not in sys.path:
28
28
  sys.path.insert(0, str(SCRIPTS))
29
29
 
30
30
  import forge_identity # noqa: E402
31
+ import forge_posix # noqa: E402
31
32
  import forge_side # noqa: E402
32
33
  from forge_findings import store, triage # noqa: E402
33
34
 
@@ -320,7 +321,7 @@ def _restore(ident, captured):
320
321
  except FileNotFoundError:
321
322
  pass
322
323
  return
323
- fd = os.open(log, os.O_WRONLY | os.O_NOFOLLOW)
324
+ fd = forge_posix.open_nofollow(log, os.O_WRONLY | forge_posix.O_NOFOLLOW)
324
325
  try:
325
326
  os.ftruncate(fd, size)
326
327
  finally:
@@ -17,7 +17,6 @@ from __future__ import annotations
17
17
 
18
18
  import contextlib
19
19
  import errno
20
- import fcntl
21
20
  import json
22
21
  import os
23
22
  import re
@@ -30,7 +29,9 @@ from pathlib import Path
30
29
  _SCRIPTS = str(Path(__file__).resolve().parents[1])
31
30
  if _SCRIPTS not in sys.path:
32
31
  sys.path.insert(0, _SCRIPTS)
32
+ import forge_flock as fcntl # noqa: E402
33
33
  import forge_identity # noqa: E402
34
+ import forge_posix # noqa: E402
34
35
  import forge_registry # noqa: E402
35
36
 
36
37
  STATUSES = ("open", "to-file", "filed", "fixed", "dismissed", "duplicate")
@@ -131,7 +132,11 @@ def lock(ident):
131
132
  key = _key(ident)
132
133
  path = _store_dir(create=True) / f"{key}.lock"
133
134
  try:
134
- fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
135
+ fd = forge_posix.open_nofollow(
136
+ path,
137
+ os.O_RDWR | os.O_CREAT | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
138
+ 0o600,
139
+ )
135
140
  except OSError as exc:
136
141
  raise Corrupt(f"{path}: cannot open the repository lock ({exc.strerror}); it must not be a symlink")
137
142
  try:
@@ -162,7 +167,10 @@ def _read_json(path: Path, noun: str):
162
167
  if not stat.S_ISREG(os.lstat(path).st_mode):
163
168
  raise Corrupt(not_regular)
164
169
  # NOFOLLOW again for a swap after the lstat; NONBLOCK so a FIFO cannot hold the open
165
- with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), "rb") as fh:
170
+ with os.fdopen(
171
+ forge_posix.open_nofollow(path, os.O_RDONLY | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK),
172
+ "rb",
173
+ ) as fh:
166
174
  if not stat.S_ISREG(os.fstat(fh.fileno()).st_mode):
167
175
  raise Corrupt(not_regular)
168
176
  raw = fh.read(FILE_MAX + 1)
@@ -314,7 +322,11 @@ def _append_log(ident, lines: list) -> None:
314
322
  try:
315
323
  base = _store_dir(create=True)
316
324
  path = base / f"{_key(ident)}.record.log.jsonl"
317
- fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
325
+ fd = forge_posix.open_nofollow(
326
+ path,
327
+ os.O_WRONLY | os.O_APPEND | os.O_CREAT | forge_posix.O_NOFOLLOW | forge_posix.O_NONBLOCK,
328
+ 0o600,
329
+ )
318
330
  try:
319
331
  if not stat.S_ISREG(os.fstat(fd).st_mode):
320
332
  return
@@ -12,7 +12,6 @@ done, and the dispatch's own side.last / side.resolved.
12
12
  """
13
13
  from __future__ import annotations
14
14
 
15
- import fcntl
16
15
  import hashlib
17
16
  import importlib.util
18
17
  import json
@@ -27,6 +26,8 @@ SCRIPTS = Path(__file__).resolve().parent.parent
27
26
  if str(SCRIPTS) not in sys.path:
28
27
  sys.path.insert(0, str(SCRIPTS))
29
28
 
29
+ import forge_flock as fcntl # noqa: E402
30
+ import forge_proc # noqa: E402
30
31
  import forge_side # noqa: E402
31
32
 
32
33
  DISPATCH = SCRIPTS / "forge-dispatch.sh"
@@ -156,17 +157,7 @@ def read_json(path):
156
157
 
157
158
 
158
159
  def alive(pid) -> bool:
159
- if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
160
- return False
161
- try:
162
- os.kill(pid, 0)
163
- except ProcessLookupError:
164
- return False
165
- except PermissionError:
166
- return True
167
- except OSError:
168
- return False
169
- return True
160
+ return forge_proc.pid_alive(pid)
170
161
 
171
162
 
172
163
  class _Lock:
@@ -453,7 +444,7 @@ def reason_of(error) -> str:
453
444
 
454
445
  def preflight(spec) -> None:
455
446
  """`forge-dispatch.sh doctor --spec S --role side`. Raises Refused with its message."""
456
- argv = ["/bin/bash", str(DISPATCH), "doctor", "--spec", str(spec), "--role", "side"]
447
+ argv = forge_proc.bash_cmd(DISPATCH, "doctor", "--spec", str(spec), "--role", "side")
457
448
  try:
458
449
  result = subprocess.run(argv, capture_output=True, text=True, stdin=subprocess.DEVNULL,
459
450
  timeout=DOCTOR_TIMEOUT)
@@ -521,9 +512,9 @@ def detach(dest, argv):
521
512
  done = dest / "done"
522
513
  wrapper = '"${@:2}"; rc=$?; printf "%s\\n" "$rc" > "$1.tmp" && mv -f "$1.tmp" "$1"; exit "$rc"'
523
514
  with open(dest / "triage.out", "ab") as out:
524
- process = subprocess.Popen(["/bin/bash", "-c", wrapper, "forge-triage", str(done), *argv],
515
+ process = subprocess.Popen(forge_proc.bash_cmd("-c", wrapper, "forge-triage", str(done), *argv),
525
516
  stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT,
526
- start_new_session=True, close_fds=True)
517
+ close_fds=True, **forge_proc.popen_group_kwargs(detached=True))
527
518
  with _Lock(dest / "state.lock"):
528
519
  state = read_json(dest / "state.json")
529
520
  if isinstance(state, dict) and state.get("state") == "running":