Skip to content

netresearch/jira-skill / skills/jira-communication

jira-communication

Flagged

Use when handling Jira issues, sprints, boards, links, fields, worklogs, attachments, or users, or on any Jira intent without a key ("create/find a ticket", "pick a project"). Auto-triggers on Jira URLs and issue keys (PROJ-123). Also use when MCP Atlassian tools fail or are unavailable for Jira Server/DC.

FileKindSize
AGENTS.mdmarkdown2.5 KB
CLAUDE.mdmarkdown9 B
SKILL.mdskill md10.4 KB
evals/evals.jsonconfig7.6 KB
references/agile.mdmarkdown1.9 KB
references/attachments.mdmarkdown4.7 KB
references/comments.mdmarkdown14.4 KB
references/creation.mdmarkdown4.0 KB
references/fields-and-users.mdmarkdown7.7 KB
references/intent-verbs.mdmarkdown13.5 KB
references/issue-editing.mdmarkdown11.6 KB
references/jql-cookbook.mdmarkdown8.0 KB
references/jql-quick-reference.mdmarkdown6.3 KB
references/links.mdmarkdown7.8 KB
references/multi-profile.mdmarkdown3.9 KB
references/no-editorializing.mdmarkdown2.3 KB
references/qa-gather.mdmarkdown12.1 KB
references/troubleshooting.mdmarkdown12.0 KB
references/versions.mdmarkdown7.7 KB
references/watchers.mdmarkdown3.9 KB
references/worklog.mdmarkdown8.6 KB
scripts/core/jira-attachment.pyexecutablescript21.2 KB
scripts/core/jira-issue.pyexecutablescript50.6 KB
scripts/core/jira-search.pyexecutablescript9.6 KB
scripts/core/jira-setup.pyexecutablescript20.0 KB
scripts/core/jira-validate.pyexecutablescript14.2 KB
scripts/core/jira-worklog.pyexecutablescript15.5 KB
scripts/lib/__init__.pyscript742 B
scripts/lib/changelog.pyscript8.0 KB
scripts/lib/client.pyscript26.4 KB
scripts/lib/config.pyscript15.9 KB
scripts/lib/errors.pyscript1.8 KB
scripts/lib/input.pyscript3.5 KB
scripts/lib/jql.pyscript375 B
scripts/lib/markup.pyscript33.2 KB
scripts/lib/markup_cli.pyscript11.3 KB
scripts/lib/output.pyscript6.9 KB
scripts/lib/preview.pyscript10.0 KB
scripts/lib/render.pyscript1.8 KB
scripts/lib/ticket_state.pyscript13.3 KB
scripts/lib/users.pyscript7.5 KB
scripts/utility/jira-fields.pyexecutablescript11.7 KB
scripts/utility/jira-link.pyexecutablescript42.9 KB
scripts/utility/jira-qa-gather.pyexecutablescript26.3 KB
scripts/utility/jira-user.pyexecutablescript9.3 KB
scripts/utility/jira-watchers.pyexecutablescript9.1 KB
scripts/utility/jira-weblink.pyexecutablescript11.2 KB
scripts/utility/jira-worklog-query.pyexecutablescript27.4 KB
scripts/workflow/jira-board.pyexecutablescript7.0 KB
scripts/workflow/jira-comment.pyexecutablescript19.2 KB
scripts/workflow/jira-create.pyexecutablescript24.3 KB
scripts/workflow/jira-move.pyexecutablescript23.5 KB
scripts/workflow/jira-sprint.pyexecutablescript8.1 KB
scripts/workflow/jira-transition.pyexecutablescript33.7 KB
scripts/workflow/jira-version.pyexecutablescript29.4 KB
scripts/workflow/tempo-account.pyexecutablescript9.1 KB

scripts/lib/config.py

View on GitHub
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Netresearch DTT GmbH

"""Environment configuration handling for Jira CLI scripts."""

import json
import os
import re
import sys
from pathlib import Path
from urllib.parse import urlparse

# === INLINE_START: config ===

# Ensure UTF-8 output on Windows — reuse the shared helper so behavior
# stays in sync (see output.py for the full rationale).
if sys.platform == "win32":
    from .output import _ensure_utf8_streams

    _ensure_utf8_streams()


def normalize_netloc(url: str) -> str:
    """Normalize a URL's netloc by lowercasing and stripping default ports."""
    parsed = urlparse(url)
    host = parsed.netloc.lower()
    scheme = parsed.scheme.lower()
    if scheme == "https" and host.endswith(":443"):
        host = host[:-4]
    elif scheme == "http" and host.endswith(":80"):
        host = host[:-3]
    return host


DEFAULT_ENV_FILE = Path.home() / ".env.jira"
PROFILES_FILE = Path.home() / ".jira" / "profiles.json"

# Cloud authentication: JIRA_USERNAME + JIRA_API_TOKEN
# Server/DC authentication: JIRA_PERSONAL_TOKEN (PAT)
REQUIRED_URL = "JIRA_URL"
CLOUD_VARS = ["JIRA_USERNAME", "JIRA_API_TOKEN"]
SERVER_VARS = ["JIRA_PERSONAL_TOKEN"]
OPTIONAL_VARS = ["JIRA_CLOUD"]
ALL_VARS = [REQUIRED_URL] + CLOUD_VARS + SERVER_VARS + OPTIONAL_VARS


def load_env(env_file: str | None = None) -> dict:
    """Load configuration from file with environment variable fallback.

    Priority order:
    1. Explicit env_file parameter (must exist if specified)
    2. ~/.env.jira (if exists)
    3. Environment variables (fallback for missing values)

    Supports two authentication modes:
    - Cloud: JIRA_URL + JIRA_USERNAME + JIRA_API_TOKEN
    - Server/DC: JIRA_URL + JIRA_PERSONAL_TOKEN

    Args:
        env_file: Path to environment file. If specified, file must exist.

    Returns:
        Dictionary of configuration values

    Raises:
        FileNotFoundError: If explicit env_file doesn't exist
    """
    config = {}
    path = Path(env_file) if env_file else DEFAULT_ENV_FILE

    # Load from file if it exists (or raise if explicitly specified but missing)
    if path.exists():
        with open(path) as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith("#") and "=" in line:
                    key, _, value = line.partition("=")
                    key = key.strip()
                    # Strip optional 'export' prefix (bash compatibility)
                    if key.startswith("export "):
                        key = key[7:].strip()
                    config[key] = value.strip().strip('"').strip("'")
    elif env_file:
        # Explicit file was specified but doesn't exist
        raise FileNotFoundError(f"Environment file not found: {path}")

    # Fill in missing values from environment variables
    for var in ALL_VARS:
        if var not in config and var in os.environ:
            config[var] = os.environ[var]

    return config


def validate_config(config: dict) -> list:
    """Validate configuration has all required variables.

    Supports two authentication modes:
    - Cloud: JIRA_URL + JIRA_USERNAME + JIRA_API_TOKEN
    - Server/DC: JIRA_URL + JIRA_PERSONAL_TOKEN

    Args:
        config: Configuration dictionary

    Returns:
        List of validation errors (empty if valid)
    """
    errors = []

    # JIRA_URL is always required
    if REQUIRED_URL not in config or not config[REQUIRED_URL]:
        errors.append(f"Missing required variable: {REQUIRED_URL}")

    # Validate URL format
    if REQUIRED_URL in config and config[REQUIRED_URL]:
        url = config[REQUIRED_URL]
        if not url.startswith(("http://", "https://")):
            errors.append(f"JIRA_URL must start with http:// or https://: {url}")

    # Check for valid authentication configuration
    has_cloud_auth = all(config.get(var) for var in CLOUD_VARS)
    has_server_auth = config.get("JIRA_PERSONAL_TOKEN")

    if not has_cloud_auth and not has_server_auth:
        errors.append(
            "Missing authentication credentials. Provide either:\n"
            "    - JIRA_USERNAME + JIRA_API_TOKEN (for Cloud)\n"
            "    - JIRA_PERSONAL_TOKEN (for Server/DC)"
        )

    return errors


def get_auth_mode(config: dict) -> str:
    """Determine authentication mode from config.

    Args:
        config: Configuration dictionary

    Returns:
        'cloud' for Cloud auth, 'pat' for Personal Access Token
    """
    if config.get("JIRA_PERSONAL_TOKEN"):
        return "pat"
    return "cloud"


def load_profiles() -> dict:
    """Load and validate profiles from ~/.jira/profiles.json.

    Returns:
        Parsed profiles dictionary

    Raises:
        FileNotFoundError: If profiles.json doesn't exist
        ValueError: If profiles.json is invalid
    """
    if not PROFILES_FILE.exists():
        raise FileNotFoundError(f"Profiles file not found: {PROFILES_FILE}")

    try:
        data = json.loads(PROFILES_FILE.read_text())
    except json.JSONDecodeError as e:
        raise ValueError(f"Invalid JSON in {PROFILES_FILE}: {e}") from e

    if not isinstance(data, dict) or "profiles" not in data:
        raise ValueError(f"Invalid profiles format: missing 'profiles' key in {PROFILES_FILE}")

    if not isinstance(data["profiles"], dict) or not data["profiles"]:
        raise ValueError(f"No profiles defined in {PROFILES_FILE}")

    return data


def resolve_profile(
    issue_key: str | None = None, url: str | None = None, profile: str | None = None, project_dir: str | None = None
) -> dict:
    """Resolve a Jira profile using the priority algorithm.

    Priority:
    1. Explicit profile name
    2. Full Jira URL → match host against profile.url
    3. Ticket key → match project prefix against profiles[].projects
    4. .jira-profile file in project directory
    5. Default profile from profiles.json

    Args:
        issue_key: Jira issue key (e.g. WEB-1381)
        url: Full Jira URL
        profile: Explicit profile name
        project_dir: Project directory path to check for .jira-profile

    Returns:
        Profile configuration dictionary with 'name' key added

    Raises:
        FileNotFoundError: If profiles.json doesn't exist
        ValueError: If profile cannot be resolved or is ambiguous
    """
    data = load_profiles()
    profiles = data["profiles"]

    # Step 1: Explicit profile name
    if profile:
        if profile not in profiles:
            available = ", ".join(sorted(profiles.keys()))
            raise ValueError(f"Profile '{profile}' not found. Available: {available}")
        result = dict(profiles[profile])
        result["name"] = profile
        return result

    # Step 2: Full Jira URL → match host (normalized to strip default ports)
    if url:
        input_host = normalize_netloc(url)
        if input_host:
            for name, prof in profiles.items():
                prof_host = normalize_netloc(prof.get("url", ""))
                if prof_host and prof_host == input_host:
                    result = dict(prof)
                    result["name"] = name
                    return result

    # Step 3: Ticket key → match project prefix
    if issue_key:
        match = re.match(r"^([A-Z][A-Z0-9_]+)-\d+$", issue_key)
        if match:
            prefix = match.group(1)
            matching_profiles = []
            for name, prof in profiles.items():
                projects = prof.get("projects")
                if isinstance(projects, list) and prefix in projects:
                    matching_profiles.append(name)

            if len(matching_profiles) == 1:
                result = dict(profiles[matching_profiles[0]])
                result["name"] = matching_profiles[0]
                return result
            elif len(matching_profiles) > 1:
                names = ", ".join(sorted(matching_profiles))
                raise ValueError(f"{prefix} found in profiles: {names}. Use --profile to disambiguate.")

    # Step 4: .jira-profile file in project directory
    if project_dir:
        profile_file = Path(project_dir) / ".jira-profile"
        if profile_file.exists():
            dir_profile = profile_file.read_text().strip()
            if dir_profile in profiles:
                result = dict(profiles[dir_profile])
                result["name"] = dir_profile
                return result
            else:
                print(
                    f"⚠ .jira-profile references unknown profile '{dir_profile}', skipping",
                    file=sys.stderr,
                )

    # Step 5: Default profile
    default_name = data.get("default")
    if default_name and default_name in profiles:
        result = dict(profiles[default_name])
        result["name"] = default_name
        return result

    # No match found
    available = ", ".join(sorted(profiles.keys()))
    raise ValueError(f"Could not resolve profile. Available profiles: {available}. Use --profile to specify one.")


def is_cloud_url(url: str) -> bool:
    """Check if a Jira URL points to Atlassian Cloud.

    Uses strict domain matching: must be exactly 'atlassian.net' or end with
    '.atlassian.net'. This prevents bypass via malicious domains like
    'attacker-atlassian.net.evil.com'.

    Args:
        url: Jira instance URL

    Returns:
        True if the URL is an Atlassian Cloud instance
    """
    netloc = urlparse(url).netloc.lower()
    return netloc == "atlassian.net" or netloc.endswith(".atlassian.net")


def resolve_is_cloud(config: dict) -> bool:
    """Whether ``config`` describes a Jira Cloud site.

    ``JIRA_CLOUD`` set to ``true`` or ``false`` (case-insensitive) wins, so a
    Cloud site behind a proxy or custom domain can be declared as Cloud. Any
    other value, or no value, falls back to ``is_cloud_url(JIRA_URL)``.

    Args:
        config: Configuration dictionary

    Returns:
        True if the site is to be treated as Jira Cloud
    """
    cloud_setting = str(config.get("JIRA_CLOUD", "")).strip().lower()
    if cloud_setting in ("true", "false"):
        return cloud_setting == "true"
    return is_cloud_url(config.get("JIRA_URL", "") or "")


def profile_to_config(prof: dict) -> dict:
    """Convert a profile dict to the env-style config dict used by the client.

    Args:
        prof: Profile dictionary from profiles.json

    Returns:
        Config dictionary compatible with validate_config/get_jira_client

    Raises:
        ValueError: If required fields are missing
    """
    url = prof.get("url")
    if not url:
        raise ValueError("Profile is missing required 'url' field")
    config = {"JIRA_URL": url}

    auth = prof.get("auth", "pat")
    if auth == "cloud":
        if not prof.get("username") or not prof.get("api_token"):
            raise ValueError("Profile is missing required 'username' and/or 'api_token' fields for cloud auth")
        config["JIRA_USERNAME"] = prof["username"]
        config["JIRA_API_TOKEN"] = prof["api_token"]
    else:
        if not prof.get("token"):
            raise ValueError("Profile is missing required 'token' field for PAT auth")
        config["JIRA_PERSONAL_TOKEN"] = prof["token"]

    if "cloud" in prof:
        if not isinstance(prof["cloud"], bool):
            raise ValueError("Profile field 'cloud' must be true or false")
        config["JIRA_CLOUD"] = "true" if prof["cloud"] else "false"

    return config


def load_config(
    profile: str | None = None, env_file: str | None = None, issue_key: str | None = None, url: str | None = None
) -> dict:
    """Unified configuration loader combining profiles and legacy env files.

    Priority:
    1. Explicit --env-file → legacy env file behavior
    2. profiles.json exists → profile resolution
    3. Legacy fallback → ~/.env.jira

    Args:
        profile: Explicit profile name
        env_file: Explicit env file path
        issue_key: Issue key for auto-resolution
        url: Jira URL for auto-resolution

    Returns:
        Config dictionary ready for get_jira_client
    """
    # --env-file always takes precedence
    if env_file:
        return load_env(env_file)

    # Try profile resolution if profiles.json exists
    if PROFILES_FILE.exists():
        try:
            cwd = os.getcwd()
        except OSError:
            cwd = None

        prof = resolve_profile(
            issue_key=issue_key,
            url=url,
            profile=profile,
            project_dir=cwd,
        )
        return profile_to_config(prof)

    # Explicit --profile but no profiles.json
    if profile:
        raise FileNotFoundError(
            f"Profile '{profile}' requested but {PROFILES_FILE} does not exist.\n"
            f"  Run: uv run scripts/core/jira-setup.py --profile {profile}"
        )

    # Legacy fallback
    return load_env()


# ═══════════════════════════════════════════════════════════════════════════════
# Workflow status sets (qa / working / resolved) used by intent verbs
# ═══════════════════════════════════════════════════════════════════════════════

DEFAULT_QA_STATUSES = (
    "QA",
    "Review",
    "In Review",
    "Code Review",
    "Ready for QA",
    "QA2",
    "UAT",
    "Acceptance",
    "Testing",
)
# "QA failed" semantically reads like a QA stage, but functionally it's a
# reject-target ("review verdict: send back to dev"). Putting it in the working
# set means `QA → QA failed` correctly classifies as REJECT rather than FORWARD.
DEFAULT_WORKING_STATUSES = (
    "In Progress",
    "Open",
    "Reopened",
    "To Do",
    "In Development",
    "Backlog",
    "QA failed",
)
DEFAULT_RESOLVED_STATUSES = (
    "Closed",
    "Resolved",
    "Done",
    "Won't Fix",
    "Cancelled",
)


def _split_csv(value: str | None) -> list[str] | None:
    if not value:
        return None
    return [item.strip() for item in value.split(",") if item.strip()]


def load_status_sets(
    profile: str | None = None,
    issue_key: str | None = None,
    url: str | None = None,
) -> dict[str, frozenset[str]]:
    """Resolve qa / working / resolved status name sets.

    Profile resolution mirrors :func:`load_config` — explicit profile name
    wins, otherwise falls back to issue-key project prefix, URL host, the
    project-directory ``.jira-profile`` marker, or the default profile from
    ``profiles.json``. This keeps CLI behaviour consistent: the same profile
    that authenticates also supplies the workflow status sets.

    Priority per set: profile field → env var → built-in default.

    Profile fields: ``qa_status_names``, ``working_status_names``,
    ``resolved_status_names`` (each a JSON list).

    Env vars: ``JIRA_QA_STATUS_NAMES``, ``JIRA_WORKING_STATUS_NAMES``,
    ``JIRA_RESOLVED_STATUS_NAMES`` (comma-separated).
    """
    prof: dict = {}
    if PROFILES_FILE.exists():
        try:
            cwd = os.getcwd()
        except OSError:
            cwd = None
        try:
            prof = resolve_profile(
                profile=profile,
                issue_key=issue_key,
                url=url,
                project_dir=cwd,
            )
        except (ValueError, FileNotFoundError):
            prof = {}

    def _resolve(profile_key: str, env_key: str, defaults: tuple[str, ...]) -> frozenset[str]:
        from_profile = prof.get(profile_key)
        if isinstance(from_profile, list) and from_profile:
            return frozenset(str(s) for s in from_profile)
        from_env = _split_csv(os.environ.get(env_key))
        if from_env:
            return frozenset(from_env)
        return frozenset(defaults)

    return {
        "qa": _resolve("qa_status_names", "JIRA_QA_STATUS_NAMES", DEFAULT_QA_STATUSES),
        "working": _resolve("working_status_names", "JIRA_WORKING_STATUS_NAMES", DEFAULT_WORKING_STATUSES),
        "resolved": _resolve("resolved_status_names", "JIRA_RESOLVED_STATUS_NAMES", DEFAULT_RESOLVED_STATUSES),
    }


# === INLINE_END: config ===
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall