Skip to content

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

agentforce-d360-analyze

Verified

Data Cloud 360° view of a single Agentforce session. TRIGGER when user asks to trace, inspect, summarize, or describe a specific Agentforce session by session id (Agent Session UUID `019d…` or MessagingSession id `0Mw…`). Also triggers on session discovery — find/list/search sessions by time, agent, channel, outcome, or conversation text — when the user has no session id yet. DO NOT TRIGGER for design-time architecture questions (use agentforce-architecture-analyze instead) or for runtime perf/latency/SLO questions that require platform telemetry beyond Data Cloud.

FileKindSize
README.mdmarkdown6.2 KB
SKILL.mdskill md13.2 KB
assets/dc/app_generation.sqlother1.9 KB
assets/dc/content_category.sqlother1.5 KB
assets/dc/content_quality.sqlother1.3 KB
assets/dc/discover_sessions.sqlother2.3 KB
assets/dc/feedback.sqlother1.5 KB
assets/dc/feedback_details.sqlother1.3 KB
assets/dc/gateway_records.sqlother1.6 KB
assets/dc/gateway_request_llm.sqlother1.6 KB
assets/dc/gateway_request_metadata.sqlother1.5 KB
assets/dc/gateway_request_tags.sqlother1.4 KB
assets/dc/gateway_requests.sqlother3.4 KB
assets/dc/gateway_responses.sqlother1.7 KB
assets/dc/generations.sqlother1.9 KB
assets/dc/interactions.sqlother2.0 KB
assets/dc/messages.sqlother2.1 KB
assets/dc/messaging_session.sqlother1.7 KB
assets/dc/moment_interactions.sqlother1.4 KB
assets/dc/moments.sqlother1.5 KB
assets/dc/participants.sqlother1.8 KB
assets/dc/sessions.sqlother3.0 KB
assets/dc/steps.sqlother2.6 KB
assets/dc/tag_associations.sqlother1.7 KB
assets/dc/tag_definition_associations.sqlother1.4 KB
assets/dc/tag_definitions.sqlother1.8 KB
assets/dc/tags.sqlother1.3 KB
assets/dc/telemetry_spans.sqlother2.1 KB
references/artifacts.mdmarkdown2.7 KB
references/dc_dmo_fields.mdmarkdown42.1 KB
references/dc_pipeline_contract.mdmarkdown26.3 KB
scripts/_shared/__init__.pyscript122 B
scripts/_shared/cli_override.pyscript3.3 KB
scripts/_shared/fs_guard.pyexecutablescript13.2 KB
scripts/_shared/paths.pyscript5.8 KB
scripts/_shared/runtime.pyscript2.0 KB
scripts/_shared/sql.pyscript548 B
scripts/assemble_dc.pyscript69.6 KB
scripts/config.pyscript1.8 KB
scripts/dc.pyscript13.8 KB
scripts/discover_sessions.pyscript21.1 KB
scripts/fetch_dc.pyscript45.1 KB
scripts/render_dc.pyscript69.7 KB
scripts/resolve_session.pyscript10.8 KB
scripts/storage.pyscript3.1 KB
scripts/tests/__init__.pyscript0 B
scripts/tests/_bootstrap.pyscript483 B
scripts/tests/fixtures/__init__.pyscript0 B
scripts/tests/fixtures/synthetic_session.pyscript14.6 KB
scripts/tests/test_assemble_dc_bootstrap_and_mode.pyscript4.2 KB
scripts/tests/test_assemble_dc_gateway_direct.pyscript8.3 KB
scripts/tests/test_assemble_dc_gateway_direct_integration.pyscript6.4 KB
scripts/tests/test_assemble_dc_helpers.pyscript10.0 KB
scripts/tests/test_assemble_dc_integration.pyscript9.3 KB
scripts/tests/test_dc_and_resolve_session.pyscript26.7 KB
scripts/tests/test_default_target_org.pyscript18.8 KB
scripts/tests/test_discover_sessions.pyscript19.0 KB
scripts/tests/test_discover_sessions_grep_ci.pyscript8.2 KB
scripts/tests/test_fetch_dc_helpers.pyscript10.6 KB
scripts/tests/test_fetch_dc_identity.pyscript22.0 KB
scripts/tests/test_fetch_dc_main.pyscript9.4 KB
scripts/tests/test_fetch_dc_waterfall.pyscript8.6 KB
scripts/tests/test_fetch_dc_waterfall_full.pyscript11.2 KB
scripts/tests/test_identity_coherence.pyscript13.8 KB
scripts/tests/test_render_dc_branches.pyscript9.9 KB
scripts/tests/test_render_dc_gateway_direct.pyscript5.1 KB
scripts/tests/test_render_dc_helpers.pyscript10.5 KB
scripts/tests/test_render_dc_integration.pyscript7.7 KB
scripts/tests/test_render_dc_planner_llm_calls.pyscript11.8 KB
scripts/tests/test_render_dc_show_prompts_gating.pyscript8.7 KB
scripts/tests/test_resolve_from_disk.pyscript4.1 KB
scripts/tests/test_resolve_session_main.pyscript5.2 KB
scripts/tests/test_runtime_override.pyscript4.2 KB
scripts/tests/test_session_shape.pyscript3.5 KB
scripts/tests/test_session_shape_dropped_by_stdm.pyscript3.5 KB
scripts/tests/test_skill_md_prefix_block.pyscript6.8 KB

scripts/_shared/fs_guard.py

View on GitHub
#!/usr/bin/env python3
r"""Filesystem-safety and input-validation guard.

One script, six check types. Emits a STATUS=INVALID_INPUT RESULT block on
failure + tees to $ERROR_TEE on disk + exits 1.

Guiding principle: the agent MUST suffix every call with `|| exit 1` — Python
`sys.exit(1)` only terminates this subprocess, not the parent bash. A bare
call without `|| exit 1` silently continues past a failed guard, which is
the worst possible failure mode for a security check.

Check types:
    symlink     — path must NOT be a symlink (rejects pre-planted attacker bait)
    owned       — path must be owned by current UID (rejects foreign-owned dirs)
    uuid          — value must match ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$
    org_id_15     — value must match ^[A-Za-z0-9]{15}$ (Salesforce org ID slice)
    api_name      — value must match ^[A-Za-z0-9_]+$ (Salesforce API identifier)
    api_version   — value must match ^v[0-9]+\.[0-9]+$ (e.g. v60.0)
    agent_version — value must match ^v[0-9]+$ (e.g. v5 — Agentforce agent version, no dot-minor)
    not_empty     — value must be non-empty string

Python-importable API:
    validate_api_name(value, label="...")      — raises ValidationError on bad input
    validate_api_version(value, label="...")   — raises ValidationError on bad input
    validate_agent_version(value, label="...") — raises ValidationError on bad input
    validate_org_id_15(value, label="...")     — raises ValidationError on bad input
    ValidationError                            — carries (label, reason)

The Python API is used by in-process callers (SOQL loader, path builders in
config.py) that need a raise-based boundary rather than the process-exit
CLI behavior. Regex is shared — do NOT duplicate API_NAME_RE / API_VERSION_RE.

Usage:
    python3 fs_guard.py <value> <label> <check> || exit 1

    # Input validation
    python3 fs_guard.py "$AGENT_API_NAME" agent_api_name api_name || exit 1
    python3 fs_guard.py "$ORG_ALIAS"      org_alias      not_empty || exit 1

    # Filesystem safety
    python3 fs_guard.py "$WORK_DIR"  WORK_DIR  symlink || exit 1
    python3 fs_guard.py "$WORK_DIR"  WORK_DIR  owned   || exit 1
    python3 fs_guard.py "$ORG_ID_15" ORG_ID_15 org_id_15 || exit 1

Inputs:
    argv[1]     value or path to check
    argv[2]     label (appears in ERROR_DETAIL; used to identify which guard tripped)
    argv[3]     check type (one of the 6 above)
    env         $ERROR_TEE (optional): path to disk-tee file. Defaults to
                $HOME/.vibe/data/investigating-agentforce-d360/_last_error_result.txt.
                Also reads $AGENT_API_NAME / $ORG_ID_18 / $ORG_ID_15 for
                RESULT-block context if set.

Outputs:
    on failure: STATUS=INVALID_INPUT RESULT block on stdout + tee to disk, exit 1
    on success: silent, exit 0
    on bad argv: exit 1 with a minimal ERROR_DETAIL ("fs_guard internal: ...")
"""
import os
import pathlib
import re
import sys

# Anchored \A...\Z (not ^...$) — Python's `$` matches before a trailing
# newline, so "00DTESTORG12345\n" passes ^...$ + .match(). Every call
# site below MUST use .fullmatch() for the same reason; .match() is
# unsafe even with \A...\Z anchors. Mirrors the pattern in
# _shared/paths.py SESSION_ID_RE.
UUID_RE = re.compile(r"\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\Z")  # @rule-suppress starter-sec-002 — re.compile, not eval/exec
ORG_ID_15_RE = re.compile(r"\A[A-Za-z0-9]{15}\Z")  # @rule-suppress starter-sec-002 — re.compile, not eval/exec
API_NAME_RE = re.compile(r"\A[A-Za-z0-9_]+\Z")  # @rule-suppress starter-sec-002 — re.compile, not eval/exec
# P0-5: api_version check — matches `v60.0`, `v66.0`, etc. Used before any
# Path composition that embeds the api_version segment.
API_VERSION_RE = re.compile(r"\Av[0-9]+\.[0-9]+\Z")  # @rule-suppress starter-sec-002 — re.compile, not eval/exec
# Agent-version check — matches Agentforce version identifiers (`v1`, `v5`,
# `v12`). Deliberately stricter than api_name (rejects free-form names like
# `release_1`) and looser than api_version (rejects `v66.0` which is a REST
# API version, never an agent version). Lives on its own so callers that
# embed agent_version in a filesystem path get the tight regex, not the
# permissive api_name fallback.
AGENT_VERSION_RE = re.compile(r"\Av[0-9]+\Z")  # @rule-suppress starter-sec-002 — re.compile, not eval/exec
VALID_CHECKS = {"symlink", "owned", "uuid", "org_id_15", "api_name", "api_version", "agent_version", "not_empty"}


# -----------------------------------------------------------------------------
# Python-importable API (P0-1, P0-5)
# -----------------------------------------------------------------------------
# In-process callers (soql_loader.load_soql, config.build_*_dir) need a
# raise-based validation boundary, distinct from the CLI script's exit-1
# behavior. The regexes are shared with the CLI checks above — do NOT
# duplicate. If a regex changes, both surfaces update in lockstep.


class ValidationError(ValueError):
    """Raised by the Python-importable validators on bad input.

    Carries the label (which field failed) + reason. Callers (e.g.
    soql_loader.load_soql) convert this into `_unresolved[]` entries or
    RESULT-level INVALID_INPUT responses as appropriate.
    """

    def __init__(self, label: str, reason: str) -> None:
        self.label = label
        self.reason = reason
        super().__init__(f"{label}: {reason}")


def validate_api_name(value, label: str = "value") -> None:
    """Validate `value` against ^[A-Za-z0-9_]+$ (Salesforce API identifier).

    P0-1: used by soql_loader.load_soql at the substitution boundary to catch
    injection attempts in names pulled from Bot XML, Flow.Metadata, ApexClass
    SymbolTable, etc.

    P0-5: used by config.build_*_dir helpers for path components that must
    not contain `..`, `/`, or other traversal characters.

    Raises ValidationError on any of: None, non-string, empty, regex miss.
    """
    if value is None:
        raise ValidationError(label, "is None")
    if not isinstance(value, str):
        raise ValidationError(label, f"must be str, got {type(value).__name__}")
    if not value:
        raise ValidationError(label, "must not be empty")
    if not API_NAME_RE.fullmatch(value):
        # Preview first 20 chars so logs/_unresolved entries carry enough
        # context to debug, without dumping an unbounded attacker-controlled
        # string into output.
        preview = value[:20]
        raise ValidationError(
            label,
            f"does not match [A-Za-z0-9_]+ (preview={preview!r})",
        )


def validate_api_version(value, label: str = "api_version") -> None:
    """Validate `value` against ^v[0-9]+\\.[0-9]+$ (Salesforce API version).

    P0-5: used by config.build_*_dir helpers. api_version is returned by
    `sf org display` and later embedded in cache paths; reject anything that
    could escape the cache subtree.
    """
    if value is None:
        raise ValidationError(label, "is None")
    if not isinstance(value, str):
        raise ValidationError(label, f"must be str, got {type(value).__name__}")
    if not value:
        raise ValidationError(label, "must not be empty")
    if not API_VERSION_RE.fullmatch(value):
        preview = value[:20]
        raise ValidationError(
            label,
            f"does not match v<major>.<minor> (preview={preview!r})",
        )


def validate_agent_version(value, label: str = "agent_version") -> None:
    """Validate `value` against ^v[0-9]+$ (Agentforce agent version).

    Strictly `v<digits>` with no dot-minor — matches the shape Agentforce
    actually uses (`v1`, `v5`, `v12`). Rejects `release_1`, `v66.0`, `FOO`,
    and anything else that could silently slip past a permissive api_name
    check and land in a filesystem path.

    P0-5: used by path-builder helpers for the agent_version segment.
    """
    if value is None:
        raise ValidationError(label, "is None")
    if not isinstance(value, str):
        raise ValidationError(label, f"must be str, got {type(value).__name__}")
    if not value:
        raise ValidationError(label, "must not be empty")
    if not AGENT_VERSION_RE.fullmatch(value):
        preview = value[:20]
        raise ValidationError(
            label,
            f"does not match v<digits> (preview={preview!r})",
        )


def validate_org_id_15(value, label: str = "org_id_15") -> None:
    """Validate `value` against ^[A-Za-z0-9]{15}$ (Salesforce 15-char org ID).

    P0-5: stricter than validate_api_name — enforces exact 15 chars AND
    no underscores. `org_id_15` always comes from a Salesforce-generated
    field, never from free-form input.
    """
    if value is None:
        raise ValidationError(label, "is None")
    if not isinstance(value, str):
        raise ValidationError(label, f"must be str, got {type(value).__name__}")
    if not value:
        raise ValidationError(label, "must not be empty")
    if not ORG_ID_15_RE.fullmatch(value):
        preview = value[:20]
        raise ValidationError(
            label,
            f"must be exactly 15 alphanumeric chars (preview={preview!r})",
        )


def scrub(s: str) -> str:
    # Same rules as sanitize.py; duplicated locally so this script has no
    # intra-skill imports. Keeps the agent-script boundary clean.
    bad = set("`$\"\\\r\t\0\n")
    return "".join(c for c in (s or "") if c not in bad)


def emit_failure(reason: str, label: str) -> None:
    agent_api_name = scrub(os.environ.get("AGENT_API_NAME", ""))
    org_id_18 = scrub(os.environ.get("ORG_ID_18", ""))
    org_id_15 = scrub(os.environ.get("ORG_ID_15", ""))
    label_safe = scrub(label)
    reason_safe = scrub(reason)

    block = (
        "=== RESULT ===\n"
        "STATUS=INVALID_INPUT\n"
        f"ERROR_DETAIL={label_safe}: {reason_safe}\n"
        f"AGENT_API_NAME={agent_api_name}\n"
        f"ORG_ID_18={org_id_18}\n"
        f"ORG_ID_15={org_id_15}\n"
    )

    # Default ERROR_TEE lives under the skill-scoped data root. Runtime-agnostic
    # default mirrors runtime.resolve_data_root() in the sibling runtime module
    # (duplicated rather than imported because fs_guard.py is also invoked
    # standalone from SKILL.md bash, where the override hook isn't active).
    tee_default = str(
        pathlib.Path.home()
        / ".vibe"
        / "data"
        / "investigating-agentforce-d360"
        / "_last_error_result.txt"
    )
    tee_path = os.environ.get("ERROR_TEE") or tee_default
    try:
        p = pathlib.Path(tee_path)
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(block)
    except OSError:
        pass

    sys.stdout.write(block)
    sys.exit(1)


def check_symlink(value: str, label: str) -> None:
    if pathlib.Path(value).is_symlink():
        emit_failure(f"path is a symlink (refusing to follow): {value}", label)


def check_owned(value: str, label: str) -> None:
    p = pathlib.Path(value)
    if not p.exists():
        return
    try:
        st = p.stat()
    except OSError as e:
        emit_failure(f"stat failed: {e}", label)
        return
    if st.st_uid != os.getuid():
        emit_failure(f"foreign-owned (uid {st.st_uid} != current {os.getuid()}): {value}", label)


def check_uuid(value: str, label: str) -> None:
    if not UUID_RE.fullmatch(value):
        emit_failure("does not match UUID pattern (8-4-4-4-12 lowercase hex)", label)


def check_org_id_15(value: str, label: str) -> None:
    if not ORG_ID_15_RE.fullmatch(value):
        emit_failure("must be exactly 15 alphanumeric characters", label)


def check_api_name(value: str, label: str) -> None:
    if not API_NAME_RE.fullmatch(value):
        emit_failure("does not match [A-Za-z0-9_]+ (Salesforce API name rules)", label)


def check_api_version(value: str, label: str) -> None:
    # P0-5: api_version must be `vNN.N` — no slashes, no dots beyond the one,
    # no path-traversal sequences.
    if not API_VERSION_RE.fullmatch(value):
        emit_failure("does not match v<major>.<minor> (e.g. v60.0)", label)


def check_agent_version(value: str, label: str) -> None:
    # Agent version must be `v<digits>` — no dots, no slashes.
    if not AGENT_VERSION_RE.fullmatch(value):
        emit_failure("does not match v<digits> (e.g. v5)", label)


def check_not_empty(value: str, label: str) -> None:
    if not value:
        emit_failure("must not be empty", label)


CHECKS = {
    "symlink": check_symlink,
    "owned": check_owned,
    "uuid": check_uuid,
    "org_id_15": check_org_id_15,
    "api_name": check_api_name,
    "api_version": check_api_version,
    "agent_version": check_agent_version,
    "not_empty": check_not_empty,
}


def main() -> int:
    if len(sys.argv) != 4:
        sys.stdout.write(
            "=== RESULT ===\n"
            "STATUS=INVALID_INPUT\n"
            "ERROR_DETAIL=fs_guard internal: wrong argv count (need value, label, check)\n"
        )
        return 1
    value, label, check = sys.argv[1], sys.argv[2], sys.argv[3]

    for arg in (value, label, check):
        if any(c == "\0" or (ord(c) < 0x20 and c not in "\t\n") for c in arg):
            emit_failure("argv contains control characters", label or "argv")

    if check not in VALID_CHECKS:
        emit_failure(f"unknown check type '{check}' (valid: {', '.join(sorted(VALID_CHECKS))})", label)

    CHECKS[check](value, label)
    return 0


if __name__ == "__main__":
    sys.exit(main())
brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).Stars: 322kUpdated Claude CodeCodexVerifiedInstall
brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).Stars: 198kUpdated Claude CodeCodexVerifiedInstall