8 min read

The 4-Part Diagnostic Prompt Framework: Context, Invariant, Failure, Constraint

Vague "why is this broken?" prompts produce shallow guesses and fragile patches. Use the repeatable CIFC framework—Context, Invariant, Failure, Constraint—to turn AI into a high-precision diagnostic partner inside multi-file codebases.

By DEBUG//LAB Engineering Team

Why Vague Prompts Fail in Real Repositories

Pasting a stack trace into an LLM and asking "Why is this broken?" works for isolated syntax errors. Inside a multi-file repository, it consistently fails.

Without architectural boundaries or explicit system rules, an LLM optimizes for the shortest path to making the immediate error disappear. That usually means:

  • Wrapping a symptom in a silent try/catch or null check that hides data corruption downstream.
  • Modifying a shared helper's return type and silently breaking three callers in other modules.
  • Suggesting an invasive rewrite or a new dependency when a two-line state-ordering fix was needed.

To get senior-level diagnostics from an AI, you have to prompt like a staff engineer writing a bug report. That is the purpose of the CIFC Framework (Context → Invariant → Failure → Constraint).

CIFC applies core principles from Anthropic's Prompt Engineering Overview and OpenAI's Prompt Engineering Guide—specifically context isolation, clear XML/markdown delimiters, and explicit output constraints—and adapts them directly for debugging multi-file software systems.

The CIFC Breakdown

PillarWhat You ProvideWhat It Prevents
1. ContextRelevant module boundaries, runtime stack, and data flow (only the files on the execution path, not the entire repo)Prevents hallucinated architectures and irrelevant fixes.
2. InvariantThe business rule or system guarantee that must always hold truePrevents patches that silence the error while violating data integrity.
3. FailureExact reproduction steps, failing test output, and expected vs. actual behaviorPrevents generic surface-level guesses.
4. ConstraintHard engineering boundaries (public API signatures, zero new dependencies, time/space complexity limits, Socratic mode)Prevents invasive rewrites and regressions.

1. Context: Bound the Execution Path

More tokens do not equal better debugging. Dumping 15 unrelated files into the context window dilutes attention and increases the chance the model latches onto an irrelevant helper.

Instead, trace the execution path from entry point to failure site and include only:

  • Runtime & stack: Language/framework version, database/cache layer, and execution model (e.g., Node.js 20, Express, PostgreSQL with READ COMMITTED).
  • Call chain: The 2–4 files or functions directly involved in the failing flow.
  • Data shapes: TypeScript interfaces, schemas, or sample payloads crossing those module boundaries.

Use explicit delimiters (like <context> tags or labeled markdown blocks) so the model never confuses your explanation with the source code itself.

2. Invariant: State the Rule That Must Never Break

An LLM cannot infer your domain's non-negotiable guarantees from a single function body. If you do not state the invariant, the model will happily violate it to make a failing test pass.

Good invariants are short, falsifiable statements:

  • "A completed payment webhook must credit the user's ledger balance at most once, even if the provider retries the same event_id concurrently."
  • "Cache invalidation must never serve a stale permission set after a role downgrade."
  • "The parser must remain single-pass O(n) without buffering the entire stream in memory."

Stating the invariant shifts the model's goal from "stop throwing" to "preserve this system guarantee."

3. Failure: Pair the Symptom With a Minimal Repro

Never summarize an error in prose when you have the actual artifact. Provide:

  1. Exact error output: Stack trace, HTTP status, or failing assertion diff.
  2. Expected vs. actual state: What the database row, UI state, or return value should have been versus what you observed.
  3. Reproduction condition: Single request vs. concurrent burst, cold cache vs. warm cache, or specific input edge case.

If the bug only happens under concurrency or specific ordering, say so explicitly—otherwise the model will analyze the code sequentially and miss the race condition.

4. Constraint: Lock Down the Blast Radius

Constraints turn an open-ended code generator into a disciplined reviewer. Always specify:

  • API compatibility: "Do not change exported function signatures or database column types."
  • Dependency hygiene: "Use only existing project utilities; zero new npm packages."
  • Performance bounds: "Keep lookup O(1) and avoid N+1 queries."
  • Diagnostic mode: "Before writing a patch, list the top 2–3 root-cause hypotheses and the exact check to confirm each."

Before vs. After: Debugging a Multi-File Bug

Consider a realistic backend bug: a payment provider retries a webhook while the first request is still in flight, resulting in a double credit across webhookHandler.ts and ledgerService.ts.

Before (Vague Prompt)

text
My payment webhook is sometimes crediting users twice. Here is webhookHandler.ts
and ledgerService.ts. Why is this broken and how do I fix it?

Why this underperforms: Without knowing your isolation level, retry behavior, or API constraints, the model often suggests superficial fixes—like adding an in-memory Set of processed IDs (which fails across multiple server instances) or rewriting your entire queue architecture.

After (CIFC Diagnostic Prompt)

text
<context>
Runtime: Node.js 20, TypeScript, PostgreSQL (READ COMMITTED), 2 stateless API replicas behind a load balancer.
Flow: POST /webhooks/stripe -> `handlePaymentSucceeded()` in `src/webhooks/webhookHandler.ts` -> `creditAccount()` in `src/services/ledgerService.ts`.

[File: src/webhooks/webhookHandler.ts]
export async function handlePaymentSucceeded(event: StripeEvent) {
  const existing = await ledgerRepo.findByEventId(event.id);
  if (existing) return { status: 'already_processed' };
  await ledgerService.creditAccount(event.accountId, event.amountCents, event.id);
  return { status: 'credited' };
}

[File: src/services/ledgerService.ts]
export async function creditAccount(accountId: string, amountCents: number, eventId: string) {
  await db.transaction(async (tx) => {
    await tx.insert(ledgerEntries).values({ accountId, amountCents, eventId });
    await tx.update(accounts).set({ balance: sql`balance + ${amountCents}` }).where(eq(accounts.id, accountId));
  });
}
</context>

<invariant>
Every unique `event.id` must credit the target account at most once, even under concurrent webhook deliveries across multiple replicas.
</invariant>

<failure>
Expected: Duplicate webhook for `evt_123` returns 200 without modifying `accounts.balance`.
Actual: When Stripe delivers two `evt_123` webhooks within 15ms, both pass `findByEventId()` before either transaction commits, crediting `accounts.balance` twice.
</failure>

<constraint>
- Keep `handlePaymentSucceeded` and `creditAccount` signatures unchanged.
- Do not use in-memory locks or introduce Redis/external queues.
- First, explain the exact race window and propose a database-enforced fix.
</constraint>

Why this works: The model immediately pinpoints the check-then-act race condition between findByEventId and creditAccount under READ COMMITTED isolation, rules out in-memory locks, and converges on an atomic idempotency pattern (UNIQUE constraint on ledger_entries.event_id with ON CONFLICT DO NOTHING / returning row check before updating accounts.balance).

Copy-Paste CIFC Prompt Templates

Use these two templates directly in your workflow—copy them with the button in the top-right corner of each block.

Template A: Root-Cause Diagnosis (No Spoilers / Socratic Mode)

text
<context>
Runtime / Stack: [e.g., React 18 + Vite / Node 20 + Postgres]
Execution Path: [Entry point -> Module A -> Module B]

[Paste only the 2-4 relevant files or functions]
</context>

<invariant>
[State the business rule or system guarantee that must never break.]
</invariant>

<failure>
Repro: [Steps or test command]
Expected: [Expected behavior/output]
Actual: [Exact error, stack trace, or wrong state]
</failure>

<constraint>
- Do NOT write a patch or full file rewrite yet.
- Rank the top 2-3 root-cause hypotheses by likelihood, referencing exact symbols/lines.
- For each hypothesis, give me 1 targeted verification question or debugger/log check to confirm or rule it out.
</constraint>

Template B: Regression-Safe Patch Verification

text
<context>
Confirmed Root Cause: [1-2 sentence summary of the verified bug]
Target Files: [Files touched by the proposed fix]

[Paste the proposed diff or updated function]
</context>

<invariant>
[State the core invariant + any secondary invariants that callers depend on.]
</invariant>

<failure>
Previously failing case: [Test case / edge case that triggered the bug]
</failure>

<constraint>
Audit this proposed fix strictly as a senior code reviewer:
1. Does it hold the invariant under concurrency, retries, and null/empty edge cases?
2. Does it preserve existing public API contracts and caller expectations?
3. What is the time and space complexity (verify O(n) / O(1) bounds)?
4. List any remaining failure modes or missing regression tests before merging.
</constraint>

Put CIFC Into Practice

Structured prompting is not a shortcut around understanding code—it is a forcing function for it. To write a clear Context, Invariant, Failure, and Constraint, you have to trace the execution path and reason about system guarantees yourself.

Practice those exact skills inside The Lab and Code Comprehension Practice, and pair this framework with our companion guide, How to Use AI as a Debugging Assistant, to build habits that hold up in production repositories.

Put These Concepts Into Practice on DEBUG//LAB

Work through realistic multi-file repository challenges in The Lab, or sharpen your algorithmic intuition with Plain & Simple DSA.