med dataset. Producer-first reading identified the correct filter logic in under 5 minutes, whereas rule-first framing led to a 25-minute exploration of irrelevant SQL paths.
- Scale Asymmetry: Feedback files accumulate faster than verification discipline. Without explicit scope constraints, rule overlap creates contradictory hypotheses, degrading agent reliability over time.
Core Solution
The solution is the Meta-Guarded Memory Architecture. This pattern introduces an interception layer that enforces producer verification before any memorized rule is invoked. Instead of treating memory files as direct verdicts, they are treated as hypotheses that require context validation.
Architecture Decisions
- Interception Protocol: A meta-feedback file acts as a gatekeeper. It defines valid and invalid contexts for specific rules. The agent must evaluate the meta-guard before accessing the rule file.
- Scope Constraints: Every rule must declare its valid data producers and invalid transformations. This prevents global application of local invariants.
- Verification Order: The workflow is strictly ordered:
Open Producer → Verify Transformations → Check Filter Semantics → Evaluate Meta-Guard → Invoke Rule.
- Versioning and Expiration: Feedback files include explicit scope constraints and versioning to prevent unbounded accumulation and stale rules.
We define a structured interface for meta-guards to ensure consistency. This replaces ad-hoc markdown descriptions with a verifiable schema.
interface MetaGuard {
ruleId: string;
description: string;
validProducers: string[];
invalidTransformations: TransformationType[];
verificationStep: string;
createdAt: string;
expiresAt?: string;
}
type TransformationType = 'distinct' | 'group_by' | 'array_collapse' | 'join_dedup';
// Example Guard Definition
const guardOrderCardinality: MetaGuard = {
ruleId: 'rule_order_cardinality',
description: 'Validates 1:1 relationship between order_id and order_record.',
validProducers: ['raw_orders_table', 'orders_handler_v2'],
invalidTransformations: ['group_by', 'distinct'],
verificationStep: 'Inspect the SQL view or handler. If the query uses GROUP BY order_date or DISTINCT, this rule is invalid. Check for aggregation logic.',
createdAt: '2026-04-22',
expiresAt: '2026-07-22'
};
The meta-guard is implemented as a configuration file that the agent reads during the debugging phase. This file enforces the behavioral constraint.
# Meta-Guard: Order Cardinality Verification
> **Rule ID:** `rule_order_cardinality`
> **Context:** This rule applies ONLY to raw order records.
>
> **Why:** Applying cardinality rules to aggregated views causes false positives.
> On 2026-04-22, a discrepancy was misdiagnosed because the rule was applied to
> `daily_order_summary`, which collapses multiple orders per day.
>
> **Verification Protocol:**
> 1. Open the data producer (SQL view, API handler, or selector).
> 2. Check for `GROUP BY`, `DISTINCT`, or array aggregation.
> 3. If transformations exist, mark rule as INVALID for this context.
> 4. If raw table access is confirmed, proceed to invoke `rule_order_cardinality`.
>
> **Invalid Contexts:**
> - `daily_order_summary`
> - `user_order_counts_view`
> - Any producer with `GROUP BY` clause.
Rationale
- Why TypeScript Interface? While the agent consumes markdown, defining the structure in TypeScript allows for programmatic validation of feedback files during CI/CD or tooling scripts. It ensures all guards have required fields like
validProducers and verificationStep.
- Why Explicit Invalid Contexts? Listing invalid contexts is as important as listing valid ones. It creates a negative constraint that catches common aggregation patterns.
- Why Expiration? Rules drift as systems evolve. An expiration date forces periodic review, preventing stale rules from accumulating in the memory directory.
Pitfall Guide
1. The "Looks Like" Trap
Explanation: Leading the investigation with "This looks like the cardinality bug" triggers pattern matching. The agent retrieves the most similar rule and validates it, ignoring contradictory evidence.
Fix: Use open-ended prompts. "Analyze the data producer for the discrepancy counter. Do not assume any prior rules."
2. Aggregation Blindness
Explanation: Assuming table-level rules apply to views. DISTINCT, GROUP BY, or JOIN operations fundamentally alter cardinality and filter semantics. A rule valid for users may be invalid for active_users_view.
Fix: Always inspect the projection and aggregation logic of the producer. Verify if cardinality has been collapsed.
3. Memory as Verdict
Explanation: Treating memorized rules as absolute truth. This leads to second-type errors where correct rules are misapplied to wrong contexts, causing the agent to defend the rule rather than investigate the data.
Fix: Treat all memory as context-bound hypotheses. Validity is contingent on producer verification.
4. Unconstrained Rule Accumulation
Explanation: Feedback files multiply without scope constraints. Over time, overlapping rules create contradictory hypotheses, increasing cognitive load and reducing agent reliability.
Fix: Enforce scope constraints in every feedback file. Implement a cleanup policy for expired rules.
5. Skipping Producer Verification
Explanation: The cognitive cost of reading code is non-zero, so developers skip it. This guarantees wasted time when the rule context does not match.
Fix: Adopt the producer-first workflow. The cost of reading the producer is always lower than the cost of chasing a false lead.
6. Static Rules in Dynamic Systems
Explanation: Rules are written once and never updated. As the codebase evolves, rules become stale, leading to false negatives or misapplied logic.
Fix: Include expiration dates and versioning. Review rules during sprint retrospectives or when related code changes are merged.
7. Prompt Contamination
Explanation: Phrasing investigations as statements ("The count is wrong because of the filter rule") hands the agent a pre-validated hypothesis. The agent acquiesces to the framing.
Fix: Phrase investigations as questions. "What is the data producer for this counter? Does the filter logic match the expected state?"
Production Bundle
Action Checklist
Decision Matrix
| Scenario | Recommended Approach | Why | Cost Impact |
|---|
| Critical Production Bug | Producer-First | Zero risk of context-mismatch. Fastest path to root cause for high-stakes issues. | High cognitive load, low risk. |
| Routine Discrepancy Check | Meta-Guarded | Balances speed and accuracy. Meta-guards prevent false positives while retaining memory benefits. | Medium cognitive load, low risk. |
| New Feature Development | Producer-First | Establishes baseline understanding of data producers. Prevents early accumulation of stale rules. | High cognitive load, low risk. |
| Legacy System Audit | Meta-Guarded | Existing rules may be outdated. Meta-guards force verification before application. | Medium cognitive load, medium risk. |
| Rapid Prototyping | Memory-First | Speed is prioritized over accuracy. Accept higher false positive rate for iteration speed. | Low cognitive load, high risk. |
Configuration Template
Use this template to standardize meta-feedback files. Copy and adapt for your domain.
# Meta-Guard: [Rule Name]
> **Rule ID:** `[unique_rule_id]`
> **Description:** [Brief description of the rule's purpose.]
>
> **Why:** [Explanation of why context verification is critical. Reference past incidents.]
>
> **Verification Protocol:**
> 1. Open the data producer.
> 2. Check for [specific transformations, e.g., GROUP BY, DISTINCT].
> 3. Verify filter semantics match [expected state].
> 4. If context matches, invoke rule. Otherwise, mark as invalid.
>
> **Valid Producers:**
> - [Producer A]
> - [Producer B]
>
> **Invalid Contexts:**
> - [Context A]
> - [Context B]
>
> **Metadata:**
> - Created: [YYYY-MM-DD]
> - Expires: [YYYY-MM-DD]
> - Owner: [Team/Developer]
Quick Start Guide
- Create Meta-Guard File: In your agent memory directory, create a new file named
meta_guard_[rule_name].md.
- Populate Template: Fill in the template with the rule ID, valid producers, invalid contexts, and verification steps.
- Add to Workflow: Update your debugging checklist to include "Evaluate Meta-Guard" before "Invoke Rule."
- Test: Run a debugging session with a known discrepancy. Verify the agent checks the producer before applying the rule.
- Iterate: Refine the meta-guard based on feedback. Add new invalid contexts as edge cases are discovered.