agent-formal-verify 0.4.12 → 0.4.13

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 (38) hide show
  1. package/CHANGES.md +136 -0
  2. package/README.md +5 -3
  3. package/package.json +2 -1
  4. package/skills/formal-verify/SKILL.md +11 -13
  5. package/skills/formal-verify/examples/kani-template/src/lib.rs +5 -6
  6. package/skills/formal-verify/examples/lean-template/Model/BoundedQueue.statements +10 -45
  7. package/skills/formal-verify/examples/tla-template/BoundedQueue.matrix +16 -13
  8. package/skills/formal-verify/examples/tla-template/BoundedQueue.mutations +92 -14
  9. package/skills/formal-verify/examples/tla-template/BoundedQueue.tla +169 -28
  10. package/skills/formal-verify/references/evidence.md +1 -1
  11. package/skills/formal-verify/references/helpers.md +4 -3
  12. package/skills/formal-verify/references/lean-brief.md +2 -2
  13. package/skills/formal-verify/references/rust-brief.md +58 -6
  14. package/skills/formal-verify/references/setup.md +23 -7
  15. package/skills/formal-verify/references/tla-brief.md +2 -2
  16. package/skills/formal-verify/scripts/baseline.py +564 -66
  17. package/skills/formal-verify/scripts/kani-check.sh +3 -1
  18. package/skills/formal-verify/scripts/kani.py +127 -59
  19. package/skills/formal-verify/scripts/lean-analysis.lean +387 -0
  20. package/skills/formal-verify/scripts/lean-check.sh +6 -243
  21. package/skills/formal-verify/scripts/lean.py +484 -0
  22. package/skills/formal-verify/scripts/lean_mutations.py +195 -0
  23. package/skills/formal-verify/scripts/lean_records.py +25 -0
  24. package/skills/formal-verify/scripts/mutate.py +81 -195
  25. package/skills/formal-verify/scripts/processes.py +266 -0
  26. package/skills/formal-verify/scripts/python-tools.sh +15 -0
  27. package/skills/formal-verify/scripts/runner.py +56 -0
  28. package/skills/formal-verify/scripts/setup.sh +18 -19
  29. package/skills/formal-verify/scripts/storage.py +207 -0
  30. package/skills/formal-verify/scripts/sync.py +401 -0
  31. package/skills/formal-verify/scripts/tlc-matrix.sh +3 -1
  32. package/skills/formal-verify/scripts/tlc.py +423 -116
  33. package/skills/formal-verify/scripts/{tlc-trace.py → tlc_trace.py} +16 -10
  34. package/skills/setup/SKILL.md +1 -1
  35. package/skills/formal-verify/scripts/lean-mutations.lean +0 -95
  36. package/skills/formal-verify/scripts/lean-statements.py +0 -161
  37. package/skills/formal-verify/scripts/lean-tools.sh +0 -24
  38. package/skills/formal-verify/scripts/tlc-tools.sh +0 -47
@@ -0,0 +1,266 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) 2026 Michael Denyer
3
+ # SPDX-License-Identifier: GPL-3.0-only
4
+ """Run checkers so that a signal or an error stops each one and every process it started.
5
+
6
+ Usage: processes.py run <command> [<argument> ...]
7
+ Run a command on this process's streams; a shell script runs a long step through here so that its
8
+ signal trap can stop the step's whole process tree. Exits with the command's status as a shell reports it.
9
+ """
10
+ import os
11
+ import signal
12
+ import subprocess
13
+ import sys
14
+ import threading
15
+ import time
16
+ from contextlib import contextmanager, suppress
17
+
18
+ # While guarded starts a process, the signals that signal_cleanup catches wait here until the process can be stopped.
19
+ _deferred = None
20
+ # Bounds on one stop: how long its ps listings of the checker's descendants may take together,
21
+ # and how many it takes before signalling what it found, in case a process keeps starting others.
22
+ PS_TIMEOUT = 5
23
+ MAX_LISTINGS = 50
24
+ # The termination signals that signal_cleanup converts and that a stop holds back until it finishes.
25
+ HANDLED = (signal.SIGINT, signal.SIGTERM, *((signal.SIGHUP,) if hasattr(signal, "SIGHUP") else ()))
26
+
27
+
28
+ class SignalTerminated(BaseException):
29
+ """Raised on handled termination signals so context managers and finally blocks still clean up."""
30
+
31
+ def __init__(self, signum):
32
+ self.signum = signum
33
+ self.status = 128 + signum
34
+ super().__init__(f"terminated by signal {signum}")
35
+
36
+ def exit(self):
37
+ """End the process by the signal itself, so a calling shell stops as it would without the cleanup."""
38
+ with suppress(OSError):
39
+ sys.stdout.flush()
40
+ sys.stderr.flush()
41
+ signal.signal(self.signum, signal.SIG_DFL)
42
+ os.kill(os.getpid(), self.signum)
43
+ sys.exit(self.status)
44
+
45
+
46
+ @contextmanager
47
+ def signal_cleanup():
48
+ """Convert non-ignored termination signals into SignalTerminated on the main thread."""
49
+ if threading.current_thread() is not threading.main_thread():
50
+ yield
51
+ return
52
+ state = {"caught": False}
53
+ previous = {}
54
+
55
+ def handle(signum, _frame):
56
+ if state["caught"]:
57
+ return
58
+ state["caught"] = True
59
+ if _deferred is not None:
60
+ _deferred.append(signum)
61
+ return
62
+ raise SignalTerminated(signum)
63
+
64
+ for signum in HANDLED:
65
+ current = signal.getsignal(signum)
66
+ if current is signal.SIG_IGN:
67
+ continue
68
+ previous[signum] = current
69
+ signal.signal(signum, handle)
70
+ try:
71
+ yield
72
+ finally:
73
+ for signum, handler in previous.items():
74
+ signal.signal(signum, handler)
75
+
76
+
77
+ def _listing(columns, timeout):
78
+ """Return each process's fields for the ps columns, in one snapshot, or None when ps fails or takes too long."""
79
+ try:
80
+ process = subprocess.Popen(["ps", "-A", "-o", columns], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
81
+ text=True)
82
+ except OSError:
83
+ return None
84
+ try:
85
+ stdout = process.communicate(timeout=timeout)[0]
86
+ except subprocess.TimeoutExpired:
87
+ stdout = None
88
+ finally:
89
+ if process.returncode is None:
90
+ process.kill()
91
+ # A ps in uninterruptible sleep cannot die until its read returns, so it is left behind, not waited for.
92
+ with suppress(subprocess.TimeoutExpired):
93
+ process.wait(timeout=1)
94
+ if stdout is None or process.returncode:
95
+ return None
96
+ return [line.split() for line in stdout.splitlines()]
97
+
98
+
99
+ def _descendants(pid, timeout):
100
+ """Return the pids of every process below pid in one ps snapshot, or None when ps fails or takes too long."""
101
+ listing = _listing("pid=,ppid=", timeout)
102
+ if listing is None:
103
+ return None
104
+ children = {}
105
+ for fields in listing:
106
+ if len(fields) == 2 and fields[0].isdigit() and fields[1].isdigit():
107
+ children.setdefault(int(fields[1]), []).append(int(fields[0]))
108
+ found, pending = [], [pid]
109
+ while pending:
110
+ below = children.get(pending.pop(), [])
111
+ found += below
112
+ pending += below
113
+ return found
114
+
115
+
116
+ def stop_process(process):
117
+ """Terminate a spawned subprocess and the processes it started, keeping them in the caller's process group.
118
+
119
+ The termination signals that signal_cleanup handles are blocked for the whole stop, so a signal that arrives
120
+ meanwhile is raised once every process is gone and no step of the stop is cut short.
121
+ """
122
+ if process.poll() is not None:
123
+ return
124
+ # Save the mask before blocking: a handler that runs inside the blocking call can raise, and must leave it restored.
125
+ blocked = signal.pthread_sigmask(signal.SIG_BLOCK, ())
126
+ try:
127
+ signal.pthread_sigmask(signal.SIG_BLOCK, HANDLED)
128
+ _stop(process)
129
+ finally:
130
+ signal.pthread_sigmask(signal.SIG_SETMASK, blocked)
131
+
132
+
133
+ def _stop(process):
134
+ # Freeze the tree before signalling it: a stopped process cannot start another or leave its children orphaned.
135
+ frozen = [process.pid]
136
+ listing_deadline = time.monotonic() + PS_TIMEOUT
137
+ try:
138
+ with suppress(ProcessLookupError):
139
+ process.send_signal(signal.SIGSTOP)
140
+ if process.returncode is not None:
141
+ return
142
+ for _ in range(MAX_LISTINGS):
143
+ listed = _descendants(process.pid, max(0, listing_deadline - time.monotonic()))
144
+ if listed is None:
145
+ sys.stderr.write("WARN ps cannot list the processes that the checker started; they may still be running\n")
146
+ break
147
+ new = [pid for pid in listed if pid not in frozen]
148
+ if not new:
149
+ break
150
+ frozen += new
151
+ for pid in new:
152
+ with suppress(OSError):
153
+ os.kill(pid, signal.SIGSTOP)
154
+ else:
155
+ sys.stderr.write(f"WARN the checker kept starting processes through {MAX_LISTINGS} ps listings; "
156
+ "processes it started later may still be running\n")
157
+ finally:
158
+ # An error in the listings, such as a warning that cannot be written, must not leave the frozen tree suspended.
159
+ # send_signal reaps a checker that exited since poll and signals nothing; its pid is then free for reuse.
160
+ if process.returncode is not None:
161
+ frozen.remove(process.pid)
162
+ for signum in (signal.SIGTERM, signal.SIGCONT):
163
+ for pid in frozen:
164
+ with suppress(OSError):
165
+ os.kill(pid, signum)
166
+ survivors = [pid for pid in frozen if pid != process.pid]
167
+ deadline = time.monotonic() + 2
168
+ with suppress(subprocess.TimeoutExpired):
169
+ process.wait(timeout=2)
170
+ while survivors and time.monotonic() < deadline:
171
+ survivors = _running(survivors)
172
+ if survivors:
173
+ time.sleep(0.05)
174
+ if process.returncode is None:
175
+ with suppress(ProcessLookupError):
176
+ process.kill()
177
+ process.wait()
178
+ # A descendant that ignores SIGTERM, as one that inherits an ignored SIGTERM does, gets SIGKILL as the checker does.
179
+ if survivors:
180
+ for pid in _running(survivors):
181
+ with suppress(OSError):
182
+ os.kill(pid, signal.SIGKILL)
183
+
184
+
185
+ def _running(pids):
186
+ """Return the pids that still run. A zombie has exited, though a parent that never reaps keeps its pid."""
187
+ listing = _listing("pid=,stat=", PS_TIMEOUT)
188
+ if listing is None:
189
+ return [pid for pid in pids if _exists(pid)]
190
+ running = {int(fields[0]) for fields in listing
191
+ if len(fields) == 2 and fields[0].isdigit() and not fields[1].startswith("Z")}
192
+ return [pid for pid in pids if pid in running]
193
+
194
+
195
+ def _exists(pid):
196
+ try:
197
+ os.kill(pid, 0)
198
+ except OSError:
199
+ return False
200
+ return True
201
+
202
+
203
+ def guarded(command, body, **kwargs):
204
+ """Start a command with Popen, return body(process), and stop the process if anything, a signal included, ends body early.
205
+
206
+ A signal that arrives while Popen runs, which waits for the command to start, is raised only once the
207
+ process exists. From then until body returns, every point where a signal handler can run is inside the
208
+ try that stops the process, which a context manager's __enter__ could not guarantee.
209
+ """
210
+ global _deferred
211
+ _deferred = deferred = []
212
+ try:
213
+ process = subprocess.Popen(command, **kwargs)
214
+ except BaseException:
215
+ _deferred = None
216
+ if not deferred:
217
+ raise
218
+ raise SignalTerminated(deferred[0]) from None
219
+ try:
220
+ _deferred = None
221
+ if deferred:
222
+ raise SignalTerminated(deferred[0])
223
+ return body(process)
224
+ except BaseException:
225
+ stop_process(process)
226
+ raise
227
+
228
+
229
+ def run_captured(command, **kwargs):
230
+ """Run a command in the caller's process group and terminate it cleanly on interruption."""
231
+ def collect(process):
232
+ stdout, stderr = process.communicate()
233
+ return subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
234
+ return guarded(command, collect, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, **kwargs)
235
+
236
+
237
+ def run_inherited(command):
238
+ """Run a command on this process's streams and return its exit status as a shell reports it."""
239
+ started = []
240
+
241
+ def wait(process):
242
+ started.append(process)
243
+ return process.wait()
244
+ try:
245
+ status = guarded(command, wait)
246
+ except OSError as error:
247
+ if started:
248
+ raise
249
+ print(f"cannot run {command[0]}: {error}", file=sys.stderr)
250
+ return 127
251
+ return 128 - status if status < 0 else status
252
+
253
+
254
+ def main():
255
+ if len(sys.argv) < 3 or sys.argv[1] != "run":
256
+ print("usage: processes.py run <command> [<argument> ...]", file=sys.stderr)
257
+ return 2
258
+ try:
259
+ with signal_cleanup():
260
+ return run_inherited(sys.argv[2:])
261
+ except SignalTerminated as error:
262
+ error.exit()
263
+
264
+
265
+ if __name__ == "__main__":
266
+ sys.exit(main())
@@ -0,0 +1,15 @@
1
+ #!/bin/bash
2
+ # Copyright (c) 2026 Michael Denyer
3
+ # SPDX-License-Identifier: GPL-3.0-only
4
+ # Shared Python check for the helpers, which need Python 3.9 or later as python3.
5
+
6
+ require_python() {
7
+ local version
8
+ version=$(python3 -c 'import sys; print("%d.%d.%d" % sys.version_info[:3]); sys.exit(sys.version_info < (3, 9))' 2> /dev/null) && return 0
9
+ if [ -n "$version" ]; then
10
+ echo "UNAVAILABLE python3 is Python $version; install Python 3.9 or later"
11
+ else
12
+ echo "UNAVAILABLE python3 is not on PATH or does not run; install Python 3.9 or later"
13
+ fi
14
+ return 3
15
+ }
@@ -0,0 +1,56 @@
1
+ # Copyright (c) 2026 Michael Denyer
2
+ # SPDX-License-Identifier: GPL-3.0-only
3
+ """What the checker runners share: the unavailable-tool error, time limits, atomic writes and the entry point."""
4
+ import os
5
+ import re
6
+ import sys
7
+ import tempfile
8
+ from pathlib import Path
9
+
10
+ sys.dont_write_bytecode = True
11
+ import processes
12
+ import storage
13
+
14
+ LIMIT = re.compile(r"\+?0*([1-9][0-9]{0,9})([smh]?)")
15
+ SECONDS = {"": 1, "s": 1, "m": 60, "h": 3600}
16
+
17
+
18
+ class Unavailable(Exception):
19
+ """A tool the check needs is missing, unusable or unverified. The message is the UNAVAILABLE line to print."""
20
+
21
+
22
+ def parse_limit(setting, raw, kind, default):
23
+ """Return a time limit's label with its unit and its length in seconds, or raise Unavailable naming the setting."""
24
+ limit = LIMIT.fullmatch(raw)
25
+ if not limit or int(limit[1]) >= 2**32:
26
+ raise Unavailable(f"UNAVAILABLE {setting}={raw!r} is not a {kind}; set a whole number from 1 to 4294967295 "
27
+ f"with an optional unit s, m or h, such as 90s or 20m, or unset it for {default}")
28
+ return limit[1] + (limit[2] or "s"), int(limit[1]) * SECONDS[limit[2]]
29
+
30
+
31
+ def atomic_write(path, text):
32
+ """Replace a file's content in one step, so a reader never sees it half written."""
33
+ path = Path(path)
34
+ descriptor, temporary = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
35
+ try:
36
+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
37
+ stream.write(text)
38
+ os.replace(temporary, path)
39
+ finally:
40
+ Path(temporary).unlink(missing_ok=True)
41
+
42
+
43
+ def run(main):
44
+ """Exit with main's status: 1 when TMPDIR is unusable, 3 when a tool is unavailable, or by a handled signal."""
45
+ try:
46
+ with processes.signal_cleanup():
47
+ status = main()
48
+ except storage.TempDirError as error:
49
+ print(error)
50
+ status = 1
51
+ except Unavailable as error:
52
+ print(error)
53
+ status = 3
54
+ except processes.SignalTerminated as error:
55
+ error.exit()
56
+ sys.exit(status)
@@ -2,34 +2,33 @@
2
2
  # Copyright (c) 2026 Michael Denyer
3
3
  # SPDX-License-Identifier: GPL-3.0-only
4
4
  # Ensures one tool is ready; system runtimes must already be installed.
5
+ # Each Python readiness check replaces this shell through exec, so a signal sent to this process reaches the check,
6
+ # which stops its probe and ends by the signal. A shell waiting for the check would hold the signal until it ended.
5
7
  set -euo pipefail
6
8
  HERE=$(cd "$(dirname "$0")" && pwd)
9
+ # shellcheck source=skills/formal-verify/scripts/python-tools.sh
10
+ source "$HERE/python-tools.sh"
11
+
7
12
  case ${1:-} in
8
13
  tla)
9
- # shellcheck source=skills/formal-verify/scripts/tlc-tools.sh
10
- source "$HERE/tlc-tools.sh"
11
- require_tlc_runtime
12
- tlc_jar_ready
13
- echo "READY TLC $TLC_JAR"
14
+ [ "$#" -eq 1 ] || { echo "usage: setup.sh tla"; exit 2; }
15
+ require_python || exit 3
16
+ exec python3 "$HERE/tlc.py" ready
14
17
  ;;
15
18
  rust)
16
19
  [ "$#" -eq 1 ] || { echo "usage: setup.sh rust"; exit 2; }
17
- command -v python3 > /dev/null || { echo "UNAVAILABLE python3 is required; install Python 3"; exit 3; }
18
- python3 "$HERE/kani.py" ready
20
+ require_python || exit 3
21
+ exec python3 "$HERE/kani.py" ready
19
22
  ;;
20
23
  lean)
21
24
  [ "$#" -eq 2 ] || { echo "usage: setup.sh lean <lake-project-dir>"; exit 2; }
22
- dir=$2
23
- # shellcheck source=skills/formal-verify/scripts/lean-tools.sh
24
- source "$HERE/lean-tools.sh"
25
- toolchain=$(lean_pin "$dir") || { status=$?; echo "$toolchain"; exit "$status"; }
26
- if ! lean_pin_ready "$toolchain"; then
27
- install_log=$(elan toolchain install "$toolchain" 2>&1) \
28
- || { echo "UNAVAILABLE cannot install $toolchain; run elan toolchain install $toolchain"; echo "$install_log"; exit 3; }
29
- lean_pin_ready "$toolchain" || { echo "UNAVAILABLE $toolchain does not run after installation; check elan toolchain list and reinstall it"; echo "$install_log"; exit 3; }
30
- [ -z "$install_log" ] || echo "$install_log"
31
- fi
32
- echo "READY Lean $toolchain"
25
+ require_python || exit 3
26
+ exec python3 "$HERE/lean.py" ready "$2"
33
27
  ;;
34
- *) echo "usage: setup.sh tla | setup.sh lean <lake-project-dir> | setup.sh rust"; exit 2 ;;
28
+ storage)
29
+ [ "$#" -eq 1 ] || { echo "usage: setup.sh storage"; exit 2; }
30
+ require_python || exit 3
31
+ python3 "$HERE/storage.py" report
32
+ ;;
33
+ *) echo "usage: setup.sh tla | setup.sh lean <lake-project-dir> | setup.sh rust | setup.sh storage"; exit 2 ;;
35
34
  esac
@@ -0,0 +1,207 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) 2026 Michael Denyer
3
+ # SPDX-License-Identifier: GPL-3.0-only
4
+ """Choose the temporary directory for checker runs and check its free space.
5
+
6
+ Usage: storage.py report | storage.py warn
7
+ report print the temporary directory, the system disk when it differs, a WARN line when either is low,
8
+ and larger writable local volumes as EXTERNAL_VOLUME lines with a suggested TMPDIR
9
+ warn print one warning to stderr when the temporary directory is critically low
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import shlex
15
+ import shutil
16
+ import stat
17
+ import subprocess
18
+ import sys
19
+ import tempfile
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+
23
+ GIB = 1024**3
24
+ DEFAULT_PREFLIGHT_MIN_GIB = 64
25
+ DEFAULT_RUNTIME_MIN_GIB = 10
26
+ SKIP_MOUNT_PREFIXES = (
27
+ "/dev",
28
+ "/proc",
29
+ "/sys",
30
+ "/run",
31
+ "/System",
32
+ "/Volumes/.timemachine",
33
+ "/Volumes/Recovery",
34
+ )
35
+
36
+ _warned_runtime = False
37
+
38
+
39
+ class TempDirError(Exception):
40
+ """Raised when an explicitly set TMPDIR cannot be created or written."""
41
+
42
+
43
+ def ensure_temp_root():
44
+ """Ensure explicit TMPDIR exists and is writable so tempfile never silently falls back."""
45
+ configured = os.environ.get("TMPDIR", "").strip()
46
+ if configured:
47
+ path = Path(configured)
48
+ try:
49
+ path.mkdir(parents=True, exist_ok=True)
50
+ except OSError as error:
51
+ raise TempDirError(f"FAIL TMPDIR={configured!r} cannot be created: {error}") from error
52
+ if not path.is_dir() or not os.access(path, os.W_OK):
53
+ raise TempDirError(f"FAIL TMPDIR={configured!r} is not a writable directory")
54
+ return path.resolve()
55
+ return Path(tempfile.gettempdir()).resolve()
56
+
57
+
58
+ def _min_free_gib(default):
59
+ raw = os.environ.get("FORMAL_MIN_FREE_GIB", "").strip()
60
+ if not raw:
61
+ return default
62
+ if raw.isdigit():
63
+ return int(raw)
64
+ return default
65
+
66
+
67
+ def _skipped_mount(mount):
68
+ if mount == "/":
69
+ return True
70
+ return any(mount == prefix or mount.startswith(prefix + "/") for prefix in SKIP_MOUNT_PREFIXES)
71
+
72
+
73
+ def parse_df_mounts(
74
+ df_text,
75
+ temp_root,
76
+ root_path=Path("/"),
77
+ *,
78
+ stat_fn=os.stat,
79
+ access_fn=os.access,
80
+ usage_fn=shutil.disk_usage,
81
+ ):
82
+ """Return writable local mounted volume directories with more free space than temp_root."""
83
+ temp_free = usage_fn(temp_root).free
84
+ seen_devs = {stat_fn(temp_root).st_dev, stat_fn(root_path).st_dev}
85
+ candidates = {}
86
+ for line in df_text.splitlines()[1:]:
87
+ parts = line.split(None, 5)
88
+ if len(parts) != 6:
89
+ continue
90
+ mount = parts[5].strip()
91
+ if not mount or _skipped_mount(mount):
92
+ continue
93
+ try:
94
+ st = stat_fn(mount)
95
+ if not stat.S_ISDIR(st.st_mode):
96
+ continue
97
+ dev = st.st_dev
98
+ if dev in seen_devs or not access_fn(mount, os.W_OK):
99
+ continue
100
+ free = usage_fn(mount).free
101
+ except OSError:
102
+ continue
103
+ if free > temp_free:
104
+ existing = candidates.get(dev)
105
+ if existing is None or len(mount) < len(existing[0]):
106
+ candidates[dev] = (mount, free)
107
+ return sorted(candidates.values(), key=lambda item: (-item[1], item[0]))
108
+
109
+
110
+ @dataclass(frozen=True)
111
+ class StorageReport:
112
+ temp_root: Path
113
+ temp_free: int
114
+ root_free: int
115
+ same_device: bool
116
+ min_gib: int
117
+ candidates: tuple
118
+
119
+
120
+ def inspect_storage(default_min_gib=DEFAULT_PREFLIGHT_MIN_GIB):
121
+ """Inspect active temporary storage, system root free space, and writable larger local volumes."""
122
+ temp_root = ensure_temp_root()
123
+ root_path = Path("/")
124
+ temp_free = shutil.disk_usage(temp_root).free
125
+ root_free = shutil.disk_usage(root_path).free
126
+ same_device = os.stat(temp_root).st_dev == os.stat(root_path).st_dev
127
+ min_gib = _min_free_gib(default_min_gib)
128
+ candidates = []
129
+ try:
130
+ done = subprocess.run(["df", "-lkP"], capture_output=True, text=True, check=False)
131
+ if done.returncode == 0 and done.stdout:
132
+ candidates = parse_df_mounts(done.stdout, temp_root, root_path)
133
+ except OSError:
134
+ candidates = []
135
+ return StorageReport(temp_root, temp_free, root_free, same_device, min_gib, tuple(candidates))
136
+
137
+
138
+ def _suggested_tmpdir(mount):
139
+ return shlex.quote(str(Path(mount) / ".tmp" / "formal-verify"))
140
+
141
+
142
+ def format_report(report):
143
+ """Format preflight storage lines for setup.sh and interactive agent checks."""
144
+ lines = [f"TEMP_DIR {report.temp_root} ({report.temp_free / GIB:.1f} GiB free)"]
145
+ if not report.same_device:
146
+ lines.append(f"SYSTEM_DISK / ({report.root_free / GIB:.1f} GiB free)")
147
+ threshold = report.min_gib * GIB
148
+ # Warn on / only when TMPDIR still shares the root device; once TMPDIR moves off /,
149
+ # a low root volume should not repeat an unclearable warning.
150
+ low_temp = report.min_gib > 0 and report.temp_free < threshold
151
+ low_root = report.same_device and report.min_gib > 0 and report.root_free < threshold
152
+ if low_temp or low_root:
153
+ lines.append(
154
+ f"WARN low free space (< {report.min_gib} GiB): temp dir {report.temp_root} has "
155
+ f"{report.temp_free / GIB:.1f} GiB free, system disk / has {report.root_free / GIB:.1f} GiB free; "
156
+ "TLC disk queues or Kani build dirs may exhaust disk space. Set TMPDIR=<dir> to choose another volume."
157
+ )
158
+ for mount, free in report.candidates:
159
+ lines.append(f"EXTERNAL_VOLUME {mount} ({free / GIB:.1f} GiB free; suggested TMPDIR={_suggested_tmpdir(mount)})")
160
+ return lines
161
+
162
+
163
+ def report():
164
+ """Print the preflight storage lines, as setup.sh reports them after each tool's readiness check."""
165
+ for line in format_report(inspect_storage()):
166
+ print(line)
167
+
168
+
169
+ def warn_runtime():
170
+ """Emit a single per-process stderr warning if active temporary space is critically low."""
171
+ global _warned_runtime
172
+ if _warned_runtime:
173
+ return
174
+ _warned_runtime = True
175
+ report = inspect_storage(DEFAULT_RUNTIME_MIN_GIB)
176
+ if report.min_gib <= 0:
177
+ return
178
+ threshold = report.min_gib * GIB
179
+ if report.temp_free >= threshold:
180
+ return
181
+ sys.stderr.write(
182
+ f"WARN low free space on temp dir {report.temp_root}: {report.temp_free / GIB:.1f} GiB free "
183
+ f"(< {report.min_gib} GiB); set TMPDIR=<dir> to use another volume.\n"
184
+ )
185
+ for mount, free in report.candidates:
186
+ sys.stderr.write(f"WARN candidate volume {mount} ({free / GIB:.1f} GiB free; suggested TMPDIR={_suggested_tmpdir(mount)})\n")
187
+ sys.stderr.flush()
188
+
189
+
190
+ def main():
191
+ action = sys.argv[1] if len(sys.argv) == 2 else ""
192
+ try:
193
+ if action == "report":
194
+ report()
195
+ return 0
196
+ if action == "warn":
197
+ warn_runtime()
198
+ return 0
199
+ except TempDirError as error:
200
+ print(error)
201
+ return 1
202
+ print("usage: storage.py report | storage.py warn", file=sys.stderr)
203
+ return 2
204
+
205
+
206
+ if __name__ == "__main__":
207
+ sys.exit(main())