rag-failure-trace

rag-failure-trace is a command for Claude Code from kumaran-is/claude-code-onboarding. It costs 20 tokens per session (1,594 once invoked), scanned A, original, MIT.

A command for recording a complete audit trail of a RAG query, where RAG means answering with information retrieved from a document or vector store.

In plain words
What is it for?
Use it to debug a RAG request, preserve a failure for regression tests, or verify that users only receive permitted information.
Why use it?
It helps reveal which pipeline stages caused a failed answer and provides evidence for checking access-control rules.

Command for Claude Code

Written for Claude Code: argument-hint in frontmatter.

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add commands/kumaran-is/claude-code-onboarding/rag-failure-trace
Clone the repo
git clone --depth 1 https://github.com/kumaran-is/claude-code-onboarding

Made for: Claude Code.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for rag-failure-trace

README.md
[![agentmods](https://agentmods.dev/badge/commands/kumaran-is/claude-code-onboarding/rag-failure-trace.svg)](https://agentmods.dev/commands/kumaran-is/claude-code-onboarding/rag-failure-trace)
Your own site
<a href="https://agentmods.dev/commands/kumaran-is/claude-code-onboarding/rag-failure-trace"><img src="https://agentmods.dev/badge/commands/kumaran-is/claude-code-onboarding/rag-failure-trace.svg" alt="Measured on agentmods" height="20"></a>
Per session 20 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 1,594 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00020 $0.01594
Opus 5 $0.00010 $0.00797
Sonnet 5 $0.00004 $0.00319
Haiku 4.5 $0.00002 $0.00159

Measured 2d ago against content hash db0837fc75c3, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-06, from the pricing page.

Security

Grade A, and why

rag-failure-trace scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

.claude/commands/rag-failure-trace.md · 188 lines

How it starts

The opening of the file, as written. The whole thing — 188 lines — stays where its author put it; the contents beside it link to each section on GitHub.

/rag-failure-trace — Capture Full RAG Audit Trace

Capture a complete audit trace for a query, conforming to the playbook §39.2 audit schema. Useful for debugging a specific failure, adding to the golden set, or demonstrating ACL enforcement.

Query: $ARGUMENTS

Phase 1: Identify the pipeline

Find the user's RAG pipeline entry point. Ask if unclear:

  • Path to the main RAG handler / endpoint
  • How to invoke it locally (CLI, test, script)
  • Whether they want to invoke against dev / staging / prod data

Phase 2: Run the query with instrumentation

If the pipeline already emits audit logs (§39.2), grab the latest. Otherwise, add temporary instrumentation:

# Temporary tracing wrapper — for trace capture only, not for production
import json
import time
import uuid
from datetime import datetime, timezone


def trace_rag_call(rag_pipeline, query: str, user_context: dict) -> dict:
    trace = {
        "response_id": f"trace-{uuid.uuid4()}",
        "generated_at": datetime.now(timezone.utc).isoformat(),
        "query": query,
        "user_id": user_context.get("user_id"),
        "tenant_id": user_context.get("tenant_id"),
        "stages": {},
    }

    # Stage 1: query understanding & classification
    t0 = time.perf_counter()
    classified = rag_pipeline.classify(query)
    trace["stages"]["classification"] = {
        "result": classified,
        "latency_ms": (time.perf_counter() - t0) * 1000,
    }

    # Stage 2: filters
    filters = rag_pipeline.build_filters(user_context, classified)
    trace["stages"]["filters_applied"] = filters

    # Stage 3: retrieval
    t0 = time.perf_counter()
    dense_results = rag_pipeline.dense_retrieve(query, filters=filters, top_k=50)
    sparse_results = rag_pipeline.sparse_retrieve(query, filters=filters, top_k=50)
    trace["stages"]["retrieval"] = {
        "dense_top10": [{"chunk_id": c.id, "score": c.score} for c in dense_results[:10]],
        "sparse_top10": [{"chunk_id": c.id, "score": c.score} for c in sparse_results[:10]],
        "latency_ms": (time.perf_counter() - t0) * 1000,
    }

    # Stage 4: fusion
    fused = rag_pipeline.rrf_fuse([dense_results, sparse_results])
    trace["stages"]["fusion"] = {
        "method": "RRF(k=60)",
        "top10_after_fusion": [{"chunk_id": c.id, "rrf_score": c.rrf_score} for c in fused[:10]],
    }

    # Stage 5: rerank
    t0 = time.perf_counter()
    reranked = rag_pipeline.rerank(query, fused[:100])
    trace["stages"]["rerank"] = {
        "top10_after_rerank": [{"chunk_id": c.id, "rerank_score": c.rerank_score} for c in reranked[:10]],
        "latency_ms": (time.perf_counter() - t0) * 1000,
    }

    # Stage 6: abstention check
    top1_score = reranked[0].rerank_score if reranked else 0
    abstention_threshold = rag_pipeline.abstention_threshold
    abstained = top1_score < abstention_threshold
    trace["stages"]["abstention"] = {
        "top1_score": top1_score,
        "threshold": abstention_threshold,
        "abstained": abstained,
    }

    if abstained:
        trace["final_response"] = "I don't have enough information to answer that."
        trace["abstained"] = True
        return trace

    # Stage 7: context packing
    packed = rag_pipeline.pack_context(reranked[:5])
    trace["stages"]["context_packing"] = {
        "chunks_packed": [{"chunk_id": c.id, "document_id": c.document_id, "version": c.version} for c in packed],
        "total_tokens": rag_pipeline.count_tokens(packed),
    }

    # Stage 8: generation
    t0 = time.perf_counter()
    response = rag_pipeline.generate(query, packed)
    trace["stages"]["generation"] = {
        "model": rag_pipeline.model_name,
        "prompt_template_version": rag_pipeline.prompt_version,
        "latency_ms": (time.perf_counter() - t0) * 1000,
    }

    trace["final_response"] = response.answer
    trace["citations"] = response.citations
    trace["abstained"] = False

    return trace


# Save the trace
trace = trace_rag_call(my_rag_pipeline, "$ARGUMENTS", user_context={...})
with open(f"traces/{trace['response_id']}.json", "w") as f:
    json.dump(trace, f, indent=2)

Read the full file on GitHub · 188 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 188 lines · 20 tokens per session scan A db0837fc75c3

Subscribe to this mod's changes

rag-failure-trace is a command published in the GitHub repository kumaran-is/claude-code-onboarding (35 stars, last pushed 2mo ago), licensed MIT. It adds 20 tokens to every session and 1,594 once invoked, about $0.0001 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-09-03.