---
title: "Establishing Traceability"
description: "Create links between artifacts to build a complete traceability graph"
---

# Establishing Traceability

Traceability is the core value proposition of TraceRTM. By linking artifacts together, you can answer questions like:

- Which tests verify this feature?
- What code implements this requirement?
- If I change this API, what tests need updating?
- Is this feature fully covered?

## The Traceability Graph

TraceRTM models your project as a directed graph:

```
                    ┌─────────────┐
                    │   FEAT-001  │
                    │User Login   │
                    └──────┬──────┘
                           │
          ┌────────────────┼────────────────┐
          │ realized_by    │ verified_by    │ depends_on
          ▼                ▼                ▼
    ┌──────────┐    ┌──────────┐    ┌──────────┐
    │ CODE-001 │    │ TEST-001 │    │ FEAT-002 │
    │auth.py   │    │test_login│    │Session   │
    └────┬─────┘    └──────────┘    └──────────┘
         │ tests
         ▼
    ┌──────────┐
    │ TEST-002 │
    │unit tests│
    └──────────┘
```

## Link Types

TraceRTM supports semantic link types:

| Link Type | From | To | Meaning |
|-----------|------|-----|---------|
| `implements` | CODE | FEATURE | Code implements the feature |
| `realized_by` | FEATURE | CODE | Feature is realized by code |
| `tests` | TEST | FEATURE/CODE | Test verifies the target |
| `verified_by` | FEATURE/CODE | TEST | Target is verified by test |
| `depends_on` | any | any | Source depends on target |
| `blocks` | any | any | Source blocks target |
| `parent_of` | any | any | Hierarchical parent |
| `child_of` | any | any | Hierarchical child |
| `related_to` | any | any | General relationship |

## Creating Links

### CLI

```bash
# Feature is implemented by code
tracertm link CODE-001 FEAT-001 --type implements

# Test verifies feature
tracertm link TEST-001 FEAT-001 --type tests

# Feature depends on another feature
tracertm link FEAT-001 FEAT-002 --type depends_on

# With metadata
tracertm link TEST-001 FEAT-001 --type tests \
  --metadata '{"coverage": "partial", "test_type": "integration"}'
```

### Python SDK

```python
from tracertm import TraceRTMClient

client = TraceRTMClient()

# Create implementation link
client.create_link(
    source_id="CODE-001",
    target_id="FEAT-001",
    link_type="implements"
)

# Create test link with metadata
client.create_link(
    source_id="TEST-001",
    target_id="FEAT-001",
    link_type="tests",
    metadata={
        "coverage": "full",
        "test_type": "integration"
    }
)

# Create dependency
client.create_link(
    source_id="FEAT-001",
    target_id="FEAT-002",
    link_type="depends_on"
)
```

### In Markdown (Local Storage)

```markdown
<!-- artifacts/features/FEAT-001.md -->
---
id: FEAT-001
title: User Authentication
links:
  - target: CODE-001
    type: realized_by
  - target: TEST-001
    type: verified_by
  - target: TEST-002
    type: verified_by
  - target: FEAT-002
    type: depends_on
---
```

## Querying the Graph

### Get Linked Items

```bash
# Get all tests for a feature
tracertm links FEAT-001 --type verified_by

# Get all code implementing a feature
tracertm links FEAT-001 --type realized_by

# Get dependencies
tracertm links FEAT-001 --type depends_on
```

```python
# Get tests for feature
tests = client.get_linked_items("FEAT-001", link_type="verified_by")
for test in tests:
    print(f"{test.id}: {test.title}")

# Get all outgoing links
links = client.get_links(source_id="FEAT-001")

# Get all incoming links
links = client.get_links(target_id="FEAT-001")
```

### Traverse the Graph

```python
# Find all artifacts within 2 hops of FEAT-001
related = client.traverse(
    start_id="FEAT-001",
    max_depth=2,
    link_types=["implements", "tests", "depends_on"]
)

# Find path between two artifacts
path = client.find_path(
    source_id="TEST-001",
    target_id="FEAT-003"
)
# Returns: TEST-001 -> FEAT-001 -> FEAT-003
```

## Impact Analysis

When something changes, find what's affected:

### CLI

```bash
# What's affected if FEAT-001 changes?
tracertm impact FEAT-001

# Output:
# Impact Analysis for FEAT-001 (User Authentication)
# ────────────────────────────────────────────────────
# Direct Impact:
#   CODE-001: auth.py (implements)
#   TEST-001: test_login_valid (tests)
#   TEST-002: test_login_invalid (tests)
#
# Indirect Impact (2 hops):
#   TEST-003: test_auth_unit (tests CODE-001)
#   FEAT-003: Dashboard (depends_on FEAT-001)
#
# Total: 5 artifacts affected
```

### Python SDK

```python
# Get impact analysis
impact = client.analyze_impact("FEAT-001")

print(f"Direct impact: {len(impact['direct'])} artifacts")
print(f"Indirect impact: {len(impact['indirect'])} artifacts")

for item in impact['direct']:
    print(f"  {item.id}: {item.title} ({item.link_type})")

# Filter by type
tests_affected = [i for i in impact['all'] if i.item_type == 'test']
print(f"Tests to update: {len(tests_affected)}")
```

## Traceability Matrix

Generate a matrix showing relationships between artifact types:

### CLI

```bash
# Feature to Test matrix
tracertm matrix --rows feature --cols test

# Output:
#              TEST-001  TEST-002  TEST-003  Coverage
# FEAT-001        ✓         ✓                  66%
# FEAT-002        ✓         ✓         ✓       100%
# FEAT-003                                      0%
```

### Python SDK

```python
# Generate matrix
matrix = client.generate_matrix(
    row_type="feature",
    col_type="test",
    project_id="proj-001"
)

# Access data
for row in matrix.rows:
    print(f"{row.id}: {row.coverage_percent}% covered")
    for col_id, linked in row.cells.items():
        if linked:
            print(f"  ✓ {col_id}")
```

## Cycle Detection

Circular dependencies can indicate design issues:

```bash
# Check for cycles
tracertm cycles

# Output:
# Cycle detected:
#   FEAT-001 depends_on FEAT-002 depends_on FEAT-003 depends_on FEAT-001
```

```python
cycles = client.detect_cycles()

if cycles:
    print("Warning: Circular dependencies found!")
    for cycle in cycles:
        print(" -> ".join(cycle))
```

## Auto-Linking with Agents

Let AI agents discover and create links:

```python
from tracertm import TraceRTMClient

client = TraceRTMClient(agent_id="auto-linker")

# Agent analyzes code and creates links
def analyze_and_link():
    # Get all code artifacts
    code_items = client.get_items(item_type="code")
    features = client.get_items(item_type="feature")

    for code in code_items:
        # Analyze code content for feature references
        content = code.metadata.get("content", "")

        for feature in features:
            # Look for feature ID in comments
            if feature.id in content:
                client.create_link(
                    source_id=code.id,
                    target_id=feature.id,
                    link_type="implements",
                    metadata={"auto_linked": True, "confidence": 0.9}
                )
```

## Link Validation

Ensure links are valid and complete:

```bash
# Validate all links
tracertm validate links

# Output:
# Link Validation Report
# ──────────────────────
# ✓ 45 valid links
# ✗ 2 broken links (target deleted)
# ⚠ 3 features without tests
# ⚠ 5 code without implementation links
```

```python
validation = client.validate_links()

if validation['broken']:
    for link in validation['broken']:
        print(f"Broken: {link.source_id} -> {link.target_id}")

if validation['missing_coverage']:
    for item in validation['missing_coverage']:
        print(f"No tests: {item.id}")
```

## Best Practices

### 1. Link as You Go

Create links when you create artifacts:

```python
# Create feature and its test together
feature = client.create_item(title="User Login", item_type="feature")
test = client.create_item(title="Test Login Flow", item_type="test")
client.create_link(test.id, feature.id, "tests")
```

### 2. Use Semantic Link Types

- Use `implements` not `related_to` for code-to-feature
- Use `tests` not `related_to` for test-to-feature
- Reserve `related_to` for informal connections

### 3. Document Link Metadata

```python
client.create_link(
    source_id="TEST-001",
    target_id="FEAT-001",
    link_type="tests",
    metadata={
        "coverage": "partial",  # full, partial, minimal
        "test_type": "integration",
        "automated": True,
        "last_verified": "2024-12-07"
    }
)
```

### 4. Review Orphans Regularly

```bash
# Find artifacts with no links
tracertm list --orphans
```

## Next Steps

- [Generating Reports](/docs/getting-started/first-project/reports) - Traceability reports
- [Impact Analysis](/docs/wiki/concepts/impact-analysis) - Deep dive
- [Agent Coordination](/docs/wiki/concepts/agent-coordination) - Automated linking

