Skip to content

amazon-science/ammo / ai_cli_session/.codex/skills/ammo

Profile and optimize GPU kernels for vLLM inference on NVIDIA GPUs. Use when targeting a specific model, hardware, dtype, parallelism, and workload to improve latency.

FileKindSize
RUNTIME.mdmarkdown4.9 KB
SKILL.mdskill md18.5 KB
agents/ammo-auditor.mdmarkdown9.1 KB
agents/ammo-champion.mdmarkdown9.6 KB
agents/ammo-delegate.mdmarkdown3.2 KB
agents/ammo-implementer.mdmarkdown13.8 KB
agents/ammo-investigator.mdmarkdown4.0 KB
agents/ammo-report.mdmarkdown2.9 KB
agents/ammo-researcher.mdmarkdown10.3 KB
agents/ammo-resolver.mdmarkdown4.4 KB
agents/ammo-transcript-monitor.mdmarkdown7.8 KB
agents/openai.yamlexecutablescript313 B
data/ATTRIBUTION.mdmarkdown1.4 KB
data/gsm8k_full.jsonexecutablescript735.5 KB
data/gsm8k_subset.jsonexecutablescript116.8 KB
eval/EVAL-SKILL.mdexecutablescript21.8 KB
eval/agents/transcript_grader.mdexecutablescript18.0 KB
eval/causal/__init__.pyexecutablescript137 B
eval/causal/agents/causal_analyzer.mdexecutablescript10.5 KB
eval/causal/build_dag.pyexecutablescript21.6 KB
eval/causal/diff_versions.pyexecutablescript38.5 KB
eval/causal/extract_events.pyexecutablescript36.3 KB
eval/causal/generate_postmortem.pyexecutablescript17.0 KB
eval/causal/score_nodes.pyexecutablescript21.5 KB
eval/causal/templates/narrative_template.mdexecutablescript472 B
eval/causal/templates/viz_template.htmlexecutablescript9.5 KB
eval/causal/tests/__init__.pyexecutablescript151 B
eval/causal/tests/conftest.pyexecutablescript448 B
eval/causal/tests/fixtures/sample_session.jsonlexecutablescript10.4 KB
eval/causal/tests/fixtures/sample_session_data.jsonexecutablescript3.4 KB
eval/causal/tests/fixtures/sample_snapshot.jsonexecutablescript2.5 KB
eval/causal/tests/test_build_dag.pyexecutablescript2.7 KB
eval/causal/tests/test_diff_versions.pyexecutablescript13.5 KB
eval/causal/tests/test_extract_events.pyexecutablescript3.7 KB
eval/causal/tests/test_generate_postmortem.pyexecutablescript3.1 KB
eval/causal/tests/test_score_nodes.pyexecutablescript3.3 KB
eval/scripts/aggregate_versions.pyexecutablescript15.2 KB
eval/scripts/archive_run.pyexecutablescript9.1 KB
eval/scripts/codex_session.pyexecutablescript10.6 KB
eval/scripts/generate_dashboard.pyexecutablescript5.3 KB
eval/scripts/parse_artifacts.pyexecutablescript48.1 KB
eval/scripts/parse_session_logs.pyexecutablescript51.3 KB
eval/scripts/rescore_archived.pyexecutablescript5.5 KB
eval/scripts/score_campaign.pyexecutablescript43.8 KB
eval/scripts/snapshot_changes.pyexecutablescript11.1 KB
eval/scripts/verify_citations.pyexecutablescript8.8 KB
eval/tests/test_dashboard_bugs.pyexecutablescript8.8 KB
eval/tests/test_parse_session_logs.pyexecutablescript3.9 KB
eval/tests/test_parse_session_logs_round_inference.pyexecutablescript11.0 KB
eval/tests/test_score_campaign_diluted.pyexecutablescript9.4 KB
eval/viewer/dashboard_template.htmlexecutablescript15.1 KB
instrumentation/sitecustomize.pyexecutablescript3.6 KB
orchestration/audit-protocol.mdmarkdown9.3 KB
orchestration/debate-protocol.mdmarkdown11.2 KB
orchestration/integration-logic.mdmarkdown10.3 KB
orchestration/parallel-tracks.mdmarkdown8.9 KB
references/artifact-layout.mdexecutablescript22.4 KB
references/audit-invariants.mdmarkdown10.6 KB
references/champion-common-patterns.mdmarkdown3.4 KB
references/crossover-probing.mdexecutablescript4.7 KB
references/cudagraph-safety.mdmarkdown2.7 KB
references/debate-rules.mdmarkdown4.7 KB
references/debate-scoring-rubric.mdexecutablescript16.7 KB
references/e2e-delta-math.mdexecutablescript17.9 KB
references/e2e-latency-guide.mdexecutablescript9.6 KB
references/fusion-feasibility-heuristics.mdmarkdown5.6 KB
references/gpu-pool.mdexecutablescript5.4 KB
references/impl-track-rules.mdexecutablescript13.8 KB
references/nsys-profiling-guide.mdmarkdown9.8 KB
references/optimization-categories.mdexecutablescript11.0 KB
references/shutdown-protocol.mdexecutablescript3.1 KB
references/technology-selection.mdmarkdown5.0 KB
references/torch-compile-contract.mdmarkdown13.8 KB
references/validation-defaults.mdexecutablescript34.2 KB
references/workload-invocation.mdexecutablescript4.9 KB
references/writing-style.mdexecutablescript6.9 KB
scripts/ammo_state.pyexecutablescript142.0 KB
scripts/artifact_layout.jsonconfig16.3 KB
scripts/check_projection_accuracy.pyexecutablescript11.7 KB
scripts/create_evidence_template.pyexecutablescript9.7 KB
scripts/create_worktree_with_build.shexecutablescript10.2 KB
scripts/generate_validation_report.pyexecutablescript35.7 KB
scripts/gpu_reservation.pyexecutablescript27.1 KB
scripts/hook_cmd_classify.pyscript13.3 KB
scripts/mine_trace.pyscript29.4 KB
scripts/monitor_queue_ack.pyexecutablescript6.1 KB
scripts/ncu_sanity.shexecutablescript5.2 KB
scripts/ncu_sanity_driver.pyexecutablescript8.5 KB
scripts/new_target.pyexecutablescript22.0 KB
scripts/preflight_vllm_api.pyexecutablescript12.3 KB
scripts/reconcile_track_state.pyexecutablescript15.8 KB
scripts/remove_worktree_cleanup.shexecutablescript1.1 KB
scripts/resolve_codex_transcript.pyexecutablescript3.6 KB
scripts/run_vllm_bench_latency_sweep.pyexecutablescript249.6 KB
scripts/transcript_filter.pyexecutablescript38.4 KB
scripts/transitions.jsonexecutablescript1.5 KB
scripts/verify_validation_gates.pyexecutablescript88.8 KB
tests/agents/test-champion.mdexecutablescript20.4 KB
tests/agents/test-impl-champion.mdexecutablescript14.3 KB
tests/agents/test-implementer.mdexecutablescript15.8 KB
tests/agents/test-orchestrator.mdexecutablescript33.8 KB
tests/agents/test-researcher.mdexecutablescript21.0 KB
tests/agents/test-transcript-monitor.mdexecutablescript13.4 KB
tests/fixtures/diluted_pass/legacy_no_phase.golden.mdmarkdown1.1 KB
tests/fixtures/diluted_pass/legacy_no_phase.golden.summary.jsonconfig582 B
tests/fixtures/diluted_pass/legacy_no_phase.jsonconfig400 B
tests/fixtures/diluted_pass/legacy_scalar_phase.golden.mdmarkdown2.0 KB
tests/fixtures/diluted_pass/legacy_scalar_phase.golden.summary.jsonconfig1.0 KB
tests/fixtures/diluted_pass/legacy_scalar_phase.jsonconfig626 B
tests/fixtures/mining/real_campaign_bottleneck_analysis.mdmarkdown20.7 KB
tests/run_all.shexecutablescript1.6 KB
tests/scripts/test_transcript_filter.pyexecutablescript41.1 KB
tests/test_agent_runtime_contracts.pyexecutablescript1.8 KB
tests/test_ammo_state.pyexecutablescript71.7 KB
tests/test_artifact_layout_manifest.pyscript11.6 KB
tests/test_audit_started.pyscript18.2 KB
tests/test_correctness_comparator.pyscript12.6 KB
tests/test_diluted_pass.pyscript24.4 KB
tests/test_drift_compat.pyscript5.1 KB
tests/test_evidence_freshness.pyexecutablescript5.6 KB
tests/test_fail_closed.pyexecutablescript14.7 KB
tests/test_gpu_reservation.pyexecutablescript24.8 KB
tests/test_gpu_reservation_session_id.pyexecutablescript11.2 KB
tests/test_guidance_semantic_contract.pyscript24.9 KB
tests/test_hook_cmd_classify_parity.pyscript11.7 KB
tests/test_hook_semantics.pyexecutablescript95.3 KB
tests/test_mine_trace.pyscript24.2 KB
tests/test_mining_invalidated_schema.pyexecutablescript9.4 KB
tests/test_new_target_dp_ep.pyexecutablescript7.4 KB
tests/test_new_target_v2_scaffold.pyexecutablescript13.1 KB
tests/test_parse_artifacts.pyexecutablescript3.0 KB
tests/test_policy_convergence.pyscript797 B
tests/test_preflight_vllm_api.pyscript13.3 KB
tests/test_projection_accuracy_v2.pyexecutablescript4.1 KB
tests/test_reconcile_track_state.pyexecutablescript18.2 KB
tests/test_resolve_codex_transcript.pyexecutablescript3.1 KB
tests/test_state_schema_semantics.pyexecutablescript7.6 KB
tests/test_status_set_sync.pyexecutablescript9.1 KB
tests/test_sweep_baseline_from_arm.pyscript11.0 KB
tests/test_sweep_decode_capture.pyexecutablescript31.8 KB
tests/test_sweep_dp.pyexecutablescript45.4 KB
tests/test_sweep_fresh_cache.pyscript5.5 KB
tests/test_sweep_profiler_guard.pyscript22.6 KB
tests/test_sweep_real_prompts.pyscript20.1 KB
tests/test_sweep_refactor.pyexecutablescript37.6 KB
tests/test_sweep_round_slot.pyexecutablescript7.4 KB
tests/test_validation_report_phase_triage.pyexecutablescript10.0 KB
tests/test_validation_report_v2.pyexecutablescript6.2 KB
tests/test_verify_validation_gates.pyexecutablescript52.9 KB
tests/test_workload_matrix.pyexecutablescript19.3 KB

eval/causal/build_dag.py

View on GitHub
#!/usr/bin/env python3
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: CC-BY-NC-4.0
"""Build a coarse stage-level causal DAG from an AMMO events list.

Reads the structured event log produced by extract_events.py and emits a
directed acyclic graph where nodes are AMMO pipeline stages and edges encode
four types of causal dependencies: file_dependency, message_dependency,
data_citation, and decision_gate.

Usage:
    python build_dag.py \\
        --events /path/to/events.json \\
        --artifact-dir /path/to/campaign/artifacts \\
        --output /path/to/dag.json
"""

from __future__ import annotations

import argparse
import json
import os
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple


# ---------------------------------------------------------------------------
# Stage → Node ID mapping
# ---------------------------------------------------------------------------

# Priority-ordered list of (substring, node_id_prefix) rules.
# The first match wins. Impl nodes use a special handler.
_STAGE_RULES: List[Tuple[str, str]] = [
    ("bottleneck", "bottleneck_mining"),
    ("mining", "bottleneck_mining"),
    # "baseline" maps to bottleneck_mining because AMMO's Stage 1 combines
    # baseline capture and bottleneck mining into a single researcher pass.
    ("baseline", "bottleneck_mining"),
    ("debate", "debate"),
    ("impl", "impl"),        # special: needs op_id suffix
    ("4_5", "impl"),         # special: needs op_id suffix
    ("integration", "integration"),
    ("eval", "campaign_eval"),
    ("6", "campaign_eval"),  # stage_6_7_eval
    ("7", "campaign_eval"),
]

# Tolerance by datum_type for data_citation matching
_CITATION_TOLERANCES: Dict[str, float] = {
    "f_value": 0.005,
    "kernel_timing": 0.02,
    "speedup": 0.01,
    "memory_size": 0.01,
    "bandwidth": 0.02,
}
_DEFAULT_TOLERANCE = 0.01

# Structural pipeline order used for decision_gate edges and disambiguation
_PIPELINE_ORDER = [
    "bottleneck_mining",
    "baseline_capture",
    "debate",
    # impl_* nodes come here (dynamic)
    "integration",
    "campaign_eval",
]


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def _basename(path: str) -> str:
    """Return the filename portion of a path."""
    return os.path.basename(path) if path else ""


def _map_stage_to_node(stage_label: str, agent_name: Optional[str] = None) -> Optional[str]:
    """Map a stage label (e.g. 'round_1:implementation') to a node ID.

    Returns None for unrecognized or empty stages (those events are skipped).
    For impl stages, returns 'impl_{op_id}' where op_id is extracted from
    agent_name if available, otherwise 'impl_track_N'.
    """
    if not stage_label:
        return None

    label_lower = stage_label.lower()

    for fragment, node_prefix in _STAGE_RULES:
        if fragment in label_lower:
            if node_prefix == "impl":
                op_id = _extract_op_id(agent_name)
                return f"impl_{op_id}" if op_id else None  # resolved later
            return node_prefix

    return None


def _extract_op_id(agent_name: Optional[str]) -> Optional[str]:
    """Extract an op ID from an agent name like 'implementer-op001' -> 'op001'."""
    if not agent_name:
        return None
    import re
    # Match op001, op1, op-001 patterns
    m = re.search(r"op[-_]?(\d+)", agent_name.lower())
    if m:
        return f"op{m.group(1).lstrip('0') or '0'}"
    return None


def _values_match(a: float, b: float, tolerance: float) -> bool:
    """Return True when |a - b| / max(|a|, |b|) < tolerance."""
    denom = max(abs(a), abs(b))
    if denom == 0:
        return a == b
    return abs(a - b) / denom < tolerance


# ---------------------------------------------------------------------------
# Core: group events into nodes
# ---------------------------------------------------------------------------

def _group_events_into_nodes(events: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
    """Group events by stage, map to node IDs, and build node metadata.

    Returns dict of node_id → node dict.
    """
    # First pass: determine the op_id counter for impl nodes without explicit ids
    impl_counter = 0
    # Map from stage_label → node_id (to stay consistent across events)
    stage_to_node: Dict[str, str] = {}

    # Pre-scan for agent_spawn events to get agent names per stage
    stage_to_agent: Dict[str, Dict[str, Any]] = {}
    for evt in events:
        stage = evt.get("stage")
        if not stage:
            continue
        if evt["event_type"] == "agent_spawn" and stage not in stage_to_agent:
            stage_to_agent[stage] = {
                "agent_id": evt.get("agent_id"),
                "agent_name": evt.get("agent_name"),
                "agent_role": evt.get("agent_role"),
            }

    # Determine node_id for each stage label
    for evt in events:
        stage = evt.get("stage")
        if not stage or stage in stage_to_node:
            continue

        agent_name = stage_to_agent.get(stage, {}).get("agent_name")
        node_id = _map_stage_to_node(stage, agent_name)

        if node_id == "impl_None" or node_id is None:
            # Try to find the impl node's agent name from spawns in this stage
            # Fall back to sequential naming
            if stage not in stage_to_node:
                impl_counter += 1
                node_id = f"impl_track_{impl_counter}"

        if node_id:
            stage_to_node[stage] = node_id

    # Build nodes dict; when multiple stages map to the same node_id, merge them
    nodes: Dict[str, Dict[str, Any]] = {}

    for idx, evt in enumerate(events):
        stage = evt.get("stage")
        if not stage or stage not in stage_to_node:
            continue

        node_id = stage_to_node[stage]
        if node_id not in nodes:
            nodes[node_id] = {
                "id": node_id,
                "stage_labels": [],
                "inputs": [],
                "outputs": [],
                "data_claims_extracted": 0,
                "event_range": {"start_idx": idx, "end_idx": idx},
                "agent_id": "orchestrator",
                "agent_name": "orchestrator",
                "agent_role": "orchestrator",
                "_events_indices": [],
            }

        node = nodes[node_id]

        # Update stage_labels
        if stage not in node["stage_labels"]:
            node["stage_labels"].append(stage)

        # Update event range
        if idx < node["event_range"]["start_idx"]:
            node["event_range"]["start_idx"] = idx
        if idx > node["event_range"]["end_idx"]:
            node["event_range"]["end_idx"] = idx

        node["_events_indices"].append(idx)

        event_type = evt["event_type"]

        if event_type == "file_write":
            path = evt.get("details", {}).get("path", "")
            if path and path not in node["outputs"]:
                node["outputs"].append(path)

        elif event_type == "file_read":
            path = evt.get("details", {}).get("path", "")
            if path and path not in node["inputs"]:
                node["inputs"].append(path)

        elif event_type == "data_output":
            node["data_claims_extracted"] += 1

        elif event_type == "agent_spawn":
            # Use the first agent_spawn to set agent metadata
            if node["agent_id"] == "orchestrator":
                node["agent_id"] = evt.get("agent_id") or "orchestrator"
                node["agent_name"] = evt.get("agent_name") or "orchestrator"
                node["agent_role"] = evt.get("agent_role") or "orchestrator"

    return nodes


# ---------------------------------------------------------------------------
# Core: build edges
# ---------------------------------------------------------------------------

def _build_file_dependency_edges(
    nodes: Dict[str, Dict[str, Any]],
    events: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
    """For each file_write in node A and file_read in node B where paths match
    and B's event is after A's event, emit a file_dependency edge."""
    edges = []
    seen: set = set()

    # Build lookup: filename → list of (node_id, event_idx, timestamp)
    # for writes and reads
    writes: Dict[str, List[Tuple[str, int, Optional[str]]]] = {}  # basename → list
    reads: Dict[str, List[Tuple[str, int, Optional[str]]]] = {}

    for node_id, node in nodes.items():
        indices = node["_events_indices"]
        for idx in indices:
            evt = events[idx]
            if evt["event_type"] == "file_write":
                path = evt.get("details", {}).get("path", "")
                bn = _basename(path)
                if bn:
                    writes.setdefault(bn, []).append((node_id, idx, evt.get("timestamp"), path))
            elif evt["event_type"] == "file_read":
                path = evt.get("details", {}).get("path", "")
                bn = _basename(path)
                if bn:
                    reads.setdefault(bn, []).append((node_id, idx, evt.get("timestamp"), path))

    # Match writes to reads where read is after write and different nodes
    for bn, write_list in writes.items():
        if bn not in reads:
            continue
        for w_node, w_idx, w_ts, w_path in write_list:
            for r_node, r_idx, r_ts, r_path in reads[bn]:
                if r_node == w_node:
                    continue
                if r_idx <= w_idx:
                    continue
                key = (w_node, r_node, bn)
                if key in seen:
                    continue
                seen.add(key)
                edges.append({
                    "type": "file_dependency",
                    "from": w_node,
                    "to": r_node,
                    "artifact": bn,
                })

    return edges


def _build_message_dependency_edges(
    nodes: Dict[str, Dict[str, Any]],
    events: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
    """For each send_message event, create edge from sender's node to receiver's node."""
    edges = []
    seen: set = set()

    # Build agent_id → node_id lookup
    agent_to_node: Dict[str, str] = {}
    for node_id, node in nodes.items():
        if node["agent_id"] and node["agent_id"] != "orchestrator":
            agent_to_node[node["agent_id"]] = node_id

    for node_id, node in nodes.items():
        for idx in node["_events_indices"]:
            evt = events[idx]
            if evt["event_type"] != "send_message":
                continue
            details = evt.get("details", {})
            from_agent = details.get("from_agent")
            to_agent = details.get("to_agent")

            from_node = agent_to_node.get(from_agent) if from_agent else node_id
            to_node = agent_to_node.get(to_agent) if to_agent else None

            if from_node and to_node and from_node != to_node:
                key = (from_node, to_node)
                if key not in seen:
                    seen.add(key)
                    edges.append({
                        "type": "message_dependency",
                        "from": from_node,
                        "to": to_node,
                    })

    return edges


def _build_data_citation_edges(
    nodes: Dict[str, Dict[str, Any]],
    events: List[Dict[str, Any]],
    pipeline_order: List[str],
) -> List[Dict[str, Any]]:
    """For each data_output in node B, match against data_outputs in upstream nodes.

    Disambiguation: when multiple upstream nodes match, prefer the one with
    the latest file_write event timestamp.
    """
    edges = []

    # Build pipeline position lookup
    def _pipeline_pos(node_id: str) -> int:
        for i, nid in enumerate(pipeline_order):
            if nid == node_id:
                return i
            if nid == "impl_*" or node_id.startswith("impl_"):
                # impl nodes sit between debate and integration
                return len(_PIPELINE_ORDER) - 1
        return len(pipeline_order)

    def _node_pipeline_pos(node_id: str) -> int:
        # Find the position of this node based on AMMO stage order
        _ORDER = ["bottleneck_mining", "baseline_capture", "debate"]
        if node_id in _ORDER:
            return _ORDER.index(node_id)
        if node_id.startswith("impl_"):
            return len(_ORDER)
        if node_id == "integration":
            return len(_ORDER) + 100
        if node_id == "campaign_eval":
            return len(_ORDER) + 200
        return len(_ORDER) + 50

    # Collect all data_outputs per node with their event index and timestamp
    node_data_outputs: Dict[str, List[Dict[str, Any]]] = {}
    for node_id, node in nodes.items():
        outputs = []
        for idx in node["_events_indices"]:
            evt = events[idx]
            if evt["event_type"] == "data_output":
                outputs.append({
                    "value": evt["details"]["value"],
                    "datum_type": evt["details"]["datum_type"],
                    "raw_text": evt["details"].get("raw_text", ""),
                    "event_idx": idx,
                    "timestamp": evt.get("timestamp"),
                })
        node_data_outputs[node_id] = outputs

    # Collect latest file_write timestamp per node (for disambiguation)
    node_latest_write_ts: Dict[str, Optional[str]] = {}
    for node_id, node in nodes.items():
        latest = None
        for idx in node["_events_indices"]:
            evt = events[idx]
            if evt["event_type"] == "file_write":
                ts = evt.get("timestamp")
                if ts and (latest is None or ts > latest):
                    latest = ts
        node_latest_write_ts[node_id] = latest

    seen_edges: set = set()

    for b_node_id, b_outputs in node_data_outputs.items():
        if not b_outputs:
            continue
        b_pos = _node_pipeline_pos(b_node_id)

        # Find upstream nodes (earlier in pipeline)
        upstream_nodes = [
            nid for nid in node_data_outputs
            if _node_pipeline_pos(nid) < b_pos
        ]

        for b_out in b_outputs:
            b_val = b_out["value"]
            b_type = b_out["datum_type"]
            tolerance = _CITATION_TOLERANCES.get(b_type, _DEFAULT_TOLERANCE)

            # Find all upstream matches
            matches: List[Tuple[str, float, Optional[str]]] = []  # (node_id, value, timestamp)
            for a_node_id in upstream_nodes:
                for a_out in node_data_outputs[a_node_id]:
                    if a_out["datum_type"] != b_type:
                        continue
                    a_val = a_out["value"]
                    if _values_match(a_val, b_val, tolerance):
                        matches.append((a_node_id, a_val, node_latest_write_ts.get(a_node_id)))

            if not matches:
                continue

            # Disambiguation: prefer the node with the latest file_write timestamp
            def _sort_key(m: Tuple[str, float, Optional[str]]) -> str:
                return m[2] or ""

            matches.sort(key=_sort_key, reverse=True)
            best_node = matches[0][0]
            matched_values = [str(m[1]) for m in matches]

            edge_key = (best_node, b_node_id, b_type, b_val)
            if edge_key in seen_edges:
                continue
            seen_edges.add(edge_key)

            edges.append({
                "type": "data_citation",
                "from": best_node,
                "to": b_node_id,
                "data_values_transferred": matched_values,
                "datum_type": b_type,
            })

    return edges


def _build_decision_gate_edges(
    nodes: Dict[str, Dict[str, Any]],
) -> List[Dict[str, Any]]:
    """Hardcoded structural edges representing AMMO's decision gates.

    baseline_capture → bottleneck_mining → debate → each impl_* →
    integration (if exists) → campaign_eval (if exists)
    """
    edges = []
    node_ids = set(nodes.keys())

    impl_nodes = sorted(nid for nid in node_ids if nid.startswith("impl_"))

    def _add(from_id: str, to_id: str) -> None:
        if from_id in node_ids and to_id in node_ids:
            edges.append({
                "type": "decision_gate",
                "from": from_id,
                "to": to_id,
            })

    # Pipeline structural order
    if "baseline_capture" in node_ids and "bottleneck_mining" in node_ids:
        _add("baseline_capture", "bottleneck_mining")

    if "bottleneck_mining" in node_ids and "debate" in node_ids:
        _add("bottleneck_mining", "debate")

    # debate → each impl_*
    for impl_id in impl_nodes:
        _add("debate", impl_id)

    # each impl_* → integration or campaign_eval
    for impl_id in impl_nodes:
        if "integration" in node_ids:
            _add(impl_id, "integration")
        elif "campaign_eval" in node_ids:
            _add(impl_id, "campaign_eval")

    if "integration" in node_ids and "campaign_eval" in node_ids:
        _add("integration", "campaign_eval")

    return edges


# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------

def build_dag(events: List[Dict[str, Any]], artifact_dir: str) -> Dict[str, Any]:
    """Build a coarse stage-level causal DAG from an events list.

    Args:
        events: Structured event list from extract_events.extract_events().
        artifact_dir: Path to the campaign artifact directory (for context).

    Returns:
        DAG dict with schema:
        {
            "version": "1.0",
            "campaign": {"artifact_dir": ...},
            "nodes": [...],
            "edges": [...],
            "summary": {"total_nodes": N, "total_edges": M, ...},
        }
    """
    # Group events into nodes
    nodes = _group_events_into_nodes(events)

    # Build pipeline order (dynamic, including impl_ nodes)
    impl_nodes = sorted(nid for nid in nodes if nid.startswith("impl_"))
    full_pipeline = [
        "baseline_capture",
        "bottleneck_mining",
        "debate",
        *impl_nodes,
        "integration",
        "campaign_eval",
    ]

    # Build all edge types
    edges: List[Dict[str, Any]] = []
    edges.extend(_build_file_dependency_edges(nodes, events))
    edges.extend(_build_message_dependency_edges(nodes, events))
    edges.extend(_build_data_citation_edges(nodes, events, full_pipeline))
    edges.extend(_build_decision_gate_edges(nodes))

    # Strip internal fields from nodes before serializing
    node_list = []
    for node in nodes.values():
        n = {k: v for k, v in node.items() if not k.startswith("_")}
        node_list.append(n)

    # Sort nodes by pipeline order
    def _node_sort_key(n: Dict[str, Any]) -> int:
        nid = n["id"]
        try:
            return full_pipeline.index(nid)
        except ValueError:
            return len(full_pipeline)

    node_list.sort(key=_node_sort_key)

    # Summary
    stage_type_counts: Dict[str, int] = {}
    for n in node_list:
        nid = n["id"]
        if nid == "baseline_capture":
            stage_type_counts["baseline_capture"] = stage_type_counts.get("baseline_capture", 0) + 1
        elif nid == "bottleneck_mining":
            stage_type_counts["bottleneck_mining"] = stage_type_counts.get("bottleneck_mining", 0) + 1
        elif nid == "debate":
            stage_type_counts["debate"] = stage_type_counts.get("debate", 0) + 1
        elif nid.startswith("impl_"):
            stage_type_counts["impl"] = stage_type_counts.get("impl", 0) + 1
        elif nid == "integration":
            stage_type_counts["integration"] = stage_type_counts.get("integration", 0) + 1
        elif nid == "campaign_eval":
            stage_type_counts["campaign_eval"] = stage_type_counts.get("campaign_eval", 0) + 1
        else:
            stage_type_counts["other"] = stage_type_counts.get("other", 0) + 1

    summary = {
        "total_nodes": len(node_list),
        "total_edges": len(edges),
        "stage_type_counts": stage_type_counts,
        "edge_type_counts": _count_by_type(edges, "type"),
    }

    return {
        "version": "1.0",
        "campaign": {"artifact_dir": str(artifact_dir)},
        "nodes": node_list,
        "edges": edges,
        "summary": summary,
    }


def _count_by_type(items: List[Dict[str, Any]], key: str) -> Dict[str, int]:
    counts: Dict[str, int] = {}
    for item in items:
        v = item.get(key, "unknown")
        counts[v] = counts.get(v, 0) + 1
    return counts


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------

def main() -> int:
    p = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    p.add_argument("--events", required=True, help="Path to events.json")
    p.add_argument(
        "--artifact-dir",
        required=True,
        help="Path to campaign artifact directory",
    )
    p.add_argument("--output", required=True, help="Output path for DAG JSON")

    args = p.parse_args()

    events_path = Path(args.events)
    if not events_path.exists():
        print(f"ERROR: events file not found: {events_path}", file=sys.stderr)
        return 1

    try:
        events = json.loads(events_path.read_text(encoding="utf-8"))
    except (json.JSONDecodeError, OSError) as e:
        print(f"ERROR reading events: {e}", file=sys.stderr)
        return 1

    dag = build_dag(events=events, artifact_dir=args.artifact_dir)

    out_path = Path(args.output)
    out_path.write_text(json.dumps(dag, indent=2, default=str) + "\n", encoding="utf-8")
    print(
        f"Wrote DAG with {dag['summary']['total_nodes']} nodes and "
        f"{dag['summary']['total_edges']} edges to: {out_path}",
        file=sys.stderr,
    )
    return 0


if __name__ == "__main__":
    sys.exit(main())
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall