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

scripts/hook_cmd_classify.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
"""Shell-command classifier for the AMMO shell hooks. Stdlib only.

Why this file exists
--------------------
Two blocking shell hooks used anchored `grep -P` regexes to classify a Bash
command, and a single token defeated both:

  * the read-only fast path in the PreToolUse campaign guard anchored at the
    START of the command string, so `cat notes.md && vllm bench latency ...`
    silenced every warning AND both hard blocks behind it;
  * the package-install deny required the verb to sit IMMEDIATELY after the
    invoker, so `pip -q install`, `/usr/bin/pip install`, and
    `bash -c "pip install"` all passed.

A regex cannot express "every segment of this pipeline is inspection-class" or
"an install verb appears in command position after unwrapping env/sudo/nested
shells". A tokenizer can, and this module is it.

This module is the ONLY implementation. The shell hooks call its CLI;
`.codex/hooks/common.py` re-exports `is_static_inspection_command` and its
helpers from here, and `.codex/hooks/pre_tool_use_guard.py` imports
`command_installs`. Nothing carries a second copy, so the two runtimes cannot
drift apart. `test_hook_cmd_classify_parity.py` pins the verdicts.

Interface
---------
    hook_cmd_classify.py --mode readonly [COMMAND]
    hook_cmd_classify.py --mode install  [COMMAND]

COMMAND is read from argv when present, otherwise from stdin. Exit codes are
the verdict, so a shell hook can branch with a bare `if`:

    0  verdict TRUE   (readonly: every segment is inspection-class /
                       install: a package install-or-uninstall was found)
    1  verdict FALSE
    2  usage error or an internal fault -- the CALLER decides fail-open vs
       fail-closed, this module never decides for it.

The verdict token (`READONLY` / `NOT_READONLY` / `INSTALL` / `NO_INSTALL`) is
also printed on stdout, for harnesses and for hooks that prefer text.
"""

from __future__ import annotations

import argparse
import re
import shlex
import sys
from pathlib import Path

# --------------------------------------------------------------------------
# Tokenizing. Two lexers, deliberately: `readonly` needs shlex.split's view of
# redirections and command substitutions as ordinary tokens so it can reject
# them; `install` needs punctuation_chars so `&&`/`;`/`|` split into segments.
# --------------------------------------------------------------------------

_SEGMENT_SEPARATORS = {"&&", ";", "||", "|"}
_PUNCTUATION_CHARS = ";&|()`"


def split_shell_command(command):
    """shlex.split, [] on an unbalanced quote."""
    try:
        return shlex.split(command or "")
    except ValueError:
        return []


def _package_guard_tokens(command):
    """Punctuation-aware lexer: `&&` / `;` / `|` become their own tokens."""
    try:
        lexer = shlex.shlex(command, posix=True, punctuation_chars=_PUNCTUATION_CHARS)
        lexer.whitespace_split = True
        lexer.commenters = ""
        return list(lexer)
    except ValueError:
        return []


# --------------------------------------------------------------------------
# readonly: is_static_inspection_command and its helpers
# --------------------------------------------------------------------------

_INSPECTION_EXECUTABLES = {
    "rg", "grep", "cat", "head", "tail", "less", "find", "ag", "ack", "env",
    "printenv", "echo", "printf", "jq", "wc", "sqlite3", "ls", "stat", "file",
    "tree", "du", "pwd", "realpath", "readlink", "dirname", "basename",
}
_READ_ONLY_GIT_VERBS = {"log", "show", "diff", "blame", "status", "branch", "tag"}


def _command_segments(parts):
    segments = []
    current = []
    for token in parts:
        if token in _SEGMENT_SEPARATORS:
            if current:
                segments.append(current)
                current = []
        else:
            current.append(token)
    if current:
        segments.append(current)
    return segments


def _first_executable_index(parts):
    skip_next_for = {"timeout"}
    idx = 0
    while idx < len(parts):
        token = parts[idx]
        if token in {"(", ")"}:
            return -1
        if token in {"env", "command", "time"} or re.fullmatch(
            r"[A-Za-z_][A-Za-z0-9_]*=.*", token
        ):
            idx += 1
            continue
        if token in skip_next_for:
            idx += 2
            continue
        return idx
    return -1


def _executable_segments(parts):
    resolved = []
    for segment in _command_segments(parts):
        idx = _first_executable_index(segment)
        if idx >= 0:
            resolved.append((Path(segment[idx]).name, segment[idx + 1:]))
    return resolved


def _is_python_executable_name(name):
    return bool(re.fullmatch(r"python(?:\d+(?:\.\d+)?)?", name))


def _is_read_only_python_snippet(text):
    lowered = text.lower()
    blocked = [
        r"\b(torch|vllm|triton|cupy|tensorflow|jax)\b",
        r"\b(subprocess|os\.system|popen|runpy|exec|eval)\b",
        r"\b(json\.dump|pickle\.dump)\b",
        r"\b(write_text|write_bytes|\.write\s*\(|mkdir|touch|unlink|remove|rename|replace|rmtree|copyfile)\b",
        r"\bopen\s*\([^)]*,\s*[\"'][wa+x]",
    ]
    if any(re.search(pattern, lowered) for pattern in blocked):
        return False
    read_markers = [
        r"\bjson\.load[s]?\b",
        r"\bread_text\s*\(",
        r"\bread_bytes\s*\(",
        r"\bopen\s*\(",
        r"\bstate\.json\b",
    ]
    return "json" in lowered and any(re.search(p, lowered) for p in read_markers)


def _is_read_only_python_segment(tail):
    if not tail:
        return False
    first = tail[0]
    if first in {"-V", "--version", "-VV", "--help", "-h"}:
        return True
    if len(tail) >= 2 and first == "-m" and tail[1] in {"json.tool"}:
        return True
    if len(tail) >= 2 and first == "-c":
        return _is_read_only_python_snippet(" ".join(tail[1:]))
    if first == "-":
        return _is_read_only_python_snippet(" ".join(tail[1:]))
    return False


def is_static_inspection_command(command):
    """True only when EVERY executable segment is inspection-class.

    A read-only executable can still mutate through shell plumbing, so every
    redirection, heredoc/process substitution, and command substitution makes
    the whole command non-static -- callers then take their fail-closed path.
    """
    parts = split_shell_command(command)
    if any(
        token in {">", ">>", "<>", "&>", "&>>", "<<", "<<<"}
        or ">" in token
        or token.startswith(("<(", ">("))
        or "$(" in token
        or "`" in token
        for token in parts
    ):
        return False
    segments = [(name, tail) for name, tail in _executable_segments(parts) if name != "cd"]
    if not segments:
        return False
    for name, tail in segments:
        if name == "sed":
            if any(token == "-i" or token.startswith("-i") for token in tail):
                return False
            continue
        if name == "git":
            if not tail or tail[0] not in _READ_ONLY_GIT_VERBS:
                return False
            continue
        if _is_python_executable_name(name) and _is_read_only_python_segment(tail):
            continue
        if name not in _INSPECTION_EXECUTABLES:
            return False
    return True


def is_inspection_only(command):
    """`is_static_inspection_command` per SEGMENT, using the punctuation lexer.

    Strictly more conservative than `is_static_inspection_command`, in one
    direction only: it can turn a READONLY verdict into NOT_READONLY, never the
    reverse. The parity test pins that one-directional relation.

    Why the extra pass: `shlex.split` does not treat `;` as a token boundary,
    so `echo hi; nsys profile python bench.py` lexes `hi;` as one word and the
    static form sees a single `echo` segment -- READONLY, with an nsys run
    hiding behind it. The punctuation-aware lexer splits that command properly,
    and each resulting segment is then judged by the static form itself.

    A NOT_READONLY verdict only costs the caller its fast path: the guard then
    evaluates the command normally. So being conservative here adds no block
    the guard would not otherwise have considered.
    """
    tokens = _package_guard_tokens(command)
    if not tokens:
        # An unbalanced quote yields no tokens; the static form reaches the
        # same verdict through its own empty-token path.
        return is_static_inspection_command(command)
    segments = list(_punct_segments(tokens))
    if not segments:
        return False
    return all(
        is_static_inspection_command(shlex.join(segment)) for segment in segments
    )


# --------------------------------------------------------------------------
# install: command_installs and its helpers
# --------------------------------------------------------------------------

_INSTALL_VERBS = {"install", "uninstall"}
_NESTED_SHELLS = {"bash", "sh", "zsh", "dash", "ksh"}


def _punct_segments(tokens):
    current = []
    for token in tokens:
        if token and all(ch in _PUNCTUATION_CHARS for ch in token):
            if current:
                yield current
                current = []
        else:
            current.append(token)
    if current:
        yield current


def _drop_assignments(tokens):
    idx = 0
    while idx < len(tokens) and re.fullmatch(
        r"[A-Za-z_][A-Za-z_0-9]*=.*", tokens[idx], re.DOTALL
    ):
        idx += 1
    return tokens[idx:]


def _unwrap_command(tokens):
    """Strip env-var assignments and the env / command / sudo wrappers."""
    tokens = _drop_assignments(tokens)
    while tokens:
        name = Path(tokens[0]).name
        if name == "env":
            idx = 1
            while idx < len(tokens):
                token = tokens[idx]
                if token in {"-u", "--unset"} and idx + 1 < len(tokens):
                    idx += 2
                elif token.startswith("-") or re.fullmatch(
                    r"[A-Za-z_][A-Za-z_0-9]*=.*", token, re.DOTALL
                ):
                    idx += 1
                else:
                    break
            tokens = tokens[idx:]
            continue
        if name == "command":
            if any(token in {"-v", "-V"} for token in tokens[1:]):
                return []
            idx = 1
            while idx < len(tokens) and tokens[idx].startswith("-"):
                idx += 1
            tokens = tokens[idx:]
            continue
        if name == "sudo":
            idx = 1
            while idx < len(tokens) and tokens[idx].startswith("-"):
                idx += 1
            tokens = tokens[idx:]
            continue
        break
    return tokens


def _has_install_verb(tokens):
    return any(token in _INSTALL_VERBS for token in tokens)


def _segment_installs(tokens, depth=0):
    tokens = _unwrap_command(tokens)
    if not tokens:
        return False
    name = Path(tokens[0]).name
    args = tokens[1:]
    if re.fullmatch(r"pip\d*", name):
        return _has_install_verb(args)
    if re.fullmatch(r"python(?:\d+(?:\.\d+)?)?", name):
        for idx, token in enumerate(args[:-1]):
            if token == "-m" and Path(args[idx + 1]).name == "pip":
                return _has_install_verb(args[idx + 2:])
        return False
    if name == "uv":
        for idx, token in enumerate(args):
            if token == "pip":
                return _has_install_verb(args[idx + 1:])
        return False
    if name in _NESTED_SHELLS and depth < 3:
        for idx, token in enumerate(args[:-1]):
            if token == "-c" or (token.startswith("-") and "c" in token[1:]):
                return command_installs(args[idx + 1], depth + 1)
    return False


def command_installs(command, depth=0):
    """True when any segment invokes a package install/uninstall.

    Command position only: a quoted mention (`grep "pip install"`) is an
    argument, not an invoker, and does not match.
    """
    tokens = _package_guard_tokens(command)
    return any(_segment_installs(segment, depth) for segment in _punct_segments(tokens))


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

MODES = {
    # readonly uses the per-segment form: a hook's fast path must require EVERY
    # segment to be inspection-class, not just the one the reference lexer saw.
    "readonly": (is_inspection_only, "READONLY", "NOT_READONLY"),
    "install": (command_installs, "INSTALL", "NO_INSTALL"),
}


def main(argv=None):
    ap = argparse.ArgumentParser(
        description="Classify a shell command for the AMMO hooks.",
        epilog="exit 0 = verdict true, 1 = verdict false, 2 = usage/internal fault",
    )
    ap.add_argument("--mode", required=True, choices=sorted(MODES))
    ap.add_argument(
        "command",
        nargs="?",
        help="the command string; read from stdin when omitted",
    )
    try:
        args = ap.parse_args(argv)
    except SystemExit:
        return 2

    command = args.command
    if command is None:
        try:
            command = sys.stdin.read()
        except OSError:
            return 2

    predicate, yes, no = MODES[args.mode]
    try:
        verdict = predicate(command or "")
    except Exception:  # a classifier fault must not read as a verdict
        return 2
    print(yes if verdict else no)
    return 0 if verdict else 1


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