Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

Update resource detection workflows

Timothy Kassisd80ca055ef36
diff --git a/skills/get-available-resources/SKILL.md b/skills/get-available-resources/SKILL.md
index 21f7a8ce..90155067 100644
--- a/skills/get-available-resources/SKILL.md
+++ b/skills/get-available-resources/SKILL.md
@@ -1,274 +1,260 @@
---
name: get-available-resources
-description: This skill should be used at the start of any computationally intensive scientific task to detect and report available system resources (CPU cores, GPUs, memory, disk space). It creates a JSON file with resource information and strategic recommendations that inform computational approach decisions such as whether to use parallel processing (joblib, multiprocessing), out-of-core computing (Dask, Zarr), GPU acceleration (PyTorch, JAX), or memory-efficient strategies. Use this skill before running analyses, training models, processing large datasets, or any task where resource constraints matter.
-license: MIT license
-metadata: {"version": "1.0", "skill-author": "K-Dense Inc."}
+description: Detect host inventory and effective CPU, memory, disk, scheduler, container, and accelerator limits when a user asks for resource-aware planning or before a clearly resource-sensitive local workload. Produces a redacted JSON snapshot and conservative planning helpers without stress tests or assuming visible host hardware is usable.
+license: MIT
+compatibility: Python 3.11+ on Linux, macOS, or Windows; standard library by default, optional psutil 7.2.2; accelerator and scheduler CLIs are optional read-only probes.
+metadata:
+ version: "1.1"
+ skill-author: K-Dense Inc.
---
# Get Available Resources
-## Overview
-
-Detect available computational resources and generate strategic recommendations for scientific computing tasks. This skill automatically identifies CPU capabilities, GPU availability (NVIDIA CUDA, AMD ROCm, Apple Silicon Metal), memory constraints, and disk space to help make informed decisions about computational approaches.
-
-## When to Use This Skill
-
-Use this skill proactively before any computationally intensive task:
-
-- **Before data analysis**: Determine if datasets can be loaded into memory or require out-of-core processing
-- **Before model training**: Check if GPU acceleration is available and which backend to use
-- **Before parallel processing**: Identify optimal number of workers for joblib, multiprocessing, or Dask
-- **Before large file operations**: Verify sufficient disk space and appropriate storage strategies
-- **At project initialization**: Understand baseline capabilities for making architectural decisions
-
-**Example scenarios:**
-- "Help me analyze this 50GB genomics dataset" → Use this skill first to determine if Dask/Zarr are needed
-- "Train a neural network on this data" → Use this skill to detect available GPUs and backends
-- "Process 10,000 files in parallel" → Use this skill to determine optimal worker count
-- "Run a computationally intensive simulation" → Use this skill to understand resource constraints
-
-## How This Skill Works
-
-### Resource Detection
-
-The skill runs `scripts/detect_resources.py` to automatically detect:
-
-1. **CPU Information**
- - Physical and logical core counts
- - Processor architecture and model
- - CPU frequency information
-
-2. **GPU Information**
- - NVIDIA GPUs: Detects via nvidia-smi, reports VRAM, driver version, compute capability
- - AMD GPUs: Detects via rocm-smi
- - Apple Silicon: Detects M1/M2/M3/M4 chips with Metal support and unified memory
-
-3. **Memory Information**
- - Total and available RAM
- - Current memory usage percentage
- - Swap space availability
-
-4. **Disk Space Information**
- - Total and available disk space for working directory
- - Current usage percentage
-
-5. **Operating System Information**
- - OS type (macOS, Linux, Windows)
- - OS version and release
- - Python version
-
-### Output Format
-
-The skill generates a `.claude_resources.json` file in the current working directory containing:
-
-```json
-{
- "timestamp": "2025-10-23T10:30:00",
- "os": {
- "system": "Darwin",
- "release": "25.0.0",
- "machine": "arm64"
- },
- "cpu": {
- "physical_cores": 8,
- "logical_cores": 8,
- "architecture": "arm64"
- },
- "memory": {
- "total_gb": 16.0,
- "available_gb": 8.5,
- "percent_used": 46.9
- },
- "disk": {
- "total_gb": 500.0,
- "available_gb": 200.0,
- "percent_used": 60.0
- },
- "gpu": {
- "nvidia_gpus": [],
- "amd_gpus": [],
- "apple_silicon": {
- "name": "Apple M2",
- "type": "Apple Silicon",
- "backend": "Metal",
- "unified_memory": true
- },
- "total_gpus": 1,
- "available_backends": ["Metal"]
- },
- "recommendations": {
- "parallel_processing": {
- "strategy": "high_parallelism",
- "suggested_workers": 6,
- "libraries": ["joblib", "multiprocessing", "dask"]
- },
- "memory_strategy": {
- "strategy": "moderate_memory",
- "libraries": ["dask", "zarr"],
- "note": "Consider chunking for datasets > 2GB"
- },
- "gpu_acceleration": {
- "available": true,
- "backends": ["Metal"],
- "suggested_libraries": ["pytorch-mps", "tensorflow-metal", "jax-metal"]
- },
- "large_data_handling": {
- "strategy": "disk_abundant",
- "note": "Sufficient space for large intermediate files"
- }
- }
-}
+Build a conservative picture of resources available to the **current process**.
+Keep host inventory, process affinity, cgroup/container limits, scheduler
+allocation, and accelerator runtime usability separate.
+
+## Safety contract
+
+Follow these rules:
+
+- Run detection when the user requests it or a specific workload needs resource
+ planning. Do not persist a fingerprint for every scientific task.
+- Use stdout by default. Persist only when the user chooses an explicit generic
+ local filename.
+- Do not run stress tests, benchmarks, large allocations, write probes, device
+ resets, driver installation, or clock/power changes.
+- Do not dump the environment. Read only the named Slurm and accelerator
+ variables implemented by the detector.
+- Do not report hostnames, absolute paths, cgroup paths, job IDs, device UUIDs,
+ PCI addresses, or raw visibility-variable values.
+- Treat a missing observation as unknown. Never convert unknown to unlimited.
+- Never infer that a visible host CPU, memory pool, or GPU is usable inside a
+ scheduler allocation or container.
+
+The bundled detector uses only fixed executable/argument tuples, no shell,
+short timeouts, bounded stdout/stderr, and partial-failure warnings.
+
+## Quick start
+
+Run from this skill directory.
+
+### Ephemeral stdout snapshot
+
+```bash
+python scripts/detect_resources.py
```
-### Strategic Recommendations
+The command emits only JSON to stdout. Redirect it only when ordinary shell
+permissions are acceptable.
-The skill generates context-aware recommendations:
+### Explicit private file
-**Parallel Processing Recommendations:**
-- **High parallelism (8+ cores)**: Use Dask, joblib, or multiprocessing with workers = cores - 2
-- **Moderate parallelism (4-7 cores)**: Use joblib or multiprocessing with workers = cores - 1
-- **Sequential (< 4 cores)**: Prefer sequential processing to avoid overhead
+```bash
+python scripts/detect_resources.py --output resource-snapshot.json
+```
-**Memory Strategy Recommendations:**
-- **Memory constrained (< 4GB available)**: Use Zarr, Dask, or H5py for out-of-core processing
-- **Moderate memory (4-16GB available)**: Use Dask/Zarr for datasets > 2GB
-- **Memory abundant (> 16GB available)**: Can load most datasets into memory directly
+Explicit output is restricted to one `.json` filename in the current
+directory, uses private permissions, rejects symlinks and path traversal, and
+refuses overwrite unless `--force` is supplied.
-**GPU Acceleration Recommendations:**
-- **NVIDIA GPUs detected**: Use PyTorch, TensorFlow, JAX, CuPy, or RAPIDS
-- **AMD GPUs detected**: Use PyTorch-ROCm or TensorFlow-ROCm
-- **Apple Silicon detected**: Use PyTorch with MPS backend, TensorFlow-Metal, or JAX-Metal
-- **No GPU detected**: Use CPU-optimized libraries
+### Optional psutil enhancement
-**Large Data Handling Recommendations:**
-- **Disk constrained (< 10GB)**: Use streaming or compression strategies
-- **Moderate disk (10-100GB)**: Use Zarr, H5py, or Parquet formats
-- **Disk abundant (> 100GB)**: Can create large intermediate files freely
+The standard-library detector works without installation. For broader
+cross-platform physical-core, affinity, available-memory, swap, and disk
+coverage:
-## Usage Instructions
+```bash
+uv pip install "psutil==7.2.2"
+```
-### Step 1: Run Resource Detection
+The import is lazy. Failure to import psutil becomes a warning, not a fatal
+error.
-Execute the detection script at the start of any computationally intensive task:
+### Skip management-tool probes
```bash
-python scripts/detect_resources.py
+python scripts/detect_resources.py --skip-accelerators
```
-Optional arguments:
-- `-o, --output <path>`: Specify custom output path (default: `.claude_resources.json`)
-- `-v, --verbose`: Print full resource information to stdout
+Use this when accelerator discovery latency is undesirable. The detector still
+summarizes the presence and state of allowlisted visibility variables without
+returning their values.
-### Step 2: Read and Apply Recommendations
+## Required interpretation
-After running detection, read the generated `.claude_resources.json` file to inform computational decisions:
+### CPU
-```python
-# Example: Use recommendations in code
-import json
+Read these as different facts:
-with open('.claude_resources.json', 'r') as f:
- resources = json.load(f)
+- `cpu.host.logical`: system-visible scheduling units.
+- `cpu.host.physical`: physical topology, or null; never inferred from logical
+ count.
+- `cpu.process.affinity_logical`: current affinity-set size when supported.
+- `cpu.cgroup_v2.cpuset_logical`: effective cgroup cpuset size.
+- `cpu.cgroup_v2.quota_cores`: finite `cpu.max` capacity, possibly fractional.
+- `scheduler.allocation.cpu_per_process`: bounded Slurm per-task
+ interpretation when scope is clear.
+- `cpu.effective.capacity_cores`: minimum positive observed constraint.
+- `cpu.effective.worker_ceiling`: conservative floor for CPU process workers.
-# Check parallel processing strategy
-if resources['recommendations']['parallel_processing']['strategy'] == 'high_parallelism':
- n_jobs = resources['recommendations']['parallel_processing']['suggested_workers']
- # Use joblib, Dask, or multiprocessing with n_jobs workers
+A quota of 1.5 is CPU-time capacity, not 1.5 physical cores. Affinity and
+cpusets constrain placement; quota constrains bandwidth.
-# Check memory strategy
-if resources['recommendations']['memory_strategy']['strategy'] == 'memory_constrained':
- # Use Dask, Zarr, or H5py for out-of-core processing
- import dask.array as da
- # Load data in chunks
+### Memory
-# Check GPU availability
-if resources['recommendations']['gpu_acceleration']['available']:
- backends = resources['recommendations']['gpu_acceleration']['backends']
- # Use appropriate GPU library based on available backend
-```
+Keep these separate:
-### Step 3: Make Informed Decisions
+- host total/available memory;
+- current cgroup usage, hard `memory.max`, and remaining hierarchical capacity;
+- `memory.high`, which is a pressure/throttle boundary rather than a hard cap;
+- scheduler memory allocation and its scope; and
+- conservative effective hard limit and available estimate.
-Use the resource information and recommendations to make strategic choices:
+On Apple silicon, `memory.model` is `unified_cpu_gpu`. Do not add integrated GPU
+memory to RAM or describe it as separate VRAM.
-**For data loading:**
-```python
-memory_available_gb = resources['memory']['available_gb']
-dataset_size_gb = 10
+### Accelerators
-if dataset_size_gb > memory_available_gb * 0.5:
- # Dataset is large relative to memory, use Dask
- import dask.dataframe as dd
- df = dd.read_csv('large_file.csv')
-else:
- # Dataset fits in memory, use pandas
- import pandas as pd
- df = pd.read_csv('large_file.csv')
-```
+Each device is a backend **candidate**:
-**For parallel processing:**
-```python
-from joblib import Parallel, delayed
+- NVIDIA GPU → CUDA candidate;
+- AMD GPU → ROCm candidate;
+- Apple integrated GPU → Metal candidate.
-n_jobs = resources['recommendations']['parallel_processing'].get('suggested_workers', 1)
+Management-query visibility does not establish:
-results = Parallel(n_jobs=n_jobs)(
- delayed(process_function)(item) for item in data
-)
-```
+1. scheduler/container permission;
+2. device-node access;
+3. driver/runtime compatibility;
+4. framework package compatibility; or
+5. operator/data-type support.
-**For GPU acceleration:**
-```python
-import torch
+Therefore `runtime_usable_devices` remains null and each device says
+`runtime_compatibility: not_tested`. Visibility/allocation counts are upper
+bounds, not guarantees.
-if 'CUDA' in resources['gpu']['available_backends']:
- device = torch.device('cuda')
-elif 'Metal' in resources['gpu']['available_backends']:
- device = torch.device('mps')
-else:
- device = torch.device('cpu')
+### Disk
-model = model.to(device)
-```
+`capacity_bytes`, filesystem `free_bytes`, user-available blocks, and a
+non-writing permission check are distinct. Filesystem or project quotas can
+still be stricter. The absolute working path is always redacted.
+
+### Scheduler and container
+
+Slurm variables describe allocation scope, but enforcement depends on site
+configuration such as task affinity or cgroups. Prefer affinity and cgroup
+observations as enforcement evidence.
+
+Container markers identify context; cgroup controls identify limits. A
+container with no finite cgroup value can still see host inventory, and a
+non-root cgroup is not automatically labeled a container.
-## Dependencies
+See [`references/resource_semantics.md`](references/resource_semantics.md) for
+the detailed platform rules.
-The detection script requires the following Python packages:
+## Plan a workload
+
+The planner consumes a validated snapshot and performs no work:
```bash
-uv pip install psutil
+python scripts/plan_workload.py resource-snapshot.json \
+ --workload cpu \
+ --tasks 100 \
+ --memory-per-worker-mib 2048
```
-All other functionality uses Python standard library modules (json, os, platform, subprocess, sys, pathlib).
+Optional controls:
-## Platform Support
+- `--workers N`: explicit upper bound.
+- `--reserve-memory-mib N`: memory kept outside the worker budget.
+- `--workload cpu|mixed|io`: selects a bounded worker heuristic.
+- `--accelerator none|any|cuda|rocm|metal`: requests a candidate backend
+ decision without claiming usability.
+- `--output plan.json`: explicit private local output; stdout is default.
-- **macOS**: Full support including Apple Silicon (M1/M2/M3/M4) GPU detection
-- **Linux**: Full support including NVIDIA (nvidia-smi) and AMD (rocm-smi) GPU detection
-- **Windows**: Full support including NVIDIA GPU detection
+For CPU or mixed work, use `suggested_workers` and
+`threads_per_worker` together. Process workers multiplied by BLAS/OpenMP native
+threads can oversubscribe an allocation.
-## Best Practices
+The I/O plan permits bounded oversubscription (maximum 32) but labels it a
+heuristic. Benchmark only the real representative workload and stay within
+scheduler/container limits.
-1. **Run early**: Execute resource detection at the start of projects or before major computational tasks
-2. **Re-run periodically**: System resources change over time (memory usage, disk space)
-3. **Check before scaling**: Verify resources before scaling up parallel workers or data sizes
-4. **Document decisions**: Keep the `.claude_resources.json` file in project directories to document resource-aware decisions
-5. **Use with versioning**: Different machines have different capabilities; resource files help maintain portability
+## Validate or diff snapshots
-## Troubleshooting
+Validate:
-**GPU not detected:**
-- Ensure GPU drivers are installed (nvidia-smi, rocm-smi, or system_profiler for Apple Silicon)
-- Check that GPU utilities are in system PATH
-- Verify GPU is not in use by other processes
+```bash
+python scripts/snapshot_tools.py validate resource-snapshot.json
+```
-**Script execution fails:**
-- Ensure psutil is installed: `uv pip install psutil`
-- Check Python version compatibility (Python 3.6+)
-- Verify script has execute permissions: `chmod +x scripts/detect_resources.py`
+Diff resource state while ignoring `observed_at`:
-**Inaccurate memory readings:**
-- Memory readings are snapshots; actual available memory changes constantly
-- Close other applications before detection for accurate "available" memory
-- Consider running detection multiple times and averaging results
+```bash
+python scripts/snapshot_tools.py diff before.json after.json
+```
+
+Use `--include-volatile` to include the timestamp. Inputs must be regular,
+non-symlink JSON files no larger than 1 MiB. Diffs are bounded.
+
+The schema and null/zero meanings are documented in
+[`references/snapshot_schema.md`](references/snapshot_schema.md).
+
+## Optional accelerator diagnostic plan
+
+Generate a plan without executing any diagnostic:
+
+```bash
+python scripts/accelerator_diagnostics.py resource-snapshot.json \
+ --backend auto
+```
+The result contains fixed, read-only management query argument lists and
+separate gates for visibility, permission, and runtime compatibility. Run a
+framework's official availability check only in the exact environment that
+will execute the workload. Do not install or mutate drivers automatically.
+
+## Partial failures and provenance
+
+One failed probe must not erase successful observations. Inspect:
+
+- `completeness`;
+- sorted `warnings` with stable codes;
+- sorted `provenance` source/status records; and
+- null fields.
+
+Subprocess stderr and raw exception text are not copied into the snapshot
+because they can contain identifiers or paths.
+
+## Platform notes
+
+- **Linux:** reads only bounded `/proc` and cgroup v2 files. Ancestor CPU and
+ memory limits are considered.
+- **macOS:** uses fixed `sysctl` keys and a bounded
+ `system_profiler SPDisplaysDataType -json` query. Apple silicon memory is
+ unified.
+- **Windows:** optional psutil improves physical-core, affinity, available
+ memory, and swap observations. Processor-group scope can make host and
+ process counts differ.
+- **Slurm:** reads an allowlist of allocation variables. It never emits job,
+ node, submit-host, GPU-ID, or path values.
+- **NVIDIA/AMD:** management CLIs are optional. Absence is normal; timeout,
+ truncation, parse failure, and runtime uncertainty remain explicit.
+
+## Bundled files
+
+- `scripts/detect_resources.py` — redacted snapshot collector.
+- `scripts/plan_workload.py` — deterministic worker/memory planner.
+- `scripts/snapshot_tools.py` — schema validator and bounded structural diff.
+- `scripts/accelerator_diagnostics.py` — non-executing read-only diagnostic
+ plan.
+- `tests/test_scripts.py` and `tests/fixtures/resource_cases.json` —
+ network-free Linux, macOS, Windows, cgroup, Slurm, and accelerator cases.
+- `references/resource_semantics.md` — interpretation and platform details.
+- `references/snapshot_schema.md` — schema 1.1 contract.
+- `references/sources.md` — dated official-source ledger.
+
+Official documentation was refreshed on **2026-07-23**; consult
+[`references/sources.md`](references/sources.md) before changing semantics or
+dependency pins.
diff --git a/skills/get-available-resources/references/resource_semantics.md b/skills/get-available-resources/references/resource_semantics.md
new file mode 100644
index 00000000..1a345835
--- /dev/null
+++ b/skills/get-available-resources/references/resource_semantics.md
@@ -0,0 +1,206 @@
+# Resource Semantics
+
+Research and behavior cut-off: **2026-07-23**. See
+[`sources.md`](sources.md) for the official documentation used.
+
+## Core rule: inventory is not entitlement
+
+Never treat a host-wide count as a promise that the current process can use it.
+Interpret usable resources as the intersection of independently observed
+constraints:
+
+1. host inventory;
+2. process affinity or processor-group scope;
+3. cgroup/container constraints;
+4. scheduler allocation;
+5. accelerator visibility and device permissions; and
+6. application runtime compatibility.
+
+Missing evidence means **unknown**, not unlimited. Scheduler variables can
+describe an allocation without proving that affinity or cgroup enforcement is
+enabled. Conversely, a cgroup or affinity mask can be stricter than the
+scheduler request.
+
+## CPU
+
+### Physical and logical CPUs
+
+- A logical CPU is an operating-system scheduling unit. Simultaneous
+ multithreading can expose multiple logical CPUs on one physical core.
+- A physical-core count describes topology, not the number of independent
+ workers the process may start.
+- `os.cpu_count()` and `psutil.cpu_count(logical=True)` are host/system
+ inventory. They can exceed the CPUs usable by the process.
+- `os.process_cpu_count()` (Python 3.13+) is process-aware. On supported
+ platforms, affinity APIs provide a more explicit process constraint.
+- On Windows systems with multiple processor groups, a system-wide logical
+ count and one process/thread group's usable count can differ.
+
+The detector reports host logical and physical counts separately. It never
+derives physical cores from a logical count.
+
+### Affinity, cpusets, and quotas
+
+- Process affinity limits the logical CPUs on which a process may execute.
+- Linux `cpuset.cpus.effective` reports CPUs actually granted after parent
+ constraints. The requested `cpuset.cpus` can differ.
+- `/proc/self/status` exposes `Cpus_allowed_list`, but the detector prefers
+ affinity APIs and cgroup effective cpusets.
+- cgroup v2 `cpu.max` is `$MAX $PERIOD`. `max` means no local bandwidth limit.
+ A finite ratio is CPU-time capacity, possibly fractional; it is not a core
+ topology count.
+- Parent cgroups also constrain children, so the detector takes the most
+ restrictive finite ancestor quota.
+
+For a `cpu.max` ratio of 1.5, the snapshot reports
+`capacity_cores: 1.5` and a conservative CPU-bound worker ceiling of 1. A
+workload may choose more threads for latency hiding, but it should expect
+throttling and must not describe those threads as 1.5 physical cores.
+
+### Python worker pools
+
+- Current Python `multiprocessing.Pool` and `ProcessPoolExecutor` defaults use
+ `os.process_cpu_count()` when available.
+- Python 3.14 no longer uses `fork` as the default start method on any platform.
+ Code that depends on a particular start method must request it deliberately.
+- Process workers do not make each worker's native-library threads disappear.
+ BLAS/OpenMP threads multiplied by process workers commonly oversubscribe an
+ allocation.
+- Windows `ProcessPoolExecutor` has a documented maximum of 61 workers.
+
+Use the workload planner's worker and threads-per-worker values as conservative
+ceilings, then benchmark a real representative workload. Do not run a synthetic
+stress test merely to discover capacity.
+
+## Memory
+
+### Host and effective memory
+
+- `psutil.virtual_memory().total` and `.available` describe system-visible
+ memory, not necessarily the process limit.
+- Linux `/proc/meminfo` `MemAvailable` is the standard-library fallback for a
+ host-availability estimate.
+- cgroup v2 `memory.current` is current cgroup usage.
+- `memory.high` is a throttle/reclaim pressure boundary. Exceeding it does not
+ itself invoke the cgroup OOM killer, and the value can be breached.
+- `memory.max` is the hard cgroup limit. If usage cannot be reduced at that
+ boundary, the cgroup OOM killer can run.
+- Parent memory limits are hierarchical. Shared ancestor usage can reduce what
+ remains for a child, so effective remaining memory is the minimum finite
+ `limit - current` observed through the ancestor chain.
+- Slurm memory variables describe requested/allocated memory, but strict
+ enforcement depends on site configuration.
+
+The detector keeps host total/available values, cgroup values, scheduler values,
+and the conservative effective values distinct. A point-in-time "available"
+value can change immediately and is not a reservation.
+
+### macOS unified memory
+
+On Apple silicon, CPU and integrated GPU share unified memory. Do not add a
+fictional GPU VRAM amount to system RAM. The snapshot marks the memory model as
+`unified_cpu_gpu` and leaves dedicated GPU memory null. Metal framework support
+and model/operator support still require application-specific checks.
+
+## Accelerators
+
+Accelerator usability has separate layers:
+
+1. **Hardware or management visibility** — a management query returns a device.
+2. **Allocation visibility** — scheduler and named visibility variables permit
+ a device or a subset.
+3. **Device permission** — the process/container can open the required device
+ interfaces.
+4. **Driver/runtime compatibility** — driver, CUDA/ROCm/Metal runtime, and
+ framework versions are compatible.
+5. **Workload compatibility** — the requested operation and data type are
+ implemented on that backend.
+
+`nvidia-smi` success confirms NVIDIA management visibility only. It does not
+prove that CUDA libraries exist or are compatible. NVIDIA documents driver and
+runtime compatibility as a separate requirement.
+
+AMD SMI or ROCm SMI success likewise does not prove HIP/ROCm runtime usability.
+New deployments should prefer `amd-smi`; `rocm-smi` is retained as a read-only
+fallback. On Linux, AMD recommends `ROCR_VISIBLE_DEVICES`; on Windows it
+recommends `HIP_VISIBLE_DEVICES`.
+
+An Apple integrated GPU is a Metal candidate, not a CUDA GPU. AMD GPUs are ROCm
+candidates, not CUDA GPUs. Neural engines, TPUs, FPGAs, and other accelerators
+must also remain distinct from CUDA devices if another inventory source adds
+them.
+
+The detector reads only these accelerator variable names and redacts their
+values:
+
+- `NVIDIA_VISIBLE_DEVICES`
+- `CUDA_VISIBLE_DEVICES`
+- `ROCR_VISIBLE_DEVICES`
+- `HIP_VISIBLE_DEVICES`
+
+Counts derived from those values are only upper bounds. Environment variables
+are not a security boundary and can be reset by an application; device
+namespace/cgroup controls are stronger isolation.
+
+## Slurm and other schedulers
+
+The detector allowlists named Slurm variables and never dumps the environment.
+It records field names, parsed bounded counts, and memory quantities, but not
+job IDs, GPU UUIDs, node names, submit hosts, or paths.
+
+Important scopes:
+
+- `SLURM_CPUS_PER_TASK`: requested CPUs per task; suitable as a per-process
+ upper bound for one task process.
+- `SLURM_CPUS_ON_NODE`: CPUs allocated to the current batch step on the node;
+ it can be shared among tasks.
+- `SLURM_JOB_CPUS_PER_NODE`: a per-node allocation list, not a process count.
+- `SLURM_MEM_PER_CPU`: memory per allocated CPU. It becomes a per-task bound
+ only when CPUs per task is known.
+- `SLURM_MEM_PER_NODE`: shared per-node memory upper bound.
+- `SLURM_GPUS_PER_TASK`: requested GPUs per task.
+- `SLURM_GPUS_ON_NODE`: GPUs allocated to the batch step on the node.
+
+Slurm CPU confinement requires site configuration such as task affinity or
+`task/cgroup` with core constraints. Memory requests are not strictly enforced
+unless the site enables an enforcement mechanism. Use affinity and cgroup
+observations as enforcement evidence; do not trust visible node inventory.
+
+For other schedulers, use their documented allocation API or variables and the
+same rule: allocation metadata and kernel enforcement are different facts.
+Do not guess from generic environment names.
+
+## Containers and OCI
+
+Docker containers have no CPU or memory limit by default. When configured,
+Docker maps CPU and memory flags to cgroup controls. OCI runtime configuration
+also defines CPU, memory, and device constraints.
+
+Inside a container:
+
+- host inventory may remain visible;
+- a CPU quota can be smaller than the visible CPU set;
+- a cpuset can be smaller than the quota's apparent capacity;
+- cgroup memory can be smaller than host RAM;
+- GPU management tools can see a different set from the application runtime;
+ and
+- mounted-volume capacity can differ from writable quota.
+
+Always report observed cgroup controls and uncertainty. A container marker
+without a finite cgroup value does not imply a finite limit.
+
+## Disk
+
+Capacity, free blocks, user-writable blocks, path permission, filesystem quota,
+and actual ability to complete a write are different:
+
+- capacity is the filesystem's total size;
+- free blocks can include blocks reserved from an unprivileged user;
+- POSIX `f_bavail` estimates blocks available to the current user;
+- `os.access(..., os.W_OK)` is a non-writing permission check, not proof that a
+ future write will succeed;
+- project/user quotas and remote storage policies can be stricter than block
+ counts.
+
+The detector does not create a probe file. It redacts the absolute working path
+and labels the scope as the working filesystem.
diff --git a/skills/get-available-resources/references/snapshot_schema.md b/skills/get-available-resources/references/snapshot_schema.md
new file mode 100644
index 00000000..f021a79b
--- /dev/null
+++ b/skills/get-available-resources/references/snapshot_schema.md
@@ -0,0 +1,172 @@
+# Snapshot Schema 1.1
+
+The detector emits one JSON object with sorted keys. Values vary by observation,
+but field names and meanings are stable for schema `1.1`.
+
+## Top-level contract
+
+- `schema_version`: `"1.1"`.
+- `snapshot_kind`: `"effective_resource_snapshot"`.
+- `observed_at`: UTC observation time.
+- `completeness`: `complete`, `complete_with_informational_notes`, or
+ `partial`.
+- `platform`: OS family, architecture, and Python version. Hostname is omitted.
+- `privacy`: explicit redaction flags.
+- `cpu`, `memory`, `disk`, `accelerators`: resource observations.
+- `cgroup_v2`, `container`, `scheduler`: execution-context observations.
+- `warnings`: bounded sorted warning records.
+- `provenance`: bounded sorted source/status records.
+
+Null means unavailable, not zero and not unlimited. Zero is used only when a
+source explicitly establishes zero (for example, a named accelerator visibility
+variable that hides all devices).
+
+## CPU
+
+`cpu.host`:
+
+- `logical`: system-visible logical CPUs.
+- `physical`: system-visible physical cores, or null. This value is not
+ converted into an effective process count.
+
+`cpu.process`:
+
+- `affinity_logical`: size of the current affinity set when supported.
+- `python_available_logical`: `os.process_cpu_count()` when supported.
+
+`cpu.cgroup_v2`:
+
+- `cpuset_logical`: count from `cpuset.cpus.effective`.
+- `quota_cores`: most restrictive finite ancestor `cpu.max` ratio. This may be
+ fractional.
+
+`cpu.effective`:
+
+- `capacity_cores`: minimum positive host/process/cgroup/scheduler capacity.
+- `worker_ceiling`: conservative bounded floor for CPU process workers.
+- `limiting_sources`: sources tied at that minimum.
+
+The effective value is intentionally not called a physical-core count.
+
+## Memory
+
+`memory.host` preserves system-visible `total_bytes` and `available_bytes`.
+
+`memory.cgroup_v2` preserves current-cgroup usage and hierarchical effective
+limits:
+
+- `current_bytes`
+- `available_bytes`
+- `high_bytes`
+- `max_bytes`
+
+`memory.effective`:
+
+- `hard_limit_bytes`: minimum of finite host total, cgroup hard limit, and
+ interpretable scheduler allocation.
+- `available_bytes`: minimum of host available, hierarchical cgroup remaining,
+ and scheduler upper bound.
+- `pressure_threshold_bytes`: cgroup `memory.high`; it is not relabeled as a
+ hard limit.
+- `hard_limit_sources` and `available_limiting_sources`: tied minimum sources.
+
+`memory.model` is `unified_cpu_gpu` on Apple silicon and `system_ram`
+otherwise. Unified GPU memory is not added again as dedicated VRAM.
+
+## Disk
+
+- `capacity_bytes`: total working-filesystem capacity.
+- `free_bytes`: filesystem free blocks.
+- `user_available_bytes`: user-available blocks where the OS exposes them.
+- `writable`: result of a non-writing access check.
+- `writability_check`: makes clear that no write probe occurred.
+- `scope`: `working_filesystem_path_redacted`.
+
+None of these values proves that a filesystem or project quota permits a write
+of the same size.
+
+## Accelerators
+
+`accelerators.devices` contains management-visible or explicitly
+platform-inferred candidates:
+
+- `vendor`: `nvidia`, `amd`, or `apple`.
+- `device_class`: keeps integrated and discrete GPU concepts distinct.
+- `backend_candidate`: `cuda`, `rocm`, or `metal`.
+- `management_query`: visibility evidence.
+- `device_permission`: `not_tested`; a query does not prove device-node access.
+- `runtime_compatibility`: `not_tested` in detector output.
+- `memory.model`: dedicated/HBM, unified, or unknown.
+- `local_index`: local query index; stable UUIDs and PCI addresses are omitted.
+
+`candidate_counts` is a query count, not a usable-device count.
+`candidate_upper_bounds` conservatively intersects query count with parsed
+visibility/allocation counts when available. `runtime_usable_devices` remains
+null because no framework runtime is loaded.
+
+`visibility_environment` includes only four allowlisted variable names. Raw
+values are never emitted.
+
+## Scheduler and cgroup
+
+`scheduler.fields_read` lists allowlisted Slurm names that were present.
+`scheduler.allocation` contains parsed bounded values and scopes.
+`scheduler.enforcement` remains `unknown`; variables alone do not prove
+confinement.
+
+`cgroup_v2.scope` says only `root`, `non_root`, `unknown`, or `not_applicable`.
+The cgroup path is not emitted.
+
+`container.detected` requires a known marker. A `cgroup_limit` can appear as
+evidence without asserting that the process is in a container.
+
+## Warnings and provenance
+
+Warnings use:
+
+```json
+{
+ "code": "STABLE_MACHINE_CODE",
+ "component": "cpu",
+ "message": "Human-readable, sanitized explanation.",
+ "severity": "info"
+}
+```
+
+Probe exception text, stderr, paths, hostnames, device UUIDs, and broad
+environment content are excluded.
+
+Provenance uses:
+
+```json
+{
+ "component": "cpu.process.affinity_logical",
+ "source": "os.sched_getaffinity",
+ "status": "ok"
+}
+```
+
+Possible status values include `ok`, `unavailable`, `absent`, `skipped`,
+`not_found`, `timeout`, `truncated`, `error`, and `parse_error`.
+
+## Validation and diff
+
+Validate:
+
+```bash
+python scripts/snapshot_tools.py validate resource-snapshot.json
+```
+
+Diff while ignoring `observed_at`:
+
+```bash
+python scripts/snapshot_tools.py diff before.json after.json
+```
+
+Use `--include-volatile` only when timestamp changes matter. Diff output is
+bounded to 512 changes.
+
+All helper inputs are regular, non-symlink JSON files no larger than 1 MiB.
+Output defaults to stdout. Explicit file output is restricted to a `.json`
+filename in the current directory, refuses overwrite unless `--force` is used,
+and is opened with private permissions.
diff --git a/skills/get-available-resources/references/sources.md b/skills/get-available-resources/references/sources.md
new file mode 100644
index 00000000..42f5d209
--- /dev/null
+++ b/skills/get-available-resources/references/sources.md
@@ -0,0 +1,124 @@
+# Official Sources
+
+Research cut-off: **2026-07-23**. Every URL below was consulted on that
+date. Undated living documentation is labeled "living docs"; a date in
+parentheses is the page/release date visible in the source.
+
+## psutil
+
+- [psutil 7.2.2 documentation](https://psutil.readthedocs.io/) — living docs.
+ Used for logical versus physical CPU counts, the warning that system CPU
+ count can differ from process-usable CPUs under affinity/cgroups/Windows
+ processor groups, `Process.cpu_affinity()`, `virtual_memory()`,
+ `swap_memory()`, and `disk_usage()`.
+- [psutil 7.2.2 on PyPI](https://pypi.org/project/psutil/7.2.2/) — current
+ stable package pin verified 2026-07-23.
+
+## Python
+
+- [Python `os` documentation](https://docs.python.org/3/library/os.html) —
+ Python 3.14.6 living docs. Used for `os.cpu_count()`,
+ `os.process_cpu_count()`, and `os.sched_getaffinity()`.
+- [Python multiprocessing](https://docs.python.org/3/library/multiprocessing.html)
+ — Python 3.14.6 living docs. Used for process-aware pool defaults and the
+ Python 3.14 start-method change.
+- [Python concurrent.futures](https://docs.python.org/3/library/concurrent.futures.html)
+ — Python 3.14.6 living docs. Used for `ProcessPoolExecutor` defaults,
+ Windows' 61-worker maximum, and `ThreadPoolExecutor` defaults.
+
+## Linux procfs and cgroup v2
+
+- [Linux kernel `/proc` filesystem documentation](https://docs.kernel.org/filesystems/proc.html)
+ — living kernel docs. Used for `Cpus_allowed` and
+ `Cpus_allowed_list`.
+- [Linux kernel cgroup v2 documentation](https://docs.kernel.org/admin-guide/cgroup-v2.html)
+ — living kernel docs; page history begins 2014-07-15. Used for
+ `cpu.max`, `cpuset.cpus.effective`, `memory.current`, `memory.high`,
+ `memory.max`, hierarchy, reclaim, and cgroup OOM behavior.
+- [Linux kernel cpuset documentation](https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v1/cpusets.html)
+ — living kernel docs. Used to cross-check the interaction between affinity
+ masks and cpuset constraints.
+
+## Containers and OCI
+
+- [Docker resource constraints](https://docs.docker.com/engine/containers/resource_constraints/)
+ — living docs. Used for Docker's default lack of constraints, `--cpus`,
+ quota/period, cpusets, and memory controls.
+- [OCI Runtime Specification: Linux resources](https://specs.opencontainers.org/runtime-spec/config-linux/?v=v1.3.0)
+ — OCI Runtime Spec 1.3.0. Used for CPU, memory, cgroup, and device resource
+ semantics.
+
+## NVIDIA
+
+- [NVIDIA System Management Interface manual](https://docs.nvidia.com/deploy/nvidia-smi/index.html)
+ — living docs. Used for fixed `--query-gpu` fields and
+ `--format=csv,noheader,nounits`; NVIDIA notes that index ordering is not
+ stable, which is why snapshots do not claim a persistent identity.
+- [NVIDIA Container Toolkit specialized configurations](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/docker-specialized.html)
+ — living docs. Used for `NVIDIA_VISIBLE_DEVICES`, driver capabilities, and
+ runtime constraints.
+- [NVIDIA `CUDA_VISIBLE_DEVICES`](https://docs.nvidia.com/deploy/topics/topic_5_2_1.html)
+ — official deployment documentation. Used for CUDA application visibility.
+- [NVIDIA CUDA compatibility](https://docs.nvidia.com/deploy/cuda-compatibility/latest/why-cuda-compatibility.html)
+ — living docs. Used to distinguish management visibility from compatible
+ GPU, driver, CUDA runtime, and dynamically linked libraries.
+
+## AMD ROCm
+
+- [AMD SMI CLI tool](https://rocm.docs.amd.com/projects/amdsmi/en/docs-7.2.0/how-to/amdsmi-cli-tool.html)
+ — AMD SMI 7.2.0 docs. Used for read-only `list`/`static` JSON output and the
+ meaning of unavailable fields.
+- [ROCm SMI Python/CLI usage](https://rocm.docs.amd.com/projects/rocm_smi_lib/en/latest/how-to/use-python.html)
+ — living docs. Used for the legacy `rocm-smi` read-only fallback.
+- [ROCm GPU isolation techniques](https://rocm.docs.amd.com/en/docs-7.2.4/conceptual/gpu-isolation.html)
+ — ROCm 7.2.4 docs. Used for `ROCR_VISIBLE_DEVICES`,
+ `HIP_VISIBLE_DEVICES`, `CUDA_VISIBLE_DEVICES`, Docker device isolation, and
+ the warning that environment variables are not isolation for untrusted code.
+- [ROCm environment variables](https://rocm.docs.amd.com/en/latest/reference/environment-variables/index.html)
+ — living docs. Used for AMD's Linux/Windows visibility-variable
+ recommendations.
+
+## Apple
+
+- [Apple: Determining system capabilities](https://developer.apple.com/documentation/kernel/1387446-sysctlbyname/determining_system_capabilities)
+ — living Apple Developer docs. Used for `hw.logicalcpu`,
+ `hw.physicalcpu`, `hw.memsize`, performance levels, and the distinction
+ between logical and physical cores.
+- [Apple `sysctl(3)` manual](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/sysctl.3.html)
+ — archived official manual. Used to cross-check physical-memory fields.
+- [Apple Developer Technical Support: system_profiler and integrated/SoC memory](https://developer.apple.com/forums/thread/688443)
+ — Apple DTS response dated 2021-08-24. Used for parseable
+ `system_profiler` output and the warning that DIMM-style details do not map
+ cleanly to integrated or Apple silicon memory.
+- The fixed `system_profiler SPDisplaysDataType -json` and named `sysctl -n`
+ queries were smoke-checked locally on Darwin 25.5.0 on 2026-07-23. The
+ script never requests the full system profile.
+
+## Slurm
+
+- [Slurm `sbatch`](https://slurm.schedmd.com/sbatch.html) — living SchedMD
+ docs. Used for exact output environment-variable scopes:
+ `SLURM_CPUS_ON_NODE`, `SLURM_CPUS_PER_TASK`,
+ `SLURM_JOB_CPUS_PER_NODE`, `SLURM_MEM_PER_CPU`,
+ `SLURM_MEM_PER_NODE`, `SLURM_NTASKS`, and GPU variables. Also used for
+ the explicit warning that memory requests require configured enforcement.
+- [Slurm CPU Management Guide](https://slurm.schedmd.com/cpu_management.html)
+ — living SchedMD docs. Used for `task/affinity`, `task/cgroup`,
+ `ConstrainCores`, binding, and logical CPU/core allocation examples.
+- [Slurm `srun`](https://slurm.schedmd.com/srun.html) — updated
+ 2026-07-14. Used for task confinement and GPU binding behavior.
+- [Slurm `scontrol`](https://slurm.schedmd.com/scontrol.html) — living docs.
+ Used for the read-only `scontrol show job` interpretation workflow.
+- [Slurm `sstat`](https://slurm.schedmd.com/sstat.html) — living docs. Used
+ for post-launch job-step accounting semantics.
+
+## Windows
+
+- [Microsoft: Processor Groups](https://learn.microsoft.com/en-us/windows/win32/procthread/processor-groups)
+ — living Microsoft docs. Used for the distinction between system logical
+ processors, physical cores, and processor-group scheduling.
+- [GetLogicalProcessorInformation](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformation)
+ — living Microsoft docs. Used for logical/physical relationships and the
+ current-group limitation on systems over 64 logical processors.
+- [GetLogicalProcessorInformationEx](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformationex)
+ — page dated 2023-03-06. Used for system-wide processor-group topology.
diff --git a/skills/get-available-resources/scripts/_common.py b/skills/get-available-resources/scripts/_common.py
new file mode 100644
index 00000000..ced48666
--- /dev/null
+++ b/skills/get-available-resources/scripts/_common.py
@@ -0,0 +1,190 @@
+#!/usr/bin/env python3
+"""Shared, dependency-free safety and JSON helpers."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import os
+import stat
+import sys
+from pathlib import Path
+from typing import Any
+
+SCHEMA_VERSION = "1.1"
+MAX_SNAPSHOT_BYTES = 1_048_576
+MAX_WORKERS = 1_024
+MAX_TASKS = 1_000_000_000
+MAX_BYTES = 1 << 63
+
+
+class ResourceToolError(ValueError):
+ """A concise, user-safe CLI error."""
+
+
+def json_text(value: Any) -> str:
+ """Serialize deterministic, standards-compliant JSON."""
+ try:
+ return (
+ json.dumps(
+ value,
+ allow_nan=False,
+ ensure_ascii=False,
+ indent=2,
+ sort_keys=True,
+ )
+ + "\n"
+ )
+ except (RecursionError, TypeError, ValueError) as exc:
+ raise ResourceToolError("result is not valid JSON data") from exc
+
+
+def _safe_output_path(raw: str) -> Path:
+ """Restrict writes to one explicit JSON filename in the current directory."""
+ if not raw or len(raw) > 255:
+ raise ResourceToolError("output must be a short JSON filename")
+ candidate = Path(raw)
+ if candidate.is_absolute() or len(candidate.parts) != 1:
+ raise ResourceToolError(
+ "output must be a filename in the current directory, not a path"
+ )
+ if candidate.name in {".", ".."} or candidate.suffix.lower() != ".json":
+ raise ResourceToolError("output filename must end in .json")
+ return Path.cwd() / candidate.name
+
+
+def emit_json(value: Any, output: str | None = None, *, force: bool = False) -> None:
+ """Write JSON to stdout or an explicit private local file."""
+ payload = json_text(value)
+ if output is None:
+ sys.stdout.write(payload)
+ return
+
+ destination = _safe_output_path(output)
+ try:
+ if destination.is_symlink():
+ raise ResourceToolError("refusing to write through a symbolic link")
+ flags = os.O_WRONLY | os.O_CREAT
+ flags |= os.O_TRUNC if force else os.O_EXCL
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ descriptor = os.open(destination, flags, 0o600)
+ try:
+ if hasattr(os, "fchmod"):
+ os.fchmod(descriptor, 0o600)
+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
+ descriptor = -1
+ stream.write(payload)
+ stream.flush()
+ os.fsync(stream.fileno())
+ finally:
+ if descriptor >= 0:
+ os.close(descriptor)
+ except FileExistsError as exc:
+ raise ResourceToolError(
+ f"{destination.name} already exists; use --force to replace it"
+ ) from exc
+ except OSError as exc:
+ raise ResourceToolError(
+ f"could not write the requested output file ({exc.__class__.__name__})"
+ ) from exc
+
+
+def read_json_file(raw: str) -> dict[str, Any]:
+ """Read one bounded regular JSON file without following symlinks."""
+ path = Path(raw)
+ try:
+ if path.is_symlink():
+ raise ResourceToolError("refusing to read a symbolic link")
+ info = path.stat()
+ if not stat.S_ISREG(info.st_mode):
+ raise ResourceToolError("snapshot input must be a regular file")
+ if info.st_size > MAX_SNAPSHOT_BYTES:
+ raise ResourceToolError(
+ f"snapshot input exceeds {MAX_SNAPSHOT_BYTES} bytes"
+ )
+ with path.open("rb") as stream:
+ payload = stream.read(MAX_SNAPSHOT_BYTES + 1)
+ if len(payload) > MAX_SNAPSHOT_BYTES:
+ raise ResourceToolError(
+ f"snapshot input exceeds {MAX_SNAPSHOT_BYTES} bytes"
+ )
+ except ResourceToolError:
+ raise
+ except OSError as exc:
+ raise ResourceToolError(
+ f"could not read snapshot ({exc.__class__.__name__})"
+ ) from exc
+ try:
+ parsed = json.loads(payload)
+ except (RecursionError, UnicodeDecodeError, json.JSONDecodeError) as exc:
+ raise ResourceToolError("snapshot is not valid UTF-8 JSON") from exc
+ if not isinstance(parsed, dict):
+ raise ResourceToolError("snapshot JSON root must be an object")
+ return parsed
+
+
+def bounded_int(
+ value: Any,
+ *,
+ minimum: int = 0,
+ maximum: int = MAX_BYTES,
+) -> int | None:
+ """Return a bounded integer without accepting booleans or floats."""
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int) and minimum <= value <= maximum:
+ return value
+ return None
+
+
+def bounded_number(
+ value: Any,
+ *,
+ minimum: float = 0.0,
+ maximum: float = float(MAX_BYTES),
+) -> float | None:
+ """Return a finite bounded number without accepting booleans."""
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ number = float(value)
+ if not math.isfinite(number) or not minimum <= number <= maximum:
+ return None
+ return number
+
+
+def argparse_positive_int(
+ value: str,
+ *,
+ maximum: int = MAX_TASKS,
+) -> int:
+ """Argparse converter for bounded positive integers."""
+ try:
+ parsed = int(value, 10)
+ except ValueError as exc:
+ raise argparse.ArgumentTypeError("must be an integer") from exc
+ if not 1 <= parsed <= maximum:
+ raise argparse.ArgumentTypeError(f"must be between 1 and {maximum}")
+ return parsed
+
+
+def argparse_nonnegative_int(
+ value: str,
+ *,
+ maximum: int = MAX_BYTES,
+) -> int:
+ """Argparse converter for bounded nonnegative integers."""
+ try:
+ parsed = int(value, 10)
+ except ValueError as exc:
+ raise argparse.ArgumentTypeError("must be an integer") from exc
+ if not 0 <= parsed <= maximum:
+ raise argparse.ArgumentTypeError(f"must be between 0 and {maximum}")
+ return parsed
+
+
+def cli_error(parser: argparse.ArgumentParser, exc: Exception) -> int:
+ """Print one safe CLI error without a traceback."""
+ parser.exit(2, f"{parser.prog}: error: {exc}\n")
+ return 2
diff --git a/skills/get-available-resources/scripts/accelerator_diagnostics.py b/skills/get-available-resources/scripts/accelerator_diagnostics.py
new file mode 100644
index 00000000..0cea5caa
--- /dev/null
+++ b/skills/get-available-resources/scripts/accelerator_diagnostics.py
@@ -0,0 +1,151 @@
+#!/usr/bin/env python3
+"""Generate, but never execute, a read-only accelerator diagnostic plan."""
+
+from __future__ import annotations
+
+import argparse
+from typing import Any, Mapping, Sequence
+
+from _common import (
+ SCHEMA_VERSION,
+ ResourceToolError,
+ cli_error,
+ emit_json,
+ read_json_file,
+)
+from snapshot_tools import validate_snapshot
+
+FIXED_COMMANDS: dict[str, list[list[str]]] = {
+ "cuda": [
+ [
+ "nvidia-smi",
+ "--query-gpu=index,name,memory.total,memory.free,driver_version,compute_cap",
+ "--format=csv,noheader,nounits",
+ ]
+ ],
+ "metal": [["system_profiler", "SPDisplaysDataType", "-json"]],
+ "rocm": [
+ ["amd-smi", "static", "--json"],
+ [
+ "rocm-smi",
+ "--showproductname",
+ "--showmeminfo",
+ "vram",
+ "--json",
+ ],
+ ],
+}
+
+
+def build_diagnostic_plan(
+ snapshot: Mapping[str, Any],
+ *,
+ backend: str = "auto",
+) -> dict[str, Any]:
+ """Return fixed read-only probes and interpretation gates."""
+ validation = validate_snapshot(snapshot)
+ if not validation["valid"]:
+ raise ResourceToolError("snapshot does not satisfy schema 1.1")
+ if backend not in {"auto", "cuda", "metal", "rocm"}:
+ raise ResourceToolError("backend must be auto, cuda, metal, or rocm")
+
+ counts = snapshot["accelerators"].get("candidate_counts", {})
+ if backend == "auto":
+ selected = [
+ candidate
+ for candidate in ("cuda", "rocm", "metal")
+ if isinstance(counts.get(candidate), int) and counts[candidate] > 0
+ ]
+ else:
+ selected = [backend]
+
+ checks: list[dict[str, Any]] = []
+ for candidate in selected:
+ checks.append(
+ {
+ "backend": candidate,
+ "commands": FIXED_COMMANDS[candidate],
+ "management_visibility_gate": (
+ "A successful query confirms only management-tool visibility."
+ ),
+ "permission_gate": (
+ "Verify the allocation/container exposes the intended device; "
+ "do not broaden device permissions automatically."
+ ),
+ "runtime_gate": (
+ "Run the target framework's documented availability check in "
+ "the exact environment and verify driver/runtime compatibility."
+ ),
+ }
+ )
+
+ if not selected:
+ status = "no_management_visible_candidate"
+ elif any(
+ snapshot["accelerators"]
+ .get("candidate_upper_bounds", {})
+ .get(candidate)
+ == 0
+ for candidate in selected
+ ):
+ status = "visibility_or_allocation_restriction_present"
+ else:
+ status = "manual_runtime_validation_required"
+ return {
+ "checks": checks,
+ "execution": "not_performed",
+ "kind": "accelerator_diagnostic_plan",
+ "prohibited_actions": [
+ "driver installation or mutation",
+ "device reset, clock, power, or persistence changes",
+ "stress tests or large allocations",
+ "broad environment dumps",
+ ],
+ "schema_version": SCHEMA_VERSION,
+ "selected_backends": selected,
+ "status": status,
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description="Produce a read-only accelerator diagnostic plan; run nothing"
+ )
+ parser.add_argument("snapshot", help="validated snapshot JSON file")
+ parser.add_argument(
+ "--backend",
+ choices=("auto", "cuda", "rocm", "metal"),
+ default="auto",
+ help="backend to plan; default: auto from snapshot candidates",
+ )
+ parser.add_argument(
+ "--output",
+ metavar="FILE.json",
+ help="write a private local JSON file instead of stdout",
+ )
+ parser.add_argument(
+ "--force",
+ action="store_true",
+ help="replace an existing explicit output file",
+ )
+ return parser
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ if args.force and not args.output:
+ parser.error("--force requires --output")
+ try:
+ report = build_diagnostic_plan(
+ read_json_file(args.snapshot),
+ backend=args.backend,
+ )
+ emit_json(report, args.output, force=args.force)
+ except ResourceToolError as exc:
+ return cli_error(parser, exc)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/get-available-resources/scripts/detect_resources.py b/skills/get-available-resources/scripts/detect_resources.py
old mode 100755
new mode 100644
index 11d50e1e..2304318a
--- a/skills/get-available-resources/scripts/detect_resources.py
+++ b/skills/get-available-resources/scripts/detect_resources.py
@@ -1,402 +1,1767 @@
#!/usr/bin/env python3
-"""
-System Resource Detection Script
-
-Detects available compute resources including CPU, GPU, memory, and disk space.
-Outputs a JSON file that Claude Code can use to make informed decisions about
-computational approaches (e.g., whether to use Dask, Zarr, Joblib, etc.).
+"""Collect a conservative, privacy-preserving resource snapshot.
-Supports: macOS, Linux, Windows
-GPU Detection: NVIDIA (CUDA), AMD (ROCm), Apple Silicon (Metal)
+The script performs only bounded, read-only probes. It never stress-tests the
+machine, allocates a large buffer, changes affinity, or changes accelerator
+state. JSON is written to stdout unless a private local filename is explicitly
+requested.
"""
-import datetime
+from __future__ import annotations
+
+import argparse
+import csv
+import datetime as dt
+import importlib
+import io
import json
+import math
import os
import platform
-import psutil
+import re
+import shutil
import subprocess
-import sys
-from pathlib import Path
-from typing import Dict, List, Any, Optional
-
-
-def get_cpu_info() -> Dict[str, Any]:
- """Detect CPU information."""
- cpu_info = {
- "physical_cores": psutil.cpu_count(logical=False),
- "logical_cores": psutil.cpu_count(logical=True),
- "max_frequency_mhz": None,
- "architecture": platform.machine(),
- "processor": platform.processor(),
- }
+import threading
+from pathlib import Path, PurePosixPath
+from typing import Any, Callable, Mapping, Sequence
+
+from _common import (
+ MAX_BYTES,
+ SCHEMA_VERSION,
+ ResourceToolError,
+ cli_error,
+ emit_json,
+)
+
+MAX_PROBE_OUTPUT = 65_536
+MAX_KERNEL_TEXT = 524_288
+MAX_CGROUP_LEVELS = 64
+MAX_CPU_ID = 1_048_575
+MAX_DEVICES = 256
+MIB = 1024**2
+GIB = 1024**3
+_AUTO = object()
+
+NVIDIA_QUERY = (
+ "nvidia-smi",
+ "--query-gpu=index,name,memory.total,memory.free,driver_version,compute_cap",
+ "--format=csv,noheader,nounits",
+)
+NVIDIA_QUERY_FALLBACK = (
+ "nvidia-smi",
+ "--query-gpu=index,name,memory.total,memory.free,driver_version",
+ "--format=csv,noheader,nounits",
+)
+AMD_SMI_QUERY = ("amd-smi", "static", "--json")
+ROCM_SMI_QUERY = (
+ "rocm-smi",
+ "--showproductname",
+ "--showmeminfo",
+ "vram",
+ "--json",
+)
+APPLE_DISPLAY_QUERY = ("system_profiler", "SPDisplaysDataType", "-json")
+APPLE_SYSCTL_QUERY = (
+ "sysctl",
+ "-n",
+ "hw.logicalcpu",
+ "hw.physicalcpu",
+ "hw.memsize",
+ "machdep.cpu.brand_string",
+)
+
+ACCELERATOR_ENV_KEYS = (
+ "CUDA_VISIBLE_DEVICES",
+ "HIP_VISIBLE_DEVICES",
+ "NVIDIA_VISIBLE_DEVICES",
+ "ROCR_VISIBLE_DEVICES",
+)
+SLURM_ENV_KEYS = (
+ "SLURM_JOB_ID",
+ "SLURM_JOBID",
+ "SLURM_CPUS_ON_NODE",
+ "SLURM_CPUS_PER_TASK",
+ "SLURM_JOB_CPUS_PER_NODE",
+ "SLURM_MEM_PER_CPU",
+ "SLURM_MEM_PER_NODE",
+ "SLURM_NTASKS",
+ "SLURM_NTASKS_PER_NODE",
+ "SLURM_TASKS_PER_NODE",
+ "SLURM_GPUS",
+ "SLURM_GPUS_ON_NODE",
+ "SLURM_GPUS_PER_TASK",
+ "SLURM_JOB_GPUS",
+ "SLURM_STEP_GPUS",
+)
+
+
+def _warning(
+ warnings: list[dict[str, str]],
+ code: str,
+ component: str,
+ message: str,
+ *,
+ severity: str = "warning",
+) -> None:
+ warnings.append(
+ {
+ "code": code,
+ "component": component,
+ "message": message,
+ "severity": severity,
+ }
+ )
- # Get CPU frequency if available
- try:
- freq = psutil.cpu_freq()
- if freq:
- cpu_info["max_frequency_mhz"] = freq.max
- cpu_info["current_frequency_mhz"] = freq.current
- except Exception:
- pass
- return cpu_info
+def _provenance(
+ records: list[dict[str, str]],
+ component: str,
+ source: str,
+ status: str,
+) -> None:
+ records.append(
+ {"component": component, "source": source, "status": status}
+ )
-def get_memory_info() -> Dict[str, Any]:
- """Detect memory information."""
- mem = psutil.virtual_memory()
- swap = psutil.swap_memory()
+def _safe_text(value: Any, maximum: int = 128) -> str | None:
+ if not isinstance(value, (str, int, float)):
+ return None
+ rendered = " ".join(str(value).split())
+ rendered = "".join(character for character in rendered if character.isprintable())
+ return rendered[:maximum] or None
- return {
- "total_gb": round(mem.total / (1024**3), 2),
- "available_gb": round(mem.available / (1024**3), 2),
- "used_gb": round(mem.used / (1024**3), 2),
- "percent_used": mem.percent,
- "swap_total_gb": round(swap.total / (1024**3), 2),
- "swap_available_gb": round((swap.total - swap.used) / (1024**3), 2),
- }
+def _read_bounded_text(path: Path, maximum: int = MAX_KERNEL_TEXT) -> str:
+ with path.open("rb") as stream:
+ payload = stream.read(maximum + 1)
+ if len(payload) > maximum:
+ raise ValueError("bounded text input exceeded")
+ return payload.decode("utf-8", errors="replace")
-def get_disk_info(path: str = None) -> Dict[str, Any]:
- """Detect disk space information for working directory or specified path."""
- if path is None:
- path = os.getcwd()
+def _try_read(
+ read_text: Callable[[Path], str],
+ path: Path,
+) -> str | None:
try:
- disk = psutil.disk_usage(path)
- return {
- "path": path,
- "total_gb": round(disk.total / (1024**3), 2),
- "available_gb": round(disk.free / (1024**3), 2),
- "used_gb": round(disk.used / (1024**3), 2),
- "percent_used": disk.percent,
- }
- except Exception as e:
- return {
- "path": path,
- "error": str(e),
- }
+ return read_text(path)
+ except (OSError, ValueError, UnicodeError):
+ return None
+
+
+def _bounded_nonnegative(value: str | int | None) -> int | None:
+ if isinstance(value, bool) or value is None:
+ return None
+ try:
+ parsed = int(str(value).strip(), 10)
+ except (TypeError, ValueError):
+ return None
+ return parsed if 0 <= parsed <= MAX_BYTES else None
-def detect_nvidia_gpus() -> List[Dict[str, Any]]:
- """Detect NVIDIA GPUs using nvidia-smi."""
- gpus = []
+def parse_cpu_list(value: str) -> int | None:
+ """Count CPUs in a Linux range list without expanding it."""
+ if not isinstance(value, str) or not value.strip() or len(value) > 4096:
+ return None
+ intervals: list[tuple[int, int]] = []
+ for token in value.strip().split(","):
+ token = token.strip()
+ match = re.fullmatch(r"(\d+)(?:-(\d+))?", token)
+ if not match:
+ return None
+ start = int(match.group(1))
+ end = int(match.group(2) or start)
+ if start > end or end > MAX_CPU_ID:
+ return None
+ intervals.append((start, end))
+ intervals.sort()
+ total = 0
+ current_start, current_end = intervals[0]
+ for start, end in intervals[1:]:
+ if start <= current_end + 1:
+ current_end = max(current_end, end)
+ else:
+ total += current_end - current_start + 1
+ current_start, current_end = start, end
+ total += current_end - current_start + 1
+ return total if total <= MAX_CPU_ID + 1 else None
+
+
+def _parse_cpu_max(value: str) -> float | None:
+ fields = value.strip().split()
+ if len(fields) != 2 or fields[0] == "max":
+ return None
+ quota = _bounded_nonnegative(fields[0])
+ period = _bounded_nonnegative(fields[1])
+ if quota is None or period in (None, 0) or quota == 0:
+ return None
+ capacity = quota / period
+ if not math.isfinite(capacity) or capacity <= 0:
+ return None
+ return round(capacity, 6)
+
+
+def _run_bounded_command(
+ argv: Sequence[str],
+ *,
+ timeout: float = 4.0,
+ maximum: int = MAX_PROBE_OUTPUT,
+) -> dict[str, Any]:
+ """Run a fixed argv with bounded stdout/stderr and no shell."""
+ if not isinstance(argv, tuple) or not argv or not all(
+ isinstance(item, str) and item for item in argv
+ ):
+ raise ValueError("internal command must be a fixed nonempty tuple")
+ try:
+ process = subprocess.Popen(
+ list(argv),
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ shell=False,
+ )
+ except FileNotFoundError:
+ return {"status": "not_found", "stdout": "", "stderr": ""}
+ except OSError:
+ return {"status": "start_error", "stdout": "", "stderr": ""}
+
+ buffers = {"stdout": bytearray(), "stderr": bytearray()}
+ truncated = threading.Event()
+
+ def drain(name: str, stream: Any) -> None:
+ try:
+ while True:
+ chunk = stream.read(4096)
+ if not chunk:
+ break
+ remaining = maximum - len(buffers[name])
+ if remaining > 0:
+ buffers[name].extend(chunk[:remaining])
+ if len(chunk) > remaining:
+ truncated.set()
+ try:
+ process.kill()
+ except OSError:
+ pass
+ finally:
+ try:
+ stream.close()
+ except OSError:
+ pass
+ threads = [
+ threading.Thread(
+ target=drain,
+ args=("stdout", process.stdout),
+ daemon=True,
+ ),
+ threading.Thread(
+ target=drain,
+ args=("stderr", process.stderr),
+ daemon=True,
+ ),
+ ]
+ for thread in threads:
+ thread.start()
+
+ timed_out = False
try:
- # Try to run nvidia-smi
- result = subprocess.run(
- ["nvidia-smi", "--query-gpu=index,name,memory.total,memory.free,driver_version,compute_cap",
- "--format=csv,noheader,nounits"],
- capture_output=True,
- text=True,
- timeout=5
- )
-
- if result.returncode == 0:
- for line in result.stdout.strip().split('\n'):
- if line:
- parts = [p.strip() for p in line.split(',')]
- if len(parts) >= 6:
- gpus.append({
- "index": int(parts[0]),
- "name": parts[1],
- "memory_total_mb": float(parts[2]),
- "memory_free_mb": float(parts[3]),
- "driver_version": parts[4],
- "compute_capability": parts[5],
- "type": "NVIDIA",
- "backend": "CUDA"
- })
- except (subprocess.TimeoutExpired, FileNotFoundError, Exception):
- pass
-
- return gpus
-
-
-def detect_amd_gpus() -> List[Dict[str, Any]]:
- """Detect AMD GPUs using rocm-smi."""
- gpus = []
+ return_code = process.wait(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ timed_out = True
+ try:
+ process.kill()
+ except OSError:
+ pass
+ return_code = process.wait()
+ for thread in threads:
+ thread.join(timeout=1.0)
+
+ status = "ok" if return_code == 0 else "error"
+ if timed_out:
+ status = "timeout"
+ elif truncated.is_set():
+ status = "truncated"
+ return {
+ "returncode": return_code,
+ "status": status,
+ "stderr": buffers["stderr"].decode("utf-8", errors="replace"),
+ "stdout": buffers["stdout"].decode("utf-8", errors="replace"),
+ }
+
+def _load_psutil(
+ warnings: list[dict[str, str]],
+ provenance: list[dict[str, str]],
+) -> Any | None:
try:
- # Try to run rocm-smi
- result = subprocess.run(
- ["rocm-smi", "--showid", "--showmeminfo", "vram"],
- capture_output=True,
- text=True,
- timeout=5
- )
-
- if result.returncode == 0:
- # Parse rocm-smi output (basic parsing, may need refinement)
- lines = result.stdout.strip().split('\n')
- gpu_index = 0
- for line in lines:
- if 'GPU' in line and 'DID' in line:
- gpus.append({
- "index": gpu_index,
- "name": "AMD GPU",
- "type": "AMD",
- "backend": "ROCm",
- "info": line.strip()
- })
- gpu_index += 1
- except (subprocess.TimeoutExpired, FileNotFoundError, Exception):
- pass
-
- return gpus
-
-
-def detect_apple_silicon_gpu() -> Optional[Dict[str, Any]]:
- """Detect Apple Silicon GPU (M1/M2/M3/etc.)."""
- if platform.system() != "Darwin":
+ module = importlib.import_module("psutil")
+ except (ImportError, OSError):
+ _warning(
+ warnings,
+ "PSUTIL_UNAVAILABLE",
+ "inventory",
+ "Optional psutil is unavailable; standard-library fallbacks were used.",
+ severity="info",
+ )
+ _provenance(provenance, "inventory.psutil", "optional_import", "unavailable")
return None
+ _provenance(provenance, "inventory.psutil", "optional_import", "ok")
+ return module
- try:
- # Check if running on Apple Silicon
- result = subprocess.run(
- ["sysctl", "-n", "machdep.cpu.brand_string"],
- capture_output=True,
- text=True,
- timeout=5
- )
-
- cpu_brand = result.stdout.strip()
-
- # Check for Apple Silicon (M1, M2, M3, etc.)
- if "Apple" in cpu_brand and any(chip in cpu_brand for chip in ["M1", "M2", "M3", "M4"]):
- # Get GPU core count if possible
- gpu_info = {
- "name": cpu_brand,
- "type": "Apple Silicon",
- "backend": "Metal",
- "unified_memory": True, # Apple Silicon uses unified memory
- }
- # Try to get GPU core information
- try:
- result = subprocess.run(
- ["system_profiler", "SPDisplaysDataType"],
- capture_output=True,
- text=True,
- timeout=10
+def _linux_physical_cores(
+ read_text: Callable[[Path], str],
+) -> int | None:
+ payload = _try_read(read_text, Path("/proc/cpuinfo"))
+ if not payload:
+ return None
+ pairs: set[tuple[str, str]] = set()
+ for block in payload.split("\n\n"):
+ fields: dict[str, str] = {}
+ for line in block.splitlines():
+ if ":" in line:
+ key, value = line.split(":", 1)
+ fields[key.strip().lower()] = value.strip()
+ if "physical id" in fields and "core id" in fields:
+ pairs.add((fields["physical id"], fields["core id"]))
+ count = len(pairs)
+ return count if 0 < count <= MAX_CPU_ID + 1 else None
+
+
+def _mac_sysctl_values(
+ run_command: Callable[..., dict[str, Any]],
+ warnings: list[dict[str, str]],
+ provenance: list[dict[str, str]],
+) -> dict[str, Any]:
+ result = run_command(APPLE_SYSCTL_QUERY, timeout=2.0)
+ if result["status"] != "ok":
+ _warning(
+ warnings,
+ "APPLE_SYSCTL_UNAVAILABLE",
+ "platform",
+ "Apple sysctl inventory was unavailable; other sources were retained.",
+ severity="info",
+ )
+ _provenance(provenance, "platform.apple_sysctl", "sysctl", result["status"])
+ return {}
+ lines = result["stdout"].splitlines()
+ if len(lines) < 4:
+ _warning(
+ warnings,
+ "APPLE_SYSCTL_PARSE_FAILED",
+ "platform",
+ "Apple sysctl returned an unexpected bounded response.",
+ )
+ _provenance(provenance, "platform.apple_sysctl", "sysctl", "parse_error")
+ return {}
+ _provenance(provenance, "platform.apple_sysctl", "sysctl", "ok")
+ return {
+ "logical": _bounded_nonnegative(lines[0]),
+ "physical": _bounded_nonnegative(lines[1]),
+ "memory": _bounded_nonnegative(lines[2]),
+ "brand": _safe_text(lines[3]),
+ }
+
+
+def _detect_cpu_inventory(
+ *,
+ system: str,
+ psutil_module: Any | None,
+ mac_sysctl: Mapping[str, Any],
+ read_text: Callable[[Path], str],
+ warnings: list[dict[str, str]],
+ provenance: list[dict[str, str]],
+) -> dict[str, int | None]:
+ host_logical = os.cpu_count()
+ if (
+ not isinstance(host_logical, int)
+ or isinstance(host_logical, bool)
+ or not 1 <= host_logical <= MAX_CPU_ID + 1
+ ):
+ host_logical = None
+ _warning(
+ warnings,
+ "HOST_LOGICAL_CPU_UNKNOWN",
+ "cpu",
+ "Host logical CPU count could not be determined.",
+ )
+ _provenance(provenance, "cpu.host.logical", "os.cpu_count", "unavailable")
+ else:
+ _provenance(provenance, "cpu.host.logical", "os.cpu_count", "ok")
+
+ host_physical: int | None = None
+ if psutil_module is not None:
+ try:
+ candidate = psutil_module.cpu_count(logical=False)
+ if (
+ isinstance(candidate, int)
+ and not isinstance(candidate, bool)
+ and 0 < candidate <= MAX_CPU_ID + 1
+ ):
+ host_physical = candidate
+ _provenance(
+ provenance, "cpu.host.physical", "psutil.cpu_count", "ok"
)
+ except (AttributeError, OSError, RuntimeError, ValueError):
+ pass
+ if host_physical is None and system == "Darwin":
+ candidate = mac_sysctl.get("physical")
+ if isinstance(candidate, int) and 0 < candidate <= MAX_CPU_ID + 1:
+ host_physical = candidate
+ _provenance(provenance, "cpu.host.physical", "sysctl", "ok")
+ if host_physical is None and system == "Linux":
+ host_physical = _linux_physical_cores(read_text)
+ if host_physical is not None:
+ _provenance(provenance, "cpu.host.physical", "proc_cpuinfo", "ok")
+ if host_physical is None:
+ _warning(
+ warnings,
+ "HOST_PHYSICAL_CPU_UNKNOWN",
+ "cpu",
+ "Physical core count is unknown and was not inferred from logical CPUs.",
+ severity="info",
+ )
+ _provenance(provenance, "cpu.host.physical", "platform_fallbacks", "unavailable")
+ return {"logical": host_logical, "physical": host_physical}
+
+
+def _detect_process_cpu_count(
+ *,
+ psutil_module: Any | None,
+ warnings: list[dict[str, str]],
+ provenance: list[dict[str, str]],
+) -> dict[str, int | None]:
+ affinity_count: int | None = None
+ affinity_source: str | None = None
+ get_affinity = getattr(os, "sched_getaffinity", None)
+ if callable(get_affinity):
+ try:
+ affinity = get_affinity(0)
+ if affinity and len(affinity) <= MAX_CPU_ID + 1:
+ affinity_count = len(affinity)
+ affinity_source = "os.sched_getaffinity"
+ except (OSError, TypeError, ValueError):
+ pass
+ if affinity_count is None and psutil_module is not None:
+ try:
+ affinity = psutil_module.Process().cpu_affinity()
+ if affinity and len(affinity) <= MAX_CPU_ID + 1:
+ affinity_count = len(affinity)
+ affinity_source = "psutil.Process.cpu_affinity"
+ except (AttributeError, OSError, RuntimeError, ValueError):
+ pass
+ if affinity_count is not None:
+ _provenance(provenance, "cpu.process.affinity_logical", affinity_source or "", "ok")
+ else:
+ _provenance(
+ provenance, "cpu.process.affinity_logical", "affinity_apis", "unavailable"
+ )
- # Parse GPU core info from system_profiler
- for line in result.stdout.split('\n'):
- if 'Chipset Model' in line:
- gpu_info["chipset"] = line.split(':')[1].strip()
- elif 'Total Number of Cores' in line:
- try:
- cores = line.split(':')[1].strip()
- gpu_info["gpu_cores"] = cores
- except:
- pass
- except Exception:
- pass
+ process_count: int | None = None
+ process_cpu_count = getattr(os, "process_cpu_count", None)
+ if callable(process_cpu_count):
+ try:
+ candidate = process_cpu_count()
+ if (
+ isinstance(candidate, int)
+ and not isinstance(candidate, bool)
+ and 0 < candidate <= MAX_CPU_ID + 1
+ ):
+ process_count = candidate
+ _provenance(
+ provenance,
+ "cpu.process.python_available_logical",
+ "os.process_cpu_count",
+ "ok",
+ )
+ except (OSError, ValueError):
+ pass
+ if affinity_count is None and process_count is None:
+ _warning(
+ warnings,
+ "PROCESS_CPU_SCOPE_UNKNOWN",
+ "cpu",
+ "No process-aware CPU count API was available.",
+ severity="info",
+ )
+ return {
+ "affinity_logical": affinity_count,
+ "python_available_logical": process_count,
+ }
- return gpu_info
- except Exception:
- pass
+def _cgroup_relative_path(payload: str) -> tuple[str, ...] | None:
+ for line in payload.splitlines():
+ fields = line.split(":", 2)
+ if len(fields) == 3 and fields[0] == "0" and fields[1] == "":
+ raw = PurePosixPath(fields[2])
+ parts = tuple(part for part in raw.parts if part not in {"/", ""})
+ if any(part in {".", ".."} for part in parts):
+ return None
+ return parts
return None
-def get_gpu_info() -> Dict[str, Any]:
- """Detect all available GPUs."""
- gpu_info = {
- "nvidia_gpus": detect_nvidia_gpus(),
- "amd_gpus": detect_amd_gpus(),
- "apple_silicon": detect_apple_silicon_gpu(),
- "total_gpus": 0,
- "available_backends": []
+def detect_cgroup_v2(
+ *,
+ read_text: Callable[[Path], str] = _read_bounded_text,
+ root: Path = Path("/sys/fs/cgroup"),
+ proc_self_cgroup: Path = Path("/proc/self/cgroup"),
+ warnings: list[dict[str, str]] | None = None,
+ provenance: list[dict[str, str]] | None = None,
+) -> dict[str, Any]:
+ """Read current and ancestor cgroup v2 limits without exposing paths."""
+ warning_records = warnings if warnings is not None else []
+ provenance_records = provenance if provenance is not None else []
+ if _try_read(read_text, root / "cgroup.controllers") is None:
+ _provenance(
+ provenance_records, "cgroup_v2", "cgroup.controllers", "unavailable"
+ )
+ return {
+ "detected": False,
+ "cpu_quota_cores": None,
+ "cpuset_logical": None,
+ "memory_available_bytes": None,
+ "memory_current_bytes": None,
+ "memory_high_bytes": None,
+ "memory_max_bytes": None,
+ "scope": "unknown",
+ }
+
+ membership = _try_read(read_text, proc_self_cgroup)
+ parts = _cgroup_relative_path(membership or "")
+ if parts is None:
+ _warning(
+ warning_records,
+ "CGROUP_MEMBERSHIP_UNKNOWN",
+ "cgroup",
+ "cgroup v2 was detected but current membership could not be parsed.",
+ )
+ parts = ()
+ current = root.joinpath(*parts)
+ chain: list[Path] = []
+ cursor = current
+ for _ in range(MAX_CGROUP_LEVELS):
+ chain.append(cursor)
+ if cursor == root:
+ break
+ parent = cursor.parent
+ if parent == cursor or (parent != root and root not in parent.parents):
+ break
+ cursor = parent
+ else:
+ _warning(
+ warning_records,
+ "CGROUP_DEPTH_BOUNDED",
+ "cgroup",
+ "cgroup ancestor traversal reached its safety bound.",
+ )
+
+ quota_candidates: list[float] = []
+ memory_max_candidates: list[int] = []
+ memory_high_candidates: list[int] = []
+ memory_available_candidates: list[int] = []
+ current_memory: int | None = None
+
+ for index, directory in enumerate(chain):
+ cpu_max_text = _try_read(read_text, directory / "cpu.max")
+ if cpu_max_text is not None:
+ quota = _parse_cpu_max(cpu_max_text)
+ if quota is not None:
+ quota_candidates.append(quota)
+
+ memory_max_text = _try_read(read_text, directory / "memory.max")
+ memory_current_text = _try_read(read_text, directory / "memory.current")
+ memory_high_text = _try_read(read_text, directory / "memory.high")
+ memory_current = _bounded_nonnegative(memory_current_text)
+ if index == 0:
+ current_memory = memory_current
+ memory_max = (
+ None
+ if memory_max_text is None or memory_max_text.strip() == "max"
+ else _bounded_nonnegative(memory_max_text)
+ )
+ memory_high = (
+ None
+ if memory_high_text is None or memory_high_text.strip() == "max"
+ else _bounded_nonnegative(memory_high_text)
+ )
+ if memory_max is not None:
+ memory_max_candidates.append(memory_max)
+ if memory_current is not None:
+ memory_available_candidates.append(max(0, memory_max - memory_current))
+ if memory_high is not None:
+ memory_high_candidates.append(memory_high)
+
+ cpuset_text = _try_read(read_text, current / "cpuset.cpus.effective")
+ cpuset_count = parse_cpu_list(cpuset_text) if cpuset_text else None
+ if cpuset_text and cpuset_count is None:
+ _warning(
+ warning_records,
+ "CGROUP_CPUSET_PARSE_FAILED",
+ "cgroup",
+ "cpuset.cpus.effective had an unexpected bounded value.",
+ )
+
+ _provenance(provenance_records, "cgroup_v2", "procfs_and_cgroupfs", "ok")
+ return {
+ "detected": True,
+ "cpu_quota_cores": min(quota_candidates) if quota_candidates else None,
+ "cpuset_logical": cpuset_count,
+ "memory_available_bytes": (
+ min(memory_available_candidates)
+ if memory_available_candidates
+ else None
+ ),
+ "memory_current_bytes": current_memory,
+ "memory_high_bytes": (
+ min(memory_high_candidates) if memory_high_candidates else None
+ ),
+ "memory_max_bytes": (
+ min(memory_max_candidates) if memory_max_candidates else None
+ ),
+ "scope": "non_root" if parts else "root",
}
- # Count total GPUs and available backends
- if gpu_info["nvidia_gpus"]:
- gpu_info["total_gpus"] += len(gpu_info["nvidia_gpus"])
- gpu_info["available_backends"].append("CUDA")
- if gpu_info["amd_gpus"]:
- gpu_info["total_gpus"] += len(gpu_info["amd_gpus"])
- gpu_info["available_backends"].append("ROCm")
+def _parse_slurm_count(value: str | None) -> int | None:
+ if value is None or not 0 < len(value) <= 128:
+ return None
+ stripped = value.strip()
+ if stripped.isdigit():
+ count = int(stripped)
+ return count if 0 <= count <= 1_000_000 else None
+ match = re.fullmatch(r"(?:[A-Za-z0-9_.+-]+:)+(\d+)", stripped)
+ if match:
+ count = int(match.group(1))
+ return count if count <= 1_000_000 else None
+ return None
- if gpu_info["apple_silicon"]:
- gpu_info["total_gpus"] += 1
- gpu_info["available_backends"].append("Metal")
- return gpu_info
+def _parse_slurm_memory(value: str | None) -> int | None:
+ if value is None or not 0 < len(value) <= 128:
+ return None
+ match = re.fullmatch(r"\s*(\d+)\s*([KkMmGgTt]?)\s*", value)
+ if not match:
+ return None
+ amount = int(match.group(1))
+ if amount == 0:
+ return None
+ suffix = match.group(2).upper()
+ multiplier = {"K": 1024, "M": MIB, "G": GIB, "T": 1024**4, "": MIB}[suffix]
+ result = amount * multiplier
+ return result if result <= MAX_BYTES else None
-def get_os_info() -> Dict[str, Any]:
- """Get operating system information."""
+def _parse_first_repeated_count(value: str | None) -> int | None:
+ if value is None or len(value) > 4096:
+ return None
+ match = re.match(r"\s*(\d+)(?:\(x\d+\))?", value)
+ if not match:
+ return None
+ count = int(match.group(1))
+ return count if count <= 1_000_000 else None
+
+
+def detect_scheduler(
+ environ: Mapping[str, str],
+ *,
+ warnings: list[dict[str, str]] | None = None,
+ provenance: list[dict[str, str]] | None = None,
+) -> dict[str, Any]:
+ """Interpret only an allowlist of Slurm allocation variables."""
+ warning_records = warnings if warnings is not None else []
+ provenance_records = provenance if provenance is not None else []
+ present = {
+ key: environ[key]
+ for key in SLURM_ENV_KEYS
+ if key in environ and isinstance(environ[key], str)
+ }
+ detected = bool(present)
+ if not detected:
+ _provenance(provenance_records, "scheduler", "named_slurm_environment", "absent")
+ return {
+ "allocation": {
+ "cpu_per_process": None,
+ "cpus_on_node": None,
+ "gpus_per_process": None,
+ "gpus_on_node": None,
+ "memory_effective_bytes": None,
+ "memory_scope": None,
+ "tasks": None,
+ },
+ "detected": False,
+ "enforcement": "not_applicable",
+ "fields_read": [],
+ "kind": None,
+ }
+
+ cpus_per_task = _parse_slurm_count(present.get("SLURM_CPUS_PER_TASK"))
+ cpus_on_node = _parse_slurm_count(present.get("SLURM_CPUS_ON_NODE"))
+ tasks = _parse_slurm_count(present.get("SLURM_NTASKS"))
+ tasks_per_node = _parse_slurm_count(present.get("SLURM_NTASKS_PER_NODE"))
+ if tasks_per_node is None:
+ tasks_per_node = _parse_first_repeated_count(
+ present.get("SLURM_TASKS_PER_NODE")
+ )
+ first_job_cpus = _parse_first_repeated_count(
+ present.get("SLURM_JOB_CPUS_PER_NODE")
+ )
+ cpu_per_process = cpus_per_task
+ if cpu_per_process is None and cpus_on_node is not None and tasks_per_node == 1:
+ cpu_per_process = cpus_on_node
+
+ memory_per_cpu = _parse_slurm_memory(present.get("SLURM_MEM_PER_CPU"))
+ memory_per_node = _parse_slurm_memory(present.get("SLURM_MEM_PER_NODE"))
+ memory_effective: int | None = None
+ memory_scope: str | None = None
+ if memory_per_cpu is not None and cpu_per_process is not None:
+ memory_effective = min(MAX_BYTES, memory_per_cpu * cpu_per_process)
+ memory_scope = "per_task_from_per_cpu"
+ elif memory_per_node is not None:
+ memory_effective = memory_per_node
+ memory_scope = "shared_per_node"
+ if tasks_per_node is None or tasks_per_node > 1:
+ _warning(
+ warning_records,
+ "SLURM_MEMORY_SHARED",
+ "scheduler",
+ "Slurm per-node memory is shared; it is only an upper bound for this process.",
+ severity="info",
+ )
+
+ gpus_per_task = _parse_slurm_count(present.get("SLURM_GPUS_PER_TASK"))
+ gpus_on_node = _parse_slurm_count(present.get("SLURM_GPUS_ON_NODE"))
+ requested_gpus = _parse_slurm_count(present.get("SLURM_GPUS"))
+
+ _warning(
+ warning_records,
+ "SLURM_ENFORCEMENT_UNKNOWN",
+ "scheduler",
+ "Allocation variables do not prove task affinity or cgroup enforcement.",
+ severity="info",
+ )
+ if cpus_per_task is None and cpus_on_node is not None and tasks_per_node != 1:
+ _warning(
+ warning_records,
+ "SLURM_CPU_SCOPE_SHARED",
+ "scheduler",
+ "Node CPU allocation was not treated as a per-process limit.",
+ severity="info",
+ )
+ _provenance(provenance_records, "scheduler", "named_slurm_environment", "ok")
return {
- "system": platform.system(),
- "release": platform.release(),
- "version": platform.version(),
- "machine": platform.machine(),
- "python_version": platform.python_version(),
+ "allocation": {
+ "cpu_per_process": cpu_per_process,
+ "cpus_on_node": cpus_on_node,
+ "first_job_cpus_per_node": first_job_cpus,
+ "gpus_per_process": gpus_per_task,
+ "gpus_on_node": gpus_on_node,
+ "gpus_requested": requested_gpus,
+ "memory_effective_bytes": memory_effective,
+ "memory_scope": memory_scope,
+ "tasks": tasks,
+ "tasks_per_node": tasks_per_node,
+ },
+ "detected": True,
+ "enforcement": "unknown",
+ "fields_read": sorted(present),
+ "kind": "slurm",
}
-def detect_all_resources(output_path: str = None) -> Dict[str, Any]:
- """
- Detect all system resources and save to JSON.
+def _effective_cpu(
+ host: Mapping[str, int | None],
+ process: Mapping[str, int | None],
+ cgroup: Mapping[str, Any],
+ scheduler: Mapping[str, Any],
+) -> dict[str, Any]:
+ candidates: list[tuple[str, float]] = []
+ for source, value in (
+ ("host_logical", host.get("logical")),
+ ("process_affinity", process.get("affinity_logical")),
+ ("python_process_count", process.get("python_available_logical")),
+ ("cgroup_cpuset", cgroup.get("cpuset_logical")),
+ ("cgroup_quota", cgroup.get("cpu_quota_cores")),
+ (
+ "scheduler_per_process",
+ scheduler.get("allocation", {}).get("cpu_per_process"),
+ ),
+ ):
+ if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0:
+ candidates.append((source, float(value)))
+ if not candidates:
+ return {
+ "capacity_cores": None,
+ "limiting_sources": [],
+ "worker_ceiling": 1,
+ }
+ capacity = min(value for _, value in candidates)
+ limiting = sorted(
+ source for source, value in candidates if abs(value - capacity) < 1e-9
+ )
+ return {
+ "capacity_cores": round(capacity, 6),
+ "limiting_sources": limiting,
+ "worker_ceiling": max(1, min(1024, math.floor(capacity))),
+ }
+
- Args:
- output_path: Optional path to save JSON. Defaults to .claude_resources.json in cwd.
+def _parse_linux_meminfo(payload: str) -> dict[str, int | None]:
+ values: dict[str, int] = {}
+ for line in payload.splitlines():
+ match = re.fullmatch(r"([A-Za-z_()]+):\s+(\d+)\s+kB", line.strip())
+ if match:
+ values[match.group(1)] = int(match.group(2)) * 1024
+ return {
+ "available": values.get("MemAvailable"),
+ "swap_free": values.get("SwapFree"),
+ "swap_total": values.get("SwapTotal"),
+ "total": values.get("MemTotal"),
+ }
- Returns:
- Dictionary containing all resource information.
- """
- if output_path is None:
- output_path = os.path.join(os.getcwd(), ".claude_resources.json")
- resources = {
- "timestamp": datetime.datetime.now().isoformat(),
- "os": get_os_info(),
- "cpu": get_cpu_info(),
- "memory": get_memory_info(),
- "disk": get_disk_info(),
- "gpu": get_gpu_info(),
+def _detect_memory(
+ *,
+ system: str,
+ machine: str,
+ psutil_module: Any | None,
+ mac_sysctl: Mapping[str, Any],
+ cgroup: Mapping[str, Any],
+ scheduler: Mapping[str, Any],
+ read_text: Callable[[Path], str],
+ warnings: list[dict[str, str]],
+ provenance: list[dict[str, str]],
+) -> dict[str, Any]:
+ host_total: int | None = None
+ host_available: int | None = None
+ swap_total: int | None = None
+ swap_free: int | None = None
+ if psutil_module is not None:
+ try:
+ memory = psutil_module.virtual_memory()
+ host_total = _bounded_nonnegative(memory.total)
+ host_available = _bounded_nonnegative(memory.available)
+ _provenance(provenance, "memory.host", "psutil.virtual_memory", "ok")
+ except (AttributeError, OSError, RuntimeError, ValueError):
+ pass
+ try:
+ swap = psutil_module.swap_memory()
+ swap_total = _bounded_nonnegative(swap.total)
+ swap_free = _bounded_nonnegative(swap.free)
+ _provenance(provenance, "memory.swap", "psutil.swap_memory", "ok")
+ except (AttributeError, OSError, RuntimeError, ValueError):
+ pass
+
+ if system == "Linux" and (host_total is None or host_available is None):
+ payload = _try_read(read_text, Path("/proc/meminfo"))
+ if payload:
+ parsed = _parse_linux_meminfo(payload)
+ host_total = host_total or parsed["total"]
+ host_available = (
+ host_available
+ if host_available is not None
+ else parsed["available"]
+ )
+ swap_total = swap_total if swap_total is not None else parsed["swap_total"]
+ swap_free = swap_free if swap_free is not None else parsed["swap_free"]
+ _provenance(provenance, "memory.host", "proc_meminfo", "ok")
+ if system == "Darwin" and host_total is None:
+ candidate = mac_sysctl.get("memory")
+ if isinstance(candidate, int) and candidate > 0:
+ host_total = candidate
+ _provenance(provenance, "memory.host.total", "sysctl", "ok")
+ if host_total is None:
+ try:
+ pages = os.sysconf("SC_PHYS_PAGES")
+ page_size = os.sysconf("SC_PAGE_SIZE")
+ candidate = pages * page_size
+ if 0 < candidate <= MAX_BYTES:
+ host_total = candidate
+ _provenance(provenance, "memory.host.total", "os.sysconf", "ok")
+ except (AttributeError, OSError, TypeError, ValueError):
+ pass
+
+ if host_total is None:
+ _warning(
+ warnings,
+ "HOST_MEMORY_TOTAL_UNKNOWN",
+ "memory",
+ "Host memory total could not be determined.",
+ )
+ if host_available is None:
+ _warning(
+ warnings,
+ "HOST_MEMORY_AVAILABLE_UNKNOWN",
+ "memory",
+ "Host available memory could not be determined without an allocation probe.",
+ severity="info",
+ )
+
+ limit_candidates: list[tuple[str, int]] = []
+ available_candidates: list[tuple[str, int]] = []
+ for source, value in (
+ ("host_total", host_total),
+ ("cgroup_memory_max", cgroup.get("memory_max_bytes")),
+ (
+ "scheduler_memory",
+ scheduler.get("allocation", {}).get("memory_effective_bytes"),
+ ),
+ ):
+ if isinstance(value, int) and value >= 0:
+ limit_candidates.append((source, value))
+ for source, value in (
+ ("host_available", host_available),
+ ("cgroup_memory_remaining", cgroup.get("memory_available_bytes")),
+ (
+ "scheduler_memory_upper_bound",
+ scheduler.get("allocation", {}).get("memory_effective_bytes"),
+ ),
+ ):
+ if isinstance(value, int) and value >= 0:
+ available_candidates.append((source, value))
+
+ effective_limit = (
+ min(value for _, value in limit_candidates) if limit_candidates else None
+ )
+ effective_available = (
+ min(value for _, value in available_candidates)
+ if available_candidates
+ else None
+ )
+ if (
+ effective_limit is not None
+ and effective_available is not None
+ and effective_available > effective_limit
+ ):
+ effective_available = effective_limit
+ limiting_sources = (
+ sorted(
+ source
+ for source, value in limit_candidates
+ if value == effective_limit
+ )
+ if effective_limit is not None
+ else []
+ )
+ available_sources = (
+ sorted(
+ source
+ for source, value in available_candidates
+ if value == effective_available
+ )
+ if effective_available is not None
+ else []
+ )
+ unified = system == "Darwin" and machine.lower() in {"arm64", "aarch64"}
+ return {
+ "cgroup_v2": {
+ "available_bytes": cgroup.get("memory_available_bytes"),
+ "current_bytes": cgroup.get("memory_current_bytes"),
+ "high_bytes": cgroup.get("memory_high_bytes"),
+ "max_bytes": cgroup.get("memory_max_bytes"),
+ },
+ "effective": {
+ "available_bytes": effective_available,
+ "available_limiting_sources": available_sources,
+ "hard_limit_bytes": effective_limit,
+ "hard_limit_sources": limiting_sources,
+ "pressure_threshold_bytes": cgroup.get("memory_high_bytes"),
+ },
+ "host": {
+ "available_bytes": host_available,
+ "total_bytes": host_total,
+ },
+ "model": "unified_cpu_gpu" if unified else "system_ram",
+ "swap": {"free_bytes": swap_free, "total_bytes": swap_total},
+ }
+
+
+def _detect_disk(
+ warnings: list[dict[str, str]],
+ provenance: list[dict[str, str]],
+) -> dict[str, Any]:
+ try:
+ usage = shutil.disk_usage(Path.cwd())
+ total = _bounded_nonnegative(usage.total)
+ free = _bounded_nonnegative(usage.free)
+ if total is None or free is None or free > total:
+ raise ValueError("invalid bounded disk values")
+ _provenance(provenance, "disk", "shutil.disk_usage", "ok")
+ except (OSError, ValueError):
+ _warning(
+ warnings,
+ "DISK_CAPACITY_UNKNOWN",
+ "disk",
+ "Working filesystem capacity could not be read.",
+ )
+ _provenance(provenance, "disk", "shutil.disk_usage", "unavailable")
+ return {
+ "capacity_bytes": None,
+ "free_bytes": None,
+ "scope": "working_filesystem_path_redacted",
+ "user_available_bytes": None,
+ "writable": None,
+ "writability_check": "not_performed",
+ }
+
+ user_available = free
+ if hasattr(os, "statvfs"):
+ try:
+ statvfs = os.statvfs(Path.cwd())
+ candidate = _bounded_nonnegative(
+ statvfs.f_bavail * statvfs.f_frsize
+ )
+ if candidate is not None:
+ user_available = candidate
+ _provenance(
+ provenance, "disk.user_available", "os.statvfs", "ok"
+ )
+ except (OSError, TypeError, ValueError):
+ pass
+ writable = os.access(Path.cwd(), os.W_OK)
+ if not writable:
+ _warning(
+ warnings,
+ "WORKING_DIRECTORY_NOT_WRITABLE",
+ "disk",
+ "The working directory failed the non-writing access check.",
+ )
+ return {
+ "capacity_bytes": total,
+ "free_bytes": free,
+ "scope": "working_filesystem_path_redacted",
+ "user_available_bytes": max(0, min(free, user_available)),
+ "writable": bool(writable),
+ "writability_check": "os_access_only_no_write_probe",
}
- # Add computational recommendations
- resources["recommendations"] = generate_recommendations(resources)
- # Save to JSON file
- with open(output_path, 'w') as f:
- json.dump(resources, f, indent=2)
+def _mib_to_bytes(value: str) -> int | None:
+ try:
+ amount = float(value)
+ except ValueError:
+ return None
+ if not math.isfinite(amount) or amount < 0:
+ return None
+ result = round(amount * MIB)
+ return result if result <= MAX_BYTES else None
+
+
+def parse_nvidia_csv(payload: str) -> list[dict[str, Any]]:
+ devices: list[dict[str, Any]] = []
+ try:
+ rows = csv.reader(io.StringIO(payload))
+ for row in rows:
+ if len(row) not in {5, 6}:
+ continue
+ index = _bounded_nonnegative(row[0])
+ if index is None or index > 4096:
+ continue
+ devices.append(
+ {
+ "backend_candidate": "cuda",
+ "compute_capability": (
+ _safe_text(row[5], 16) if len(row) == 6 else None
+ ),
+ "device_class": "gpu",
+ "device_permission": "not_tested",
+ "driver_version": _safe_text(row[4], 64),
+ "local_index": index,
+ "management_query": "visible",
+ "memory": {
+ "dedicated_free_bytes": _mib_to_bytes(row[3].strip()),
+ "dedicated_total_bytes": _mib_to_bytes(row[2].strip()),
+ "model": "dedicated",
+ },
+ "name": _safe_text(row[1]) or "NVIDIA GPU",
+ "runtime_compatibility": "not_tested",
+ "vendor": "nvidia",
+ }
+ )
+ except csv.Error:
+ return []
+ return sorted(devices, key=lambda item: item["local_index"])
+
+
+def _recursive_scalar(
+ value: Any,
+ accepted_keys: set[str],
+) -> tuple[str, Any] | None:
+ if isinstance(value, dict):
+ for key, child in value.items():
+ normalized = re.sub(r"[^a-z0-9]+", "_", str(key).lower()).strip("_")
+ if normalized in accepted_keys and isinstance(child, (str, int, float)):
+ return normalized, child
+ for child in value.values():
+ found = _recursive_scalar(child, accepted_keys)
+ if found is not None:
+ return found
+ elif isinstance(value, list):
+ for child in value:
+ found = _recursive_scalar(child, accepted_keys)
+ if found is not None:
+ return found
+ return None
- return resources
+def _amd_entries(data: Any) -> list[tuple[int, dict[str, Any]]]:
+ entries: list[tuple[int, dict[str, Any]]] = []
+ if isinstance(data, list):
+ for index, item in enumerate(data):
+ if isinstance(item, dict) and (
+ "gpu" in {str(key).lower() for key in item}
+ or "asic" in {str(key).lower() for key in item}
+ ):
+ gpu_value = next(
+ (
+ value
+ for key, value in item.items()
+ if str(key).lower() == "gpu"
+ ),
+ index,
+ )
+ gpu_index = _bounded_nonnegative(gpu_value)
+ entries.append((gpu_index if gpu_index is not None else index, item))
+ elif isinstance(data, dict):
+ for key, item in data.items():
+ normalized = re.sub(
+ r"[^a-z0-9]+", "_", str(key).lower()
+ ).strip("_")
+ if normalized in {"gpu_data", "gpu_devices", "gpus"}:
+ entries.extend(_amd_entries(item))
+ for key, item in data.items():
+ match = re.fullmatch(r"(?:card|gpu)\s*(\d+)", str(key), re.IGNORECASE)
+ if match and isinstance(item, dict):
+ entries.append((int(match.group(1)), item))
+ if not entries and "gpu" in {str(key).lower() for key in data}:
+ gpu_value = next(
+ value for key, value in data.items() if str(key).lower() == "gpu"
+ )
+ if not isinstance(gpu_value, (dict, list)):
+ gpu_index = _bounded_nonnegative(gpu_value)
+ entries.append((gpu_index or 0, data))
+ deduplicated: dict[int, dict[str, Any]] = {}
+ for index, entry in entries:
+ deduplicated.setdefault(index, entry)
+ return sorted(deduplicated.items())
+
+
+def _amd_memory_bytes(entry: Mapping[str, Any]) -> int | None:
+ for key, value in entry.items():
+ normalized = re.sub(r"[^a-z0-9]+", "_", str(key).lower()).strip("_")
+ if (
+ "vram" in normalized
+ and ("total" in normalized or "size" in normalized)
+ and isinstance(value, (str, int, float))
+ ):
+ match = re.search(r"(\d+(?:\.\d+)?)", str(value))
+ if not match:
+ continue
+ amount = float(match.group(1))
+ unit_context = f"{normalized} {str(value).lower()}"
+ if "gib" in unit_context or "gb" in unit_context:
+ multiplier = GIB
+ elif "mib" in unit_context or "mb" in unit_context:
+ multiplier = MIB
+ else:
+ multiplier = 1
+ result = round(amount * multiplier)
+ if 0 <= result <= MAX_BYTES:
+ return result
+ if isinstance(value, dict):
+ nested = _amd_memory_bytes(value)
+ if nested is not None:
+ return nested
+ return None
-def generate_recommendations(resources: Dict[str, Any]) -> Dict[str, Any]:
- """
- Generate computational approach recommendations based on available resources.
- """
- recommendations = {
- "parallel_processing": {},
- "memory_strategy": {},
- "gpu_acceleration": {},
- "large_data_handling": {}
+
+def parse_amd_json(payload: str) -> list[dict[str, Any]]:
+ try:
+ data = json.loads(payload)
+ entries = _amd_entries(data)
+ except (json.JSONDecodeError, RecursionError):
+ return []
+ devices: list[dict[str, Any]] = []
+ name_keys = {
+ "asic_market_name",
+ "card_model",
+ "card_series",
+ "market_name",
+ "product_name",
}
+ for index, entry in entries:
+ try:
+ found = _recursive_scalar(entry, name_keys)
+ total_memory = _amd_memory_bytes(entry)
+ except RecursionError:
+ continue
+ name = _safe_text(found[1]) if found else None
+ devices.append(
+ {
+ "backend_candidate": "rocm",
+ "compute_capability": None,
+ "device_class": "gpu",
+ "device_permission": "not_tested",
+ "driver_version": None,
+ "local_index": index,
+ "management_query": "visible",
+ "memory": {
+ "dedicated_free_bytes": None,
+ "dedicated_total_bytes": total_memory,
+ "model": "dedicated_or_hbm",
+ },
+ "name": name or "AMD GPU",
+ "runtime_compatibility": "not_tested",
+ "vendor": "amd",
+ }
+ )
+ return sorted(devices, key=lambda item: item["local_index"])
+
- # CPU recommendations
- cpu_cores = resources["cpu"]["logical_cores"]
- if cpu_cores >= 8:
- recommendations["parallel_processing"]["strategy"] = "high_parallelism"
- recommendations["parallel_processing"]["suggested_workers"] = max(cpu_cores - 2, 1)
- recommendations["parallel_processing"]["libraries"] = ["joblib", "multiprocessing", "dask"]
- elif cpu_cores >= 4:
- recommendations["parallel_processing"]["strategy"] = "moderate_parallelism"
- recommendations["parallel_processing"]["suggested_workers"] = max(cpu_cores - 1, 1)
- recommendations["parallel_processing"]["libraries"] = ["joblib", "multiprocessing"]
+def parse_apple_profiler_json(
+ payload: str,
+ *,
+ machine: str,
+) -> list[dict[str, Any]]:
+ try:
+ data = json.loads(payload)
+ except (json.JSONDecodeError, RecursionError):
+ return []
+ entries = data.get("SPDisplaysDataType") if isinstance(data, dict) else None
+ if not isinstance(entries, list):
+ return []
+ unified = machine.lower() in {"arm64", "aarch64"}
+ devices: list[dict[str, Any]] = []
+ for index, entry in enumerate(entries):
+ if not isinstance(entry, dict):
+ continue
+ name = _safe_text(entry.get("sppci_model") or entry.get("_name"))
+ core_value = (
+ entry.get("sppci_cores")
+ or entry.get("spdisplays_gpu_cores")
+ or entry.get("_spdisplays_gpu_cores")
+ )
+ devices.append(
+ {
+ "backend_candidate": "metal",
+ "compute_capability": None,
+ "device_class": "integrated_gpu" if unified else "gpu",
+ "device_permission": "not_tested",
+ "driver_version": None,
+ "gpu_cores": _bounded_nonnegative(core_value),
+ "local_index": index,
+ "management_query": "visible",
+ "memory": {
+ "dedicated_free_bytes": None,
+ "dedicated_total_bytes": None,
+ "model": "unified" if unified else "unknown",
+ },
+ "name": name or "Apple display accelerator",
+ "runtime_compatibility": "not_tested",
+ "vendor": "apple",
+ }
+ )
+ return devices
+
+
+def _visibility_summary(environ: Mapping[str, str]) -> dict[str, Any]:
+ summary: dict[str, Any] = {}
+ for key in ACCELERATOR_ENV_KEYS:
+ if key not in environ:
+ summary[key] = {
+ "entry_count": None,
+ "set": False,
+ "state": "unset",
+ "value_redacted": True,
+ }
+ continue
+ raw = environ[key] if isinstance(environ[key], str) else ""
+ if len(raw) > 4096:
+ summary[key] = {
+ "entry_count": None,
+ "set": True,
+ "state": "invalid_or_oversized",
+ "value_redacted": True,
+ }
+ continue
+ stripped = raw.strip()
+ lowered = stripped.lower()
+ if lowered in {"", "-1", "none", "void"}:
+ state, count = "none", 0
+ elif lowered == "all":
+ state, count = "all", None
+ else:
+ entries = {
+ item.strip() for item in stripped.split(",") if item.strip()
+ }
+ state = "restricted" if entries else "none"
+ count = min(len(entries), 4096)
+ summary[key] = {
+ "entry_count": count,
+ "set": True,
+ "state": state,
+ "value_redacted": True,
+ }
+ return summary
+
+
+def _accelerator_upper_bounds(
+ devices: Sequence[Mapping[str, Any]],
+ visibility: Mapping[str, Mapping[str, Any]],
+ scheduler: Mapping[str, Any],
+) -> dict[str, int | None]:
+ result: dict[str, int | None] = {}
+ scheduler_count = scheduler.get("allocation", {}).get("gpus_per_process")
+ if scheduler_count is None:
+ scheduler_count = scheduler.get("allocation", {}).get("gpus_on_node")
+ environment_keys = {
+ "cuda": ("CUDA_VISIBLE_DEVICES", "NVIDIA_VISIBLE_DEVICES"),
+ "rocm": ("ROCR_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"),
+ "metal": (),
+ }
+ for backend, keys in environment_keys.items():
+ query_count = sum(
+ 1 for device in devices if device.get("backend_candidate") == backend
+ )
+ if query_count == 0:
+ result[backend] = None
+ continue
+ limits = [query_count]
+ if isinstance(scheduler_count, int):
+ limits.append(scheduler_count)
+ for key in keys:
+ item = visibility.get(key, {})
+ if item.get("state") == "none":
+ limits.append(0)
+ elif (
+ item.get("state") == "restricted"
+ and isinstance(item.get("entry_count"), int)
+ ):
+ limits.append(item["entry_count"])
+ result[backend] = min(limits)
+ return result
+
+
+def _record_probe_failure(
+ result: Mapping[str, Any],
+ *,
+ code: str,
+ component: str,
+ tool: str,
+ warnings: list[dict[str, str]],
+ provenance: list[dict[str, str]],
+) -> None:
+ status = str(result.get("status", "error"))
+ _provenance(provenance, component, tool, status)
+ if status != "not_found":
+ _warning(
+ warnings,
+ code,
+ component,
+ f"{tool} read-only query did not complete successfully ({status}).",
+ severity="info" if status in {"start_error", "error"} else "warning",
+ )
+
+
+def _detect_accelerators(
+ *,
+ system: str,
+ machine: str,
+ environ: Mapping[str, str],
+ scheduler: Mapping[str, Any],
+ run_command: Callable[..., dict[str, Any]],
+ warnings: list[dict[str, str]],
+ provenance: list[dict[str, str]],
+) -> dict[str, Any]:
+ devices: list[dict[str, Any]] = []
+
+ nvidia = run_command(NVIDIA_QUERY, timeout=4.0)
+ nvidia_devices = parse_nvidia_csv(nvidia.get("stdout", "")) if nvidia["status"] == "ok" else []
+ if nvidia["status"] == "error":
+ fallback = run_command(NVIDIA_QUERY_FALLBACK, timeout=4.0)
+ if fallback["status"] == "ok":
+ nvidia = fallback
+ nvidia_devices = parse_nvidia_csv(fallback.get("stdout", ""))
+ if nvidia["status"] == "ok":
+ _provenance(provenance, "accelerators.nvidia", "nvidia-smi", "ok")
+ if nvidia.get("stdout", "").strip() and not nvidia_devices:
+ _warning(
+ warnings,
+ "NVIDIA_OUTPUT_PARSE_FAILED",
+ "accelerators",
+ "nvidia-smi returned an unexpected bounded CSV response.",
+ )
else:
- recommendations["parallel_processing"]["strategy"] = "sequential"
- recommendations["parallel_processing"]["note"] = "Limited cores, prefer sequential processing"
-
- # Memory recommendations
- available_memory_gb = resources["memory"]["available_gb"]
- total_memory_gb = resources["memory"]["total_gb"]
-
- if available_memory_gb < 4:
- recommendations["memory_strategy"]["strategy"] = "memory_constrained"
- recommendations["memory_strategy"]["libraries"] = ["zarr", "dask", "h5py"]
- recommendations["memory_strategy"]["note"] = "Use out-of-core processing for large datasets"
- elif available_memory_gb < 16:
- recommendations["memory_strategy"]["strategy"] = "moderate_memory"
- recommendations["memory_strategy"]["libraries"] = ["dask", "zarr"]
- recommendations["memory_strategy"]["note"] = "Consider chunking for datasets > 2GB"
+ _record_probe_failure(
+ nvidia,
+ code="NVIDIA_QUERY_FAILED",
+ component="accelerators.nvidia",
+ tool="nvidia-smi",
+ warnings=warnings,
+ provenance=provenance,
+ )
+ devices.extend(nvidia_devices)
+
+ amd = run_command(AMD_SMI_QUERY, timeout=4.0)
+ amd_devices = parse_amd_json(amd.get("stdout", "")) if amd["status"] == "ok" else []
+ amd_tool = "amd-smi"
+ if not amd_devices and amd["status"] in {"not_found", "error", "start_error"}:
+ amd = run_command(ROCM_SMI_QUERY, timeout=4.0)
+ amd_tool = "rocm-smi"
+ amd_devices = parse_amd_json(amd.get("stdout", "")) if amd["status"] == "ok" else []
+ if amd["status"] == "ok":
+ _provenance(provenance, "accelerators.amd", amd_tool, "ok")
+ if amd.get("stdout", "").strip() and not amd_devices:
+ _warning(
+ warnings,
+ "AMD_OUTPUT_PARSE_FAILED",
+ "accelerators",
+ f"{amd_tool} returned an unexpected bounded JSON response.",
+ )
else:
- recommendations["memory_strategy"]["strategy"] = "memory_abundant"
- recommendations["memory_strategy"]["note"] = "Can load most datasets into memory"
-
- # GPU recommendations
- gpu_info = resources["gpu"]
- if gpu_info["total_gpus"] > 0:
- recommendations["gpu_acceleration"]["available"] = True
- recommendations["gpu_acceleration"]["backends"] = gpu_info["available_backends"]
-
- if "CUDA" in gpu_info["available_backends"]:
- recommendations["gpu_acceleration"]["suggested_libraries"] = [
- "pytorch", "tensorflow", "jax", "cupy", "rapids"
- ]
- elif "Metal" in gpu_info["available_backends"]:
- recommendations["gpu_acceleration"]["suggested_libraries"] = [
- "pytorch-mps", "tensorflow-metal", "jax-metal"
- ]
- elif "ROCm" in gpu_info["available_backends"]:
- recommendations["gpu_acceleration"]["suggested_libraries"] = [
- "pytorch-rocm", "tensorflow-rocm"
+ _record_probe_failure(
+ amd,
+ code="AMD_QUERY_FAILED",
+ component="accelerators.amd",
+ tool=amd_tool,
+ warnings=warnings,
+ provenance=provenance,
+ )
+ devices.extend(amd_devices)
+
+ if system == "Darwin":
+ apple = run_command(APPLE_DISPLAY_QUERY, timeout=5.0)
+ apple_devices = (
+ parse_apple_profiler_json(apple.get("stdout", ""), machine=machine)
+ if apple["status"] == "ok"
+ else []
+ )
+ if apple["status"] == "ok":
+ _provenance(
+ provenance, "accelerators.apple", "system_profiler", "ok"
+ )
+ else:
+ _record_probe_failure(
+ apple,
+ code="APPLE_ACCELERATOR_QUERY_FAILED",
+ component="accelerators.apple",
+ tool="system_profiler",
+ warnings=warnings,
+ provenance=provenance,
+ )
+ if (
+ not apple_devices
+ and machine.lower() in {"arm64", "aarch64"}
+ ):
+ apple_devices = [
+ {
+ "backend_candidate": "metal",
+ "compute_capability": None,
+ "device_class": "integrated_gpu",
+ "device_permission": "not_tested",
+ "driver_version": None,
+ "gpu_cores": None,
+ "local_index": 0,
+ "management_query": "inferred_from_apple_silicon_platform",
+ "memory": {
+ "dedicated_free_bytes": None,
+ "dedicated_total_bytes": None,
+ "model": "unified",
+ },
+ "name": "Apple silicon integrated GPU",
+ "runtime_compatibility": "not_tested",
+ "vendor": "apple",
+ }
]
- else:
- recommendations["gpu_acceleration"]["available"] = False
- recommendations["gpu_acceleration"]["note"] = "No GPU detected, use CPU-based libraries"
-
- # Large data handling recommendations
- disk_available_gb = resources["disk"]["available_gb"]
- if disk_available_gb < 10:
- recommendations["large_data_handling"]["strategy"] = "disk_constrained"
- recommendations["large_data_handling"]["note"] = "Limited disk space, use streaming or compression"
- elif disk_available_gb < 100:
- recommendations["large_data_handling"]["strategy"] = "moderate_disk"
- recommendations["large_data_handling"]["libraries"] = ["zarr", "h5py", "parquet"]
- else:
- recommendations["large_data_handling"]["strategy"] = "disk_abundant"
- recommendations["large_data_handling"]["note"] = "Sufficient space for large intermediate files"
+ devices.extend(apple_devices)
+
+ devices.sort(
+ key=lambda item: (
+ str(item.get("backend_candidate")),
+ int(item.get("local_index", 0)),
+ str(item.get("name")),
+ )
+ )
+ if len(devices) > MAX_DEVICES:
+ devices = devices[:MAX_DEVICES]
+ _warning(
+ warnings,
+ "ACCELERATOR_DEVICE_LIST_BOUNDED",
+ "accelerators",
+ f"Accelerator output was limited to {MAX_DEVICES} devices.",
+ )
+ visibility = _visibility_summary(environ)
+ if devices:
+ _warning(
+ warnings,
+ "ACCELERATOR_RUNTIME_NOT_TESTED",
+ "accelerators",
+ "Management visibility does not prove permission or framework/runtime compatibility.",
+ severity="info",
+ )
+ counts = {
+ backend: sum(
+ 1 for device in devices if device.get("backend_candidate") == backend
+ )
+ for backend in ("cuda", "metal", "rocm")
+ }
+ return {
+ "candidate_counts": counts,
+ "candidate_upper_bounds": _accelerator_upper_bounds(
+ devices, visibility, scheduler
+ ),
+ "devices": devices,
+ "runtime_usable_devices": None,
+ "visibility_environment": visibility,
+ }
+
+
+def _container_context(
+ *,
+ cgroup: Mapping[str, Any],
+ exists: Callable[[Path], bool] = Path.exists,
+) -> dict[str, Any]:
+ evidence: list[str] = []
+ for marker, label in (
+ (Path("/.dockerenv"), "docker_marker"),
+ (Path("/run/.containerenv"), "containerenv_marker"),
+ ):
+ try:
+ if exists(marker):
+ evidence.append(label)
+ except OSError:
+ pass
+ if cgroup.get("detected") and any(
+ cgroup.get(key) is not None
+ for key in ("cpu_quota_cores", "cpuset_logical", "memory_max_bytes")
+ ):
+ evidence.append("cgroup_limit")
+ return {
+ "detected": bool(
+ {"docker_marker", "containerenv_marker"}.intersection(evidence)
+ ),
+ "evidence": sorted(evidence),
+ "runtime": (
+ "docker_or_compatible"
+ if "docker_marker" in evidence
+ else "oci_compatible"
+ if "containerenv_marker" in evidence
+ else None
+ ),
+ }
- return recommendations
+def _observed_at() -> str:
+ return (
+ dt.datetime.now(dt.timezone.utc)
+ .replace(microsecond=0)
+ .isoformat()
+ .replace("+00:00", "Z")
+ )
-def main():
- """Main entry point for CLI usage."""
- import argparse
- parser = argparse.ArgumentParser(
- description="Detect system resources for scientific computing"
+def collect_snapshot(
+ *,
+ skip_accelerators: bool = False,
+ observed_at: str | None = None,
+ environ: Mapping[str, str] | None = None,
+ psutil_module: Any = _AUTO,
+ read_text: Callable[[Path], str] = _read_bounded_text,
+ run_command: Callable[..., dict[str, Any]] = _run_bounded_command,
+) -> dict[str, Any]:
+ """Collect one snapshot; individual probe failures remain warnings."""
+ warnings: list[dict[str, str]] = []
+ provenance: list[dict[str, str]] = []
+ environment = os.environ if environ is None else environ
+ system = _safe_text(platform.system(), 64) or "Unknown"
+ machine = _safe_text(platform.machine(), 64) or "unknown"
+
+ if psutil_module is _AUTO:
+ psutil_module = _load_psutil(warnings, provenance)
+ elif psutil_module is None:
+ _provenance(provenance, "inventory.psutil", "injected", "unavailable")
+
+ mac_sysctl: dict[str, Any] = {}
+ if system == "Darwin":
+ mac_sysctl = _mac_sysctl_values(run_command, warnings, provenance)
+ host_cpu = _detect_cpu_inventory(
+ system=system,
+ psutil_module=psutil_module,
+ mac_sysctl=mac_sysctl,
+ read_text=read_text,
+ warnings=warnings,
+ provenance=provenance,
)
- parser.add_argument(
- "-o", "--output",
- default=".claude_resources.json",
- help="Output JSON file path (default: .claude_resources.json)"
+ process_cpu = _detect_process_cpu_count(
+ psutil_module=psutil_module,
+ warnings=warnings,
+ provenance=provenance,
)
- parser.add_argument(
- "-v", "--verbose",
- action="store_true",
- help="Print resources to stdout"
+ cgroup = (
+ detect_cgroup_v2(
+ read_text=read_text,
+ warnings=warnings,
+ provenance=provenance,
+ )
+ if system == "Linux"
+ else {
+ "detected": False,
+ "cpu_quota_cores": None,
+ "cpuset_logical": None,
+ "memory_available_bytes": None,
+ "memory_current_bytes": None,
+ "memory_high_bytes": None,
+ "memory_max_bytes": None,
+ "scope": "not_applicable",
+ }
+ )
+ scheduler = detect_scheduler(
+ environment,
+ warnings=warnings,
+ provenance=provenance,
)
+ cpu = {
+ "cgroup_v2": {
+ "cpuset_logical": cgroup.get("cpuset_logical"),
+ "quota_cores": cgroup.get("cpu_quota_cores"),
+ },
+ "effective": _effective_cpu(host_cpu, process_cpu, cgroup, scheduler),
+ "host": host_cpu,
+ "process": process_cpu,
+ }
+ memory = _detect_memory(
+ system=system,
+ machine=machine,
+ psutil_module=psutil_module,
+ mac_sysctl=mac_sysctl,
+ cgroup=cgroup,
+ scheduler=scheduler,
+ read_text=read_text,
+ warnings=warnings,
+ provenance=provenance,
+ )
+ if skip_accelerators:
+ accelerators = {
+ "candidate_counts": {"cuda": 0, "metal": 0, "rocm": 0},
+ "candidate_upper_bounds": {
+ "cuda": None,
+ "metal": None,
+ "rocm": None,
+ },
+ "devices": [],
+ "runtime_usable_devices": None,
+ "visibility_environment": _visibility_summary(environment),
+ }
+ _provenance(provenance, "accelerators", "user_option", "skipped")
+ else:
+ accelerators = _detect_accelerators(
+ system=system,
+ machine=machine,
+ environ=environment,
+ scheduler=scheduler,
+ run_command=run_command,
+ warnings=warnings,
+ provenance=provenance,
+ )
- args = parser.parse_args()
+ disk = _detect_disk(warnings, provenance)
+ warnings.sort(
+ key=lambda item: (
+ item["component"],
+ item["code"],
+ item["message"],
+ )
+ )
+ provenance.sort(
+ key=lambda item: (item["component"], item["source"], item["status"])
+ )
+ completeness = (
+ "partial"
+ if any(item["severity"] == "warning" for item in warnings)
+ else "complete_with_informational_notes"
+ if warnings
+ else "complete"
+ )
+ return {
+ "accelerators": accelerators,
+ "cgroup_v2": {
+ "detected": cgroup.get("detected"),
+ "scope": cgroup.get("scope"),
+ },
+ "completeness": completeness,
+ "container": _container_context(cgroup=cgroup),
+ "cpu": cpu,
+ "disk": disk,
+ "memory": memory,
+ "observed_at": observed_at or _observed_at(),
+ "platform": {
+ "machine": machine,
+ "python_version": _safe_text(platform.python_version(), 64) or "unknown",
+ "system": system,
+ },
+ "privacy": {
+ "absolute_paths_included": False,
+ "environment_values_included": False,
+ "hostnames_included": False,
+ "identifiers_redacted_by_default": True,
+ },
+ "provenance": provenance,
+ "scheduler": scheduler,
+ "schema_version": SCHEMA_VERSION,
+ "snapshot_kind": "effective_resource_snapshot",
+ "warnings": warnings,
+ }
- print("🔍 Detecting system resources...")
- resources = detect_all_resources(args.output)
- print(f"✅ Resources detected and saved to: {args.output}")
+def detect_all_resources(output_path: str | None = None) -> dict[str, Any]:
+ """Compatibility API: collect a snapshot and optionally write it safely."""
+ snapshot = collect_snapshot()
+ if output_path is not None:
+ emit_json(snapshot, output_path)
+ return snapshot
- if args.verbose:
- print("\n" + "="*60)
- print(json.dumps(resources, indent=2))
- print("="*60)
- # Print summary
- print("\n📊 Resource Summary:")
- print(f" OS: {resources['os']['system']} {resources['os']['release']}")
- print(f" CPU: {resources['cpu']['logical_cores']} cores ({resources['cpu']['physical_cores']} physical)")
- print(f" Memory: {resources['memory']['total_gb']} GB total, {resources['memory']['available_gb']} GB available")
- print(f" Disk: {resources['disk']['total_gb']} GB total, {resources['disk']['available_gb']} GB available")
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Report host inventory and effective process limits as deterministic JSON"
+ )
+ )
+ parser.add_argument(
+ "--output",
+ metavar="FILE.json",
+ help=(
+ "write a private JSON file in the current directory; default: stdout"
+ ),
+ )
+ parser.add_argument(
+ "--force",
+ action="store_true",
+ help="replace an existing explicit output file",
+ )
+ parser.add_argument(
+ "--skip-accelerators",
+ action="store_true",
+ help="skip bounded accelerator management queries",
+ )
+ return parser
- if resources['gpu']['total_gpus'] > 0:
- print(f" GPU: {resources['gpu']['total_gpus']} detected ({', '.join(resources['gpu']['available_backends'])})")
- else:
- print(" GPU: None detected")
- print("\n💡 Recommendations:")
- recs = resources['recommendations']
- print(f" Parallel Processing: {recs['parallel_processing'].get('strategy', 'N/A')}")
- print(f" Memory Strategy: {recs['memory_strategy'].get('strategy', 'N/A')}")
- print(f" GPU Acceleration: {'Available' if recs['gpu_acceleration'].get('available') else 'Not Available'}")
+def main(argv: Sequence[str] | None = None) -> int:
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ if args.force and not args.output:
+ parser.error("--force requires --output")
+ try:
+ snapshot = collect_snapshot(skip_accelerators=args.skip_accelerators)
+ emit_json(snapshot, args.output, force=args.force)
+ except ResourceToolError as exc:
+ return cli_error(parser, exc)
+ return 0
if __name__ == "__main__":
- main()
+ raise SystemExit(main())
diff --git a/skills/get-available-resources/scripts/plan_workload.py b/skills/get-available-resources/scripts/plan_workload.py
new file mode 100644
index 00000000..17288a62
--- /dev/null
+++ b/skills/get-available-resources/scripts/plan_workload.py
@@ -0,0 +1,311 @@
+#!/usr/bin/env python3
+"""Build a conservative worker and memory plan from a validated snapshot."""
+
+from __future__ import annotations
+
+import argparse
+import math
+from typing import Any, Mapping, Sequence
+
+from _common import (
+ MAX_BYTES,
+ MAX_TASKS,
+ MAX_WORKERS,
+ SCHEMA_VERSION,
+ ResourceToolError,
+ argparse_nonnegative_int,
+ argparse_positive_int,
+ bounded_number,
+ cli_error,
+ emit_json,
+ read_json_file,
+)
+from snapshot_tools import validate_snapshot
+
+MIB = 1024**2
+
+
+def _optional_number(value: Any) -> float | None:
+ return bounded_number(value, maximum=float(MAX_BYTES))
+
+
+def _accelerator_decision(
+ snapshot: Mapping[str, Any],
+ requested: str,
+) -> dict[str, Any]:
+ if requested == "none":
+ return {
+ "candidate_count_upper_bound": 0,
+ "requested": "none",
+ "status": "not_requested",
+ }
+ accelerators = snapshot["accelerators"]
+ bounds = accelerators.get("candidate_upper_bounds", {})
+ counts = accelerators.get("candidate_counts", {})
+ if requested == "any":
+ candidates = [
+ value
+ for backend, value in bounds.items()
+ if backend in {"cuda", "metal", "rocm"} and isinstance(value, int)
+ ]
+ query_count = sum(
+ value
+ for backend, value in counts.items()
+ if backend in {"cuda", "metal", "rocm"} and isinstance(value, int)
+ )
+ upper_bound = sum(candidates) if candidates else None
+ else:
+ query_count = counts.get(requested, 0)
+ upper_bound = bounds.get(requested)
+ if not query_count:
+ status = "no_management_visible_candidate"
+ elif upper_bound == 0:
+ status = "restricted_by_allocation_or_visibility"
+ else:
+ status = "diagnostic_required"
+ return {
+ "candidate_count_upper_bound": upper_bound,
+ "management_query_count": query_count,
+ "requested": requested,
+ "status": status,
+ "usability": "not_verified",
+ }
+
+
+def build_plan(
+ snapshot: Mapping[str, Any],
+ *,
+ workload: str = "cpu",
+ task_count: int | None = None,
+ requested_workers: int | None = None,
+ memory_per_worker_mib: int | None = None,
+ reserve_memory_mib: int | None = None,
+ accelerator: str = "none",
+) -> dict[str, Any]:
+ """Return a bounded deterministic plan without executing work."""
+ validation = validate_snapshot(snapshot)
+ if not validation["valid"]:
+ raise ResourceToolError("snapshot does not satisfy schema 1.1")
+ if workload not in {"cpu", "io", "mixed"}:
+ raise ResourceToolError("workload must be cpu, io, or mixed")
+ if accelerator not in {"none", "any", "cuda", "metal", "rocm"}:
+ raise ResourceToolError(
+ "accelerator must be none, any, cuda, metal, or rocm"
+ )
+ for label, value, maximum in (
+ ("task_count", task_count, MAX_TASKS),
+ ("requested_workers", requested_workers, MAX_WORKERS),
+ ("memory_per_worker_mib", memory_per_worker_mib, 1_048_576),
+ ):
+ if value is not None and (
+ isinstance(value, bool)
+ or not isinstance(value, int)
+ or not 1 <= value <= maximum
+ ):
+ raise ResourceToolError(f"{label} is outside its safe range")
+ if reserve_memory_mib is not None and (
+ isinstance(reserve_memory_mib, bool)
+ or not isinstance(reserve_memory_mib, int)
+ or not 0 <= reserve_memory_mib <= 1_048_576
+ ):
+ raise ResourceToolError("reserve_memory_mib is outside its safe range")
+
+ effective_cpu = snapshot["cpu"]["effective"]
+ cpu_capacity = _optional_number(effective_cpu.get("capacity_cores"))
+ cpu_ceiling = effective_cpu.get("worker_ceiling", 1)
+ if not isinstance(cpu_ceiling, int):
+ cpu_ceiling = 1
+ cpu_ceiling = max(1, min(MAX_WORKERS, cpu_ceiling))
+ if workload == "io":
+ workload_ceiling = min(MAX_WORKERS, 32, max(2, cpu_ceiling * 2))
+ else:
+ workload_ceiling = cpu_ceiling
+
+ available_memory = _optional_number(
+ snapshot["memory"]["effective"].get("available_bytes")
+ )
+ if reserve_memory_mib is None and available_memory is not None:
+ reserve_bytes = min(
+ int(available_memory * 0.5),
+ max(256 * MIB, int(available_memory * 0.1)),
+ )
+ elif reserve_memory_mib is not None:
+ reserve_bytes = reserve_memory_mib * MIB
+ else:
+ reserve_bytes = None
+
+ memory_ceiling: int | None = None
+ planner_warnings: list[dict[str, str]] = []
+ if memory_per_worker_mib is not None:
+ per_worker_bytes = memory_per_worker_mib * MIB
+ if available_memory is None or reserve_bytes is None:
+ memory_ceiling = 1
+ planner_warnings.append(
+ {
+ "code": "MEMORY_UNKNOWN",
+ "message": (
+ "Memory per worker was supplied but effective available "
+ "memory is unknown; one worker is recommended."
+ ),
+ }
+ )
+ else:
+ usable = max(0, int(available_memory) - reserve_bytes)
+ memory_ceiling = max(1, min(MAX_WORKERS, usable // per_worker_bytes))
+ if usable < per_worker_bytes:
+ planner_warnings.append(
+ {
+ "code": "MEMORY_REQUIREMENT_EXCEEDS_BUDGET",
+ "message": (
+ "One worker may exceed the post-reserve memory budget; "
+ "use chunking or out-of-core processing."
+ ),
+ }
+ )
+
+ ceilings: list[tuple[str, int]] = [("workload_cpu", workload_ceiling)]
+ if memory_ceiling is not None:
+ ceilings.append(("memory", memory_ceiling))
+ if task_count is not None:
+ ceilings.append(("tasks", min(task_count, MAX_WORKERS)))
+ if requested_workers is not None:
+ ceilings.append(("user_request", requested_workers))
+ suggested = max(1, min(value for _, value in ceilings))
+ binding = sorted(source for source, value in ceilings if value == suggested)
+
+ if workload == "io":
+ planner_warnings.append(
+ {
+ "code": "IO_OVERSUBSCRIPTION_HEURISTIC",
+ "message": (
+ "The I/O worker count is a bounded heuristic; benchmark the "
+ "real workload without exceeding allocations."
+ ),
+ }
+ )
+ if snapshot["scheduler"].get("detected"):
+ planner_warnings.append(
+ {
+ "code": "SCHEDULER_SCOPE",
+ "message": (
+ "Remain inside the scheduler allocation even when host "
+ "inventory is larger."
+ ),
+ }
+ )
+ if cpu_capacity is None:
+ planner_warnings.append(
+ {
+ "code": "CPU_CAPACITY_UNKNOWN",
+ "message": "Effective CPU capacity is unknown; the plan remains conservative.",
+ }
+ )
+
+ threads_per_worker = 1
+ if workload in {"cpu", "mixed"} and cpu_capacity is not None:
+ threads_per_worker = max(1, math.floor(cpu_capacity / suggested))
+ planner_warnings.sort(key=lambda item: (item["code"], item["message"]))
+ return {
+ "accelerator": _accelerator_decision(snapshot, accelerator),
+ "inputs": {
+ "accelerator": accelerator,
+ "memory_per_worker_bytes": (
+ memory_per_worker_mib * MIB
+ if memory_per_worker_mib is not None
+ else None
+ ),
+ "requested_workers": requested_workers,
+ "reserve_memory_bytes": reserve_bytes,
+ "task_count": task_count,
+ "workload": workload,
+ },
+ "kind": "workload_plan",
+ "limits": {
+ "cpu_capacity_cores": cpu_capacity,
+ "cpu_worker_ceiling": cpu_ceiling,
+ "memory_worker_ceiling": memory_ceiling,
+ "workload_worker_ceiling": workload_ceiling,
+ },
+ "recommendation": {
+ "binding_limits": binding,
+ "suggested_workers": suggested,
+ "threads_per_worker": threads_per_worker,
+ },
+ "schema_version": SCHEMA_VERSION,
+ "warnings": planner_warnings,
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description="Plan bounded workers and memory from a resource snapshot"
+ )
+ parser.add_argument("snapshot", help="validated snapshot JSON file")
+ parser.add_argument(
+ "--workload",
+ choices=("cpu", "io", "mixed"),
+ default="cpu",
+ help="workload shape; default: cpu",
+ )
+ parser.add_argument(
+ "--tasks",
+ type=argparse_positive_int,
+ help="number of independent tasks",
+ )
+ parser.add_argument(
+ "--workers",
+ type=lambda value: argparse_positive_int(value, maximum=MAX_WORKERS),
+ help="explicit upper bound on workers",
+ )
+ parser.add_argument(
+ "--memory-per-worker-mib",
+ type=lambda value: argparse_positive_int(value, maximum=1_048_576),
+ help="estimated MiB required by each worker",
+ )
+ parser.add_argument(
+ "--reserve-memory-mib",
+ type=lambda value: argparse_nonnegative_int(value, maximum=1_048_576),
+ help="explicit MiB to keep outside the worker budget",
+ )
+ parser.add_argument(
+ "--accelerator",
+ choices=("none", "any", "cuda", "rocm", "metal"),
+ default="none",
+ help="request a candidate backend without assuming runtime usability",
+ )
+ parser.add_argument(
+ "--output",
+ metavar="FILE.json",
+ help="write a private local JSON file instead of stdout",
+ )
+ parser.add_argument(
+ "--force",
+ action="store_true",
+ help="replace an existing explicit output file",
+ )
+ return parser
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ if args.force and not args.output:
+ parser.error("--force requires --output")
+ try:
+ plan = build_plan(
+ read_json_file(args.snapshot),
+ workload=args.workload,
+ task_count=args.tasks,
+ requested_workers=args.workers,
+ memory_per_worker_mib=args.memory_per_worker_mib,
+ reserve_memory_mib=args.reserve_memory_mib,
+ accelerator=args.accelerator,
+ )
+ emit_json(plan, args.output, force=args.force)
+ except ResourceToolError as exc:
+ return cli_error(parser, exc)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/get-available-resources/scripts/snapshot_tools.py b/skills/get-available-resources/scripts/snapshot_tools.py
new file mode 100644
index 00000000..43f4da67
--- /dev/null
+++ b/skills/get-available-resources/scripts/snapshot_tools.py
@@ -0,0 +1,486 @@
+#!/usr/bin/env python3
+"""Validate or deterministically diff resource snapshots."""
+
+from __future__ import annotations
+
+import argparse
+import copy
+from typing import Any, Mapping, Sequence
+
+from _common import (
+ MAX_BYTES,
+ SCHEMA_VERSION,
+ ResourceToolError,
+ bounded_number,
+ cli_error,
+ emit_json,
+ read_json_file,
+)
+
+MAX_DIFFS = 512
+
+
+def _is_optional_nonnegative_number(value: Any) -> bool:
+ return value is None or bounded_number(value, maximum=float(MAX_BYTES)) is not None
+
+
+def _expect_mapping(
+ parent: Mapping[str, Any],
+ key: str,
+ path: str,
+ errors: list[dict[str, str]],
+) -> Mapping[str, Any]:
+ value = parent.get(key)
+ if not isinstance(value, dict):
+ errors.append(
+ {
+ "code": "TYPE",
+ "message": "must be an object",
+ "path": f"{path}.{key}",
+ }
+ )
+ return {}
+ return value
+
+
+def _check_optional_number(
+ parent: Mapping[str, Any],
+ key: str,
+ path: str,
+ errors: list[dict[str, str]],
+) -> None:
+ if not _is_optional_nonnegative_number(parent.get(key)):
+ errors.append(
+ {
+ "code": "NUMBER",
+ "message": "must be null or a finite nonnegative bounded number",
+ "path": f"{path}.{key}",
+ }
+ )
+
+
+def validate_snapshot(snapshot: Mapping[str, Any]) -> dict[str, Any]:
+ """Validate the stable 1.1 resource snapshot contract."""
+ errors: list[dict[str, str]] = []
+ notes: list[dict[str, str]] = []
+ if snapshot.get("schema_version") != SCHEMA_VERSION:
+ errors.append(
+ {
+ "code": "SCHEMA_VERSION",
+ "message": f"must equal {SCHEMA_VERSION}",
+ "path": "$.schema_version",
+ }
+ )
+ if snapshot.get("snapshot_kind") != "effective_resource_snapshot":
+ errors.append(
+ {
+ "code": "SNAPSHOT_KIND",
+ "message": "must equal effective_resource_snapshot",
+ "path": "$.snapshot_kind",
+ }
+ )
+ observed_at = snapshot.get("observed_at")
+ if not isinstance(observed_at, str) or not observed_at.endswith("Z"):
+ errors.append(
+ {
+ "code": "TIMESTAMP",
+ "message": "must be a UTC string ending in Z",
+ "path": "$.observed_at",
+ }
+ )
+
+ platform = _expect_mapping(snapshot, "platform", "$", errors)
+ for key in ("system", "machine", "python_version"):
+ if not isinstance(platform.get(key), str) or not platform.get(key):
+ errors.append(
+ {
+ "code": "PLATFORM",
+ "message": "must be a nonempty string",
+ "path": f"$.platform.{key}",
+ }
+ )
+
+ cpu = _expect_mapping(snapshot, "cpu", "$", errors)
+ host_cpu = _expect_mapping(cpu, "host", "$.cpu", errors)
+ process_cpu = _expect_mapping(cpu, "process", "$.cpu", errors)
+ cpu_cgroup = _expect_mapping(cpu, "cgroup_v2", "$.cpu", errors)
+ effective_cpu = _expect_mapping(cpu, "effective", "$.cpu", errors)
+ for key in ("logical", "physical"):
+ _check_optional_number(host_cpu, key, "$.cpu.host", errors)
+ for key in ("affinity_logical", "python_available_logical"):
+ _check_optional_number(process_cpu, key, "$.cpu.process", errors)
+ for key in ("cpuset_logical", "quota_cores"):
+ _check_optional_number(cpu_cgroup, key, "$.cpu.cgroup_v2", errors)
+ _check_optional_number(
+ effective_cpu, "capacity_cores", "$.cpu.effective", errors
+ )
+ worker_ceiling = effective_cpu.get("worker_ceiling")
+ if (
+ isinstance(worker_ceiling, bool)
+ or not isinstance(worker_ceiling, int)
+ or not 1 <= worker_ceiling <= 1024
+ ):
+ errors.append(
+ {
+ "code": "WORKER_CEILING",
+ "message": "must be an integer between 1 and 1024",
+ "path": "$.cpu.effective.worker_ceiling",
+ }
+ )
+ if not isinstance(effective_cpu.get("limiting_sources"), list):
+ errors.append(
+ {
+ "code": "LIMIT_SOURCES",
+ "message": "must be an array",
+ "path": "$.cpu.effective.limiting_sources",
+ }
+ )
+
+ memory = _expect_mapping(snapshot, "memory", "$", errors)
+ host_memory = _expect_mapping(memory, "host", "$.memory", errors)
+ effective_memory = _expect_mapping(memory, "effective", "$.memory", errors)
+ memory_cgroup = _expect_mapping(memory, "cgroup_v2", "$.memory", errors)
+ swap = _expect_mapping(memory, "swap", "$.memory", errors)
+ for key in ("available_bytes", "total_bytes"):
+ _check_optional_number(host_memory, key, "$.memory.host", errors)
+ for key in (
+ "available_bytes",
+ "hard_limit_bytes",
+ "pressure_threshold_bytes",
+ ):
+ _check_optional_number(effective_memory, key, "$.memory.effective", errors)
+ for key in ("available_bytes", "current_bytes", "high_bytes", "max_bytes"):
+ _check_optional_number(memory_cgroup, key, "$.memory.cgroup_v2", errors)
+ for key in ("free_bytes", "total_bytes"):
+ _check_optional_number(swap, key, "$.memory.swap", errors)
+ available = effective_memory.get("available_bytes")
+ hard_limit = effective_memory.get("hard_limit_bytes")
+ if (
+ isinstance(available, (int, float))
+ and not isinstance(available, bool)
+ and isinstance(hard_limit, (int, float))
+ and not isinstance(hard_limit, bool)
+ and available > hard_limit
+ ):
+ errors.append(
+ {
+ "code": "MEMORY_ORDER",
+ "message": "available memory cannot exceed the effective hard limit",
+ "path": "$.memory.effective.available_bytes",
+ }
+ )
+
+ disk = _expect_mapping(snapshot, "disk", "$", errors)
+ for key in ("capacity_bytes", "free_bytes", "user_available_bytes"):
+ _check_optional_number(disk, key, "$.disk", errors)
+ if disk.get("writable") is not None and not isinstance(
+ disk.get("writable"), bool
+ ):
+ errors.append(
+ {
+ "code": "DISK_WRITABLE",
+ "message": "must be boolean or null",
+ "path": "$.disk.writable",
+ }
+ )
+ free = disk.get("free_bytes")
+ user_available = disk.get("user_available_bytes")
+ capacity = disk.get("capacity_bytes")
+ if all(
+ isinstance(value, (int, float)) and not isinstance(value, bool)
+ for value in (free, user_available, capacity)
+ ):
+ if not 0 <= user_available <= free <= capacity:
+ errors.append(
+ {
+ "code": "DISK_ORDER",
+ "message": "expected user_available <= free <= capacity",
+ "path": "$.disk",
+ }
+ )
+
+ accelerators = _expect_mapping(snapshot, "accelerators", "$", errors)
+ devices = accelerators.get("devices")
+ if not isinstance(devices, list) or len(devices) > 256:
+ errors.append(
+ {
+ "code": "ACCELERATOR_DEVICES",
+ "message": "must be an array with at most 256 entries",
+ "path": "$.accelerators.devices",
+ }
+ )
+ else:
+ for index, device in enumerate(devices):
+ if not isinstance(device, dict):
+ errors.append(
+ {
+ "code": "ACCELERATOR_DEVICE",
+ "message": "must be an object",
+ "path": f"$.accelerators.devices[{index}]",
+ }
+ )
+ continue
+ if device.get("backend_candidate") not in {"cuda", "metal", "rocm"}:
+ errors.append(
+ {
+ "code": "ACCELERATOR_BACKEND",
+ "message": "must be cuda, metal, or rocm",
+ "path": (
+ f"$.accelerators.devices[{index}].backend_candidate"
+ ),
+ }
+ )
+ if device.get("device_permission") != "not_tested":
+ notes.append(
+ {
+ "code": "PERMISSION_ASSERTION",
+ "message": (
+ "device permission differs from the detector's "
+ "conservative not_tested default"
+ ),
+ "path": (
+ f"$.accelerators.devices[{index}].device_permission"
+ ),
+ }
+ )
+ if device.get("runtime_compatibility") != "not_tested":
+ notes.append(
+ {
+ "code": "RUNTIME_ASSERTION",
+ "message": (
+ "runtime compatibility differs from the detector's "
+ "conservative not_tested default"
+ ),
+ "path": (
+ f"$.accelerators.devices[{index}].runtime_compatibility"
+ ),
+ }
+ )
+
+ scheduler = _expect_mapping(snapshot, "scheduler", "$", errors)
+ if not isinstance(scheduler.get("fields_read"), list):
+ errors.append(
+ {
+ "code": "SCHEDULER_FIELDS",
+ "message": "must be an array",
+ "path": "$.scheduler.fields_read",
+ }
+ )
+ privacy = _expect_mapping(snapshot, "privacy", "$", errors)
+ for key in (
+ "absolute_paths_included",
+ "environment_values_included",
+ "hostnames_included",
+ "identifiers_redacted_by_default",
+ ):
+ if not isinstance(privacy.get(key), bool):
+ errors.append(
+ {
+ "code": "PRIVACY",
+ "message": "must be boolean",
+ "path": f"$.privacy.{key}",
+ }
+ )
+ if any(
+ privacy.get(key) is True
+ for key in (
+ "absolute_paths_included",
+ "environment_values_included",
+ "hostnames_included",
+ )
+ ):
+ notes.append(
+ {
+ "code": "PRIVACY_EXPANDED",
+ "message": "snapshot includes fields normally redacted",
+ "path": "$.privacy",
+ }
+ )
+
+ warning_items = snapshot.get("warnings")
+ if not isinstance(warning_items, list) or len(warning_items) > 512:
+ errors.append(
+ {
+ "code": "WARNINGS",
+ "message": "must be an array with at most 512 entries",
+ "path": "$.warnings",
+ }
+ )
+ provenance = snapshot.get("provenance")
+ if not isinstance(provenance, list) or len(provenance) > 512:
+ errors.append(
+ {
+ "code": "PROVENANCE",
+ "message": "must be an array with at most 512 entries",
+ "path": "$.provenance",
+ }
+ )
+
+ errors.sort(key=lambda item: (item["path"], item["code"], item["message"]))
+ notes.sort(key=lambda item: (item["path"], item["code"], item["message"]))
+ return {
+ "errors": errors,
+ "kind": "snapshot_validation",
+ "notes": notes,
+ "schema_version": SCHEMA_VERSION,
+ "valid": not errors,
+ }
+
+
+def _strip_volatile(snapshot: Mapping[str, Any]) -> dict[str, Any]:
+ cleaned = copy.deepcopy(dict(snapshot))
+ cleaned.pop("observed_at", None)
+ return cleaned
+
+
+def _diff_values(
+ before: Any,
+ after: Any,
+ path: str,
+ changes: list[dict[str, Any]],
+) -> None:
+ if len(changes) >= MAX_DIFFS:
+ return
+ if isinstance(before, dict) and isinstance(after, dict):
+ for key in sorted(set(before) | set(after)):
+ child_path = f"{path}.{key}"
+ if key not in before:
+ changes.append(
+ {
+ "after": after[key],
+ "before": None,
+ "change": "added",
+ "path": child_path,
+ }
+ )
+ elif key not in after:
+ changes.append(
+ {
+ "after": None,
+ "before": before[key],
+ "change": "removed",
+ "path": child_path,
+ }
+ )
+ else:
+ _diff_values(before[key], after[key], child_path, changes)
+ if len(changes) >= MAX_DIFFS:
+ return
+ return
+ if isinstance(before, list) and isinstance(after, list):
+ maximum = max(len(before), len(after))
+ for index in range(maximum):
+ child_path = f"{path}[{index}]"
+ if index >= len(before):
+ changes.append(
+ {
+ "after": after[index],
+ "before": None,
+ "change": "added",
+ "path": child_path,
+ }
+ )
+ elif index >= len(after):
+ changes.append(
+ {
+ "after": None,
+ "before": before[index],
+ "change": "removed",
+ "path": child_path,
+ }
+ )
+ else:
+ _diff_values(before[index], after[index], child_path, changes)
+ if len(changes) >= MAX_DIFFS:
+ return
+ return
+ if before != after:
+ changes.append(
+ {
+ "after": after,
+ "before": before,
+ "change": "changed",
+ "path": path,
+ }
+ )
+
+
+def diff_snapshots(
+ before: Mapping[str, Any],
+ after: Mapping[str, Any],
+ *,
+ include_volatile: bool = False,
+) -> dict[str, Any]:
+ """Return a bounded, stable structural diff."""
+ before_validation = validate_snapshot(before)
+ after_validation = validate_snapshot(after)
+ if not before_validation["valid"] or not after_validation["valid"]:
+ raise ResourceToolError("both snapshots must validate before diffing")
+ try:
+ left = dict(before) if include_volatile else _strip_volatile(before)
+ right = dict(after) if include_volatile else _strip_volatile(after)
+ changes: list[dict[str, Any]] = []
+ _diff_values(left, right, "$", changes)
+ except RecursionError as exc:
+ raise ResourceToolError("snapshot nesting exceeds the diff safety bound") from exc
+ return {
+ "change_count": len(changes),
+ "changes": changes,
+ "ignored_paths": [] if include_volatile else ["$.observed_at"],
+ "kind": "snapshot_diff",
+ "schema_version": SCHEMA_VERSION,
+ "truncated": len(changes) >= MAX_DIFFS,
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description="Validate or structurally diff resource snapshot JSON"
+ )
+ parser.add_argument(
+ "--output",
+ metavar="FILE.json",
+ help="write a private local JSON file instead of stdout",
+ )
+ parser.add_argument(
+ "--force",
+ action="store_true",
+ help="replace an existing explicit output file",
+ )
+ commands = parser.add_subparsers(dest="command", required=True)
+ validate = commands.add_parser("validate", help="validate one snapshot")
+ validate.add_argument("snapshot", help="snapshot JSON file")
+ diff = commands.add_parser("diff", help="diff two valid snapshots")
+ diff.add_argument("before", help="earlier snapshot JSON file")
+ diff.add_argument("after", help="later snapshot JSON file")
+ diff.add_argument(
+ "--include-volatile",
+ action="store_true",
+ help="include observed_at in the diff",
+ )
+ return parser
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ if args.force and not args.output:
+ parser.error("--force requires --output")
+ try:
+ if args.command == "validate":
+ report = validate_snapshot(read_json_file(args.snapshot))
+ emit_json(report, args.output, force=args.force)
+ return 0 if report["valid"] else 1
+ report = diff_snapshots(
+ read_json_file(args.before),
+ read_json_file(args.after),
+ include_volatile=args.include_volatile,
+ )
+ emit_json(report, args.output, force=args.force)
+ return 0
+ except ResourceToolError as exc:
+ return cli_error(parser, exc)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/get-available-resources/tests/fixtures/resource_cases.json b/skills/get-available-resources/tests/fixtures/resource_cases.json
new file mode 100644
index 00000000..1f2f37a2
--- /dev/null
+++ b/skills/get-available-resources/tests/fixtures/resource_cases.json
@@ -0,0 +1,87 @@
+{
+ "amd_rocm_smi": {
+ "card0": {
+ "Card Series": "AMD Instinct MI250X",
+ "vram Total Memory (B)": "68702699520"
+ }
+ },
+ "linux_cgroup_v2": {
+ "expected": {
+ "cpu_quota_cores": 1.5,
+ "cpuset_logical": 2,
+ "memory_available_bytes": 1610612736,
+ "memory_current_bytes": 134217728,
+ "memory_high_bytes": 1610612736,
+ "memory_max_bytes": 2147483648,
+ "scope": "non_root"
+ },
+ "files": {
+ "/proc/self/cgroup": "0::/jobs/example/step\n",
+ "/sys/fs/cgroup/cgroup.controllers": "cpu cpuset memory pids\n",
+ "/sys/fs/cgroup/cpu.max": "max 100000\n",
+ "/sys/fs/cgroup/jobs/cpu.max": "150000 100000\n",
+ "/sys/fs/cgroup/jobs/example/cpu.max": "max 100000\n",
+ "/sys/fs/cgroup/jobs/example/step/cpu.max": "max 100000\n",
+ "/sys/fs/cgroup/jobs/example/step/cpuset.cpus.effective": "2-3\n",
+ "/sys/fs/cgroup/jobs/example/step/memory.current": "134217728\n",
+ "/sys/fs/cgroup/jobs/example/step/memory.high": "max\n",
+ "/sys/fs/cgroup/jobs/example/step/memory.max": "max\n",
+ "/sys/fs/cgroup/jobs/example/memory.current": "268435456\n",
+ "/sys/fs/cgroup/jobs/example/memory.high": "max\n",
+ "/sys/fs/cgroup/jobs/example/memory.max": "max\n",
+ "/sys/fs/cgroup/jobs/memory.current": "536870912\n",
+ "/sys/fs/cgroup/jobs/memory.high": "1610612736\n",
+ "/sys/fs/cgroup/jobs/memory.max": "2147483648\n",
+ "/sys/fs/cgroup/memory.current": "1073741824\n",
+ "/sys/fs/cgroup/memory.high": "max\n",
+ "/sys/fs/cgroup/memory.max": "max\n"
+ }
+ },
+ "macos": {
+ "profiler": {
+ "SPDisplaysDataType": [
+ {
+ "_name": "Apple M4 Pro",
+ "spdisplays_gpu_cores": "20",
+ "spdisplays_metal": "spdisplays_supported"
+ }
+ ]
+ },
+ "sysctl_stdout": "14\n14\n51539607552\nApple M4 Pro\n"
+ },
+ "nvidia_csv": "0, NVIDIA H100 80GB HBM3, 81559, 70000, 570.133.20, 9.0\n",
+ "slurm": {
+ "environment": {
+ "CUDA_VISIBLE_DEVICES": "2,5",
+ "SLURM_CPUS_ON_NODE": "16",
+ "SLURM_CPUS_PER_TASK": "4",
+ "SLURM_GPUS_ON_NODE": "2",
+ "SLURM_GPUS_PER_TASK": "1",
+ "SLURM_JOB_CPUS_PER_NODE": "16(x2)",
+ "SLURM_JOB_ID": "12345",
+ "SLURM_MEM_PER_CPU": "2G",
+ "SLURM_NTASKS": "8",
+ "SLURM_NTASKS_PER_NODE": "4"
+ },
+ "expected": {
+ "cpu_per_process": 4,
+ "cpus_on_node": 16,
+ "gpus_per_process": 1,
+ "gpus_on_node": 2,
+ "memory_effective_bytes": 8589934592,
+ "tasks": 8
+ }
+ },
+ "windows": {
+ "affinity": [
+ 0,
+ 1,
+ 2,
+ 3
+ ],
+ "host_logical": 128,
+ "host_physical": 64,
+ "memory_available": 34359738368,
+ "memory_total": 68719476736
+ }
+}
diff --git a/skills/get-available-resources/tests/test_scripts.py b/skills/get-available-resources/tests/test_scripts.py
new file mode 100644
index 00000000..4b1889ae
--- /dev/null
+++ b/skills/get-available-resources/tests/test_scripts.py
@@ -0,0 +1,514 @@
+"""Synthetic, network-free tests for resource detection and planning."""
+
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import os
+import stat
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest import mock
+
+SKILL_ROOT = Path(__file__).resolve().parents[1]
+SCRIPTS = SKILL_ROOT / "scripts"
+FIXTURES = Path(__file__).resolve().parent / "fixtures" / "resource_cases.json"
+sys.path.insert(0, str(SCRIPTS))
+
+import _common # noqa: E402
+import accelerator_diagnostics # noqa: E402
+import detect_resources # noqa: E402
+import plan_workload # noqa: E402
+import snapshot_tools # noqa: E402
+
+
+CASES = json.loads(FIXTURES.read_text(encoding="utf-8"))
+GIB = 1024**3
+
+
+def canonical_snapshot() -> dict:
+ return {
+ "accelerators": {
+ "candidate_counts": {"cuda": 1, "metal": 0, "rocm": 0},
+ "candidate_upper_bounds": {"cuda": 1, "metal": None, "rocm": None},
+ "devices": [
+ {
+ "backend_candidate": "cuda",
+ "device_class": "gpu",
+ "device_permission": "not_tested",
+ "local_index": 0,
+ "management_query": "visible",
+ "memory": {
+ "dedicated_free_bytes": 20 * GIB,
+ "dedicated_total_bytes": 40 * GIB,
+ "model": "dedicated",
+ },
+ "name": "Synthetic GPU",
+ "runtime_compatibility": "not_tested",
+ "vendor": "nvidia",
+ }
+ ],
+ "runtime_usable_devices": None,
+ "visibility_environment": {},
+ },
+ "cgroup_v2": {"detected": True, "scope": "non_root"},
+ "completeness": "complete_with_informational_notes",
+ "container": {
+ "detected": True,
+ "evidence": ["cgroup_limit", "docker_marker"],
+ "runtime": "docker_or_compatible",
+ },
+ "cpu": {
+ "cgroup_v2": {"cpuset_logical": 4, "quota_cores": 3.5},
+ "effective": {
+ "capacity_cores": 3.5,
+ "limiting_sources": ["cgroup_quota"],
+ "worker_ceiling": 3,
+ },
+ "host": {"logical": 32, "physical": 16},
+ "process": {
+ "affinity_logical": 4,
+ "python_available_logical": 4,
+ },
+ },
+ "disk": {
+ "capacity_bytes": 100 * GIB,
+ "free_bytes": 60 * GIB,
+ "scope": "working_filesystem_path_redacted",
+ "user_available_bytes": 50 * GIB,
+ "writable": True,
+ "writability_check": "os_access_only_no_write_probe",
+ },
+ "memory": {
+ "cgroup_v2": {
+ "available_bytes": 8 * GIB,
+ "current_bytes": 8 * GIB,
+ "high_bytes": 14 * GIB,
+ "max_bytes": 16 * GIB,
+ },
+ "effective": {
+ "available_bytes": 8 * GIB,
+ "available_limiting_sources": ["cgroup_memory_remaining"],
+ "hard_limit_bytes": 16 * GIB,
+ "hard_limit_sources": ["cgroup_memory_max"],
+ "pressure_threshold_bytes": 14 * GIB,
+ },
+ "host": {"available_bytes": 32 * GIB, "total_bytes": 64 * GIB},
+ "model": "system_ram",
+ "swap": {"free_bytes": 2 * GIB, "total_bytes": 4 * GIB},
+ },
+ "observed_at": "2026-07-23T12:00:00Z",
+ "platform": {
+ "machine": "x86_64",
+ "python_version": "3.13.5",
+ "system": "Linux",
+ },
+ "privacy": {
+ "absolute_paths_included": False,
+ "environment_values_included": False,
+ "hostnames_included": False,
+ "identifiers_redacted_by_default": True,
+ },
+ "provenance": [
+ {
+ "component": "cpu.host.logical",
+ "source": "os.cpu_count",
+ "status": "ok",
+ }
+ ],
+ "scheduler": {
+ "allocation": {
+ "cpu_per_process": 4,
+ "cpus_on_node": 4,
+ "gpus_per_process": 1,
+ "gpus_on_node": 1,
+ "memory_effective_bytes": 16 * GIB,
+ "memory_scope": "shared_per_node",
+ "tasks": 1,
+ },
+ "detected": True,
+ "enforcement": "unknown",
+ "fields_read": ["SLURM_CPUS_PER_TASK"],
+ "kind": "slurm",
+ },
+ "schema_version": "1.1",
+ "snapshot_kind": "effective_resource_snapshot",
+ "warnings": [
+ {
+ "code": "ACCELERATOR_RUNTIME_NOT_TESTED",
+ "component": "accelerators",
+ "message": "Synthetic informational warning.",
+ "severity": "info",
+ }
+ ],
+ }
+
+
+class CommonSafetyTests(unittest.TestCase):
+ def test_stdout_is_default_and_file_output_is_private(self) -> None:
+ captured = io.StringIO()
+ with contextlib.redirect_stdout(captured):
+ _common.emit_json({"ok": True})
+ self.assertEqual(json.loads(captured.getvalue()), {"ok": True})
+
+ old_cwd = Path.cwd()
+ try:
+ with tempfile.TemporaryDirectory() as directory:
+ os.chdir(directory)
+ _common.emit_json({"ok": True}, "resource-snapshot.json")
+ output = Path("resource-snapshot.json")
+ self.assertEqual(json.loads(output.read_text()), {"ok": True})
+ self.assertEqual(stat.S_IMODE(output.stat().st_mode), 0o600)
+ with self.assertRaises(_common.ResourceToolError):
+ _common.emit_json({"ok": False}, "resource-snapshot.json")
+ with self.assertRaises(_common.ResourceToolError):
+ _common.emit_json({"ok": False}, "../escape.json")
+ finally:
+ os.chdir(old_cwd)
+
+ def test_snapshot_reader_rejects_symlink(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ real = Path(directory) / "snapshot.json"
+ link = Path(directory) / "link.json"
+ real.write_text("{}", encoding="utf-8")
+ try:
+ link.symlink_to(real)
+ except OSError:
+ self.skipTest("symlinks unavailable")
+ with self.assertRaises(_common.ResourceToolError):
+ _common.read_json_file(str(link))
+
+
+class ParserTests(unittest.TestCase):
+ def test_cpu_list_is_counted_without_expansion(self) -> None:
+ self.assertEqual(detect_resources.parse_cpu_list("0-3,6,8-9"), 7)
+ self.assertEqual(detect_resources.parse_cpu_list("0-3,2-5"), 6)
+ self.assertIsNone(detect_resources.parse_cpu_list("0-99999999"))
+ self.assertIsNone(detect_resources.parse_cpu_list("0-3;echo unsafe"))
+
+ def test_nvidia_csv_is_typed_and_does_not_expose_uuid(self) -> None:
+ devices = detect_resources.parse_nvidia_csv(CASES["nvidia_csv"])
+ self.assertEqual(len(devices), 1)
+ self.assertEqual(devices[0]["backend_candidate"], "cuda")
+ self.assertEqual(devices[0]["compute_capability"], "9.0")
+ self.assertEqual(devices[0]["runtime_compatibility"], "not_tested")
+ self.assertNotIn("uuid", json.dumps(devices).lower())
+
+ def test_amd_and_apple_accelerators_are_not_cuda(self) -> None:
+ amd = detect_resources.parse_amd_json(
+ json.dumps(CASES["amd_rocm_smi"])
+ )
+ apple = detect_resources.parse_apple_profiler_json(
+ json.dumps(CASES["macos"]["profiler"]),
+ machine="arm64",
+ )
+ self.assertEqual(amd[0]["backend_candidate"], "rocm")
+ self.assertEqual(amd[0]["memory"]["dedicated_total_bytes"], 68702699520)
+ self.assertEqual(apple[0]["backend_candidate"], "metal")
+ self.assertEqual(apple[0]["memory"]["model"], "unified")
+ self.assertEqual(apple[0]["device_class"], "integrated_gpu")
+
+ def test_accelerator_probe_timeout_is_a_partial_warning(self) -> None:
+ def fake_run(command: tuple[str, ...], timeout: float) -> dict:
+ if command[0] == "nvidia-smi":
+ return {"status": "timeout", "stdout": "", "stderr": ""}
+ return {"status": "not_found", "stdout": "", "stderr": ""}
+
+ warnings: list[dict[str, str]] = []
+ provenance: list[dict[str, str]] = []
+ result = detect_resources._detect_accelerators(
+ system="Linux",
+ machine="x86_64",
+ environ={},
+ scheduler={"allocation": {}},
+ run_command=fake_run,
+ warnings=warnings,
+ provenance=provenance,
+ )
+ self.assertEqual(result["devices"], [])
+ self.assertIn(
+ "NVIDIA_QUERY_FAILED",
+ {item["code"] for item in warnings},
+ )
+ self.assertIn(
+ "timeout",
+ {item["status"] for item in provenance},
+ )
+
+
+class LinuxCgroupTests(unittest.TestCase):
+ def test_hierarchical_limits_use_most_restrictive_ancestor(self) -> None:
+ case = CASES["linux_cgroup_v2"]
+ files = case["files"]
+
+ def reader(path: Path) -> str:
+ try:
+ return files[str(path)]
+ except KeyError as exc:
+ raise FileNotFoundError(str(path)) from exc
+
+ report = detect_resources.detect_cgroup_v2(read_text=reader)
+ for key, expected in case["expected"].items():
+ self.assertEqual(report[key], expected, key)
+
+ def test_cpu_quota_is_capacity_not_a_topology_count(self) -> None:
+ effective = detect_resources._effective_cpu(
+ {"logical": 64, "physical": 32},
+ {"affinity_logical": 8, "python_available_logical": 8},
+ {"cpuset_logical": 4, "cpu_quota_cores": 1.5},
+ {"allocation": {"cpu_per_process": 2}},
+ )
+ self.assertEqual(effective["capacity_cores"], 1.5)
+ self.assertEqual(effective["worker_ceiling"], 1)
+ self.assertEqual(effective["limiting_sources"], ["cgroup_quota"])
+
+
+class SchedulerTests(unittest.TestCase):
+ def test_slurm_named_allocation_is_bounded_and_redacted(self) -> None:
+ environment = dict(CASES["slurm"]["environment"])
+ environment["UNRELATED_SECRET"] = "must-not-be-read"
+ warnings: list[dict[str, str]] = []
+ report = detect_resources.detect_scheduler(
+ environment,
+ warnings=warnings,
+ )
+ expected = CASES["slurm"]["expected"]
+ for key, value in expected.items():
+ self.assertEqual(report["allocation"][key], value, key)
+ serialized = json.dumps(report)
+ self.assertNotIn("12345", serialized)
+ self.assertNotIn("must-not-be-read", serialized)
+ self.assertNotIn("UNRELATED_SECRET", report["fields_read"])
+ self.assertEqual(report["enforcement"], "unknown")
+
+ def test_visibility_values_are_summarized_not_returned(self) -> None:
+ value = "GPU-private-uuid,GPU-other-private-uuid"
+ summary = detect_resources._visibility_summary(
+ {"CUDA_VISIBLE_DEVICES": value}
+ )
+ serialized = json.dumps(summary)
+ self.assertNotIn("GPU-private", serialized)
+ self.assertEqual(
+ summary["CUDA_VISIBLE_DEVICES"]["entry_count"],
+ 2,
+ )
+
+
+class PlatformMockTests(unittest.TestCase):
+ def test_macos_sysctl_and_unified_memory(self) -> None:
+ result = {
+ "status": "ok",
+ "stdout": CASES["macos"]["sysctl_stdout"],
+ "stderr": "",
+ }
+ values = detect_resources._mac_sysctl_values(
+ lambda command, timeout: result,
+ [],
+ [],
+ )
+ memory = detect_resources._detect_memory(
+ system="Darwin",
+ machine="arm64",
+ psutil_module=None,
+ mac_sysctl=values,
+ cgroup={
+ "memory_available_bytes": None,
+ "memory_current_bytes": None,
+ "memory_high_bytes": None,
+ "memory_max_bytes": None,
+ },
+ scheduler={"allocation": {"memory_effective_bytes": None}},
+ read_text=lambda path: (_ for _ in ()).throw(FileNotFoundError()),
+ warnings=[],
+ provenance=[],
+ )
+ self.assertEqual(values["logical"], 14)
+ self.assertEqual(values["physical"], 14)
+ self.assertEqual(memory["host"]["total_bytes"], 48 * GIB)
+ self.assertEqual(memory["model"], "unified_cpu_gpu")
+
+ def test_windows_psutil_affinity_and_processor_groups(self) -> None:
+ case = CASES["windows"]
+
+ class FakeProcess:
+ def cpu_affinity(self) -> list[int]:
+ return case["affinity"]
+
+ fake_psutil = SimpleNamespace(Process=FakeProcess)
+ provenance: list[dict[str, str]] = []
+ with mock.patch.object(
+ detect_resources.os,
+ "sched_getaffinity",
+ new=None,
+ create=True,
+ ), mock.patch.object(
+ detect_resources.os,
+ "process_cpu_count",
+ return_value=4,
+ create=True,
+ ):
+ process = detect_resources._detect_process_cpu_count(
+ psutil_module=fake_psutil,
+ warnings=[],
+ provenance=provenance,
+ )
+ self.assertEqual(process["affinity_logical"], 4)
+ self.assertEqual(process["python_available_logical"], 4)
+
+ def test_windows_psutil_memory_is_kept_separate_from_limits(self) -> None:
+ case = CASES["windows"]
+ fake_psutil = SimpleNamespace(
+ virtual_memory=lambda: SimpleNamespace(
+ total=case["memory_total"],
+ available=case["memory_available"],
+ ),
+ swap_memory=lambda: SimpleNamespace(total=8 * GIB, free=4 * GIB),
+ )
+ memory = detect_resources._detect_memory(
+ system="Windows",
+ machine="AMD64",
+ psutil_module=fake_psutil,
+ mac_sysctl={},
+ cgroup={
+ "memory_available_bytes": None,
+ "memory_current_bytes": None,
+ "memory_high_bytes": None,
+ "memory_max_bytes": None,
+ },
+ scheduler={
+ "allocation": {"memory_effective_bytes": 16 * GIB}
+ },
+ read_text=lambda path: (_ for _ in ()).throw(FileNotFoundError()),
+ warnings=[],
+ provenance=[],
+ )
+ self.assertEqual(memory["host"]["total_bytes"], 64 * GIB)
+ self.assertEqual(memory["host"]["available_bytes"], 32 * GIB)
+ self.assertEqual(memory["effective"]["hard_limit_bytes"], 16 * GIB)
+ self.assertEqual(memory["effective"]["available_bytes"], 16 * GIB)
+
+ def test_linux_partial_failure_still_returns_valid_snapshot(self) -> None:
+ meminfo = (
+ "MemTotal: 16777216 kB\n"
+ "MemAvailable: 8388608 kB\n"
+ "SwapTotal: 2097152 kB\n"
+ "SwapFree: 1048576 kB\n"
+ )
+
+ def reader(path: Path) -> str:
+ if str(path) == "/proc/meminfo":
+ return meminfo
+ raise FileNotFoundError(str(path))
+
+ with mock.patch.object(
+ detect_resources.platform, "system", return_value="Linux"
+ ), mock.patch.object(
+ detect_resources.platform, "machine", return_value="x86_64"
+ ), mock.patch.object(
+ detect_resources.platform, "python_version", return_value="3.13.5"
+ ), mock.patch.object(
+ detect_resources.os, "cpu_count", return_value=8
+ ), mock.patch.object(
+ detect_resources.os,
+ "sched_getaffinity",
+ return_value={0, 1},
+ create=True,
+ ), mock.patch.object(
+ detect_resources.shutil,
+ "disk_usage",
+ return_value=SimpleNamespace(
+ total=100 * GIB,
+ used=40 * GIB,
+ free=60 * GIB,
+ ),
+ ), mock.patch.object(
+ detect_resources.os,
+ "statvfs",
+ return_value=SimpleNamespace(f_bavail=50, f_frsize=GIB),
+ create=True,
+ ):
+ snapshot = detect_resources.collect_snapshot(
+ skip_accelerators=True,
+ observed_at="2026-07-23T12:00:00Z",
+ environ={},
+ psutil_module=None,
+ read_text=reader,
+ )
+ validation = snapshot_tools.validate_snapshot(snapshot)
+ self.assertTrue(validation["valid"], validation["errors"])
+ self.assertEqual(snapshot["cpu"]["effective"]["capacity_cores"], 2.0)
+ self.assertEqual(snapshot["memory"]["effective"]["available_bytes"], 8 * GIB)
+ serialized = json.dumps(snapshot)
+ self.assertNotIn(str(Path.cwd()), serialized)
+ self.assertNotIn("hostname", serialized.lower().replace("hostnames", ""))
+
+
+class SnapshotToolTests(unittest.TestCase):
+ def test_validator_accepts_canonical_snapshot(self) -> None:
+ report = snapshot_tools.validate_snapshot(canonical_snapshot())
+ self.assertTrue(report["valid"], report["errors"])
+
+ def test_validator_rejects_impossible_disk_order(self) -> None:
+ snapshot = canonical_snapshot()
+ snapshot["disk"]["user_available_bytes"] = 70 * GIB
+ report = snapshot_tools.validate_snapshot(snapshot)
+ self.assertFalse(report["valid"])
+ self.assertIn("DISK_ORDER", {item["code"] for item in report["errors"]})
+
+ def test_diff_ignores_timestamp_by_default(self) -> None:
+ before = canonical_snapshot()
+ after = canonical_snapshot()
+ after["observed_at"] = "2026-07-23T12:05:00Z"
+ self.assertEqual(
+ snapshot_tools.diff_snapshots(before, after)["change_count"],
+ 0,
+ )
+ after["cpu"]["effective"]["capacity_cores"] = 2.0
+ diff = snapshot_tools.diff_snapshots(before, after)
+ self.assertEqual(diff["change_count"], 1)
+ self.assertEqual(
+ diff["changes"][0]["path"],
+ "$.cpu.effective.capacity_cores",
+ )
+
+
+class PlannerTests(unittest.TestCase):
+ def test_worker_plan_uses_cpu_memory_tasks_and_request(self) -> None:
+ plan = plan_workload.build_plan(
+ canonical_snapshot(),
+ workload="cpu",
+ task_count=10,
+ requested_workers=8,
+ memory_per_worker_mib=2048,
+ reserve_memory_mib=1024,
+ accelerator="cuda",
+ )
+ self.assertEqual(plan["limits"]["cpu_worker_ceiling"], 3)
+ self.assertEqual(plan["limits"]["memory_worker_ceiling"], 3)
+ self.assertEqual(plan["recommendation"]["suggested_workers"], 3)
+ self.assertEqual(plan["recommendation"]["threads_per_worker"], 1)
+ self.assertEqual(plan["accelerator"]["status"], "diagnostic_required")
+
+ def test_io_plan_is_bounded(self) -> None:
+ snapshot = canonical_snapshot()
+ snapshot["cpu"]["effective"]["worker_ceiling"] = 1024
+ plan = plan_workload.build_plan(snapshot, workload="io")
+ self.assertEqual(plan["recommendation"]["suggested_workers"], 32)
+
+ def test_accelerator_plan_executes_nothing(self) -> None:
+ plan = accelerator_diagnostics.build_diagnostic_plan(
+ canonical_snapshot(),
+ backend="cuda",
+ )
+ self.assertEqual(plan["execution"], "not_performed")
+ self.assertEqual(plan["selected_backends"], ["cuda"])
+ self.assertEqual(plan["checks"][0]["commands"][0][0], "nvidia-smi")
+ self.assertIn("stress tests or large allocations", plan["prohibited_actions"])
+
+
+if __name__ == "__main__":
+ unittest.main()