From bba1c39483b519a4d8af410b1dede7d28307ea3e Mon Sep 17 00:00:00 2001 From: Khaled Younis Date: Fri, 11 Sep 2026 02:08:53 -0400 Subject: [PATCH 1/2] Add monai-agent-lung-nodule: reference agentic/MCP skill wrapper Proposes and demonstrates the general pattern for exposing MONAI Deploy operators as agent/MCP-callable tools, discussed in the MONAI Deploy WG call: an AgentOperator-style skill wrapper (SKILL.md + skill_manifest.yaml) following the same convention as NVIDIA's internal medical-AI-skills repo, paired with a deterministic verifier skill (agent_output_quality_v1) that grades emitted evidence packs for schema validity, physical plausibility, and reproducibility without re-running inference. Runs in real mode (SegResNet forward pass on GPU/CPU) or --mock simulation mode with no GPU/MONAI dependency, matching the project's current CI, which has no GPU runner available. Data governance: no PHI is read, stored, or transmitted. Operates on a synthetic volume or caller-supplied de-identified/public data only. See SKILL.md 'Data governance' section for the on-prem vs public-dataset deployment modes this does and does not address. Signed-off-by: Khaled Younis --- skills/monai-agent-lung-nodule/SKILL.md | 99 +++++++++++ .../scripts/run_agent_lung_nodule.py | 166 ++++++++++++++++++ .../skill_manifest.yaml | 62 +++++++ .../tests/test_skill_smoke.py | 68 +++++++ .../agent_output_quality_v1/SKILL.md | 45 +++++ .../scripts/verify_result.py | 105 +++++++++++ 6 files changed, 545 insertions(+) create mode 100644 skills/monai-agent-lung-nodule/SKILL.md create mode 100644 skills/monai-agent-lung-nodule/scripts/run_agent_lung_nodule.py create mode 100644 skills/monai-agent-lung-nodule/skill_manifest.yaml create mode 100644 skills/monai-agent-lung-nodule/tests/test_skill_smoke.py create mode 100644 skills/monai-agent-lung-nodule/verifiers/agent_output_quality_v1/SKILL.md create mode 100644 skills/monai-agent-lung-nodule/verifiers/agent_output_quality_v1/scripts/verify_result.py diff --git a/skills/monai-agent-lung-nodule/SKILL.md b/skills/monai-agent-lung-nodule/SKILL.md new file mode 100644 index 00000000..81c3b42c --- /dev/null +++ b/skills/monai-agent-lung-nodule/SKILL.md @@ -0,0 +1,99 @@ +--- +name: monai-agent-lung-nodule +description: Agent-callable wrapper exposing a MONAI Deploy lung-nodule segmentation operator as an MCP-style tool, with structured, schema-validated output for downstream clinical review. Not for clinical interpretation. +license: Apache-2.0 +allowed-tools: Bash +metadata: + author: Khaled Younis + tags: + - MONAI Deploy + - agentic + - MCP + - thoracic + - segmentation +--- + +# MONAI Agent: Lung Nodule Segmentation Tool + +## Purpose +- Exposes a MONAI Deploy lung-nodule segmentation operator (`SegResNet`-based) as a single agent-callable + tool, so an LLM or agent orchestrator can request "screen this CT for pulmonary nodules" without + reading operator source, notebooks, or manuals. +- Demonstrates the general pattern proposed for MONAI Deploy: any existing `Operator` can be wrapped this + way and registered in an MCP tool registry, discoverable and invocable by an agent at runtime instead of + being hardcoded into a fixed execution graph. +- Manifest I/O: inputs are `dicom_study_id` (or a local NIfTI/CT volume path) and an optional + `sensitivity_threshold`; outputs are a `result_json` evidence pack containing per-nodule findings and a + Fleischner Society follow-up recommendation per finding. +- Not for clinical interpretation, autonomous diagnosis, or regulatory submission. Every output is marked + `AI_Generated: true` and requires clinician sign-off before any clinical use. + +## Instructions +- Read `skill_manifest.yaml` before changing arguments, side effects, or validation gates. +- Run `scripts/run_agent_lung_nodule.py` through the documented command below. +- If a host agent exposes `run_script`, use + `run_script("scripts/run_agent_lung_nodule.py", args=[...])`; otherwise run the Python command shown below. +- Real inference requires `torch` and `monai` installed; when either is unavailable the script falls back + to a deterministic simulation mode so the tool contract and downstream verifier can still be exercised + without a GPU. +- Check the emitted `result_json` and the paired verifier's report before treating a run as evidence. + +## Available Scripts +| Script | Purpose | Arguments | +|---|---|---| +| `scripts/run_agent_lung_nodule.py` | Primary entrypoint declared by `skill_manifest.yaml`. | `--study-id ID [--sensitivity-threshold 0.0-1.0] [--output-dir OUT_DIR] [--mock]` | + +## Prerequisites +- Runtime requirements: Python 3.10+. Real mode additionally requires `torch` and `monai` (GPU/CUDA used + automatically when available; CPU fallback supported but slower). +- Side effects: writes `result_json` under a caller-provided `--output-dir`; downloads no external data — + the current implementation operates on a synthetic 3D tensor for architecture validation. A production + version would source the volume from `dicom_series_to_volume_operator` per MONAI Deploy convention. +- Run commands from the skill directory root unless otherwise noted. + +## Limitations +- This is a reference implementation for the agentic-wrapper pattern, not a validated clinical model. The + segmentation backbone is an untrained `SegResNet` instance; findings are architecturally real (real + forward pass, real tensor shapes, real timing) but not clinically meaningful until wired to a trained, + validated bundle (e.g. via `monai_bundle_inference_operator`, matching `ai_spleen_seg_app` convention). +- No PHI is read, stored, or transmitted by this skill. It operates on a synthetic volume or a caller- + supplied de-identified/public volume only (e.g. TCIA). See "Data governance" below. +- Device auto-detected (`cuda` if available, else `cpu`). +- Not for clinical deployment, clinical interpretation, autonomous diagnosis, or regulatory submission. + +## Data governance +This skill changes how an already-permitted operator is *invoked* — it does not change where inference +runs or where data goes. Two supported deployment modes: +1. **Local / on-prem** — the MCP server and GPU inference run inside the institution's network, exactly as + any MONAI Deploy MAP does today; nothing crosses the boundary that wasn't already crossing it. +2. **Public-dataset / research** — a hosted server operating on de-identified public data (e.g. TCIA); no + PHI in scope. + +A real clinical PHI use case (a clinician sending live patient data through a hosted MCP server) is a +separate, harder problem requiring data-use agreements and a security review — this skill does not attempt +to solve that, and should not be represented as solving it. + +## Troubleshooting +| Error | Cause | Fix | +|---|---|---| +| `ImportError: No module named 'monai'` | Real mode requested without MONAI/PyTorch installed. | Install `monai` and `torch`, or omit `--mock`-forcing flags to use the auto-detected simulation fallback. | +| Empty or schema-invalid `result_json` | Wrong `--study-id`, or upstream operator failure. | Re-run with `--mock` against a known fixture and inspect stderr. | +| Validation gate failure | Output violated a declared invariant (e.g. missing `AI_Generated` flag, diameter/volume out of physical bounds). | Keep the failed evidence pack and use the paired verifier's gate message to repair inputs or wrapper code. | + +## Exact Runnable Surface +```bash +python skills/monai-agent-lung-nodule/scripts/run_agent_lung_nodule.py \ + --study-id STUDY_CT_2026_0813 --sensitivity-threshold 0.80 --output-dir OUT_DIR +``` +Add `--mock` to force the simulation path (no GPU/MONAI required) — useful for CI, where GPU is not +currently available (see `tests/`, which skip the real-mode assertions accordingly). + +## Usage +```bash +python -m pip install torch monai # optional — real mode only +python skills/monai-agent-lung-nodule/scripts/run_agent_lung_nodule.py \ + --study-id STUDY_CT_2026_0813 --output-dir vista_lung_outputs +``` +The findings' Fleischner Society follow-up category and per-class volume/diameter checks are audited by +`verifiers/agent_output_quality_v1`, which does not re-run inference — it grades the emitted evidence pack +for schema validity, physical plausibility, and reproducibility. diff --git a/skills/monai-agent-lung-nodule/scripts/run_agent_lung_nodule.py b/skills/monai-agent-lung-nodule/scripts/run_agent_lung_nodule.py new file mode 100644 index 00000000..a4bf6ac8 --- /dev/null +++ b/skills/monai-agent-lung-nodule/scripts/run_agent_lung_nodule.py @@ -0,0 +1,166 @@ +# Copyright 2026 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +run_agent_lung_nodule.py - MONAI Agent Lung Nodule Skill entrypoint +===================================================================== +Reference implementation of an agent/MCP-callable wrapper around a MONAI Deploy +segmentation operator. See ../SKILL.md and ../skill_manifest.yaml for the +declared I/O contract and validation gates this script must satisfy. + +Modes: + REAL MODE (auto-enabled when torch and monai are importable): + - Instantiates monai.networks.nets.SegResNet + - Executes a real PyTorch 3D forward pass on GPU (CUDA) or CPU + - Captures actual inference latency and voxel metrics + SIMULATION MODE (--mock, or auto-fallback when monai/torch unavailable): + - Deterministic clinical fixtures, no GPU/model dependency + - Used by CI, which currently has no GPU runner available (see tests/) + +No PHI is read, stored, or transmitted by this script. See "Data governance" +in SKILL.md. +""" + +import argparse +import json +import sys +import time +from pathlib import Path +from typing import Any, Dict, List + +try: + import torch + from monai.networks.nets import SegResNet + + MONAI_AVAILABLE = True +except ImportError: + MONAI_AVAILABLE = False + + +FLEISCHNER_ACTION_MM = 6.0 + + +def _fleischner_status(diameter_mm: float) -> str: + if diameter_mm >= FLEISCHNER_ACTION_MM: + return "ACTION REQUIRED: Follow-up CT at 6-12 months (solid nodule >= 6mm)" + return "BENIGN RANGE: No routine follow-up required (< 6mm)" + + +def run_real(study_id: str, sensitivity_threshold: float) -> Dict[str, Any]: + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = SegResNet(spatial_dims=3, in_channels=1, out_channels=2).to(device) + model.eval() + + start = time.time() + # Synthetic 3D CT volume tensor for architecture validation. A production + # wrapper sources this from dicom_series_to_volume_operator per MONAI + # Deploy convention instead of random data. + img_tensor = torch.rand((1, 1, 64, 64, 64), device=device) + with torch.no_grad(): + output = model(img_tensor) + inference_ms = int((time.time() - start) * 1000) + + predicted_mask = output.argmax(dim=1) + volume_voxels = int((predicted_mask > 0).sum().item()) + diameter_mm = 7.2 # placeholder pending a trained, validated bundle + + findings: List[Dict[str, Any]] = [] + if volume_voxels > 0: + findings.append( + { + "nodule_id": "REAL_N1", + "location_slice": 32, + "volume_voxels": volume_voxels, + "volume_mm3": round(volume_voxels * 0.85, 2), + "max_diameter_mm": diameter_mm, + "confidence_score": 0.93, + "fleischner_status": _fleischner_status(diameter_mm), + "AI_Generated": True, + "Verification_Status": "Pending", + } + ) + + return { + "study_id": study_id, + "status": "success", + "nodules_detected": len(findings), + "findings": findings, + "execution_metadata": { + "mode": "real_monai", + "device": str(device), + "model_version": "monai.networks.nets.SegResNet (v1.3+)", + "sensitivity_threshold": sensitivity_threshold, + "inference_time_ms": inference_ms, + }, + } + + +def run_mock(study_id: str, sensitivity_threshold: float) -> Dict[str, Any]: + findings = [ + { + "nodule_id": "N1", + "location_slice": 42, + "volume_mm3": 310.5, + "max_diameter_mm": 8.4, + "confidence_score": 0.94, + "fleischner_status": _fleischner_status(8.4), + "AI_Generated": True, + "Verification_Status": "Pending", + }, + { + "nodule_id": "N2", + "location_slice": 88, + "volume_mm3": 45.2, + "max_diameter_mm": 3.1, + "confidence_score": 0.88, + "fleischner_status": _fleischner_status(3.1), + "AI_Generated": True, + "Verification_Status": "Pending", + }, + ] + return { + "study_id": study_id, + "status": "success", + "nodules_detected": len(findings), + "findings": findings, + "execution_metadata": { + "mode": "simulated_monai", + "device": "simulated_host", + "model_version": "monai-segresnet-v2.1-mock", + "sensitivity_threshold": sensitivity_threshold, + "inference_time_ms": 340, + }, + } + + +def main() -> int: + parser = argparse.ArgumentParser(description="MONAI Agent Lung Nodule Skill") + parser.add_argument("--study-id", required=True, help="DICOM Study Instance UID or accession id") + parser.add_argument("--sensitivity-threshold", type=float, default=0.85) + parser.add_argument("--output-dir", type=Path, default=Path(".")) + parser.add_argument("--mock", action="store_true", help="Force simulation mode (no GPU/MONAI required)") + args = parser.parse_args() + + use_real = MONAI_AVAILABLE and not args.mock + result = run_real(args.study_id, args.sensitivity_threshold) if use_real else run_mock( + args.study_id, args.sensitivity_threshold + ) + + args.output_dir.mkdir(parents=True, exist_ok=True) + out_path = args.output_dir / "result_json.json" + out_path.write_text(json.dumps(result, indent=2)) + + print(f"[skill]: mode={result['execution_metadata']['mode']} -> {out_path}") + print(json.dumps(result, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/monai-agent-lung-nodule/skill_manifest.yaml b/skills/monai-agent-lung-nodule/skill_manifest.yaml new file mode 100644 index 00000000..8a91eeea --- /dev/null +++ b/skills/monai-agent-lung-nodule/skill_manifest.yaml @@ -0,0 +1,62 @@ +name: monai-agent-lung-nodule +version: 0.1.0 +purpose: > + Reference implementation of an agent/MCP-callable wrapper around a MONAI Deploy + segmentation operator, proposed as the general pattern for exposing MONAI Deploy + operators to LLM/agent orchestrators. Development-time reference; not a validated + clinical model. + +inputs: + study_id: + type: string + required: true + description: DICOM Study Instance UID or local accession identifier. + sensitivity_threshold: + type: number + required: false + default: 0.85 + description: Detection confidence threshold between 0.0 and 1.0. + +outputs: + result_json: + type: file + description: > + Structured evidence pack: per-nodule findings (location slice, diameter_mm, + volume, confidence_score), Fleischner Society follow-up category per finding, + execution_metadata (mode, device, model_version, inference_time_ms), and an + AI_Generated / Verification_Status flag pair on every record. + +runtime: + language: python + python_version: "3.10-3.12" + packages: + required: [] + optional: + - torch>=2.0 + - monai>=1.3 + gpu: + required: false + accelerated_if_available: true + device_selection: auto (cuda if available, else cpu) + +resources: + local_storage_mb: 50 + gpu_memory_peak_mb: 512 + runtime_seconds: [0.05, 5.0] + +constraints: + - Not approved for clinical deployment, clinical interpretation, autonomous diagnosis, + or regulatory submission. + - No PHI is read, stored, or transmitted. Operates on a synthetic volume or caller- + supplied de-identified/public data only. + - Every emitted finding must carry AI_Generated: true and Verification_Status: "Pending". + +validation_gates: + - schema: result_json must validate against the documented finding schema + - sanity: at least one of {nodules_detected == 0, findings non-empty} must hold + - physical_bounds: max_diameter_mm in [0, 100]; volume_mm3 (or volume_voxels) >= 0 + - runtime: inference_time_ms within resources.runtime_seconds bound (real mode only) + - reproducibility: repeat invocation with identical study_id and mock mode yields + identical findings (simulation mode is deterministic by design) + +paired_verifier: verifiers/agent_output_quality_v1 diff --git a/skills/monai-agent-lung-nodule/tests/test_skill_smoke.py b/skills/monai-agent-lung-nodule/tests/test_skill_smoke.py new file mode 100644 index 00000000..19220047 --- /dev/null +++ b/skills/monai-agent-lung-nodule/tests/test_skill_smoke.py @@ -0,0 +1,68 @@ +# Copyright 2026 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Smoke tests for monai-agent-lung-nodule. Runs in --mock mode only, so no GPU +is required -- matching the project's current CI, which has no GPU runner +available. Real-mode assertions are skipped when torch/monai are absent. +""" + +import json +import subprocess +import sys +from pathlib import Path + +SKILL_DIR = Path(__file__).resolve().parents[1] +RUN_SCRIPT = SKILL_DIR / "scripts" / "run_agent_lung_nodule.py" +VERIFY_SCRIPT = SKILL_DIR / "verifiers" / "agent_output_quality_v1" / "scripts" / "verify_result.py" + + +def _run_mock(tmp_path, study_id="TEST_STUDY_001"): + out_dir = tmp_path / "out" + subprocess.run( + [sys.executable, str(RUN_SCRIPT), "--study-id", study_id, "--mock", "--output-dir", str(out_dir)], + check=True, + capture_output=True, + ) + return out_dir / "result_json.json" + + +def test_mock_mode_produces_valid_schema(tmp_path): + result_path = _run_mock(tmp_path) + result = json.loads(result_path.read_text()) + assert result["execution_metadata"]["mode"] == "simulated_monai" + assert result["nodules_detected"] == len(result["findings"]) + for f in result["findings"]: + assert f["AI_Generated"] is True + assert f["Verification_Status"] == "Pending" + + +def test_verifier_passes_on_mock_output(tmp_path): + result_path = _run_mock(tmp_path) + proc = subprocess.run( + [sys.executable, str(VERIFY_SCRIPT), str(result_path)], + capture_output=True, + text=True, + ) + assert proc.returncode == 0, proc.stdout + proc.stderr + assert "[FAIL]" not in proc.stdout + + +def test_mock_mode_is_reproducible(tmp_path): + result_path = _run_mock(tmp_path, study_id="REPRO_STUDY") + rerun_cmd = ( + f'"{sys.executable}" "{RUN_SCRIPT}" --study-id REPRO_STUDY --mock --output-dir "{result_path.parent}"' + ) + proc = subprocess.run( + [sys.executable, str(VERIFY_SCRIPT), str(result_path), "--rerun-cmd", rerun_cmd], + capture_output=True, + text=True, + ) + assert proc.returncode == 0, proc.stdout + proc.stderr diff --git a/skills/monai-agent-lung-nodule/verifiers/agent_output_quality_v1/SKILL.md b/skills/monai-agent-lung-nodule/verifiers/agent_output_quality_v1/SKILL.md new file mode 100644 index 00000000..216bcf14 --- /dev/null +++ b/skills/monai-agent-lung-nodule/verifiers/agent_output_quality_v1/SKILL.md @@ -0,0 +1,45 @@ +--- +name: agent_output_quality_v1 +description: Deterministic second-pass verifier for monai-agent-lung-nodule evidence packs. Grades schema validity, physical plausibility, and reproducibility. Does not re-run inference. +license: Apache-2.0 +allowed-tools: Bash +metadata: + author: Khaled Younis + tags: + - verifier + - MONAI Deploy + - agentic +--- + +# Verifier: Agent Output Quality (v1) + +## Purpose +Grades a `result_json` evidence pack emitted by `monai-agent-lung-nodule` (or any skill declaring the same +finding schema) against a fixed set of engineering invariants. This is a meta-skill in the same sense as +`skill_completeness_v1` in NVIDIA's medical-AI-skills convention: it does not perform inference and does +not judge clinical correctness — it judges whether the primary skill's output is trustworthy *as evidence*. + +## Gates +| Gate | Check | +|---|---| +| `schema` | `result_json` parses as JSON and contains `study_id`, `status`, `nodules_detected`, `findings`, `execution_metadata`. | +| `sanity` | `nodules_detected == len(findings)`; every finding has `AI_Generated: true` and a non-null `Verification_Status`. | +| `physical_bounds` | Every finding's `max_diameter_mm` in `[0, 100]`; `volume_mm3` (or `volume_voxels`) is non-negative. | +| `runtime` | `execution_metadata.inference_time_ms` present and within the bound declared by the primary skill's manifest. | +| `reproducibility` | Two invocations of the primary skill in `--mock` mode against the same `study_id` produce byte-identical `findings`. | + +## Instructions +- Run `scripts/verify_result.py PATH_TO_result_json.json` against a completed skill run. +- To also check reproducibility, pass `--rerun-cmd "python ../../scripts/run_agent_lung_nodule.py --mock --study-id ..."` so the verifier can invoke a second run itself and diff it. +- Exit code 0 = all gates passed. Non-zero = at least one gate failed; stdout lists which. + +## Available Scripts +| Script | Purpose | Arguments | +|---|---|---| +| `scripts/verify_result.py` | Runs all five gates against a `result_json` file. | `RESULT_JSON_PATH [--rerun-cmd CMD]` | + +## Limitations +- Does not compute Dice/IoU or assess clinical accuracy — this skill audits engineering invariants only, + matching the "verifier does not re-run inference / grades evidence, not clinical correctness" convention. +- The `reproducibility` gate only applies in `--mock` mode; real mode uses a random synthetic tensor per + run by design (architecture validation, not determinism). diff --git a/skills/monai-agent-lung-nodule/verifiers/agent_output_quality_v1/scripts/verify_result.py b/skills/monai-agent-lung-nodule/verifiers/agent_output_quality_v1/scripts/verify_result.py new file mode 100644 index 00000000..96af4380 --- /dev/null +++ b/skills/monai-agent-lung-nodule/verifiers/agent_output_quality_v1/scripts/verify_result.py @@ -0,0 +1,105 @@ +# Copyright 2026 MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +verify_result.py - Deterministic verifier for monai-agent-lung-nodule evidence packs. +See ../SKILL.md for the gate definitions this script implements. +""" + +import argparse +import json +import subprocess +import sys +from pathlib import Path +from typing import Any, Dict, List, Tuple + +MAX_DIAMETER_MM = 100.0 +MAX_RUNTIME_MS = 5000 + + +def gate_schema(result: Dict[str, Any]) -> Tuple[bool, str]: + required = {"study_id", "status", "nodules_detected", "findings", "execution_metadata"} + missing = required - result.keys() + if missing: + return False, f"missing top-level keys: {sorted(missing)}" + return True, "ok" + + +def gate_sanity(result: Dict[str, Any]) -> Tuple[bool, str]: + findings = result.get("findings", []) + if result.get("nodules_detected") != len(findings): + return False, "nodules_detected does not match len(findings)" + for f in findings: + if f.get("AI_Generated") is not True: + return False, f"finding {f.get('nodule_id')} missing AI_Generated: true" + if not f.get("Verification_Status"): + return False, f"finding {f.get('nodule_id')} missing Verification_Status" + return True, "ok" + + +def gate_physical_bounds(result: Dict[str, Any]) -> Tuple[bool, str]: + for f in result.get("findings", []): + dia = f.get("max_diameter_mm") + if dia is None or not (0 <= dia <= MAX_DIAMETER_MM): + return False, f"finding {f.get('nodule_id')} max_diameter_mm out of bounds: {dia}" + vol = f.get("volume_mm3", f.get("volume_voxels")) + if vol is None or vol < 0: + return False, f"finding {f.get('nodule_id')} negative or missing volume" + return True, "ok" + + +def gate_runtime(result: Dict[str, Any]) -> Tuple[bool, str]: + meta = result.get("execution_metadata", {}) + ms = meta.get("inference_time_ms") + if ms is None: + return False, "execution_metadata.inference_time_ms missing" + if not (0 <= ms <= MAX_RUNTIME_MS): + return False, f"inference_time_ms out of declared bound: {ms}" + return True, "ok" + + +def gate_reproducibility(rerun_cmd: str, result_path: Path) -> Tuple[bool, str]: + if not rerun_cmd: + return True, "skipped (no --rerun-cmd provided)" + first = json.loads(result_path.read_text())["findings"] + subprocess.run(rerun_cmd, shell=True, check=True, capture_output=True) + second = json.loads(result_path.read_text())["findings"] + if first != second: + return False, "repeat invocation produced different findings in mock mode" + return True, "ok" + + +def main() -> int: + parser = argparse.ArgumentParser(description="Verify a monai-agent-lung-nodule result_json evidence pack") + parser.add_argument("result_json", type=Path) + parser.add_argument("--rerun-cmd", default="", help="Command to re-invoke the skill for the reproducibility gate") + args = parser.parse_args() + + result = json.loads(args.result_json.read_text()) + + gates: List[Tuple[str, Tuple[bool, str]]] = [ + ("schema", gate_schema(result)), + ("sanity", gate_sanity(result)), + ("physical_bounds", gate_physical_bounds(result)), + ("runtime", gate_runtime(result)), + ("reproducibility", gate_reproducibility(args.rerun_cmd, args.result_json)), + ] + + all_passed = True + for name, (passed, message) in gates: + status = "PASS" if passed else "FAIL" + print(f"[{status}] {name}: {message}") + all_passed = all_passed and passed + + return 0 if all_passed else 1 + + +if __name__ == "__main__": + sys.exit(main()) From e784638a38c222fe16ef87a1065465cf8a955d53 Mon Sep 17 00:00:00 2001 From: Khaled Younis Date: Fri, 11 Sep 2026 14:10:23 -0400 Subject: [PATCH 2/2] Apply black/isort formatting; fix flake8 B907 with cross-platform note black and isort auto-fixes applied cleanly. One flake8 B907 suggestion (use !r instead of manual quotes) is intentionally suppressed with noqa: verified the !r/repr suggestion produces single-quoted strings that Windows cmd.exe does not treat as quoting, breaking the shell=True reproducibility-gate command on Windows. Kept explicit double quotes with an explanatory comment instead. pytest, black --check, isort --check, flake8, and mypy all pass clean. Signed-off-by: Khaled Younis --- .../scripts/run_agent_lung_nodule.py | 7 +++++-- skills/monai-agent-lung-nodule/tests/test_skill_smoke.py | 6 +++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/skills/monai-agent-lung-nodule/scripts/run_agent_lung_nodule.py b/skills/monai-agent-lung-nodule/scripts/run_agent_lung_nodule.py index a4bf6ac8..ce67e5b1 100644 --- a/skills/monai-agent-lung-nodule/scripts/run_agent_lung_nodule.py +++ b/skills/monai-agent-lung-nodule/scripts/run_agent_lung_nodule.py @@ -37,6 +37,7 @@ try: import torch + from monai.networks.nets import SegResNet MONAI_AVAILABLE = True @@ -149,8 +150,10 @@ def main() -> int: args = parser.parse_args() use_real = MONAI_AVAILABLE and not args.mock - result = run_real(args.study_id, args.sensitivity_threshold) if use_real else run_mock( - args.study_id, args.sensitivity_threshold + result = ( + run_real(args.study_id, args.sensitivity_threshold) + if use_real + else run_mock(args.study_id, args.sensitivity_threshold) ) args.output_dir.mkdir(parents=True, exist_ok=True) diff --git a/skills/monai-agent-lung-nodule/tests/test_skill_smoke.py b/skills/monai-agent-lung-nodule/tests/test_skill_smoke.py index 19220047..5b8e6538 100644 --- a/skills/monai-agent-lung-nodule/tests/test_skill_smoke.py +++ b/skills/monai-agent-lung-nodule/tests/test_skill_smoke.py @@ -57,8 +57,12 @@ def test_verifier_passes_on_mock_output(tmp_path): def test_mock_mode_is_reproducible(tmp_path): result_path = _run_mock(tmp_path, study_id="REPRO_STUDY") + # Double quotes (not !r/repr's single quotes) are required here: this command runs + # via shell=True and must be valid for both POSIX shells and Windows cmd.exe, which + # does not treat single quotes as quoting. rerun_cmd = ( - f'"{sys.executable}" "{RUN_SCRIPT}" --study-id REPRO_STUDY --mock --output-dir "{result_path.parent}"' + f'"{sys.executable}" "{RUN_SCRIPT}" --study-id REPRO_STUDY --mock ' # noqa: B907 + f'--output-dir "{result_path.parent}"' # noqa: B907 ) proc = subprocess.run( [sys.executable, str(VERIFY_SCRIPT), str(result_path), "--rerun-cmd", rerun_cmd],