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/tests/test_parse_wave_main.py

View on GitHub
"""Tests for ``parse_wave.main`` orchestrator + tree-walking helpers.

Covers:
- ``walk_and_inflate``        recursive Flow inflation
- ``inflate_flow_leaf``       cycle + depth-cap behavior
- ``build_root_children``     bundle → root children + new_refs
- ``main`` (full path)        env-driven pipeline against a tmp WORK_DIR
- ``main --finalize-cap``     drain pending → unresolved
"""
from __future__ import annotations

import json
import os
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest import mock

from . import _bootstrap  # noqa: F401  — sys.path setup

import parse_wave  # type: ignore


_FLOW_NS = "http://soap.sforce.com/2006/04/metadata"


# -----------------------------------------------------------------------------
# walk_and_inflate
# -----------------------------------------------------------------------------


class WalkAndInflateTests(unittest.TestCase):

    def test_no_op_for_non_FLOW_non_GEN_AI_FUNCTION_node(self):
        node = {"kind": "TOPIC", "api_name": "T1", "children": []}
        flow_children: dict = {}
        # Should not raise; should not mutate.
        parse_wave.walk_and_inflate(node, flow_children)
        self.assertEqual(node["children"], [])

    def test_inflates_flow_leaf_under_gen_ai_function(self):
        # GEN_AI_FUNCTION wraps a FLOW leaf — walker recurses into it.
        node = {
            "kind": "GEN_AI_FUNCTION",
            "api_name": "GAF1",
            "children": [{"kind": "FLOW", "api_name": "MyFlow", "children": []}],
        }
        flow_children = {"MyFlow": [
            {"kind": "APEX", "element_name": "callA", "api_name": "MyClass"},
        ]}
        parse_wave.walk_and_inflate(node, flow_children)
        # FLOW leaf got inflated with the APEX child
        flow_leaf = node["children"][0]
        self.assertEqual(len(flow_leaf["children"]), 1)
        self.assertEqual(flow_leaf["children"][0]["kind"], "APEX")

    def test_recursively_walks_through_topic_to_inflate_flow(self):
        # Walker should descend through TOPIC/non-special nodes too.
        node = {
            "kind": "BOT_DEFINITION", "api_name": "Agent",
            "children": [{
                "kind": "TOPIC", "api_name": "T1",
                "children": [{
                    "kind": "GEN_AI_FUNCTION", "api_name": "GAF1",
                    "children": [{"kind": "FLOW", "api_name": "DeepFlow",
                                  "children": []}],
                }],
            }],
        }
        flow_children = {"DeepFlow": [
            {"kind": "APEX", "element_name": "callA", "api_name": "DeepClass"},
        ]}
        parse_wave.walk_and_inflate(node, flow_children)
        # DeepFlow got the APEX child
        deep_flow = node["children"][0]["children"][0]["children"][0]
        self.assertEqual(deep_flow["children"][0]["api_name"], "DeepClass")

    def test_pending_out_collects_depth_cap_truncations(self):
        # Build a chain longer than MAX_BFS_DEPTH so the cap trips.
        # Generate 25 flows that each subflow into the next.
        flow_children: dict = {}
        for i in range(25):
            next_name = f"F{i+1}" if i < 24 else None
            kids = []
            if next_name:
                kids.append({"kind": "FLOW", "element_name": f"sub_{i}",
                             "api_name": next_name})
            flow_children[f"F{i}"] = kids
        node = {"kind": "FLOW", "api_name": "F0", "children": []}
        pending: dict = parse_wave.empty_kind_sets()
        parse_wave.walk_and_inflate(node, flow_children, pending_out=pending)
        # Some subflow ended up in pending due to the depth cap (>= MAX_BFS_DEPTH).
        self.assertTrue(any(pending[k] for k in parse_wave.BFS_KINDS))


# -----------------------------------------------------------------------------
# inflate_flow_leaf — cycle detection
# -----------------------------------------------------------------------------


class InflateFlowLeafCycleTests(unittest.TestCase):

    def test_self_recursion_marked_as_cycle(self):
        # Flow A subflows back to A itself → cycle.
        flow_children = {"A": [
            {"kind": "FLOW", "element_name": "self", "api_name": "A"},
        ]}
        leaf = {"kind": "FLOW", "api_name": "A", "children": []}
        parse_wave.inflate_flow_leaf(leaf, flow_children)
        # The recursive child got annotated with _truncated.
        kid = leaf["children"][0]
        self.assertIn("_truncated", kid)
        self.assertEqual(kid["_truncated"]["reason"],
                         parse_wave.TRUNCATION_CYCLE)

    def test_unknown_flow_no_inflation(self):
        # leaf.api_name not in flow_children → nothing to inflate.
        leaf = {"kind": "FLOW", "api_name": "Missing", "children": []}
        parse_wave.inflate_flow_leaf(leaf, {})
        self.assertEqual(leaf["children"], [])


# -----------------------------------------------------------------------------
# build_root_children
# -----------------------------------------------------------------------------


class BuildRootChildrenTests(unittest.TestCase):

    def test_topics_become_root_children(self):
        bundle = {
            "topics": [
                {"name": "Greetings", "actions": [
                    {"name": "Hello", "invocationTarget": "MyFlow",
                     "invocationTargetType": "flow"},
                ]},
            ],
        }
        visited = parse_wave.empty_kind_sets()
        aux: set = set()
        children, new_refs = parse_wave.build_root_children(bundle, visited, aux)
        self.assertEqual(len(children), 1)
        self.assertEqual(children[0]["kind"], "TOPIC")
        self.assertEqual(children[0]["api_name"], "Greetings")
        # GEN_AI_FUNCTION wrapping the action
        self.assertEqual(children[0]["children"][0]["kind"], "GEN_AI_FUNCTION")
        # FLOW ref harvested into new_refs
        self.assertIn("MyFlow", new_refs["FLOW"])
        # Topic + action recorded in aux_visited
        self.assertIn(("TOPIC", "Greetings"), aux)
        self.assertIn(("GEN_AI_FUNCTION", "Hello"), aux)

    def test_skips_already_visited_refs(self):
        bundle = {
            "topics": [{"name": "T", "actions": [
                {"name": "A1", "invocationTarget": "FlowA",
                 "invocationTargetType": "flow"},
            ]}],
        }
        visited = parse_wave.empty_kind_sets()
        visited["FLOW"].add("FlowA")
        aux: set = set()
        _, new_refs = parse_wave.build_root_children(bundle, visited, aux)
        # FlowA already visited → not added to new_refs
        self.assertNotIn("FlowA", new_refs["FLOW"])

    def test_standard_action_does_not_pollute_new_refs(self):
        # STANDARD_ACTION is declared-only, must NOT
        # land in new_refs (would pollute _pending_fetches).
        bundle = {
            "topics": [{"name": "T", "actions": [
                {"name": "A1", "invocationTarget": "createRecord",
                 "invocationTargetType": "standardinvocableaction"},
            ]}],
        }
        visited = parse_wave.empty_kind_sets()
        aux: set = set()
        _, new_refs = parse_wave.build_root_children(bundle, visited, aux)
        self.assertNotIn("createRecord", new_refs["STANDARD_ACTION"])

    def test_empty_bundle_returns_empty_children(self):
        children, new_refs = parse_wave.build_root_children(
            {}, parse_wave.empty_kind_sets(), set(),
        )
        self.assertEqual(children, [])
        for v in new_refs.values():
            self.assertEqual(v, set())


# -----------------------------------------------------------------------------
# main() — happy path + finalize-cap branch
# -----------------------------------------------------------------------------


def _setup_workdir(tmp: Path, *, bundle: dict | None = None) -> Path:
    """Plant a WORK_DIR with _bundle_parsed.json + minimal sf_meta layout."""
    work_dir = tmp / "work"
    work_dir.mkdir()
    bundle = bundle or {
        "plannerName": "MyPlanner",
        "plannerType": "Atlas__Reasoning",
        "generation": "nga",
        "topics": [{"name": "Greetings", "actions": [
            {"name": "SayHi", "invocationTarget": "GreetingsFlow",
             "invocationTargetType": "flow"},
        ]}],
    }
    (work_dir / "_bundle_parsed.json").write_text(json.dumps(bundle))
    # Empty sf_meta is fine — harvest_waves returns empty when missing.
    return work_dir


def _run_main(*, work_dir: Path, argv_extra: list[str] | None = None,
              env_extra: dict | None = None) -> int:
    """Invoke parse_wave.main with controlled env + argv."""
    saved_env = dict(os.environ)
    saved_argv = list(parse_wave.sys.argv)
    try:
        os.environ.update({
            "WORK_DIR": str(work_dir),
            "AGENT_API_NAME": "DemoAgent",
            "AGENT_VERSION": "v3",
            "BOT_ID": "0Xx000000000ABC",
            "BOT_MASTER_LABEL": "Demo Agent",
            "VERSION_AUTO_PICKED": "false",
        })
        if env_extra:
            os.environ.update(env_extra)
        parse_wave.sys.argv = ["parse_wave.py", *(argv_extra or [])]
        return parse_wave.main()
    finally:
        os.environ.clear()
        os.environ.update(saved_env)
        parse_wave.sys.argv = saved_argv


class MainHappyPathTests(unittest.TestCase):

    def test_main_writes_declared_action_tree_json(self):
        with TemporaryDirectory() as t:
            tmp = Path(t)
            work_dir = _setup_workdir(tmp)
            with mock.patch.object(parse_wave.sys, "stderr"):
                rc = _run_main(work_dir=work_dir)
            self.assertEqual(rc, 0)
            tree_path = work_dir / "declared_action_tree.json"
            self.assertTrue(tree_path.is_file())
            tree = json.loads(tree_path.read_text())
            # Tree has the expected shape
            self.assertEqual(tree["_schema_version"], "3.1")
            self.assertEqual(tree["agent"]["api_name"], "DemoAgent")
            self.assertEqual(tree["root"]["kind"], "BOT_DEFINITION")
            # One topic became a root child
            kinds = [c["kind"] for c in tree["root"]["children"]]
            self.assertIn("TOPIC", kinds)

    def test_main_records_pending_for_unfetched_flow(self):
        with TemporaryDirectory() as t:
            tmp = Path(t)
            work_dir = _setup_workdir(tmp)
            with mock.patch.object(parse_wave.sys, "stderr"):
                _run_main(work_dir=work_dir)
            tree = json.loads(
                (work_dir / "declared_action_tree.json").read_text()
            )
        # GreetingsFlow not on disk → in _pending_fetches.FLOW
        self.assertIn("GreetingsFlow", tree["_pending_fetches"]["FLOW"])
        self.assertTrue(tree["_partial"])
        # _partial_reason populated on first run when pending refs exist
        # but no depth cap was tripped.
        self.assertEqual(tree["_partial_reason"], "pending-refs")

    def test_main_writes_pending_refs_reason_when_initial_reason_is_none(self):
        # init_tree seeds `_partial_reason=None`. The writer's elif branch
        # must populate it with "pending-refs" when any pending bucket is
        # non-empty and the depth cap did not trip — a setdefault against
        # `None` is a no-op, which is the bug this guards.
        with TemporaryDirectory() as t:
            tmp = Path(t)
            work_dir = _setup_workdir(tmp)
            with mock.patch.object(parse_wave.sys, "stderr"):
                _run_main(work_dir=work_dir)
            tree = json.loads(
                (work_dir / "declared_action_tree.json").read_text()
            )
        # Sanity: pending exists, depth cap was NOT tripped.
        self.assertIn("GreetingsFlow", tree["_pending_fetches"]["FLOW"])
        # The fix: a None-valued reason gets promoted to "pending-refs".
        self.assertEqual(tree["_partial_reason"], "pending-refs")

    def test_main_preserves_existing_partial_reason_when_pending_refs(self):
        # init_tree primes _partial_reason=None; setdefault used to be a
        # no-op against that None and left the reason blank. Today the
        # writer treats None as "unset" and fills in "pending-refs".
        # When a prior reason exists (e.g. "max-depth-cap" from a previous
        # wave), the writer must NOT overwrite it.
        with TemporaryDirectory() as t:
            tmp = Path(t)
            work_dir = _setup_workdir(tmp)
            # Plant a tree on disk that mimics a previously-suspended run:
            # _partial_reason="max-depth-cap" and empty root children, so
            # main() enters the fresh-tree branch and re-collects bundle
            # refs (GreetingsFlow pending) yet sees the prior reason.
            tree_path = work_dir / "declared_action_tree.json"
            tree_path.write_text(json.dumps({
                "_schema_version": "3.1",
                "agent": {"api_name": "DemoAgent", "version": "v3"},
                "root": {"kind": "BOT_DEFINITION", "api_name": "DemoAgent",
                         "children": []},
                "_partial": True,
                "_partial_reason": "max-depth-cap",
                "_pending_fetches": {k: [] for k in parse_wave.BFS_KINDS},
                "_unresolved": [],
                "_visited": [],
            }))
            with mock.patch.object(parse_wave.sys, "stderr"):
                _run_main(work_dir=work_dir)
            tree2 = json.loads(tree_path.read_text())
        # GreetingsFlow is pending → any_pending=True → elif branch runs.
        self.assertIn("GreetingsFlow", tree2["_pending_fetches"]["FLOW"])
        # Existing more-specific reason is preserved.
        self.assertEqual(tree2["_partial_reason"], "max-depth-cap")

    def test_main_returns_one_when_work_dir_env_missing(self):
        saved_env = dict(os.environ)
        try:
            for k in ("WORK_DIR", "AGENT_API_NAME", "AGENT_VERSION"):
                os.environ.pop(k, None)
            with mock.patch.object(parse_wave.sys, "argv", ["parse_wave.py"]):
                with mock.patch.object(parse_wave.sys, "stderr"):
                    rc = parse_wave.main()
        finally:
            os.environ.clear()
            os.environ.update(saved_env)
        self.assertEqual(rc, 1)

    def test_main_returns_one_when_bundle_missing(self):
        with TemporaryDirectory() as t:
            tmp = Path(t)
            work_dir = tmp / "work"
            work_dir.mkdir()
            # No _bundle_parsed.json
            with mock.patch.object(parse_wave.sys, "stderr"):
                rc = _run_main(work_dir=work_dir)
        self.assertEqual(rc, 1)

    def test_main_reparses_existing_tree(self):
        # Two-pass: first run creates the tree, second re-uses it.
        with TemporaryDirectory() as t:
            tmp = Path(t)
            work_dir = _setup_workdir(tmp)
            with mock.patch.object(parse_wave.sys, "stderr"):
                _run_main(work_dir=work_dir)
                # Second invocation should load + augment without crashing
                rc = _run_main(work_dir=work_dir)
        self.assertEqual(rc, 0)


class MainFinalizeCapTests(unittest.TestCase):

    def test_finalize_cap_drains_pending_into_unresolved(self):
        with TemporaryDirectory() as t:
            tmp = Path(t)
            work_dir = _setup_workdir(tmp)
            # First run produces a tree with pending FLOW=GreetingsFlow.
            with mock.patch.object(parse_wave.sys, "stderr"):
                _run_main(work_dir=work_dir)
                # --finalize-cap drains pending → unresolved
                rc = _run_main(
                    work_dir=work_dir, argv_extra=["--finalize-cap"],
                )
            self.assertEqual(rc, 0)
            tree = json.loads(
                (work_dir / "declared_action_tree.json").read_text()
            )
            # All buckets emptied
            for kind in parse_wave.BFS_KINDS:
                self.assertEqual(tree["_pending_fetches"][kind], [])
            # GreetingsFlow now in _unresolved
            api_names = [u["api_name"] for u in tree["_unresolved"]]
            self.assertIn("GreetingsFlow", api_names)

    def test_finalize_cap_with_no_existing_tree_is_noop(self):
        with TemporaryDirectory() as t:
            tmp = Path(t)
            work_dir = tmp / "work"
            work_dir.mkdir()
            with mock.patch.object(parse_wave.sys, "stderr"):
                rc = _run_main(
                    work_dir=work_dir, argv_extra=["--finalize-cap"],
                )
        # No tree file → noop, exit 0.
        self.assertEqual(rc, 0)


if __name__ == "__main__":
    unittest.main()
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