Skip to content

forcedotcom/sf-skills / plugins/builder/agentforce-adlc/skills/agentforce-architecture-analyze

agentforce-architecture-analyze

Verified

Declared architecture snapshot for one Agentforce agent: planner, topics, actions, flows, Apex, prompt templates, and NGA plugins. Renders a human-readable architecture document and Mermaid invocation graph from design-time metadata (not runtime audit rows). TRIGGER when user asks to describe, diagram, inventory, audit, document, or diff (e.g. v3 vs v5) the architecture / action tree / topic structure / tool inventory of a specific agent by agent API name in a specific org. DO NOT TRIGGER for runtime session traces, conversation transcripts, generation timings, or gateway audit chains — this skill reads design-time metadata only (use agentforce-d360-analyze for session traces).

FileKindSize
README.mdmarkdown8.5 KB
SKILL.mdskill md17.5 KB
assets/cli/describe_sobject.yamlconfig317 B
assets/cli/describe_tooling_sobject.yamlconfig347 B
assets/cli/list_metadata_genaiprompttemplate.yamlconfig342 B
assets/cli/org_display.yamlconfig280 B
assets/cli/retrieve_genai_plugin.yamlconfig391 B
assets/cli/show_access_token.yamlconfig700 B
assets/mermaid/action_tree.mmdother986 B
assets/mermaid/data_flow.mmdother893 B
assets/mermaid/dependency_graph.mmdother810 B
assets/mermaid/invocation_sequence.mmdother1004 B
assets/mermaid/planner_state.mmdother813 B
assets/soql/apex_class_bodies_by_ids.soqlother103 B
assets/soql/apex_class_bodies_by_names.soqlother102 B
assets/soql/bot_definition_details.soqlother152 B
assets/soql/bot_version_lookup.soqlother186 B
assets/soql/flow_definition_by_ids.soqlother115 B
assets/soql/flow_definition_ids_by_names.soqlother146 B
assets/soql/flow_definition_view_by_durable_ids.soqlother180 B
assets/soql/flow_metadata_by_id.soqlother73 B
assets/soql/functions_by_plugins.soqlother317 B
assets/soql/planner_attrs_by_parent_ids.soqlother156 B
assets/soql/planner_bundle_functions.soqlother93 B
assets/soql/planner_definition_by_agent_chain.soqlother174 B
assets/soql/plugin_functions_by_plugin_ids.soqlother93 B
assets/soql/plugin_instructions_by_plugin_ids.soqlother168 B
assets/soql/plugins_by_planner.soqlother199 B
references/architecture_sections.mdmarkdown8.3 KB
references/contract.jsonconfig11.7 KB
references/soql_fields.mdmarkdown24.6 KB
scripts/_shared/__init__.pyscript82 B
scripts/_shared/fs_guard.pyexecutablescript12.8 KB
scripts/_shared/paths.pyscript3.9 KB
scripts/_shared/runtime.pyscript2.0 KB
scripts/_shared/sql.pyscript355 B
scripts/cache_check.pyexecutablescript8.9 KB
scripts/config.pyscript5.9 KB
scripts/emit_env.pyexecutablescript5.1 KB
scripts/emit_result.pyexecutablescript10.7 KB
scripts/fetch_soql.pyscript26.1 KB
scripts/finalize.pyexecutablescript11.8 KB
scripts/main.pyscript113.9 KB
scripts/metadata_listing.pyscript9.5 KB
scripts/parallel_retrieve.pyscript3.3 KB
scripts/parse_bundle.pyexecutablescript7.9 KB
scripts/parse_wave.pyexecutablescript36.1 KB
scripts/probe_channels.pyscript11.1 KB
scripts/render_architecture.pyscript40.0 KB
scripts/resolve_bot.pyexecutablescript9.4 KB
scripts/resolve_invocation_target.pyscript4.8 KB
scripts/rest_client.pyscript33.7 KB
scripts/retrieve_planner.pyscript464 B
scripts/sanitize.pyexecutablescript1013 B
scripts/sf_cli.pyscript12.3 KB
scripts/soql_loader.pyscript11.1 KB
scripts/summarize_tree.pyexecutablescript4.6 KB
scripts/tests/__init__.pyscript0 B
scripts/tests/_bootstrap.pyscript843 B
scripts/tests/fixtures/__init__.pyscript0 B
scripts/tests/fixtures/genai_payloads.pyscript12.5 KB
scripts/tests/test_cache_check.pyscript12.6 KB
scripts/tests/test_cache_check_main.pyscript10.4 KB
scripts/tests/test_config.pyscript3.8 KB
scripts/tests/test_end_to_end_fixture.pyscript26.2 KB
scripts/tests/test_finalize.pyscript11.2 KB
scripts/tests/test_flow_children_inflation.pyscript25.6 KB
scripts/tests/test_fs_guard.pyscript4.3 KB
scripts/tests/test_iterative_wave_b.pyscript19.0 KB
scripts/tests/test_main_pipeline.pyscript145.1 KB
scripts/tests/test_parallel_retrieve.pyscript4.8 KB
scripts/tests/test_parse_bundle.pyscript15.6 KB
scripts/tests/test_parse_wave.pyscript26.9 KB
scripts/tests/test_parse_wave_classifiers.pyscript8.6 KB
scripts/tests/test_parse_wave_helpers.pyscript14.3 KB
scripts/tests/test_parse_wave_main.pyscript16.4 KB
scripts/tests/test_per_branch_visited.pyscript9.5 KB
scripts/tests/test_probe_channels.pyscript13.3 KB
scripts/tests/test_probe_cli_recipes.pyscript8.2 KB
scripts/tests/test_render_architecture.pyscript32.7 KB
scripts/tests/test_resolve_bot.pyscript7.5 KB
scripts/tests/test_resolve_creds.pyscript12.0 KB
scripts/tests/test_resolve_invocation_target.pyscript5.2 KB
scripts/tests/test_rest_client.pyscript49.8 KB
scripts/tests/test_runtime_override.pyscript3.9 KB
scripts/tests/test_sf_cli.pyscript17.3 KB
scripts/tests/test_signature_stamping.pyscript18.0 KB
scripts/tests/test_skill_md_pipeline_block.pyscript12.7 KB
scripts/tests/test_soql_loader.pyscript21.3 KB
scripts/tests/test_summarize_tree.pyscript8.9 KB
scripts/tests/test_write_emit_ctx.pyscript19.2 KB
scripts/write_emit_ctx.pyexecutablescript14.1 KB

scripts/sf_cli.py

View on GitHub
"""sf CLI recipe loader — reads assets/cli/*.yaml, runs argv via subprocess.

Security: YAML recipes are loaded via yaml.safe_load only; yaml.load is banned.
PyYAML's `yaml.load` deserializes arbitrary Python objects (including
constructor-injected code in some tags) and must never run on attacker-reachable
YAML. The recipes live inside this repo and are author-controlled, but we
still use `safe_load` as defence in depth — a compromised dist/ or a botched
copy-paste can't escalate to code execution.

the `_SAFE_LOADER` module-level binding is THE loader used everywhere
in this module; tests assert its identity against `yaml.safe_load`.

every stringification of a subprocess.CalledProcessError or related
exception is routed through `rest_client.redact_error` so stderr containing
an access token (rare but observed on some `sf` failure paths) cannot leak
into logs or RESULT blocks.
"""
from __future__ import annotations

import json
import re
import subprocess
from pathlib import Path
from typing import Any, Dict

import yaml

from config import CLI_DIR
# hoisted `redact_text` to module-top alongside
# `redact_error`. Previously `_redact_subprocess_stderr` performed a lazy
# import of the module-private `_redact_text` on every call, which (a)
# tied this module to a name that could be renamed silently and (b) meant
# an ImportError from rest_client would surface only at redaction time —
# possibly in a frame whose locals held the raw, un-redacted stderr.
# Hoisting is safe: rest_client does not import sf_cli (no cycle).
from rest_client import redact_error, redact_text

# the ONE allowed loader for this module. Test asserts identity.
# NEVER change this to yaml.load (which can construct arbitrary Python
# objects via tag hooks).
_SAFE_LOADER = yaml.safe_load


class AuthRequired(RuntimeError):
    """sf CLI returned a known auth-failure pattern.

    Carries a redacted stderr snippet — any bearer token in stderr is scrubbed
    via redact_error before reaching this message.
    """


class SfCliError(RuntimeError):
    """sf CLI returned non-zero exit or JSON status != 0.

    Message is redacted  before construction.
    """


_show_access_token_capability_ok = False
"""Set once the preflight succeeds; the check then never reruns in this
process (401-triggered creds refreshes skip it). Failures are NOT cached,
so a fixed PATH/upgrade is picked up on the next call."""

_SHOW_ACCESS_TOKEN_HELP_SIGNATURE_RE = re.compile(
    r"\$\s*sf\s+org\s+auth\s+show-access-token\b"
)
"""USAGE-line form that real ``--help`` output always contains
(``$ sf org auth show-access-token -o <value> ...``). The bare command name
is not enough: unknown-command notices echo it too
(``Command org:auth:show-access-token not found``,
``show-access-token is not a sf command``). A zero-exit probe whose output
lacks the USAGE form is treated as a failed check."""

_ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]")


def assert_show_access_token_capability() -> None:
    """Fail fast when the installed sf CLI lacks ``sf org auth show-access-token``.

    That command is the only supported runtime token-retrieval path
    (forcedotcom/cli#3560). Probing ``--help`` is cheap, needs no org auth,
    and gives the operator an actionable upgrade message instead of a
    confusing downstream auth failure. A successful probe is cached for
    the process lifetime.

    Exit status alone is not trusted: a CLI build that answers an unknown
    command with exit 0 (e.g. printing top-level help or a "not found"
    notice) would otherwise pass. The probe therefore also requires the
    command's USAGE line (``$ sf org auth show-access-token``) in the
    ANSI-stripped stdout+stderr; if it is absent the check fails and is not
    cached.
    """
    global _show_access_token_capability_ok
    if _show_access_token_capability_ok:
        return
    try:
        proc = subprocess.run(
            ["sf", "org", "auth", "show-access-token", "--help"],
            capture_output=True,
            text=True,
            timeout=30,
            check=True,
        )
    except FileNotFoundError as exc:
        raise SfCliError(
            "sf CLI not found on PATH — install Salesforce CLI first"
        ) from exc
    except subprocess.CalledProcessError as exc:
        safe_detail = _redact_subprocess_stderr(exc.stderr or exc.stdout or "")
        raise SfCliError(
            "sf CLI is missing required command 'sf org auth show-access-token'. "
            "Upgrade/reinstall Salesforce CLI to a version that provides this "
            f"command. Preflight detail: {safe_detail or 'unknown error'}"
        ) from exc
    except subprocess.TimeoutExpired as exc:
        raise SfCliError(
            f"sf CLI capability preflight timed out: {redact_error(exc)}"
        ) from exc
    help_text = _ANSI_ESCAPE_RE.sub(
        "", f"{proc.stdout or ''}\n{proc.stderr or ''}",
    )
    if not _SHOW_ACCESS_TOKEN_HELP_SIGNATURE_RE.search(help_text):
        # Zero exit without the command's help signature — the CLI did not
        # recognise the command. Fail (uncached) like a non-zero exit.
        # Redact before truncating so a token can never be split past the regex.
        safe_detail = _redact_subprocess_stderr(help_text.strip())[:500]
        raise SfCliError(
            "sf CLI is missing required command 'sf org auth show-access-token'. "
            "Upgrade/reinstall Salesforce CLI to a version that provides this "
            "command. Preflight detail: "
            f"{safe_detail or 'help output lacked the command signature'}"
        )
    _show_access_token_capability_ok = True


def _load_recipe(name: str) -> Dict[str, Any]:
    """Read and parse a CLI recipe file with yaml.safe_load.

    _SAFE_LOADER is bound to yaml.safe_load at module top; using it
    here (instead of `yaml.safe_load` directly) makes the identity testable
    and gives a single point to review if the loader ever changes.
    """
    path = CLI_DIR / f"{name}.yaml"
    with path.open("r", encoding="utf-8") as fh:
        recipe = _SAFE_LOADER(fh)
    if not isinstance(recipe, dict):
        raise SfCliError(
            f"recipe {name!r} did not parse to a mapping (got {type(recipe).__name__})"
        )
    return recipe


def _sub(arg: str, params: Dict[str, str]) -> str:
    """Substitute {{KEY}} placeholders in a single argv element.

    Input validation: `params` values are expected to be already-validated
    strings (SKILL.md phase 1 runs fs_guard on every user-supplied input).
    We do not revalidate here because argv substitution is shell-escape-safe
    by construction — subprocess.run with a list argv never invokes a shell.
    """
    out = arg
    for key, value in params.items():
        out = out.replace(f"{{{{{key}}}}}", value)
    return out


def _parse_stdout_json(stdout: str) -> Dict[str, Any]:
    """Parse sf CLI's --json stdout.

    sf CLI emits `{"status": 0, "result": {...}}` on success; malformed
    stdout (e.g. when the CLI crashes before JSON serialization) raises
    SfCliError with a redacted message.
    """
    try:
        return json.loads(stdout)
    except json.JSONDecodeError as e:
        # stdout could in theory contain a token on some crash paths;
        # redact before surfacing.
        raise SfCliError(
            f"sf CLI stdout is not JSON: {redact_error(e)}"
        ) from None


_AUTH_LINE_PREFIX_RE = re.compile(r"^(?:Error|Warning):\s")  # @rule-suppress starter-sec-002 — re.compile, not python compile()


def _stderr_matches_auth(stderr: str, patterns) -> bool:
    """Check if any auth-failure pattern appears on an Error:/Warning: line.

    previously a substring scan across the entire stderr, which
    false-positived on Node ESM warnings ("Warning: @gthoppae/sf-cli-
    plugin-data360 is a linked ESM module") if they happened to echo an
    auth pattern substring. Now we only match on lines starting with
    `Error:` or `Warning:` followed by whitespace. This keeps every
    true-positive we care about (real sf auth errors always surface as
    `Error: NoOrgAuthenticationError ...`) while pruning the noise.

    Matching rules:
      * Line starts with `Error:<ws>` or `Warning:<ws>` (anchored at
        start-of-line, so embedded-in-prose mentions don't match).
      * Pattern is a substring of the REST of that line (after the
        prefix). We strip only the prefix — we do not re-scope to word
        boundaries, since sf auth tokens like `NoOrgAuthenticationError`
        are always well-formed identifiers without adjacent alphanum.
      * Empty stderr / empty patterns → no match.
    """
    if not stderr or not patterns:
        return False
    for line in stderr.splitlines():
        m = _AUTH_LINE_PREFIX_RE.match(line)
        if not m:
            continue
        tail = line[m.end():]
        if any(p in tail for p in patterns):
            return True
    return False


def run_sf(name: str, **params: str) -> Dict[str, Any]:
    """Execute a recipe-defined sf CLI command and return parsed stdout.

    Steps:
      1. Load recipe (yaml.safe_load).
      2. Enforce required_params.
      3. Substitute {{KEY}} into argv.
      4. subprocess.run with list argv (no shell, no bash -c).
      5. Parse stdout JSON; check `status == 0`.
      6. On failure: classify as AuthRequired (stderr pattern match) or
         SfCliError; every message is redacted via redact_error .

    Exception semantics:
      * AuthRequired — user needs to `sf org login`
      * SfCliError   — anything else (timeout, non-zero exit, JSON parse,
        status != 0)

    NEVER uses shell=True. NEVER calls log.exception(). NEVER echoes raw
    stderr without redaction .
    """
    recipe = _load_recipe(name)

    required = set(recipe.get("required_params") or [])
    missing = required - params.keys()
    if missing:
        raise SfCliError(f"missing required params for {name!r}: {sorted(missing)}")

    argv_template = recipe.get("argv") or []
    if not isinstance(argv_template, list):
        raise SfCliError(f"recipe {name!r} argv must be a list")

    argv = [_sub(str(e), params) for e in argv_template]
    timeout = int(recipe.get("timeout_seconds", 60))
    auth_patterns = recipe.get("auth_required_stderr_patterns") or []

    try:
        cp = subprocess.run(
            argv,
            capture_output=True,
            text=True,
            timeout=timeout,
            check=False,
        )
    except subprocess.TimeoutExpired as e:
        # timeout exceptions carry stderr via e.stderr — redact.
        raise SfCliError(
            f"sf CLI {name!r} timed out after {timeout}s: {redact_error(e)}"
        ) from None
    except (OSError, subprocess.SubprocessError) as e:
        # any subprocess-layer error gets redacted.
        raise SfCliError(
            f"sf CLI {name!r} invocation failed: {redact_error(e)}"
        ) from None

    # Even on nonzero exit sf CLI usually still emits JSON on stdout; try
    # to parse before deciding failure mode.
    try:
        data = _parse_stdout_json(cp.stdout) if cp.stdout else {}
    except SfCliError:
        data = {}

    status_field = data.get("status", 0) if isinstance(data, dict) else 1
    if cp.returncode != 0 or status_field != 0:
        # stderr could contain a token on some failure paths; redact
        # the ENTIRE string before deciding how to classify or what to show.
        safe_stderr = _redact_subprocess_stderr(cp.stderr)
        if _stderr_matches_auth(cp.stderr, auth_patterns):
            raise AuthRequired(safe_stderr or "auth required")
        # Include exit code + JSON status in the message (both are
        # numeric/well-known, no token risk) plus the redacted stderr tail.
        raise SfCliError(
            f"sf CLI {name!r} failed "
            f"(exit={cp.returncode}, json_status={status_field}): {safe_stderr}"
        )

    return data


def _redact_subprocess_stderr(stderr: str) -> str:
    """run stderr text through the rest_client redaction regexes.

    stderr may contain `Authorization: Bearer ...` or `accessToken=...` if
    the sf CLI echoes a failing request; scrub before surfacing.

    calls the public `redact_text` (imported at module
    top). Previously imported the module-private `_redact_text` lazily on
    every call — a rename could have silently broken redaction, and an
    ImportError would have propagated through `run_sf` with the raw stderr
    still live in the traceback's frame locals.
    """
    return redact_text(stderr or "")
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall