Source code for imednet_workflows.cli

"""CLI commands for iMednet workflows.

This module provides the Typer/argparse integration for common clinical data
workflows, including record extraction, cache synchronization, standards
readiness validation, and state ledger management.
"""

# pylint: disable=duplicate-code

from __future__ import annotations

import argparse
import contextlib
import io
import os
import re
import sys
from collections.abc import Mapping
from datetime import UTC, datetime
from importlib import import_module
from pathlib import Path
from typing import TYPE_CHECKING, Any, NoReturn

import imednet.spi.cli as _spi_cli
import imednet.spi.utils as _spi_utils
from imednet.spi.cli import (
    NON_INTERACTIVE_ENV,
    OUTPUT_FORMAT_ENV,
    UniqueStoreAction,
    add_no_interactive,
    add_output_format,
    add_simulation_arg,
    add_study_key_args,
    clear_line,
    cli_execution_guard,
    collect_list_items_with_remainder,
    console,
    display_list,
    emit_json,
    fetching_status,
    flush_stdout,
    is_json_output_mode,
    load_offline_schema,
    parse_email_notify,
    parse_filter_args,
    parse_record_data_filter,
    positive_int,
    prepare_list_query,
    print_error,
    redact_cli_secrets,
    resolve_cli_schema,
    resolve_endpoint_filter_attributes,
    resolve_hybrid_study_and_key,
    resolve_output_format,
    resolve_study_key,
    simulation_mode_context,
    validate_cli_path_segment,
    with_sdk,
    write_stdout,
)
from imednet.spi.models import (
    PROFILE_REGISTRY,
    Query,
    QueryStatus,
    StudyConfiguration,
    TriageItem,
    TriageStatus,
)
from imednet.spi.utils import (
    PathTraversalValidationError,
    build_study_sensitivity_registry,
    global_sensitivity_registry,
    mask_clinical_phi,
    redact_sensitive_text,
    sanitize_diagnostic_text,
    sdk_governance_context,
    validate_path_segment,
)
from imednet.spi.validation import DataDictionary, ValidationSchemaProtocol

from ._audit_cli import setup_audit_parsers

if TYPE_CHECKING:
    from imednet.sdk import ImednetSDK

DEFAULT_LEDGER_PATH: str = os.environ.get(
    "IMEDNET_WORKFLOW_LEDGER_PATH",
    str(Path.home() / ".imednet" / "pipeline_ledger.json"),
)


def _resolve_workflow_phi_fields(
    study_key: str | None,
    *,
    sdk: Any = None,
) -> set[str]:
    """Resolve normalized study PHI keys via SPI under *sdk* governance."""
    sk = (study_key or "").strip()
    if not sk:
        return set()
    patched = globals().get("resolve_study_configuration")
    if callable(patched) and patched is not _spi_utils.resolve_study_configuration:
        with sdk_governance_context(sdk):
            cfg = patched(sk)
        raw_fields = getattr(cfg, "phi_fields", None) if cfg is not None else None
        if not raw_fields:
            return set()
        non_exempt = [
            str(k)
            for k in raw_fields
            if str(k).strip() and not global_sensitivity_registry.is_exempt(str(k))
        ]
        if not non_exempt:
            return set()
        return set(
            _spi_utils.EnrichmentPipeline(
                StudyConfiguration(study_key="PHI", phi_fields=non_exempt)
            ).phi_keys
        )
    return set(_spi_cli.resolve_cli_phi_fields(sk, sdk=sdk))


_LAZY_ATTRS: dict[str, tuple[str, str]] = {
    "DataExtractionWorkflow": ("imednet_workflows.data_extraction", "DataExtractionWorkflow"),
    "DuckDBIngestionWorkflow": ("imednet_workflows.duckdb_centralizer", "DuckDBIngestionWorkflow"),
    "QueryManagementWorkflow": ("imednet_workflows.query_management", "QueryManagementWorkflow"),
    "SubjectDataWorkflow": ("imednet_workflows.subject_data", "SubjectDataWorkflow"),
    "SyncWorker": ("imednet_workflows.sync_worker", "SyncWorker"),
    "SyncWorkerConfig": ("imednet_workflows.sync_worker", "SyncWorkerConfig"),
    "SyncWorkerState": ("imednet_workflows.sync_worker", "SyncWorkerState"),
    "TriageStore": ("imednet_workflows.triage_store", "TriageStore"),
    "get_state_provider": ("imednet_workflows.state_ledger", "get_state_provider"),
    "resolve_study_configuration": ("imednet.spi.utils", "resolve_study_configuration"),
}


def _load_lazy_attr(name: str) -> Any:
    """Import and cache a lazy workflow attribute on first access."""
    if name in _LAZY_ATTRS:
        mod_name, attr_name = _LAZY_ATTRS[name]
        mod = import_module(mod_name)  # nosem
        val = getattr(mod, attr_name)
        globals()[name] = val
        return val
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


if not TYPE_CHECKING:

    def __getattr__(name: str) -> Any:
        """Lazily load workflow execution classes and state providers on demand (PEP 562)."""
        return _load_lazy_attr(name)


def _resolve_attr(name: str) -> Any:
    """Resolve a lazy workflow symbol while preserving module-level monkeypatches."""
    if name in globals():
        return globals()[name]
    return _load_lazy_attr(name)


def _emit_line(text: str = "", *, err: bool = False) -> None:
    """Write a PHI/secret-redacted line safely via structured CLI output."""
    sanitized = redact_cli_secrets(redact_sensitive_text(str(text)))
    if err:
        print_error(sanitized)
        return
    write_stdout(sanitized)


def _reject_interactive_json_mode(interactive: bool, output_format: str | None) -> None:
    """Exit 1 on stderr with empty stdout when --interactive conflicts with JSON output mode."""
    if not interactive:
        return
    resolved = resolve_output_format(output_format)
    if resolved == "json" or (output_format is None and is_json_output_mode()):
        print_error(
            "Error: Cannot combine --interactive with --format json or IMEDNET_CLI_OUTPUT_FORMAT=json."
        )
        sys.exit(1)


def _exit_uat_validation_error(
    exc: BaseException | str,
    *,
    study_key: str | None = None,
    sdk: Any = None,
) -> NoReturn:
    """Emit a secret- and PHI-redacted UAT validation error to stderr and exit 1."""
    safe_phi_study: str | None = None
    if isinstance(study_key, str) and study_key.strip():
        with contextlib.suppress(Exception):
            validate_path_segment(study_key.strip(), name="study_key")
            safe_phi_study = study_key.strip()
    custom_phi = _resolve_workflow_phi_fields(safe_phi_study, sdk=sdk)
    sanitized = _sanitize_uat_error_text(str(exc), custom_phi_fields=custom_phi)
    prefix = "" if sanitized.startswith("Validation Error:") else "Validation Error: "
    print_error(f"{prefix}{sanitized}")
    sys.exit(1)


def _validate_uat_subject_count(subject_count: int) -> int:
    """Validate --subject-count bounds (1..100) during CLI preflight."""
    if isinstance(subject_count, bool) or not 1 <= subject_count <= 100:
        raise ValueError("subject_count must be between 1 and 100.")
    return subject_count


def _load_uat_data_dictionary(
    dd_path: str | None,
    *,
    study_key: str,
) -> DataDictionary | None:
    """Load an offline DataDictionary from JSON, CDISC ODM XML, REDCap CSV, ZIP, or CSV dir."""
    if not dd_path:
        return None
    loaded = load_offline_schema(dd_path, study_key=study_key)
    if not isinstance(loaded, DataDictionary):
        raise ValueError(
            f"Unsupported Data Dictionary source '{dd_path}': expected JSON, ODM XML, REDCap CSV, ZIP, or CSV directory."
        )
    return loaded


def _sanitize_phi_issue_message(
    message: str,
    *,
    variable_name: str | None,
    custom_phi_fields: set[str],
) -> str:
    """Redact credentials, sensitive URIs, and clinical PHI values in issue messages."""
    active_registry = build_study_sensitivity_registry(custom_phi_fields)

    sanitized = redact_cli_secrets(
        sanitize_diagnostic_text(redact_sensitive_text(message), registry=active_registry)
    )

    if variable_name is None:
        inferred = re.search(r"variable '([A-Za-z0-9_-]+)'", sanitized)
        if inferred:
            variable_name = inferred.group(1)

    if isinstance(variable_name, str) and active_registry.is_sensitive(variable_name):

        def _mask_quote(match: re.Match[str]) -> str:
            inner = match.group(1)
            if inner == variable_name:
                return match.group(0)
            return "'***MASKED***'"

        sanitized = re.sub(r"'([^']*)'", _mask_quote, sanitized)
    return sanitized


def _sanitize_validation_report_dict(
    report_dict: dict[str, Any],
    *,
    custom_phi_fields: set[str],
) -> dict[str, Any]:
    """Sanitize validationReport issue messages for secrets and clinical PHI."""
    cleaned = dict(report_dict)
    for list_key in ("errors", "warnings"):
        raw_items = cleaned.get(list_key)
        if not isinstance(raw_items, list):
            continue
        sanitized_items: list[Any] = []
        for entry in raw_items:
            if not isinstance(entry, Mapping):
                sanitized_items.append(entry)
                continue
            rebuilt_entry = dict(entry)
            raw_msg = rebuilt_entry.get("message")
            var_name = rebuilt_entry.get("variableName")
            if isinstance(raw_msg, str):
                rebuilt_entry["message"] = _sanitize_phi_issue_message(
                    raw_msg,
                    variable_name=var_name if isinstance(var_name, str) else None,
                    custom_phi_fields=custom_phi_fields,
                )
            sanitized_items.append(rebuilt_entry)
        cleaned[list_key] = sanitized_items
    return cleaned


def _sanitize_uat_error_text(text: str, *, custom_phi_fields: set[str]) -> str:
    """Redact secrets and mask PHI values across multi-line UAT error summaries."""
    sanitized_lines: list[str] = []
    for line in text.splitlines():
        var_match = re.search(r"\[variable=([^\]]+)\]", line)
        var_name = var_match.group(1) if var_match else None
        sanitized_lines.append(
            _sanitize_phi_issue_message(
                line,
                variable_name=var_name,
                custom_phi_fields=custom_phi_fields,
            )
        )
    return "\n".join(sanitized_lines)


def _emit_uat_json_failure(
    exc: BaseException | str,
    *,
    study_key: str | None,
    dry_run: bool,
    failure_phase: str = "PREFLIGHT",
    sdk: Any = None,
) -> NoReturn:
    """Emit a single PHI-masked, secret-redacted failed uat_run JSON envelope and exit 1."""
    from .uat import UATRunResult, UATWorkflowState

    resolved_study = study_key.strip() if isinstance(study_key, str) and study_key.strip() else ""
    safe_phi_study: str | None = None
    if resolved_study:
        with contextlib.suppress(Exception):
            validate_path_segment(resolved_study, name="study_key")
            safe_phi_study = resolved_study
    custom_phi = _resolve_workflow_phi_fields(safe_phi_study, sdk=sdk)
    now = datetime.now(UTC)
    failed_result = UATRunResult.model_construct(
        study_key=resolved_study,
        run_id="",
        started_at=now,
        completed_at=now,
        state=UATWorkflowState.FAILED,
        state_history=[failure_phase, UATWorkflowState.FAILED]
        if failure_phase
        else [UATWorkflowState.FAILED],
        failure_phase=failure_phase,
        error_message=str(exc),
        spec=None,
        record_sets=[],
        submission_result=None,
        poll_summary=None,
        dry_run=bool(dry_run),
        validation_report=None,
        phase_durations={},
    )
    item = _serialize_uat_run_result(
        failed_result,
        study_key=resolved_study,
        dry_run=dry_run,
        custom_phi_fields=custom_phi,
        sdk=sdk,
    )
    emit_json([item], "uat_run", status="failed")
    sys.exit(1)


def _serialize_uat_run_result(
    result: Any,
    *,
    study_key: str,
    dry_run: bool,
    custom_phi_fields: set[str],
    sdk: Any = None,
) -> dict[str, Any]:
    """Serialize a UATRunResult into a PHI-masked camelCase dictionary for emit_json."""
    state_raw = getattr(result, "state", None)
    state_str = (
        state_raw.value
        if state_raw is not None and hasattr(state_raw, "value")
        else str(state_raw or "COMPLETED")
    )
    history_raw = getattr(result, "state_history", None)
    history_list = (
        [s.value if hasattr(s, "value") else str(s) for s in history_raw]
        if isinstance(history_raw, list)
        else []
    )
    fail_raw = getattr(result, "failure_phase", None)
    fail_str = (
        fail_raw.value
        if fail_raw is not None and hasattr(fail_raw, "value")
        else (str(fail_raw) if fail_raw is not None else None)
    )
    record_sets = getattr(result, "record_sets", None)
    forms_tested = len(record_sets) if isinstance(record_sets, list) else 0
    records_generated = (
        sum(len(getattr(rs, "payloads", []) or []) for rs in record_sets)
        if isinstance(record_sets, list)
        else 0
    )
    sub_res = getattr(result, "submission_result", None)
    records_submitted = (
        int(sub_res.total_records_submitted)
        if sub_res is not None
        and isinstance(getattr(sub_res, "total_records_submitted", None), int)
        else 0
    )
    poll_sum = getattr(result, "poll_summary", None)
    jobs_monitored = 0
    if poll_sum is not None:
        res_map = getattr(poll_sum, "results", None)
        fail_map = getattr(poll_sum, "failures", None)
        if isinstance(res_map, dict):
            jobs_monitored += len(res_map)
        if isinstance(fail_map, dict):
            jobs_monitored += len(fail_map)

    val_rep = getattr(result, "validation_report", None)
    if val_rep is not None and callable(getattr(val_rep, "to_dict", None)):
        val_rep_dict = _sanitize_validation_report_dict(
            val_rep.to_dict(),
            custom_phi_fields=custom_phi_fields,
        )
    elif isinstance(val_rep, dict):
        val_rep_dict = _sanitize_validation_report_dict(
            val_rep,
            custom_phi_fields=custom_phi_fields,
        )
    else:
        val_rep_dict = None

    err_msg = getattr(result, "error_message", None)
    sanitized_err = (
        _sanitize_uat_error_text(err_msg, custom_phi_fields=custom_phi_fields)
        if isinstance(err_msg, str)
        else None
    )
    raw_durations = getattr(result, "phase_durations", None)
    phase_durations = dict(raw_durations) if isinstance(raw_durations, Mapping) else {}

    item: dict[str, Any] = {
        "runId": str(getattr(result, "run_id", "") or ""),
        "studyKey": str(getattr(result, "study_key", None) or study_key),
        "dryRun": bool(getattr(result, "dry_run", dry_run)),
        "state": state_str,
        "stateHistory": history_list,
        "overallSuccess": bool(getattr(result, "overall_success", False)),
        "formsTested": forms_tested,
        "recordsGenerated": records_generated,
        "recordsSubmitted": records_submitted,
        "jobsMonitored": jobs_monitored,
        "failurePhase": fail_str,
        "errorMessage": sanitized_err,
        "validationReport": val_rep_dict,
        "phaseDurations": phase_durations,
    }
    masked = _spi_cli.mask_cli_models(
        [item],
        study_key=study_key,
        mask_phi=True,
        sdk=sdk,
        custom_phi_fields=custom_phi_fields,
    )[0]
    return masked if isinstance(masked, dict) else item


def _to_serializable(value: Any) -> Any:
    """Convert Pydantic models, mappings, and sequences into plain JSON-compatible objects."""
    if value is None or isinstance(value, (str, int, float, bool)):
        return value
    if isinstance(value, Mapping):
        return {str(k): _to_serializable(v) for k, v in value.items()}
    if isinstance(value, (list, tuple, set)):
        return [_to_serializable(item) for item in value]
    model_dump = getattr(type(value), "model_dump", None)
    if callable(model_dump):
        try:
            dumped = value.model_dump(mode="json", warnings=False)
        except TypeError:
            dumped = value.model_dump(mode="json")
        if dumped is not value and isinstance(
            dumped, (Mapping, list, tuple, str, int, float, bool)
        ):
            return _to_serializable(dumped)
    instance_dump = getattr(value, "model_dump", None)
    if callable(instance_dump):
        try:
            dumped = instance_dump(warnings=False)
        except TypeError:
            dumped = instance_dump()
        if dumped is not value and isinstance(
            dumped, (Mapping, list, tuple, str, int, float, bool)
        ):
            return _to_serializable(dumped)
    return str(value)


def _execute_set_state(
    study_key: str | None,
    stream: str | None,
    timestamp: str | None,
    records_processed: int,
    ledger_path: str,
    interactive: bool = False,
    parser: argparse.ArgumentParser | None = None,
    no_interactive: bool = False,
    force: bool = False,
    output_format: str | None = None,
) -> None:
    """Execute high-water mark timestamp update for a study/stream in the ledger."""
    _reject_interactive_json_mode(interactive, output_format)
    if study_key is not None:
        validate_cli_path_segment(study_key, name="study_key")
    if stream is not None:
        validate_cli_path_segment(stream, name="stream")

    if not interactive:
        missing = [
            flag
            for flag, val in [
                ("-s/--study-key", study_key),
                ("-m/--stream", stream),
                ("-t/--timestamp", timestamp),
            ]
            if not val
        ]
        if missing:
            msg = f"the following arguments are required: {', '.join(missing)}"
            if parser is not None:
                parser.error(msg)
            _emit_line(f"Error: {msg}", err=True)
            sys.exit(2)

        try:
            normalized = timestamp.replace("Z", "+00:00")  # type: ignore[union-attr]
            dt = datetime.fromisoformat(normalized)
            dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
        except ValueError as err:
            _emit_line(f"Invalid ISO timestamp format: {err}", err=True)
            sys.exit(1)

        ledger = _resolve_attr("get_state_provider")(ledger_path)
        try:
            ledger.set_last_timestamp(
                study_key=study_key,  # type: ignore[arg-type]
                stream_name=stream,  # type: ignore[arg-type]
                timestamp=dt,
                records_processed=records_processed,
                status="success",
                force=force,
            )
            if resolve_output_format(output_format) == "json":
                emit_json(
                    [
                        {
                            "studyKey": study_key,
                            "streamName": stream,
                            "lastTimestamp": dt.isoformat(),
                            "recordsProcessed": records_processed,
                            "status": "success",
                            "errorMessage": None,
                        }
                    ],
                    "ledger_state",
                )
            else:
                _emit_line(
                    f"Successfully set high-water mark for '{study_key}' -> '{stream}' to {dt.isoformat()}"
                )
        except Exception as err:
            _emit_line(f"Failed to write ledger: {err}", err=True)
            sys.exit(1)
        return

    from .wizard import (
        display_ledger_streams,
        ensure_interactive_stdin,
        print_progress,
        prompt_confirm,
        prompt_iso8601_timestamp,
        prompt_non_negative_int,
        prompt_stream_name,
        prompt_study_key,
        validate_iso8601_timestamp,
    )

    ensure_interactive_stdin(force_non_interactive=no_interactive)
    ledger = _resolve_attr("get_state_provider")(ledger_path)
    current_state = display_ledger_streams(
        ledger_path=ledger_path,
        study_key=study_key,
        state_provider=ledger,
    )
    study_key = prompt_study_key(study_key)
    stream = prompt_stream_name(stream)

    if not timestamp:
        _, dt = prompt_iso8601_timestamp(
            "Enter ISO-8601 UTC timestamp (e.g., '2026-05-22T12:00:00Z')"
        )
    else:
        is_valid, dt_val, val_err = validate_iso8601_timestamp(timestamp)
        if not is_valid or dt_val is None:
            print_progress(f"Validation Error in provided timestamp: {val_err}")
            _, dt = prompt_iso8601_timestamp(
                "Enter ISO-8601 UTC timestamp (e.g., '2026-05-22T12:00:00Z')"
            )
        else:
            dt = dt_val

    records_processed = prompt_non_negative_int(
        "Enter number of records processed", default=records_processed
    )

    current_status = "None"
    current_ts_str = "None"
    if current_state is not None:
        try:
            if (
                study_key in current_state.studies
                and stream in current_state.studies[study_key].streams
            ):
                st = current_state.studies[study_key].streams[stream]
                current_status = str(st.last_run_status)
                current_ts_str = st.last_timestamp.isoformat() if st.last_timestamp else "None"
        except Exception as exc:
            print_progress(f"Notice: unable to read stream state from ledger: {exc}")

    print_progress("\nProposed State Transition:")
    print_progress(f"  Study:             {study_key}")
    print_progress(f"  Stream:            {stream}")
    print_progress(f"  Current Status:    {current_status} (timestamp: {current_ts_str})")
    print_progress(f"  New Status:        success (timestamp: {dt.isoformat()})")
    print_progress(f"  Records Processed: {records_processed}")

    confirmed = prompt_confirm("Confirm state transition and write to ledger?", default=False)
    if not confirmed:
        print_progress("State update cancelled. Ledger was not modified.")
        return

    try:
        ledger.set_last_timestamp(
            study_key=study_key,
            stream_name=stream,
            timestamp=dt,
            records_processed=records_processed,
            status="success",
            force=force,
        )
        _emit_line(
            f"Successfully set high-water mark for '{study_key}' -> '{stream}' to {dt.isoformat()}"
        )
    except Exception as err:
        _emit_line(f"Failed to write ledger: {err}", err=True)
        sys.exit(1)


def _execute_reset_state(
    study_key: str | None,
    stream: str | None,
    ledger_path: str,
    interactive: bool = False,
    parser: argparse.ArgumentParser | None = None,
    no_interactive: bool = False,
    force: bool = False,
    output_format: str | None = None,
) -> None:
    """Execute high-water mark state deletion for a study/stream."""
    _reject_interactive_json_mode(interactive, output_format)
    if study_key is not None:
        validate_cli_path_segment(study_key, name="study_key")
    if stream is not None:
        validate_cli_path_segment(stream, name="stream")

    if interactive:
        from .wizard import (
            ensure_interactive_stdin,
            print_progress,
            prompt_confirm,
            prompt_study_key,
        )

        ensure_interactive_stdin(force_non_interactive=no_interactive)
        study_key = prompt_study_key(study_key)
        target_desc = (
            f"stream '{stream}' for study '{study_key}'"
            if stream
            else f"all streams for study '{study_key}'"
        )
        confirmed = prompt_confirm(f"Are you sure you want to reset {target_desc}?", default=False)
        if not confirmed:
            print_progress("Reset cancelled by user. Ledger was not modified.")
            return
    elif not study_key:
        msg = "the following arguments are required: -s/--study-key"
        if parser is not None:
            parser.error(msg)
        _emit_line(f"Error: {msg}", err=True)
        sys.exit(2)

    ledger = _resolve_attr("get_state_provider")(ledger_path)
    try:
        if stream:
            removed = (
                ledger.delete_entry(study_key, stream, force=True)
                if force
                else ledger.delete_entry(study_key, stream)
            )
            if resolve_output_format(output_format) == "json":
                emit_json(
                    [{"studyKey": study_key, "streamName": stream, "removed": bool(removed)}],
                    "ledger_state",
                )
                return
            if removed:
                _emit_line(f"Successfully reset stream '{stream}' for study '{study_key}'.")
            else:
                _emit_line(f"No stream '{stream}' found for study '{study_key}'.")
                return
        else:
            removed = (
                ledger.delete_entry(study_key, force=True)
                if force
                else ledger.delete_entry(study_key)
            )
            if resolve_output_format(output_format) == "json":
                emit_json(
                    [{"studyKey": study_key, "streamName": None, "removed": bool(removed)}],
                    "ledger_state",
                )
                return
            if removed:
                _emit_line(f"Successfully reset all streams for study '{study_key}'.")
            else:
                _emit_line(f"No state found for study '{study_key}'.")
                return
    except Exception as err:
        _emit_line(f"Failed to reset ledger state: {err}", err=True)
        sys.exit(1)


def _execute_show_state(
    ledger_path: str,
    study_key: str | None = None,
    *,
    interactive: bool = False,
    no_interactive: bool = False,
    output_format: str | None = None,
) -> None:
    """Display current high-water mark records and stream metadata from the ledger."""
    _reject_interactive_json_mode(interactive, output_format)
    resolved_format = resolve_output_format(output_format)
    if study_key is not None:
        validate_cli_path_segment(study_key, name="study_key")

    if interactive:
        from .wizard import ensure_interactive_stdin, prompt_input

        ensure_interactive_stdin(force_non_interactive=no_interactive)
        study_input = prompt_input(
            "Enter study key to filter (leave blank for all studies)",
            default=study_key or "",
        )
        study_key = study_input if study_input else None
        if study_key is not None:
            validate_cli_path_segment(study_key, name="study_key")

    ledger = _resolve_attr("get_state_provider")(ledger_path)
    try:
        state = ledger.read_state()
    except Exception as err:
        _emit_line(f"Failed to read ledger from {ledger_path}: {err}", err=True)
        sys.exit(1)

    entries: list[dict[str, Any]] = []
    for s_key, study_state in state.studies.items():
        if study_key and s_key != study_key:
            continue
        for stream_name, stream_state in study_state.streams.items():
            ts_iso = (
                stream_state.last_timestamp.isoformat()
                if stream_state.last_timestamp is not None
                else None
            )
            entries.append(
                {
                    "studyKey": s_key,
                    "streamName": stream_name,
                    "lastTimestamp": ts_iso,
                    "recordsProcessed": stream_state.records_processed,
                    "status": str(stream_state.last_run_status),
                    "errorMessage": stream_state.error_message,
                }
            )

    if resolved_format == "json":
        emit_json(entries, "ledger_state")
        return

    _emit_line(f"iMednet Extraction Ledger ({ledger_path})")
    _emit_line(
        "Study Key | Stream Name | Last Timestamp (UTC) | Records Processed | Status | Error Message"
    )
    for entry in entries:
        ts_str = entry["lastTimestamp"] if entry["lastTimestamp"] is not None else "None"
        _emit_line(
            f"{entry['studyKey']} | {entry['streamName']} | {ts_str} | {entry['recordsProcessed']} | {entry['status']} | {entry['errorMessage'] or ''}"
        )

    if not entries:
        _emit_line("No ledger entries found matching filters.")


def _resolve_state_study_key(
    parser: argparse.ArgumentParser,
    args: argparse.Namespace,
) -> str | None:
    """Resolve study_key for state commands, exiting 1 on blank/whitespace or path-traversal keys."""
    flag_val = getattr(args, "study_key_flag", None)
    pos_val = getattr(args, "study_key", None)
    if isinstance(flag_val, str) and not flag_val.strip():
        validate_cli_path_segment(flag_val, name="study_key")
    if isinstance(pos_val, str) and not pos_val.strip():
        validate_cli_path_segment(pos_val, name="study_key")
    study_key = resolve_study_key(parser, args, required=False)
    if study_key is not None:
        validate_cli_path_segment(study_key, name="study_key")
    return study_key


def _configure_state_subparsers(state_parser: argparse.ArgumentParser) -> None:
    """Attach show, set, and reset subparsers to a state ArgumentParser."""
    state_sub = state_parser.add_subparsers(dest="state_command")

    show_parser = state_sub.add_parser(
        "show", help="Show the current high-water mark records and stream metadata."
    )
    show_parser.add_argument(
        "-l",
        "--ledger-path",
        default=DEFAULT_LEDGER_PATH,
        help="Path to the pipeline ledger JSON file.",
    )
    add_study_key_args(show_parser, flag_help="Filter the ledger by a specific study key.")
    show_parser.add_argument(
        "--interactive", action="store_true", help="Run in interactive wizard mode."
    )
    add_output_format(show_parser)

    def _dispatch_show_state(args: argparse.Namespace) -> None:
        _reject_interactive_json_mode(args.interactive, getattr(args, "output_format", None))
        study_key = _resolve_state_study_key(show_parser, args)
        _execute_show_state(
            ledger_path=args.ledger_path,
            study_key=study_key,
            interactive=args.interactive,
            no_interactive=getattr(args, "no_interactive", False),
            output_format=getattr(args, "output_format", None),
        )

    show_parser.set_defaults(func=_dispatch_show_state)

    set_parser = state_sub.add_parser(
        "set", help="Manually set a high-water mark timestamp for a study and stream."
    )
    add_study_key_args(set_parser, flag_help="The study key.")
    set_parser.add_argument("-m", "--stream", help="The stream name.")
    set_parser.add_argument("-t", "--timestamp", help="The ISO-8601 timestamp (UTC).")
    set_parser.add_argument(
        "-r", "--records-processed", type=int, default=0, help="Number of records processed."
    )
    set_parser.add_argument(
        "-l",
        "--ledger-path",
        default=DEFAULT_LEDGER_PATH,
        help="Path to the pipeline ledger JSON file.",
    )
    set_parser.add_argument(
        "-f",
        "--force",
        action="store_true",
        help="Force state transition override even when the current status disallows it.",
    )
    set_parser.add_argument(
        "--interactive", action="store_true", help="Run in interactive wizard mode."
    )
    add_output_format(set_parser)

    def _dispatch_set_state(args: argparse.Namespace) -> None:
        _reject_interactive_json_mode(args.interactive, getattr(args, "output_format", None))
        study_key = _resolve_state_study_key(set_parser, args)
        _execute_set_state(
            study_key=study_key,
            stream=args.stream,
            timestamp=args.timestamp,
            records_processed=args.records_processed,
            ledger_path=args.ledger_path,
            interactive=args.interactive,
            parser=set_parser,
            no_interactive=getattr(args, "no_interactive", False),
            force=getattr(args, "force", False),
            output_format=getattr(args, "output_format", None),
        )

    set_parser.set_defaults(func=_dispatch_set_state)

    reset_parser = state_sub.add_parser(
        "reset", help="Reset (clear) high-water mark state for a study/stream."
    )
    add_study_key_args(reset_parser, flag_help="The study key.")
    reset_parser.add_argument(
        "-m",
        "--stream",
        help="The stream name. If omitted, all streams for the study will be reset.",
    )
    reset_parser.add_argument(
        "-l",
        "--ledger-path",
        default=DEFAULT_LEDGER_PATH,
        help="Path to the pipeline ledger JSON file.",
    )
    reset_parser.add_argument(
        "-f",
        "--force",
        action="store_true",
        help="Force state reset even when an active RUNNING lease is held.",
    )
    reset_parser.add_argument(
        "--interactive", action="store_true", help="Run in interactive wizard mode."
    )
    add_output_format(reset_parser)

    def _dispatch_reset_state(args: argparse.Namespace) -> None:
        _reject_interactive_json_mode(args.interactive, getattr(args, "output_format", None))
        study_key = _resolve_state_study_key(reset_parser, args)
        _execute_reset_state(
            study_key=study_key,
            stream=args.stream,
            ledger_path=args.ledger_path,
            interactive=args.interactive,
            parser=reset_parser,
            no_interactive=getattr(args, "no_interactive", False),
            force=getattr(args, "force", False),
            output_format=getattr(args, "output_format", None),
        )

    reset_parser.set_defaults(func=_dispatch_reset_state)


[docs]def setup_parser(subparsers: argparse._SubParsersAction[Any]) -> None: """Set up the workflows argparse subparsers.""" wf_parser = subparsers.add_parser("workflows", help="Execute common data workflows.") sub = wf_parser.add_subparsers(dest="wf_command") extract_parser = sub.add_parser( "extract-records", help="Extract records based on criteria spanning subjects, visits, and records.", ) add_study_key_args(extract_parser) extract_parser.add_argument( "--record-filter", action="append", help="Record filter criteria (e.g., 'form_key=DEMO'). Repeat for multiple filters.", ) extract_parser.add_argument( "--record-data-filter", dest="record_data_filter", action="append", help=( "Filter by form variable values (e.g., 'AGE>25', 'RACE==White'). " "Repeatable; combined with AND." ), ) extract_parser.add_argument( "--subject-filter", action="append", help="Subject filter criteria (e.g., 'subject_status=Screened'). Repeat for multiple filters.", ) extract_parser.add_argument( "--visit-filter", action="append", help="Visit filter criteria (e.g., 'interval_name=Screening'). Repeat for multiple filters.", ) extract_parser.add_argument( "--limit", type=positive_int, default=None, help="Maximum number of items to return (default: 100 in table mode; unlimited for --format json).", ) extract_parser.add_argument( "--all", dest="fetch_all", action="store_true", default=False, help="Fetch all matching pages without the default 100-item table cap.", ) extract_parser.add_argument( "--interactive", action="store_true", help="Run in interactive wizard mode with step-by-step prompts.", ) extract_parser.add_argument( "--mask-phi", dest="mask_phi", action=argparse.BooleanOptionalAction, default=True, help="Mask clinical PHI fields with '***MASKED***' (default: enabled).", ) add_output_format(extract_parser) add_simulation_arg(extract_parser) def _extract_record_view_row(rec_obj: Any) -> dict[str, Any]: if isinstance(rec_obj, Mapping): return { "ID": rec_obj.get("record_id"), "Subject": rec_obj.get("subject_key"), "Form": rec_obj.get("form_key"), "Status": rec_obj.get("record_status"), "Created": rec_obj.get("date_created"), } return { "ID": getattr(rec_obj, "record_id", None), "Subject": getattr(rec_obj, "subject_key", None), "Form": getattr(rec_obj, "form_key", None), "Status": getattr(rec_obj, "record_status", None), "Created": getattr(rec_obj, "date_created", None), } def _coalesce_record_data_filter(raw: str | list[str] | None) -> str | None: if raw is None: return None if isinstance(raw, str): stripped = raw.strip() return stripped or None joined = ";".join(part.strip() for part in raw if part and part.strip()) return joined or None @with_sdk def extract_records( sdk: ImednetSDK, study_key: str | None, record_filter: list[str] | None = None, record_data_filter: str | list[str] | None = None, subject_filter: list[str] | None = None, visit_filter: list[str] | None = None, limit: int | None = None, fetch_all: bool = False, interactive: bool = False, no_interactive: bool = False, output_format: str | None = None, mask_phi: bool = True, _prepared_query: tuple[dict[str, Any], int | None] | None = None, ) -> None: from imednet.spi.models import Record, Subject, Visit from .data_extraction import DataExtractionWorkflow as _RealDataExtractionWorkflow from .wizard import print_progress _reject_interactive_json_mode(interactive, output_format) resolved_format = resolve_output_format(output_format) json_mode = resolved_format == "json" or (output_format is None and is_json_output_mode()) if interactive: from .wizard import ensure_interactive_stdin, prompt_filters, prompt_study_key ensure_interactive_stdin(force_non_interactive=no_interactive) study_key = prompt_study_key(study_key) record_filter = prompt_filters( "record filter", "form_key=DEMO", existing_filters=record_filter, model=Record, ) subject_filter = prompt_filters( "subject filter", "subject_status=Screened", existing_filters=subject_filter, model=Subject, ) visit_filter = prompt_filters( "visit filter", "interval_name=Screening", existing_filters=visit_filter, model=Visit, ) _prepared_query = None elif not study_key: extract_parser.error("the following arguments are required: study_key") assert study_key is not None validate_path_segment(study_key, name="study_key") workflow = _resolve_attr("DataExtractionWorkflow")(sdk) coalesced_rdf = _coalesce_record_data_filter(record_data_filter) req_kwargs, effective_limit = ( (dict(_prepared_query[0]), _prepared_query[1]) if _prepared_query is not None else prepare_list_query( filter_args=record_filter, record_data_filter=coalesced_rdf, limit=limit, fetch_all=fetch_all, output_format=resolved_format, no_interactive=no_interactive, model=Record, disallow_study_key=False, ) ) combined_rdf: str | None = req_kwargs.pop("record_data_filter", None) page_size: int | None = req_kwargs.pop("size", None) parsed_record_filter: dict[str, Any] | None = req_kwargs or None parsed_subject_filter = parse_filter_args(subject_filter, model=Subject) parsed_visit_filter = parse_filter_args(visit_filter, model=Visit) progress_cb = ( (lambda msg: print_progress(f"[Progress] {msg}")) if interactive and not json_mode else None ) if not json_mode: print_progress(f"Extracting records for study '{study_key}'...") if isinstance(workflow, _RealDataExtractionWorkflow): iter_extra: dict[str, Any] = {} if page_size is not None: iter_extra["size"] = page_size stream = workflow.iter_records_by_criteria( study_key=study_key, record_filter=parsed_record_filter, subject_filter=parsed_subject_filter, visit_filter=parsed_visit_filter, on_progress=progress_cb, record_data_filter=combined_rdf, **iter_extra, ) records, truncated, load_remaining = collect_list_items_with_remainder( stream, effective_limit, ) else: criteria_kwargs: dict[str, Any] = { "study_key": study_key, "record_filter": parsed_record_filter, "subject_filter": parsed_subject_filter, "visit_filter": parsed_visit_filter, } if combined_rdf is not None: criteria_kwargs["record_data_filter"] = combined_rdf if progress_cb is not None: criteria_kwargs["on_progress"] = progress_cb raw_records = workflow.extract_records_by_criteria(**criteria_kwargs) records, truncated, load_remaining = collect_list_items_with_remainder( raw_records, effective_limit, ) custom_phi_fields = ( _resolve_workflow_phi_fields(study_key, sdk=sdk) if mask_phi and (records or load_remaining is not None) else None ) masked_records = _spi_cli.mask_cli_records( records, study_key=study_key, mask_phi=mask_phi, sdk=sdk, custom_phi_fields=custom_phi_fields, ) if resolved_format == "json": display_list(masked_records, "records", output_format="json") return view_models = [_extract_record_view_row(r) for r in masked_records] def _load_more_extracted_records() -> tuple[list[dict[str, Any]], list[Any]]: more = load_remaining() if load_remaining is not None else [] masked_more = _spi_cli.mask_cli_records( more, study_key=study_key, mask_phi=mask_phi, sdk=sdk, custom_phi_fields=custom_phi_fields, ) return [_extract_record_view_row(r) for r in masked_more], masked_more display_list( view_models, "matching records", "No records found matching the criteria.", details=masked_records, truncated=truncated, interactive=False if no_interactive else None, output_format=resolved_format, on_load_all=_load_more_extracted_records if load_remaining is not None else None, entity_kind="records", drain_on_fallback=limit is None, ) def _handle_extract_records(args: argparse.Namespace) -> None: no_interactive = getattr(args, "no_interactive", False) raw_format = getattr(args, "output_format", None) _reject_interactive_json_mode(args.interactive, raw_format) output_format = resolve_output_format(raw_format) study_key = resolve_study_key(extract_parser, args, required=not args.interactive) prepared_query: tuple[dict[str, Any], int | None] | None = None coalesced_rdf = _coalesce_record_data_filter(getattr(args, "record_data_filter", None)) if args.interactive: from .wizard import ensure_interactive_stdin if getattr(args, "limit", None) is not None and getattr(args, "fetch_all", False): print_error("Error: Cannot combine --limit with --all.") sys.exit(1) parse_record_data_filter(coalesced_rdf) ensure_interactive_stdin(force_non_interactive=no_interactive) else: assert study_key is not None validate_cli_path_segment(study_key, name="study_key") from imednet.spi.models import Record, Subject, Visit prepared_query = prepare_list_query( filter_args=args.record_filter, record_data_filter=coalesced_rdf, limit=getattr(args, "limit", None), fetch_all=bool(getattr(args, "fetch_all", False)), output_format=output_format, no_interactive=no_interactive, model=Record, disallow_study_key=False, ) parse_filter_args(args.subject_filter, model=Subject) parse_filter_args(args.visit_filter, model=Visit) with simulation_mode_context(bool(getattr(args, "simulation", False))): extract_records( study_key=study_key, record_filter=args.record_filter, record_data_filter=getattr(args, "record_data_filter", None), subject_filter=args.subject_filter, visit_filter=args.visit_filter, limit=getattr(args, "limit", None), fetch_all=bool(getattr(args, "fetch_all", False)), interactive=args.interactive, no_interactive=no_interactive, output_format=output_format, mask_phi=getattr(args, "mask_phi", True), _prepared_query=prepared_query, ) extract_parser.set_defaults(func=_handle_extract_records) sync_parser = sub.add_parser( "sync-worker", help="Run an idempotent background cache refresh worker." ) add_study_key_args(sync_parser) sync_parser.add_argument( "--interval", type=positive_int, default=900, help="Polling interval in seconds." ) sync_parser.add_argument( "--once", action="store_true", help="Run a single sync cycle and exit." ) add_no_interactive(sync_parser) add_simulation_arg(sync_parser) @with_sdk def sync_worker( sdk: ImednetSDK, study_key: str, interval: int = 900, once: bool = False, ) -> None: from .cached_loader import CachedRecordsLoader sync_worker_cls = _resolve_attr("SyncWorker") sync_worker_cfg_cls = _resolve_attr("SyncWorkerConfig") sync_worker_state_cls = _resolve_attr("SyncWorkerState") worker = sync_worker_cls( CachedRecordsLoader(sdk), # type: ignore[arg-type] config=sync_worker_cfg_cls(study_key=study_key, interval_seconds=interval), ) if once: count = worker.run_once() _emit_line(f"Synced {count} cached records for study '{study_key}'.") return try: with console.status( f"Starting sync worker for study '{study_key}' (interval={interval}s). Press Ctrl+C to stop.", announce_non_interactive=False, ) as status: def on_cycle(cycle: int, count: int) -> None: status.step(f"Study '{study_key}' - cycle {cycle}: synced {count} records.") def on_sleep_tick(cycle: int, remaining: int) -> None: status.update( f"Study '{study_key}' - cycle {cycle}: sleeping ({remaining}s remaining)..." ) try: worker.run_forever(on_cycle=on_cycle, on_sleep_tick=on_sleep_tick) except TypeError: worker.run_forever() if worker.state == sync_worker_state_cls.FAILED: err_detail = f": {worker.last_error}" if worker.last_error is not None else "" print_error( redact_cli_secrets( f"Sync worker failed after {worker.consecutive_failures}/" f"{worker.max_consecutive_failures} consecutive failures{err_detail}" ) ) sys.exit(1) except KeyboardInterrupt: clear_line() worker.stop() _emit_line("Sync worker termination requested. Exiting cleanly.") def _handle_sync_worker(args: argparse.Namespace) -> None: study_key = resolve_study_key(sync_parser, args, required=True) assert study_key is not None validate_cli_path_segment(study_key, name="study_key") with simulation_mode_context(bool(getattr(args, "simulation", False))): sync_worker(study_key=study_key, interval=args.interval, once=args.once) sync_parser.set_defaults(func=_handle_sync_worker) state_parser = sub.add_parser("state", help="Manage high-water mark execution ledger state.") _configure_state_subparsers(state_parser) # UAT command integration uat_parser = sub.add_parser("uat", help="Manage and execute UAT acceptance test pipelines.") uat_sub = uat_parser.add_subparsers(dest="uat_command") uat_parser.set_defaults( func=lambda _args: uat_parser.error("the following arguments are required: uat_command") ) uat_build_spec_parser = uat_sub.add_parser( "build-spec", help="Inspect a study and export a UATSpecification JSON plan.", ) add_study_key_args(uat_build_spec_parser) uat_build_spec_parser.add_argument( "--subject-count", type=int, default=2, help="Number of test subjects to generate (1..100).", ) uat_build_spec_parser.add_argument( "--site-name", default=None, help="Target enrollment-eligible site name for synthetic subjects.", ) uat_build_spec_parser.add_argument( "--form-key", action="append", dest="enabled_form_keys", help="Target active form key to include. Repeat for multiple forms.", ) uat_build_spec_parser.add_argument( "--data-dictionary", dest="data_dictionary", default=None, help="Offline Data Dictionary path (.json, .xml ODM, .csv REDCap, .zip, or CSV directory).", ) uat_build_spec_parser.add_argument( "--seed", type=int, default=None, help="Optional random seed to record in the generated UATSpecification.", ) uat_build_spec_parser.add_argument( "-o", "--output", default=None, help="Output file path for UATSpecification JSON (writes to stdout if omitted).", ) add_no_interactive(uat_build_spec_parser) add_simulation_arg(uat_build_spec_parser) @with_sdk def uat_build_spec( sdk: ImednetSDK, *, study_key: str, subject_count: int = 2, site_name: str | None = None, enabled_form_keys: list[str] | None = None, data_dictionary: DataDictionary | None = None, seed: int | None = None, output_path: str | None = None, ) -> None: from .uat import StudySchemaInspector, UATSpecificationBuilder from .wizard import print_progress try: snapshot = StudySchemaInspector(sdk).inspect(study_key) # type: ignore[arg-type] spec = UATSpecificationBuilder(data_dictionary=data_dictionary).build( snapshot, subject_count=subject_count, site_name=site_name, enabled_form_keys=enabled_form_keys, seed=seed, ) serialized = spec.model_dump_json(indent=2, by_alias=True) if output_path: dest = Path(output_path) dest.parent.mkdir(parents=True, exist_ok=True) dest.write_text(f"{serialized}\n", encoding="utf-8") if not is_json_output_mode(): print_progress(f"Wrote UAT specification for study '{study_key}' to '{dest}'.") return if write_stdout(serialized): flush_stdout() except (ValueError, OSError) as exc: _exit_uat_validation_error(exc) def _handle_uat_build_spec(args: argparse.Namespace) -> None: study_key = resolve_study_key(uat_build_spec_parser, args, required=True) assert study_key is not None validate_cli_path_segment(study_key, name="study_key") try: subject_count = _validate_uat_subject_count(args.subject_count) loaded_dd = _load_uat_data_dictionary(args.data_dictionary, study_key=study_key) except (ValueError, OSError) as exc: _exit_uat_validation_error(exc) with simulation_mode_context(bool(getattr(args, "simulation", False))): uat_build_spec( study_key=study_key, subject_count=subject_count, site_name=args.site_name, enabled_form_keys=args.enabled_form_keys, data_dictionary=loaded_dd, seed=args.seed, output_path=args.output, ) uat_build_spec_parser.set_defaults(func=_handle_uat_build_spec) uat_run_parser = uat_sub.add_parser("run", help="Run the end-to-end UAT pipeline for a study.") add_study_key_args(uat_run_parser) uat_run_parser.add_argument( "--interactive", action="store_true", help="Run in interactive wizard mode." ) uat_run_parser.add_argument( "--subject-count", type=int, default=None, help="Number of test subjects to generate (1..100).", ) uat_run_parser.add_argument( "--site-name", default=None, help="Target site name for synthetic subjects." ) uat_run_parser.add_argument( "--form-key", action="append", dest="enabled_form_keys", help="Target form key to include. Repeat for multiple forms.", ) uat_run_parser.add_argument( "--email-notify", default=None, help="Optional email notification destination or boolean ('true'/'false').", ) uat_run_parser.add_argument( "--spec", dest="spec_path", default=None, help="Path to a saved UATSpecification JSON file.", ) uat_run_parser.add_argument( "--data-dictionary", dest="data_dictionary", default=None, help="Offline Data Dictionary path (.json, .xml ODM, .csv REDCap, .zip, or CSV directory).", ) uat_run_parser.add_argument( "--schema", dest="schema_source", default=None, help=( "Validation schema path (.json, .xml ODM, .csv REDCap, .zip, or CSV dir) " "or 'api' to fetch live study variables." ), ) uat_run_parser.add_argument( "--dry-run", action="store_true", default=False, help="Inspect, generate, and validate synthetic UAT payloads locally without API writes.", ) uat_run_parser.add_argument( "--seed", type=int, default=None, help="Deterministic random seed for synthetic record generation.", ) add_output_format(uat_run_parser) add_no_interactive(uat_run_parser) add_simulation_arg(uat_run_parser) @with_sdk def uat_run( sdk: ImednetSDK, study_key: str | None, interactive: bool = False, subject_count: int | None = None, site_name: str | None = None, enabled_form_keys: list[str] | None = None, email_notify: bool | str | None = None, no_interactive: bool = False, *, spec: Any = None, data_dictionary: DataDictionary | None = None, data_dictionary_path: str | None = None, preloaded_schema: ValidationSchemaProtocol | None = None, schema_source: str | None = None, dry_run: bool = False, seed: int | None = None, output_format: str | None = None, _entered_marker: list[bool] | None = None, ) -> None: if _entered_marker is not None: _entered_marker.append(True) from .uat import UATWorkflow, UATWorkflowState from .wizard import ( ensure_interactive_stdin, print_progress, prompt_email_notify, prompt_input, prompt_study_key, prompt_subject_count, ) _reject_interactive_json_mode(interactive, output_format) resolved_format = resolve_output_format(output_format) json_mode = resolved_format == "json" or (output_format is None and is_json_output_mode()) effective_subject_count: int | None = subject_count if interactive: ensure_interactive_stdin(force_non_interactive=no_interactive) study_key = prompt_study_key(study_key) if subject_count is not None: spec_default_count = subject_count elif spec is not None and getattr(spec, "subject_specs", None): raw_sc = getattr(spec.subject_specs[0], "subject_count", 2) spec_default_count = ( int(raw_sc) if isinstance(raw_sc, int) and not isinstance(raw_sc, bool) else 2 ) elif spec is not None and getattr(spec, "form_specs", None): raw_fc = getattr(spec.form_specs[0], "subject_count", 2) spec_default_count = ( int(raw_fc) if isinstance(raw_fc, int) and not isinstance(raw_fc, bool) else 2 ) else: spec_default_count = 2 spec_default_count = min(max(spec_default_count, 1), 100) prompted_count = prompt_subject_count( "Enter number of test subjects", default=spec_default_count ) if spec is not None and subject_count is None and prompted_count == spec_default_count: effective_subject_count = None else: effective_subject_count = prompted_count site_input = prompt_input( "Enter target site name (leave blank for study default)", default=site_name or "", ) site_name = site_input if site_input else None form_input = prompt_input( "Enter target form keys (comma-separated, leave blank for all forms)", default=",".join(enabled_form_keys) if enabled_form_keys else "", ) if form_input: enabled_form_keys = [k.strip() for k in form_input.split(",") if k.strip()] else: enabled_form_keys = None if not dry_run: email_notify = prompt_email_notify(default=email_notify) elif not study_key: uat_run_parser.error("the following arguments are required: study_key") elif spec is None and effective_subject_count is None: effective_subject_count = 2 assert study_key is not None try: validate_path_segment(study_key, name="study_key") except PathTraversalValidationError as exc: if json_mode: _emit_uat_json_failure( exc, study_key=study_key, dry_run=dry_run, failure_phase="PREFLIGHT", ) validate_cli_path_segment(study_key, name="study_key") if spec is not None and getattr(spec, "study_key", study_key) != study_key: mismatch_msg = ( f"Specification studyKey '{spec.study_key}' does not match study '{study_key}'." ) if json_mode: _emit_uat_json_failure( mismatch_msg, study_key=study_key, dry_run=dry_run, failure_phase="PREFLIGHT", ) _exit_uat_validation_error(mismatch_msg) try: if data_dictionary is None and data_dictionary_path: data_dictionary = _load_uat_data_dictionary( data_dictionary_path, study_key=study_key, ) if ( preloaded_schema is None and schema_source and schema_source.strip().lower() != "api" ): preloaded_schema = load_offline_schema(schema_source, study_key=study_key) resolved_schema = ( preloaded_schema if preloaded_schema is not None else resolve_cli_schema(sdk, study_key, schema_source) ) except Exception as exc: if json_mode: phase = ( "INSPECTING" if schema_source and schema_source.strip().lower() == "api" else "PREFLIGHT" ) _emit_uat_json_failure( exc, study_key=study_key, dry_run=dry_run, failure_phase=phase, ) if isinstance(exc, (ValueError, OSError)): _exit_uat_validation_error(exc) raise def _emit_progress(message: str) -> None: if not json_mode: print_progress(message) if dry_run: active_phase_descriptions = { UATWorkflowState.INSPECTING: ( "[Phase 1/3] Inspecting study schema and metadata..." ), UATWorkflowState.BUILDING_SPEC: "[Phase 2/3] Building test specification...", UATWorkflowState.GENERATING: ( "[Phase 3/3] Generating and validating synthetic test records..." ), } else: active_phase_descriptions = { UATWorkflowState.INSPECTING: ( "[Phase 1/5] Inspecting study schema and metadata..." ), UATWorkflowState.BUILDING_SPEC: "[Phase 2/5] Building test specification...", UATWorkflowState.GENERATING: "[Phase 3/5] Generating synthetic test records...", UATWorkflowState.SUBMITTING: "[Phase 4/5] Submitting records to iMednet API...", UATWorkflowState.MONITORING: ( "[Phase 5/5] Monitoring asynchronous job completion..." ), } def on_phase(phase: UATWorkflowState) -> None: if phase in (UATWorkflowState.COMPLETED, UATWorkflowState.FAILED): return msg = active_phase_descriptions.get(phase, f"UAT Phase transition: {phase.value}") _emit_progress(msg) def on_progress(batch_id: str, status: Any, elapsed: float) -> None: state_val = getattr(status, "state", getattr(status, "status", str(status))) _emit_progress(f"[Job Progress] Batch {batch_id}: {state_val} ({elapsed:.1f}s)") effective_seed = ( seed if seed is not None else (getattr(spec, "seed", None) if spec is not None else None) ) _emit_progress(f"Starting UAT pipeline for study '{study_key}'...") wf_kwargs: dict[str, Any] = { "on_progress": on_progress, "on_phase_change": on_phase, } if effective_seed is not None: wf_kwargs["seed"] = effective_seed if data_dictionary is not None: wf_kwargs["data_dictionary"] = data_dictionary workflow = UATWorkflow( sdk, # type: ignore[arg-type] **wf_kwargs, ) run_kwargs: dict[str, Any] = { "study_key": study_key, "subject_count": effective_subject_count, "site_name": site_name, "enabled_form_keys": enabled_form_keys, "email_notify": email_notify, } if spec is not None: run_kwargs["spec"] = spec if data_dictionary is not None: run_kwargs["data_dictionary"] = data_dictionary if resolved_schema is not None: run_kwargs["schema"] = resolved_schema if effective_seed is not None: run_kwargs["seed"] = effective_seed if dry_run: run_kwargs["dry_run"] = True try: result = workflow.run(**run_kwargs) except Exception as exc: if json_mode: last_res = getattr(workflow, "last_result", None) if last_res is not None and isinstance(getattr(last_res, "run_id", None), str): custom_phi = _resolve_workflow_phi_fields(study_key, sdk=sdk) item = _serialize_uat_run_result( last_res, study_key=study_key, dry_run=dry_run, custom_phi_fields=custom_phi, sdk=sdk, ) emit_json([item], "uat_run", status="failed") sys.exit(1) _emit_uat_json_failure( exc, study_key=study_key, dry_run=dry_run, failure_phase="PREFLIGHT", sdk=sdk, ) if isinstance(exc, (ValueError, OSError)): _exit_uat_validation_error(exc, study_key=study_key, sdk=sdk) raise result_state = getattr(result, "state", None) is_success = bool(result.overall_success) and result_state != UATWorkflowState.FAILED if json_mode: custom_phi = _resolve_workflow_phi_fields(study_key, sdk=sdk) item = _serialize_uat_run_result( result, study_key=study_key, dry_run=dry_run, custom_phi_fields=custom_phi, sdk=sdk, ) emit_json([item], "uat_run", status="complete" if is_success else "failed") if not is_success: sys.exit(1) return if is_success: _emit_progress("[Complete] UAT pipeline execution finished successfully.") else: _emit_progress("[Failed] UAT pipeline execution encountered an error.") _emit_line(result.summary()) if not is_success: sys.exit(1) def _handle_uat_run(args: argparse.Namespace) -> None: no_interactive = getattr(args, "no_interactive", False) raw_format = getattr(args, "output_format", None) dry_run_flag = bool(getattr(args, "dry_run", False)) _reject_interactive_json_mode(args.interactive, raw_format) resolved_format = resolve_output_format(raw_format) json_mode = not args.interactive and ( resolved_format == "json" or (raw_format is None and is_json_output_mode()) ) def _fail_preflight( exc: BaseException | str, *, resolved_study: str | None = None ) -> NoReturn: if json_mode: _emit_uat_json_failure( exc, study_key=resolved_study, dry_run=dry_run_flag, failure_phase="PREFLIGHT", ) _exit_uat_validation_error(exc) raw_flag_study = getattr(args, "study_key_flag", None) raw_pos_study = getattr(args, "study_key", None) candidate_study = ( raw_flag_study if isinstance(raw_flag_study, str) and raw_flag_study.strip() else ( raw_pos_study if isinstance(raw_pos_study, str) and raw_pos_study.strip() else None ) ) subject_count: int | None = None if args.subject_count is not None: try: subject_count = _validate_uat_subject_count(args.subject_count) except ValueError as exc: _fail_preflight(exc, resolved_study=candidate_study) try: normalized_email_notify = parse_email_notify(args.email_notify) except ValueError as exc: _fail_preflight(exc, resolved_study=candidate_study) loaded_spec: Any = None if getattr(args, "spec_path", None): from .uat import UATSpecification spec_file = Path(args.spec_path) if not spec_file.is_file(): _fail_preflight( f"Specification file not found: '{args.spec_path}'", resolved_study=candidate_study, ) try: loaded_spec = UATSpecification.from_json(spec_file) except (ValueError, OSError) as exc: _fail_preflight( f"Invalid UAT specification '{args.spec_path}': {exc}", resolved_study=candidate_study, ) if not args.interactive: if isinstance(raw_flag_study, str) and not raw_flag_study.strip(): _fail_preflight( "Invalid study_key: segment must not be empty.", resolved_study="", ) if isinstance(raw_pos_study, str) and not raw_pos_study.strip(): _fail_preflight( "Invalid study_key: segment must not be empty.", resolved_study="", ) study_key = resolve_study_key(uat_run_parser, args, required=False) if study_key is None and loaded_spec is not None: study_key = loaded_spec.study_key loaded_dd: DataDictionary | None = None preloaded_schema: ValidationSchemaProtocol | None = None raw_dd_path = getattr(args, "data_dictionary", None) raw_schema_src = getattr(args, "schema_source", None) if args.interactive: from .wizard import ensure_interactive_stdin ensure_interactive_stdin(force_non_interactive=no_interactive) if study_key is not None: validate_cli_path_segment(study_key, name="study_key") else: if not study_key: uat_run_parser.error("the following arguments are required: study_key") assert study_key is not None try: validate_path_segment(study_key, name="study_key") except PathTraversalValidationError as exc: if json_mode: _emit_uat_json_failure( exc, study_key=study_key, dry_run=dry_run_flag, failure_phase="PREFLIGHT", ) validate_cli_path_segment(study_key, name="study_key") if loaded_spec is not None and loaded_spec.study_key != study_key: _fail_preflight( f"Specification studyKey '{loaded_spec.study_key}' does not match study '{study_key}'.", resolved_study=study_key, ) try: loaded_dd = _load_uat_data_dictionary(raw_dd_path, study_key=study_key) preloaded_schema = ( load_offline_schema(raw_schema_src, study_key=study_key) if raw_schema_src and raw_schema_src.strip().lower() != "api" else None ) except (ValueError, OSError) as exc: _fail_preflight(exc, resolved_study=study_key) entered_marker: list[bool] = [] uat_call_kwargs: dict[str, Any] = { "study_key": study_key, "interactive": args.interactive, "subject_count": subject_count, "site_name": args.site_name, "enabled_form_keys": args.enabled_form_keys, "email_notify": normalized_email_notify, "no_interactive": no_interactive, "spec": loaded_spec, "data_dictionary": loaded_dd, "data_dictionary_path": raw_dd_path, "preloaded_schema": preloaded_schema, "schema_source": raw_schema_src, "dry_run": dry_run_flag, "seed": getattr(args, "seed", None), "output_format": raw_format, "_entered_marker": entered_marker, } with simulation_mode_context(bool(getattr(args, "simulation", False))): if json_mode: sdk_err_buf = io.StringIO() try: with contextlib.redirect_stderr(sdk_err_buf): uat_run(**uat_call_kwargs) except SystemExit as exc: if not entered_marker and exc.code not in (0, None, 130): captured_err = ( sdk_err_buf.getvalue().strip() or "SDK initialization failed." ) _emit_uat_json_failure( captured_err, study_key=study_key, dry_run=dry_run_flag, failure_phase="PREFLIGHT", ) captured = sdk_err_buf.getvalue() if captured: print_error(captured, end="") raise else: uat_run(**uat_call_kwargs) uat_run_parser.set_defaults(func=_handle_uat_run) validate_std_parser = sub.add_parser( "validate-standards", help="Validate study records and schema against CDISC CDASH and SDTM readiness rules.", ) add_study_key_args(validate_std_parser) validate_std_parser.add_argument( "--profile", "--standards-profile", dest="standards_profile", choices=tuple(PROFILE_REGISTRY.list_profiles()), default="general", help="Regulatory CDISC standards profile (default: general).", ) validate_std_parser.add_argument( "--domain", "--sdtm-domain", dest="sdtm_domain", default=None, help="Optional target SDTM domain code (e.g. DM, AE, LB, VS, CM, EX, MH).", ) validate_std_parser.add_argument( "--min-score", "--min-standards-score", dest="min_standards_score", type=float, default=None, help="Minimum standards readiness score (0-100) required for exit code 0.", ) validate_std_parser.add_argument( "--mask-phi", dest="mask_phi", action=argparse.BooleanOptionalAction, default=True, help="Mask clinical PHI in reported diagnostics (default: enabled).", ) add_output_format(validate_std_parser) add_simulation_arg(validate_std_parser) @with_sdk def validate_standards( sdk: ImednetSDK, study_key: str, standards_profile: str = "general", sdtm_domain: str | None = None, min_standards_score: float | None = None, output_format: str | None = None, mask_phi: bool = True, ) -> None: from imednet.spi.models import ( resolve_sdtm_domain, validate_cdash_variable, ) from imednet.spi.sink_base import ( SinkConfig, build_form_sdtm_domain_map, evaluate_standards_readiness, filter_forms_by_sdtm_domain, merge_form_ids_into_record_filter, record_matches_sdtm_domain, resolve_form_sdtm_domain, ) validate_path_segment(study_key, name="study_key") if min_standards_score is not None and not 0.0 <= min_standards_score <= 100.0: validate_std_parser.error("min-score must be between 0 and 100") resolved_fmt = resolve_output_format(output_format) json_mode = resolved_fmt == "json" or is_json_output_mode() target_domain = ( resolve_sdtm_domain(sdtm_domain, fallback="") if sdtm_domain else "" ) or None with sdk_governance_context(sdk): study_cfg = _resolve_attr("resolve_study_configuration")(study_key) def _fetch_inputs() -> tuple[list[Any], list[Any], list[Any]]: forms = list(sdk.forms.list(study_key=study_key)) variables = list(sdk.variables.list(study_key=study_key)) rec_kwargs: dict[str, Any] = {} if target_domain is not None and forms: matched_for_fetch = filter_forms_by_sdtm_domain( forms, target_domain, study_config=study_cfg, ) if not matched_for_fetch: return forms, variables, [] merged_rec_filter = merge_form_ids_into_record_filter(None, matched_for_fetch) if isinstance(merged_rec_filter, Mapping): rec_kwargs.update(merged_rec_filter) recs = [ rec for rec in sdk.records.list(study_key=study_key, **rec_kwargs) if not bool( rec.get("deleted") if isinstance(rec, Mapping) else getattr(rec, "deleted", False) ) ] return forms, variables, recs if json_mode: raw_forms, raw_variables, raw_records = _fetch_inputs() else: with fetching_status("standards readiness", study_key): raw_forms, raw_variables, raw_records = _fetch_inputs() def _positive_fid(val: Any) -> int | None: if isinstance(val, int) and not isinstance(val, bool): return val if val > 0 else None if isinstance(val, str) and val.strip().isdigit(): parsed = int(val.strip()) return parsed if parsed > 0 else None return None form_id_to_key: dict[int, str] = {} for f_obj in raw_forms: fid = _positive_fid( f_obj.get("form_id", f_obj.get("formId")) if isinstance(f_obj, Mapping) else getattr(f_obj, "form_id", getattr(f_obj, "formId", None)) ) fkey = ( f_obj.get("form_key", f_obj.get("formKey")) if isinstance(f_obj, Mapping) else getattr(f_obj, "form_key", getattr(f_obj, "formKey", None)) ) if fid is not None and fkey: form_id_to_key[fid] = str(fkey) cli_form_map: dict[Any, str] = build_form_sdtm_domain_map( raw_forms, study_config=study_cfg, ) for f_obj in raw_forms: fid = _positive_fid( f_obj.get("form_id", f_obj.get("formId")) if isinstance(f_obj, Mapping) else getattr(f_obj, "form_id", getattr(f_obj, "formId", None)) ) fkey = ( f_obj.get("form_key", f_obj.get("formKey")) if isinstance(f_obj, Mapping) else getattr(f_obj, "form_key", getattr(f_obj, "formKey", None)) ) if fkey and fkey not in cli_form_map: fallback_dom = resolve_sdtm_domain(str(fkey), fallback="") if fallback_dom: cli_form_map[str(fkey)] = fallback_dom if fid is not None and fid not in cli_form_map: cli_form_map[fid] = fallback_dom def _resolve_item_domain(item: Any) -> str: fid = _positive_fid( item.get("form_id", item.get("formId")) if isinstance(item, Mapping) else getattr(item, "form_id", getattr(item, "formId", None)) ) fkey = ( item.get("form_key", item.get("formKey")) if isinstance(item, Mapping) else getattr(item, "form_key", getattr(item, "formKey", None)) ) resolved_dom = resolve_form_sdtm_domain( item, study_config=study_cfg, form_domain_map=cli_form_map or None, fallback="", ) if not resolved_dom and not fkey and fid is not None: mapped_fk = form_id_to_key.get(fid) if mapped_fk: resolved_dom = resolve_form_sdtm_domain( mapped_fk, study_config=study_cfg, form_domain_map=cli_form_map or None, fallback="", ) if not resolved_dom and fid is not None and fid in cli_form_map: resolved_dom = cli_form_map[fid] if resolved_dom: return resolved_dom if isinstance(fkey, str) and fkey.strip(): return resolve_sdtm_domain(fkey, fallback="") raw_dom = ( item.get("DOMAIN") or item.get("domain") if isinstance(item, Mapping) else getattr(item, "domain", None) ) if isinstance(raw_dom, str) and raw_dom.strip(): return resolve_sdtm_domain(raw_dom, fallback="") return "" if target_domain is not None: raw_variables = [ var for var in raw_variables if _resolve_item_domain(var) == target_domain ] raw_records = [ rec for rec in raw_records if record_matches_sdtm_domain( rec, target_domain, form_domain_map=cli_form_map, study_config=study_cfg, ) ] cdash_warnings: list[str] = [] for var in raw_variables: var_name = ( var.get("variable_name", var.get("variableName")) if isinstance(var, Mapping) else getattr(var, "variable_name", getattr(var, "variableName", None)) ) if not var_name: continue inferred_dom = _resolve_item_domain(var) if inferred_dom: valid_cdash, warning = validate_cdash_variable(str(var_name), inferred_dom) if not valid_cdash and warning and warning not in cdash_warnings: cdash_warnings.append(warning) cfg_lookups: dict[str, dict[str, str]] | None = None raw_cfg_lookups = getattr(study_cfg, "terminology_lookups", None) if isinstance(raw_cfg_lookups, Mapping) and raw_cfg_lookups: cfg_lookups = { str(tbl_name): {str(k): str(v) for k, v in tbl_vals.items()} for tbl_name, tbl_vals in raw_cfg_lookups.items() if isinstance(tbl_vals, Mapping) } or None eval_config = SinkConfig( study_key=study_key, mask_phi=mask_phi, standards_profile=standards_profile, sdtm_domain=target_domain, extra={"study_config": study_cfg} if study_cfg is not None else {}, ) report = evaluate_standards_readiness( raw_records, study_key=study_key, config=eval_config, standards_profile=standards_profile, sdtm_domain=target_domain, terminology_lookups=cfg_lookups, form_domain_map=cli_form_map if (cli_form_map or raw_forms) else None, ) custom_phi = list(_resolve_workflow_phi_fields(study_key, sdk=sdk)) if mask_phi else [] if mask_phi and study_cfg is not None: cfg_phi = getattr(study_cfg, "phi_fields", None) or [] if cfg_phi: custom_phi = list(dict.fromkeys([*custom_phi, *(str(f) for f in cfg_phi)])) active_registry = ( build_study_sensitivity_registry(custom_phi) if mask_phi else global_sensitivity_registry ) sensitive_literals: list[str] = [] if mask_phi: seen_literals: set[str] = set() def _collect_record_phi_literals(obj: Any) -> None: if isinstance(obj, Mapping): for k, v in obj.items(): k_str = str(k) if isinstance(v, (Mapping, list, tuple)): _collect_record_phi_literals(v) elif v is not None and not isinstance(v, bool): k_norm = re.sub(r"[^a-z0-9]", "", k_str.lower()) is_birth = k_norm in {"birthdate", "brthdtc", "brthdat", "dob"} if ( is_birth or ( not active_registry.is_exempt(k_str) and active_registry.is_sensitive(k_str) ) or any( re.sub(r"[^a-z0-9]", "", cp.lower()) == k_norm for cp in custom_phi ) ): lit = str(v).strip() if len(lit) >= 2 and lit not in seen_literals: seen_literals.add(lit) sensitive_literals.append(lit) elif isinstance(obj, (list, tuple)): for elem in obj: _collect_record_phi_literals(elem) _collect_record_phi_literals(_to_serializable(raw_records)) sensitive_literals.sort(key=len, reverse=True) def _scrub_cli_diagnostic(text: str) -> str: if not mask_phi or not text: return text scrubbed = redact_sensitive_text(text) scrubbed = str(mask_clinical_phi(scrubbed)) scrubbed = sanitize_diagnostic_text(scrubbed, registry=active_registry) scrubbed = re.sub( r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", "***MASKED***", scrubbed, ) scrubbed = re.sub(r"\b\d{3}-\d{2}-\d{4}\b", "***MASKED***", scrubbed) for lit in sensitive_literals: if lit not in scrubbed: continue if len(lit) <= 3: scrubbed = re.sub( rf"(?<=Subject ){re.escape(lit)}(?= record )", "***MASKED***", scrubbed, ) else: scrubbed = re.sub( rf"(?<![A-Za-z0-9]){re.escape(lit)}(?![A-Za-z0-9])", "***MASKED***", scrubbed, ) return scrubbed raw_all_warnings = list(dict.fromkeys([*report.warnings, *cdash_warnings])) all_warnings = ( list(dict.fromkeys(_scrub_cli_diagnostic(w) for w in raw_all_warnings)) if mask_phi else raw_all_warnings ) threshold = 100.0 if min_standards_score is None else float(min_standards_score) has_domain_level_error = any( v.severity.upper() == "ERROR" and v.field in {*report.domain_scores, "study"} for v in report.violations ) passed = ( False if (report.checked_records == 0 or report.checked_fields == 0 or has_domain_level_error) else (report.is_ready if min_standards_score is None else report.score >= threshold) ) serialized_violations: list[Any] = [] for v in report.violations: if hasattr(v, "model_dump"): dumped_v = dict(v.model_dump()) if mask_phi and isinstance(dumped_v.get("message"), str): dumped_v["message"] = _scrub_cli_diagnostic(dumped_v["message"]) serialized_violations.append(dumped_v) else: serialized_violations.append(_scrub_cli_diagnostic(str(v))) payload = { "study_key": study_key, "profile": report.profile, "domain": target_domain, "score": report.score, "is_ready": report.is_ready, "passed": passed, "checked_records": report.checked_records, "checked_fields": report.checked_fields, "successfully_validated_fields": report.successfully_validated_fields, "domain_scores": dict(report.domain_scores), "warnings": all_warnings, "violations": serialized_violations, } if json_mode: serialized_payload = _to_serializable(payload) sanitized_payload = _spi_cli.mask_cli_models( [serialized_payload], study_key=study_key, mask_phi=mask_phi, sdk=sdk, custom_phi_fields=custom_phi if mask_phi else None, )[0] emit_json([sanitized_payload], "standards_readiness") else: _emit_line( f"Standards Readiness Report — Study: {study_key} (profile: {report.profile})" ) _emit_line( f"Score: {report.score:.2f}/100.00 | Ready: {report.is_ready} | " f"Checked Records: {report.checked_records} | Checked Fields: {report.checked_fields}" ) if report.domain_scores: _emit_line("Domain Scores:") for dom_code, dom_score in sorted(report.domain_scores.items()): _emit_line(f" {dom_code}: {dom_score:.2f}") if all_warnings: _emit_line(f"Warnings ({len(all_warnings)}):") for warn_msg in all_warnings: _emit_line(f" - {warn_msg}") if serialized_violations: _emit_line(f"Violations ({len(serialized_violations)}):") for v_entry in serialized_violations: if isinstance(v_entry, Mapping): v_msg = f"[{v_entry.get('severity', 'ERROR')}] {v_entry.get('field', '')}: {v_entry.get('message', '')}" else: v_msg = str(v_entry) _emit_line(f" - {v_msg}") if not passed: sys.exit(1) def _handle_validate_standards(args: argparse.Namespace) -> None: study_key = resolve_study_key(validate_std_parser, args, required=True) assert study_key is not None validate_cli_path_segment(study_key, name="study_key") if args.min_standards_score is not None and not 0.0 <= args.min_standards_score <= 100.0: validate_std_parser.error("min-score must be between 0 and 100") with simulation_mode_context(bool(getattr(args, "simulation", False))): validate_standards( study_key=study_key, standards_profile=args.standards_profile, sdtm_domain=args.sdtm_domain, min_standards_score=args.min_standards_score, output_format=resolve_output_format(getattr(args, "output_format", None)), mask_phi=getattr(args, "mask_phi", True), ) validate_std_parser.set_defaults(func=_handle_validate_standards) setup_audit_parsers( sub, resolve_attr=_resolve_attr, resolve_phi_fields=_resolve_workflow_phi_fields, emit_line=_emit_line, ) _setup_query_and_triage_parsers(sub)
_WORKFLOW_QUERY_STATUS_CHOICES = tuple(s.value for s in QueryStatus) _WORKFLOW_TRIAGE_STATUS_CHOICES = tuple(s.value for s in TriageStatus) _WORKFLOW_QUERY_SUMMARY_FIELDS = [ "annotation_id", "status", "subject_key", "variable", "annotation_type", "description", "date_created", ] _WORKFLOW_TRIAGE_SUMMARY_FIELDS = [ "item_id", "study_key", "status", "severity", "assignee", ] def _parse_workflow_query_status(value: str) -> str: """Normalize a CLI ``--status`` argument into a ``QueryStatus`` string.""" try: return QueryStatus(value).value except ValueError as exc: valid = ", ".join(_WORKFLOW_QUERY_STATUS_CHOICES) raise argparse.ArgumentTypeError( f"invalid status value: {value!r} (choose from {valid})" ) from exc def _parse_workflow_triage_status(value: str) -> str: """Normalize a CLI ``--status`` argument into a ``TriageStatus`` string.""" if isinstance(value, str) and value.strip(): candidate = value.strip().upper() for member in TriageStatus: if member.value == candidate: return member.value valid = ", ".join(_WORKFLOW_TRIAGE_STATUS_CHOICES) raise argparse.ArgumentTypeError(f"invalid status value: {value!r} (choose from {valid})") def _resolve_validated_study_key( parser: argparse.ArgumentParser, args: argparse.Namespace, ) -> str: """Resolve required ``study_key`` and validate path segment safety before SDK/SQLite calls.""" for raw in (getattr(args, "study_key_flag", None), getattr(args, "study_key", None)): if isinstance(raw, str) and not raw.strip(): validate_cli_path_segment(raw, name="study_key") study_key = resolve_study_key(parser, args, required=True) assert study_key is not None validate_cli_path_segment(study_key, name="study_key") return study_key def _resolve_hybrid_item_id( parser: argparse.ArgumentParser, args: argparse.Namespace, ) -> str: """Resolve hybrid positional/flag ``item_id`` and validate path segment safety.""" flag_val = getattr(args, "item_id_flag", None) pos_val = getattr(args, "item_id", None) for raw in (flag_val, pos_val): if isinstance(raw, str) and not raw.strip(): validate_cli_path_segment(raw, name="item_id") if flag_val is not None and pos_val is not None and flag_val != pos_val: parser.error( f"conflicting values provided for item_id: '{flag_val}' (flag) and '{pos_val}' (positional)" ) resolved = flag_val if flag_val is not None else pos_val if not resolved: parser.error("the following arguments are required: item_id") validate_cli_path_segment(resolved, name="item_id") return str(resolved) def _query_cli_allowed_attributes() -> frozenset[str] | None: """Return endpoint filter allowlist unioned with client-side ``status`` for ``Query``.""" base_attrs = resolve_endpoint_filter_attributes(Query) if base_attrs is None: return None return frozenset(set(base_attrs) | {"status"}) def _open_triage_store(db_path: str | None, *, sdk: Any = None) -> Any: """Instantiate ``TriageStore`` preserving origin partitioning and explicit ``--db-path``.""" store_cls = _resolve_attr("TriageStore") try: if db_path is not None: return store_cls(db_path) if sdk is not None: return store_cls(sdk=sdk) return store_cls() except (OSError, ValueError) as exc: _emit_line(f"Error: {exc}", err=True) sys.exit(1) def _mask_triage_items_for_cli( items: list[TriageItem], *, study_key: str | None, mask_phi: bool, sdk: Any = None, store: Any = None, ) -> list[Any]: """Scrub annotations/history comments and apply CLI PHI masking on ``TriageItem`` models.""" if not mask_phi or not items: return list(items) resolved_study = study_key or (items[0].study_key if items else None) custom_phi = _resolve_workflow_phi_fields(resolved_study, sdk=sdk) registry = build_study_sensitivity_registry(custom_phi) scrub_fn = getattr(store, "_scrub_comment", None) def _scrub_note(text: str, sk: str) -> str: if callable(scrub_fn): return str(scrub_fn(text, study_key=sk, registry=registry)) return sanitize_diagnostic_text(text, registry=registry) scrubbed_items: list[TriageItem] = [] for item in items: item_sk = item.study_key new_anns = [ ann.model_copy(update={"comment": _scrub_note(ann.comment, item_sk)}) for ann in item.annotations ] new_hist = [ entry.model_copy( update={ "comment": ( _scrub_note(entry.comment, item_sk) if entry.comment is not None else None ) } ) for entry in item.history ] scrubbed_items.append( item.model_copy(update={"annotations": new_anns, "history": new_hist}) ) return list( _spi_cli.mask_cli_models( scrubbed_items, study_key=resolved_study, mask_phi=True, sdk=sdk, custom_phi_fields=custom_phi, ) ) def _render_triage_items( items: list[TriageItem], *, study_key: str | None, mask_phi: bool, resolved_format: str, no_interactive: bool, sdk: Any = None, store: Any = None, ) -> None: """Render ``TriageItem`` records in table or JSON format with optional PHI masking.""" rendered = _mask_triage_items_for_cli( items, study_key=study_key, mask_phi=mask_phi, sdk=sdk, store=store, ) if resolved_format == "json": display_list(rendered, "triage_items", output_format="json") return display_list( rendered, "triage items", fields=_WORKFLOW_TRIAGE_SUMMARY_FIELDS, output_format=resolved_format, details=rendered, interactive=False if no_interactive else None, ) def _add_triage_sync_args(sync_parser: argparse.ArgumentParser) -> None: """Attach shared CLI arguments for ``workflows queries sync`` and ``workflows triage sync``.""" add_study_key_args(sync_parser) sync_parser.add_argument( "--db-path", dest="db_path", default=None, action=UniqueStoreAction, help=( "Optional SQLite triage database path " "(defaults to IMEDNET_TRIAGE_DB_PATH or ~/.imednet/<origin>/triage.sqlite3)." ), ) sync_parser.add_argument( "--unresolved", dest="unresolved_only", action="store_true", default=False, help="Synchronize only unresolved (OPEN and ANSWERED) queries.", ) sync_parser.add_argument( "--severity", dest="default_severity", default=None, action=UniqueStoreAction, help="Default severity assigned to newly created triage items (default: medium).", ) sync_parser.add_argument( "-f", "--filter", dest="filter_args", action="append", help="Filter queries before syncing (e.g., 'subjectKey==SUBJ-001', 'status==OPEN').", ) sync_parser.add_argument( "--mask-phi", dest="mask_phi", action=argparse.BooleanOptionalAction, default=True, help="Mask clinical PHI fields with '***MASKED***' (default: enabled).", ) add_no_interactive(sync_parser) add_output_format(sync_parser) add_simulation_arg(sync_parser) def _setup_query_and_triage_parsers(sub: argparse._SubParsersAction[Any]) -> None: """Register ``queries`` and ``triage`` workflow subcommands under ``imednet workflows``.""" queries_parser = sub.add_parser( "queries", help="Inspect study query discrepancy summaries and synchronize triage queues.", ) queries_sub = queries_parser.add_subparsers(dest="queries_command") queries_parser.set_defaults(func=lambda _args: (queries_parser.print_help(), sys.exit(2))) q_list_parser = queries_sub.add_parser( "list", help="List study queries filtered by lifecycle status, subject, or site.", ) add_study_key_args(q_list_parser) q_list_parser.add_argument( "--status", dest="query_status", type=_parse_workflow_query_status, choices=_WORKFLOW_QUERY_STATUS_CHOICES, action=UniqueStoreAction, default=None, help="Filter queries by lifecycle status (OPEN, ANSWERED, CLOSED, CANCELLED).", ) q_list_parser.add_argument( "--unresolved", dest="unresolved_only", action="store_true", default=False, help="Return only unresolved (OPEN and ANSWERED) queries.", ) q_list_parser.add_argument( "-k", "--subject-key", "--subject", dest="subject_key", default=None, action=UniqueStoreAction, help="Filter queries attached to a specific subject key.", ) q_list_parser.add_argument( "--site-key", "--site", dest="site_key", default=None, action=UniqueStoreAction, help="Filter queries across enrolled subjects at a specific site.", ) q_list_parser.add_argument( "-f", "--filter", dest="filter_args", action="append", help="Additional query filter expressions (e.g., 'variable==V_AGE', 'status==OPEN').", ) q_list_parser.add_argument( "--mask-phi", dest="mask_phi", action=argparse.BooleanOptionalAction, default=True, help="Mask clinical PHI fields with '***MASKED***' (default: enabled).", ) add_no_interactive(q_list_parser) add_output_format(q_list_parser) add_simulation_arg(q_list_parser) @with_sdk def _queries_list_cmd( sdk: ImednetSDK, study_key: str, query_status: str | None = None, unresolved_only: bool = False, subject_key: str | None = None, site_key: str | None = None, parsed_filters: dict[str, Any] | None = None, mask_phi: bool = True, output_format: str | None = None, no_interactive: bool = False, ) -> None: resolved_format = resolve_output_format(output_format) workflow = _resolve_attr("QueryManagementWorkflow")(sdk) if resolved_format == "json" or is_json_output_mode(): queries = workflow.list_queries( study_key, status=query_status, unresolved_only=unresolved_only, subject_key=subject_key, site_key=site_key, additional_filter=parsed_filters, ) else: with fetching_status("queries", study_key): queries = workflow.list_queries( study_key, status=query_status, unresolved_only=unresolved_only, subject_key=subject_key, site_key=site_key, additional_filter=parsed_filters, ) items: list[Any] = list(queries) if mask_phi and items: custom_phi = _resolve_workflow_phi_fields(study_key, sdk=sdk) items = list( _spi_cli.mask_cli_models( items, study_key=study_key, mask_phi=True, sdk=sdk, custom_phi_fields=custom_phi, ) ) display_list( items, "queries", fields=_WORKFLOW_QUERY_SUMMARY_FIELDS, output_format=resolved_format, details=items, interactive=False if no_interactive else None, ) def _dispatch_queries_list(args: argparse.Namespace) -> None: study_key = _resolve_validated_study_key(q_list_parser, args) if args.subject_key is not None: validate_cli_path_segment(args.subject_key, name="subject_key") if args.site_key is not None: validate_cli_path_segment(args.site_key, name="site_key") parsed_filters = parse_filter_args( args.filter_args, model=Query, allowed_attributes=_query_cli_allowed_attributes(), disallow_study_key=True, multi_bound_attributes=frozenset({"status"}), ) with simulation_mode_context(bool(getattr(args, "simulation", False))): _queries_list_cmd( study_key=study_key, query_status=args.query_status, unresolved_only=bool(args.unresolved_only), subject_key=args.subject_key, site_key=args.site_key, parsed_filters=parsed_filters, mask_phi=bool(getattr(args, "mask_phi", True)), output_format=getattr(args, "output_format", None), no_interactive=bool(getattr(args, "no_interactive", False)), ) q_list_parser.set_defaults(func=_dispatch_queries_list) q_counts_parser = queries_sub.add_parser( "counts", help="Count study queries grouped by QueryStatus (OPEN, ANSWERED, CLOSED, CANCELLED).", ) add_study_key_args(q_counts_parser) q_counts_parser.add_argument( "-f", "--filter", dest="filter_args", action="append", help="Optional query filter expressions applied before counting.", ) add_no_interactive(q_counts_parser) add_output_format(q_counts_parser) add_simulation_arg(q_counts_parser) @with_sdk def _queries_counts_cmd( sdk: ImednetSDK, study_key: str, parsed_filters: dict[str, Any] | None = None, output_format: str | None = None, ) -> None: resolved_format = resolve_output_format(output_format) workflow = _resolve_attr("QueryManagementWorkflow")(sdk) filter_kwargs = dict(parsed_filters) if parsed_filters else {} if resolved_format == "json" or is_json_output_mode(): raw_counts = workflow.get_query_state_counts(study_key, **filter_kwargs) else: with fetching_status("query counts", study_key): raw_counts = workflow.get_query_state_counts(study_key, **filter_kwargs) ordered = {s.value: int(raw_counts.get(s.value, 0)) for s in QueryStatus} if resolved_format == "json": emit_json( [{"study_key": study_key, **ordered, "total": sum(ordered.values())}], "query_counts", ) return rows = [{"status": k, "count": v} for k, v in ordered.items()] display_list( rows, "query counts", fields=["status", "count"], output_format=resolved_format, interactive=False, ) def _dispatch_queries_counts(args: argparse.Namespace) -> None: study_key = _resolve_validated_study_key(q_counts_parser, args) parsed_filters = parse_filter_args( args.filter_args, model=Query, allowed_attributes=_query_cli_allowed_attributes(), disallow_study_key=True, multi_bound_attributes=frozenset({"status"}), ) with simulation_mode_context(bool(getattr(args, "simulation", False))): _queries_counts_cmd( study_key=study_key, parsed_filters=parsed_filters, output_format=getattr(args, "output_format", None), ) q_counts_parser.set_defaults(func=_dispatch_queries_counts) @with_sdk def _sync_queries_to_triage_cmd( sdk: ImednetSDK, study_key: str, db_path: str | None = None, unresolved_only: bool = False, default_severity: str = "medium", parsed_filters: dict[str, Any] | None = None, mask_phi: bool = True, output_format: str | None = None, no_interactive: bool = False, ) -> None: resolved_format = resolve_output_format(output_format) store = _open_triage_store(db_path, sdk=sdk) workflow = _resolve_attr("QueryManagementWorkflow")(sdk) if resolved_format == "json" or is_json_output_mode(): items = workflow.sync_queries_to_triage( study_key, store=store, additional_filter=parsed_filters, unresolved_only=unresolved_only, default_severity=default_severity, ) else: with fetching_status("triage synchronization", study_key): items = workflow.sync_queries_to_triage( study_key, store=store, additional_filter=parsed_filters, unresolved_only=unresolved_only, default_severity=default_severity, ) _render_triage_items( items, study_key=study_key, mask_phi=mask_phi, resolved_format=resolved_format, no_interactive=no_interactive, sdk=sdk, store=store, ) def _make_sync_dispatcher(target_parser: argparse.ArgumentParser) -> Any: def _dispatch_sync(args: argparse.Namespace) -> None: study_key = _resolve_validated_study_key(target_parser, args) raw_severity = getattr(args, "default_severity", None) severity = "medium" if raw_severity is None else str(raw_severity).strip() if not severity: _emit_line("Error: severity must not be empty.", err=True) sys.exit(1) parsed_filters = parse_filter_args( args.filter_args, model=Query, allowed_attributes=_query_cli_allowed_attributes(), disallow_study_key=True, multi_bound_attributes=frozenset({"status"}), ) with simulation_mode_context(bool(getattr(args, "simulation", False))): _sync_queries_to_triage_cmd( study_key=study_key, db_path=getattr(args, "db_path", None), unresolved_only=bool(getattr(args, "unresolved_only", False)), default_severity=severity, parsed_filters=parsed_filters, mask_phi=bool(getattr(args, "mask_phi", True)), output_format=getattr(args, "output_format", None), no_interactive=bool(getattr(args, "no_interactive", False)), ) return _dispatch_sync q_sync_parser = queries_sub.add_parser( "sync", help="Synchronize study queries into the local SQLite TriageStore queue.", ) _add_triage_sync_args(q_sync_parser) q_sync_parser.set_defaults(func=_make_sync_dispatcher(q_sync_parser)) triage_parser = sub.add_parser( "triage", help="Manage local SQLite query triage queues, reviewer assignments, and transition history.", ) triage_sub = triage_parser.add_subparsers(dest="triage_command") triage_parser.set_defaults(func=lambda _args: (triage_parser.print_help(), sys.exit(2))) t_sync_parser = triage_sub.add_parser( "sync", help="Pull study queries from iMednet into the local SQLite TriageStore queue.", ) _add_triage_sync_args(t_sync_parser) t_sync_parser.set_defaults(func=_make_sync_dispatcher(t_sync_parser)) t_list_parser = triage_sub.add_parser( "list", help="List queued triage items for a study from the local SQLite TriageStore.", ) add_study_key_args(t_list_parser) t_list_parser.add_argument( "--status", dest="triage_status", type=_parse_workflow_triage_status, choices=_WORKFLOW_TRIAGE_STATUS_CHOICES, action=UniqueStoreAction, default=None, help="Filter triage items by status (NEW, UNDER_REVIEW, RESOLVED).", ) t_list_parser.add_argument( "-a", "--assignee", dest="assignee", default=None, action=UniqueStoreAction, help="Filter triage items assigned to a specific reviewer user ID.", ) t_list_parser.add_argument( "--db-path", dest="db_path", default=None, action=UniqueStoreAction, help="Optional SQLite triage database path.", ) t_list_parser.add_argument( "--mask-phi", dest="mask_phi", action=argparse.BooleanOptionalAction, default=True, help="Mask clinical PHI fields with '***MASKED***' (default: enabled).", ) add_no_interactive(t_list_parser) add_output_format(t_list_parser) def _dispatch_triage_list(args: argparse.Namespace) -> None: study_key = _resolve_validated_study_key(t_list_parser, args) resolved_format = resolve_output_format(getattr(args, "output_format", None)) store = _open_triage_store(getattr(args, "db_path", None)) status_enum = TriageStatus(args.triage_status) if args.triage_status else None items = store.get_queue(study_key, status=status_enum) if args.assignee is not None: target_assignee = args.assignee.strip() items = [item for item in items if item.assignee == target_assignee] _render_triage_items( items, study_key=study_key, mask_phi=bool(getattr(args, "mask_phi", True)), resolved_format=resolved_format, no_interactive=bool(getattr(args, "no_interactive", False)), store=store, ) t_list_parser.set_defaults(func=_dispatch_triage_list) t_counts_parser = triage_sub.add_parser( "counts", help="Count local triage queue items grouped by TriageStatus (NEW, UNDER_REVIEW, RESOLVED).", ) add_study_key_args(t_counts_parser) t_counts_parser.add_argument( "--db-path", dest="db_path", default=None, action=UniqueStoreAction, help="Optional SQLite triage database path.", ) add_no_interactive(t_counts_parser) add_output_format(t_counts_parser) def _dispatch_triage_counts(args: argparse.Namespace) -> None: study_key = _resolve_validated_study_key(t_counts_parser, args) resolved_format = resolve_output_format(getattr(args, "output_format", None)) store = _open_triage_store(getattr(args, "db_path", None)) if hasattr(store, "get_status_counts"): raw_counts = store.get_status_counts(study_key) else: raw_counts = {s.value: 0 for s in TriageStatus} for item in store.get_queue(study_key): raw_counts[item.status.value] = raw_counts.get(item.status.value, 0) + 1 ordered = {s.value: int(raw_counts.get(s.value, 0)) for s in TriageStatus} if resolved_format == "json": emit_json( [{"study_key": study_key, **ordered, "total": sum(ordered.values())}], "triage_counts", ) return rows = [{"status": k, "count": v} for k, v in ordered.items()] display_list( rows, "triage counts", fields=["status", "count"], output_format=resolved_format, interactive=False, ) t_counts_parser.set_defaults(func=_dispatch_triage_counts) t_assign_parser = triage_sub.add_parser( "assign", help="Assign ownership of a triage item to a reviewer and optionally add a scrubbed note.", ) t_assign_parser.add_argument( "--item-id", dest="item_id_flag", default=None, action=UniqueStoreAction, help="Identifier of the triage item (e.g. 'DEMO-STUDY:701').", ) t_assign_parser.add_argument( "item_id", nargs="?", default=None, help="Identifier of the triage item (e.g. 'DEMO-STUDY:701').", ) t_assign_parser.add_argument( "-a", "--assignee", dest="assignee_flag", default=None, action=UniqueStoreAction, help="Reviewer user ID to assign ownership to.", ) t_assign_parser.add_argument( "assignee", nargs="?", default=None, help="Reviewer user ID to assign ownership to.", ) t_assign_parser.add_argument( "-u", "--user", "--user-id", dest="user_id", default=None, action=UniqueStoreAction, help="Reviewer user ID recorded on optional --comment annotation (defaults to assignee).", ) t_assign_parser.add_argument( "-c", "--comment", dest="comment", default=None, help="Optional reviewer note scrubbed for PHI and appended to item annotations.", ) t_assign_parser.add_argument( "--db-path", dest="db_path", default=None, action=UniqueStoreAction, help="Optional SQLite triage database path.", ) t_assign_parser.add_argument( "--mask-phi", dest="mask_phi", action=argparse.BooleanOptionalAction, default=True, help="Mask clinical PHI fields with '***MASKED***' (default: enabled).", ) add_no_interactive(t_assign_parser) add_output_format(t_assign_parser) def _dispatch_triage_assign(args: argparse.Namespace) -> None: flag_item = getattr(args, "item_id_flag", None) flag_assignee = getattr(args, "assignee_flag", None) pos_first = getattr(args, "item_id", None) pos_second = getattr(args, "assignee", None) if ( flag_item is not None and pos_first is not None and pos_second is None and flag_assignee is None ): resolved_item_id = flag_item resolved_assignee = pos_first else: resolved_item_id = _resolve_hybrid_item_id(t_assign_parser, args) if flag_assignee is not None and pos_second is not None and flag_assignee != pos_second: t_assign_parser.error( f"conflicting values provided for assignee: '{flag_assignee}' (flag) and '{pos_second}' (positional)" ) resolved_assignee = flag_assignee if flag_assignee is not None else pos_second validate_cli_path_segment(resolved_item_id, name="item_id") if resolved_assignee is None: t_assign_parser.error("the following arguments are required: assignee") cleaned_assignee = str(resolved_assignee).strip() if not cleaned_assignee: _emit_line("Error: assignee must not be empty.", err=True) sys.exit(1) resolved_format = resolve_output_format(getattr(args, "output_format", None)) store = _open_triage_store(getattr(args, "db_path", None)) try: store.assign_item(resolved_item_id, cleaned_assignee) if args.comment is not None: actor = str(args.user_id).strip() if args.user_id is not None else cleaned_assignee if not actor: raise ValueError("Reviewer user_id must not be empty") store.add_annotation(resolved_item_id, actor, args.comment) except ValueError as exc: _emit_line(f"Error: {exc}", err=True) sys.exit(1) updated = store.get_triage_item(resolved_item_id) if updated is None: _emit_line(f"Error: Unknown triage item: {resolved_item_id}", err=True) sys.exit(1) _render_triage_items( [updated], study_key=updated.study_key, mask_phi=bool(getattr(args, "mask_phi", True)), resolved_format=resolved_format, no_interactive=bool(getattr(args, "no_interactive", False)), store=store, ) t_assign_parser.set_defaults(func=_dispatch_triage_assign) t_resolve_parser = triage_sub.add_parser( "resolve", help="Transition a triage item status (defaults to RESOLVED) and record audit history.", ) t_resolve_parser.add_argument( "--item-id", dest="item_id_flag", default=None, action=UniqueStoreAction, help="Identifier of the triage item (e.g. 'DEMO-STUDY:701').", ) t_resolve_parser.add_argument( "item_id", nargs="?", default=None, help="Identifier of the triage item (e.g. 'DEMO-STUDY:701').", ) t_resolve_parser.add_argument( "--status", dest="target_status", type=_parse_workflow_triage_status, choices=_WORKFLOW_TRIAGE_STATUS_CHOICES, action=UniqueStoreAction, default=None, help="Target triage status (NEW, UNDER_REVIEW, RESOLVED; default: RESOLVED).", ) t_resolve_parser.add_argument( "-u", "--user", "--user-id", dest="user_id", default=None, action=UniqueStoreAction, help="Reviewer user ID recorded in transition history (defaults to item assignee or 'cli').", ) t_resolve_parser.add_argument( "-c", "--comment", dest="comment", default=None, help="Optional transition note scrubbed for PHI before persisting.", ) t_resolve_parser.add_argument( "--db-path", dest="db_path", default=None, action=UniqueStoreAction, help="Optional SQLite triage database path.", ) t_resolve_parser.add_argument( "--mask-phi", dest="mask_phi", action=argparse.BooleanOptionalAction, default=True, help="Mask clinical PHI fields with '***MASKED***' (default: enabled).", ) add_no_interactive(t_resolve_parser) add_output_format(t_resolve_parser) def _dispatch_triage_resolve(args: argparse.Namespace) -> None: item_id = _resolve_hybrid_item_id(t_resolve_parser, args) resolved_format = resolve_output_format(getattr(args, "output_format", None)) store = _open_triage_store(getattr(args, "db_path", None)) existing = store.get_triage_item(item_id) if existing is None: _emit_line(f"Error: Unknown triage item: {item_id}", err=True) sys.exit(1) if args.user_id is not None: actor = str(args.user_id).strip() if not actor: _emit_line("Error: user_id must not be empty.", err=True) sys.exit(1) else: actor = existing.assignee or "cli" raw_target = getattr(args, "target_status", None) target_enum = TriageStatus(raw_target) if raw_target is not None else TriageStatus.RESOLVED try: existing.status.validate_transition_to(target_enum) store.update_status(item_id, target_enum, actor, args.comment) except ValueError as exc: _emit_line(f"Error: {exc}", err=True) sys.exit(1) updated = store.get_triage_item(item_id) if updated is None: _emit_line(f"Error: Unknown triage item: {item_id}", err=True) sys.exit(1) _render_triage_items( [updated], study_key=updated.study_key, mask_phi=bool(getattr(args, "mask_phi", True)), resolved_format=resolved_format, no_interactive=bool(getattr(args, "no_interactive", False)), store=store, ) t_resolve_parser.set_defaults(func=_dispatch_triage_resolve) t_history_parser = triage_sub.add_parser( "history", help="Inspect ordered status transition history for a triage item.", ) t_history_parser.add_argument( "--item-id", dest="item_id_flag", default=None, action=UniqueStoreAction, help="Identifier of the triage item (e.g. 'DEMO-STUDY:701').", ) t_history_parser.add_argument( "item_id", nargs="?", default=None, help="Identifier of the triage item (e.g. 'DEMO-STUDY:701').", ) t_history_parser.add_argument( "--db-path", dest="db_path", default=None, action=UniqueStoreAction, help="Optional SQLite triage database path.", ) t_history_parser.add_argument( "--mask-phi", dest="mask_phi", action=argparse.BooleanOptionalAction, default=True, help="Mask clinical PHI fields with '***MASKED***' (default: enabled).", ) add_no_interactive(t_history_parser) add_output_format(t_history_parser) def _dispatch_triage_history(args: argparse.Namespace) -> None: item_id = _resolve_hybrid_item_id(t_history_parser, args) resolved_format = resolve_output_format(getattr(args, "output_format", None)) store = _open_triage_store(getattr(args, "db_path", None)) item = store.get_triage_item(item_id) if item is None: _emit_line(f"Error: Unknown triage item: {item_id}", err=True) sys.exit(1) masked_item = _mask_triage_items_for_cli( [item], study_key=item.study_key, mask_phi=bool(getattr(args, "mask_phi", True)), store=store, )[0] history_entries = list(getattr(masked_item, "history", [])) if resolved_format == "json": emit_json(history_entries, "triage_history") return display_list( history_entries, "triage history entries", empty_msg=f"No transition history recorded for '{item_id}'.", fields=["transition_id", "from_status", "to_status", "user_id", "comment", "timestamp"], output_format=resolved_format, details=history_entries, interactive=False if getattr(args, "no_interactive", False) else None, ) t_history_parser.set_defaults(func=_dispatch_triage_history)
[docs]def setup_subject_parser(subparsers: argparse._SubParsersAction[Any]) -> None: """Set up the subject-data argparse subparsers.""" subj_parser = subparsers.add_parser( "subject-data", help="Retrieve all data for a single subject.", description=( "Retrieve all data for a single subject within a study. " "Arguments may be provided via flags (--study-key, --subject-key/--subject), " "positional arguments (<study_key> <subject_key>), or hybrid combinations " "where a remaining positional argument maps deterministically to the missing key. " "Flags take precedence over positional arguments." ), ) add_study_key_args(subj_parser) subj_parser.add_argument( "-k", "--subject-key", "--subject", dest="subject_key_flag", default=None, action=UniqueStoreAction, help="The key identifying the subject.", ) subj_parser.add_argument( "subject_key", nargs="?", default=None, help="The key identifying the subject." ) subj_parser.add_argument( "--mask-phi", dest="mask_phi", action=argparse.BooleanOptionalAction, default=True, help="Mask clinical PHI fields with '***MASKED***' (default: enabled).", ) add_output_format(subj_parser) add_simulation_arg(subj_parser) @with_sdk def subject_data( sdk: ImednetSDK, study_key: str, subject_key: str, output_format: str | None = None, no_interactive: bool = False, mask_phi: bool = True, ) -> None: resolved_format = resolve_output_format(output_format) workflow = _resolve_attr("SubjectDataWorkflow")(sdk) if resolved_format == "json" or is_json_output_mode(): data = workflow.get_all_subject_data(study_key, subject_key) else: with fetching_status("subject data", study_key): data = workflow.get_all_subject_data(study_key, subject_key) if not isinstance(data, Mapping) and getattr(data, "subject_details", None) is None: print_error(f"Error: Subject '{subject_key}' not found in study '{study_key}'.") sys.exit(1) custom_phi = _resolve_workflow_phi_fields(study_key, sdk=sdk) if mask_phi else None masked_data = _spi_cli.mask_cli_models( [data], study_key=study_key, mask_phi=mask_phi, sdk=sdk, custom_phi_fields=custom_phi, )[0] if resolved_format == "json": emit_json([masked_data], "subject_data") return if isinstance(masked_data, Mapping): subj_dict = masked_data.get("subject_details", masked_data.get("subjectDetails")) subj_map = subj_dict if isinstance(subj_dict, Mapping) else masked_data raw_keywords = subj_map.get("keywords") or [] keywords_str = ", ".join( str( k.get("keyword_name", k) if isinstance(k, Mapping) else getattr(k, "keyword_name", k) ) for k in raw_keywords ) view_row = { "subject_key": subj_map.get("subject_key", subj_map.get("subjectKey")) or subject_key, "status": subj_map.get("subject_status", subj_map.get("subjectStatus")), "site": subj_map.get("site_name", subj_map.get("siteName")), "enrollment_date": subj_map.get( "enrollment_start_date", subj_map.get("enrollmentStartDate") ), "visits": len(masked_data.get("visits") or []), "records": len(masked_data.get("records") or []), "queries": len(masked_data.get("queries") or []), "keywords": keywords_str or None, } else: subj = masked_data.subject_details raw_keywords = getattr(subj, "keywords", None) or [] keywords_str = ", ".join(str(getattr(k, "keyword_name", k)) for k in raw_keywords) view_row = { "subject_key": getattr(subj, "subject_key", None) or subject_key, "status": getattr(subj, "subject_status", None), "site": getattr(subj, "site_name", None), "enrollment_date": getattr(subj, "enrollment_start_date", None), "visits": len(masked_data.visits), "records": len(masked_data.records), "queries": len(masked_data.queries), "keywords": keywords_str or None, } display_list( [view_row], "subject data", details=[masked_data], interactive=False if no_interactive else None, output_format=resolved_format, ) def handle_subject_data(args: argparse.Namespace) -> None: study_key, subject_key = resolve_hybrid_study_and_key( subj_parser, args, secondary_dest="subject_key", secondary_flag_dest="subject_key_flag", ) validate_cli_path_segment(study_key, name="study_key") validate_cli_path_segment(subject_key, name="subject_key") with simulation_mode_context(bool(getattr(args, "simulation", False))): subject_data( study_key=study_key, subject_key=subject_key, output_format=resolve_output_format(getattr(args, "output_format", None)), no_interactive=getattr(args, "no_interactive", False), mask_phi=getattr(args, "mask_phi", True), ) subj_parser.set_defaults(func=handle_subject_data)
[docs]def state_app(args: list[str] | None = None) -> None: """Execute the state app logic directly for tests.""" if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser(description="Manage high-water mark execution ledger state.") add_no_interactive(parser, suppress_default=False) _configure_state_subparsers(parser) parsed = parser.parse_args(args) old_non_interactive = os.environ.get(NON_INTERACTIVE_ENV) old_output_format = os.environ.get(OUTPUT_FORMAT_ENV) try: if getattr(parsed, "no_interactive", False): os.environ[NON_INTERACTIVE_ENV] = "1" explicit_format = getattr(parsed, "output_format", None) if explicit_format == "json": os.environ[OUTPUT_FORMAT_ENV] = "json" elif explicit_format == "table": os.environ.pop(OUTPUT_FORMAT_ENV, None) with cli_execution_guard(): if hasattr(parsed, "func"): parsed.func(parsed) else: parser.print_help() finally: if old_non_interactive is not None: os.environ[NON_INTERACTIVE_ENV] = old_non_interactive else: os.environ.pop(NON_INTERACTIVE_ENV, None) if old_output_format is not None: os.environ[OUTPUT_FORMAT_ENV] = old_output_format else: os.environ.pop(OUTPUT_FORMAT_ENV, None)