Skip to main content
ClaudeWave
Skill85 estrellas del repoactualizado 3mo ago

code-instrumentation-generator

Automatically instruments source code to collect runtime information such as function calls, branch decisions, variable values, and execution traces while preserving original program semantics. Use when users need to: (1) Add logging or tracing to code for debugging, (2) Collect runtime execution data for analysis, (3) Monitor function calls and control flow, (4) Track variable values during execution, (5) Generate execution traces for testing or profiling. Supports Python, Java, JavaScript, and C/C++ with configurable instrumentation levels.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE /tmp/code-instrumentation-generator && cp -r /tmp/code-instrumentation-generator/skills/code-instrumentation-generator ~/.claude/skills/code-instrumentation-generator
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# Code Instrumentation Generator

Automatically instrument source code to collect runtime information while preserving program semantics.

## Workflow

Follow these steps to instrument code:

### 1. Analyze the Source Code

Understand the code structure and identify instrumentation points:

- **Language detection**: Identify the programming language
- **Code structure**: Parse functions, classes, branches, loops
- **Entry/exit points**: Locate function boundaries
- **Control flow**: Identify branches (if/else, switch, loops)
- **Variable scope**: Understand variable declarations and usage

### 2. Determine Instrumentation Strategy

Choose appropriate instrumentation based on requirements:

**Instrumentation levels:**
- **Function-level**: Entry/exit of functions with parameters and return values
- **Branch-level**: Execution of conditional branches (if/else, switch cases)
- **Statement-level**: Individual statement execution
- **Variable-level**: Variable assignments and value changes

**Configuration options:**
- Enable/disable specific instrumentation types
- Filter by function names or file patterns
- Set verbosity level
- Choose output format (logs, JSON, CSV)

### 3. Insert Instrumentation Code

Add instrumentation hooks at identified points:

**Function instrumentation:**
- Insert entry hook at function start
- Capture function name, parameters, timestamp
- Insert exit hook before returns
- Capture return value, execution time

**Branch instrumentation:**
- Insert hooks at branch conditions
- Record which branch was taken
- Track branch coverage

**Variable instrumentation:**
- Insert hooks after variable assignments
- Capture variable name and value
- Track value changes over time

### 4. Ensure Semantic Preservation

Verify that instrumentation doesn't change program behavior:

- **No side effects**: Instrumentation code doesn't modify program state
- **Exception safety**: Instrumentation handles exceptions properly
- **Performance**: Minimal overhead added
- **Thread safety**: Instrumentation is safe in concurrent code

### 5. Generate Output

Provide instrumented code and documentation:

- **Instrumented source code**: Modified code with instrumentation
- **Probe description**: Documentation of inserted instrumentation points
- **Configuration file**: Settings to enable/disable instrumentation
- **Usage instructions**: How to run and collect data

## Language-Specific Patterns

### Python

```python
# Original code
def calculate_sum(a, b):
    result = a + b
    return result

# Instrumented code
import logging
logging.basicConfig(level=logging.INFO)

def calculate_sum(a, b):
    # Function entry instrumentation
    logging.info(f"ENTER calculate_sum(a={a}, b={b})")

    result = a + b
    # Variable instrumentation
    logging.info(f"VAR result={result}")

    # Function exit instrumentation
    logging.info(f"EXIT calculate_sum() -> {result}")
    return result
```

### Java

```java
// Original code
public int calculateSum(int a, int b) {
    int result = a + b;
    return result;
}

// Instrumented code
public int calculateSum(int a, int b) {
    // Function entry instrumentation
    System.out.println("ENTER calculateSum(a=" + a + ", b=" + b + ")");

    int result = a + b;
    // Variable instrumentation
    System.out.println("VAR result=" + result);

    // Function exit instrumentation
    System.out.println("EXIT calculateSum() -> " + result);
    return result;
}
```

### JavaScript

```javascript
// Original code
function calculateSum(a, b) {
    const result = a + b;
    return result;
}

// Instrumented code
function calculateSum(a, b) {
    // Function entry instrumentation
    console.log(`ENTER calculateSum(a=${a}, b=${b})`);

    const result = a + b;
    // Variable instrumentation
    console.log(`VAR result=${result}`);

    // Function exit instrumentation
    console.log(`EXIT calculateSum() -> ${result}`);
    return result;
}
```

### C/C++

```c
// Original code
int calculate_sum(int a, int b) {
    int result = a + b;
    return result;
}

// Instrumented code
#include <stdio.h>

int calculate_sum(int a, int b) {
    // Function entry instrumentation
    printf("ENTER calculate_sum(a=%d, b=%d)\n", a, b);

    int result = a + b;
    // Variable instrumentation
    printf("VAR result=%d\n", result);

    // Function exit instrumentation
    printf("EXIT calculate_sum() -> %d\n", result);
    return result;
}
```

## Branch Instrumentation Example

```python
# Original code
def check_value(x):
    if x > 0:
        return "positive"
    else:
        return "non-positive"

# Instrumented code
def check_value(x):
    logging.info(f"ENTER check_value(x={x})")

    # Branch instrumentation
    if x > 0:
        logging.info("BRANCH if(x > 0) -> TRUE")
        result = "positive"
    else:
        logging.info("BRANCH if(x > 0) -> FALSE")
        result = "non-positive"

    logging.info(f"EXIT check_value() -> {result}")
    return result
```

## Configuration-Based Instrumentation

Generate a configuration file to control instrumentation:

```python
# instrumentation_config.py
INSTRUMENTATION_ENABLED = True
INSTRUMENT_FUNCTIONS = True
INSTRUMENT_BRANCHES = True
INSTRUMENT_VARIABLES = False
LOG_LEVEL = "INFO"
OUTPUT_FORMAT = "text"  # or "json", "csv"

# Instrumented code with configuration
import instrumentation_config as config

def calculate_sum(a, b):
    if config.INSTRUMENT_FUNCTIONS:
        logging.info(f"ENTER calculate_sum(a={a}, b={b})")

    result = a + b

    if config.INSTRUMENT_VARIABLES:
        logging.info(f"VAR result={result}")

    if config.INSTRUMENT_FUNCTIONS:
        logging.info(f"EXIT calculate_sum() -> {result}")

    return result
```

## Output Format

### Probe Description Document

```markdown
## Instrumentation Report

**File**: calculator.py
**Instrumentation Date**: 2024-02-17
**Configuration**: Function-level + Branch-level

### Instrumented Functions

1. **calculate_sum(a, b)**
   - Entry probe: Line 3
   - Exit probe
abstract-domain-explorerSkill

Applies abstract interpretation using different abstract domains (intervals, octagons, polyhedra, sign, congruence) to statically analyze program variables and infer invariants, value ranges, and relationships. Use when analyzing program properties, inferring loop invariants, detecting potential errors, or understanding variable relationships through static analysis.

abstract-invariant-generatorSkill

Uses abstract interpretation to automatically infer loop invariants, function preconditions, and postconditions for formal verification. Generates invariants that capture program behavior and support correctness proofs in Dafny, Isabelle, Coq, and other verification systems. Use when adding formal specifications to code, generating verification conditions, inferring contracts for functions, or discovering loop invariants for proofs.

abstract-state-analyzerSkill

Performs abstract interpretation over source code to infer possible program states, variable ranges, and data properties without executing the program. Reports potential runtime errors including out-of-bounds accesses, null dereferences, type inconsistencies, division by zero, and integer overflows. Use when analyzing code for potential runtime errors, performing static analysis, checking safety properties, or verifying program behavior without execution.

abstract-trace-summarizerSkill

Performs abstract interpretation to produce summarized execution traces and high-level program behavior representations. Highlights key control flow paths, variable relationships, loop invariants, function summaries, and potential runtime states using abstract domains (intervals, signs, nullness, etc.). Use when analyzing program behavior, understanding execution paths, computing loop invariants, tracking variable ranges, detecting potential runtime errors, or generating program summaries without concrete execution.

acsl-annotation-assistantSkill

Create ACSL (ANSI/ISO C Specification Language) formal annotations for C/C++ programs. Use this skill when working with formal verification, adding function contracts (requires/ensures), loop invariants, assertions, memory safety annotations, or any ACSL specifications. Supports Frama-C verification and generates comprehensive formal specifications for C/C++ code.

agent-browserSkill

CLI-based browser automation with persistent page state using ref-based element interaction. Use when users ask to navigate websites, interact with web pages, fill forms, take screenshots, test web applications, or extract information from web pages.

ambiguity-detectorSkill

Detects and analyzes ambiguous language in software requirements and user stories. Use when reviewing requirements documents, user stories, specifications, or any software requirement text to identify vague quantifiers, unclear scope, undefined terms, missing edge cases, subjective language, and incomplete specifications. Provides detailed analysis with clarifying questions and suggested improvements.

api-design-assistantSkill

Design and review APIs with suggestions for endpoints, parameters, return types, and best practices. Use when designing new APIs from requirements, reviewing existing API designs, generating API documentation, or getting implementation guidance. Supports REST APIs with focus on endpoint structure, request/response schemas, authentication, pagination, filtering, versioning, and OpenAPI specifications. Triggers when users ask to design, review, document, or improve APIs.