# Self-Critique Protocol — Feature Plan

After writing the initial plan (Phase 4), refine it through automated adversarial review before presenting to the user for approval. The user sees only the final refined plan plus a deliberation log.

## Design Principle

**All discovery and user input is complete before this runs.** The plan is built from the approved spec + live environment discovery. The critique loop validates the plan against the spec and platform constraints — catching errors that would surface during implementation. The user sees one polished plan with a transparent log of what was debated internally.

## When This Runs

- **After** the plan is written to file (Phase 4)
- **Before** presenting for approval (Phase 5)
- Fully automated — **NO questions to the user** during this phase
- All discovery (Phase 1), classification (Phase 2), and pseudo logic (Phase 3) are complete

## Protocol

Run up to **3 rounds** of critique-and-fix. Each round is a structured dialogue between the **Author** (the orchestrating skill) and the **Critic** (a spawned agent).

### Round 1: Initial Critique

1. **Critic pass** — Spawn a separate critic agent with the Round 1 Critic Prompt (below). The critic should run with the highest-capability model/mode available in the current runtime. The critic reads BOTH the plan file AND the approved spec, then returns a structured findings table.

   **Runtime adaptation:**
   | Runtime | Critic mechanism |
   |---------|-----------------|
   | Claude Code | Agent tool, `subagent_type: general-purpose` (use strongest available model) |

2. **Author evaluates** — For each finding from the critic:

   | Verdict | Criteria | Action |
   |---------|----------|--------|
   | **ACCEPTED** | Valid + evidence + CRITICAL or HIGH severity | Apply fix to plan file |
   | **REJECTED** | No evidence, factually incorrect, or style-only | Log with detailed rejection reason |
   | **DEFERRED** | Valid but MEDIUM/LOW severity + non-blocking | Log for user awareness |

3. **Convergence check** — If 0 new CRITICAL or HIGH findings → **exit loop early**

4. **Update deliberation log** — Append round summary to the plan's `## Deliberation Log` section

### Round 2: Dialogue — Critic Responds

The critic receives Round 1 results and can:
- Raise **entirely new findings** not previously raised
- **Counter-argue** a rejected finding — ONLY with new evidence that directly addresses the rejection reason

1. **Critic pass** — Spawn a critic agent (same mechanism as Round 1) with the Round 2+ Critic Prompt (below). Include the Round 1 deliberation log so the critic sees what was accepted, rejected, and deferred.

2. **Author evaluates** — Same verdict table. Counter-arguments that provide genuinely new evidence are evaluated on merit. Counter-arguments that merely restate the original finding → **CIRCULAR** (auto-reject).

3. **Convergence check** — If 0 new CRITICAL/HIGH findings AND 0 accepted counter-arguments → **exit loop early**

4. **Update deliberation log** — Append round summary, distinguishing new findings from counter-arguments.

### Round 3: Final Pass (if needed)

Same as Round 2. Any finding rejected twice (original + counter-argument) **cannot be raised again**. This is the hard termination point — the loop ALWAYS exits after Round 3.

### Fallback (No Agent Capability)

If the runtime does not support spawning separate agents (some IDE targets), perform **inline self-critique**:

1. After writing the plan, pause and switch to "critic mode" mentally
2. Systematically check each rubric item (CR-1 through CR-7) against the plan AND the approved spec
3. For each finding, apply the same ACCEPT/REJECT/DEFER verdict
4. Write the deliberation log with the same format
5. Run all 3 rounds inline — less adversarial than a separate agent but still catches factual errors

The key difference: inline mode lacks the separation between author and critic, so the author may be biased toward defending their own work. Mitigate by strictly following the rubric and requiring evidence for every finding.

## Critic Rubric (Plan-Specific)

| # | Category | What to Check |
|---|----------|---------------|
| CR-1 | **Spec alignment** | Does the plan implement everything in the approved spec? Cross-check: every use case in spec §5 has corresponding workflow/ruleset coverage; every entity in spec §6 is addressed; every UI page in spec §9a has a §10 plan artifact; every acceptance criterion in spec §13 has a §17 test. |
| CR-2 | **Architecture validity** | Are Fluent patterns correct? Correct entity types and subtypes; workflow structure (status + trigger + rules); rule annotations (`@ParamString` for static config, `@EventAttribute` for dynamic data); setting conventions (`JSON`/`ACCOUNT`/`0` for manifests); manifest architecture (plugins in root only, routes in fragments). |
| CR-3 | **Artifact classification** | Is NEW/EXISTING/MODIFIED/REUSED/OOTB correct for each artifact? Did Phase 1 discovery confirm existence of "EXISTING" items? Are "OOTB" rules actually available in `plugin.list`? Are "REUSED" patterns actually present in the codebase? **For UI components:** Did §1.6 OOTB Component Search run? Are any "NEW" custom components reimplementing behavior already available in OOTB `fc.*` components (e.g., custom list when `fc.quantity.list` exists, custom scanner when BarcodeFilter is built into QuantityList)? Reclassify to WRAP if an OOTB equivalent exists. |
| CR-4 | **Dependency ordering** | Are deployment steps (§18) sequenced correctly? Module deploy before workflow deploy? Rule scaffold before build? Settings created before rules that read them? Workflow version incremented? |
| CR-5 | **Risk completeness** | Missing deployment risks, rollback scenarios, or breaking change warnings in §16/§19? Version conflicts? Data migration needs? Entities stuck at removed statuses? |
| CR-6 | **Pseudo logic quality** | For NEW rules in §8: is the logic unambiguous and implementable? Every READ/QUERY/MUTATE path clear? Error paths with specific exceptions? All `@ParamString` and `@EventAttribute` declared? No `DynamicUtils.getJsonPath(context, "event.X")` anti-pattern? |
| CR-7 | **Section completeness** | Are all applicable plan sections (per Section Applicability Guide in `PLAN_TEMPLATE.md`) present? Missing diagrams that should exist? Empty sections that should have content? If the spec has §5a user journey diagrams, does §3 Architecture refine them into technical diagrams (state machines, cross-entity flows)? Every actor and use case from spec §5a should be traceable in the plan's architecture. |

## Round 1 Critic Prompt

```
You are a senior Fluent Commerce solution architect conducting an adversarial review of a Feature Plan. Your job is to find ERRORS and GAPS — not style preferences. Think deeply and critically about whether this plan would succeed in production.

Read the plan at: {plan_path}
Read the approved spec at: {spec_path}
{If exists: Also read: knowledge/platform/domain-model.md, knowledge/platform/rule-development-contract.md}
{If exists: Also read: accounts/<PROFILE>/knowledge/naming-conventions.md, accounts/<PROFILE>/knowledge/coding-standards.md}

{feedback_pitfalls}

Review against these 7 criteria:
1. Spec alignment — does the plan implement everything the spec requires?
2. Architecture validity — correct Fluent patterns, conventions, and constraints?
3. Artifact classification — NEW/EXISTING/MODIFIED/REUSED/OOTB accurate?
4. Dependency ordering — deployment sequence correct?
5. Risk completeness — missing risks or rollback gaps?
6. Pseudo logic quality — NEW rule designs unambiguous and implementable?
7. Section completeness — all required plan sections present?

Rules:
- Every finding MUST include EVIDENCE: a spec section reference, platform constraint, or logical proof
- "I think" or "it seems" is NOT evidence — cite specifics or don't raise it
- Do NOT raise style, formatting, or wording issues
- Cross-reference the approved spec — the plan MUST cover what the spec requires
- Focus on things that would cause implementation failure
- Think about what a real developer would struggle with when implementing this plan

Output format — one markdown table, nothing else:

| # | Severity | Category | Finding | Evidence | Proposed Fix |
|---|----------|----------|---------|----------|--------------|
| C1 | CRITICAL/HIGH/MEDIUM/LOW | CR-N | What's wrong | Proof it's wrong | How to fix it |

Severity guide:
- CRITICAL: Would cause implementation failure (missing rules, wrong entity types, broken deployment order)
- HIGH: Likely to cause issues (missing test cases, incomplete pseudo logic, wrong classification)
- MEDIUM: Should fix but won't block (missing optional section, incomplete risk analysis)
- LOW: Minor improvement, non-blocking

If no issues found, output exactly: "No findings — plan passes all 7 criteria."
```

## Round 2+ Critic Prompt (Dialogue Mode)

For rounds 2 and 3, the critic receives the full deliberation context:

```
You are a senior Fluent Commerce solution architect conducting round {N} of an adversarial review.

Read the plan at: {plan_path}
Read the approved spec at: {spec_path}
{If exists: Also read: knowledge/platform/domain-model.md, knowledge/platform/rule-development-contract.md}
{If exists: Also read: accounts/<PROFILE>/knowledge/naming-conventions.md, accounts/<PROFILE>/knowledge/coding-standards.md}

{feedback_pitfalls}

## Prior Round Context

The following findings were raised and evaluated in prior rounds:

### Accepted (already fixed in plan):
{For each accepted finding:}
- {finding_id}: {finding text} → Fix applied: {what changed}

### Rejected (author disagreed):
{For each rejected finding:}
- {finding_id}: {finding text}
  Evidence cited: {original evidence}
  Rejection reason: {why it was rejected}

### Deferred (noted for user):
{For each deferred finding:}
- {finding_id}: {finding text}

## Your Task

You may:
1. Raise **entirely new findings** not previously raised — apply the same 7 criteria
2. **Counter-argue** a rejected finding — BUT ONLY if you have NEW EVIDENCE that directly addresses the rejection reason. Simply restating the original finding or rephrasing it is NOT a counter-argument.

Counter-arguments must include:
- Reference: "Counter to {finding_id}"
- New evidence that wasn't in the original finding
- Why the rejection reason was incorrect or incomplete

Rules (same as Round 1, plus):
- Do NOT re-raise a finding with the same evidence — that's circular
- Do NOT argue about DEFERRED items — they're already noted for the user
- Counter-arguments without genuinely new evidence will be auto-rejected
- If a finding was rejected twice (original + counter), it CANNOT be raised again

Output format — same table. Mark counter-arguments clearly:

| # | Severity | Category | Finding | Evidence | Proposed Fix |
|---|----------|----------|---------|----------|--------------|
| C{N} | SEVERITY | CR-N | [NEW] or [COUNTER to C{X}]: finding text | evidence | fix |

If no new findings and no valid counter-arguments:
"No new findings — prior review was comprehensive."
```

## Guardrails

| Guardrail | Rule |
|-----------|------|
| **Max rounds** | 3 — hard cap, no exceptions |
| **Early exit** | 0 new CRITICAL/HIGH findings AND 0 accepted counter-arguments in a round → stop |
| **Critic capability** | Use the highest-capability model/mode available in the runtime. Claude Code: strongest available model via Agent tool. Other runtimes: strongest available model or inline deep-think. |
| **Counter-argument rule** | A rejected finding may be counter-argued ONCE with new evidence. If the counter-argument is also rejected, the finding is permanently closed. No third attempt. |
| **Evidence required** | Findings without specific evidence are auto-rejected |
| **Severity filter** | Only CRITICAL and HIGH findings trigger plan changes. MEDIUM/LOW are logged only |
| **No style changes** | Wording, formatting, subjective preferences → auto-reject |
| **No scope expansion** | Critic cannot add requirements beyond the approved spec → auto-reject |
| **No user interaction** | The entire loop runs without prompting the user |
| **Deterministic termination** | Always exits after at most 3 rounds (5 for HIGH complexity) |
| **Escalation** | CRITICAL finding rejected twice + critic counter-argues with new evidence + author rejects again → ESCALATED. User arbitrates |
| **Complexity scaling** | 5+ entity types OR 3+ workflows OR 10+ NEW rules → HIGH complexity → max 5 rounds |
| **Multi-critic** | HIGH complexity → dual parallel critics. Conflicting findings on same issue → ESCALATED |
| **Feedback check** | Pre-Round 1: read last 10 feedback records, extract top 3 pitfall patterns for critic context |

## Escalation Mechanism

When the normal ACCEPT/REJECT/DEFER verdicts cannot resolve a CRITICAL finding:

1. Critic raises CRITICAL finding → Author REJECTS with reason
2. Critic counter-argues with **new evidence** → Author REJECTS again
3. Finding is marked **ESCALATED** in the deliberation log (not permanently closed)

ESCALATED findings are surfaced prominently in the User-Facing Summary. The user arbitrates — their decision is final. The author MUST NOT silently close a twice-rejected CRITICAL finding if the critic provided genuinely new evidence in the counter-argument.

Verdict table addition:

| Verdict | Criteria | Action |
|---------|----------|--------|
| **ESCALATED** | CRITICAL finding rejected twice, critic provided new evidence both times | Log for user arbitration |

## Pre-Critique Feedback Check

Before Round 1, check for prior execution feedback:

1. Read `accounts/<PROFILE>/feedback/fluent-feature-plan.jsonl` (last 10 records)
2. Filter for `FAILURE`, `USER_CORRECTED`, `PARTIAL_SUCCESS` outcomes
3. Extract top 3 recurring patterns (e.g., "missing @EventAttribute annotations", "wrong artifact classification for OOTB rules")
4. Inject as `{feedback_pitfalls}` in both critic prompts

Add to **Round 1 Critic Prompt** (after the knowledge file lines):
```
{If feedback_pitfalls exist:}
Known pitfalls from prior plan executions (pay special attention to these):
{feedback_pitfalls}
```

Add the same block to **Round 2+ Critic Prompt** (after the knowledge file lines).

If no feedback file exists or no relevant records found, omit the block — do not mention it.

## Revision Re-Critique

When `planRevision > 1` in `status.json`, re-run critique on **changed sections only**:

1. Compute diff between previous plan version and revised plan
2. Critic receives: diff + original deliberation log + approved spec
3. **Max 2 rounds** (lighter than initial critique)
4. Convergence: 0 new CRITICAL findings → exit
5. Existing deliberation log is preserved; revision rounds are appended as `### Revision Round N`

Critic prompt addition for revision mode:
```
This is a REVISION review (planRevision {N}). Only review the CHANGED sections shown in the diff below.
The original deliberation log is included — do not re-raise resolved findings.

{diff}
```

## Complexity-Based Scaling

Assess plan complexity before Round 1:

| Indicator | Threshold | Effect |
|-----------|-----------|--------|
| Entity types touched | 5+ | HIGH complexity |
| Workflows modified/created | 3+ | HIGH complexity |
| NEW rules in §8 | 10+ | HIGH complexity |
| Data migration or deletion | Any | Add IR-SECURITY to rubric |

**HIGH complexity:** max rounds increases from 3 to 5. Enables Multi-Critic Mode.

**IR-SECURITY rubric item** (added when data migration/deletion present):

| # | Category | What to Check |
|---|----------|---------------|
| IR-S | **Security / data safety** | Irreversible operations identified? Rollback plan covers data state? Migration tested in non-prod? Deletion has confirmation gate? |

Standard features (below all thresholds): 3 rounds, single critic, no IR-SECURITY.

## Multi-Critic Mode

Triggered when complexity is HIGH. Two critic agents run in **parallel**:

| Critic | Rubric items | Focus |
|--------|-------------|-------|
| Architecture Critic | CR-1, CR-2, CR-4 (+ IR-S if present) | Spec alignment, platform patterns, deployment order |
| Implementation Critic | CR-3, CR-5, CR-6, CR-7 | Artifact classification, risks, pseudo logic, completeness |

Execution:
1. Spawn both critics simultaneously (two Agent calls in parallel)
2. Author receives merged findings table (prefixed `[ARCH]` or `[IMPL]`)
3. Evaluate using standard verdict rules
4. **Conflict resolution:** If both critics raise findings on the **same artifact** with contradictory fixes → mark as ESCALATED (user arbitrates)

Standard complexity plans: single critic (unchanged from base protocol).

## Deliberation Log Format

Append this section to the plan file, after §19 Rollback Plan and before any Revision Log:

```markdown
## Deliberation Log

### Round 1 — Initial Critique

| # | Severity | Category | Finding | Evidence | Verdict | Action |
|---|----------|----------|---------|----------|---------|--------|
| C1 | CRITICAL | CR-1 | [finding text] | [evidence] | ACCEPTED | Applied: [what changed in plan] |
| C2 | HIGH | CR-4 | [finding text] | [evidence] | REJECTED | Reason: [why it's wrong] |
| C6 | CRITICAL | CR-2 | [finding text] | [evidence] | ESCALATED | User arbitration needed: [context] |

### Round 2 — Dialogue

| # | Severity | Category | Finding | Evidence | Verdict | Action |
|---|----------|----------|---------|----------|---------|--------|
| C3 | HIGH | CR-2 | [NEW] [finding text] | [evidence] | ACCEPTED | Applied: [what changed] |
| C4 | HIGH | CR-4 | [COUNTER to C2] [new argument] | [new evidence] | ACCEPTED | Overturned C2 rejection. Applied: [fix] |
| C5 | MEDIUM | CR-3 | [COUNTER to C2] [restated argument] | [same evidence] | CIRCULAR | Auto-rejected: no new evidence |

### Round 3 — Final Pass
...

### Summary
- **Rounds:** N (exit: [clean pass / converged / max reached])
- **Findings:** X total — Y accepted, Z rejected, W deferred, V counter-argued, U escalated
- **Counter-arguments:** A raised, B accepted (overturned prior rejections), C rejected
- **Plan changes:** [list of all accepted changes applied, in order]
- **Open items for user:** [list of deferred findings the user should be aware of]

### User-Facing Summary
- **Findings**: X total — Y applied, Z rejected, W deferred, V escalated
- **Key changes**: [1-line per accepted change]
- **Deferred**: [items user should know about]
- **Escalated**: [CRITICAL items needing user arbitration]
- **Complexity tier**: Standard / HIGH (reason)
- **Feedback applied**: [pitfalls from prior executions, if any]
```

If Round 1 finds 0 issues:

```markdown
## Deliberation Log

### Round 1 — Initial Critique
No findings — plan passed all 7 criteria on first review.

### Summary
- **Rounds:** 1 (exit: clean pass)
- **Findings:** 0

### User-Facing Summary
- **Findings**: 0
- **Complexity tier**: Standard
```
